Skip to main content

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`] attempts **for that one delegation** before giving up
30//! with a clean, quoted "re-delegation limit reached" error. A non-retryable
31//! failure (unknown agent, bad config) propagates immediately without
32//! consuming the budget.
33//!
34//! # #2852: the budget counts RETRIES, not delegations
35//!
36//! The original #2265 implementation shared ONE run-wide counter across every
37//! `delegate_to_agent` call and refused the 4th, whatever it was. That
38//! conflated two unrelated things: a *failing engineer being retried* (what
39//! the cap is for) and a *PM using delegation to read files before building*
40//! (the normal PM shape). A PM that spent three successful delegations on
41//! reconnaissance had its FOURTH call — the actual build — refused without the
42//! inner runner ever being invoked, and the latched signal then stopped the PM
43//! loop, making it unrecoverable. Measured cost: 2-in-7 total-loss L4 bake-off
44//! runs, caused by the harness rather than the model.
45//!
46//! So the two concerns are now counted separately:
47//!
48//! * [`MAX_REDELEGATIONS`] bounds attempts **within a single delegation**, via
49//!   a local counter reset at every [`RedelegatingRunner::run_with_retries`]
50//!   entry. A successful delegation therefore consumes NO budget from a later
51//!   one. Exhausting it latches `retry_budget_exhausted` (informational: it
52//!   labels the report) but deliberately does NOT stop the PM loop — a fresh,
53//!   different delegation is a legitimate move that could well succeed, so the
54//!   error is recoverable, exactly like #2683/#2805's post-completion refusal.
55//! * [`MAX_FAILED_INVOCATIONS`] bounds **failed** engineer invocations
56//!   run-wide. It is the surviving purpose of the shared signal: a genuinely
57//!   broken run whose delegations keep failing must still terminate. It counts
58//!   only FAILURES, never successes — otherwise the very bug above would simply
59//!   reappear one level up, with a deep-but-successful recon sequence
60//!   guillotined by a total-cost ceiling instead of by a per-run retry counter.
61//!   Only THIS ceiling latches `cap_reached`, and hence only this one fires
62//!   `run_task::mod`'s `with_stop_signal` — at which point stopping really is
63//!   correct, because delegations have demonstrably stopped clearing it.
64//!
65//! Test: `redelegating_runner_retries_on_llm_error_then_succeeds`,
66//! `successful_delegations_never_consume_a_later_delegations_budget`,
67//! `many_successful_delegations_never_latch_the_failure_ceiling`,
68//! `redelegating_runner_stops_at_per_call_cap_without_latching_stop_signal`,
69//! `failure_ceiling_latches_cap_reached`,
70//! `redelegating_runner_propagates_non_retryable_errors_immediately`,
71//! `cap_reached_message_names_the_project_path`.
72
73use std::path::PathBuf;
74use std::sync::Arc;
75use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
76
77use anyhow::Result;
78use async_trait::async_trait;
79
80use crate::tools::delegate::redelegation_hint;
81use crate::tools::{AgentOutput, AgentRunner, RunContext};
82
83/// Maximum engineer attempts for ONE `delegate_to_agent` call — 1 initial
84/// invocation plus up to 2 reuse-aware retries (#2265, re-scoped by #2852).
85///
86/// Why: This — not the PM's own turn budget — is the ceiling on retry count.
87/// 3 attempts is deliberately modest: each retry costs up to 40 engineer turns
88/// (#2233's raised default), so a generous bound would reintroduce the
89/// runaway-cost failure mode #2265 closed. #2852 re-scoped it from "per run"
90/// to "per delegation": as a RUN-wide bound it silently guillotined PMs that
91/// used delegation for legitimate reconnaissance before building, since a
92/// successful delegation consumed budget a later one then lacked. Retries are
93/// what needs bounding; delegations are not.
94/// What: Checked against a counter local to each
95/// [`RedelegatingRunner::run_with_retries`] call, reset at loop entry. Once
96/// exceeded, that delegation stops without invoking the inner runner and
97/// returns a recoverable error — the PM's loop continues and may delegate
98/// again with a full, fresh budget (see [`MAX_FAILED_INVOCATIONS`] for the
99/// run-wide backstop that keeps "again" from being unbounded).
100/// Test: `redelegating_runner_stops_at_per_call_cap_without_latching_stop_signal`,
101/// `successful_delegations_never_consume_a_later_delegations_budget`.
102pub const MAX_REDELEGATIONS: u32 = 3;
103
104/// Maximum FAILED engineer invocations across a whole `execute_run_task` run
105/// (#2852).
106///
107/// Why: With [`MAX_REDELEGATIONS`] scoped per-delegation, something must still
108/// bound a pathological run in which delegations keep FAILING — otherwise a PM
109/// stuck in a failing loop could re-delegate once per turn forever, which is
110/// the runaway #2265 existed to prevent. Only FAILURES count toward it. This
111/// fix's central thesis is that a successful delegation must never consume
112/// budget a later one needs; that has to hold at the run-wide ceiling too, not
113/// just at the per-delegation counter, or the same guillotine simply moves up
114/// one level. A PM issuing many successful read-only recon delegations — one
115/// per atomic recon step, the normal shape, and `tcode` is an interactive
116/// daily driver rather than only a bake-off runner — must never be terminated
117/// for it, no matter how deep the recon goes.
118/// 12 is 4× the per-delegation retry budget: four separate delegations may
119/// each fail completely before the run is declared hopeless.
120/// What: Checked against the shared [`RedelegationCapSignal`] after an engineer
121/// invocation FAILS. Reaching it is the ONLY thing that latches `cap_reached`,
122/// and hence the only thing that fires `run_task::mod`'s `with_stop_signal` to
123/// halt the PM loop — correct here precisely because a run that has failed this
124/// many times has demonstrated that fresh delegations are not clearing it.
125/// Successful invocations are counted only by
126/// [`RedelegationCapSignal::attempts`], which is reporting-only and governs
127/// nothing.
128/// Test: `failure_ceiling_latches_cap_reached`,
129/// `many_successful_delegations_never_latch_the_failure_ceiling`.
130pub const MAX_FAILED_INVOCATIONS: u32 = 12;
131
132/// Shared, run-scoped state behind [`RedelegationCapSignal`].
133///
134/// Why: Kept as a private inner type so the public handle stays a cheap,
135/// `Clone`-able `Arc` wrapper — see [`RedelegationCapSignal`]'s own docs.
136/// What: `attempts` counts every engineer invocation actually dispatched across
137/// the whole run — a truthful cost measure for REPORTING only; it governs
138/// nothing (#2852). `failed_invocations` counts only the subset that failed,
139/// and is the sole input to the terminal ceiling, so that no number of
140/// successes can ever end a run. `retry_budget_exhausted` latches `true` the
141/// first time any ONE delegation burns all [`MAX_REDELEGATIONS`] attempts —
142/// informational only. `cap_reached` latches `true` only when
143/// `failed_invocations` reaches [`MAX_FAILED_INVOCATIONS`]; that one is
144/// terminal (#2852).
145/// Test: Exercised indirectly through `RedelegationCapSignal`'s own tests.
146#[derive(Debug, Default)]
147struct RedelegationCapState {
148    attempts: AtomicU32,
149    failed_invocations: AtomicU32,
150    retry_budget_exhausted: AtomicBool,
151    cap_reached: AtomicBool,
152}
153
154/// Shared signal tracking total re-delegation attempts across one run (#2265).
155///
156/// Why: [`RedelegatingRunner`] and `run_task::assemble_report` are different
157/// call sites that both need to observe the SAME attempt count / cap state —
158/// the runner to enforce the cap, the report assembler to recognise a
159/// cap-triggered terminal state even when the PM's own loop error doesn't
160/// literally say so (e.g. the PM's NEXT turn separately exhausts its own
161/// budget after seeing the cap-reached tool error). An `Arc`-wrapped group of
162/// atomics is the simplest thing that is `Send + Sync` and cheap to clone into
163/// both places.
164/// What: `new()` starts at zero attempts with both flags clear.
165/// `is_cap_reached()`, `is_retry_budget_exhausted()` and `attempts()` are
166/// read-only accessors for `assemble_report`; `record_attempt`,
167/// `mark_retry_budget_exhausted` and `mark_cap_reached` are private, called
168/// only by [`RedelegatingRunner`]. The two flags are deliberately distinct:
169/// only `cap_reached` is terminal (#2852).
170/// Test: `redelegating_runner_stops_at_per_call_cap_without_latching_stop_signal`,
171/// `failure_ceiling_latches_cap_reached`,
172/// `successful_delegations_never_consume_a_later_delegations_budget`.
173#[derive(Debug, Clone, Default)]
174pub struct RedelegationCapSignal(Arc<RedelegationCapState>);
175
176impl RedelegationCapSignal {
177    /// Build a fresh signal with zero recorded attempts.
178    ///
179    /// Why: Each `execute_run_task` call needs its OWN signal — attempts must
180    /// never leak across independent runs.
181    /// What: `Self::default()`.
182    /// Test: `redelegating_runner_retries_on_llm_error_then_succeeds`.
183    pub fn new() -> Self {
184        Self::default()
185    }
186
187    /// Record one more dispatched engineer invocation.
188    ///
189    /// Why: Reporting only (#2852) — an operator wants to know how much
190    /// engineer work the run actually bought. It deliberately governs NOTHING:
191    /// making total cost terminal is precisely the bug this fix removes.
192    /// What: `fetch_add(1)`. Called only for invocations that actually reach
193    /// the inner runner, so the count stays a truthful cost measure.
194    /// Test: `many_successful_delegations_never_latch_the_failure_ceiling`.
195    fn record_attempt(&self) {
196        self.0.attempts.fetch_add(1, Ordering::SeqCst);
197    }
198
199    /// Record one FAILED engineer invocation and return the new run-wide total.
200    ///
201    /// Why: This is the terminal ceiling's only input. The runner must compare
202    /// the POST-increment total against [`MAX_FAILED_INVOCATIONS`] atomically
203    /// with recording it, so two concurrent failures can never both observe
204    /// "one under the ceiling" and both proceed.
205    /// What: `fetch_add(1) + 1`. Called once per invocation that returned an
206    /// error, retryable or not — both shapes are failures the ceiling exists
207    /// to bound.
208    /// Test: `failure_ceiling_latches_cap_reached`.
209    fn record_failure(&self) -> u32 {
210        self.0.failed_invocations.fetch_add(1, Ordering::SeqCst) + 1
211    }
212
213    /// Latch the "some delegation burned its whole retry budget" flag (#2852).
214    ///
215    /// Why: `assemble_report` needs this to keep labelling a genuinely
216    /// retry-exhausted run "re-delegation limit reached" (and to map it to
217    /// `Partial` when a deliverable exists) — diagnostics #2852 must not lose.
218    /// It is deliberately SEPARATE from `cap_reached`: this condition is
219    /// recoverable, so it must never reach the PM loop's stop signal.
220    /// What: Stores `true`.
221    /// Test: `redelegating_runner_stops_at_per_call_cap_without_latching_stop_signal`.
222    fn mark_retry_budget_exhausted(&self) {
223        self.0.retry_budget_exhausted.store(true, Ordering::SeqCst);
224    }
225
226    /// Latch the terminal run-wide failure-ceiling flag.
227    ///
228    /// Why: Called exactly once, the moment failed invocations reach
229    /// [`MAX_FAILED_INVOCATIONS`] — the run has failed too many times for a
230    /// fresh delegation to be worth betting on, so this is what both
231    /// `assemble_report` and the PM loop's stop signal key off.
232    /// What: Stores `true`.
233    /// Test: `failure_ceiling_latches_cap_reached`.
234    fn mark_cap_reached(&self) {
235        self.0.cap_reached.store(true, Ordering::SeqCst);
236    }
237
238    /// Whether the run-wide FAILED-invocation ceiling was hit (#2852).
239    ///
240    /// Why: Drives `run_task::mod`'s `with_stop_signal`, so it must be `true`
241    /// ONLY for conditions a fresh delegation genuinely cannot clear. Neither
242    /// per-call retry exhaustion (see [`Self::is_retry_budget_exhausted`]) nor
243    /// sheer invocation COUNT is one of those — a run of successful recon
244    /// delegations must never land here.
245    /// What: Reads the latched flag.
246    /// Test: `failure_ceiling_latches_cap_reached`,
247    /// `many_successful_delegations_never_latch_the_failure_ceiling`.
248    pub fn is_cap_reached(&self) -> bool {
249        self.0.cap_reached.load(Ordering::SeqCst)
250    }
251
252    /// Test-only: a signal with `retry_budget_exhausted` already latched.
253    ///
254    /// Why: `run_task::mod`'s `assemble_report` must be unit-testable against
255    /// the retry-exhausted-with-deliverable shape — the most common real-world
256    /// outcome once #2852 makes retry exhaustion recoverable — without
257    /// standing up a whole scripted `RedelegatingRunner` from a sibling module.
258    /// Kept `#[cfg(test)]` so the production API kept its invariant that only
259    /// [`RedelegatingRunner`] can latch this.
260    /// What: `Self::default()` with the one flag set.
261    /// Test: `assemble_report_maps_retry_exhausted_with_deliverable_to_partial`.
262    #[cfg(test)]
263    pub(crate) fn retry_exhausted_for_test() -> Self {
264        let signal = Self::default();
265        signal.mark_retry_budget_exhausted();
266        signal
267    }
268
269    /// Total FAILED engineer invocations recorded so far, run-wide.
270    ///
271    /// Why: The number the terminal report must quote — it is the ceiling's
272    /// actual input, and unlike a pre-incremented dispatch counter it is
273    /// exactly the count of invocations that really failed, so an operator is
274    /// never told "13" when 12 occurred.
275    /// What: Reads the atomic counter.
276    /// Test: `failure_ceiling_latches_cap_reached`.
277    pub fn failed_invocations(&self) -> u32 {
278        self.0.failed_invocations.load(Ordering::SeqCst)
279    }
280
281    /// Whether any single delegation exhausted its [`MAX_REDELEGATIONS`]
282    /// retry budget during this run (#2852).
283    ///
284    /// Why: Lets `assemble_report` distinguish "the engineer really was
285    /// retried to exhaustion" from an unrelated PM-loop error, WITHOUT that
286    /// observation stopping the loop. Read-only for report assembly.
287    /// What: Reads the latched flag.
288    /// Test: `redelegating_runner_stops_at_per_call_cap_without_latching_stop_signal`.
289    pub fn is_retry_budget_exhausted(&self) -> bool {
290        self.0.retry_budget_exhausted.load(Ordering::SeqCst)
291    }
292
293    /// Total engineer invocations (successes AND failures) recorded so far,
294    /// run-wide.
295    ///
296    /// Why: A truthful total-cost measure for callers that want it (e.g.
297    /// future observability/metrics) — but it is reporting-only and governs
298    /// nothing (#2852): the terminal report's message quotes
299    /// [`Self::failed_invocations`] instead, precisely so a run of successful
300    /// delegations is never described as having "failed" anything.
301    /// What: Reads the atomic counter.
302    /// Test: `many_successful_delegations_never_latch_the_failure_ceiling`,
303    /// `redelegating_runner_retries_on_llm_error_then_succeeds`.
304    pub fn attempts(&self) -> u32 {
305        self.0.attempts.load(Ordering::SeqCst)
306    }
307}
308
309/// `AgentRunner` decorator that internally retries a failed engineer
310/// delegation, reuse-hint-augmented, up to [`MAX_REDELEGATIONS`] times before
311/// giving up (#2265).
312///
313/// Why: This is the concrete "decouple retries from PM turns" implementation
314/// chosen for fix #3 — every retry this decorator performs happens INSIDE one
315/// `AgentRunner::run`/`run_with_context` call, i.e. inside one
316/// `delegate_to_agent` tool dispatch from the PM's perspective, so the PM's
317/// own `AgentLoopConfig::max_turns` is never consumed by them. Wrapping at the
318/// `AgentRunner` seam (rather than inside `DelegateToAgentTool` itself) keeps
319/// the tool free of retry policy and makes the retry/cap behaviour unit
320/// testable in isolation with a scripted inner runner.
321/// What: Holds the inner (real) engineer runner, a shared
322/// [`RedelegationCapSignal`], and the project path (quoted in the
323/// cap-reached message per the required wording, "…partial work preserved at
324/// <path>"). If the run-wide ceiling has already latched, the delegation is
325/// refused up front without dispatching anything. Otherwise, per delegation, a
326/// LOCAL attempt counter starts at zero (#2852):
327/// if it would exceed [`MAX_REDELEGATIONS`], stop WITHOUT invoking the inner
328/// runner, latch `retry_budget_exhausted`, warn, and return a RECOVERABLE
329/// error (the PM may delegate again with a fresh budget). Otherwise invoke the
330/// inner runner; on success, return it. On failure, record the failure
331/// run-wide; if that reaches [`MAX_FAILED_INVOCATIONS`], latch `cap_reached`
332/// (terminal — stops the PM loop) and return. Otherwise, on a failure whose
333/// [`redelegation_hint`] is `Some`, retry with the task text augmented by
334/// that hint; on a failure whose hint is `None` (no partial work to reuse),
335/// propagate immediately without consuming further budget.
336/// Test: `redelegating_runner_retries_on_llm_error_then_succeeds`,
337/// `successful_delegations_never_consume_a_later_delegations_budget`,
338/// `many_successful_delegations_never_latch_the_failure_ceiling`,
339/// `redelegating_runner_stops_at_per_call_cap_without_latching_stop_signal`,
340/// `failure_ceiling_latches_cap_reached`,
341/// `redelegating_runner_propagates_non_retryable_errors_immediately`.
342pub struct RedelegatingRunner {
343    inner: Arc<dyn AgentRunner>,
344    signal: RedelegationCapSignal,
345    project: PathBuf,
346}
347
348impl RedelegatingRunner {
349    /// Construct from the inner engineer runner, a shared cap signal, and the
350    /// project root (used only for the cap-reached message).
351    ///
352    /// Why: Constructor injection keeps this testable with a scripted inner
353    /// runner, exactly like the crate's other `AgentRunner` decorators
354    /// (`ModelPinningRunner`).
355    /// What: Stores all three fields verbatim.
356    /// Test: Every test in this module constructs one directly.
357    pub fn new(
358        inner: Arc<dyn AgentRunner>,
359        signal: RedelegationCapSignal,
360        project: PathBuf,
361    ) -> Self {
362        Self {
363            inner,
364            signal,
365            project,
366        }
367    }
368
369    /// Drive the retry loop for one logical delegation.
370    ///
371    /// Why: Shared by both `AgentRunner` methods so `run` and
372    /// `run_with_context` can never drift on retry policy.
373    /// What: See the type-level docs for the full attempt/retry/cap
374    /// contract. `attempt` is LOCAL to this call and starts at zero every time
375    /// (#2852) — that is the whole fix: a delegation's retry budget belongs to
376    /// that delegation, so an earlier successful one cannot spend it. Returns
377    /// the first successful `AgentOutput`; or, once this call's attempts would
378    /// exceed [`MAX_REDELEGATIONS`], a recoverable error naming the count and
379    /// project path; or, once the run's FAILED invocations reach
380    /// [`MAX_FAILED_INVOCATIONS`], a terminal error that also latches the
381    /// stop signal; or, on a non-retryable failure, that failure verbatim.
382    /// Test: `redelegating_runner_retries_on_llm_error_then_succeeds`,
383    /// `successful_delegations_never_consume_a_later_delegations_budget`,
384    /// `many_successful_delegations_never_latch_the_failure_ceiling`,
385    /// `redelegating_runner_stops_at_per_call_cap_without_latching_stop_signal`,
386    /// `failure_ceiling_latches_cap_reached`,
387    /// `redelegating_runner_propagates_non_retryable_errors_immediately`,
388    /// `cap_reached_message_names_the_project_path`.
389    async fn run_with_retries(
390        &self,
391        agent_name: &str,
392        task: &str,
393        ctx: &RunContext,
394    ) -> Result<AgentOutput> {
395        // Once the run-wide ceiling has latched, refuse WITHOUT dispatching.
396        // The PM loop is already being stopped, so further engineer work is
397        // pure waste — and dispatching it would also inflate the failure count
398        // the terminal report quotes, telling an operator more invocations
399        // failed than the ceiling actually allowed.
400        if self.signal.is_cap_reached() {
401            return Err(anyhow::anyhow!(
402                "engineer failure ceiling reached after {} failed invocations this run; \
403                 partial work preserved at {}",
404                self.signal.failed_invocations(),
405                self.project.display()
406            ));
407        }
408
409        let mut current_task = task.to_string();
410        // #2852: per-CALL, not per-run. Reset at entry so reconnaissance
411        // delegations that succeed never starve the build that follows.
412        let mut attempt: u32 = 0;
413        loop {
414            attempt += 1;
415            if attempt > MAX_REDELEGATIONS {
416                self.signal.mark_retry_budget_exhausted();
417                // #2852: this cap used to be entirely silent — run-6's stderr
418                // carried no trace of it and the mechanism was only findable
419                // by cross-run forensics on the report's `task` label. Say so.
420                // Recoverable: the PM's loop continues (this does NOT latch
421                // `cap_reached`), so it may delegate afresh.
422                tracing::warn!(
423                    agent = agent_name,
424                    attempts = MAX_REDELEGATIONS,
425                    run_invocations = self.signal.attempts(),
426                    "re-delegation retry budget exhausted for this delegation; refusing \
427                     further retries of it. The PM loop continues — a fresh delegation \
428                     gets a full budget."
429                );
430                return Err(anyhow::anyhow!(
431                    "re-delegation limit reached after {MAX_REDELEGATIONS} attempts; \
432                     partial work preserved at {}",
433                    self.project.display()
434                ));
435            }
436
437            // Reporting only (#2852): total invocations govern nothing, so a
438            // run of successful delegations can never be terminated for its
439            // count. Recorded before dispatch so the cost measure stays
440            // truthful even if the invocation panics or fails.
441            self.signal.record_attempt();
442
443            match self
444                .inner
445                .run_with_context(agent_name, &current_task, ctx)
446                .await
447            {
448                Ok(out) => return Ok(out),
449                Err(e) => {
450                    // Only FAILURES feed the terminal ceiling — the whole point
451                    // of #2852, applied at the run-wide level too and not just
452                    // to the per-delegation counter.
453                    let failures = self.signal.record_failure();
454                    if failures >= MAX_FAILED_INVOCATIONS {
455                        self.signal.mark_cap_reached();
456                        // Terminal, unlike the per-call budget above: the run
457                        // has failed too many times for a fresh delegation to
458                        // be worth betting on, so `run_task::mod`'s stop signal
459                        // halts the PM loop at its next turn boundary. Log
460                        // loudly — this ends the run.
461                        tracing::warn!(
462                            agent = agent_name,
463                            failed_invocations = failures,
464                            ceiling = MAX_FAILED_INVOCATIONS,
465                            "run-wide engineer failure ceiling reached; stopping the PM \
466                             loop. Delegations this run kept failing rather than \
467                             succeeding."
468                        );
469                        return Err(anyhow::anyhow!(
470                            "engineer failure ceiling reached after {failures} failed \
471                             invocations this run; partial work preserved at {}",
472                            self.project.display()
473                        ));
474                    }
475
476                    let Some(hint) = redelegation_hint(&e) else {
477                        // No partial work to reuse — this is a hard failure
478                        // (unknown agent, bad config), not a re-delegation
479                        // candidate. Propagate immediately.
480                        return Err(e);
481                    };
482                    current_task = format!("{task}{hint}");
483                }
484            }
485        }
486    }
487}
488
489#[async_trait]
490impl AgentRunner for RedelegatingRunner {
491    /// See [`Self::run_with_retries`]; forwards with a default `RunContext`.
492    async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
493        self.run_with_retries(agent_name, task, &RunContext::default())
494            .await
495    }
496
497    /// See [`Self::run_with_retries`]; forwards the caller's `RunContext`
498    /// unchanged to every attempt.
499    async fn run_with_context(
500        &self,
501        agent_name: &str,
502        task: &str,
503        ctx: &RunContext,
504    ) -> Result<AgentOutput> {
505        self.run_with_retries(agent_name, task, ctx).await
506    }
507}
508
509// ── Tests ─────────────────────────────────────────────────────────────────────
510
511#[cfg(test)]
512mod tests;