diff --git a/Cargo.lock b/Cargo.lock index ce42c86..84b9211 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -677,6 +677,7 @@ dependencies = [ "harness-mcp", "harness-providers", "harness-tools", + "serde_json", "tempfile", "thiserror 2.0.18", "tokio", diff --git a/crates/harness-app/Cargo.toml b/crates/harness-app/Cargo.toml index 0fd5f60..a452203 100644 --- a/crates/harness-app/Cargo.toml +++ b/crates/harness-app/Cargo.toml @@ -20,6 +20,7 @@ tracing = { workspace = true } [dev-dependencies] tempfile = { workspace = true } futures = { workspace = true } +serde_json = { workspace = true } [lints] workspace = true diff --git a/crates/harness-app/src/lib.rs b/crates/harness-app/src/lib.rs index 7db5393..d9822d3 100644 --- a/crates/harness-app/src/lib.rs +++ b/crates/harness-app/src/lib.rs @@ -18,7 +18,9 @@ use harness_core::engine::{run_session, RunConfig, StepContext}; use harness_core::event::{AppEvent, EventBus, RunOutcome}; use harness_core::permission::{PermissionReply, PermissionService, Rule, Ruleset}; use harness_core::store::{Store, StoreError}; -use harness_core::tool::{SpawnError, SpawnOutcome, SpawnRequest, SubagentSpawner, ToolRegistry}; +use harness_core::tool::{ + ContextReporter, SpawnError, SpawnOutcome, SpawnRequest, SubagentSpawner, ToolRegistry, +}; use harness_core::types::{ Message, MessageId, ModelRef, Part, PartBody, PartId, Session, SessionId, }; @@ -26,7 +28,7 @@ use harness_providers::{AnthropicProvider, ModelCatalog, OpenAiProvider, Provide use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; -/// Placeholder until M4's markdown agent registry lands (`assets/agents/orchestrator.md`). +/// Fallback prompt for an agent whose markdown body is empty or that isn't in the registry. pub const DEFAULT_AGENT_PROMPT: &str = "You are a helpful coding assistant with access to tools for reading, editing, running \ commands, and searching code. Use them as needed to satisfy the user's request, then \ @@ -312,6 +314,7 @@ impl EngineHandle { now, spawner: Some(self.inner.clone()), job_board: Some(board), + context_reporter: None, // root session has no parent board to report to }; let run_config = RunConfig { agent_name: agent.name.clone(), @@ -573,6 +576,7 @@ impl EngineInner { parent_rules: Ruleset, extra_rules: Ruleset, board: Arc, + reporter: Option>, cancel: CancellationToken, now: i64, ) -> StepContext { @@ -591,10 +595,27 @@ impl EngineInner { now, spawner: Some(self.arc()), job_board: Some(board), + context_reporter: reporter, } } } +/// Reports a child session's file reads to its job on the parent board. +struct BoardReporter { + board: Arc, + task_id: String, +} + +#[async_trait] +impl ContextReporter for BoardReporter { + async fn report_file(&self, path: String, lines: u32) { + let _ = self + .board + .report_context_file(&self.task_id, path, lines, now_ms()) + .await; + } +} + #[async_trait] impl SubagentSpawner for EngineInner { async fn spawn(&self, req: SpawnRequest) -> Result { @@ -720,6 +741,10 @@ impl SubagentSpawner for EngineInner { } .unwrap_or_default(); + let reporter: Arc = Arc::new(BoardReporter { + board: board.clone(), + task_id: task_id.clone(), + }); let ctx = self.child_ctx( child_id.clone(), child_tools, @@ -727,6 +752,7 @@ impl SubagentSpawner for EngineInner { parent_rules, child_session.extra_rules.clone(), child_board, + Some(reporter), cancel, now, ); @@ -760,6 +786,10 @@ impl SubagentSpawner for EngineInner { }) } else { // Foreground: run to completion under the tool call's token and return the text. + let reporter: Arc = Arc::new(BoardReporter { + board: board.clone(), + task_id: task_id.clone(), + }); let ctx = self.child_ctx( child_id.clone(), child_tools, @@ -767,6 +797,7 @@ impl SubagentSpawner for EngineInner { parent_rules, child_session.extra_rules.clone(), child_board, + Some(reporter), req.cancel.clone(), now, ); @@ -931,6 +962,128 @@ mod tests { .unwrap() } + /// Drives a subagent through one `read` tool call, then a final answer. + struct ReadThenAnswerProvider { + steps: std::sync::Mutex>>>, + } + + #[async_trait] + impl Provider for ReadThenAnswerProvider { + fn id(&self) -> &str { + "mock" + } + async fn list_models(&self) -> Result, ProviderError> { + Ok(vec![]) + } + async fn stream( + &self, + _req: LlmRequest, + _cancel: CancellationToken, + ) -> Result { + let events = self.steps.lock().unwrap().pop_front().unwrap_or_else(|| { + vec![ + Ok(LlmEvent::TextStart { id: "d".into() }), + Ok(LlmEvent::TextDelta { + id: "d".into(), + text: "done".into(), + }), + Ok(LlmEvent::TextEnd { id: "d".into() }), + Ok(LlmEvent::Finish { + reason: FinishReason::Stop, + usage: TokenUsage::default(), + }), + ] + }); + Ok(Box::pin(futures::stream::iter(events))) + } + } + + #[tokio::test] + async fn subagent_file_reads_land_on_the_job_board() { + let dir = tempfile::tempdir().unwrap(); + // A file with ≥10 lines so the read clears the board's reporting threshold. + let body = (1..=15) + .map(|n| format!("line {n}")) + .collect::>() + .join("\n"); + std::fs::write(dir.path().join("auth.rs"), body).unwrap(); + + let provider = Arc::new(ReadThenAnswerProvider { + steps: std::sync::Mutex::new( + vec![ + // Turn 1: call the read tool. + vec![ + Ok(LlmEvent::ToolCall { + call_id: "c1".into(), + name: "read".into(), + input: serde_json::json!({"file_path": "auth.rs"}), + }), + Ok(LlmEvent::Finish { + reason: FinishReason::ToolCalls, + usage: TokenUsage::default(), + }), + ], + // Turn 2: final answer. + vec![ + Ok(LlmEvent::TextStart { id: "t".into() }), + Ok(LlmEvent::TextDelta { + id: "t".into(), + text: "found it".into(), + }), + Ok(LlmEvent::TextEnd { id: "t".into() }), + Ok(LlmEvent::Finish { + reason: FinishReason::Stop, + usage: TokenUsage::default(), + }), + ], + ] + .into(), + ), + }); + let mut providers = ProviderRegistry::new(); + providers.register(provider); + let engine = EngineHandle::build( + dir.path().to_path_buf(), + Store::open_in_memory().unwrap(), + Config::default(), + providers, + ) + .unwrap(); + // Auto-approve permission asks (the child's read tool gates on `read`). + spawn_auto_approve_task(&engine); + + let root = engine + .new_session("orchestrator", "mock/mock-model") + .await + .unwrap(); + let out = engine + .inner + .spawn(SpawnRequest { + parent_session_id: root.clone(), + parent_message_id: MessageId::new(), + agent: "explorer".into(), + description: "read auth".into(), + prompt: "read auth.rs".into(), + reuse_task_id: None, + background: false, + cancel: CancellationToken::new(), + }) + .await + .unwrap(); + + let board = engine.inner.board_for(&root).await.unwrap(); + let job = board + .snapshot() + .into_iter() + .find(|j| j.child_session == out.child_session_id) + .expect("job on board"); + assert!( + job.context_files.iter().any(|f| f.path == "auth.rs"), + "expected auth.rs on the board, got {:?}", + job.context_files + ); + } + #[tokio::test] async fn foreground_task_runs_a_subagent_and_alias_reuse_continues_the_same_session() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/harness-core/src/engine/loop.rs b/crates/harness-core/src/engine/loop.rs index 200358a..c0f7619 100644 --- a/crates/harness-core/src/engine/loop.rs +++ b/crates/harness-core/src/engine/loop.rs @@ -411,6 +411,7 @@ mod tests { now: 1, spawner: None, job_board: None, + context_reporter: None, } } diff --git a/crates/harness-core/src/engine/processor.rs b/crates/harness-core/src/engine/processor.rs index 89befed..8d0e472 100644 --- a/crates/harness-core/src/engine/processor.rs +++ b/crates/harness-core/src/engine/processor.rs @@ -11,7 +11,8 @@ use crate::llm::{FinishReason, LlmEvent, LlmEventStream, ProviderError}; use crate::permission::{PermissionService, Ruleset}; use crate::store::Store; use crate::tool::{ - MetadataSink, PermissionHandle, SubagentSpawner, Tool, ToolCtx, ToolError, ToolRegistry, + ContextReporter, MetadataSink, PermissionHandle, SubagentSpawner, Tool, ToolCtx, ToolError, + ToolRegistry, }; use crate::types::{Message, MessageId, Part, PartBody, PartId, SessionId, TokenUsage, ToolState}; @@ -65,6 +66,9 @@ pub struct StepContext { /// This session's background job board (as a parent). Injected into requests when the /// running agent can delegate; `None` disables the board. pub job_board: Option>, + /// Present in subagent sessions: reports read files to this session's job on the parent + /// board. `None` for root sessions (nothing to report to). + pub context_reporter: Option>, } struct FlushTracker { @@ -506,6 +510,7 @@ impl<'a> Run<'a> { ask, metadata: metadata_sink, spawner: self.ctx.spawner.clone(), + context_reporter: self.ctx.context_reporter.clone(), }; let result = tokio::select! { diff --git a/crates/harness-core/src/tool/mod.rs b/crates/harness-core/src/tool/mod.rs index 685624e..3ee7e17 100644 --- a/crates/harness-core/src/tool/mod.rs +++ b/crates/harness-core/src/tool/mod.rs @@ -54,6 +54,14 @@ pub trait SubagentSpawner: Send + Sync { async fn spawn(&self, req: SpawnRequest) -> Result; } +/// Lets a child session report the files it read to its job board entry, so a completed +/// specialist advertises what it already looked at (docs/04-multiagent.md). Present only in +/// subagent sessions; the spawner wires it to the right board + job. +#[async_trait] +pub trait ContextReporter: Send + Sync { + async fn report_file(&self, path: String, lines: u32); +} + #[derive(Debug, thiserror::Error)] pub enum ToolError { #[error("permission denied")] @@ -185,6 +193,8 @@ pub struct ToolCtx { /// Present when the engine can spawn subagents (the `task` tool's capability). `None` /// in headless/test contexts with no orchestration wired in. pub spawner: Option>, + /// Present in subagent sessions: lets the read tool report files to the job board. + pub context_reporter: Option>, } #[derive(Debug)] diff --git a/crates/harness-tools/src/bash.rs b/crates/harness-tools/src/bash.rs index 0c3f831..b9dae14 100644 --- a/crates/harness-tools/src/bash.rs +++ b/crates/harness-tools/src/bash.rs @@ -150,6 +150,7 @@ mod tests { ), metadata, spawner: None, + context_reporter: None, } } diff --git a/crates/harness-tools/src/edit/mod.rs b/crates/harness-tools/src/edit/mod.rs index 6cd140a..654ca8d 100644 --- a/crates/harness-tools/src/edit/mod.rs +++ b/crates/harness-tools/src/edit/mod.rs @@ -233,6 +233,7 @@ mod tests { ), metadata, spawner: None, + context_reporter: None, } } diff --git a/crates/harness-tools/src/glob.rs b/crates/harness-tools/src/glob.rs index 44b59db..1600f5f 100644 --- a/crates/harness-tools/src/glob.rs +++ b/crates/harness-tools/src/glob.rs @@ -131,6 +131,7 @@ mod tests { ), metadata, spawner: None, + context_reporter: None, } } diff --git a/crates/harness-tools/src/grep.rs b/crates/harness-tools/src/grep.rs index 012f33c..15cf098 100644 --- a/crates/harness-tools/src/grep.rs +++ b/crates/harness-tools/src/grep.rs @@ -160,6 +160,7 @@ mod tests { ), metadata, spawner: None, + context_reporter: None, } } diff --git a/crates/harness-tools/src/read.rs b/crates/harness-tools/src/read.rs index 4ba2aa3..03f26f4 100644 --- a/crates/harness-tools/src/read.rs +++ b/crates/harness-tools/src/read.rs @@ -102,6 +102,13 @@ impl Tool for ReadTool { "(empty file or offset past end)".to_string(), )); } + + // In a subagent session, advertise this read on the job board. + if let Some(reporter) = &ctx.context_reporter { + let reported = paths::relative_pattern(&ctx.cwd, &path); + reporter.report_file(reported, numbered.len() as u32).await; + } + Ok(ToolOutput::new( params.file_path.clone(), numbered.join("\n"), @@ -140,6 +147,7 @@ mod tests { ), metadata, spawner: None, + context_reporter: None, } } diff --git a/crates/harness-tools/src/write.rs b/crates/harness-tools/src/write.rs index 7011030..6a07da7 100644 --- a/crates/harness-tools/src/write.rs +++ b/crates/harness-tools/src/write.rs @@ -115,6 +115,7 @@ mod tests { ), metadata, spawner: None, + context_reporter: None, } }