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
16pub(crate) mod diff;
17mod recorder;
18mod redelegation;
19mod report;
20
21#[cfg(test)]
22mod tests;
23
24use std::path::{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, CompactionConfig};
32use crate::agents::AgentConfig;
33use crate::agents::skill_refs::user_skill_refs_dir;
34use crate::llm::{DebugCaptureSink, InferenceAdapter, wrap_with_debug_capture};
35use crate::mode::HarnessMode;
36use crate::project_context::load_project_context;
37use crate::prompt::assemble_system_prompt_for_mode;
38use crate::provider::{
39    resolve_context_window, resolve_deadline_secs, resolve_max_tokens, resolve_model,
40    resolve_model_with_override,
41};
42use crate::runner::{InProcessAgentRunner, RegistryFactory};
43use crate::skills::{FsSkillResolver, format_skill_catalog, locate_skills_dir};
44use crate::tools::{
45    AgentOutput, AgentRunner, BashTool, DelegateToAgentTool, EditTool, EngineerCompletionSignal,
46    FinishTaskTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, RunContext, SkillResolver,
47    ToolRegistry, TrustySearchTool, UseSkillTool, WriteFileTool, WriteFilesTool,
48};
49
50pub use recorder::{RecordingLlmClient, SharedTranscript, TurnRecord};
51pub use redelegation::{MAX_REDELEGATIONS, RedelegationCapSignal};
52pub use report::{ExitCode, RunReport, aggregate_usage_per_role};
53
54/// Default bash timeout for the engineer's tools, in seconds.
55const ENGINEER_BASH_TIMEOUT_SECS: u64 = 120;
56
57/// The delegated engineer's agent name (matches
58/// `task::executor::ENGINEER_AGENT_NAME`, the daemon path's own copy of this
59/// same literal — kept as two constants, not one shared item, since neither
60/// module depends on the other and a shared constant would be a heavier
61/// coupling than the two paths' otherwise-independent module boundaries
62/// warrant).
63const ENGINEER_AGENT_NAME: &str = "python-engineer";
64
65/// Fire-and-forget best-effort trusty-search indexing of a task's working
66/// project, at task/session START (trusty-search-first discovery, PR B).
67///
68/// Why: a tcode run's answers are far better when the working project is
69/// discoverable via trusty-search's `search`/`grep`/`get_call_chain` tools, but
70/// nothing previously ensured the project's index existed and was populated —
71/// that register-and-reindex logic lived only in trusty-mpm's session launch.
72/// This shares the ONE promoted implementation
73/// ([`trusty_common::search_index::ensure_project_indexed`]) so the two crates
74/// can never diverge. It runs at task start, detached, so the index is built
75/// WHILE the agent loop proceeds rather than blocking it. Fail-open by design:
76/// the shared helper logs-and-swallows every daemon/HTTP error, so a missing or
77/// slow trusty-search daemon never affects the run.
78/// What: indexes `project` UNCONDITIONALLY — git is a nice-to-have for tcode,
79/// not a requirement (owner directive), and trusty-search's own orphan-reaper
80/// already garbage-collects indexes for scratch directories that get deleted,
81/// so there is no cost to indexing a non-git or short-lived working directory.
82/// [`trusty_common::search_index::ensure_project_indexed`] already resolves a
83/// sensible root and index id whether or not `project` is inside a git repo.
84/// Spawns a detached OS thread that calls the shared helper (which itself runs
85/// the blocking HTTP on its own short-timeout threads) and returns immediately,
86/// so the caller never waits on the network.
87/// After warming, this also SURFACES the resulting index readiness to the
88/// session (issue #2784): a cold-indexed large repo has a real semantic
89/// warm-up window (lexical ready in seconds, semantic embedding `InProgress`
90/// for minutes), so a daily-driver `tcode` session that starts querying
91/// immediately would otherwise get lexical-only results with no signal. The
92/// detached thread probes `GET /indexes/{id}/status` right after triggering the
93/// warm and emits ONE `tracing` line (via the shared
94/// [`trusty_common::search_readiness::log_index_readiness`]) describing which
95/// lanes are ready — `warn` while semantic is still warming, `info` once it is
96/// ready. Same fail-open contract: no daemon ⇒ no log, never a block.
97///
98/// The readiness is ALSO handed to the optional `on_readiness` observer, which
99/// is how the daemon path (`task::executor`) turns it into a
100/// `session.attach`able `Event::IndexReadiness` for the UI — the stderr log
101/// alone is unreachable to any API consumer. The observer is passed the raw
102/// `Option`: `None` (no daemon / undrivable id) is itself meaningful — it means
103/// an empty search result is not evidence of absence — so it is reported rather
104/// than swallowed. `run_task`'s own CLI path passes `None` and keeps the
105/// pre-existing log-only behaviour exactly. Taking a callback (rather than a
106/// `SessionRegistry`) is what keeps this module free of a dependency on the
107/// higher-level session layer, mirroring `agent_loop::sink`'s layering rule.
108///
109/// Test: the promoted helper's fail-open + no-daemon + non-git-root behaviour is
110/// unit-tested in `trusty_common::search_index::tests`; the readiness probe/parse
111/// in `trusty_common::search_readiness::tests`. This thin spawn wrapper is
112/// side-effect-only (detached thread) and has no return to assert; see
113/// `spawns_indexing_thread_for_non_git_project_path` for the one thing it IS
114/// mechanically checked for here — that it never short-circuits before spawning,
115/// and `background_indexing_invokes_readiness_observer` for the observer
116/// contract.
117pub(crate) fn ensure_project_indexed_in_background(
118    project: PathBuf,
119    on_readiness: Option<ReadinessObserver>,
120) {
121    std::thread::spawn(move || {
122        // Warm first, then surface the readiness the warm produced so the
123        // session knows whether a semantic search is trustworthy yet (#2784).
124        // `allow_sensitive_path: true` (issue #2914): tcode's working project
125        // is legitimately a `directory` binding that can live under an
126        // OS-temp prefix (issue #2747's bake-off scratch project case), so
127        // this caller opts in to the daemon's temp-dir denylist bypass —
128        // unlike trusty-mpm's session-launch caller, which never needs it.
129        let _ = trusty_common::search_index::ensure_project_indexed(&project, true);
130        // Probe ONCE and use that single snapshot for both surfaces — probing
131        // again for the observer would double the HTTP cost and could report a
132        // lane that flipped between the two reads.
133        let readiness = trusty_common::search_readiness::probe_index_readiness(&project);
134        if let Some(r) = &readiness {
135            trusty_common::search_readiness::log_readiness(r);
136        }
137        if let Some(observe) = on_readiness {
138            observe(readiness);
139        }
140    });
141}
142
143/// Observer handed the result of the background index-readiness probe.
144///
145/// Why: lets the daemon path publish readiness as a session event without
146/// `run_task` (the low-level CLI execution module) taking a dependency on the
147/// `session` layer — the same layering rule `agent_loop::sink` documents.
148/// What: called at most once, on the detached indexing thread, with the probe's
149/// raw fail-open `Option` (`None` == nothing probeable, which is itself a
150/// reportable state). Boxed `FnOnce + Send` because it runs on that thread and
151/// typically carries an `Arc<SessionRegistry>` and a session id.
152/// Test: `run_task::tests::background_indexing_invokes_readiness_observer`.
153pub(crate) type ReadinessObserver =
154    Box<dyn FnOnce(Option<trusty_common::search_readiness::IndexReadiness>) + Send>;
155
156/// Discover the (cheap, metadata-only) skill catalog under `project` and build
157/// a resolver over it (#2924).
158///
159/// Why: this legacy one-shot/bake-off CLI path (`execute_run_task`) predates
160/// #2059's `HarnessMode` plumbing and has no `--mode` flag or `RunTaskParams`
161/// field to thread a resolved mode through — unlike `task::executor`'s
162/// `daily_driver_skills_catalog`, which gates on `HarnessMode::Parity` to
163/// protect that path's benchmark-fairness guarantee, this path never runs in
164/// `Parity` at all, so it always resolves the catalog as if it were
165/// `HarnessMode::DailyDriver` outright, with no mode check needed.
166/// What: Returns `Some((rendered_catalog, resolver))` — the resolver backs
167/// the PM's `use_skill` tool registration and the rendered catalog feeds
168/// `assemble_system_prompt_for_mode`. `skills::discover_skill_metadata` (the
169/// source behind `resolver.metadata()`) falls back to the embedded default
170/// skill catalog (`crate::assets::DEFAULT_SKILLS`, #2895) when `project` has
171/// no (or an empty) `.claude/skills/` directory, so `catalog.is_empty()`
172/// below is no longer reachable in practice — this path effectively always
173/// returns `Some` now, the same as `task::executor`'s
174/// `daily_driver_skills_catalog` in `DailyDriver` mode.
175/// Test: `run_task::tests::use_skill_on_legacy_path_reaches_pm_and_transcript`.
176fn daily_driver_skills_catalog(project: &Path) -> Option<(String, Arc<dyn SkillResolver>)> {
177    let skills_dir = locate_skills_dir(project);
178    let resolver: Arc<dyn SkillResolver> = Arc::new(FsSkillResolver::new(skills_dir));
179    let catalog = format_skill_catalog(&resolver.metadata());
180    if catalog.is_empty() {
181        None
182    } else {
183        Some((catalog, resolver))
184    }
185}
186
187/// Inputs to a single `run-task` invocation, parsed from the CLI.
188///
189/// Why: Bundling the inputs keeps `execute_run_task`'s signature stable as flags
190/// are added and lets the binary layer construct one value from clap.
191/// What: `agent` is the top-level (PM) agent name; `task` is the request; `project`
192/// is the canonical project root; `agents_dir` is where `<agent>.md` live;
193/// `engineer_model` is the optional per-run engineer model override (#1035).
194/// Test: `run_task::tests` build these directly.
195#[derive(Debug, Clone)]
196pub struct RunTaskParams {
197    /// Top-level agent name (typically `"pm"`).
198    pub agent: String,
199    /// Free-form task description.
200    pub task: String,
201    /// Canonical project root.
202    pub project: PathBuf,
203    /// Directory holding `<agent>.md` configs.
204    pub agents_dir: PathBuf,
205    /// Optional per-run engineer model override (#1035). `None` routes the
206    /// engineer via its own config model.
207    pub engineer_model: Option<String>,
208    /// (#8030) Optional per-run override for the TOP-LEVEL agent's own model.
209    ///
210    /// Why: `--engineer-model` only rewired the delegated runner, so the
211    /// top-level agent's calls could be repointed only by hand-editing the
212    /// deployed `<agent>.md`. This is the CLI/API-reachable half #8030 names.
213    /// What: already through [`crate::provider::resolve_pm_model_override`]'s
214    /// flag-then-env tiers by the time it reaches here; `None` leaves
215    /// [`crate::provider::resolve_model`]'s own ladder (front matter, then
216    /// `DEFAULT_MODEL`) untouched. A short alias (`opus`/`sonnet`/`haiku`) is
217    /// normalised at the point of use, same as `engineer_model`.
218    /// Test: `run_task::tests::pm_model_override_pins_the_pm_loops_model`,
219    /// `run_task::tests::absent_pm_model_override_uses_the_agent_config_model`.
220    pub pm_model: Option<String>,
221    /// (#8128) Optional per-run override for the PM loop's turn cap. `None`
222    /// keeps [`crate::agent_loop::AgentLoopConfig`]'s built-in 8, so an
223    /// absent flag changes nothing. Already validated (non-zero) by
224    /// [`crate::provider::resolve_max_turns`] before it reaches here.
225    /// Test: `run_task::tests::max_turns_override_raises_the_pm_turn_cap`.
226    pub max_turns: Option<u32>,
227    /// Optional per-run wall-clock deadline override, in seconds (#2207).
228    /// `None` falls through to [`crate::provider::resolve_deadline_secs`]'s
229    /// env-var/default tiers — see that function's docs for the full
230    /// precedence. Applied to BOTH the PM's own loop and the delegated
231    /// engineer's loop (`build_engineer_runner`).
232    pub deadline_secs: Option<u64>,
233    /// (#7948) What this HEADLESS run does with an agent's `ask` rule. A
234    /// one-shot CLI run has no client, so `PermissionMode::Default` refuses
235    /// the call and `AllowAsks` (`--permission-mode allow-asks` or
236    /// `TCODE_PERMISSION_MODE=allow-asks`) permits it. A `deny` is refused
237    /// either way.
238    pub permission_mode: crate::permissions::PermissionMode,
239    /// (#8031) Run the named top-level agent ALONE: `true` swaps
240    /// [`DelegateToAgentTool`] on the PM registry for that agent's own tcode
241    /// tools.
242    ///
243    /// Why: `run-task engineer <task>` still advertised `delegate_to_agent`,
244    /// and the model self-delegated read/write work instead of doing it — a
245    /// guaranteed single-agent run was not expressible. Dropping the tool
246    /// alone is not enough: `read_file`, `write_file`, `edit` and `bash` only
247    /// ever existed on the DELEGATED agent's per-delegation registry.
248    /// What: `true` skips the delegate tool and merges in the set
249    /// [`crate::runner::agent_registry`] builds for [`Self::agent`] — the SAME
250    /// `ProjectToolFactory` output, narrowed by the SAME `tools.allowed` gate,
251    /// a delegation of that agent would get; the loop's existing
252    /// `PermissionGate` (already minted from this agent's config) then decides
253    /// each call. `false` (the default every pre-#8031 caller gets) registers
254    /// the delegate tool exactly as before and merges nothing.
255    /// Test: `run_task::tests::no_delegate_run_omits_delegate_tool`,
256    /// `run_task::tests::no_delegate_run_registers_the_agents_own_tools`,
257    /// `run_task::tests::default_run_registers_delegate_tool`.
258    pub no_delegate: bool,
259}
260
261/// Execute a `run-task` end-to-end and return the rendered report.
262///
263/// Why: The single orchestration entry point the binary calls (with a real
264/// `LlmClient`) and tests call (with a scripted mock). Keeping the LLM client as
265/// an injected `Arc<dyn InferenceAdapter>` is what makes the whole path testable
266/// offline without a network call or an API key.
267/// What: Loads the PM config, assembles its prompt (BASE + PM prompt + project
268/// `CLAUDE.md`), builds the engineer runner (fs/bash scoped to the project, with
269/// the optional per-run model override), wraps it in the PM's
270/// `DelegateToAgentTool`, snapshots the working tree, runs the PM `AgentLoop`
271/// (#2265 fix #5: wired with `with_stop_signal` against the SAME
272/// `redelegation_signal` the engineer runner shares, so the PM stops issuing
273/// `delegate_to_agent` calls the turn after the re-delegation cap latches
274/// instead of spinning through its remaining turns on doomed retries),
275/// snapshots again, and assembles a `RunReport` (diff + transcript + usage/cost +
276/// exit code). A PM-config or loop error yields a `ConfigError`/`RunFailure`
277/// report rather than a panic.
278/// (#8031) `params.no_delegate` skips the `DelegateToAgentTool` registration
279/// and merges the named agent's own tool set onto the PM registry instead, so
280/// the agent that runs alone can actually do the work.
281/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
282/// `diff_reflects_engineer_file_change`, `usage_and_cost_aggregate_end_to_end`,
283/// `exit_code_reflects_run_failure`,
284/// `run_wide_ceiling_stops_the_pm_loop_and_ends_partial_promptly`,
285/// `no_delegate_run_omits_delegate_tool`,
286/// `no_delegate_run_registers_the_agents_own_tools`,
287/// `default_run_registers_delegate_tool`.
288pub async fn execute_run_task(params: RunTaskParams, llm: Arc<dyn InferenceAdapter>) -> RunReport {
289    // Trusty-search-first discovery (PR B): at task START, best-effort/detached,
290    // ensure the working project is indexed so `search`/`grep` are useful while
291    // the loop below proceeds. Fail-open, git-optional — see the helper's docs.
292    // CLI path: no session to publish an event to, so readiness stays
293    // log-only exactly as before.
294    ensure_project_indexed_in_background(params.project.clone(), None);
295
296    let transcript: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
297
298    // #2264: resolve the (optional) full wire-level debug-capture sink once
299    // per run, shared by BOTH the pm and engineer wrappers below so a
300    // directory-mode capture lands in one file with a single globally
301    // ordered turn sequence — mirrors `transcript`'s own "one shared
302    // accumulator per run" shape. `None` when `TCODE_DEBUG_TRANSCRIPT` is
303    // unset (the default): `wrap_with_debug_capture` then returns each
304    // inner client unchanged, so this costs nothing when disabled.
305    let debug_sink: Option<Arc<DebugCaptureSink>> = DebugCaptureSink::from_env();
306
307    // Load the PM config; a missing/invalid config is a configuration error.
308    // (#3046) Routes through the shared disk-then-embedded resolver so a
309    // top-level agent name that is only in the embedded roster (e.g.
310    // `engineer`, `rust-engineer`) resolves here too, not just via
311    // `load_all_agents`'s dir-wide scan. Note the embedded roster has no
312    // `pm` entry, so `run-task pm ...` still requires a disk `pm.md` — only
313    // `run-task engineer` / `run-task rust-engineer` etc. exercise the new
314    // fallback.
315    let pm_config = match crate::agents::resolve_agent(&params.agents_dir, &params.agent) {
316        Ok(cfg) => cfg,
317        Err(e) => return config_error_report(&params, &transcript, &format!("{e}")),
318    };
319
320    // Load project context (#1033) — absent file is fine.
321    let project_context = load_project_context(&params.project);
322
323    // #8030: the PM's own model, with the `--pm-model`/`TCODE_PM_MODEL`
324    // override ahead of the agent's front matter.
325    let pm_model = resolve_model_with_override(&pm_config, params.pm_model.as_deref());
326
327    // #2207: resolve the run's wall-clock deadline once, applied to BOTH the
328    // PM's own loop (below) and the delegated engineer's loop
329    // (`build_engineer_runner`, via `with_timeout_secs`).
330    let deadline_secs = resolve_deadline_secs(params.deadline_secs);
331
332    // (#2265) The re-delegation cap signal is shared between the engineer
333    // runner's retry decorator (`RedelegatingRunner`, wired inside
334    // `build_engineer_runner`) and `assemble_report` below, so a cap-hit run
335    // gets a clean terminal report regardless of what the PM's own loop
336    // subsequently does.
337    let redelegation_signal = RedelegationCapSignal::new();
338
339    // (#2683) The engineer-completion latch is shared between the PM's
340    // `DelegateToAgentTool` (which sets it when a delegation returns an explicit
341    // successful `finish_task`, and refuses any subsequent re-delegation once
342    // set) and `assemble_report` below (which reports success rather than
343    // partial for a run the engineer already completed). This is what stops a
344    // gratuitous post-finish re-verify round from mislabeling a complete,
345    // all-tests-passing run as `partial`/exit-6.
346    let completion_signal = EngineerCompletionSignal::new();
347
348    // #2924: discover the (cheap, metadata-only) skill catalog and, mirroring
349    // `task::executor::run_and_record`'s DailyDriver-only wiring, register
350    // `use_skill` so the PM can lazily fetch a skill's full body on demand.
351    // This CLI path has no `--mode`/Parity guarantee to protect (see
352    // `daily_driver_skills_catalog`'s own docs), so it always resolves the
353    // catalog as if running under `HarnessMode::DailyDriver`.
354    let skills_catalog = daily_driver_skills_catalog(&params.project);
355
356    // Build the engineer runner, scoped to the project working dir, sharing the
357    // transcript (engineer turns are tagged "python-engineer"). The full
358    // `(catalog, resolver)` pair is threaded through (rather than just the
359    // catalog string) so `ProjectToolFactory` can register `use_skill` against
360    // the SAME resolver instance the catalog was rendered from (experimental,
361    // refs #2892).
362    let engineer_runner = build_engineer_runner(
363        wrap_with_debug_capture(Arc::clone(&llm), ENGINEER_AGENT_NAME, debug_sink.as_ref()),
364        &params,
365        project_context.clone(),
366        skills_catalog.clone(),
367        Arc::clone(&transcript),
368        deadline_secs,
369        redelegation_signal.clone(),
370    );
371
372    // The PM's tool registry: the delegate tool (the PM orchestrates; the
373    // engineer does the file work) plus `finish_task` (#2072) so the PM can
374    // signal completion with a structured report instead of relying solely on
375    // the implicit no-tool-call convention. Pre-flight validation uses the
376    // agents dir.
377    let mut pm_registry = ToolRegistry::new();
378    // #8031: `--no-delegate` makes this a single-agent run — the tool is never
379    // registered, so the named agent cannot hand the task to the engineer.
380    if !params.no_delegate {
381        pm_registry.register(Arc::new(
382            DelegateToAgentTool::new(engineer_runner)
383                .with_config_dir(params.agents_dir.clone())
384                // (#2683) refuse a re-delegation once the engineer has completed.
385                .with_completion_signal(completion_signal.clone()),
386        ));
387    }
388    pm_registry.register(Arc::new(FinishTaskTool::new()));
389    // #2924: mirrors `task::executor::run_and_record` — only the PM registers
390    // `use_skill`; the delegated engineer inherits the catalog/prompt but not
391    // the tool itself.
392    if let Some((_, resolver)) = &skills_catalog {
393        pm_registry.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
394    }
395    // #8031: with no engineer to delegate to, the named agent must carry its
396    // OWN tcode tools or the run has nothing to work with. Merged AFTER the
397    // harness tools above so they win the `finish_task`/`use_skill` overlap.
398    if params.no_delegate {
399        let factory = project_tool_factory(&params, &skills_catalog);
400        pm_registry.merge_missing(
401            crate::runner::agent_registry(&factory, &pm_config, &RunContext::default())
402                .await
403                .as_ref(),
404        );
405    }
406
407    // The PM's loop uses a transcript-recording client tagged "pm".
408    let pm_llm: Arc<dyn InferenceAdapter> = Arc::new(RecordingLlmClient::new(
409        wrap_with_debug_capture(Arc::clone(&llm), "pm", debug_sink.as_ref()),
410        "pm",
411        Arc::clone(&transcript),
412    ));
413
414    // Inject DOC-28 catch-up digest as seed context into the PM prompt (#1762 PR2).
415    // The catch-up engine is async and fail-open: if the daemon is offline or the
416    // project has no activity, it returns None and the prompt is assembled without
417    // the section.  Sub-agents are NOT wired here; only the PM receives this digest.
418    let catchup_ctx = crate::catchup::pm_catchup_context(&params.project).await;
419
420    // #2924: mirrors `task::executor::run_and_record` — always resolves as
421    // `HarnessMode::DailyDriver` (see `daily_driver_skills_catalog`'s docs
422    // for why this path never needs to resolve `Parity`).
423    // #4602: gated on the PM's OWN registry — a delegating PM carries harness
424    // tools only, so it must not be told to call `glob`/`grep`/`list_dir`.
425    let pm_system = assemble_system_prompt_for_mode(
426        HarnessMode::DailyDriver,
427        &pm_config,
428        project_context.as_deref(),
429        catchup_ctx.as_deref(),
430        skills_catalog.as_ref().map(|(catalog, _)| catalog.as_str()),
431        Some(&pm_registry),
432    );
433    // (#2265 fix #5, re-scoped by #2852) Once the shared cap latches, every
434    // further `delegate_to_agent` call the PM might issue is a guaranteed dead
435    // end — `RedelegatingRunner` will reject it immediately without even
436    // invoking the engineer. Wiring the SAME signal into the PM's own loop as
437    // a stop condition (checked at the existing turn-boundary, alongside the
438    // #2056 cancellation flag) stops the PM from spending its remaining
439    // `max_turns` issuing those doomed calls one per turn — the bake-off L1
440    // regression fix #5 closes (see `redelegation` module docs for the
441    // full before/after).
442    //
443    // #2852 is what makes that "guaranteed dead end" premise TRUE. This hook
444    // is unrecoverable by construction — the PM never gets another turn — so
445    // it may only ever fire on a condition no subsequent delegation could
446    // clear. `is_cap_reached()` now latches ONLY on the run-wide
447    // `MAX_FAILED_INVOCATIONS` ceiling — a run whose delegations have failed
448    // that many times over, which is exactly such a condition. Successful
449    // invocations never feed it, no matter how many the PM makes.
450    // It deliberately does NOT latch on a single delegation exhausting its
451    // `MAX_REDELEGATIONS` retries: that is recoverable (a fresh delegation
452    // gets a full budget), and stopping the loop on it is precisely the bug
453    // #2852 fixes — it killed runs whose next call was the real build.
454    // `assemble_report` still maps a cap- OR retry-exhausted, deliverable-
455    // bearing run to `ExitCode::Partial` regardless of which `AgentLoopError`
456    // variant the PM's loop returns, so this purely trims wasted turns — it
457    // does not change the reported outcome.
458    let stop_signal = redelegation_signal.clone();
459    let mut pm_loop_config = AgentLoopConfig {
460        model: pm_model.clone(),
461        max_tokens: resolve_max_tokens(&pm_config),
462        timeout_secs: deadline_secs,
463        // #2308: model-aware compaction threshold — see
464        // `CompactionConfig::for_context_window`'s doc for why the
465        // struct-update `..AgentLoopConfig::default()` below must not be
466        // allowed to silently supply the flat, model-blind default here.
467        compaction: CompactionConfig::for_context_window(resolve_context_window(&pm_model)),
468        // #2346: `cadence` stays the `..AgentLoopConfig::default()` value
469        // (`None`) here, deliberately — the legacy one-shot/bake-off
470        // `run-task` CLI path is explicitly out of scope for the cadence
471        // compressor (epic #2343 scopes it to the daemon-driven,
472        // persistent-session path in `task::executor::run_and_record`
473        // only), so this run sees zero behaviour change from before
474        // #2346.
475        ..AgentLoopConfig::default()
476    };
477    // #8128: `--max-turns`/`TCODE_MAX_TURNS`. Applied after the literal so an
478    // ABSENT override leaves `AgentLoopConfig::default()`'s own cap of 8.
479    if let Some(turns) = params.max_turns {
480        pm_loop_config.max_turns = turns;
481    }
482
483    let pm_loop = AgentLoop::new(pm_loop_config, pm_llm, Arc::new(pm_registry))
484        .with_stop_signal(Arc::new(move || stop_signal.is_cap_reached()))
485        // (UI Phase 1) Attribute the PM's tool events. Inert on this legacy
486        // one-shot/bake-off CLI path — it attaches no `ToolEventSink`, so nothing
487        // reads the attribution today. Set anyway so the identity is correct the
488        // moment a sink ever is attached here, rather than silently emitting
489        // `UNATTRIBUTED_AGENT`.
490        // #8031: a `--no-delegate` run's tool calls are the NAMED agent's own, so
491        // they must carry its name, not the orchestrator role it is not playing.
492        .with_agent(if params.no_delegate {
493            params.agent.clone()
494        } else {
495            "pm".to_string()
496        })
497        // (DOC-39 AC-13) Same reasoning as `agent`: inert today (no sink on this
498        // path), set anyway so the PM has a stable identity the moment a sink is
499        // ever attached. Unlike `task::executor`'s session-scoped id, this
500        // one-shot CLI invocation has no session — a fresh UUID per invocation is
501        // the natural equivalent (this whole run IS the "session").
502        .with_agent_id(uuid::Uuid::new_v4().to_string())
503        // #7948: the PM's own calls are gated too, headless. The project is the
504        // run's working root, so a relative path rule also decides the absolute
505        // in-root spelling of the same file.
506        .with_permission_gate(Arc::new(
507            crate::permissions::PermissionContext::headless(params.permission_mode)
508                .with_root(params.project.clone())
509                .gate_for(Arc::new(pm_config.clone()), "pm"),
510        ))
511        // #2279: the PM never calls `bash` itself (its registry above is
512        // `delegate_to_agent` + `finish_task` only), so its verify-before-finish
513        // gate must scan the delegated engineer's transcript instead of its
514        // own — `verify_gate::pm_finish_gate` does exactly that against the
515        // SAME shared `transcript` the engineer's `RecordingLlmClient` records
516        // into (see `build_engineer_runner` above).
517        // #8206: the bound project root, so the PM's gate cannot refuse a
518        // finish on a root with no detectable test suite.
519        .with_finish_gate(crate::verify_gate::pm_finish_gate(
520            Arc::clone(&transcript),
521            Some(params.project.clone()),
522        ));
523
524    // Snapshot before, run the PM, snapshot after.
525    let before = diff::capture_snapshot(&params.project);
526    let pm_result = pm_loop.run(&pm_system, &params.task).await;
527    let after = diff::capture_snapshot(&params.project);
528
529    // Resolve the engineer's model independently (#1475 bug 1) so the report
530    // prices its turns at its OWN rate rather than blending everything
531    // under the PM model.
532    let engineer_model = resolve_agent_model_slug(
533        &params.agents_dir,
534        ENGINEER_AGENT_NAME,
535        params.engineer_model.as_deref(),
536    );
537
538    assemble_report(
539        &params,
540        &transcript,
541        &pm_model,
542        &engineer_model,
543        RunOutcome {
544            before,
545            after,
546            pm_result,
547        },
548        &redelegation_signal,
549        &completion_signal,
550    )
551}
552
553/// Build the in-process engineer runner with project-scoped fs/bash tools.
554///
555/// Why: The engineer must write/read/run inside the project and see the same
556/// project context as the PM. This wires a `RegistryFactory` that constructs fs +
557/// bash tools scoped to the project dir plus the project context, then routes the
558/// result through the per-run model-override seam (`apply_engineer_model_override`).
559/// `deadline_secs` (#2207) is the SAME resolved wall-clock budget applied to the
560/// delegating PM's own loop, so a raised deadline covers the whole run, not just
561/// the PM's half of it. (#2265) The outermost layer is
562/// `redelegation::RedelegatingRunner`, which internally retries a failed
563/// attempt (reuse-hint-augmented, capped at `redelegation::MAX_REDELEGATIONS`)
564/// entirely within one `AgentRunner::run`/`run_with_context` call — this is
565/// the chosen "decouple retries from PM turns" design for fix #3: every
566/// retry happens inside a SINGLE `delegate_to_agent` tool dispatch, so it
567/// never consumes any of the PM's own `AgentLoopConfig::max_turns` budget
568/// (left at its crate default of 8 — raising it was the alternative design,
569/// rejected here because the cap in fix #1 is a cleaner, purpose-built ceiling
570/// than a bigger, still-somewhat-arbitrary PM turn budget would be).
571/// What: Returns an `Arc<dyn AgentRunner>` the `DelegateToAgentTool` dispatches
572/// to. The engineer's own LLM turns are recorded under the "python-engineer" role.
573/// `redelegation_signal` is shared with `assemble_report` via the caller.
574/// `skills_catalog` (#2924) is the same rendered `(catalog, resolver)` pair the
575/// PM's own prompt/registry are built from, threaded through so the delegated
576/// engineer's DailyDriver prompt also sees the catalog text AND — as of this
577/// experimental change (refs #2892) — so `ProjectToolFactory` can register
578/// `use_skill` against the SAME resolver instance, rather than a second,
579/// independently-constructed one. This is a deliberate divergence from
580/// `task::executor::build_engineer_runner`, which still defers wiring
581/// `use_skill` into the engineer's own per-delegation registry; see that
582/// function's docs for the daemon path's reasoning.
583/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
584/// `run_task::tests::use_skill_on_legacy_path_reaches_pm_and_transcript`,
585/// `run_task::tests::use_skill_on_legacy_path_reaches_engineer_and_transcript`.
586fn build_engineer_runner(
587    llm: Arc<dyn InferenceAdapter>,
588    params: &RunTaskParams,
589    project_context: Option<String>,
590    skills_catalog: Option<(String, Arc<dyn SkillResolver>)>,
591    transcript: SharedTranscript,
592    deadline_secs: u64,
593    redelegation_signal: RedelegationCapSignal,
594) -> Arc<dyn AgentRunner> {
595    let engineer_llm: Arc<dyn InferenceAdapter> = Arc::new(RecordingLlmClient::new(
596        llm,
597        ENGINEER_AGENT_NAME,
598        transcript,
599    ));
600
601    let factory: Arc<dyn RegistryFactory> = Arc::new(project_tool_factory(params, &skills_catalog));
602
603    let mut runner = InProcessAgentRunner::new(engineer_llm, factory, params.agents_dir.clone())
604        .with_timeout_secs(deadline_secs)
605        // #8206: the project the engineer's tools are scoped to, so its own
606        // verify-before-finish gate probes the right directory.
607        .with_work_root(params.project.clone())
608        // #2924: mirrors `task::executor::build_engineer_runner` — this path
609        // always resolves as `HarnessMode::DailyDriver` (see
610        // `daily_driver_skills_catalog`'s docs).
611        .with_mode(HarnessMode::DailyDriver)
612        // #7948: headless — no broker, so a delegated agent's `ask` resolves
613        // at once per `params.permission_mode`. The root is the project the
614        // engineer's tools are scoped to, matching its gate's path rules.
615        .with_permissions(
616            crate::permissions::PermissionContext::headless(params.permission_mode)
617                .with_root(params.project.clone()),
618        );
619    if let Some(ctx) = project_context {
620        runner = runner.with_project_context(ctx);
621    }
622    if let Some((catalog, _)) = skills_catalog {
623        runner = runner.with_skills_catalog(catalog);
624    }
625    let pinned = apply_engineer_model_override(Arc::new(runner), params);
626    Arc::new(redelegation::RedelegatingRunner::new(
627        pinned,
628        redelegation_signal,
629        params.project.clone(),
630    ))
631}
632
633/// The project-scoped tool factory for this run.
634///
635/// Why (#8031): two call sites now need the identical factory — the delegated
636/// engineer's runner, and a `--no-delegate` run assembling the top-level
637/// agent's own tools — so its three fields are constructed in one place rather
638/// than transcribed twice.
639/// What: binds `params.project` as the fs/bash scope, the run's shared skill
640/// resolver (`None` when no catalog resolved), and a fresh per-factory MCP
641/// `OnceCell`.
642/// Test: `run_task::tests::no_delegate_run_registers_the_agents_own_tools`.
643fn project_tool_factory(
644    params: &RunTaskParams,
645    skills_catalog: &Option<(String, Arc<dyn SkillResolver>)>,
646) -> ProjectToolFactory {
647    ProjectToolFactory {
648        project: params.project.clone(),
649        skill_resolver: skills_catalog
650            .as_ref()
651            .map(|(_, resolver)| Arc::clone(resolver)),
652        mcp: tokio::sync::OnceCell::new(),
653    }
654}
655
656/// Builds the engineer's project-scoped tool registry for each delegation.
657///
658/// Why: The engineer needs real file and shell tools that cannot escape the
659/// project root, plus (#2072) `finish_task` so it can signal completion with a
660/// structured report. This factory constructs `read_file`, `write_file`,
661/// `write_files` (#2681 batch write), `edit`, the `glob`/`grep`/`list_dir`
662/// exploration tools (#1027), and `bash` all scoped to `self.project`, so the
663/// engineer operates only inside the project working tree; `finish_task` has no
664/// filesystem footprint and needs no scoping. `skill_resolver` (experimental,
665/// refs #2892) is the SAME `Arc<dyn SkillResolver>` the PM's own `use_skill`
666/// tool and the rendered catalog were built from — `None` when
667/// `daily_driver_skills_catalog` found no project skills, mirroring the PM's
668/// own conditional registration in `execute_run_task`.
669/// What: Implements `RegistryFactory::build`, returning an `Arc<ToolRegistry>`
670/// with every tool; the runner then gates them by the engineer's
671/// `tools.allowed`. When `skill_resolver` is `Some`, `use_skill` is registered
672/// too, so the delegated engineer can lazily fetch a skill's full body on
673/// demand, the same way the PM already can (#2924).
674/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer` (the engineer's
675/// `write_file` actually writes into the project);
676/// `run_task::tests::use_skill_on_legacy_path_reaches_engineer_and_transcript`
677/// (the engineer's `use_skill` registration and invocation).
678struct ProjectToolFactory {
679    project: PathBuf,
680    skill_resolver: Option<Arc<dyn SkillResolver>>,
681    /// #5428: the operator's configured MCP servers, spawned at most ONCE per
682    /// run and shared by every delegation's registry. A `OnceCell` rather than
683    /// an eager field because the load is async and this factory is built from
684    /// a sync helper; the first `build` pays for it, before the agent loop, and
685    /// no turn ever does.
686    mcp: tokio::sync::OnceCell<crate::mcp::McpToolSet>,
687}
688
689#[async_trait]
690impl RegistryFactory for ProjectToolFactory {
691    async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
692        // #2068: resolve the engineer's model slug so `EditTool` can pick its
693        // per-model edit-format fallback order (see `resolve_model`'s own
694        // precedence docs — RunContext override > agent config > default).
695        let model_slug = resolve_model(agent, Some(ctx));
696        let mut reg = ToolRegistry::new();
697        // #7727: embedded agents' skill pointers resolve outside the project.
698        reg.register(Arc::new(
699            ReadFileTool::new(&self.project).with_skill_refs(user_skill_refs_dir()),
700        ));
701        reg.register(Arc::new(WriteFileTool::new(&self.project)));
702        // #2681: batch-write decouples turn-count from file-count.
703        reg.register(Arc::new(WriteFilesTool::new(&self.project)));
704        reg.register(Arc::new(
705            EditTool::new(&self.project).with_model_slug(model_slug),
706        ));
707        // #1027: native file discovery so the engineer stops shelling out to
708        // find/grep/ls (the dominant bake-off agent-turn sink).
709        reg.register(Arc::new(GlobTool::new(&self.project)));
710        reg.register(Arc::new(GrepTool::new(&self.project)));
711        reg.register(Arc::new(ListDirTool::new(&self.project)));
712        // PR A (#2689): trusty-search-backed conceptual discovery as the PRIMARY
713        // path; the local glob/grep tools above are the fail-open FALLBACK. The
714        // `run_task` CLI is always the daily-driver path (the parity benchmark
715        // runs through `task::executor`, which gates this on `HarnessMode`), so
716        // registration is unconditional here.
717        reg.register(Arc::new(TrustySearchTool::new(&self.project)));
718        // #5428: every MCP server the operator configured, as
719        // `mcp__<server>__<tool>`. The set is loaded once per run; a broken
720        // config or an unstartable server is reported here and costs only
721        // itself.
722        let mcp = self
723            .mcp
724            .get_or_init(|| crate::mcp::McpToolSet::load(&self.project))
725            .await;
726        crate::mcp::register_configured_tools(&mut reg, mcp).log();
727        reg.register(Arc::new(BashTool::new(
728            Some(self.project.clone()),
729            Duration::from_secs(ENGINEER_BASH_TIMEOUT_SECS),
730        )));
731        reg.register(Arc::new(FinishTaskTool::new()));
732        // Experimental (refs #2892): mirrors the PM's own conditional
733        // `use_skill` registration in `execute_run_task` — only when a skill
734        // catalog actually resolved for this project.
735        if let Some(resolver) = &self.skill_resolver {
736            reg.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
737        }
738        Arc::new(reg)
739    }
740}
741
742/// Apply the per-run engineer-model override to the runner, if any (#1035).
743///
744/// Why: The engineer routes to its own configured model by default. A per-run
745/// `--engineer-model` (or `TCODE_ENGINEER_MODEL`) must reroute *only* the engineer
746/// for that single run — the model-comparison harness varies the engineer model
747/// while the PM model stays fixed. Keeping the override here lets
748/// `build_engineer_runner` stay agnostic to whether a model is pinned.
749/// What: When `params.engineer_model` is `Some`, wraps the runner in a
750/// `ModelPinningRunner` that injects `RunContext.model` on every delegation;
751/// otherwise returns the runner unchanged.
752/// Test: `run_task::tests::engineer_model_swap_routes_engineer`,
753/// `two_runs_route_engineer_to_distinct_slugs`.
754fn apply_engineer_model_override(
755    runner: Arc<dyn AgentRunner>,
756    params: &RunTaskParams,
757) -> Arc<dyn AgentRunner> {
758    match &params.engineer_model {
759        Some(model) => Arc::new(ModelPinningRunner {
760            inner: runner,
761            model: model.clone(),
762        }),
763        None => runner,
764    }
765}
766
767/// Resolve an agent's model slug, honouring an optional per-run override
768/// (#1035, #1475 bug 1 fix's prerequisite).
769///
770/// Why: `InProcessAgentRunner` resolves the engineer's model internally and
771/// does not expose it, so pricing the engineer's turns against its OWN
772/// model (rather than blending everything under the PM model — the #1475
773/// bug) needs this same resolution done independently, here, purely for the
774/// pricing step. Shared with the daemon path (`task::executor`'s own
775/// `resolve_engineer_model`, which now delegates here) so the two paths
776/// can never independently drift on how per-role pricing resolves a model.
777/// What: (#3046) resolves `<agents_dir>/<agent_name>.md` via the shared
778/// disk-then-embedded [`crate::agents::resolve_agent`]; on any resolution
779/// failure (missing everywhere, or an invalid disk/embedded file) falls
780/// back to the literal string `"unknown"` — `crate::perf::cost_usd`
781/// degrades gracefully (Sonnet-equivalent pricing) for an unrecognised
782/// model rather than erroring, so a missing agent config degrades pricing
783/// accuracy, not the whole run. When `model_override` is `Some`, it wins
784/// over the config's own model (mirrors `RunContext`'s override
785/// precedence).
786/// Test: `run_task::tests::resolve_agent_model_slug_falls_back_when_config_missing`,
787/// `run_task::tests::resolve_agent_model_slug_honours_override`.
788pub fn resolve_agent_model_slug(
789    agents_dir: &std::path::Path,
790    agent_name: &str,
791    model_override: Option<&str>,
792) -> String {
793    let Ok(config) = crate::agents::resolve_agent(agents_dir, agent_name) else {
794        return "unknown".to_string();
795    };
796    match model_override {
797        Some(model) => {
798            let ctx = RunContext {
799                model: Some(model.to_string()),
800                ..Default::default()
801            };
802            resolve_model(&config, Some(&ctx))
803        }
804        None => resolve_model(&config, None),
805    }
806}
807
808/// An `AgentRunner` decorator that pins a fixed model for every delegation (#1035).
809///
810/// Why: `DelegateToAgentTool::execute` calls `runner.run` with a default
811/// `RunContext`, so the per-run `--engineer-model` override cannot be threaded
812/// through the tool itself. This decorator injects `RunContext.model` and forwards
813/// to `run_with_context`, so the engineer's loop routes to the pinned slug while
814/// the PM model stays fixed.
815/// What: Holds the inner runner and the pinned model; both `run` and
816/// `run_with_context` set `ctx.model` before delegating.
817/// Test: `run_task::tests::engineer_model_swap_routes_engineer`.
818struct ModelPinningRunner {
819    inner: Arc<dyn AgentRunner>,
820    model: String,
821}
822
823#[async_trait]
824impl AgentRunner for ModelPinningRunner {
825    async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
826        let ctx = RunContext {
827            model: Some(self.model.clone()),
828            ..Default::default()
829        };
830        self.inner.run_with_context(agent_name, task, &ctx).await
831    }
832
833    async fn run_with_context(
834        &self,
835        agent_name: &str,
836        task: &str,
837        ctx: &RunContext,
838    ) -> Result<AgentOutput> {
839        let mut ctx = ctx.clone();
840        ctx.model = Some(self.model.clone());
841        self.inner.run_with_context(agent_name, task, &ctx).await
842    }
843}
844
845/// Drain the shared transcript into an owned `Vec`.
846///
847/// Why: The report owns its transcript; this lifts it out of the shared mutex.
848/// What: Clones the locked vector (empty on a poisoned lock — the run must not
849/// panic while building the report).
850/// Test: Exercised by every end-to-end test.
851fn drain_transcript(transcript: &SharedTranscript) -> Vec<TurnRecord> {
852    transcript.lock().map(|g| g.clone()).unwrap_or_default()
853}
854
855/// Build a `ConfigError` report (PM config missing/invalid).
856///
857/// Why: A configuration failure must produce a faithful report + exit code, not a
858/// panic, so callers can branch on it.
859/// What: Returns a `RunReport` with an empty diff, the (likely empty) transcript,
860/// zero usage, and `ExitCode::ConfigError`; the error text rides in the task line
861/// of the human form via a synthesized note.
862/// Test: `run_task::tests::missing_agent_config_is_config_error`.
863fn config_error_report(
864    params: &RunTaskParams,
865    transcript: &SharedTranscript,
866    err: &str,
867) -> RunReport {
868    RunReport {
869        agent: params.agent.clone(),
870        task: format!("{} [config error: {err}]", params.task),
871        diff: String::new(),
872        transcript: drain_transcript(transcript),
873        usage: crate::perf::TokenUsage::default(),
874        cost_usd: None,
875        exit: ExitCode::ConfigError,
876    }
877}
878
879/// The run's raw outcome: before/after working-tree snapshots plus the PM
880/// loop's own `Result`.
881///
882/// Why: These three values are always produced and consumed together; bundling
883/// them keeps `assemble_report`'s argument count under clippy's
884/// `too_many_arguments` limit (#2265 added an 8th argument,
885/// `redelegation_signal`, that pushed the plain-argument version over it)
886/// without losing any of the fields or their names.
887/// What: Plain data holder, no behaviour.
888/// Test: Exercised through every `assemble_report` test.
889struct RunOutcome {
890    before: diff::Snapshot,
891    after: diff::Snapshot,
892    pm_result: Result<AgentOutput, AgentLoopError>,
893}
894
895/// Assemble the final report from the run's outcome.
896///
897/// Why: Centralises the mapping from (PM loop result, before/after snapshots) to a
898/// `RunReport` with the correct exit code so the success / no-change / failure
899/// branches never drift.
900/// What: (#2683) FIRST — before any error-variant branching — if
901/// `completion_signal` reports the delegated engineer already returned an
902/// EXPLICIT successful `finish_task` completion, the task is genuinely done:
903/// the outcome is `Success` (or `NoChanges` for an empty diff), NEVER
904/// `Partial`/`DeadlineExceeded`/`RunFailure`, regardless of how the PM's own
905/// loop later terminated. This is the data-integrity fix for the bug where a
906/// gratuitous post-finish re-delegation that then ran out of turns/time
907/// mislabeled a complete, all-tests-passing run as `partial`/exit-6. On a
908/// PM-loop error with NO such completion → `DeadlineExceeded` when the error is
909/// specifically `AgentLoopError::Timeout` (#2207 — distinct from a genuine
910/// failure so a caller can tell "timed out" from "errored"). (#2265 fix #4)
911/// Otherwise, when the error is `AgentLoopError::TurnCapExceeded` OR
912/// `redelegation_signal` reports the re-delegation cap (fix #1) was hit, the
913/// diff is computed (filesystem-based, independent of which turn/attempt
914/// produced it) and — if it is non-empty, i.e. a deliverable actually exists on
915/// disk — the outcome is `ExitCode::Partial`, NOT `RunFailure`; trusty-code
916/// cannot generically verify correctness, so this gates purely on "work was
917/// produced", leaving the downstream bake-off harness to score correctness
918/// itself. Every other PM-loop error (a hard `Llm`/`Cancelled` failure, or ANY
919/// error with an empty diff — including a cap/turn-cap hit that produced
920/// nothing) still maps to `RunFailure`, preserving that path for genuine
921/// no-output failures. On success → compute the diff; empty diff → `NoChanges`,
922/// else `Success`.
923/// Usage and cost are aggregated from the transcript and priced PER ROLE —
924/// `pm_model` for `"pm"` turns, `engineer_model` for the delegated engineer's
925/// — per the #1475 bug 1 fix (`aggregate_usage_per_role`), not blended under
926/// one model. #2206: this aggregation now runs on every error path too, so a
927/// `run_failure`, `partial`, or `deadline_exceeded` report still carries the
928/// real usage/cost of every turn that DID complete, rather than a zeroed
929/// placeholder.
930/// Test: `run_task::tests::*` (success, no-change, failure, deadline, and
931/// #2265 partial/cap-reached paths).
932fn assemble_report(
933    params: &RunTaskParams,
934    transcript: &SharedTranscript,
935    pm_model: &str,
936    engineer_model: &str,
937    outcome: RunOutcome,
938    redelegation_signal: &RedelegationCapSignal,
939    completion_signal: &EngineerCompletionSignal,
940) -> RunReport {
941    let RunOutcome {
942        before,
943        after,
944        pm_result,
945    } = outcome;
946    let turns = drain_transcript(transcript);
947
948    // #2683: the authoritative success signal. If the delegated engineer
949    // already reported an EXPLICIT successful `finish_task` completion, the
950    // task is genuinely done — a gratuitous post-finish re-delegation that
951    // subsequently ran the PM's loop out of turns/time (or hit any other
952    // terminal error) must NOT mislabel this complete, correct run as
953    // `partial`/`deadline_exceeded`/`run_failure`. The on-disk diff is the
954    // authoritative deliverable regardless of which turn produced it: a
955    // non-empty diff is `Success`, an empty one is `NoChanges`. This is checked
956    // FIRST, before any PM-error-variant branching, so it overrides every one
957    // of them.
958    if completion_signal.is_completed() {
959        let (usage, cost) = aggregate_usage_per_role(&turns, pm_model, engineer_model);
960        let rendered_diff = diff::diff_snapshots(&before, &after);
961        let exit = if rendered_diff.trim().is_empty() {
962            ExitCode::NoChanges
963        } else {
964            ExitCode::Success
965        };
966        return RunReport {
967            agent: params.agent.clone(),
968            task: params.task.clone(),
969            diff: rendered_diff,
970            transcript: turns,
971            usage,
972            cost_usd: Some(cost),
973            exit,
974        };
975    }
976
977    // A PM-loop error is a runtime failure (or, #2207, a deadline; or, #2265,
978    // a turn-cap/re-delegation-cap hit that still produced a deliverable);
979    // the transcript still reflects whatever turns ran before the error. The
980    // PM's `AgentOutput` content is not needed for the report — the
981    // transcript and diff are the authoritative artifacts. #2206: usage/cost
982    // are aggregated from those completed turns here too, not zeroed.
983    if let Err(e) = pm_result {
984        let (usage, cost) = aggregate_usage_per_role(&turns, pm_model, engineer_model);
985
986        if matches!(e, AgentLoopError::Timeout { .. }) {
987            return RunReport {
988                agent: params.agent.clone(),
989                task: format!("{} [deadline exceeded: {e}]", params.task),
990                diff: String::new(),
991                transcript: turns,
992                usage,
993                cost_usd: Some(cost),
994                exit: ExitCode::DeadlineExceeded,
995            };
996        }
997
998        // #2265 fix #4: a turn-cap or re-delegation-cap terminal condition
999        // must not be blindly reported as `run_failure` when a deliverable
1000        // already exists on disk — the diff is filesystem-based, so it is
1001        // authoritative regardless of which attempt produced it.
1002        //
1003        // #2852 split the one cap flag in two. Reporting must key off BOTH:
1004        // `is_cap_reached` (the run-wide invocation ceiling, which also stops
1005        // the PM loop) and `is_retry_budget_exhausted` (some delegation burned
1006        // all its retries — recoverable, so it does NOT stop the loop, but it
1007        // is still exactly the "engineer was retried to exhaustion" diagnosis
1008        // this label exists to report). Keying off only the former would have
1009        // silently downgraded genuinely retry-exhausted runs to an opaque
1010        // `run_failure` — losing the diagnostics #2852 set out to improve.
1011        let cap_reached = redelegation_signal.is_cap_reached();
1012        let retry_exhausted = redelegation_signal.is_retry_budget_exhausted();
1013        let budget_spent = cap_reached || retry_exhausted;
1014        let is_turn_cap = matches!(e, AgentLoopError::TurnCapExceeded { .. });
1015        let rendered_diff = diff::diff_snapshots(&before, &after);
1016        let has_deliverable = !rendered_diff.trim().is_empty();
1017
1018        if (budget_spent || is_turn_cap) && has_deliverable {
1019            let label = if cap_reached {
1020                // #2852: quote the FAILURE count, which is the ceiling's actual
1021                // input and is exactly the number of invocations that really
1022                // failed — never a pre-incremented dispatch counter, which
1023                // would tell an operator "13" when 12 occurred.
1024                format!(
1025                    "partial: engineer failure ceiling reached after {} failed invocations; \
1026                     partial work preserved at {}",
1027                    redelegation_signal.failed_invocations(),
1028                    params.project.display()
1029                )
1030            } else if retry_exhausted {
1031                format!(
1032                    "partial: re-delegation limit reached after {} attempts; partial work \
1033                     preserved at {}",
1034                    redelegation::MAX_REDELEGATIONS,
1035                    params.project.display()
1036                )
1037            } else {
1038                "partial: PM turn cap exceeded but a deliverable was produced".to_string()
1039            };
1040            return RunReport {
1041                agent: params.agent.clone(),
1042                task: format!("{} [{label}: {e}]", params.task),
1043                diff: rendered_diff,
1044                transcript: turns,
1045                usage,
1046                cost_usd: Some(cost),
1047                exit: ExitCode::Partial,
1048            };
1049        }
1050
1051        // Genuine failure: no deliverable exists, or the error is neither a
1052        // turn cap nor a re-delegation-cap hit (e.g. a hard `Llm`/`Cancelled`
1053        // failure). This path is intentionally left mapped to `RunFailure` —
1054        // "Keep genuine no-output failures mapped to RunFailure" per #2265.
1055        // When the cap WAS reached but produced nothing reusable, the label
1056        // still names that (so an operator/log reader is not left guessing
1057        // whether this was an opaque crash or an exhausted, reuse-aware
1058        // retry budget), even though the exit code itself is unchanged.
1059        let label = if cap_reached {
1060            format!(
1061                "run failure (engineer failure ceiling reached after {} failed invocations, \
1062                 no deliverable produced)",
1063                redelegation_signal.failed_invocations()
1064            )
1065        } else if retry_exhausted {
1066            format!(
1067                "run failure (re-delegation limit reached after {} attempts, no deliverable \
1068                 produced)",
1069                redelegation::MAX_REDELEGATIONS
1070            )
1071        } else {
1072            "run failure".to_string()
1073        };
1074        return RunReport {
1075            agent: params.agent.clone(),
1076            task: format!("{} [{label}: {e}]", params.task),
1077            diff: String::new(),
1078            transcript: turns,
1079            usage,
1080            cost_usd: Some(cost),
1081            exit: ExitCode::RunFailure,
1082        };
1083    }
1084
1085    let rendered_diff = diff::diff_snapshots(&before, &after);
1086
1087    // Sum usage across every recorded PM + engineer turn, pricing each turn
1088    // against its OWN role's resolved model (#1475 bug 1 fix). The PM's own
1089    // `AgentOutput.usage` omits the engineer's tokens (they return as a
1090    // tool-result string), so the transcript is the faithful total.
1091    let (total_usage, cost) = aggregate_usage_per_role(&turns, pm_model, engineer_model);
1092
1093    let exit = if rendered_diff.trim().is_empty() {
1094        ExitCode::NoChanges
1095    } else {
1096        ExitCode::Success
1097    };
1098
1099    RunReport {
1100        agent: params.agent.clone(),
1101        task: params.task.clone(),
1102        diff: rendered_diff,
1103        transcript: turns,
1104        usage: total_usage,
1105        cost_usd: Some(cost),
1106        exit,
1107    }
1108}