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