use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use serde_json::json;
use super::{
DELEGATE_TO_AGENT_TOOL_NAME, DelegateToAgentTool, EngineerCompletionSignal, redelegation_hint,
};
use crate::agent_loop::AgentLoopError;
use crate::llm::InferenceError;
use crate::runner::RunnerError;
use crate::tools::finish_task::FinishStatus;
use crate::tools::traits::{AgentOutput, AgentRunner, ToolExecutor};
struct RecordingRunner {
invoked: std::sync::Mutex<Vec<(String, String)>>,
}
#[async_trait]
impl AgentRunner for RecordingRunner {
async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
self.invoked
.lock()
.expect("lock poisoned")
.push((agent_name.to_string(), task.to_string()));
Ok(AgentOutput::from_content("ok"))
}
}
#[tokio::test]
async fn unknown_agent_returns_helpful_error() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(tmp.path().join("engineer.md"), "---\nname: engineer\n---\n").expect("write");
std::fs::write(tmp.path().join("qa-agent.md"), "---\nname: qa-agent\n---\n").expect("write");
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone()).with_config_dir(tmp.path().to_path_buf());
let result = tool
.execute(json!({"agent_name": "ghost", "task": "do something"}))
.await;
assert!(result.is_error(), "must reject unknown agent");
let msg = result.content();
assert!(
msg.contains("Unknown agent 'ghost'"),
"error must name the unknown agent, got: {msg}"
);
assert!(
msg.contains("engineer") && msg.contains("qa-agent"),
"error must list available agents, got: {msg}"
);
assert!(
msg.contains("native tools"),
"error must clarify native-vs-agent, got: {msg}"
);
assert!(
runner.invoked.lock().expect("lock").is_empty(),
"runner must not be called when validation fails"
);
}
#[tokio::test]
async fn known_agent_reaches_runner() {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::write(tmp.path().join("engineer.md"), "---\nname: engineer\n---\n").expect("write");
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone()).with_config_dir(tmp.path().to_path_buf());
let result = tool
.execute(json!({"agent_name": "engineer", "task": "do the thing"}))
.await;
assert!(
!result.is_error(),
"valid agent should succeed: {}",
result.content()
);
let invoked = runner.invoked.lock().expect("lock");
assert_eq!(invoked.len(), 1, "runner should be called exactly once");
assert_eq!(invoked[0].0, "engineer");
}
#[tokio::test]
async fn namespaced_plugin_agent_reaches_runner() {
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");
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone()).with_config_dir(agents_dir);
let result = tool
.execute(json!({"agent_name": "my-plugin:reviewer", "task": "review this"}))
.await;
assert!(
!result.is_error(),
"a valid namespaced plugin agent should succeed: {}",
result.content()
);
let invoked = runner.invoked.lock().expect("lock");
assert_eq!(invoked.len(), 1, "runner should be called exactly once");
assert_eq!(invoked[0].0, "my-plugin:reviewer");
}
#[tokio::test]
async fn namespaced_traversal_agent_name_is_rejected_before_runner() {
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 runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone()).with_config_dir(agents_dir);
let result = tool
.execute(json!({"agent_name": "my-plugin:../../etc/passwd", "task": "x"}))
.await;
assert!(result.is_error(), "traversal payload must be rejected");
assert!(
runner.invoked.lock().expect("lock").is_empty(),
"the runner must never be invoked for a rejected name"
);
}
#[tokio::test]
#[cfg(unix)]
async fn namespaced_symlinked_agent_leak_is_rejected_before_runner() {
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");
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone()).with_config_dir(agents_dir);
let result = tool
.execute(json!({"agent_name": "my-plugin:leak", "task": "x"}))
.await;
assert!(result.is_error(), "symlinked plugin agent must be rejected");
assert!(
!result.content().contains("SECRET_KEY_MATERIAL"),
"the secret content must never appear in the tool result, got: {}",
result.content()
);
assert!(
runner.invoked.lock().expect("lock").is_empty(),
"the runner must never be invoked for a rejected symlinked agent"
);
}
#[tokio::test]
async fn no_config_dir_skips_validation() {
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone());
let result = tool
.execute(json!({"agent_name": "anything-goes", "task": "do it"}))
.await;
assert!(!result.is_error(), "legacy mode should bypass validation");
assert_eq!(runner.invoked.lock().expect("lock").len(), 1);
}
#[tokio::test]
async fn missing_agent_name_returns_error() {
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner);
let result = tool.execute(json!({"task": "something"})).await;
assert!(result.is_error());
assert!(result.content().contains("missing 'agent_name'"));
}
#[tokio::test]
async fn path_traversal_agent_name_is_rejected() {
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone());
for bad_name in &[
"../../etc/passwd",
"../sibling",
"agent/sub",
"agent name",
"",
] {
let result = tool
.execute(json!({"agent_name": bad_name, "task": "do it"}))
.await;
assert!(
result.is_error(),
"traversal/invalid name '{bad_name}' must be rejected"
);
assert!(
result.content().contains("Invalid agent name"),
"error must describe the problem, got: {}",
result.content()
);
}
assert!(
runner.invoked.lock().expect("lock").is_empty(),
"runner must never be called for invalid names"
);
}
#[tokio::test]
async fn valid_agent_name_passes_sanitization() {
let runner = Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
});
let tool = DelegateToAgentTool::new(runner.clone());
for good_name in &["engineer", "qa-agent", "python_engineer", "rust-2024"] {
let result = tool
.execute(json!({"agent_name": good_name, "task": "do it"}))
.await;
assert!(
!result.is_error(),
"valid name '{good_name}' must be accepted: {}",
result.content()
);
}
assert_eq!(
runner.invoked.lock().expect("lock").len(),
4,
"runner must be called for each valid name"
);
}
struct FailingRunner<F: Fn() -> anyhow::Error + Send + Sync> {
make_err: F,
}
#[async_trait]
impl<F: Fn() -> anyhow::Error + Send + Sync> AgentRunner for FailingRunner<F> {
async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
Err((self.make_err)())
}
}
#[tokio::test]
async fn redelegation_hint_present_on_turn_cap_exceeded() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::TurnCapExceeded {
max_turns: 8,
partial: Box::new(AgentOutput::from_content("partial work")),
},
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build the package"}))
.await;
assert!(result.is_error());
let msg = result.content();
assert!(
msg.contains("READ and CONTINUE"),
"must instruct the PM to reuse existing work, got: {msg}"
);
assert!(
msg.contains("already written real, partial progress"),
"must explain why re-delegation should not start over, got: {msg}"
);
}
#[tokio::test]
async fn redelegation_hint_present_on_timeout() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::Timeout {
timeout_secs: 120,
partial: Box::new(AgentOutput::from_content("partial work")),
},
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build the package"}))
.await;
assert!(result.is_error());
assert!(result.content().contains("READ and CONTINUE"));
}
#[tokio::test]
async fn redelegation_hint_present_on_cancelled() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::Cancelled {
partial: Box::new(AgentOutput::from_content("partial work")),
},
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build the package"}))
.await;
assert!(result.is_error());
assert!(result.content().contains("READ and CONTINUE"));
}
#[tokio::test]
async fn redelegation_hint_absent_on_unknown_agent() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::UnknownAgent {
name: "ghost".to_string(),
dir: std::path::PathBuf::from("/agents"),
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "ghost", "task": "build the package"}))
.await;
assert!(result.is_error());
assert!(
!result.content().contains("READ and CONTINUE"),
"no partial work exists for an unresolved agent config, got: {}",
result.content()
);
}
#[tokio::test]
async fn redelegation_hint_present_on_llm_error() {
let runner = Arc::new(FailingRunner {
make_err: || {
anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::Llm(InferenceError::Api {
status: 500,
body: "internal error".to_string(),
}),
})
},
});
let tool = DelegateToAgentTool::new(runner);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build the package"}))
.await;
assert!(result.is_error());
assert!(
result.content().contains("READ and CONTINUE"),
"an LLM/transport error must ALSO carry the reuse directive (#2265), got: {}",
result.content()
);
}
#[test]
fn redelegation_hint_fn_returns_some_for_llm_error() {
let err = anyhow::Error::from(RunnerError::Loop {
name: "engineer".to_string(),
source: AgentLoopError::Llm(InferenceError::Api {
status: 503,
body: "bedrock throttled".to_string(),
}),
});
assert!(
redelegation_hint(&err).is_some(),
"redelegation_hint must return Some for AgentLoopError::Llm (#2265)"
);
}
struct FinishingRunner {
finish_status: Option<FinishStatus>,
invoked: std::sync::Mutex<u32>,
}
#[async_trait]
impl AgentRunner for FinishingRunner {
async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
*self.invoked.lock().expect("invoked lock") += 1;
let mut out = AgentOutput::from_content("engineer finished");
out.finish_status = self.finish_status;
Ok(out)
}
}
#[tokio::test]
async fn completion_signal_latches_on_completed_finish() {
let runner = Arc::new(FinishingRunner {
finish_status: Some(FinishStatus::Completed),
invoked: std::sync::Mutex::new(0),
});
let signal = EngineerCompletionSignal::new();
let tool = DelegateToAgentTool::new(runner).with_completion_signal(signal.clone());
let result = tool
.execute(json!({"agent_name": "engineer", "task": "build it"}))
.await;
assert!(!result.is_error(), "a completed delegation must succeed");
assert!(
signal.is_completed(),
"a Completed finish_task must latch the completion signal"
);
}
#[tokio::test]
async fn completion_signal_ignores_non_completed_finish() {
for status in [
Some(FinishStatus::Failed),
Some(FinishStatus::Cancelled),
None,
] {
let runner = Arc::new(FinishingRunner {
finish_status: status,
invoked: std::sync::Mutex::new(0),
});
let signal = EngineerCompletionSignal::new();
let tool = DelegateToAgentTool::new(runner).with_completion_signal(signal.clone());
let _ = tool
.execute(json!({"agent_name": "engineer", "task": "attempt it"}))
.await;
assert!(
!signal.is_completed(),
"finish_status {status:?} must not latch the completion signal"
);
}
}
#[tokio::test]
async fn delegate_refused_once_engineer_completed() {
let runner = Arc::new(FinishingRunner {
finish_status: Some(FinishStatus::Completed),
invoked: std::sync::Mutex::new(0),
});
let signal = EngineerCompletionSignal::new();
signal.mark_completed();
let tool = DelegateToAgentTool::new(runner.clone()).with_completion_signal(signal);
let result = tool
.execute(json!({"agent_name": "engineer", "task": "re-verify the work"}))
.await;
assert!(
result.is_error(),
"a post-completion delegation must be refused"
);
assert!(
!result.is_fatal(),
"the refusal must be recoverable, not fatal"
);
let msg = result.content();
assert!(
msg.contains("refused") && msg.contains("finish_task"),
"the refusal must nudge the PM to finish_task, got: {msg}"
);
assert_eq!(
*runner.invoked.lock().expect("invoked lock"),
0,
"the runner must never be invoked once the engineer has completed"
);
}
#[tokio::test]
async fn delegate_refusal_logs_warn() {
crate::test_support::begin_capture();
let runner = Arc::new(FinishingRunner {
finish_status: Some(FinishStatus::Completed),
invoked: std::sync::Mutex::new(0),
});
let signal = EngineerCompletionSignal::new();
signal.mark_completed();
let tool = DelegateToAgentTool::new(runner).with_completion_signal(signal);
tool.execute(json!({"agent_name": "engineer", "task": "re-verify the work"}))
.await;
let captured = crate::test_support::captured_at_least(tracing::Level::WARN);
assert!(
captured.iter().any(|m| m.contains("completion latch")),
"expected a warn-level refusal log, got: {captured:?}"
);
}
#[test]
fn delegate_tool_name_matches_the_constant() {
let tool = DelegateToAgentTool::new(Arc::new(RecordingRunner {
invoked: std::sync::Mutex::new(Vec::new()),
}));
assert_eq!(tool.name(), DELEGATE_TO_AGENT_TOOL_NAME);
}