huskies: merge 604_story_service_module_conventions_and_first_extraction

This commit is contained in:
dave
2026-04-24 13:40:47 +00:00
parent 3521649cbf
commit 2f07365745
11 changed files with 1365 additions and 201 deletions
+131 -200
View File
@@ -1,11 +1,14 @@
//! HTTP agent endpoints — REST API for listing, starting, stopping, and inspecting agents.
use crate::config::ProjectConfig;
//! HTTP agent endpoints — thin adapters over `service::agents`.
//!
//! Each handler: extracts payload → calls `service::agents::X` → shapes
//! response DTO → returns HTTP result. No filesystem access, no inline
//! validation, no process invocations.
use crate::http::context::{AppContext, OpenApiResult, bad_request, not_found};
use crate::service::agents::{self as svc, AgentConfigEntry, WorkItemContent};
use crate::workflow::{StoryTestResults, TestCaseResult, TestStatus};
use crate::worktree;
use poem::http::StatusCode;
use poem_openapi::{Object, OpenApi, Tags, param::Path, payload::Json};
use serde::Serialize;
use std::path;
use std::sync::Arc;
#[derive(Tags)]
@@ -45,6 +48,20 @@ struct AgentConfigInfoResponse {
max_budget_usd: Option<f64>,
}
impl From<AgentConfigEntry> for AgentConfigInfoResponse {
fn from(e: AgentConfigEntry) -> Self {
Self {
name: e.name,
role: e.role,
stage: e.stage,
model: e.model,
allowed_tools: e.allowed_tools,
max_turns: e.max_turns,
max_budget_usd: e.max_budget_usd,
}
}
}
#[derive(Object)]
struct CreateWorktreePayload {
story_id: String,
@@ -73,6 +90,17 @@ struct WorkItemContentResponse {
agent: Option<String>,
}
impl From<WorkItemContent> for WorkItemContentResponse {
fn from(w: WorkItemContent) -> Self {
Self {
content: w.content,
stage: w.stage,
name: w.name,
agent: w.agent,
}
}
}
/// A single test case result for the OpenAPI response.
#[derive(Object, Serialize)]
struct TestCaseResultResponse {
@@ -153,15 +181,23 @@ struct AllTokenUsageResponse {
records: Vec<TokenUsageRecordResponse>,
}
/// Returns true if the story file exists in `work/5_done/` or `work/6_archived/`.
///
/// Used to exclude agents for already-archived stories from the `list_agents`
/// response so the agents panel is not cluttered with old completed items on
/// frontend startup.
pub fn story_is_archived(project_root: &path::Path, story_id: &str) -> bool {
let work = project_root.join(".huskies").join("work");
let filename = format!("{story_id}.md");
work.join("5_done").join(&filename).exists() || work.join("6_archived").join(&filename).exists()
/// Map a `service::agents::Error` to a Poem HTTP error with the correct status.
fn map_svc_error(err: svc::Error) -> poem::Error {
match err {
svc::Error::AgentNotFound(_) => {
poem::Error::from_string(err.to_string(), StatusCode::NOT_FOUND)
}
svc::Error::WorkItemNotFound(_) => {
poem::Error::from_string(err.to_string(), StatusCode::NOT_FOUND)
}
svc::Error::Worktree(_) => {
poem::Error::from_string(err.to_string(), StatusCode::BAD_REQUEST)
}
svc::Error::Config(_) => poem::Error::from_string(err.to_string(), StatusCode::BAD_REQUEST),
svc::Error::Io(_) => {
poem::Error::from_string(err.to_string(), StatusCode::INTERNAL_SERVER_ERROR)
}
}
}
pub struct AgentsApi {
@@ -183,18 +219,16 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let info = self
.ctx
.agents
.start_agent(
&project_root,
&payload.0.story_id,
payload.0.agent_name.as_deref(),
None,
None,
)
.await
.map_err(bad_request)?;
let info = svc::start_agent(
&self.ctx.agents,
&project_root,
&payload.0.story_id,
payload.0.agent_name.as_deref(),
None,
None,
)
.await
.map_err(map_svc_error)?;
Ok(Json(AgentInfoResponse {
story_id: info.story_id,
@@ -214,11 +248,14 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
self.ctx
.agents
.stop_agent(&project_root, &payload.0.story_id, &payload.0.agent_name)
.await
.map_err(bad_request)?;
svc::stop_agent(
&self.ctx.agents,
&project_root,
&payload.0.story_id,
&payload.0.agent_name,
)
.await
.map_err(map_svc_error)?;
Ok(Json(true))
}
@@ -231,17 +268,12 @@ impl AgentsApi {
#[oai(path = "/agents", method = "get")]
async fn list_agents(&self) -> OpenApiResult<Json<Vec<AgentInfoResponse>>> {
let project_root = self.ctx.agents.get_project_root(&self.ctx.state).ok();
let agents = self.ctx.agents.list_agents().map_err(bad_request)?;
let agents =
svc::list_agents(&self.ctx.agents, project_root.as_deref()).map_err(map_svc_error)?;
Ok(Json(
agents
.into_iter()
.filter(|info| {
project_root
.as_deref()
.map(|root| !story_is_archived(root, &info.story_id))
.unwrap_or(true)
})
.map(|info| AgentInfoResponse {
story_id: info.story_id,
agent_name: info.agent_name,
@@ -262,21 +294,11 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let config = ProjectConfig::load(&project_root).map_err(bad_request)?;
let entries = svc::get_agent_config(&project_root).map_err(map_svc_error)?;
Ok(Json(
config
.agent
.iter()
.map(|a| AgentConfigInfoResponse {
name: a.name.clone(),
role: a.role.clone(),
stage: a.stage.clone(),
model: a.model.clone(),
allowed_tools: a.allowed_tools.clone(),
max_turns: a.max_turns,
max_budget_usd: a.max_budget_usd,
})
entries
.into_iter()
.map(AgentConfigInfoResponse::from)
.collect(),
))
}
@@ -290,21 +312,11 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let config = ProjectConfig::load(&project_root).map_err(bad_request)?;
let entries = svc::reload_config(&project_root).map_err(map_svc_error)?;
Ok(Json(
config
.agent
.iter()
.map(|a| AgentConfigInfoResponse {
name: a.name.clone(),
role: a.role.clone(),
stage: a.stage.clone(),
model: a.model.clone(),
allowed_tools: a.allowed_tools.clone(),
max_turns: a.max_turns,
max_budget_usd: a.max_budget_usd,
})
entries
.into_iter()
.map(AgentConfigInfoResponse::from)
.collect(),
))
}
@@ -321,12 +333,9 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let info = self
.ctx
.agents
.create_worktree(&project_root, &payload.0.story_id)
let info = svc::create_worktree(&self.ctx.agents, &project_root, &payload.0.story_id)
.await
.map_err(bad_request)?;
.map_err(map_svc_error)?;
Ok(Json(WorktreeInfoResponse {
story_id: payload.0.story_id,
@@ -345,7 +354,7 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let entries = worktree::list_worktrees(&project_root).map_err(bad_request)?;
let entries = svc::list_worktrees(&project_root).map_err(map_svc_error)?;
Ok(Json(
entries
@@ -373,64 +382,12 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let stages = [
("1_backlog", "backlog"),
("2_current", "current"),
("3_qa", "qa"),
("4_merge", "merge"),
("5_done", "done"),
("6_archived", "archived"),
];
let item = svc::get_work_item_content(&project_root, &story_id.0).map_err(|e| match e {
svc::Error::WorkItemNotFound(_) => not_found(e.to_string()),
other => map_svc_error(other),
})?;
let work_dir = project_root.join(".huskies").join("work");
let filename = format!("{}.md", story_id.0);
for (stage_dir, stage_name) in &stages {
let file_path = work_dir.join(stage_dir).join(&filename);
if file_path.exists() {
let content = std::fs::read_to_string(&file_path)
.map_err(|e| bad_request(format!("Failed to read work item: {e}")))?;
let metadata = crate::io::story_metadata::parse_front_matter(&content).ok();
let name = metadata.as_ref().and_then(|m| m.name.clone());
let agent = metadata.and_then(|m| m.agent);
return Ok(Json(WorkItemContentResponse {
content,
stage: stage_name.to_string(),
name,
agent,
}));
}
}
// Filesystem miss — fall back to CRDT-only path (story exists in the CRDT
// but has no corresponding .md file on disk).
if let Some(content) = crate::db::read_content(&story_id.0) {
let item = crate::pipeline_state::read_typed(&story_id.0)
.map_err(|e| bad_request(format!("Pipeline read error: {e}")))?;
let stage = item
.as_ref()
.map(|i| match &i.stage {
crate::pipeline_state::Stage::Backlog => "backlog",
crate::pipeline_state::Stage::Coding => "current",
crate::pipeline_state::Stage::Qa => "qa",
crate::pipeline_state::Stage::Merge { .. } => "merge",
crate::pipeline_state::Stage::Done { .. } => "done",
crate::pipeline_state::Stage::Archived { .. } => "archived",
})
.unwrap_or("unknown")
.to_string();
let metadata = crate::io::story_metadata::parse_front_matter(&content).ok();
let name = metadata.as_ref().and_then(|m| m.name.clone());
let agent = metadata.and_then(|m| m.agent);
return Ok(Json(WorkItemContentResponse {
content,
stage,
name,
agent,
}));
}
Err(not_found(format!("Work item not found: {}", story_id.0)))
Ok(Json(WorkItemContentResponse::from(item)))
}
/// Get test results for a work item by its story_id.
@@ -442,30 +399,37 @@ impl AgentsApi {
&self,
story_id: Path<String>,
) -> OpenApiResult<Json<Option<TestResultsResponse>>> {
// Try in-memory workflow state first.
let workflow = self
.ctx
.workflow
.lock()
.map_err(|e| bad_request(format!("Lock error: {e}")))?;
if let Some(results) = workflow.results.get(&story_id.0) {
return Ok(Json(Some(TestResultsResponse::from_story_results(results))));
// Fast path: return from in-memory state without requiring project_root.
let in_memory = {
let workflow = self
.ctx
.workflow
.lock()
.map_err(|e| bad_request(format!("Lock error: {e}")))?;
workflow.results.get(&story_id.0).cloned()
};
if let Some(results) = in_memory {
return Ok(Json(Some(TestResultsResponse::from_story_results(
&results,
))));
}
drop(workflow);
// Fall back to file-persisted results.
// Slow path: fall back to results persisted in the story file.
let project_root = self
.ctx
.agents
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let file_results =
crate::http::workflow::read_test_results_from_story_file(&project_root, &story_id.0);
let workflow = self
.ctx
.workflow
.lock()
.map_err(|e| bad_request(format!("Lock error: {e}")))?;
let results = svc::get_test_results(&project_root, &story_id.0, &workflow);
Ok(Json(
file_results.map(|r| TestResultsResponse::from_story_results(&r)),
results.map(|r| TestResultsResponse::from_story_results(&r)),
))
}
@@ -486,26 +450,8 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let log_path = crate::agent_log::find_latest_log(&project_root, &story_id.0, &agent_name.0);
let Some(path) = log_path else {
return Ok(Json(AgentOutputResponse {
output: String::new(),
}));
};
let entries = crate::agent_log::read_log(&path).map_err(bad_request)?;
let output: String = entries
.iter()
.filter(|e| e.event.get("type").and_then(|t| t.as_str()) == Some("output"))
.filter_map(|e| {
e.event
.get("text")
.and_then(|t| t.as_str())
.map(str::to_owned)
})
.collect();
let output = svc::get_agent_output(&project_root, &story_id.0, &agent_name.0)
.map_err(map_svc_error)?;
Ok(Json(AgentOutputResponse { output }))
}
@@ -519,10 +465,9 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let config = ProjectConfig::load(&project_root).map_err(bad_request)?;
worktree::remove_worktree_by_story_id(&project_root, &story_id.0, &config)
svc::remove_worktree(&project_root, &story_id.0)
.await
.map_err(bad_request)?;
.map_err(map_svc_error)?;
Ok(Json(true))
}
@@ -542,39 +487,25 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let all_records = crate::agents::token_usage::read_all(&project_root)
.map_err(|e| bad_request(format!("Failed to read token usage: {e}")))?;
let summary =
svc::get_work_item_token_cost(&project_root, &story_id.0).map_err(map_svc_error)?;
let mut agent_map: std::collections::HashMap<String, AgentCostEntry> =
std::collections::HashMap::new();
let mut total_cost_usd = 0.0_f64;
for record in all_records.into_iter().filter(|r| r.story_id == story_id.0) {
total_cost_usd += record.usage.total_cost_usd;
let entry = agent_map
.entry(record.agent_name.clone())
.or_insert_with(|| AgentCostEntry {
agent_name: record.agent_name.clone(),
model: record.model.clone(),
input_tokens: 0,
output_tokens: 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
total_cost_usd: 0.0,
});
entry.input_tokens += record.usage.input_tokens;
entry.output_tokens += record.usage.output_tokens;
entry.cache_creation_input_tokens += record.usage.cache_creation_input_tokens;
entry.cache_read_input_tokens += record.usage.cache_read_input_tokens;
entry.total_cost_usd += record.usage.total_cost_usd;
}
let mut agents: Vec<AgentCostEntry> = agent_map.into_values().collect();
agents.sort_by(|a, b| a.agent_name.cmp(&b.agent_name));
let agents = summary
.agents
.into_iter()
.map(|a| AgentCostEntry {
agent_name: a.agent_name,
model: a.model,
input_tokens: a.input_tokens,
output_tokens: a.output_tokens,
cache_creation_input_tokens: a.cache_creation_input_tokens,
cache_read_input_tokens: a.cache_read_input_tokens,
total_cost_usd: a.total_cost_usd,
})
.collect();
Ok(Json(TokenCostResponse {
total_cost_usd,
total_cost_usd: summary.total_cost_usd,
agents,
}))
}
@@ -590,8 +521,7 @@ impl AgentsApi {
.get_project_root(&self.ctx.state)
.map_err(bad_request)?;
let records = crate::agents::token_usage::read_all(&project_root)
.map_err(|e| bad_request(format!("Failed to read token usage: {e}")))?;
let records = svc::get_all_token_usage(&project_root).map_err(map_svc_error)?;
let response_records: Vec<TokenUsageRecordResponse> = records
.into_iter()
@@ -618,6 +548,7 @@ impl AgentsApi {
mod tests {
use super::*;
use crate::agents::AgentStatus;
use std::path;
use tempfile::TempDir;
fn make_work_dirs(tmp: &TempDir) -> path::PathBuf {
@@ -632,7 +563,7 @@ mod tests {
fn story_is_archived_false_when_file_absent() {
let tmp = TempDir::new().unwrap();
let root = make_work_dirs(&tmp);
assert!(!story_is_archived(&root, "79_story_foo"));
assert!(!svc::is_archived(&root, "79_story_foo"));
}
#[test]
@@ -644,7 +575,7 @@ mod tests {
"---\nname: test\n---\n",
)
.unwrap();
assert!(story_is_archived(&root, "79_story_foo"));
assert!(svc::is_archived(&root, "79_story_foo"));
}
#[test]
@@ -656,7 +587,7 @@ mod tests {
"---\nname: test\n---\n",
)
.unwrap();
assert!(story_is_archived(&root, "79_story_foo"));
assert!(svc::is_archived(&root, "79_story_foo"));
}
#[tokio::test]
+1 -1
View File
@@ -86,7 +86,7 @@ pub(super) fn tool_list_agents(ctx: &AppContext) -> Result<String, String> {
.filter(|a| {
project_root
.as_deref()
.map(|root| !crate::http::agents::story_is_archived(root, &a.story_id))
.map(|root| !crate::service::agents::is_archived(root, &a.story_id))
.unwrap_or(true)
})
.map(|a| json!({