Skip to main content

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.toml` 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;
34
35use async_trait::async_trait;
36use serde_json::{Value, json};
37
38use crate::agent_loop::AgentLoopError;
39use crate::runner::RunnerError;
40use crate::tools::traits::{AgentRunner, ToolExecutor, ToolResult};
41
42/// Detect whether an `AgentRunner` failure means the sub-agent's OWN attempt
43/// may have left partial work already on disk (turn cap, timeout,
44/// cancellation, or a retryable LLM/transport hiccup), as opposed to a hard
45/// failure (unknown agent, bad config) that leaves nothing to reuse.
46///
47/// Why: (bake-off L1 diagnosis) The PM only sees this failure as opaque error
48/// text; without a structured signal, its free-text re-delegation brief has no
49/// reliable reason to mention the sub-agent's partial progress, so the next
50/// delegated instance rebuilds from scratch and orphans correct prior work.
51/// Surfacing a fixed directive automatically — every time this specific
52/// failure shape occurs — makes "read existing files, then continue" the
53/// default recovery instead of something the PM must remember to ask for.
54/// (#2265) `AgentLoopError::Llm` — a recoverable Bedrock/transport error that
55/// aborts the engineer's sub-loop mid-session — is the DOMINANT failure mode
56/// observed in the bake-off transcripts, yet #2233 left it out of this match,
57/// so the reuse hint never fired for the most common case and every retry
58/// re-read PROBLEM.md from zero. It now gets the same hint: tool calls the
59/// engineer already dispatched before the failing `chat` call (e.g.
60/// `write_file`) already landed on disk even though `AgentLoopError::Llm`
61/// itself carries no `partial: Box<AgentOutput>` (unlike the three
62/// budget-abort variants) — there is real, on-disk work to reuse even though
63/// there is no partial transcript snapshot to point to.
64/// What: Downcasts `err` to [`RunnerError`] and matches `RunnerError::Loop`
65/// whose source is `AgentLoopError::TurnCapExceeded`, `Timeout`, `Cancelled`,
66/// (#2265) `Llm`, or (#2265 fix #5) `StoppedBySignal`. Returns `None` only
67/// for `UnknownAgent`/`ConfigLoad` — failures that never reached a sub-agent
68/// loop at all, so there is nothing on disk to reuse.
69/// Note: a delegated engineer's own sub-loop never actually attaches a stop
70/// signal today (only `run_task`'s PM loop does, via
71/// `AgentLoop::with_stop_signal`), so `StoppedBySignal` is unreachable from
72/// this call site in practice; it is included for exhaustiveness and to stay
73/// correct if that ever changes.
74/// Test: `redelegation_hint_present_on_turn_cap_exceeded`,
75/// `redelegation_hint_present_on_timeout`,
76/// `redelegation_hint_present_on_cancelled`,
77/// `redelegation_hint_present_on_llm_error`,
78/// `redelegation_hint_absent_on_unknown_agent`.
79pub(crate) fn redelegation_hint(err: &anyhow::Error) -> Option<&'static str> {
80    let RunnerError::Loop { source, .. } = err.downcast_ref::<RunnerError>()? else {
81        return None;
82    };
83    match source {
84        AgentLoopError::TurnCapExceeded { .. }
85        | AgentLoopError::Timeout { .. }
86        | AgentLoopError::Cancelled { .. }
87        | AgentLoopError::StoppedBySignal { .. }
88        | AgentLoopError::Llm(_) => Some(
89            "\n\nNOTE for re-delegation: the sub-agent's previous attempt did not reach a \
90             normal finish — it ran out of turns or time, was cancelled, or hit a \
91             transient LLM/transport error — NOT a task failure. It has likely already \
92             written real, partial progress to disk. Before delegating this task again: \
93             (1) inspect the project's current files to see what the sub-agent already \
94             produced, (2) instruct the next sub-agent to READ and CONTINUE/BUILD ON that \
95             existing work rather than rewriting it from scratch, and (3) consider a narrower \
96             follow-up task (or a higher turn budget) so it can finish what is already started \
97             instead of starting over.",
98        ),
99    }
100}
101
102/// Tool executor that delegates a task to a named sub-agent.
103///
104/// Why: Encapsulates the `delegate_to_agent` tool so the PM loop registers a
105/// single `Arc<dyn ToolExecutor>` rather than branching on the tool name inline.
106/// What: Holds an `AgentRunner` for subprocess/in-process dispatch and an
107/// optional `config_dir` for pre-flight agent name validation.
108/// Test: `unknown_agent_returns_helpful_error`, `known_agent_reaches_runner`,
109/// `no_config_dir_skips_validation`.
110pub struct DelegateToAgentTool {
111    runner: Arc<dyn AgentRunner>,
112    /// Directory holding `<agent>.toml` files. When `Some`, `execute()` rejects
113    /// calls whose `agent_name` does not have a matching TOML. When `None`,
114    /// validation is skipped (legacy / test mode).
115    config_dir: Option<PathBuf>,
116}
117
118impl DelegateToAgentTool {
119    /// Construct with an injected `AgentRunner`.
120    ///
121    /// Why: Lets tests substitute an in-process mock runner without touching
122    /// production subprocess code.
123    /// What: Stores `runner`; no pre-flight name validation until `with_config_dir`
124    /// is also called.
125    /// Test: `DelegateToAgentTool::new(Arc::new(MockRunner))` compiles and
126    /// yields a tool whose `name()` is `delegate_to_agent`.
127    pub fn new(runner: Arc<dyn AgentRunner>) -> Self {
128        Self {
129            runner,
130            config_dir: None,
131        }
132    }
133
134    /// Attach an agent config directory for pre-flight `agent_name` validation.
135    ///
136    /// Why: When the LLM hallucinates an agent name, spawning the subprocess
137    /// fails with a generic IO error. Validating up front returns a structured
138    /// `ToolResult::err` listing available agents so the LLM can self-correct.
139    /// What: Stores `dir`. Files matching `<dir>/<agent_name>.toml` are
140    /// considered valid. Missing dir is treated as "no agents available".
141    /// Test: `unknown_agent_returns_helpful_error`.
142    pub fn with_config_dir(mut self, dir: PathBuf) -> Self {
143        self.config_dir = Some(dir);
144        self
145    }
146
147    /// List agent names discoverable in `config_dir`, if any.
148    ///
149    /// Why: Builds the "available agents" hint in error messages so the LLM
150    /// gets immediate, structured feedback when it invents a name.
151    /// What: Reads `<config_dir>/*.toml` and returns each file stem. Returns
152    /// `None` when no `config_dir` was attached.
153    /// Test: Indirect via `unknown_agent_returns_helpful_error`.
154    fn available_agents(&self) -> Option<Vec<String>> {
155        let dir = self.config_dir.as_ref()?;
156        let entries = std::fs::read_dir(dir).ok()?;
157        let mut names: Vec<String> = entries
158            .flatten()
159            .filter_map(|e| {
160                let p = e.path();
161                if p.extension().and_then(|x| x.to_str()) == Some("toml") {
162                    p.file_stem()
163                        .and_then(|s| s.to_str())
164                        .map(|s| s.to_string())
165                } else {
166                    None
167                }
168            })
169            .collect();
170        names.sort();
171        Some(names)
172    }
173}
174
175#[async_trait]
176impl ToolExecutor for DelegateToAgentTool {
177    fn name(&self) -> &str {
178        "delegate_to_agent"
179    }
180
181    fn schema(&self) -> Value {
182        json!({
183            "type": "function",
184            "function": {
185                "name": "delegate_to_agent",
186                "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.",
187                "parameters": {
188                    "type": "object",
189                    "properties": {
190                        "agent_name": {
191                            "type": "string",
192                            "description": "Short name of the sub-agent. Must match an existing agent config; native tools are not agent names."
193                        },
194                        "task": {
195                            "type": "string",
196                            "description": "Concrete task description for the sub-agent."
197                        }
198                    },
199                    "required": ["agent_name", "task"],
200                    "additionalProperties": false
201                }
202            }
203        })
204    }
205
206    async fn execute(&self, args: Value) -> ToolResult {
207        let Some(agent_name) = args.get("agent_name").and_then(Value::as_str) else {
208            return ToolResult::err("delegate_to_agent: missing 'agent_name'");
209        };
210        let Some(task) = args.get("task").and_then(Value::as_str) else {
211            return ToolResult::err("delegate_to_agent: missing 'task'");
212        };
213
214        // Guard against path traversal: the LLM supplies agent_name which is
215        // joined into a filesystem path. Reject any name that is not strictly
216        // [a-zA-Z0-9_-] before the path join so a crafted value like
217        // "../../etc/passwd" cannot escape the agents config directory.
218        if agent_name.is_empty()
219            || !agent_name
220                .chars()
221                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
222        {
223            return ToolResult::err(format!(
224                "Invalid agent name '{agent_name}': \
225                 agent names must be non-empty and contain only [a-zA-Z0-9_-]"
226            ));
227        }
228
229        // Pre-flight validation: if a config_dir was attached, verify the agent
230        // config exists before spawning. Converts a generic IO error into a
231        // structured tool error the LLM can act on.
232        if let Some(dir) = &self.config_dir {
233            let agent_toml = dir.join(format!("{agent_name}.toml"));
234            if !agent_toml.exists() {
235                let available = self.available_agents().unwrap_or_default();
236                let available_str = if available.is_empty() {
237                    "(none discovered)".to_string()
238                } else {
239                    available.join(", ")
240                };
241                return ToolResult::err(format!(
242                    "Unknown agent '{agent_name}'. Available agents: {available_str}. \
243                     Note: native tools (search_code, web_search, etc.) are NOT agent \
244                     names — call them directly as tools instead of via delegate_to_agent."
245                ));
246            }
247        }
248
249        match self.runner.run(agent_name, task).await {
250            Ok(out) => ToolResult::ok(out.content),
251            Err(e) => {
252                let hint = redelegation_hint(&e).unwrap_or("");
253                ToolResult::err(format!("sub-agent '{agent_name}' failed: {e:#}{hint}"))
254            }
255        }
256    }
257}
258
259// ── Tests ─────────────────────────────────────────────────────────────────────
260
261#[cfg(test)]
262mod tests {
263    use std::sync::Arc;
264
265    use anyhow::Result;
266    use async_trait::async_trait;
267    use serde_json::json;
268
269    use super::{DelegateToAgentTool, redelegation_hint};
270    use crate::agent_loop::AgentLoopError;
271    use crate::llm::LlmError;
272    use crate::runner::RunnerError;
273    use crate::tools::traits::{AgentOutput, AgentRunner, ToolExecutor};
274
275    /// Recording mock runner.
276    ///
277    /// Why: Tests need to verify the runner was (or was not) invoked.
278    /// What: Records `(agent_name, task)` pairs in a Mutex-guarded Vec.
279    /// Test: `known_agent_reaches_runner`, `no_config_dir_skips_validation`.
280    struct RecordingRunner {
281        invoked: std::sync::Mutex<Vec<(String, String)>>,
282    }
283
284    #[async_trait]
285    impl AgentRunner for RecordingRunner {
286        async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
287            self.invoked
288                .lock()
289                .expect("lock poisoned")
290                .push((agent_name.to_string(), task.to_string()));
291            Ok(AgentOutput::from_content("ok"))
292        }
293    }
294
295    /// An unknown agent name returns a structured error listing available agents,
296    /// and the runner is NOT invoked.
297    ///
298    /// Why: Guards against hallucinated agent names causing confusing IO errors.
299    /// What: Calls `execute({"agent_name":"ghost",...})` with a tempdir
300    /// containing only `engineer.toml`; expects error with "ghost" and "engineer".
301    /// Test: This test.
302    #[tokio::test]
303    async fn unknown_agent_returns_helpful_error() {
304        let tmp = tempfile::tempdir().expect("tempdir");
305        std::fs::write(
306            tmp.path().join("engineer.toml"),
307            "[agent]\nname = \"engineer\"\n",
308        )
309        .expect("write");
310        std::fs::write(
311            tmp.path().join("qa-agent.toml"),
312            "[agent]\nname = \"qa-agent\"\n",
313        )
314        .expect("write");
315
316        let runner = Arc::new(RecordingRunner {
317            invoked: std::sync::Mutex::new(Vec::new()),
318        });
319        let tool =
320            DelegateToAgentTool::new(runner.clone()).with_config_dir(tmp.path().to_path_buf());
321
322        let result = tool
323            .execute(json!({"agent_name": "ghost", "task": "do something"}))
324            .await;
325
326        assert!(result.is_error(), "must reject unknown agent");
327        let msg = result.content();
328        assert!(
329            msg.contains("Unknown agent 'ghost'"),
330            "error must name the unknown agent, got: {msg}"
331        );
332        assert!(
333            msg.contains("engineer") && msg.contains("qa-agent"),
334            "error must list available agents, got: {msg}"
335        );
336        assert!(
337            msg.contains("native tools"),
338            "error must clarify native-vs-agent, got: {msg}"
339        );
340        assert!(
341            runner.invoked.lock().expect("lock").is_empty(),
342            "runner must not be called when validation fails"
343        );
344    }
345
346    /// A valid agent name passes validation and reaches the runner.
347    ///
348    /// Why: Verify the happy-path dispatch contract.
349    /// What: Register `engineer.toml`, dispatch with `agent_name="engineer"`.
350    /// Test: This test.
351    #[tokio::test]
352    async fn known_agent_reaches_runner() {
353        let tmp = tempfile::tempdir().expect("tempdir");
354        std::fs::write(
355            tmp.path().join("engineer.toml"),
356            "[agent]\nname = \"engineer\"\n",
357        )
358        .expect("write");
359
360        let runner = Arc::new(RecordingRunner {
361            invoked: std::sync::Mutex::new(Vec::new()),
362        });
363        let tool =
364            DelegateToAgentTool::new(runner.clone()).with_config_dir(tmp.path().to_path_buf());
365
366        let result = tool
367            .execute(json!({"agent_name": "engineer", "task": "do the thing"}))
368            .await;
369
370        assert!(
371            !result.is_error(),
372            "valid agent should succeed: {}",
373            result.content()
374        );
375        let invoked = runner.invoked.lock().expect("lock");
376        assert_eq!(invoked.len(), 1, "runner should be called exactly once");
377        assert_eq!(invoked[0].0, "engineer");
378    }
379
380    /// Without `with_config_dir`, validation is skipped — the runner is invoked.
381    ///
382    /// Why: Preserves backward compatibility with callers that don't need
383    /// pre-flight validation (e.g. integration tests).
384    /// What: Construct tool without config_dir; any agent name reaches the runner.
385    /// Test: This test.
386    #[tokio::test]
387    async fn no_config_dir_skips_validation() {
388        let runner = Arc::new(RecordingRunner {
389            invoked: std::sync::Mutex::new(Vec::new()),
390        });
391        let tool = DelegateToAgentTool::new(runner.clone());
392
393        let result = tool
394            .execute(json!({"agent_name": "anything-goes", "task": "do it"}))
395            .await;
396
397        assert!(!result.is_error(), "legacy mode should bypass validation");
398        assert_eq!(runner.invoked.lock().expect("lock").len(), 1);
399    }
400
401    /// Missing `agent_name` field returns a structured error.
402    ///
403    /// Why: Guard against malformed LLM function call arguments.
404    /// What: `execute({})` without `agent_name` key.
405    /// Test: This test.
406    #[tokio::test]
407    async fn missing_agent_name_returns_error() {
408        let runner = Arc::new(RecordingRunner {
409            invoked: std::sync::Mutex::new(Vec::new()),
410        });
411        let tool = DelegateToAgentTool::new(runner);
412        let result = tool.execute(json!({"task": "something"})).await;
413        assert!(result.is_error());
414        assert!(result.content().contains("missing 'agent_name'"));
415    }
416
417    /// A path-traversal agent name is rejected before any filesystem access.
418    ///
419    /// Why: The LLM supplies `agent_name` which is joined into a filesystem path.
420    /// A crafted name like `../../etc/passwd` must be caught before the join to
421    /// prevent escaping the agents config directory.
422    /// What: Calls `execute` with a traversal string; asserts error and runner
423    /// not invoked.
424    /// Test: This test.
425    #[tokio::test]
426    async fn path_traversal_agent_name_is_rejected() {
427        let runner = Arc::new(RecordingRunner {
428            invoked: std::sync::Mutex::new(Vec::new()),
429        });
430        // No config_dir — traversal guard fires before config check.
431        let tool = DelegateToAgentTool::new(runner.clone());
432
433        for bad_name in &[
434            "../../etc/passwd",
435            "../sibling",
436            "agent/sub",
437            "agent name",
438            "",
439        ] {
440            let result = tool
441                .execute(json!({"agent_name": bad_name, "task": "do it"}))
442                .await;
443            assert!(
444                result.is_error(),
445                "traversal/invalid name '{bad_name}' must be rejected"
446            );
447            assert!(
448                result.content().contains("Invalid agent name"),
449                "error must describe the problem, got: {}",
450                result.content()
451            );
452        }
453        assert!(
454            runner.invoked.lock().expect("lock").is_empty(),
455            "runner must never be called for invalid names"
456        );
457    }
458
459    /// A valid agent name passes the sanitisation guard and reaches the runner.
460    ///
461    /// Why: Confirms the allowlist does not over-reject legitimate names.
462    /// What: `execute({"agent_name":"engineer",...})` without config_dir; runner
463    /// is called once.
464    /// Test: This test.
465    #[tokio::test]
466    async fn valid_agent_name_passes_sanitization() {
467        let runner = Arc::new(RecordingRunner {
468            invoked: std::sync::Mutex::new(Vec::new()),
469        });
470        let tool = DelegateToAgentTool::new(runner.clone());
471
472        for good_name in &["engineer", "qa-agent", "python_engineer", "rust-2024"] {
473            let result = tool
474                .execute(json!({"agent_name": good_name, "task": "do it"}))
475                .await;
476            assert!(
477                !result.is_error(),
478                "valid name '{good_name}' must be accepted: {}",
479                result.content()
480            );
481        }
482        assert_eq!(
483            runner.invoked.lock().expect("lock").len(),
484            4,
485            "runner must be called for each valid name"
486        );
487    }
488
489    /// Mock runner that always fails with a caller-supplied error.
490    ///
491    /// Why: `redelegation_hint` tests need to control exactly which
492    /// `RunnerError`/`AgentLoopError` shape `execute()` observes, without
493    /// driving a real `AgentLoop`.
494    /// What: `run` always returns `Err` built from the stored `anyhow::Error`
495    /// factory (a `Fn` so each call gets a fresh error, since `anyhow::Error`
496    /// is not `Clone`).
497    /// Test: `redelegation_hint_present_on_turn_cap_exceeded` and siblings.
498    struct FailingRunner<F: Fn() -> anyhow::Error + Send + Sync> {
499        make_err: F,
500    }
501
502    #[async_trait]
503    impl<F: Fn() -> anyhow::Error + Send + Sync> AgentRunner for FailingRunner<F> {
504        async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
505            Err((self.make_err)())
506        }
507    }
508
509    /// A `TurnCapExceeded` sub-agent failure carries the reuse/continue
510    /// directive in the tool's error text.
511    ///
512    /// Why: This is the core bake-off L1 fix — the PM must see an automatic,
513    /// structured instruction to inspect and reuse partial work instead of
514    /// relying on its own free text remembering to ask for it.
515    /// What: `FailingRunner` returns `RunnerError::Loop` wrapping
516    /// `AgentLoopError::TurnCapExceeded`; assert the rendered error mentions
517    /// both re-delegation and reading/continuing existing work.
518    /// Test: this test.
519    #[tokio::test]
520    async fn redelegation_hint_present_on_turn_cap_exceeded() {
521        let runner = Arc::new(FailingRunner {
522            make_err: || {
523                anyhow::Error::from(RunnerError::Loop {
524                    name: "engineer".to_string(),
525                    source: AgentLoopError::TurnCapExceeded {
526                        max_turns: 8,
527                        partial: Box::new(AgentOutput::from_content("partial work")),
528                    },
529                })
530            },
531        });
532        let tool = DelegateToAgentTool::new(runner);
533
534        let result = tool
535            .execute(json!({"agent_name": "engineer", "task": "build the package"}))
536            .await;
537
538        assert!(result.is_error());
539        let msg = result.content();
540        assert!(
541            msg.contains("READ and CONTINUE"),
542            "must instruct the PM to reuse existing work, got: {msg}"
543        );
544        assert!(
545            msg.contains("already written real, partial progress"),
546            "must explain why re-delegation should not start over, got: {msg}"
547        );
548    }
549
550    /// A `Timeout` sub-agent failure gets the same reuse/continue directive.
551    ///
552    /// Why: A wall-clock timeout carries partial work exactly like a turn-cap
553    /// abort (per `AgentLoopError`'s own docs); the hint must not be
554    /// TurnCapExceeded-specific.
555    /// What: `FailingRunner` returns `RunnerError::Loop` wrapping
556    /// `AgentLoopError::Timeout`.
557    /// Test: this test.
558    #[tokio::test]
559    async fn redelegation_hint_present_on_timeout() {
560        let runner = Arc::new(FailingRunner {
561            make_err: || {
562                anyhow::Error::from(RunnerError::Loop {
563                    name: "engineer".to_string(),
564                    source: AgentLoopError::Timeout {
565                        timeout_secs: 120,
566                        partial: Box::new(AgentOutput::from_content("partial work")),
567                    },
568                })
569            },
570        });
571        let tool = DelegateToAgentTool::new(runner);
572
573        let result = tool
574            .execute(json!({"agent_name": "engineer", "task": "build the package"}))
575            .await;
576
577        assert!(result.is_error());
578        assert!(result.content().contains("READ and CONTINUE"));
579    }
580
581    /// A `Cancelled` sub-agent failure gets the same reuse/continue directive.
582    ///
583    /// What: `FailingRunner` returns `RunnerError::Loop` wrapping
584    /// `AgentLoopError::Cancelled`.
585    /// Test: this test.
586    #[tokio::test]
587    async fn redelegation_hint_present_on_cancelled() {
588        let runner = Arc::new(FailingRunner {
589            make_err: || {
590                anyhow::Error::from(RunnerError::Loop {
591                    name: "engineer".to_string(),
592                    source: AgentLoopError::Cancelled {
593                        partial: Box::new(AgentOutput::from_content("partial work")),
594                    },
595                })
596            },
597        });
598        let tool = DelegateToAgentTool::new(runner);
599
600        let result = tool
601            .execute(json!({"agent_name": "engineer", "task": "build the package"}))
602            .await;
603
604        assert!(result.is_error());
605        assert!(result.content().contains("READ and CONTINUE"));
606    }
607
608    /// An `UnknownAgent` runner failure gets NO reuse directive — there is no
609    /// partial work to reuse when the agent config never resolved.
610    ///
611    /// Why: The hint must not fire indiscriminately on every failure; guard
612    /// the negative case.
613    /// What: `FailingRunner` returns `RunnerError::UnknownAgent`.
614    /// Test: this test.
615    #[tokio::test]
616    async fn redelegation_hint_absent_on_unknown_agent() {
617        let runner = Arc::new(FailingRunner {
618            make_err: || {
619                anyhow::Error::from(RunnerError::UnknownAgent {
620                    name: "ghost".to_string(),
621                    dir: std::path::PathBuf::from("/agents"),
622                })
623            },
624        });
625        let tool = DelegateToAgentTool::new(runner);
626
627        let result = tool
628            .execute(json!({"agent_name": "ghost", "task": "build the package"}))
629            .await;
630
631        assert!(result.is_error());
632        assert!(
633            !result.content().contains("READ and CONTINUE"),
634            "no partial work exists for an unresolved agent config, got: {}",
635            result.content()
636        );
637    }
638
639    /// A plain LLM/transport failure gets the SAME reuse/continue directive
640    /// (#2265 fix #2: this is the dominant bake-off failure mode, previously
641    /// excluded from the hint).
642    ///
643    /// Why: A recoverable Bedrock/transport error aborting the engineer's
644    /// sub-loop is the dominant failure mode observed in the bake-off
645    /// transcripts; the reuse hint must fire here too so re-delegation checks
646    /// for and continues from files already on disk instead of restarting
647    /// exploration from scratch.
648    /// What: `FailingRunner` returns `RunnerError::Loop` wrapping
649    /// `AgentLoopError::Llm`; assert the hint is present.
650    /// Test: this test.
651    #[tokio::test]
652    async fn redelegation_hint_present_on_llm_error() {
653        let runner = Arc::new(FailingRunner {
654            make_err: || {
655                anyhow::Error::from(RunnerError::Loop {
656                    name: "engineer".to_string(),
657                    source: AgentLoopError::Llm(LlmError::ApiError {
658                        status: 500,
659                        body: "internal error".to_string(),
660                    }),
661                })
662            },
663        });
664        let tool = DelegateToAgentTool::new(runner);
665
666        let result = tool
667            .execute(json!({"agent_name": "engineer", "task": "build the package"}))
668            .await;
669
670        assert!(result.is_error());
671        assert!(
672            result.content().contains("READ and CONTINUE"),
673            "an LLM/transport error must ALSO carry the reuse directive (#2265), got: {}",
674            result.content()
675        );
676    }
677
678    /// `redelegation_hint` itself (unit-level, not through the tool) returns
679    /// `Some` for `AgentLoopError::Llm` (#2265 fix #2).
680    ///
681    /// Why: The tool-level test above proves the end-to-end wiring; this test
682    /// pins the specific function contract directly, matching the task's
683    /// required "redelegation_hint(AgentLoopError::Llm) now returns
684    /// Some(<reuse hint>)" assertion.
685    /// What: Builds a `RunnerError::Loop` wrapping `AgentLoopError::Llm`,
686    /// calls `redelegation_hint` directly, asserts `Some`.
687    /// Test: this test.
688    #[test]
689    fn redelegation_hint_fn_returns_some_for_llm_error() {
690        let err = anyhow::Error::from(RunnerError::Loop {
691            name: "engineer".to_string(),
692            source: AgentLoopError::Llm(LlmError::ApiError {
693                status: 503,
694                body: "bedrock throttled".to_string(),
695            }),
696        });
697        assert!(
698            redelegation_hint(&err).is_some(),
699            "redelegation_hint must return Some for AgentLoopError::Llm (#2265)"
700        );
701    }
702}