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