trusty_code/run_task/redelegation.rs
1//! Re-delegation cap: bounds total engineer delegation attempts per run (#2265).
2//!
3//! Why: (#2265, completes #2233) Before this module, the ONLY ceiling on how
4//! many times the PM could re-delegate a failing engineer task was the PM's
5//! OWN `AgentLoopConfig::default().max_turns` (8) — because #2233 raised the
6//! delegated ENGINEER's turn budget to 40 without raising or decoupling the
7//! PM's, each blind PM-driven retry could burn up to 40 engineer turns while
8//! the PM itself had only 8 total attempts to notice, react, and finish. That
9//! asymmetry produced non-deterministic failure storms (session turn counts
10//! blowing up from ~40 to ~111) that hit the PM's turn cap and were reported
11//! as an opaque `run_failure`, even when a fully working solution already sat
12//! on disk from an earlier attempt. This module makes an explicit,
13//! independent cap ([`MAX_REDELEGATIONS`]) the thing that governs retry
14//! count, and — critically — enforces it INSIDE a single `delegate_to_agent`
15//! tool dispatch via [`RedelegatingRunner`], so retries never consume
16//! additional PM turns at all (the "decouple" design chosen for fix #3: see
17//! `run_task::mod`'s `build_engineer_runner` docs for why this was preferred
18//! over raising the PM's `max_turns`).
19//! What: [`RedelegationCapSignal`] is a small `Arc`-shared attempt
20//! counter/flag, constructed once per `execute_run_task` call and threaded
21//! into both [`RedelegatingRunner`] (which increments it and retries) and
22//! `assemble_report` (which reads `is_cap_reached()` to produce a clean
23//! terminal report instead of riding on a coincidental PM-turn-cap failure).
24//! [`RedelegatingRunner`] wraps the engineer `AgentRunner`: on a failure whose
25//! [`crate::tools::delegate::redelegation_hint`] returns `Some` (partial work
26//! may exist — turn cap, timeout, cancellation, or a retryable LLM/transport
27//! error, per that function's #2265-updated docs), it retries the SAME
28//! engineer agent with the task text augmented by the reuse hint, up to
29//! [`MAX_REDELEGATIONS`] total attempts (shared across every
30//! `delegate_to_agent` call in the run, not reset per call) before giving up
31//! with a clean, quoted "re-delegation limit reached" error. A non-retryable
32//! failure (unknown agent, bad config) propagates immediately without
33//! consuming the cap.
34//! Test: `redelegating_runner_retries_on_llm_error_then_succeeds`,
35//! `redelegating_runner_stops_at_cap_and_marks_signal`,
36//! `redelegating_runner_propagates_non_retryable_errors_immediately`,
37//! `cap_reached_message_names_the_project_path`.
38
39use std::path::PathBuf;
40use std::sync::Arc;
41use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
42
43use anyhow::Result;
44use async_trait::async_trait;
45
46use crate::tools::delegate::redelegation_hint;
47use crate::tools::{AgentOutput, AgentRunner, RunContext};
48
49/// Maximum total engineer delegation attempts for a single `execute_run_task`
50/// run, shared across every `delegate_to_agent` call the PM makes (#2265).
51///
52/// Why: This — not the PM's own turn budget — is the ceiling on retry count
53/// going forward. 3 total attempts (1 initial + up to 2 reuse-aware retries)
54/// is deliberately modest: each retry now costs up to 40 engineer turns
55/// (#2233's raised default), so an unbounded or generous cap here would
56/// reintroduce the same runaway-cost failure mode this fix closes.
57/// What: Checked BEFORE every engineer invocation in
58/// [`RedelegatingRunner::run_with_retries`]; once the shared attempt count
59/// exceeds this value, no further engineer invocation happens at all.
60/// Test: `redelegating_runner_stops_at_cap_and_marks_signal`.
61pub const MAX_REDELEGATIONS: u32 = 3;
62
63/// Shared, run-scoped state behind [`RedelegationCapSignal`].
64///
65/// Why: Kept as a private inner type so the public handle stays a cheap,
66/// `Clone`-able `Arc` wrapper — see [`RedelegationCapSignal`]'s own docs.
67/// What: `attempts` counts every engineer invocation attempted across the
68/// whole run; `cap_reached` latches `true` the first time an attempt would
69/// exceed [`MAX_REDELEGATIONS`].
70/// Test: Exercised indirectly through `RedelegationCapSignal`'s own tests.
71#[derive(Debug, Default)]
72struct RedelegationCapState {
73 attempts: AtomicU32,
74 cap_reached: AtomicBool,
75}
76
77/// Shared signal tracking total re-delegation attempts across one run (#2265).
78///
79/// Why: [`RedelegatingRunner`] and `run_task::assemble_report` are different
80/// call sites that both need to observe the SAME attempt count / cap state —
81/// the runner to enforce the cap, the report assembler to recognise a
82/// cap-triggered terminal state even when the PM's own loop error doesn't
83/// literally say so (e.g. the PM's NEXT turn separately exhausts its own
84/// budget after seeing the cap-reached tool error). An `Arc`-wrapped atomic
85/// pair is the simplest thing that is `Send + Sync` and cheap to clone into
86/// both places.
87/// What: `new()` starts at zero attempts, cap not reached. `is_cap_reached()`
88/// and `attempts()` are read-only accessors for `assemble_report`;
89/// `record_attempt`/`mark_cap_reached` are private, called only by
90/// [`RedelegatingRunner`].
91/// Test: `redelegating_runner_stops_at_cap_and_marks_signal`.
92#[derive(Debug, Clone, Default)]
93pub struct RedelegationCapSignal(Arc<RedelegationCapState>);
94
95impl RedelegationCapSignal {
96 /// Build a fresh signal with zero recorded attempts.
97 ///
98 /// Why: Each `execute_run_task` call needs its OWN signal — attempts must
99 /// never leak across independent runs.
100 /// What: `Self::default()`.
101 /// Test: `redelegating_runner_retries_on_llm_error_then_succeeds`.
102 pub fn new() -> Self {
103 Self::default()
104 }
105
106 /// Record one more attempt and return the new total.
107 ///
108 /// Why: The runner must check the POST-increment total against the cap
109 /// atomically with recording it, so two attempts can never both observe
110 /// "one under the cap" and both proceed.
111 /// What: `fetch_add(1) + 1`.
112 /// Test: `redelegating_runner_stops_at_cap_and_marks_signal`.
113 fn record_attempt(&self) -> u32 {
114 self.0.attempts.fetch_add(1, Ordering::SeqCst) + 1
115 }
116
117 /// Latch the cap-reached flag.
118 ///
119 /// Why: Called exactly once, the moment an attempt would exceed
120 /// [`MAX_REDELEGATIONS`] — this is the signal `assemble_report` checks.
121 /// What: Stores `true`.
122 /// Test: `redelegating_runner_stops_at_cap_and_marks_signal`.
123 fn mark_cap_reached(&self) {
124 self.0.cap_reached.store(true, Ordering::SeqCst);
125 }
126
127 /// Whether the re-delegation cap was hit during this run.
128 ///
129 /// Why: `assemble_report` uses this to distinguish a cap-triggered
130 /// terminal state from an unrelated PM-loop error.
131 /// What: Reads the latched flag.
132 /// Test: `redelegating_runner_stops_at_cap_and_marks_signal`.
133 pub fn is_cap_reached(&self) -> bool {
134 self.0.cap_reached.load(Ordering::SeqCst)
135 }
136
137 /// Total engineer attempts recorded so far.
138 ///
139 /// Why: Surfaced in the clean terminal report's message so an operator
140 /// knows exactly how many tries were made.
141 /// What: Reads the atomic counter.
142 /// Test: `redelegating_runner_stops_at_cap_and_marks_signal`.
143 pub fn attempts(&self) -> u32 {
144 self.0.attempts.load(Ordering::SeqCst)
145 }
146}
147
148/// `AgentRunner` decorator that internally retries a failed engineer
149/// delegation, reuse-hint-augmented, up to [`MAX_REDELEGATIONS`] times before
150/// giving up (#2265).
151///
152/// Why: This is the concrete "decouple retries from PM turns" implementation
153/// chosen for fix #3 — every retry this decorator performs happens INSIDE one
154/// `AgentRunner::run`/`run_with_context` call, i.e. inside one
155/// `delegate_to_agent` tool dispatch from the PM's perspective, so the PM's
156/// own `AgentLoopConfig::max_turns` is never consumed by them. Wrapping at the
157/// `AgentRunner` seam (rather than inside `DelegateToAgentTool` itself) keeps
158/// the tool free of retry policy and makes the retry/cap behaviour unit
159/// testable in isolation with a scripted inner runner.
160/// What: Holds the inner (real) engineer runner, a shared
161/// [`RedelegationCapSignal`], and the project path (quoted in the
162/// cap-reached message per the required wording, "…partial work preserved at
163/// <path>"). On each attempt: record it against the shared signal; if the
164/// new total exceeds [`MAX_REDELEGATIONS`], stop WITHOUT invoking the inner
165/// runner, latch the cap, and return a clean, descriptive error. Otherwise
166/// invoke the inner runner; on success, return it; on a failure whose
167/// [`redelegation_hint`] is `Some`, retry with the task text augmented by
168/// that hint; on a failure whose hint is `None` (no partial work to reuse),
169/// propagate immediately without consuming further cap budget.
170/// Test: `redelegating_runner_retries_on_llm_error_then_succeeds`,
171/// `redelegating_runner_stops_at_cap_and_marks_signal`,
172/// `redelegating_runner_propagates_non_retryable_errors_immediately`.
173pub struct RedelegatingRunner {
174 inner: Arc<dyn AgentRunner>,
175 signal: RedelegationCapSignal,
176 project: PathBuf,
177}
178
179impl RedelegatingRunner {
180 /// Construct from the inner engineer runner, a shared cap signal, and the
181 /// project root (used only for the cap-reached message).
182 ///
183 /// Why: Constructor injection keeps this testable with a scripted inner
184 /// runner, exactly like the crate's other `AgentRunner` decorators
185 /// (`ModelPinningRunner`).
186 /// What: Stores all three fields verbatim.
187 /// Test: Every test in this module constructs one directly.
188 pub fn new(
189 inner: Arc<dyn AgentRunner>,
190 signal: RedelegationCapSignal,
191 project: PathBuf,
192 ) -> Self {
193 Self {
194 inner,
195 signal,
196 project,
197 }
198 }
199
200 /// Drive the retry loop for one logical delegation.
201 ///
202 /// Why: Shared by both `AgentRunner` methods so `run` and
203 /// `run_with_context` can never drift on retry policy.
204 /// What: See the type-level docs for the full attempt/retry/cap
205 /// contract. Returns the first successful `AgentOutput`, or — once the
206 /// shared attempt count would exceed [`MAX_REDELEGATIONS`] — a clean
207 /// error naming the attempt count and the project path, or — on a
208 /// non-retryable failure — that failure verbatim.
209 /// Test: `redelegating_runner_retries_on_llm_error_then_succeeds`,
210 /// `redelegating_runner_stops_at_cap_and_marks_signal`,
211 /// `redelegating_runner_propagates_non_retryable_errors_immediately`,
212 /// `cap_reached_message_names_the_project_path`.
213 async fn run_with_retries(
214 &self,
215 agent_name: &str,
216 task: &str,
217 ctx: &RunContext,
218 ) -> Result<AgentOutput> {
219 let mut current_task = task.to_string();
220 loop {
221 let attempt = self.signal.record_attempt();
222 if attempt > MAX_REDELEGATIONS {
223 self.signal.mark_cap_reached();
224 return Err(anyhow::anyhow!(
225 "re-delegation limit reached after {MAX_REDELEGATIONS} attempts; \
226 partial work preserved at {}",
227 self.project.display()
228 ));
229 }
230
231 match self
232 .inner
233 .run_with_context(agent_name, ¤t_task, ctx)
234 .await
235 {
236 Ok(out) => return Ok(out),
237 Err(e) => {
238 let Some(hint) = redelegation_hint(&e) else {
239 // No partial work to reuse — this is a hard failure
240 // (unknown agent, bad config), not a re-delegation
241 // candidate. Propagate immediately.
242 return Err(e);
243 };
244 current_task = format!("{task}{hint}");
245 }
246 }
247 }
248 }
249}
250
251#[async_trait]
252impl AgentRunner for RedelegatingRunner {
253 /// See [`Self::run_with_retries`]; forwards with a default `RunContext`.
254 async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
255 self.run_with_retries(agent_name, task, &RunContext::default())
256 .await
257 }
258
259 /// See [`Self::run_with_retries`]; forwards the caller's `RunContext`
260 /// unchanged to every attempt.
261 async fn run_with_context(
262 &self,
263 agent_name: &str,
264 task: &str,
265 ctx: &RunContext,
266 ) -> Result<AgentOutput> {
267 self.run_with_retries(agent_name, task, ctx).await
268 }
269}
270
271// ── Tests ─────────────────────────────────────────────────────────────────────
272
273#[cfg(test)]
274mod tests {
275 use std::sync::Mutex;
276
277 use anyhow::anyhow;
278
279 use super::*;
280 use crate::agent_loop::AgentLoopError;
281 use crate::llm::LlmError;
282 use crate::runner::RunnerError;
283
284 /// Scripted inner runner: replays a fixed queue of `Result`s in order,
285 /// recording the task text it was called with each time.
286 ///
287 /// Why: Deterministic, offline substitute for the real engineer runner so
288 /// these tests exercise ONLY the retry/cap policy in `RedelegatingRunner`.
289 /// What: `outcomes` is drained front-to-back via a `Mutex<VecDeque<..>>`;
290 /// `calls` records every `(agent_name, task)` pair seen.
291 /// Test: Used by every test below.
292 struct ScriptedInner {
293 outcomes: Mutex<std::collections::VecDeque<Result<AgentOutput>>>,
294 calls: Mutex<Vec<String>>,
295 }
296
297 impl ScriptedInner {
298 fn new(outcomes: Vec<Result<AgentOutput>>) -> Self {
299 Self {
300 outcomes: Mutex::new(outcomes.into_iter().collect()),
301 calls: Mutex::new(Vec::new()),
302 }
303 }
304 }
305
306 #[async_trait]
307 impl AgentRunner for ScriptedInner {
308 async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
309 self.calls
310 .lock()
311 .expect("calls lock")
312 .push(task.to_string());
313 self.outcomes
314 .lock()
315 .expect("outcomes lock")
316 .pop_front()
317 .unwrap_or_else(|| Err(anyhow!("ScriptedInner exhausted for {agent_name}")))
318 }
319 }
320
321 fn llm_error() -> anyhow::Error {
322 anyhow::Error::from(RunnerError::Loop {
323 name: "python-engineer".to_string(),
324 source: AgentLoopError::Llm(LlmError::ApiError {
325 status: 500,
326 body: "bedrock hiccup".to_string(),
327 }),
328 })
329 }
330
331 fn unknown_agent_error() -> anyhow::Error {
332 anyhow::Error::from(RunnerError::UnknownAgent {
333 name: "python-engineer".to_string(),
334 dir: PathBuf::from("/agents"),
335 })
336 }
337
338 /// A retryable `AgentLoopError::Llm` failure is retried automatically,
339 /// with the reuse hint appended, and a later success is returned.
340 ///
341 /// Why: This is the core #2265 fix #3 behaviour — retries happen inside
342 /// ONE call, invisible to the PM's own turn budget.
343 /// What: Script [Err(llm), Ok(success)]; call `run`; assert the returned
344 /// output is the success, the inner runner was called twice, and the
345 /// SECOND call's task text carries the reuse hint.
346 /// Test: this test.
347 #[tokio::test]
348 async fn redelegating_runner_retries_on_llm_error_then_succeeds() {
349 let inner = Arc::new(ScriptedInner::new(vec![
350 Err(llm_error()),
351 Ok(AgentOutput::from_content("done")),
352 ]));
353 let signal = RedelegationCapSignal::new();
354 let runner = RedelegatingRunner::new(
355 Arc::clone(&inner) as Arc<dyn AgentRunner>,
356 signal.clone(),
357 PathBuf::from("/tmp/project"),
358 );
359
360 let out = runner
361 .run("python-engineer", "build the package")
362 .await
363 .expect("second attempt must succeed");
364 assert_eq!(out.content, "done");
365
366 let calls = inner.calls.lock().expect("calls lock");
367 assert_eq!(
368 calls.len(),
369 2,
370 "must retry exactly once after the LLM error"
371 );
372 assert_eq!(calls[0], "build the package");
373 assert!(
374 calls[1].contains("READ and CONTINUE"),
375 "the retried task must carry the reuse hint, got: {}",
376 calls[1]
377 );
378 assert!(
379 !signal.is_cap_reached(),
380 "cap must not be reached on a successful retry"
381 );
382 assert_eq!(signal.attempts(), 2);
383 }
384
385 /// Once attempts exceed `MAX_REDELEGATIONS`, the runner stops calling the
386 /// inner runner, marks the cap reached, and returns a clean error naming
387 /// the attempt count.
388 ///
389 /// Why: This is fix #1 — the explicit ceiling that replaces the PM's own
390 /// turn budget as the retry governor.
391 /// What: Script `MAX_REDELEGATIONS` failing `Llm` outcomes (all
392 /// retryable); assert the final error mentions "re-delegation limit
393 /// reached" and the exact attempt count, the inner runner was called
394 /// exactly `MAX_REDELEGATIONS` times (not `MAX_REDELEGATIONS + 1` — the
395 /// cap check happens BEFORE the attempt that would exceed it), and the
396 /// signal reports `is_cap_reached() == true`.
397 /// Test: this test.
398 #[tokio::test]
399 async fn redelegating_runner_stops_at_cap_and_marks_signal() {
400 let outcomes = (0..MAX_REDELEGATIONS).map(|_| Err(llm_error())).collect();
401 let inner = Arc::new(ScriptedInner::new(outcomes));
402 let signal = RedelegationCapSignal::new();
403 let runner = RedelegatingRunner::new(
404 Arc::clone(&inner) as Arc<dyn AgentRunner>,
405 signal.clone(),
406 PathBuf::from("/tmp/project"),
407 );
408
409 let err = runner
410 .run("python-engineer", "build the package")
411 .await
412 .expect_err("must fail once the cap is exceeded");
413
414 assert!(
415 err.to_string().contains("re-delegation limit reached"),
416 "error must name the cap condition, got: {err}"
417 );
418 assert!(
419 err.to_string().contains(&MAX_REDELEGATIONS.to_string()),
420 "error must name the attempt count, got: {err}"
421 );
422
423 let calls = inner.calls.lock().expect("calls lock");
424 assert_eq!(
425 calls.len(),
426 MAX_REDELEGATIONS as usize,
427 "the inner runner must be called exactly MAX_REDELEGATIONS times, not more"
428 );
429 assert!(signal.is_cap_reached(), "signal must latch cap-reached");
430 assert_eq!(signal.attempts(), MAX_REDELEGATIONS + 1);
431 }
432
433 /// A non-retryable failure (no partial work to reuse) propagates
434 /// immediately, without consuming further cap budget on retries that
435 /// would never help.
436 ///
437 /// Why: Guards the negative case — the retry loop must not blindly retry
438 /// EVERY failure, only ones `redelegation_hint` says are worth reusing.
439 /// What: Script a single `UnknownAgent` error; assert it propagates
440 /// verbatim after exactly one attempt, and the cap is NOT marked reached.
441 /// Test: this test.
442 #[tokio::test]
443 async fn redelegating_runner_propagates_non_retryable_errors_immediately() {
444 let inner = Arc::new(ScriptedInner::new(vec![Err(unknown_agent_error())]));
445 let signal = RedelegationCapSignal::new();
446 let runner = RedelegatingRunner::new(
447 Arc::clone(&inner) as Arc<dyn AgentRunner>,
448 signal.clone(),
449 PathBuf::from("/tmp/project"),
450 );
451
452 let err = runner
453 .run("python-engineer", "build the package")
454 .await
455 .expect_err("unknown-agent failures must propagate");
456
457 assert!(err.to_string().contains("unknown agent"));
458 let calls = inner.calls.lock().expect("calls lock");
459 assert_eq!(calls.len(), 1, "must not retry a non-retryable failure");
460 assert!(
461 !signal.is_cap_reached(),
462 "cap must not be marked reached for a non-retryable failure"
463 );
464 }
465
466 /// The cap-reached error message names the exact project path passed to
467 /// the constructor.
468 ///
469 /// Why: The required message shape is "re-delegation limit reached after
470 /// N attempts; partial work preserved at <path>" — pin the `<path>` half.
471 /// What: Force the cap with `MAX_REDELEGATIONS` failures against a
472 /// distinctive project path; assert it appears in the error text.
473 /// Test: this test.
474 #[tokio::test]
475 async fn cap_reached_message_names_the_project_path() {
476 let outcomes = (0..MAX_REDELEGATIONS).map(|_| Err(llm_error())).collect();
477 let inner = Arc::new(ScriptedInner::new(outcomes));
478 let signal = RedelegationCapSignal::new();
479 let runner = RedelegatingRunner::new(
480 Arc::clone(&inner) as Arc<dyn AgentRunner>,
481 signal,
482 PathBuf::from("/very/distinctive/project/path"),
483 );
484
485 let err = runner
486 .run("python-engineer", "build the package")
487 .await
488 .expect_err("must fail once the cap is exceeded");
489
490 assert!(
491 err.to_string().contains("/very/distinctive/project/path"),
492 "error must name the project path, got: {err}"
493 );
494 }
495}