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, CompactionConfig};
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::{
37    resolve_context_window, resolve_deadline_secs, resolve_max_tokens, resolve_model,
38};
39use crate::runner::{InProcessAgentRunner, RegistryFactory};
40use crate::tools::{
41    AgentOutput, AgentRunner, BashTool, DelegateToAgentTool, EditTool, EngineerCompletionSignal,
42    FinishTaskTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, RunContext, ToolRegistry,
43    TrustySearchTool, WriteFileTool, WriteFilesTool,
44};
45
46pub use recorder::{RecordingLlmClient, SharedTranscript, TurnRecord};
47pub use redelegation::{MAX_REDELEGATIONS, RedelegationCapSignal};
48pub use report::{ExitCode, RunReport, aggregate_usage_per_role};
49
50/// Default bash timeout for the engineer's tools, in seconds.
51const ENGINEER_BASH_TIMEOUT_SECS: u64 = 120;
52
53/// The delegated engineer's agent name (matches
54/// `task::executor::ENGINEER_AGENT_NAME`, the daemon path's own copy of this
55/// same literal — kept as two constants, not one shared item, since neither
56/// module depends on the other and a shared constant would be a heavier
57/// coupling than the two paths' otherwise-independent module boundaries
58/// warrant).
59const ENGINEER_AGENT_NAME: &str = "python-engineer";
60
61/// Fire-and-forget best-effort trusty-search indexing of a task's working
62/// project, at task/session START (trusty-search-first discovery, PR B).
63///
64/// Why: a tcode run's answers are far better when the working project is
65/// discoverable via trusty-search's `search`/`grep`/`get_call_chain` tools, but
66/// nothing previously ensured the project's index existed and was populated —
67/// that register-and-reindex logic lived only in trusty-mpm's session launch.
68/// This shares the ONE promoted implementation
69/// ([`trusty_common::search_index::ensure_project_indexed`]) so the two crates
70/// can never diverge. It runs at task start, detached, so the index is built
71/// WHILE the agent loop proceeds rather than blocking it. Fail-open by design:
72/// the shared helper logs-and-swallows every daemon/HTTP error, so a missing or
73/// slow trusty-search daemon never affects the run.
74/// What: indexes `project` UNCONDITIONALLY — git is a nice-to-have for tcode,
75/// not a requirement (owner directive), and trusty-search's own orphan-reaper
76/// already garbage-collects indexes for scratch directories that get deleted,
77/// so there is no cost to indexing a non-git or short-lived working directory.
78/// [`trusty_common::search_index::ensure_project_indexed`] already resolves a
79/// sensible root and index id whether or not `project` is inside a git repo.
80/// Spawns a detached OS thread that calls the shared helper (which itself runs
81/// the blocking HTTP on its own short-timeout threads) and returns immediately,
82/// so the caller never waits on the network.
83/// After warming, this also SURFACES the resulting index readiness to the
84/// session (issue #2784): a cold-indexed large repo has a real semantic
85/// warm-up window (lexical ready in seconds, semantic embedding `InProgress`
86/// for minutes), so a daily-driver `tcode` session that starts querying
87/// immediately would otherwise get lexical-only results with no signal. The
88/// detached thread probes `GET /indexes/{id}/status` right after triggering the
89/// warm and emits ONE `tracing` line (via the shared
90/// [`trusty_common::search_readiness::log_index_readiness`]) describing which
91/// lanes are ready — `warn` while semantic is still warming, `info` once it is
92/// ready. Same fail-open contract: no daemon ⇒ no log, never a block.
93///
94/// Test: the promoted helper's fail-open + no-daemon + non-git-root behaviour is
95/// unit-tested in `trusty_common::search_index::tests`; the readiness probe/parse
96/// in `trusty_common::search_readiness::tests`. This thin spawn wrapper is
97/// side-effect-only (detached thread) and has no return to assert; see
98/// `spawns_indexing_thread_for_non_git_project_path` for the one thing it IS
99/// mechanically checked for here — that it never short-circuits before spawning.
100pub(crate) fn ensure_project_indexed_in_background(project: PathBuf) {
101    std::thread::spawn(move || {
102        // Warm first, then surface the readiness the warm produced so the
103        // session knows whether a semantic search is trustworthy yet (#2784).
104        let _ = trusty_common::search_index::ensure_project_indexed(&project);
105        trusty_common::search_readiness::log_index_readiness(&project);
106    });
107}
108
109/// Inputs to a single `run-task` invocation, parsed from the CLI.
110///
111/// Why: Bundling the inputs keeps `execute_run_task`'s signature stable as flags
112/// are added and lets the binary layer construct one value from clap.
113/// What: `agent` is the top-level (PM) agent name; `task` is the request; `project`
114/// is the canonical project root; `agents_dir` is where `<agent>.toml` live;
115/// `engineer_model` is the optional per-run engineer model override (#1035).
116/// Test: `run_task::tests` build these directly.
117#[derive(Debug, Clone)]
118pub struct RunTaskParams {
119    /// Top-level agent name (typically `"pm"`).
120    pub agent: String,
121    /// Free-form task description.
122    pub task: String,
123    /// Canonical project root.
124    pub project: PathBuf,
125    /// Directory holding `<agent>.toml` configs.
126    pub agents_dir: PathBuf,
127    /// Optional per-run engineer model override (#1035). `None` routes the
128    /// engineer via its own config model.
129    pub engineer_model: Option<String>,
130    /// Optional per-run wall-clock deadline override, in seconds (#2207).
131    /// `None` falls through to [`crate::provider::resolve_deadline_secs`]'s
132    /// env-var/default tiers — see that function's docs for the full
133    /// precedence. Applied to BOTH the PM's own loop and the delegated
134    /// engineer's loop (`build_engineer_runner`).
135    pub deadline_secs: Option<u64>,
136}
137
138/// Execute a `run-task` end-to-end and return the rendered report.
139///
140/// Why: The single orchestration entry point the binary calls (with a real
141/// `LlmClient`) and tests call (with a scripted mock). Keeping the LLM client as
142/// an injected `Arc<dyn LlmClientTrait>` is what makes the whole path testable
143/// offline without a network call or an API key.
144/// What: Loads the PM config, assembles its prompt (BASE + PM prompt + project
145/// `CLAUDE.md`), builds the engineer runner (fs/bash scoped to the project, with
146/// the optional per-run model override), wraps it in the PM's
147/// `DelegateToAgentTool`, snapshots the working tree, runs the PM `AgentLoop`
148/// (#2265 fix #5: wired with `with_stop_signal` against the SAME
149/// `redelegation_signal` the engineer runner shares, so the PM stops issuing
150/// `delegate_to_agent` calls the turn after the re-delegation cap latches
151/// instead of spinning through its remaining turns on doomed retries),
152/// snapshots again, and assembles a `RunReport` (diff + transcript + usage/cost +
153/// exit code). A PM-config or loop error yields a `ConfigError`/`RunFailure`
154/// report rather than a panic.
155/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
156/// `diff_reflects_engineer_file_change`, `usage_and_cost_aggregate_end_to_end`,
157/// `exit_code_reflects_run_failure`,
158/// `pm_stops_redelegating_once_cap_latched_ends_partial_promptly`.
159pub async fn execute_run_task(params: RunTaskParams, llm: Arc<dyn LlmClientTrait>) -> RunReport {
160    // Trusty-search-first discovery (PR B): at task START, best-effort/detached,
161    // ensure the working project is indexed so `search`/`grep` are useful while
162    // the loop below proceeds. Fail-open, git-optional — see the helper's docs.
163    ensure_project_indexed_in_background(params.project.clone());
164
165    let transcript: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
166
167    // #2264: resolve the (optional) full wire-level debug-capture sink once
168    // per run, shared by BOTH the pm and engineer wrappers below so a
169    // directory-mode capture lands in one file with a single globally
170    // ordered turn sequence — mirrors `transcript`'s own "one shared
171    // accumulator per run" shape. `None` when `TCODE_DEBUG_TRANSCRIPT` is
172    // unset (the default): `wrap_with_debug_capture` then returns each
173    // inner client unchanged, so this costs nothing when disabled.
174    let debug_sink: Option<Arc<DebugCaptureSink>> = DebugCaptureSink::from_env();
175
176    // Load the PM config; a missing/invalid config is a configuration error.
177    let pm_config =
178        match AgentConfig::load(&params.agents_dir.join(format!("{}.toml", params.agent))) {
179            Ok(cfg) => cfg,
180            Err(e) => return config_error_report(&params, &transcript, &format!("{e:#}")),
181        };
182
183    // Load project context (#1033) — absent file is fine.
184    let project_context = load_project_context(&params.project);
185
186    // Resolve the PM's own model (no per-call override for the PM).
187    let pm_model = resolve_model(&pm_config, None);
188
189    // #2207: resolve the run's wall-clock deadline once, applied to BOTH the
190    // PM's own loop (below) and the delegated engineer's loop
191    // (`build_engineer_runner`, via `with_timeout_secs`).
192    let deadline_secs = resolve_deadline_secs(params.deadline_secs);
193
194    // (#2265) The re-delegation cap signal is shared between the engineer
195    // runner's retry decorator (`RedelegatingRunner`, wired inside
196    // `build_engineer_runner`) and `assemble_report` below, so a cap-hit run
197    // gets a clean terminal report regardless of what the PM's own loop
198    // subsequently does.
199    let redelegation_signal = RedelegationCapSignal::new();
200
201    // (#2683) The engineer-completion latch is shared between the PM's
202    // `DelegateToAgentTool` (which sets it when a delegation returns an explicit
203    // successful `finish_task`, and refuses any subsequent re-delegation once
204    // set) and `assemble_report` below (which reports success rather than
205    // partial for a run the engineer already completed). This is what stops a
206    // gratuitous post-finish re-verify round from mislabeling a complete,
207    // all-tests-passing run as `partial`/exit-6.
208    let completion_signal = EngineerCompletionSignal::new();
209
210    // Build the engineer runner, scoped to the project working dir, sharing the
211    // transcript (engineer turns are tagged "python-engineer").
212    let engineer_runner = build_engineer_runner(
213        wrap_with_debug_capture(Arc::clone(&llm), ENGINEER_AGENT_NAME, debug_sink.as_ref()),
214        &params,
215        project_context.clone(),
216        Arc::clone(&transcript),
217        deadline_secs,
218        redelegation_signal.clone(),
219    );
220
221    // The PM's tool registry: the delegate tool (the PM orchestrates; the
222    // engineer does the file work) plus `finish_task` (#2072) so the PM can
223    // signal completion with a structured report instead of relying solely on
224    // the implicit no-tool-call convention. Pre-flight validation uses the
225    // agents dir.
226    let mut pm_registry = ToolRegistry::new();
227    pm_registry.register(Arc::new(
228        DelegateToAgentTool::new(engineer_runner)
229            .with_config_dir(params.agents_dir.clone())
230            // (#2683) refuse a re-delegation once the engineer has completed.
231            .with_completion_signal(completion_signal.clone()),
232    ));
233    pm_registry.register(Arc::new(FinishTaskTool::new()));
234
235    // The PM's loop uses a transcript-recording client tagged "pm".
236    let pm_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
237        wrap_with_debug_capture(Arc::clone(&llm), "pm", debug_sink.as_ref()),
238        "pm",
239        Arc::clone(&transcript),
240    ));
241
242    // Inject DOC-28 catch-up digest as seed context into the PM prompt (#1762 PR2).
243    // The catch-up engine is async and fail-open: if the daemon is offline or the
244    // project has no activity, it returns None and the prompt is assembled without
245    // the section.  Sub-agents are NOT wired here; only the PM receives this digest.
246    let catchup_ctx = crate::catchup::pm_catchup_context(&params.project).await;
247
248    let pm_system = assemble_system_prompt(
249        &pm_config,
250        project_context.as_deref(),
251        catchup_ctx.as_deref(),
252    );
253    // (#2265 fix #5) Once the shared re-delegation cap latches, every further
254    // `delegate_to_agent` call the PM might issue is a guaranteed dead end —
255    // `RedelegatingRunner` will reject it immediately without even invoking
256    // the engineer. Wiring the SAME signal into the PM's own loop as a stop
257    // condition (checked at the existing turn-boundary, alongside the #2056
258    // cancellation flag) stops the PM from spending its remaining
259    // `max_turns` issuing those doomed calls one per turn — the bake-off L1
260    // regression this fix closes (see `redelegation` module docs for the
261    // full before/after). `assemble_report` already maps a cap-latched,
262    // deliverable-bearing run to `ExitCode::Partial` regardless of which
263    // `AgentLoopError` variant the PM's loop returns, so this purely trims
264    // wasted turns — it does not change the reported outcome.
265    let stop_signal = redelegation_signal.clone();
266    let pm_loop = AgentLoop::new(
267        AgentLoopConfig {
268            model: pm_model.clone(),
269            max_tokens: resolve_max_tokens(&pm_config),
270            timeout_secs: deadline_secs,
271            // #2308: model-aware compaction threshold — see
272            // `CompactionConfig::for_context_window`'s doc for why the
273            // struct-update `..AgentLoopConfig::default()` below must not be
274            // allowed to silently supply the flat, model-blind default here.
275            compaction: CompactionConfig::for_context_window(resolve_context_window(&pm_model)),
276            // #2346: `cadence` stays the `..AgentLoopConfig::default()` value
277            // (`None`) here, deliberately — the legacy one-shot/bake-off
278            // `run-task` CLI path is explicitly out of scope for the cadence
279            // compressor (epic #2343 scopes it to the daemon-driven,
280            // persistent-session path in `task::executor::run_and_record`
281            // only), so this run sees zero behaviour change from before
282            // #2346.
283            ..AgentLoopConfig::default()
284        },
285        pm_llm,
286        Arc::new(pm_registry),
287    )
288    .with_stop_signal(Arc::new(move || stop_signal.is_cap_reached()))
289    // #2279: the PM never calls `bash` itself (its registry above is
290    // `delegate_to_agent` + `finish_task` only), so its verify-before-finish
291    // gate must scan the delegated engineer's transcript instead of its
292    // own — `verify_gate::pm_finish_gate` does exactly that against the
293    // SAME shared `transcript` the engineer's `RecordingLlmClient` records
294    // into (see `build_engineer_runner` above).
295    .with_finish_gate(crate::verify_gate::pm_finish_gate(Arc::clone(&transcript)));
296
297    // Snapshot before, run the PM, snapshot after.
298    let before = diff::capture_snapshot(&params.project);
299    let pm_result = pm_loop.run(&pm_system, &params.task).await;
300    let after = diff::capture_snapshot(&params.project);
301
302    // Resolve the engineer's model independently (#1475 bug 1) so the report
303    // prices its turns at its OWN rate rather than blending everything
304    // under the PM model.
305    let engineer_model = resolve_agent_model_slug(
306        &params.agents_dir,
307        ENGINEER_AGENT_NAME,
308        params.engineer_model.as_deref(),
309    );
310
311    assemble_report(
312        &params,
313        &transcript,
314        &pm_model,
315        &engineer_model,
316        RunOutcome {
317            before,
318            after,
319            pm_result,
320        },
321        &redelegation_signal,
322        &completion_signal,
323    )
324}
325
326/// Build the in-process engineer runner with project-scoped fs/bash tools.
327///
328/// Why: The engineer must write/read/run inside the project and see the same
329/// project context as the PM. This wires a `RegistryFactory` that constructs fs +
330/// bash tools scoped to the project dir plus the project context, then routes the
331/// result through the per-run model-override seam (`apply_engineer_model_override`).
332/// `deadline_secs` (#2207) is the SAME resolved wall-clock budget applied to the
333/// delegating PM's own loop, so a raised deadline covers the whole run, not just
334/// the PM's half of it. (#2265) The outermost layer is
335/// `redelegation::RedelegatingRunner`, which internally retries a failed
336/// attempt (reuse-hint-augmented, capped at `redelegation::MAX_REDELEGATIONS`)
337/// entirely within one `AgentRunner::run`/`run_with_context` call — this is
338/// the chosen "decouple retries from PM turns" design for fix #3: every
339/// retry happens inside a SINGLE `delegate_to_agent` tool dispatch, so it
340/// never consumes any of the PM's own `AgentLoopConfig::max_turns` budget
341/// (left at its crate default of 8 — raising it was the alternative design,
342/// rejected here because the cap in fix #1 is a cleaner, purpose-built ceiling
343/// than a bigger, still-somewhat-arbitrary PM turn budget would be).
344/// What: Returns an `Arc<dyn AgentRunner>` the `DelegateToAgentTool` dispatches
345/// to. The engineer's own LLM turns are recorded under the "python-engineer" role.
346/// `redelegation_signal` is shared with `assemble_report` via the caller.
347/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
348fn build_engineer_runner(
349    llm: Arc<dyn LlmClientTrait>,
350    params: &RunTaskParams,
351    project_context: Option<String>,
352    transcript: SharedTranscript,
353    deadline_secs: u64,
354    redelegation_signal: RedelegationCapSignal,
355) -> Arc<dyn AgentRunner> {
356    let engineer_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
357        llm,
358        ENGINEER_AGENT_NAME,
359        transcript,
360    ));
361
362    let factory: Arc<dyn RegistryFactory> = Arc::new(ProjectToolFactory {
363        project: params.project.clone(),
364    });
365
366    let mut runner = InProcessAgentRunner::new(engineer_llm, factory, params.agents_dir.clone())
367        .with_timeout_secs(deadline_secs);
368    if let Some(ctx) = project_context {
369        runner = runner.with_project_context(ctx);
370    }
371    let pinned = apply_engineer_model_override(Arc::new(runner), params);
372    Arc::new(redelegation::RedelegatingRunner::new(
373        pinned,
374        redelegation_signal,
375        params.project.clone(),
376    ))
377}
378
379/// Builds the engineer's project-scoped tool registry for each delegation.
380///
381/// Why: The engineer needs real file and shell tools that cannot escape the
382/// project root, plus (#2072) `finish_task` so it can signal completion with a
383/// structured report. This factory constructs `read_file`, `write_file`,
384/// `write_files` (#2681 batch write), `edit`, the `glob`/`grep`/`list_dir`
385/// exploration tools (#1027), and `bash` all scoped to `self.project`, so the
386/// engineer operates only inside the project working tree; `finish_task` has no
387/// filesystem footprint and needs no scoping.
388/// What: Implements `RegistryFactory::build`, returning an `Arc<ToolRegistry>`
389/// with every tool; the runner then gates them by the engineer's
390/// `tools.allowed`.
391/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer` (the engineer's
392/// `write_file` actually writes into the project).
393struct ProjectToolFactory {
394    project: PathBuf,
395}
396
397#[async_trait]
398impl RegistryFactory for ProjectToolFactory {
399    async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
400        // #2068: resolve the engineer's model slug so `EditTool` can pick its
401        // per-model edit-format fallback order (see `resolve_model`'s own
402        // precedence docs — RunContext override > agent config > default).
403        let model_slug = resolve_model(agent, Some(ctx));
404        let mut reg = ToolRegistry::new();
405        reg.register(Arc::new(ReadFileTool::new(&self.project)));
406        reg.register(Arc::new(WriteFileTool::new(&self.project)));
407        // #2681: batch-write decouples turn-count from file-count.
408        reg.register(Arc::new(WriteFilesTool::new(&self.project)));
409        reg.register(Arc::new(
410            EditTool::new(&self.project).with_model_slug(model_slug),
411        ));
412        // #1027: native file discovery so the engineer stops shelling out to
413        // find/grep/ls (the dominant bake-off agent-turn sink).
414        reg.register(Arc::new(GlobTool::new(&self.project)));
415        reg.register(Arc::new(GrepTool::new(&self.project)));
416        reg.register(Arc::new(ListDirTool::new(&self.project)));
417        // PR A (#2689): trusty-search-backed conceptual discovery as the PRIMARY
418        // path; the local glob/grep tools above are the fail-open FALLBACK. The
419        // `run_task` CLI is always the daily-driver path (the parity benchmark
420        // runs through `task::executor`, which gates this on `HarnessMode`), so
421        // registration is unconditional here.
422        reg.register(Arc::new(TrustySearchTool::new(&self.project)));
423        reg.register(Arc::new(BashTool::new(
424            Some(self.project.clone()),
425            Duration::from_secs(ENGINEER_BASH_TIMEOUT_SECS),
426        )));
427        reg.register(Arc::new(FinishTaskTool::new()));
428        Arc::new(reg)
429    }
430}
431
432/// Apply the per-run engineer-model override to the runner, if any (#1035).
433///
434/// Why: The engineer routes to its own configured model by default. A per-run
435/// `--engineer-model` (or `TCODE_ENGINEER_MODEL`) must reroute *only* the engineer
436/// for that single run — the model-comparison harness varies the engineer model
437/// while the PM model stays fixed. Keeping the override here lets
438/// `build_engineer_runner` stay agnostic to whether a model is pinned.
439/// What: When `params.engineer_model` is `Some`, wraps the runner in a
440/// `ModelPinningRunner` that injects `RunContext.model` on every delegation;
441/// otherwise returns the runner unchanged.
442/// Test: `run_task::tests::engineer_model_swap_routes_engineer`,
443/// `two_runs_route_engineer_to_distinct_slugs`.
444fn apply_engineer_model_override(
445    runner: Arc<dyn AgentRunner>,
446    params: &RunTaskParams,
447) -> Arc<dyn AgentRunner> {
448    match &params.engineer_model {
449        Some(model) => Arc::new(ModelPinningRunner {
450            inner: runner,
451            model: model.clone(),
452        }),
453        None => runner,
454    }
455}
456
457/// Resolve an agent's model slug, honouring an optional per-run override
458/// (#1035, #1475 bug 1 fix's prerequisite).
459///
460/// Why: `InProcessAgentRunner` resolves the engineer's model internally and
461/// does not expose it, so pricing the engineer's turns against its OWN
462/// model (rather than blending everything under the PM model — the #1475
463/// bug) needs this same resolution done independently, here, purely for the
464/// pricing step. Shared with the daemon path (`task::executor`'s own
465/// `resolve_engineer_model`, which now delegates here) so the two paths
466/// can never independently drift on how per-role pricing resolves a model.
467/// What: loads `<agents_dir>/<agent_name>.toml`; on any load failure
468/// (missing/invalid file) falls back to the literal string `"unknown"` —
469/// `crate::perf::cost_usd` degrades gracefully (Sonnet-equivalent pricing)
470/// for an unrecognised model rather than erroring, so a missing agent
471/// config degrades pricing accuracy, not the whole run. When
472/// `model_override` is `Some`, it wins over the config's own model (mirrors
473/// `RunContext`'s override precedence).
474/// Test: `run_task::tests::resolve_agent_model_slug_falls_back_when_config_missing`,
475/// `run_task::tests::resolve_agent_model_slug_honours_override`.
476pub fn resolve_agent_model_slug(
477    agents_dir: &std::path::Path,
478    agent_name: &str,
479    model_override: Option<&str>,
480) -> String {
481    let path = agents_dir.join(format!("{agent_name}.toml"));
482    let Ok(config) = AgentConfig::load(&path) else {
483        return "unknown".to_string();
484    };
485    match model_override {
486        Some(model) => {
487            let ctx = RunContext {
488                model: Some(model.to_string()),
489                ..Default::default()
490            };
491            resolve_model(&config, Some(&ctx))
492        }
493        None => resolve_model(&config, None),
494    }
495}
496
497/// An `AgentRunner` decorator that pins a fixed model for every delegation (#1035).
498///
499/// Why: `DelegateToAgentTool::execute` calls `runner.run` with a default
500/// `RunContext`, so the per-run `--engineer-model` override cannot be threaded
501/// through the tool itself. This decorator injects `RunContext.model` and forwards
502/// to `run_with_context`, so the engineer's loop routes to the pinned slug while
503/// the PM model stays fixed.
504/// What: Holds the inner runner and the pinned model; both `run` and
505/// `run_with_context` set `ctx.model` before delegating.
506/// Test: `run_task::tests::engineer_model_swap_routes_engineer`.
507struct ModelPinningRunner {
508    inner: Arc<dyn AgentRunner>,
509    model: String,
510}
511
512#[async_trait]
513impl AgentRunner for ModelPinningRunner {
514    async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
515        let ctx = RunContext {
516            model: Some(self.model.clone()),
517            ..Default::default()
518        };
519        self.inner.run_with_context(agent_name, task, &ctx).await
520    }
521
522    async fn run_with_context(
523        &self,
524        agent_name: &str,
525        task: &str,
526        ctx: &RunContext,
527    ) -> Result<AgentOutput> {
528        let mut ctx = ctx.clone();
529        ctx.model = Some(self.model.clone());
530        self.inner.run_with_context(agent_name, task, &ctx).await
531    }
532}
533
534/// Drain the shared transcript into an owned `Vec`.
535///
536/// Why: The report owns its transcript; this lifts it out of the shared mutex.
537/// What: Clones the locked vector (empty on a poisoned lock — the run must not
538/// panic while building the report).
539/// Test: Exercised by every end-to-end test.
540fn drain_transcript(transcript: &SharedTranscript) -> Vec<TurnRecord> {
541    transcript.lock().map(|g| g.clone()).unwrap_or_default()
542}
543
544/// Build a `ConfigError` report (PM config missing/invalid).
545///
546/// Why: A configuration failure must produce a faithful report + exit code, not a
547/// panic, so callers can branch on it.
548/// What: Returns a `RunReport` with an empty diff, the (likely empty) transcript,
549/// zero usage, and `ExitCode::ConfigError`; the error text rides in the task line
550/// of the human form via a synthesized note.
551/// Test: `run_task::tests::missing_pm_config_is_config_error`.
552fn config_error_report(
553    params: &RunTaskParams,
554    transcript: &SharedTranscript,
555    err: &str,
556) -> RunReport {
557    RunReport {
558        agent: params.agent.clone(),
559        task: format!("{} [config error: {err}]", params.task),
560        diff: String::new(),
561        transcript: drain_transcript(transcript),
562        usage: crate::perf::TokenUsage::default(),
563        cost_usd: None,
564        exit: ExitCode::ConfigError,
565    }
566}
567
568/// The run's raw outcome: before/after working-tree snapshots plus the PM
569/// loop's own `Result`.
570///
571/// Why: These three values are always produced and consumed together; bundling
572/// them keeps `assemble_report`'s argument count under clippy's
573/// `too_many_arguments` limit (#2265 added an 8th argument,
574/// `redelegation_signal`, that pushed the plain-argument version over it)
575/// without losing any of the fields or their names.
576/// What: Plain data holder, no behaviour.
577/// Test: Exercised through every `assemble_report` test.
578struct RunOutcome {
579    before: diff::Snapshot,
580    after: diff::Snapshot,
581    pm_result: Result<AgentOutput, AgentLoopError>,
582}
583
584/// Assemble the final report from the run's outcome.
585///
586/// Why: Centralises the mapping from (PM loop result, before/after snapshots) to a
587/// `RunReport` with the correct exit code so the success / no-change / failure
588/// branches never drift.
589/// What: (#2683) FIRST — before any error-variant branching — if
590/// `completion_signal` reports the delegated engineer already returned an
591/// EXPLICIT successful `finish_task` completion, the task is genuinely done:
592/// the outcome is `Success` (or `NoChanges` for an empty diff), NEVER
593/// `Partial`/`DeadlineExceeded`/`RunFailure`, regardless of how the PM's own
594/// loop later terminated. This is the data-integrity fix for the bug where a
595/// gratuitous post-finish re-delegation that then ran out of turns/time
596/// mislabeled a complete, all-tests-passing run as `partial`/exit-6. On a
597/// PM-loop error with NO such completion → `DeadlineExceeded` when the error is
598/// specifically `AgentLoopError::Timeout` (#2207 — distinct from a genuine
599/// failure so a caller can tell "timed out" from "errored"). (#2265 fix #4)
600/// Otherwise, when the error is `AgentLoopError::TurnCapExceeded` OR
601/// `redelegation_signal` reports the re-delegation cap (fix #1) was hit, the
602/// diff is computed (filesystem-based, independent of which turn/attempt
603/// produced it) and — if it is non-empty, i.e. a deliverable actually exists on
604/// disk — the outcome is `ExitCode::Partial`, NOT `RunFailure`; trusty-code
605/// cannot generically verify correctness, so this gates purely on "work was
606/// produced", leaving the downstream bake-off harness to score correctness
607/// itself. Every other PM-loop error (a hard `Llm`/`Cancelled` failure, or ANY
608/// error with an empty diff — including a cap/turn-cap hit that produced
609/// nothing) still maps to `RunFailure`, preserving that path for genuine
610/// no-output failures. On success → compute the diff; empty diff → `NoChanges`,
611/// else `Success`.
612/// Usage and cost are aggregated from the transcript and priced PER ROLE —
613/// `pm_model` for `"pm"` turns, `engineer_model` for the delegated engineer's
614/// — per the #1475 bug 1 fix (`aggregate_usage_per_role`), not blended under
615/// one model. #2206: this aggregation now runs on every error path too, so a
616/// `run_failure`, `partial`, or `deadline_exceeded` report still carries the
617/// real usage/cost of every turn that DID complete, rather than a zeroed
618/// placeholder.
619/// Test: `run_task::tests::*` (success, no-change, failure, deadline, and
620/// #2265 partial/cap-reached paths).
621fn assemble_report(
622    params: &RunTaskParams,
623    transcript: &SharedTranscript,
624    pm_model: &str,
625    engineer_model: &str,
626    outcome: RunOutcome,
627    redelegation_signal: &RedelegationCapSignal,
628    completion_signal: &EngineerCompletionSignal,
629) -> RunReport {
630    let RunOutcome {
631        before,
632        after,
633        pm_result,
634    } = outcome;
635    let turns = drain_transcript(transcript);
636
637    // #2683: the authoritative success signal. If the delegated engineer
638    // already reported an EXPLICIT successful `finish_task` completion, the
639    // task is genuinely done — a gratuitous post-finish re-delegation that
640    // subsequently ran the PM's loop out of turns/time (or hit any other
641    // terminal error) must NOT mislabel this complete, correct run as
642    // `partial`/`deadline_exceeded`/`run_failure`. The on-disk diff is the
643    // authoritative deliverable regardless of which turn produced it: a
644    // non-empty diff is `Success`, an empty one is `NoChanges`. This is checked
645    // FIRST, before any PM-error-variant branching, so it overrides every one
646    // of them.
647    if completion_signal.is_completed() {
648        let (usage, cost) = aggregate_usage_per_role(&turns, pm_model, engineer_model);
649        let rendered_diff = diff::diff_snapshots(&before, &after);
650        let exit = if rendered_diff.trim().is_empty() {
651            ExitCode::NoChanges
652        } else {
653            ExitCode::Success
654        };
655        return RunReport {
656            agent: params.agent.clone(),
657            task: params.task.clone(),
658            diff: rendered_diff,
659            transcript: turns,
660            usage,
661            cost_usd: Some(cost),
662            exit,
663        };
664    }
665
666    // A PM-loop error is a runtime failure (or, #2207, a deadline; or, #2265,
667    // a turn-cap/re-delegation-cap hit that still produced a deliverable);
668    // the transcript still reflects whatever turns ran before the error. The
669    // PM's `AgentOutput` content is not needed for the report — the
670    // transcript and diff are the authoritative artifacts. #2206: usage/cost
671    // are aggregated from those completed turns here too, not zeroed.
672    if let Err(e) = pm_result {
673        let (usage, cost) = aggregate_usage_per_role(&turns, pm_model, engineer_model);
674
675        if matches!(e, AgentLoopError::Timeout { .. }) {
676            return RunReport {
677                agent: params.agent.clone(),
678                task: format!("{} [deadline exceeded: {e}]", params.task),
679                diff: String::new(),
680                transcript: turns,
681                usage,
682                cost_usd: Some(cost),
683                exit: ExitCode::DeadlineExceeded,
684            };
685        }
686
687        // #2265 fix #4: a turn-cap or re-delegation-cap terminal condition
688        // must not be blindly reported as `run_failure` when a deliverable
689        // already exists on disk — the diff is filesystem-based, so it is
690        // authoritative regardless of which attempt produced it.
691        let cap_reached = redelegation_signal.is_cap_reached();
692        let is_turn_cap = matches!(e, AgentLoopError::TurnCapExceeded { .. });
693        let rendered_diff = diff::diff_snapshots(&before, &after);
694        let has_deliverable = !rendered_diff.trim().is_empty();
695
696        if (cap_reached || is_turn_cap) && has_deliverable {
697            let label = if cap_reached {
698                format!(
699                    "partial: re-delegation limit reached after {} attempts; partial work \
700                     preserved at {}",
701                    redelegation_signal.attempts(),
702                    params.project.display()
703                )
704            } else {
705                "partial: PM turn cap exceeded but a deliverable was produced".to_string()
706            };
707            return RunReport {
708                agent: params.agent.clone(),
709                task: format!("{} [{label}: {e}]", params.task),
710                diff: rendered_diff,
711                transcript: turns,
712                usage,
713                cost_usd: Some(cost),
714                exit: ExitCode::Partial,
715            };
716        }
717
718        // Genuine failure: no deliverable exists, or the error is neither a
719        // turn cap nor a re-delegation-cap hit (e.g. a hard `Llm`/`Cancelled`
720        // failure). This path is intentionally left mapped to `RunFailure` —
721        // "Keep genuine no-output failures mapped to RunFailure" per #2265.
722        // When the cap WAS reached but produced nothing reusable, the label
723        // still names that (so an operator/log reader is not left guessing
724        // whether this was an opaque crash or an exhausted, reuse-aware
725        // retry budget), even though the exit code itself is unchanged.
726        let label = if cap_reached {
727            format!(
728                "run failure (re-delegation limit reached after {} attempts, no deliverable \
729                 produced)",
730                redelegation_signal.attempts()
731            )
732        } else {
733            "run failure".to_string()
734        };
735        return RunReport {
736            agent: params.agent.clone(),
737            task: format!("{} [{label}: {e}]", params.task),
738            diff: String::new(),
739            transcript: turns,
740            usage,
741            cost_usd: Some(cost),
742            exit: ExitCode::RunFailure,
743        };
744    }
745
746    let rendered_diff = diff::diff_snapshots(&before, &after);
747
748    // Sum usage across every recorded PM + engineer turn, pricing each turn
749    // against its OWN role's resolved model (#1475 bug 1 fix). The PM's own
750    // `AgentOutput.usage` omits the engineer's tokens (they return as a
751    // tool-result string), so the transcript is the faithful total.
752    let (total_usage, cost) = aggregate_usage_per_role(&turns, pm_model, engineer_model);
753
754    let exit = if rendered_diff.trim().is_empty() {
755        ExitCode::NoChanges
756    } else {
757        ExitCode::Success
758    };
759
760    RunReport {
761        agent: params.agent.clone(),
762        task: params.task.clone(),
763        diff: rendered_diff,
764        transcript: turns,
765        usage: total_usage,
766        cost_usd: Some(cost),
767        exit,
768    }
769}