use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use async_trait::async_trait;
use serde_json::{Value, json};
use tempfile::TempDir;
use super::{InProcessAgentRunner, InProcessRunnerConfig};
use crate::agent_loop::ToolEventSink;
use crate::agents::AgentConfig;
use crate::llm::{ChatRequest, ChatResponse, InferenceAdapter, InferenceError};
use crate::tools::{
AgentRunner, DelegateToAgentTool, RunContext, ToolExecutor, ToolRegistry, ToolResult,
};
struct ScriptedLlm {
responses: Vec<ChatResponse>,
cursor: AtomicUsize,
seen: Mutex<Vec<(String, String)>>,
max_tokens_seen: Mutex<Vec<Option<u32>>>,
}
impl ScriptedLlm {
fn from_json(fixtures: &[Value]) -> Self {
let responses = fixtures
.iter()
.map(|v| serde_json::from_value(v.clone()).expect("valid ChatResponse fixture"))
.collect();
Self {
responses,
cursor: AtomicUsize::new(0),
seen: Mutex::new(Vec::new()),
max_tokens_seen: Mutex::new(Vec::new()),
}
}
fn calls(&self) -> usize {
self.cursor.load(Ordering::SeqCst)
}
fn first_request(&self) -> (String, String) {
self.seen
.lock()
.expect("seen lock")
.first()
.cloned()
.expect("at least one request recorded")
}
fn first_max_tokens(&self) -> Option<u32> {
self.max_tokens_seen
.lock()
.expect("max_tokens_seen lock")
.first()
.copied()
.expect("at least one request recorded")
}
}
#[async_trait]
impl InferenceAdapter for ScriptedLlm {
crate::llm::mock_adapter_identity!("mock-scripted");
async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
let system = req
.messages
.iter()
.find(|m| m.role == "system")
.and_then(|m| m.content.clone())
.unwrap_or_default();
self.seen
.lock()
.expect("seen lock")
.push((req.model.clone(), system));
self.max_tokens_seen
.lock()
.expect("max_tokens_seen lock")
.push(req.max_tokens);
let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
match self.responses.get(idx) {
Some(resp) => Ok(resp.clone()),
None => Err(InferenceError::MissingConfig(format!(
"scripted LLM exhausted at call {idx}"
))),
}
}
}
struct SleepyLlm {
inner: ScriptedLlm,
delay: std::time::Duration,
}
#[async_trait]
impl InferenceAdapter for SleepyLlm {
crate::llm::mock_adapter_identity!("mock-sleepy");
async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
tokio::time::sleep(self.delay).await;
self.inner.chat(req).await
}
}
struct RecordingTool {
name: &'static str,
invoked: Arc<Mutex<Vec<String>>>,
}
#[async_trait]
impl ToolExecutor for RecordingTool {
fn name(&self) -> &str {
self.name
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": self.name,
"description": "recording tool",
"parameters": { "type": "object", "properties": {} }
}
})
}
async fn execute(&self, _args: Value) -> ToolResult {
self.invoked
.lock()
.expect("invoked lock")
.push(self.name.to_string());
ToolResult::ok(format!("{}: ran", self.name))
}
}
fn tool_call_response(call_id: &str, tool: &str) -> Value {
json!({
"id": "gen-tool",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": call_id,
"type": "function",
"function": { "name": tool, "arguments": "{}" }
}]
},
"finish_reason": "tool_calls"
}],
"usage": { "prompt_tokens": 30, "completion_tokens": 10, "total_tokens": 40 }
})
}
fn stop_response(text: &str) -> Value {
json!({
"id": "gen-stop",
"choices": [{
"message": { "role": "assistant", "content": text, "tool_calls": [] },
"finish_reason": "stop"
}],
"usage": { "prompt_tokens": 15, "completion_tokens": 5, "total_tokens": 20 }
})
}
fn agents_dir_with(body: &str, agent: &str) -> TempDir {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(tmp.path().join(format!("{agent}.md")), body).expect("write agent md");
tmp
}
fn recording_factory(
tools: Vec<&'static str>,
invoked: Arc<Mutex<Vec<String>>>,
) -> impl Fn(
AgentConfig,
RunContext,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Arc<ToolRegistry>> + Send>> {
move |_agent: AgentConfig, _ctx: RunContext| {
let tools = tools.clone();
let invoked = Arc::clone(&invoked);
Box::pin(async move {
let mut reg = ToolRegistry::new();
for name in tools {
reg.register(Arc::new(RecordingTool {
name,
invoked: Arc::clone(&invoked),
}));
}
Arc::new(reg)
})
}
}
fn finish_task_call_response(call_id: &str, arguments: &str) -> Value {
json!({
"id": "gen-finish",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": call_id,
"type": "function",
"function": { "name": "finish_task", "arguments": arguments }
}]
},
"finish_reason": "tool_calls"
}],
"usage": { "prompt_tokens": 30, "completion_tokens": 10, "total_tokens": 40 }
})
}
fn finish_and_bash_factory() -> impl Fn(
AgentConfig,
RunContext,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Arc<ToolRegistry>> + Send>,
> {
move |_agent: AgentConfig, _ctx: RunContext| {
Box::pin(async move {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(crate::tools::FinishTaskTool::new()));
reg.register(Arc::new(crate::tools::BashTool::default_config()));
Arc::new(reg)
})
}
}
#[test]
fn config_default_is_sane() {
let cfg = InProcessRunnerConfig::default();
assert!(cfg.max_turns >= 1);
assert!(cfg.timeout_secs >= 1);
}
#[test]
fn default_max_turns_is_generous() {
let cfg = InProcessRunnerConfig::default();
assert!(
cfg.max_turns > 8,
"default max_turns must be raised above the old 8-turn cap, got {}",
cfg.max_turns
);
assert!(
cfg.max_turns >= 30,
"default max_turns should comfortably fit a multi-file package task, got {}",
cfg.max_turns
);
}
#[test]
fn agent_config_exists_detects_present_and_absent() {
let tmp = agents_dir_with("---\nname: python-engineer\n---\n", "python-engineer");
assert!(super::agent_config_exists(tmp.path(), "python-engineer"));
assert!(!super::agent_config_exists(tmp.path(), "ghost"));
}
#[test]
fn agent_config_exists_detects_embedded_default() {
let tmp = tempfile::tempdir().expect("tempdir");
assert!(super::agent_config_exists(tmp.path(), "rust-engineer"));
assert!(!super::agent_config_exists(tmp.path(), "totally-bogus"));
}
#[test]
fn agent_config_exists_detects_plugin_agent() {
let tmp = tempfile::tempdir().expect("tempdir");
let agents_dir = tmp.path().join(".claude").join("agents");
std::fs::create_dir_all(&agents_dir).expect("mkdir");
let plugin_agents_dir = tmp
.path()
.join(".claude")
.join("plugins")
.join("my-plugin")
.join("agents");
std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");
std::fs::write(
plugin_agents_dir.join("reviewer.md"),
"---\nname: reviewer\n---\n\nBody.\n",
)
.expect("write");
assert!(super::agent_config_exists(
&agents_dir,
"my-plugin:reviewer"
));
assert!(!super::agent_config_exists(&agents_dir, "my-plugin:ghost"));
assert!(!super::agent_config_exists(
&agents_dir,
"no-such-plugin:reviewer"
));
}
#[test]
fn agent_config_exists_rejects_plugin_traversal_name() {
let tmp = tempfile::tempdir().expect("tempdir");
let agents_dir = tmp.path().join(".claude").join("agents");
std::fs::create_dir_all(&agents_dir).expect("mkdir");
assert!(!super::agent_config_exists(
&agents_dir,
"my-plugin:../../etc/passwd"
));
assert!(!super::agent_config_exists(
&agents_dir,
"my-plugin:/etc/passwd"
));
}
#[test]
#[cfg(unix)]
fn agent_config_exists_rejects_symlinked_plugin_agent() {
let tmp = tempfile::tempdir().expect("tempdir");
let agents_dir = tmp.path().join(".claude").join("agents");
std::fs::create_dir_all(&agents_dir).expect("mkdir");
let plugin_agents_dir = tmp
.path()
.join(".claude")
.join("plugins")
.join("my-plugin")
.join("agents");
std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");
let secret_dir = tmp.path().join("outside");
std::fs::create_dir_all(&secret_dir).expect("mkdir");
let secret_path = secret_dir.join("id_rsa");
std::fs::write(&secret_path, "SECRET_KEY_MATERIAL").expect("write secret");
std::os::unix::fs::symlink(&secret_path, plugin_agents_dir.join("leak.md")).expect("symlink");
assert!(!super::agent_config_exists(&agents_dir, "my-plugin:leak"));
}
#[tokio::test]
async fn embedded_restricted_agent_dispatch_preserves_tools_allowed() {
let tmp = tempfile::tempdir().expect("tempdir");
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("c1", "bash"),
stop_response("concluded"),
]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(
vec!["read_file", "bash"],
Arc::clone(&invoked),
));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());
let out = runner
.run("qa", "try the denied tool")
.await
.expect("loop completes (denied tool surfaces a recoverable error)");
assert_eq!(out.content, "concluded");
let ran = invoked.lock().expect("invoked");
assert!(
!ran.contains(&"bash".to_string()),
"the embedded 'qa' agent's restricted allowlist must gate out 'bash' \
even though it was never loaded from disk, ran: {ran:?}"
);
}
#[tokio::test]
async fn delegate_runs_engineer_loop() {
let body = "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\n\
You are a Python engineer.\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("c1", "work_tool"),
stop_response("engineer done"),
]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["work_tool"], Arc::clone(&invoked)));
let runner = Arc::new(InProcessAgentRunner::new(
llm.clone(),
factory,
tmp.path().to_path_buf(),
));
let delegate = DelegateToAgentTool::new(runner).with_config_dir(tmp.path().to_path_buf());
let result = delegate
.execute(json!({"agent_name": "python-engineer", "task": "write a function"}))
.await;
assert!(
!result.is_error(),
"delegation should succeed: {}",
result.content()
);
assert_eq!(
result.content(),
"engineer done",
"PM must receive the engineer's final AgentOutput content"
);
assert_eq!(llm.calls(), 2, "engineer loop made exactly two chat calls");
let (model, _) = llm.first_request();
assert_eq!(
model, "deepseek/deepseek-chat",
"engineer's own model slug must drive its loop"
);
assert_eq!(
invoked.lock().expect("invoked").as_slice(),
["work_tool"],
"the engineer's tool must have run inside its own loop"
);
}
#[tokio::test]
async fn engineer_llm_max_tokens_reaches_chat_request() {
let body = "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n\
max_tokens: 8192\n---\n\nYou are a Python engineer.\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("engineer done")]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["work_tool"], Arc::clone(&invoked)));
let runner = Arc::new(InProcessAgentRunner::new(
llm.clone(),
factory,
tmp.path().to_path_buf(),
));
let delegate = DelegateToAgentTool::new(runner).with_config_dir(tmp.path().to_path_buf());
let result = delegate
.execute(json!({"agent_name": "python-engineer", "task": "write a function"}))
.await;
assert!(
!result.is_error(),
"delegation should succeed: {}",
result.content()
);
assert_eq!(
llm.first_max_tokens(),
Some(8192),
"the engineer's configured [llm].max_tokens must reach its ChatRequest"
);
}
#[tokio::test]
async fn unknown_agent_errors() {
let tmp = tempfile::tempdir().expect("tempdir");
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("never reached")]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec![], invoked));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());
let err = runner
.run("ghost", "do something")
.await
.expect_err("unknown agent must error");
assert!(
err.to_string().contains("ghost"),
"error must name the unknown agent, got: {err}"
);
assert_eq!(llm.calls(), 0, "loop must not run for an unknown agent");
}
#[tokio::test]
async fn tools_allowed_is_enforced() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n\
tcode_tools: [allowed_tool]\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("c1", "denied_tool"),
stop_response("concluded"),
]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(
vec!["allowed_tool", "denied_tool"],
Arc::clone(&invoked),
));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());
let out = runner
.run("python-engineer", "try the denied tool")
.await
.expect("loop completes (denied tool surfaces a recoverable error)");
assert_eq!(out.content, "concluded");
let ran = invoked.lock().expect("invoked");
assert!(
!ran.contains(&"denied_tool".to_string()),
"denied tool must never execute; gated out of the registry, ran: {ran:?}"
);
}
#[tokio::test]
async fn no_allowlist_permits_all() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("c1", "any_tool"),
stop_response("ok"),
]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["any_tool"], Arc::clone(&invoked)));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());
runner
.run("python-engineer", "use a tool")
.await
.expect("completes");
assert_eq!(
invoked.lock().expect("invoked").as_slice(),
["any_tool"],
"with no allowlist, the tool must run"
);
}
#[tokio::test]
async fn usage_rolls_up_to_output() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("c1", "any_tool"),
stop_response("done"),
]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["any_tool"], invoked));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());
let out = runner
.run("python-engineer", "task")
.await
.expect("completes");
assert_eq!(
out.usage.prompt_tokens,
30 + 15,
"prompt tokens sum across turns"
);
assert_eq!(
out.usage.completion_tokens,
10 + 5,
"completion tokens sum across turns"
);
}
#[tokio::test]
async fn run_context_overrides_model() {
let body = "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec![], invoked));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());
let ctx = RunContext {
model: Some("anthropic/claude-sonnet-4-6".to_string()),
..Default::default()
};
runner
.run_with_context("python-engineer", "task", &ctx)
.await
.expect("completes");
let (model, _) = llm.first_request();
assert_eq!(
model, "anthropic/claude-sonnet-4-6",
"RunContext.model must override the agent's configured model"
);
}
#[tokio::test]
async fn run_context_overrides_max_turns() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("c1", "any_tool"),
tool_call_response("c2", "any_tool"),
tool_call_response("c3", "any_tool"),
]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["any_tool"], invoked));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
.with_config(InProcessRunnerConfig {
max_turns: 8,
timeout_secs: 30,
});
let ctx = RunContext {
max_turns_override: Some(1),
..Default::default()
};
let err = runner
.run_with_context("python-engineer", "loop", &ctx)
.await
.expect_err("a 1-turn cap on a non-converging loop must abort");
assert!(
err.to_string().contains("turn cap of 1"),
"error should report the overridden cap, got: {err}"
);
assert_eq!(
llm.calls(),
1,
"loop must stop after the single allowed turn"
);
}
#[tokio::test]
async fn with_timeout_secs_shortens_the_deadline() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(SleepyLlm {
inner: ScriptedLlm::from_json(&[stop_response("done")]),
delay: std::time::Duration::from_secs(3),
});
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec![], invoked));
let runner =
InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf()).with_timeout_secs(1);
let started = std::time::Instant::now();
let err = runner
.run("python-engineer", "task")
.await
.expect_err("a 1s deadline against a 3s-delayed response must time out");
let elapsed = started.elapsed();
assert!(
err.to_string().contains("wall-clock timeout of 1s"),
"error must be the Timeout variant, got: {err}"
);
assert!(
elapsed < std::time::Duration::from_secs(3),
"the 1s override must fire well before the mock's 3s delay, elapsed={elapsed:?}"
);
}
#[tokio::test]
async fn with_timeout_secs_preserves_configured_max_turns() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("c1", "any_tool"),
tool_call_response("c2", "any_tool"),
tool_call_response("c3", "any_tool"),
]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["any_tool"], invoked));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
.with_config(InProcessRunnerConfig {
max_turns: 2,
timeout_secs: 30,
})
.with_timeout_secs(300);
let err = runner
.run("python-engineer", "task")
.await
.expect_err("a 2-turn cap on a non-converging loop must abort");
assert!(
err.to_string().contains("turn cap of 2"),
"max_turns=2 from with_config must survive the later with_timeout_secs call, got: {err}"
);
assert_eq!(
llm.calls(),
2,
"loop must stop after the configured 2 turns"
);
}
#[tokio::test]
async fn project_context_reaches_prompt() {
let body =
"---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n\nAGENT-PROMPT-MARKER\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec![], invoked));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
.with_project_context("PROJECT-CONTEXT-MARKER");
runner
.run("python-engineer", "task")
.await
.expect("completes");
let (_, system) = llm.first_request();
assert!(
system.contains("AGENT-PROMPT-MARKER"),
"assembled prompt must include the agent's own system prompt"
);
assert!(
system.contains("PROJECT-CONTEXT-MARKER"),
"assembled prompt must include the injected project context"
);
}
#[tokio::test]
async fn skills_catalog_reaches_daily_driver_prompt() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec![], invoked));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
.with_skills_catalog("SKILLS-CATALOG-MARKER");
runner
.run("python-engineer", "task")
.await
.expect("completes");
let (_, system) = llm.first_request();
assert!(
system.contains("SKILLS-CATALOG-MARKER"),
"assembled DailyDriver prompt must include the skill catalog"
);
}
#[tokio::test]
async fn skills_catalog_ignored_in_parity() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec![], invoked));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
.with_skills_catalog("SKILLS-CATALOG-MARKER")
.with_mode(crate::mode::HarnessMode::Parity);
runner
.run("python-engineer", "task")
.await
.expect("completes");
let (_, system) = llm.first_request();
assert!(
!system.contains("SKILLS-CATALOG-MARKER"),
"Parity prompt must never include the skill catalog"
);
}
#[tokio::test]
async fn with_mode_completes_a_delegated_run_in_both_modes() {
let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
let tmp = agents_dir_with(body, "python-engineer");
for mode in [
crate::mode::HarnessMode::DailyDriver,
crate::mode::HarnessMode::Parity,
] {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec![], invoked));
let runner =
InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf()).with_mode(mode);
runner
.run("python-engineer", "task")
.await
.unwrap_or_else(|e| panic!("run must complete under mode {mode:?}: {e}"));
}
}
#[derive(Default)]
struct RecordingSink {
calls: Mutex<Vec<String>>,
started_ids: Mutex<Vec<(String, String)>>,
lifecycle: Mutex<Vec<String>>,
}
#[async_trait]
impl ToolEventSink for RecordingSink {
async fn tool_started(
&self,
agent: &str,
agent_id: &str,
call_id: &str,
tool: &str,
_args_preview: &str,
) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("started:{agent}:{tool}:{call_id}"));
self.started_ids
.lock()
.expect("lock poisoned")
.push((agent.to_string(), agent_id.to_string()));
}
async fn tool_finished(
&self,
agent: &str,
_agent_id: &str,
call_id: &str,
tool: &str,
success: bool,
_result_preview: &str,
) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("finished:{agent}:{tool}:{call_id}:{success}"));
}
async fn tool_error(
&self,
agent: &str,
_agent_id: &str,
call_id: &str,
tool: &str,
_error: &str,
) {
self.calls
.lock()
.expect("lock poisoned")
.push(format!("error:{agent}:{tool}:{call_id}"));
}
async fn agent_spawned(&self, agent: &str, agent_id: &str, task_preview: &str) {
self.lifecycle
.lock()
.expect("lock poisoned")
.push(format!("spawned:{agent}:{agent_id}:{task_preview}"));
}
async fn agent_done(&self, agent: &str, agent_id: &str, status: &str) {
self.lifecycle
.lock()
.expect("lock poisoned")
.push(format!("done:{agent}:{agent_id}:{status}"));
}
async fn agent_failed(&self, agent: &str, agent_id: &str, _error: &str) {
self.lifecycle
.lock()
.expect("lock poisoned")
.push(format!("failed:{agent}:{agent_id}"));
}
}
#[tokio::test]
async fn delegation_emits_spawned_then_done_on_the_sink() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "mytool"),
stop_response("engineer done"),
]));
let tmp = agents_dir_with(
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
"python-engineer",
);
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["mytool"], invoked));
let sink = Arc::new(RecordingSink::default());
let runner = InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf())
.with_tool_event_sink(sink.clone());
runner
.run("python-engineer", "build the thing")
.await
.expect("completes");
let lifecycle = sink.lifecycle.lock().expect("lock poisoned").clone();
assert_eq!(lifecycle.len(), 2, "one spawn, one close: {lifecycle:?}");
let spawned = lifecycle[0]
.strip_prefix("spawned:python-engineer:")
.expect("first hook must be agent_spawned for the delegated agent");
let (spawn_id, task) = spawned
.split_once(':')
.expect("spawned record carries an id and the task preview");
assert!(!spawn_id.is_empty(), "the spawn must carry its agent_id");
assert_eq!(task, "build the thing");
assert_eq!(
lifecycle[1],
format!("done:python-engineer:{spawn_id}:success")
);
let started_ids = sink.started_ids.lock().expect("lock poisoned").clone();
assert_eq!(
started_ids[0].1, spawn_id,
"the sub-agent's tool events must carry the SAME id the spawn \
announced, or a consumer cannot file them under that delegation"
);
}
#[tokio::test]
async fn failed_delegation_emits_agent_failed() {
let llm = Arc::new(ScriptedLlm::from_json(&[]));
let tmp = agents_dir_with(
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
"python-engineer",
);
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["mytool"], invoked));
let sink = Arc::new(RecordingSink::default());
let runner = InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf())
.with_tool_event_sink(sink.clone());
runner
.run("python-engineer", "build the thing")
.await
.expect_err("an exhausted script must abort the loop");
let lifecycle = sink.lifecycle.lock().expect("lock poisoned").clone();
assert_eq!(lifecycle.len(), 2, "{lifecycle:?}");
assert!(lifecycle[0].starts_with("spawned:python-engineer:"));
assert!(
lifecycle[1].starts_with("failed:python-engineer:"),
"a failed delegation must close with agent_failed: {lifecycle:?}"
);
}
#[tokio::test]
async fn sink_reaches_delegated_loop() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "mytool"),
stop_response("engineer done"),
]));
let tmp = agents_dir_with(
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
"python-engineer",
);
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["mytool"], invoked));
let sink = Arc::new(RecordingSink::default());
let runner = InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf())
.with_tool_event_sink(sink.clone());
runner
.run("python-engineer", "task")
.await
.expect("completes");
assert_eq!(
sink.calls.lock().expect("lock poisoned").as_slice(),
[
"started:python-engineer:mytool:call-1",
"finished:python-engineer:mytool:call-1:true"
],
"the runner must attribute a delegated sub-agent's tool events to \
that sub-agent — the sink is shared with the PM, so an unattributed \
(or PM-attributed) event here would make the two indistinguishable"
);
}
#[tokio::test]
async fn sequential_delegations_to_same_named_agent_get_distinct_ids() {
let llm = Arc::new(ScriptedLlm::from_json(&[
tool_call_response("call-1", "mytool"),
stop_response("engineer done 1"),
tool_call_response("call-2", "mytool"),
stop_response("engineer done 2"),
]));
let tmp = agents_dir_with(
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
"python-engineer",
);
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["mytool"], invoked));
let sink = Arc::new(RecordingSink::default());
let runner = InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf())
.with_tool_event_sink(sink.clone());
runner
.run("python-engineer", "task A")
.await
.expect("first delegation completes");
runner
.run("python-engineer", "task B")
.await
.expect("second delegation completes");
let ids = sink.started_ids.lock().expect("lock poisoned").clone();
assert_eq!(ids.len(), 2, "expected one tool_started per delegation");
let (agent_a, id_a) = &ids[0];
let (agent_b, id_b) = &ids[1];
assert_eq!(agent_a, "python-engineer");
assert_eq!(agent_b, "python-engineer");
assert_ne!(
id_a, id_b,
"two delegations to the SAME agent_name must mint DISTINCT agent_ids \
(DOC-39 AC-13) — otherwise same-named delegated agents stay \
indistinguishable on the event stream"
);
assert!(!id_a.is_empty() && id_a != crate::events::UNATTRIBUTED_AGENT_ID);
assert!(!id_b.is_empty() && id_b != crate::events::UNATTRIBUTED_AGENT_ID);
}
struct ConversationAwareLlm;
#[async_trait]
impl InferenceAdapter for ConversationAwareLlm {
crate::llm::mock_adapter_identity!("mock-conversation-aware");
async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
tokio::task::yield_now().await;
let last_was_tool_result = req
.messages
.last()
.map(|m| m.role == "tool")
.unwrap_or(false);
let fixture = if last_was_tool_result {
stop_response("engineer done")
} else {
tool_call_response("call-1", "mytool")
};
serde_json::from_value(fixture).map_err(|e| {
InferenceError::MissingConfig(format!("ConversationAwareLlm: invalid fixture: {e}"))
})
}
}
#[tokio::test]
async fn concurrently_delegated_same_named_agents_get_distinct_ids_under_tokio_join() {
let llm = Arc::new(ConversationAwareLlm);
let tmp = agents_dir_with(
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
"python-engineer",
);
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec!["mytool"], invoked));
let sink = Arc::new(RecordingSink::default());
let runner = InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf())
.with_tool_event_sink(sink.clone());
let (result_a, result_b) = tokio::join!(
runner.run("python-engineer", "task A"),
runner.run("python-engineer", "task B"),
);
result_a.expect("delegation A completes");
result_b.expect("delegation B completes");
let ids = sink.started_ids.lock().expect("lock poisoned").clone();
assert_eq!(
ids.len(),
2,
"expected one tool_started per concurrently-run delegation: {ids:?}"
);
assert!(
ids.iter().all(|(agent, _)| agent == "python-engineer"),
"both concurrent delegations must attribute to the SAME agent name: {ids:?}"
);
let (_, id_a) = &ids[0];
let (_, id_b) = &ids[1];
assert_ne!(
id_a, id_b,
"two GENUINELY CONCURRENT delegations to the SAME agent_name must \
still mint DISTINCT agent_ids (DOC-39 AC-13) — this empirically \
exercises the per-spawn UUID mint under an actual race, not just a \
by-construction argument"
);
assert!(!id_a.is_empty() && id_a != crate::events::UNATTRIBUTED_AGENT_ID);
assert!(!id_b.is_empty() && id_b != crate::events::UNATTRIBUTED_AGENT_ID);
}
#[tokio::test]
async fn cancel_flag_reaches_delegated_loop() {
let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
"should never be reached",
)]));
let tmp = agents_dir_with(
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
"python-engineer",
);
let invoked = Arc::new(Mutex::new(Vec::new()));
let factory = Arc::new(recording_factory(vec![], invoked));
let cancel = Arc::new(AtomicBool::new(true));
let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
.with_cancel_flag(cancel);
let result = runner.run("python-engineer", "task").await;
assert!(result.is_err(), "a pre-cancelled run must error");
assert_eq!(
llm.calls(),
0,
"cancellation must be observed before any chat call"
);
}
#[tokio::test]
async fn work_root_reaches_the_finish_gate() {
let body = "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\n\
You are a Python engineer.\n";
let tmp = agents_dir_with(body, "python-engineer");
let project = tempfile::tempdir().expect("tempdir for the work root");
std::fs::write(
project.path().join("Cargo.toml"),
"[package]\nname = \"fixture\"\n",
)
.expect("write Cargo.toml");
let script = [
finish_task_call_response(
"c1",
r#"{"status": "completed", "summary": "done (premature)"}"#,
),
stop_response("engineer done"),
];
let factory: Arc<dyn super::in_process::RegistryFactory> = Arc::new(finish_and_bash_factory());
let bound = Arc::new(ScriptedLlm::from_json(&script));
let runner = InProcessAgentRunner::new(bound.clone(), Arc::clone(&factory), tmp.path())
.with_work_root(project.path());
runner
.run("python-engineer", "run cargo test before finishing")
.await
.expect("the loop must recover after the gate's refusal");
assert_eq!(
bound.calls(),
2,
"a bound work root with a Cargo.toml must let the gate refuse turn 1's finish"
);
let unbound = Arc::new(ScriptedLlm::from_json(&script));
let runner = InProcessAgentRunner::new(unbound.clone(), factory, tmp.path());
runner
.run("python-engineer", "run cargo test before finishing")
.await
.expect("an unbound runner must accept the finish");
assert_eq!(
unbound.calls(),
1,
"with no work root there is nothing to detect, so the finish stands"
);
}