Skip to main content

trusty_code/run_task/
mod.rs

1//! `tcode run-task` end-to-end execution (#1034, #1035).
2//!
3//! Why: This is the closer that makes the `tcode` binary actually run a task. It
4//! wires every M1 piece together: load the project `CLAUDE.md` context (#1033),
5//! assemble the PM system prompt, run the PM through an `AgentLoop` against the
6//! real (or mocked) `LlmClient`, let the PM delegate to the `python-engineer` via
7//! the `DelegateToAgentTool` + `InProcessAgentRunner`, and have the engineer run
8//! its own loop with fs/bash tools scoped to the project. The run captures a diff
9//! of the working tree, the PM+engineer transcript, and aggregated token/cost
10//! usage, then renders both a human and a JSON report with meaningful exit codes.
11//! What: `RunTaskParams` carries the CLI inputs; `execute_run_task` is the async
12//! orchestrator returning a `RunReport`. The LLM client is injected so production
13//! passes a real `LlmClient` and tests pass a scripted mock — no live key needed.
14//! Test: `run_task::tests` drive the whole PM→engineer path offline.
15
16mod diff;
17mod recorder;
18mod redelegation;
19mod report;
20
21#[cfg(test)]
22mod tests;
23
24use std::path::PathBuf;
25use std::sync::{Arc, Mutex};
26use std::time::Duration;
27
28use anyhow::Result;
29use async_trait::async_trait;
30
31use crate::agent_loop::{AgentLoop, AgentLoopConfig, AgentLoopError};
32use crate::agents::AgentConfig;
33use crate::llm::{DebugCaptureSink, LlmClientTrait, wrap_with_debug_capture};
34use crate::project_context::load_project_context;
35use crate::prompt::assemble_system_prompt;
36use crate::provider::{resolve_deadline_secs, resolve_max_tokens, resolve_model};
37use crate::runner::{InProcessAgentRunner, RegistryFactory};
38use crate::tools::{
39    AgentOutput, AgentRunner, BashTool, DelegateToAgentTool, EditTool, FinishTaskTool,
40    ReadFileTool, RunContext, ToolRegistry, WriteFileTool,
41};
42
43pub use recorder::{RecordingLlmClient, SharedTranscript, TurnRecord};
44pub use redelegation::{MAX_REDELEGATIONS, RedelegationCapSignal};
45pub use report::{ExitCode, RunReport, aggregate_usage_per_role};
46
47/// Default bash timeout for the engineer's tools, in seconds.
48const ENGINEER_BASH_TIMEOUT_SECS: u64 = 120;
49
50/// The delegated engineer's agent name (matches
51/// `task::executor::ENGINEER_AGENT_NAME`, the daemon path's own copy of this
52/// same literal — kept as two constants, not one shared item, since neither
53/// module depends on the other and a shared constant would be a heavier
54/// coupling than the two paths' otherwise-independent module boundaries
55/// warrant).
56const ENGINEER_AGENT_NAME: &str = "python-engineer";
57
58/// Inputs to a single `run-task` invocation, parsed from the CLI.
59///
60/// Why: Bundling the inputs keeps `execute_run_task`'s signature stable as flags
61/// are added and lets the binary layer construct one value from clap.
62/// What: `agent` is the top-level (PM) agent name; `task` is the request; `project`
63/// is the canonical project root; `agents_dir` is where `<agent>.toml` live;
64/// `engineer_model` is the optional per-run engineer model override (#1035).
65/// Test: `run_task::tests` build these directly.
66#[derive(Debug, Clone)]
67pub struct RunTaskParams {
68    /// Top-level agent name (typically `"pm"`).
69    pub agent: String,
70    /// Free-form task description.
71    pub task: String,
72    /// Canonical project root.
73    pub project: PathBuf,
74    /// Directory holding `<agent>.toml` configs.
75    pub agents_dir: PathBuf,
76    /// Optional per-run engineer model override (#1035). `None` routes the
77    /// engineer via its own config model.
78    pub engineer_model: Option<String>,
79    /// Optional per-run wall-clock deadline override, in seconds (#2207).
80    /// `None` falls through to [`crate::provider::resolve_deadline_secs`]'s
81    /// env-var/default tiers — see that function's docs for the full
82    /// precedence. Applied to BOTH the PM's own loop and the delegated
83    /// engineer's loop (`build_engineer_runner`).
84    pub deadline_secs: Option<u64>,
85}
86
87/// Execute a `run-task` end-to-end and return the rendered report.
88///
89/// Why: The single orchestration entry point the binary calls (with a real
90/// `LlmClient`) and tests call (with a scripted mock). Keeping the LLM client as
91/// an injected `Arc<dyn LlmClientTrait>` is what makes the whole path testable
92/// offline without a network call or an API key.
93/// What: Loads the PM config, assembles its prompt (BASE + PM prompt + project
94/// `CLAUDE.md`), builds the engineer runner (fs/bash scoped to the project, with
95/// the optional per-run model override), wraps it in the PM's
96/// `DelegateToAgentTool`, snapshots the working tree, runs the PM `AgentLoop`
97/// (#2265 fix #5: wired with `with_stop_signal` against the SAME
98/// `redelegation_signal` the engineer runner shares, so the PM stops issuing
99/// `delegate_to_agent` calls the turn after the re-delegation cap latches
100/// instead of spinning through its remaining turns on doomed retries),
101/// snapshots again, and assembles a `RunReport` (diff + transcript + usage/cost +
102/// exit code). A PM-config or loop error yields a `ConfigError`/`RunFailure`
103/// report rather than a panic.
104/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
105/// `diff_reflects_engineer_file_change`, `usage_and_cost_aggregate_end_to_end`,
106/// `exit_code_reflects_run_failure`,
107/// `pm_stops_redelegating_once_cap_latched_ends_partial_promptly`.
108pub async fn execute_run_task(params: RunTaskParams, llm: Arc<dyn LlmClientTrait>) -> RunReport {
109    let transcript: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
110
111    // #2264: resolve the (optional) full wire-level debug-capture sink once
112    // per run, shared by BOTH the pm and engineer wrappers below so a
113    // directory-mode capture lands in one file with a single globally
114    // ordered turn sequence — mirrors `transcript`'s own "one shared
115    // accumulator per run" shape. `None` when `TCODE_DEBUG_TRANSCRIPT` is
116    // unset (the default): `wrap_with_debug_capture` then returns each
117    // inner client unchanged, so this costs nothing when disabled.
118    let debug_sink: Option<Arc<DebugCaptureSink>> = DebugCaptureSink::from_env();
119
120    // Load the PM config; a missing/invalid config is a configuration error.
121    let pm_config =
122        match AgentConfig::load(&params.agents_dir.join(format!("{}.toml", params.agent))) {
123            Ok(cfg) => cfg,
124            Err(e) => return config_error_report(&params, &transcript, &format!("{e:#}")),
125        };
126
127    // Load project context (#1033) — absent file is fine.
128    let project_context = load_project_context(&params.project);
129
130    // Resolve the PM's own model (no per-call override for the PM).
131    let pm_model = resolve_model(&pm_config, None);
132
133    // #2207: resolve the run's wall-clock deadline once, applied to BOTH the
134    // PM's own loop (below) and the delegated engineer's loop
135    // (`build_engineer_runner`, via `with_timeout_secs`).
136    let deadline_secs = resolve_deadline_secs(params.deadline_secs);
137
138    // (#2265) The re-delegation cap signal is shared between the engineer
139    // runner's retry decorator (`RedelegatingRunner`, wired inside
140    // `build_engineer_runner`) and `assemble_report` below, so a cap-hit run
141    // gets a clean terminal report regardless of what the PM's own loop
142    // subsequently does.
143    let redelegation_signal = RedelegationCapSignal::new();
144
145    // Build the engineer runner, scoped to the project working dir, sharing the
146    // transcript (engineer turns are tagged "python-engineer").
147    let engineer_runner = build_engineer_runner(
148        wrap_with_debug_capture(Arc::clone(&llm), ENGINEER_AGENT_NAME, debug_sink.as_ref()),
149        &params,
150        project_context.clone(),
151        Arc::clone(&transcript),
152        deadline_secs,
153        redelegation_signal.clone(),
154    );
155
156    // The PM's tool registry: the delegate tool (the PM orchestrates; the
157    // engineer does the file work) plus `finish_task` (#2072) so the PM can
158    // signal completion with a structured report instead of relying solely on
159    // the implicit no-tool-call convention. Pre-flight validation uses the
160    // agents dir.
161    let mut pm_registry = ToolRegistry::new();
162    pm_registry.register(Arc::new(
163        DelegateToAgentTool::new(engineer_runner).with_config_dir(params.agents_dir.clone()),
164    ));
165    pm_registry.register(Arc::new(FinishTaskTool::new()));
166
167    // The PM's loop uses a transcript-recording client tagged "pm".
168    let pm_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
169        wrap_with_debug_capture(Arc::clone(&llm), "pm", debug_sink.as_ref()),
170        "pm",
171        Arc::clone(&transcript),
172    ));
173
174    // Inject DOC-28 catch-up digest as seed context into the PM prompt (#1762 PR2).
175    // The catch-up engine is async and fail-open: if the daemon is offline or the
176    // project has no activity, it returns None and the prompt is assembled without
177    // the section.  Sub-agents are NOT wired here; only the PM receives this digest.
178    let catchup_ctx = crate::catchup::pm_catchup_context(&params.project).await;
179
180    let pm_system = assemble_system_prompt(
181        &pm_config,
182        project_context.as_deref(),
183        catchup_ctx.as_deref(),
184    );
185    // (#2265 fix #5) Once the shared re-delegation cap latches, every further
186    // `delegate_to_agent` call the PM might issue is a guaranteed dead end —
187    // `RedelegatingRunner` will reject it immediately without even invoking
188    // the engineer. Wiring the SAME signal into the PM's own loop as a stop
189    // condition (checked at the existing turn-boundary, alongside the #2056
190    // cancellation flag) stops the PM from spending its remaining
191    // `max_turns` issuing those doomed calls one per turn — the bake-off L1
192    // regression this fix closes (see `redelegation` module docs for the
193    // full before/after). `assemble_report` already maps a cap-latched,
194    // deliverable-bearing run to `ExitCode::Partial` regardless of which
195    // `AgentLoopError` variant the PM's loop returns, so this purely trims
196    // wasted turns — it does not change the reported outcome.
197    let stop_signal = redelegation_signal.clone();
198    let pm_loop = AgentLoop::new(
199        AgentLoopConfig {
200            model: pm_model.clone(),
201            max_tokens: resolve_max_tokens(&pm_config),
202            timeout_secs: deadline_secs,
203            ..AgentLoopConfig::default()
204        },
205        pm_llm,
206        Arc::new(pm_registry),
207    )
208    .with_stop_signal(Arc::new(move || stop_signal.is_cap_reached()));
209
210    // Snapshot before, run the PM, snapshot after.
211    let before = diff::capture_snapshot(&params.project);
212    let pm_result = pm_loop.run(&pm_system, &params.task).await;
213    let after = diff::capture_snapshot(&params.project);
214
215    // Resolve the engineer's model independently (#1475 bug 1) so the report
216    // prices its turns at its OWN rate rather than blending everything
217    // under the PM model.
218    let engineer_model = resolve_agent_model_slug(
219        &params.agents_dir,
220        ENGINEER_AGENT_NAME,
221        params.engineer_model.as_deref(),
222    );
223
224    assemble_report(
225        &params,
226        &transcript,
227        &pm_model,
228        &engineer_model,
229        RunOutcome {
230            before,
231            after,
232            pm_result,
233        },
234        &redelegation_signal,
235    )
236}
237
238/// Build the in-process engineer runner with project-scoped fs/bash tools.
239///
240/// Why: The engineer must write/read/run inside the project and see the same
241/// project context as the PM. This wires a `RegistryFactory` that constructs fs +
242/// bash tools scoped to the project dir plus the project context, then routes the
243/// result through the per-run model-override seam (`apply_engineer_model_override`).
244/// `deadline_secs` (#2207) is the SAME resolved wall-clock budget applied to the
245/// delegating PM's own loop, so a raised deadline covers the whole run, not just
246/// the PM's half of it. (#2265) The outermost layer is
247/// `redelegation::RedelegatingRunner`, which internally retries a failed
248/// attempt (reuse-hint-augmented, capped at `redelegation::MAX_REDELEGATIONS`)
249/// entirely within one `AgentRunner::run`/`run_with_context` call — this is
250/// the chosen "decouple retries from PM turns" design for fix #3: every
251/// retry happens inside a SINGLE `delegate_to_agent` tool dispatch, so it
252/// never consumes any of the PM's own `AgentLoopConfig::max_turns` budget
253/// (left at its crate default of 8 — raising it was the alternative design,
254/// rejected here because the cap in fix #1 is a cleaner, purpose-built ceiling
255/// than a bigger, still-somewhat-arbitrary PM turn budget would be).
256/// What: Returns an `Arc<dyn AgentRunner>` the `DelegateToAgentTool` dispatches
257/// to. The engineer's own LLM turns are recorded under the "python-engineer" role.
258/// `redelegation_signal` is shared with `assemble_report` via the caller.
259/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
260fn build_engineer_runner(
261    llm: Arc<dyn LlmClientTrait>,
262    params: &RunTaskParams,
263    project_context: Option<String>,
264    transcript: SharedTranscript,
265    deadline_secs: u64,
266    redelegation_signal: RedelegationCapSignal,
267) -> Arc<dyn AgentRunner> {
268    let engineer_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
269        llm,
270        ENGINEER_AGENT_NAME,
271        transcript,
272    ));
273
274    let factory: Arc<dyn RegistryFactory> = Arc::new(ProjectToolFactory {
275        project: params.project.clone(),
276    });
277
278    let mut runner = InProcessAgentRunner::new(engineer_llm, factory, params.agents_dir.clone())
279        .with_timeout_secs(deadline_secs);
280    if let Some(ctx) = project_context {
281        runner = runner.with_project_context(ctx);
282    }
283    let pinned = apply_engineer_model_override(Arc::new(runner), params);
284    Arc::new(redelegation::RedelegatingRunner::new(
285        pinned,
286        redelegation_signal,
287        params.project.clone(),
288    ))
289}
290
291/// Builds the engineer's project-scoped tool registry for each delegation.
292///
293/// Why: The engineer needs real file and shell tools that cannot escape the
294/// project root, plus (#2072) `finish_task` so it can signal completion with a
295/// structured report. This factory constructs `read_file`, `write_file`,
296/// `edit`, and `bash` all scoped to `self.project`, so the engineer operates
297/// only inside the project working tree; `finish_task` has no filesystem
298/// footprint and needs no scoping.
299/// What: Implements `RegistryFactory::build`, returning an `Arc<ToolRegistry>`
300/// with all five tools; the runner then gates them by the engineer's
301/// `tools.allowed`.
302/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer` (the engineer's
303/// `write_file` actually writes into the project).
304struct ProjectToolFactory {
305    project: PathBuf,
306}
307
308#[async_trait]
309impl RegistryFactory for ProjectToolFactory {
310    async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
311        // #2068: resolve the engineer's model slug so `EditTool` can pick its
312        // per-model edit-format fallback order (see `resolve_model`'s own
313        // precedence docs — RunContext override > agent config > default).
314        let model_slug = resolve_model(agent, Some(ctx));
315        let mut reg = ToolRegistry::new();
316        reg.register(Arc::new(ReadFileTool::new(&self.project)));
317        reg.register(Arc::new(WriteFileTool::new(&self.project)));
318        reg.register(Arc::new(
319            EditTool::new(&self.project).with_model_slug(model_slug),
320        ));
321        reg.register(Arc::new(BashTool::new(
322            Some(self.project.clone()),
323            Duration::from_secs(ENGINEER_BASH_TIMEOUT_SECS),
324        )));
325        reg.register(Arc::new(FinishTaskTool::new()));
326        Arc::new(reg)
327    }
328}
329
330/// Apply the per-run engineer-model override to the runner, if any (#1035).
331///
332/// Why: The engineer routes to its own configured model by default. A per-run
333/// `--engineer-model` (or `TCODE_ENGINEER_MODEL`) must reroute *only* the engineer
334/// for that single run — the model-comparison harness varies the engineer model
335/// while the PM model stays fixed. Keeping the override here lets
336/// `build_engineer_runner` stay agnostic to whether a model is pinned.
337/// What: When `params.engineer_model` is `Some`, wraps the runner in a
338/// `ModelPinningRunner` that injects `RunContext.model` on every delegation;
339/// otherwise returns the runner unchanged.
340/// Test: `run_task::tests::engineer_model_swap_routes_engineer`,
341/// `two_runs_route_engineer_to_distinct_slugs`.
342fn apply_engineer_model_override(
343    runner: Arc<dyn AgentRunner>,
344    params: &RunTaskParams,
345) -> Arc<dyn AgentRunner> {
346    match &params.engineer_model {
347        Some(model) => Arc::new(ModelPinningRunner {
348            inner: runner,
349            model: model.clone(),
350        }),
351        None => runner,
352    }
353}
354
355/// Resolve an agent's model slug, honouring an optional per-run override
356/// (#1035, #1475 bug 1 fix's prerequisite).
357///
358/// Why: `InProcessAgentRunner` resolves the engineer's model internally and
359/// does not expose it, so pricing the engineer's turns against its OWN
360/// model (rather than blending everything under the PM model — the #1475
361/// bug) needs this same resolution done independently, here, purely for the
362/// pricing step. Shared with the daemon path (`task::executor`'s own
363/// `resolve_engineer_model`, which now delegates here) so the two paths
364/// can never independently drift on how per-role pricing resolves a model.
365/// What: loads `<agents_dir>/<agent_name>.toml`; on any load failure
366/// (missing/invalid file) falls back to the literal string `"unknown"` —
367/// `crate::perf::cost_usd` degrades gracefully (Sonnet-equivalent pricing)
368/// for an unrecognised model rather than erroring, so a missing agent
369/// config degrades pricing accuracy, not the whole run. When
370/// `model_override` is `Some`, it wins over the config's own model (mirrors
371/// `RunContext`'s override precedence).
372/// Test: `run_task::tests::resolve_agent_model_slug_falls_back_when_config_missing`,
373/// `run_task::tests::resolve_agent_model_slug_honours_override`.
374pub fn resolve_agent_model_slug(
375    agents_dir: &std::path::Path,
376    agent_name: &str,
377    model_override: Option<&str>,
378) -> String {
379    let path = agents_dir.join(format!("{agent_name}.toml"));
380    let Ok(config) = AgentConfig::load(&path) else {
381        return "unknown".to_string();
382    };
383    match model_override {
384        Some(model) => {
385            let ctx = RunContext {
386                model: Some(model.to_string()),
387                ..Default::default()
388            };
389            resolve_model(&config, Some(&ctx))
390        }
391        None => resolve_model(&config, None),
392    }
393}
394
395/// An `AgentRunner` decorator that pins a fixed model for every delegation (#1035).
396///
397/// Why: `DelegateToAgentTool::execute` calls `runner.run` with a default
398/// `RunContext`, so the per-run `--engineer-model` override cannot be threaded
399/// through the tool itself. This decorator injects `RunContext.model` and forwards
400/// to `run_with_context`, so the engineer's loop routes to the pinned slug while
401/// the PM model stays fixed.
402/// What: Holds the inner runner and the pinned model; both `run` and
403/// `run_with_context` set `ctx.model` before delegating.
404/// Test: `run_task::tests::engineer_model_swap_routes_engineer`.
405struct ModelPinningRunner {
406    inner: Arc<dyn AgentRunner>,
407    model: String,
408}
409
410#[async_trait]
411impl AgentRunner for ModelPinningRunner {
412    async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
413        let ctx = RunContext {
414            model: Some(self.model.clone()),
415            ..Default::default()
416        };
417        self.inner.run_with_context(agent_name, task, &ctx).await
418    }
419
420    async fn run_with_context(
421        &self,
422        agent_name: &str,
423        task: &str,
424        ctx: &RunContext,
425    ) -> Result<AgentOutput> {
426        let mut ctx = ctx.clone();
427        ctx.model = Some(self.model.clone());
428        self.inner.run_with_context(agent_name, task, &ctx).await
429    }
430}
431
432/// Drain the shared transcript into an owned `Vec`.
433///
434/// Why: The report owns its transcript; this lifts it out of the shared mutex.
435/// What: Clones the locked vector (empty on a poisoned lock — the run must not
436/// panic while building the report).
437/// Test: Exercised by every end-to-end test.
438fn drain_transcript(transcript: &SharedTranscript) -> Vec<TurnRecord> {
439    transcript.lock().map(|g| g.clone()).unwrap_or_default()
440}
441
442/// Build a `ConfigError` report (PM config missing/invalid).
443///
444/// Why: A configuration failure must produce a faithful report + exit code, not a
445/// panic, so callers can branch on it.
446/// What: Returns a `RunReport` with an empty diff, the (likely empty) transcript,
447/// zero usage, and `ExitCode::ConfigError`; the error text rides in the task line
448/// of the human form via a synthesized note.
449/// Test: `run_task::tests::missing_pm_config_is_config_error`.
450fn config_error_report(
451    params: &RunTaskParams,
452    transcript: &SharedTranscript,
453    err: &str,
454) -> RunReport {
455    RunReport {
456        agent: params.agent.clone(),
457        task: format!("{} [config error: {err}]", params.task),
458        diff: String::new(),
459        transcript: drain_transcript(transcript),
460        usage: crate::perf::TokenUsage::default(),
461        cost_usd: None,
462        exit: ExitCode::ConfigError,
463    }
464}
465
466/// The run's raw outcome: before/after working-tree snapshots plus the PM
467/// loop's own `Result`.
468///
469/// Why: These three values are always produced and consumed together; bundling
470/// them keeps `assemble_report`'s argument count under clippy's
471/// `too_many_arguments` limit (#2265 added an 8th argument,
472/// `redelegation_signal`, that pushed the plain-argument version over it)
473/// without losing any of the fields or their names.
474/// What: Plain data holder, no behaviour.
475/// Test: Exercised through every `assemble_report` test.
476struct RunOutcome {
477    before: diff::Snapshot,
478    after: diff::Snapshot,
479    pm_result: Result<AgentOutput, AgentLoopError>,
480}
481
482/// Assemble the final report from the run's outcome.
483///
484/// Why: Centralises the mapping from (PM loop result, before/after snapshots) to a
485/// `RunReport` with the correct exit code so the success / no-change / failure
486/// branches never drift.
487/// What: On a PM-loop error → `DeadlineExceeded` when the error is specifically
488/// `AgentLoopError::Timeout` (#2207 — distinct from a genuine failure so a
489/// caller can tell "timed out" from "errored"). (#2265 fix #4) Otherwise, when
490/// the error is `AgentLoopError::TurnCapExceeded` OR `redelegation_signal`
491/// reports the re-delegation cap (fix #1) was hit, the diff is computed
492/// (filesystem-based, independent of which turn/attempt produced it) and — if
493/// it is non-empty, i.e. a deliverable actually exists on disk — the outcome
494/// is `ExitCode::Partial`, NOT `RunFailure`; trusty-code cannot generically
495/// verify correctness, so this gates purely on "work was produced", leaving
496/// the downstream bake-off harness to score correctness itself. Every other
497/// PM-loop error (a hard `Llm`/`Cancelled` failure, or ANY error with an empty
498/// diff — including a cap/turn-cap hit that produced nothing) still maps to
499/// `RunFailure`, preserving that path for genuine no-output failures. On
500/// success → compute the diff; empty diff → `NoChanges`, else `Success`.
501/// Usage and cost are aggregated from the transcript and priced PER ROLE —
502/// `pm_model` for `"pm"` turns, `engineer_model` for the delegated engineer's
503/// — per the #1475 bug 1 fix (`aggregate_usage_per_role`), not blended under
504/// one model. #2206: this aggregation now runs on every error path too, so a
505/// `run_failure`, `partial`, or `deadline_exceeded` report still carries the
506/// real usage/cost of every turn that DID complete, rather than a zeroed
507/// placeholder.
508/// Test: `run_task::tests::*` (success, no-change, failure, deadline, and
509/// #2265 partial/cap-reached paths).
510fn assemble_report(
511    params: &RunTaskParams,
512    transcript: &SharedTranscript,
513    pm_model: &str,
514    engineer_model: &str,
515    outcome: RunOutcome,
516    redelegation_signal: &RedelegationCapSignal,
517) -> RunReport {
518    let RunOutcome {
519        before,
520        after,
521        pm_result,
522    } = outcome;
523    let turns = drain_transcript(transcript);
524
525    // A PM-loop error is a runtime failure (or, #2207, a deadline; or, #2265,
526    // a turn-cap/re-delegation-cap hit that still produced a deliverable);
527    // the transcript still reflects whatever turns ran before the error. The
528    // PM's `AgentOutput` content is not needed for the report — the
529    // transcript and diff are the authoritative artifacts. #2206: usage/cost
530    // are aggregated from those completed turns here too, not zeroed.
531    if let Err(e) = pm_result {
532        let (usage, cost) = aggregate_usage_per_role(&turns, pm_model, engineer_model);
533
534        if matches!(e, AgentLoopError::Timeout { .. }) {
535            return RunReport {
536                agent: params.agent.clone(),
537                task: format!("{} [deadline exceeded: {e}]", params.task),
538                diff: String::new(),
539                transcript: turns,
540                usage,
541                cost_usd: Some(cost),
542                exit: ExitCode::DeadlineExceeded,
543            };
544        }
545
546        // #2265 fix #4: a turn-cap or re-delegation-cap terminal condition
547        // must not be blindly reported as `run_failure` when a deliverable
548        // already exists on disk — the diff is filesystem-based, so it is
549        // authoritative regardless of which attempt produced it.
550        let cap_reached = redelegation_signal.is_cap_reached();
551        let is_turn_cap = matches!(e, AgentLoopError::TurnCapExceeded { .. });
552        let rendered_diff = diff::diff_snapshots(&before, &after);
553        let has_deliverable = !rendered_diff.trim().is_empty();
554
555        if (cap_reached || is_turn_cap) && has_deliverable {
556            let label = if cap_reached {
557                format!(
558                    "partial: re-delegation limit reached after {} attempts; partial work \
559                     preserved at {}",
560                    redelegation_signal.attempts(),
561                    params.project.display()
562                )
563            } else {
564                "partial: PM turn cap exceeded but a deliverable was produced".to_string()
565            };
566            return RunReport {
567                agent: params.agent.clone(),
568                task: format!("{} [{label}: {e}]", params.task),
569                diff: rendered_diff,
570                transcript: turns,
571                usage,
572                cost_usd: Some(cost),
573                exit: ExitCode::Partial,
574            };
575        }
576
577        // Genuine failure: no deliverable exists, or the error is neither a
578        // turn cap nor a re-delegation-cap hit (e.g. a hard `Llm`/`Cancelled`
579        // failure). This path is intentionally left mapped to `RunFailure` —
580        // "Keep genuine no-output failures mapped to RunFailure" per #2265.
581        // When the cap WAS reached but produced nothing reusable, the label
582        // still names that (so an operator/log reader is not left guessing
583        // whether this was an opaque crash or an exhausted, reuse-aware
584        // retry budget), even though the exit code itself is unchanged.
585        let label = if cap_reached {
586            format!(
587                "run failure (re-delegation limit reached after {} attempts, no deliverable \
588                 produced)",
589                redelegation_signal.attempts()
590            )
591        } else {
592            "run failure".to_string()
593        };
594        return RunReport {
595            agent: params.agent.clone(),
596            task: format!("{} [{label}: {e}]", params.task),
597            diff: String::new(),
598            transcript: turns,
599            usage,
600            cost_usd: Some(cost),
601            exit: ExitCode::RunFailure,
602        };
603    }
604
605    let rendered_diff = diff::diff_snapshots(&before, &after);
606
607    // Sum usage across every recorded PM + engineer turn, pricing each turn
608    // against its OWN role's resolved model (#1475 bug 1 fix). The PM's own
609    // `AgentOutput.usage` omits the engineer's tokens (they return as a
610    // tool-result string), so the transcript is the faithful total.
611    let (total_usage, cost) = aggregate_usage_per_role(&turns, pm_model, engineer_model);
612
613    let exit = if rendered_diff.trim().is_empty() {
614        ExitCode::NoChanges
615    } else {
616        ExitCode::Success
617    };
618
619    RunReport {
620        agent: params.agent.clone(),
621        task: params.task.clone(),
622        diff: rendered_diff,
623        transcript: turns,
624        usage: total_usage,
625        cost_usd: Some(cost),
626        exit,
627    }
628}