trusty_code/tools/delegate.rs
1//! `delegate_to_agent` tool — the PM's primary tool for dispatching to sub-agents.
2//!
3//! Why: Keeps the delegation schema and its executor colocated so the PM's tool
4//! registry can register a single type that owns both. Pre-flight validation of
5//! `agent_name` against the on-disk agent config directory prevents the LLM from
6//! hallucinating sub-agent names and crashing the subprocess runner with a
7//! confusing IO error (#204 equivalent). (bake-off L1 diagnosis) A delegated
8//! engineer that exhausts its turn/time budget has usually already written
9//! real, partial progress to disk; the PM's recovery historically was a
10//! free-text "re-delegate with a streamlined brief" that never told the next
11//! engineer instance to look at what was already there, so it silently
12//! rebuilt a simpler (sometimes incomplete) solution and orphaned the correct
13//! work. `redelegation_hint` makes the safer instruction automatic: it fires
14//! on every `TurnCapExceeded`/`Timeout`/`Cancelled` abort, regardless of
15//! whether the PM's own free text remembers to ask for it.
16//! What: `DelegateToAgentTool` wraps an `AgentRunner` and (optionally) an agent
17//! config directory. `execute()` parses `{agent_name, task}`, validates the agent
18//! config exists, and hands off to the runner. On miss, returns a helpful error
19//! listing available agents. On a runner failure caused by the sub-agent's own
20//! loop aborting with partial work still on disk, the returned `ToolResult`
21//! error appends a fixed reuse/continue directive (`redelegation_hint`).
22//! (#2265) `redelegation_hint` is also `pub(crate)` so
23//! `run_task::redelegation::RedelegatingRunner` can reuse the SAME hint logic
24//! to decide, entirely inside one `delegate_to_agent` dispatch, whether a
25//! failed engineer attempt is worth automatically retrying — see that
26//! module's docs for the retry/cap mechanics.
27//! Test: `unknown_agent_returns_helpful_error` builds a tool pointed at a tempdir
28//! containing `engineer.md` only, calls `execute({"agent_name":"ghost",...})`,
29//! and asserts the error names the unknown agent and lists `engineer`.
30//! `redelegation_hint_*` tests cover the reuse-directive behaviour.
31
32use std::path::PathBuf;
33use std::sync::Arc;
34use std::sync::atomic::{AtomicBool, Ordering};
35
36use async_trait::async_trait;
37use serde_json::{Value, json};
38
39use crate::agent_loop::AgentLoopError;
40use crate::runner::RunnerError;
41use crate::tools::finish_task::FinishStatus;
42use crate::tools::traits::{AgentOutput, AgentRunner, ToolExecutor, ToolResult};
43
44/// Detect whether an `AgentRunner` failure means the sub-agent's OWN attempt
45/// may have left partial work already on disk (turn cap, timeout,
46/// cancellation, or a retryable LLM/transport hiccup), as opposed to a hard
47/// failure (unknown agent, bad config) that leaves nothing to reuse.
48///
49/// Why: (bake-off L1 diagnosis) The PM only sees this failure as opaque error
50/// text; without a structured signal, its free-text re-delegation brief has no
51/// reliable reason to mention the sub-agent's partial progress, so the next
52/// delegated instance rebuilds from scratch and orphans correct prior work.
53/// Surfacing a fixed directive automatically — every time this specific
54/// failure shape occurs — makes "read existing files, then continue" the
55/// default recovery instead of something the PM must remember to ask for.
56/// (#2265) `AgentLoopError::Llm` — a recoverable Bedrock/transport error that
57/// aborts the engineer's sub-loop mid-session — is the DOMINANT failure mode
58/// observed in the bake-off transcripts, yet #2233 left it out of this match,
59/// so the reuse hint never fired for the most common case and every retry
60/// re-read PROBLEM.md from zero. It now gets the same hint: tool calls the
61/// engineer already dispatched before the failing `chat` call (e.g.
62/// `write_file`) already landed on disk even though `AgentLoopError::Llm`
63/// itself carries no `partial: Box<AgentOutput>` (unlike the three
64/// budget-abort variants) — there is real, on-disk work to reuse even though
65/// there is no partial transcript snapshot to point to.
66/// What: Downcasts `err` to [`RunnerError`] and matches `RunnerError::Loop`
67/// whose source is `AgentLoopError::TurnCapExceeded`, `Timeout`, `Cancelled`,
68/// (#2265) `Llm`, or (#2265 fix #5) `StoppedBySignal`. Returns `None` only
69/// for `UnknownAgent`/`ConfigLoad` — failures that never reached a sub-agent
70/// loop at all, so there is nothing on disk to reuse.
71/// Note: a delegated engineer's own sub-loop never actually attaches a stop
72/// signal today (only `run_task`'s PM loop does, via
73/// `AgentLoop::with_stop_signal`), so `StoppedBySignal` is unreachable from
74/// this call site in practice; it is included for exhaustiveness and to stay
75/// correct if that ever changes.
76/// Test: `redelegation_hint_present_on_turn_cap_exceeded`,
77/// `redelegation_hint_present_on_timeout`,
78/// `redelegation_hint_present_on_cancelled`,
79/// `redelegation_hint_present_on_llm_error`,
80/// `redelegation_hint_absent_on_unknown_agent`.
81pub(crate) fn redelegation_hint(err: &anyhow::Error) -> Option<&'static str> {
82 let RunnerError::Loop { source, .. } = err.downcast_ref::<RunnerError>()? else {
83 return None;
84 };
85 match source {
86 AgentLoopError::TurnCapExceeded { .. }
87 | AgentLoopError::Timeout { .. }
88 | AgentLoopError::Cancelled { .. }
89 | AgentLoopError::StoppedBySignal { .. }
90 | AgentLoopError::Llm(_) => Some(
91 "\n\nNOTE for re-delegation: the sub-agent's previous attempt did not reach a \
92 normal finish — it ran out of turns or time, was cancelled, or hit a \
93 transient LLM/transport error — NOT a task failure. It has likely already \
94 written real, partial progress to disk. Before delegating this task again: \
95 (1) inspect the project's current files to see what the sub-agent already \
96 produced, (2) instruct the next sub-agent to READ and CONTINUE/BUILD ON that \
97 existing work rather than rewriting it from scratch, and (3) consider a narrower \
98 follow-up task (or a higher turn budget) so it can finish what is already started \
99 instead of starting over.",
100 ),
101 }
102}
103
104/// Run-scoped latch recording that a delegated engineer already reported an
105/// EXPLICIT successful completion (`finish_task` with `status: completed`)
106/// during this run (#2683).
107///
108/// Why: The bake-off regression this closes is a PM that, after the engineer
109/// already called `finish_task` with all tests passing, fires ONE MORE
110/// gratuitous `delegate_to_agent` "re-verify" round; when that extra round
111/// then runs out of turns / wall-clock time, the run terminated mid-round and
112/// was mislabeled `partial`/exit-6 even though a complete, correct,
113/// all-tests-passing deliverable already sat on disk — corrupting run
114/// status/telemetry (issue #2683 recurrence comment, 2026-07-15). This shared
115/// latch is the authoritative "the task is genuinely done" signal: once set,
116/// [`DelegateToAgentTool`] refuses further re-delegation (part b of the fix)
117/// and `run_task::assemble_report` reports success rather than partial (the
118/// data-integrity half). Modeled as a cheap `Arc<AtomicBool>` handle,
119/// mirroring `run_task::redelegation::RedelegationCapSignal`, so the tool (the
120/// setter) and the report assembler (the reader) observe the SAME state.
121/// What: `new()` starts un-latched; `mark_completed` latches it (set only by
122/// [`DelegateToAgentTool::execute`] when the delegated runner returns an
123/// `AgentOutput` whose `finish_status` is `Some(FinishStatus::Completed)`);
124/// `is_completed` reads it. `Clone` shares the same underlying flag.
125/// Test: `tools::delegate::tests::completion_signal_latches_on_completed_finish`,
126/// `tools::delegate::tests::completion_signal_ignores_non_completed_finish`,
127/// `tools::delegate::tests::delegate_refused_once_engineer_completed`.
128#[derive(Debug, Clone, Default)]
129pub struct EngineerCompletionSignal(Arc<AtomicBool>);
130
131impl EngineerCompletionSignal {
132 /// Build a fresh, un-latched signal for one run.
133 ///
134 /// Why: Each `execute_run_task` call needs its OWN signal — a prior run's
135 /// completion must never leak into a later run's report.
136 /// What: `Self::default()`.
137 /// Test: `completion_signal_latches_on_completed_finish`.
138 pub fn new() -> Self {
139 Self::default()
140 }
141
142 /// Latch the "engineer completed successfully" flag.
143 ///
144 /// Why: Called exactly once, the first time a delegation returns an explicit
145 /// successful `finish_task` completion.
146 /// What: Stores `true` with `SeqCst` (paired with `is_completed`'s load).
147 /// Test: `completion_signal_latches_on_completed_finish`.
148 pub(crate) fn mark_completed(&self) {
149 self.0.store(true, Ordering::SeqCst);
150 }
151
152 /// Whether a delegated engineer has already completed successfully.
153 ///
154 /// Why: [`DelegateToAgentTool::execute`] reads this to refuse a gratuitous
155 /// re-delegation, and `run_task::assemble_report` reads it to report
156 /// success instead of partial.
157 /// What: Loads the latched flag.
158 /// Test: `completion_signal_latches_on_completed_finish`.
159 pub fn is_completed(&self) -> bool {
160 self.0.load(Ordering::SeqCst)
161 }
162}
163
164/// Tool executor that delegates a task to a named sub-agent.
165///
166/// Why: Encapsulates the `delegate_to_agent` tool so the PM loop registers a
167/// single `Arc<dyn ToolExecutor>` rather than branching on the tool name inline.
168/// What: Holds an `AgentRunner` for subprocess/in-process dispatch, an optional
169/// `config_dir` for pre-flight agent name validation, and (#2683) an optional
170/// shared [`EngineerCompletionSignal`] used to refuse a re-delegation once the
171/// engineer has already reported a successful `finish_task` completion.
172/// Test: `unknown_agent_returns_helpful_error`, `known_agent_reaches_runner`,
173/// `no_config_dir_skips_validation`, `delegate_refused_once_engineer_completed`.
174pub struct DelegateToAgentTool {
175 runner: Arc<dyn AgentRunner>,
176 /// Directory holding `<agent>.md` files. When `Some`, `execute()` rejects
177 /// calls whose `agent_name` does not have a matching `.md`. When `None`,
178 /// validation is skipped (legacy / test mode).
179 config_dir: Option<PathBuf>,
180 /// Shared, run-scoped completion latch (#2683). When `Some` and already
181 /// latched, `execute()` refuses further delegation with a recoverable error
182 /// that nudges the PM to call `finish_task`. When `None` (the default /
183 /// legacy path), the refusal behaviour is disabled entirely.
184 completion_signal: Option<EngineerCompletionSignal>,
185}
186
187impl DelegateToAgentTool {
188 /// Construct with an injected `AgentRunner`.
189 ///
190 /// Why: Lets tests substitute an in-process mock runner without touching
191 /// production subprocess code.
192 /// What: Stores `runner`; no pre-flight name validation until `with_config_dir`
193 /// is also called.
194 /// Test: `DelegateToAgentTool::new(Arc::new(MockRunner))` compiles and
195 /// yields a tool whose `name()` is `delegate_to_agent`.
196 pub fn new(runner: Arc<dyn AgentRunner>) -> Self {
197 Self {
198 runner,
199 config_dir: None,
200 completion_signal: None,
201 }
202 }
203
204 /// Attach an agent config directory for pre-flight `agent_name` validation.
205 ///
206 /// Why: When the LLM hallucinates an agent name, spawning the subprocess
207 /// fails with a generic IO error. Validating up front returns a structured
208 /// `ToolResult::err` listing available agents so the LLM can self-correct.
209 /// What: Stores `dir`. Files matching `<dir>/<agent_name>.md` are
210 /// considered valid. Missing dir is treated as "no agents available".
211 /// Test: `unknown_agent_returns_helpful_error`.
212 pub fn with_config_dir(mut self, dir: PathBuf) -> Self {
213 self.config_dir = Some(dir);
214 self
215 }
216
217 /// Attach a shared [`EngineerCompletionSignal`] so a re-delegation after a
218 /// successful engineer completion is refused (#2683).
219 ///
220 /// Why: Once the delegated engineer has reported an explicit successful
221 /// `finish_task` completion, any further `delegate_to_agent` call is the
222 /// gratuitous post-finish re-delegation that mislabels a complete run as
223 /// `partial`; refusing it (and nudging the PM to `finish_task` instead) is
224 /// the "do not re-delegate once the finish gate is satisfied" half of the
225 /// fix. `run_task::execute_run_task` shares the SAME signal instance with
226 /// `assemble_report`.
227 /// What: Builder-style setter; returns `self` for chaining. When unset (the
228 /// default), the refusal behaviour is disabled and this tool behaves
229 /// exactly as before. (#2857) Every refusal fired via this signal emits a
230 /// `tracing::warn!` — the refusal silently changes the run's outcome (a
231 /// delegation attempt the model made is dropped without ever invoking the
232 /// runner), so it must be diagnosable from stderr alone, not just from the
233 /// tool-facing error text.
234 /// Test: `delegate_refused_once_engineer_completed`, `delegate_refusal_logs_warn`.
235 pub fn with_completion_signal(mut self, signal: EngineerCompletionSignal) -> Self {
236 self.completion_signal = Some(signal);
237 self
238 }
239
240 /// List agent names discoverable in `config_dir`, disk ∪ embedded
241 /// (#3046), if any.
242 ///
243 /// Why: Builds the "available agents" hint in error messages so the LLM
244 /// gets immediate, structured feedback when it invents a name. Reuses
245 /// `agents::available_agent_names` (rather than re-implementing its own
246 /// dir scan) so this hint, the actual load path
247 /// (`crate::agents::resolve_agent`), and the pre-flight gate
248 /// (`crate::runner::agent_config_exists`) can never independently drift
249 /// on which agents are real — before #3046 this hint only ever named
250 /// disk agents, so on a fresh project with no `.claude/agents/` it named
251 /// NONE even though the 31-agent embedded roster was dispatchable.
252 /// What: Delegates to `crate::agents::available_agent_names`, which
253 /// already returns disk ∪ embedded names, sorted and deduped. Returns
254 /// `None` when no `config_dir` was attached.
255 /// Test: Indirect via `unknown_agent_returns_helpful_error`.
256 fn available_agents(&self) -> Option<Vec<String>> {
257 let dir = self.config_dir.as_ref()?;
258 Some(crate::agents::available_agent_names(dir))
259 }
260}
261
262#[async_trait]
263impl ToolExecutor for DelegateToAgentTool {
264 fn name(&self) -> &str {
265 "delegate_to_agent"
266 }
267
268 fn schema(&self) -> Value {
269 json!({
270 "type": "function",
271 "function": {
272 "name": "delegate_to_agent",
273 "description": "Delegate a task to a specialized sub-agent. Use this for any implementation work (writing code, running analysis, etc.). The sub-agent will be spawned and its result returned to you. NOTE: agent_name must be an actual sub-agent (e.g. 'engineer', 'python-engineer', 'qa-agent'); native tools like search_code, web_search are NOT agent names — call them directly.",
274 "parameters": {
275 "type": "object",
276 "properties": {
277 "agent_name": {
278 "type": "string",
279 "description": "Short name of the sub-agent. Must match an existing agent config; native tools are not agent names."
280 },
281 "task": {
282 "type": "string",
283 "description": "Concrete task description for the sub-agent."
284 }
285 },
286 "required": ["agent_name", "task"],
287 "additionalProperties": false
288 }
289 }
290 })
291 }
292
293 async fn execute(&self, args: Value) -> ToolResult {
294 // #2683: once the delegated engineer has already reported a successful
295 // `finish_task` completion, refuse any further delegation BEFORE
296 // parsing/validating args or invoking the runner. This is the "do not
297 // re-delegate once the finish gate is satisfied" half of the fix: the
298 // deliverable is on disk and the task is done, so a re-verify round is
299 // gratuitous — nudge the PM to `finish_task` instead of spawning
300 // another engineer loop that can only end the run mid-round and
301 // mislabel it `partial`. Recoverable (not fatal) so the PM's loop
302 // continues and can act on the guidance.
303 if let Some(signal) = &self.completion_signal
304 && signal.is_completed()
305 {
306 tracing::warn!(
307 "delegate_to_agent refused (#2683 completion latch): the delegated engineer \
308 already reported a successful finish_task completion for this run — refusing \
309 further delegation without invoking the runner"
310 );
311 return ToolResult::err(
312 "delegate_to_agent refused: the delegated engineer already reported a \
313 successful completion (finish_task with status=completed) for this run. \
314 The deliverable is on disk and the task is done — do NOT re-delegate to \
315 re-verify. Call finish_task now to report the result.",
316 );
317 }
318
319 let Some(agent_name) = args.get("agent_name").and_then(Value::as_str) else {
320 return ToolResult::err("delegate_to_agent: missing 'agent_name'");
321 };
322 let Some(task) = args.get("task").and_then(Value::as_str) else {
323 return ToolResult::err("delegate_to_agent: missing 'task'");
324 };
325
326 // Guard against path traversal: the LLM supplies agent_name which is
327 // joined into a filesystem path. Reject any name that is not strictly
328 // [a-zA-Z0-9_-] before the path join so a crafted value like
329 // "../../etc/passwd" cannot escape the agents config directory.
330 // A namespaced `<plugin>:<name>` plugin agent dispatch name (#3539)
331 // is checked FIRST via `plugins::is_valid_namespaced_name` — exactly
332 // two `[a-z0-9-]+`-charset segments, which is itself the traversal
333 // guard for a plugin agent's path (issue #3547 HIGH 4): previously
334 // ANY name containing `:` was rejected here, so a plugin agent could
335 // never reach the runner even though `agents::resolve_agent` already
336 // resolved it.
337 let is_valid_plain_name = !agent_name.is_empty()
338 && agent_name
339 .chars()
340 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
341 if !is_valid_plain_name && !crate::plugins::is_valid_namespaced_name(agent_name) {
342 return ToolResult::err(format!(
343 "Invalid agent name '{agent_name}': agent names must be non-empty and contain \
344 only [a-zA-Z0-9_-], or be a namespaced <plugin>:<name> where both segments \
345 are [a-z0-9-]+ (<= 64 chars)"
346 ));
347 }
348
349 // Pre-flight validation: if a config_dir was attached, verify the agent
350 // config exists before spawning. Converts a generic IO error into a
351 // structured tool error the LLM can act on. Reuses
352 // `runner::agent_config_exists` (the SAME `<dir>/<name>.md` rule the
353 // runner itself applies) rather than re-deriving the extension here.
354 if let Some(dir) = &self.config_dir
355 && !crate::runner::agent_config_exists(dir, agent_name)
356 {
357 let available = self.available_agents().unwrap_or_default();
358 let available_str = if available.is_empty() {
359 "(none discovered)".to_string()
360 } else {
361 available.join(", ")
362 };
363 return ToolResult::err(format!(
364 "Unknown agent '{agent_name}'. Available agents: {available_str}. \
365 Note: native tools (search_code, web_search, etc.) are NOT agent \
366 names — call them directly as tools instead of via delegate_to_agent."
367 ));
368 }
369
370 match self.runner.run(agent_name, task).await {
371 Ok(out) => {
372 // #2683: latch the run-scoped completion signal when the engineer
373 // terminated via an EXPLICIT successful `finish_task` — the
374 // authoritative "task is genuinely done" signal both the refusal
375 // above and `run_task::assemble_report` key off. A `failed` /
376 // `cancelled` finish, or a plain no-tool-call stop, does NOT
377 // latch it: those leave re-delegation legitimately available.
378 self.mark_completion_if_finished(&out);
379 ToolResult::ok(out.content)
380 }
381 Err(e) => {
382 let hint = redelegation_hint(&e).unwrap_or("");
383 ToolResult::err(format!("sub-agent '{agent_name}' failed: {e:#}{hint}"))
384 }
385 }
386 }
387}
388
389impl DelegateToAgentTool {
390 /// Latch the shared completion signal iff `out` represents an explicit
391 /// successful `finish_task` completion (#2683).
392 ///
393 /// Why: Factored out of `execute` so the "what counts as a successful
394 /// completion" rule lives in one named place and is unit-testable.
395 /// What: No-op when no `completion_signal` is attached; otherwise latches it
396 /// only when `out.finish_status == Some(FinishStatus::Completed)`.
397 /// Test: `completion_signal_latches_on_completed_finish`,
398 /// `completion_signal_ignores_non_completed_finish`.
399 fn mark_completion_if_finished(&self, out: &AgentOutput) {
400 if let Some(signal) = &self.completion_signal
401 && out.finish_status == Some(FinishStatus::Completed)
402 {
403 signal.mark_completed();
404 }
405 }
406}
407
408// ── Tests ─────────────────────────────────────────────────────────────────────
409
410#[cfg(test)]
411#[path = "delegate_tests.rs"]
412mod tests;