Skip to main content

trusty_code/task/
executor.rs

1//! Daemon-owned background task execution (#2056): wires the session/event
2//! layer (#2054/#2055) to the existing engine (`agent_loop`/`runner`/`tools`/
3//! `llm`) — the M1 control-plane cut line.
4//!
5//! Why: `run_task` (the CLI's `tcode run-task`) already proves this engine
6//! end-to-end, but it runs synchronously, in the calling process, and
7//! renders a `RunReport` for a terminal. A daemon-driven task must instead
8//! run as a background task the triggering RPC does NOT block on, stream
9//! its progress live to `session.attach`ed clients via the #2055 event
10//! envelope, and persist its outcome onto the `Session` for a future
11//! `session.get_transcript` (#2058). This module is new glue, NOT a fork of
12//! the engine: it builds the exact same PM-delegates-to-engineer shape
13//! `run_task::execute_run_task` does (see that module's doc comment), reusing
14//! `agent_loop::AgentLoop`, `runner::InProcessAgentRunner`, `tools::*`, and
15//! `run_task`'s own public `RecordingLlmClient`/`TurnRecord`/
16//! `aggregate_usage_per_role`/`resolve_agent_model_slug` machinery — only the
17//! orchestration shell (spawn-and-report vs. run-and-render) differs.
18//! What: [`TaskRunParams`] carries one run's inputs; [`spawn_task_run`] is
19//! the single entry point `task::protocol::task_run` calls — it reserves the
20//! session's execution slot synchronously (rejecting a second overlapping
21//! run before any background work starts), then hands the actual run off to
22//! a `tokio::spawn`'d task that builds both loops (attaching the #2056
23//! `SessionToolEventSink` + a shared cancel flag to BOTH the PM's and the
24//! delegated engineer's `AgentLoop`), drives the PM loop, prices the
25//! transcript PER ROLE against each role's own resolved model via
26//! `run_task::aggregate_usage_per_role` (#1475 bug 1 — this daemon path and
27//! the legacy CLI path now share the ONE implementation, so they can never
28//! independently drift), persists the outcome, and transitions the session
29//! to its terminal state.
30//! Test: `task::executor::tests::*`; the full flow end-to-end (a real
31//! subprocess) in `tests/task_e2e.rs`.
32
33use std::path::{Path, PathBuf};
34use std::sync::atomic::AtomicBool;
35use std::sync::{Arc, Mutex};
36use std::time::Duration;
37
38use async_trait::async_trait;
39
40use crate::agent_loop::{
41    AgentLoop, AgentLoopConfig, CompactionConfig, ToolEventSink, resolve_cadence_config,
42};
43use crate::agents::AgentConfig;
44use crate::binding::ProjectBinding;
45use crate::jsonrpc::RpcError;
46use crate::llm::{DebugCaptureSink, InferenceAdapter, wrap_with_debug_capture};
47use crate::mode::HarnessMode;
48use crate::project_context::load_project_context;
49use crate::prompt::assemble_system_prompt_for_mode;
50use crate::provider::{
51    resolve_context_window, resolve_deadline_secs, resolve_max_tokens, resolve_model,
52};
53use crate::run_task::{
54    RecordingLlmClient, SharedTranscript, aggregate_usage_per_role, resolve_agent_model_slug,
55};
56use crate::runner::{InProcessAgentRunner, RegistryFactory};
57use crate::session::{SessionRegistry, SessionStatus};
58use crate::skills::{FsSkillResolver, format_skill_catalog, locate_skills_dir};
59use crate::tools::{
60    AgentOutput, AgentRunner, BashTool, ClearGoalTool, DelegateToAgentTool, EditTool,
61    FinishTaskTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, RecallSessionTool, RunContext,
62    SetGoalTool, SkillResolver, ToolRegistry, TrustySearchTool, UseSkillTool, WriteFileTool,
63    WriteFilesTool,
64};
65
66use super::sink::SessionToolEventSink;
67
68/// Default bash timeout for the engineer's tools, in seconds (mirrors
69/// `run_task::ENGINEER_BASH_TIMEOUT_SECS` — not exported, so duplicated as a
70/// small constant rather than restructuring that module's visibility).
71const ENGINEER_BASH_TIMEOUT_SECS: u64 = 120;
72
73/// Hardcoded delegated engineer agent name, matching the `run_task`/fixture
74/// convention used across this crate (`<agents_dir>/python-engineer.md`).
75/// A future ticket may make this configurable per `task.run` call.
76pub const ENGINEER_AGENT_NAME: &str = "python-engineer";
77
78/// Inputs to start one background task execution.
79///
80/// Why: bundles everything `spawn_task_run` needs so `task::protocol`'s
81/// handler stays a thin params-parsing shim.
82/// What: `session_id` must already exist in the registry (created by the
83/// caller — see `task::protocol::task_run`); `agent_name` is the top-level
84/// (PM) agent, `task` is the free-form request text, `agents_dir` mirrors
85/// `run_task::RunTaskParams`, and `model_override` pins the
86/// DELEGATED ENGINEER's model for this run only (mirrors `run_task`'s
87/// `--engineer-model`). `mode` (#2059) is the ALREADY-RESOLVED `HarnessMode`
88/// (`task::protocol::task_run` resolves it via `crate::mode::resolve_mode`
89/// before constructing this — resolution is a request-parsing concern, not
90/// an execution one). `binding` replaces what was a required `project:
91/// PathBuf`; see [`run_and_record`]'s docs for what each of its three states
92/// does to indexing, the memory palace, and the tools' working root.
93#[derive(Debug, Clone)]
94pub struct TaskRunParams {
95    pub session_id: String,
96    pub task: String,
97    pub agent_name: String,
98    /// This run's project binding — projectless, a non-git directory, or a git
99    /// repo. `ProjectBinding::None` is a fully supported state, not an error.
100    pub binding: ProjectBinding,
101    pub agents_dir: PathBuf,
102    pub model_override: Option<String>,
103    pub mode: HarnessMode,
104    /// Per-run wall-clock deadline override, in seconds (#2207). `None`
105    /// falls through to `crate::provider::resolve_deadline_secs`'s env-var
106    /// and default tiers — resolved once in `run_and_record` and applied to
107    /// BOTH the PM's own loop and the delegated engineer's loop.
108    pub deadline_secs: Option<u64>,
109    /// Test-only override for the PM loop's `AgentLoopConfig::telemetry_data_dir`
110    /// (issue #3902). `None` on every production call site
111    /// (`task::protocol::task_run`) — falls through to
112    /// `telemetry::default_data_dir()` exactly as before this field existed.
113    /// A `spawn_task_run` test that runs enough turns to trip a real
114    /// cadence/threshold fire (this daemon path always sets `cadence:
115    /// Some(_)` on the PM loop, see the `cadence` field's docs below) MUST
116    /// set this — `AgentLoop::telemetry_data_dir`'s `#[cfg(test)]` guard
117    /// panics on the first un-injected fire rather than risk the #3902 race.
118    /// `spawn_task_run` immediately `tokio::spawn`s the actual run, which
119    /// outlives the caller's own stack frame, so the
120    /// `telemetry::with_data_dir_env_fut` pattern
121    /// `compression_telemetry_tests.rs` uses (hold a lock across one
122    /// `.await`) does not fit here — injecting through this field is the
123    /// only mechanism that reaches a detached background task correctly.
124    pub telemetry_data_dir: Option<PathBuf>,
125}
126
127/// Reserve the session's execution slot and spawn the background run.
128///
129/// Why: the single entry point `task::protocol::task_run` calls. Reserving
130/// the slot SYNCHRONOUSLY (before any `tokio::spawn`) is what makes "a
131/// second overlapping `task.run` on the same session is rejected"
132/// observable to the CALLER of the second request, not just internally.
133/// What: calls `registry.begin_execution` (propagating `session_not_found`/
134/// `invalid_argument` — already terminal / already running — verbatim),
135/// then spawns [`run_and_record`] and immediately attaches the real
136/// `JoinHandle` back onto the registry (see `SessionRegistry::attach_execution_handle`'s
137/// docs for why that is a separate call).
138/// Test: `task::executor::tests::spawn_task_run_rejects_second_overlapping_run`;
139/// the full run is exercised by `tests/task_e2e.rs`.
140pub fn spawn_task_run(
141    registry: Arc<SessionRegistry>,
142    llm: Arc<dyn InferenceAdapter>,
143    params: TaskRunParams,
144) -> Result<(), RpcError> {
145    let cancel = registry.begin_execution(&params.session_id)?;
146    let session_id = params.session_id.clone();
147    let registry_for_task = Arc::clone(&registry);
148
149    let handle = tokio::spawn(async move {
150        run_and_record(registry_for_task, llm, params, cancel).await;
151    });
152    registry.attach_execution_handle(&session_id, handle);
153    Ok(())
154}
155
156/// The actual PM -> engineer run, executed entirely inside the spawned task.
157///
158/// Why: kept as one function (rather than splitting further) because every
159/// step depends on state built by the previous one; the doc comment on
160/// `spawn_task_run` and the module docs carry the "why this shape" framing.
161/// What: loads the PM config (a failure here is recorded as a `Failed`
162/// outcome, not a panic); builds the engineer runner + PM registry with the
163/// SAME shape `run_task::execute_run_task` uses; (#2344) retrieves this
164/// session's persistent PM `Transcript` via
165/// `SessionRegistry::begin_pm_transcript` (seeding it fresh on the session's
166/// first run, or appending `params.task` onto its existing history on every
167/// run after that) and drives the PM `AgentLoop` against it via
168/// `AgentLoop::run_with_transcript` instead of the fresh-seeding `run` (both
169/// the PM and the delegated engineer share the #2056 sink + cancel flag);
170/// persists that transcript back UNCONDITIONALLY via
171/// `SessionRegistry::store_pm_transcript` so a future run continues from
172/// here even on failure/cancellation/timeout; prices the accounting
173/// transcript per-role; persists that run outcome (now CUMULATIVE, #2344);
174/// and transitions the session to `Finished`/`Cancelled`/`Failed` before
175/// clearing the execution slot. (#2344) `Finished` is no longer a dead end —
176/// `SessionRegistry::begin_execution` resumes a `Finished` session back to
177/// `Running` on its next `task.run`, which is what makes this whole
178/// persistence chain observable across repeated calls. (#2345) after this
179/// run's turn (prompt + whatever response text it produced, even on
180/// failure/cancellation/timeout) is captured, it is durably enqueued onto the
181/// session's lazily-constructed `session::TurnMemorySink` — fire-and-forget,
182/// never able to block or fail this run — for the ONE-time-per-session dual
183/// write to trusty-memory (`chat_turn_append` + `memory_remember`); see
184/// `session::memory_sink` module docs for the fail-open contract and the
185/// per-run (not yet per-turn) enqueue granularity this ticket settles for.
186///
187/// **Projectless (`ProjectBinding::None`).** Three things assume a project, and
188/// each gets a DEFINED behaviour rather than a panic: indexing is **skipped**
189/// (nothing to index); the project-scoped memory palace is **skipped** (no
190/// project to scope one to — `memory_sink_for` takes `Option<&Path>` and returns
191/// `None`); and the fs/bash tools, which need a real directory to be
192/// constructible at all, are rooted at an **ephemeral scratch dir** discarded
193/// when the run ends. The scratch root is the deliberate choice over dropping
194/// the tools entirely: an engineer with no file tools fails in confusing ways,
195/// whereas a throwaway root keeps chat/planning coherent while guaranteeing
196/// nothing lands in a project the operator never chose. It is logged at `warn`
197/// (stderr) so a projectless write is observable, never silent. `CLAUDE.md`,
198/// catch-up, skills, and the settings.json mode tier all already degrade to
199/// "absent" for a directory that has none, so they need no projectless
200/// special-casing — they simply find nothing in the scratch root.
201async fn run_and_record(
202    registry: Arc<SessionRegistry>,
203    llm: Arc<dyn InferenceAdapter>,
204    params: TaskRunParams,
205    cancel: Arc<AtomicBool>,
206) {
207    let session_id = params.session_id.clone();
208
209    // Resolve the working root BEFORE anything else: every step below needs a
210    // real directory, and projectless has none. `_scratch` must stay alive for
211    // the whole run — dropping a `TempDir` deletes it — so it is bound here,
212    // not inside the `else` arm.
213    let _scratch = match params.binding.root() {
214        Some(_) => None,
215        None => match tempfile::tempdir() {
216            Ok(dir) => {
217                tracing::warn!(
218                    session_id = %session_id,
219                    scratch_root = %dir.path().display(),
220                    "projectless run: no project bound — file tools are rooted at an \
221                     ephemeral scratch dir that is DISCARDED when this run ends, and \
222                     nothing is indexed. Bind a project to persist work."
223                );
224                Some(dir)
225            }
226            Err(e) => {
227                finish_with_failure(
228                    &registry,
229                    &session_id,
230                    &format!("projectless scratch root error: {e}"),
231                )
232                .await;
233                return;
234            }
235        },
236    };
237    let work_root: PathBuf = match (params.binding.root(), &_scratch) {
238        (Some(root), _) => root.to_path_buf(),
239        (None, Some(dir)) => dir.path().to_path_buf(),
240        // Unreachable: the match above binds `_scratch` to `Some` for exactly
241        // the `None` root case, returning early on failure. Handled rather than
242        // `unwrap`ped per the crate's no-panic-in-library rule.
243        (None, None) => {
244            finish_with_failure(&registry, &session_id, "projectless scratch root missing").await;
245            return;
246        }
247    };
248
249    // Trusty-search-first discovery (PR B): at task START, best-effort/detached,
250    // ensure the working project is indexed so the delegated engineer's
251    // `search`/`grep` tools are useful while this run proceeds. Fail-open,
252    // non-blocking, and git-optional (git is a nice-to-have, not required) —
253    // reuses the ONE shared helper (see
254    // `run_task::ensure_project_indexed_in_background`) so the daemon and CLI
255    // paths can never diverge.
256    //
257    // Unlike the CLI path, this daemon path OWNS a session, so it also
258    // publishes the resulting readiness as an `Event::IndexReadiness` (#2784
259    // UI Phase-1): the UI is a thin client over this daemon, so a warming
260    // index is only renderable if it arrives as an event. Without it a
261    // mid-warm-up empty search is indistinguishable from a ready index with
262    // genuinely zero hits — opposite meanings, identical wire shape.
263    //
264    // Gated on `should_index` so a projectless run never indexes its
265    // throwaway scratch root — note the gate is `should_index`, i.e. "is a
266    // project bound", NOT "is it git": a non-git directory DOES index
267    // (#2728/#2747).
268    if params.binding.should_index() {
269        let registry = Arc::clone(&registry);
270        let session_id = session_id.clone();
271        crate::run_task::ensure_project_indexed_in_background(
272            work_root.clone(),
273            Some(Box::new(move |readiness| {
274                let summary = match &readiness {
275                    Some(r) => r.summary(),
276                    None => "trusty-search index readiness unknown: no reachable daemon — \
277                             search results may be incomplete and an empty result is not \
278                             evidence of absence"
279                        .to_string(),
280                };
281                if let Err(e) =
282                    registry.record_index_readiness(&session_id, readiness.as_ref(), &summary)
283                {
284                    // The session finishing before this detached probe lands is
285                    // an ordinary race, not a fault — log and drop, exactly as
286                    // the tool-event sink does.
287                    tracing::debug!(session_id = %session_id, "record_index_readiness skipped: {e}");
288                }
289            })),
290        );
291    }
292    let transcript: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
293    let sink: Arc<dyn ToolEventSink> = Arc::new(SessionToolEventSink::new(
294        Arc::clone(&registry),
295        session_id.clone(),
296    ));
297
298    // #2264: mirrors `run_task::execute_run_task`'s own resolution — one
299    // shared (optional) debug-capture sink for the whole run, so pm and
300    // engineer turns land in one globally-ordered JSONL file when
301    // `TCODE_DEBUG_TRANSCRIPT` is set, and cost nothing when it is not.
302    let debug_sink: Option<Arc<DebugCaptureSink>> = DebugCaptureSink::from_env();
303
304    // (#3046) Routes through the shared disk-then-embedded resolver —
305    // mirrors `run_task::execute_run_task`'s own PM-config load — so a
306    // top-level agent name that only exists in the embedded roster (e.g.
307    // `engineer`, `rust-engineer`) resolves here too, on the daemon-driven
308    // session path.
309    let pm_config = match crate::agents::resolve_agent(&params.agents_dir, &params.agent_name) {
310        Ok(cfg) => cfg,
311        Err(e) => {
312            finish_with_failure(&registry, &session_id, &format!("PM config error: {e}")).await;
313            return;
314        }
315    };
316
317    let project_context = load_project_context(&work_root);
318    let pm_model = resolve_model(&pm_config, None);
319    let engineer_model = resolve_engineer_model(&params);
320
321    // #2207: resolve the run's wall-clock deadline once, applied to BOTH the
322    // PM's own loop (below) and the delegated engineer's loop
323    // (`build_engineer_runner`, via `with_timeout_secs`).
324    let deadline_secs = resolve_deadline_secs(params.deadline_secs);
325
326    // #2069: discover the (cheap, metadata-only) skill catalog and, in
327    // DailyDriver mode only, register `use_skill` so the PM can lazily fetch
328    // a skill's full body on demand. Parity never sees the catalog or the
329    // tool — see `assemble_system_prompt_for_mode`'s docs.
330    let skills_catalog = daily_driver_skills_catalog(&params, &work_root);
331
332    let engineer_runner = build_engineer_runner(
333        wrap_with_debug_capture(Arc::clone(&llm), ENGINEER_AGENT_NAME, debug_sink.as_ref()),
334        &params,
335        &work_root,
336        EngineerPromptContext {
337            project_context: project_context.clone(),
338            skills_catalog: skills_catalog.as_ref().map(|(catalog, _)| catalog.clone()),
339            skill_resolver: skills_catalog
340                .as_ref()
341                .map(|(_, resolver)| Arc::clone(resolver)),
342        },
343        Arc::clone(&transcript),
344        Arc::clone(&sink),
345        Arc::clone(&cancel),
346    );
347
348    // Catch-up is already git-optional and fail-open (it degrades to `None` for
349    // a directory with no history), so the projectless scratch root needs no
350    // special-casing here — it simply yields no digest.
351    let catchup_ctx = crate::catchup::pm_catchup_context(&work_root).await;
352    let pm_system = assemble_system_prompt_for_mode(
353        params.mode,
354        &pm_config,
355        project_context.as_deref(),
356        catchup_ctx.as_deref(),
357        skills_catalog.as_ref().map(|(catalog, _)| catalog.as_str()),
358    );
359
360    // #2344: seed the PM's persistent conversation on this session's FIRST
361    // run, or append `params.task` as a new user turn onto its EXISTING,
362    // already-growing history on every run after that — see
363    // `SessionRegistry::begin_pm_transcript`'s docs. A failure here can only
364    // be `session_not_found` (the session vanished between `begin_execution`
365    // and here), handled the same way a PM-config load failure is above.
366    // (#2347) Fetched BEFORE `pm_registry` is built (moved up from its
367    // original post-registry position) so `set_goal`/`clear_goal` can be
368    // registered against this SAME transcript's live goal slots via
369    // `goals_handle` — see that method's docs for why the tools and the
370    // transcript must share one `Arc<Mutex<GoalSlots>>`.
371    let mut pm_transcript =
372        match registry.begin_pm_transcript(&session_id, &pm_system, &params.task) {
373            Ok(t) => t,
374            Err(e) => {
375                finish_with_failure(&registry, &session_id, &format!("PM transcript error: {e}"))
376                    .await;
377                return;
378            }
379        };
380    let goals = pm_transcript.goals_handle();
381
382    // #2345/#2348: fetch (lazily constructing on the session's first run)
383    // this session's turn-recorder sink BEFORE building the PM registry, so
384    // its already-resolved base_url/palace can be reused by #2348's
385    // `recall_session` tool below rather than re-derived. Fetching this
386    // early (rather than only once, right before the run, as the #2345
387    // comment near `turn_mark` below still does for its OWN purpose) is
388    // safe: `SessionRegistry::memory_sink_for` is idempotent per session, so
389    // calling it twice in one run just returns the same `Arc` both times.
390    // Independent of the `pm_transcript`/`goals` fetch above (#2347) — the
391    // two features don't touch each other's state, so either order works.
392    // Projectless has no project to scope a memory palace to, so this yields
393    // `None` — see `memory_sink_for`'s `Option<&Path>` contract. The scratch
394    // root is deliberately NOT passed: deriving a palace id from a throwaway
395    // temp path would mint a fresh, orphaned palace on every projectless run.
396    let memory_sink = registry.memory_sink_for(&session_id, params.binding.root());
397
398    // #2072: `finish_task` gives the PM a structured, schema-validated way to
399    // signal completion alongside the delegate tool. (#2347) `set_goal`/
400    // `clear_goal` are registered ONLY on this daemon-session PM registry —
401    // never on `run_task`'s one-shot/bake-off registry or a delegated
402    // engineer's registry — since goal slots are a session, not sub-agent,
403    // feature.
404    let mut pm_registry = ToolRegistry::new();
405    pm_registry.register(Arc::new(
406        DelegateToAgentTool::new(engineer_runner).with_config_dir(params.agents_dir.clone()),
407    ));
408    pm_registry.register(Arc::new(FinishTaskTool::new()));
409    pm_registry.register(Arc::new(SetGoalTool::new(Arc::clone(&goals))));
410    pm_registry.register(Arc::new(ClearGoalTool::new(Arc::clone(&goals))));
411    if let Some((_, resolver)) = &skills_catalog {
412        pm_registry.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
413    }
414    // #2348: `recall_session` is registered ONLY on this daemon-session
415    // path — never on `run_task::execute_run_task`'s one-shot/bake-off path,
416    // which has no session to scope a memory query to and must keep
417    // Parity-mode prompts byte-identical to the pre-#2343 baseline (epic
418    // #2343 scope note). `None` only when the session vanished between
419    // `begin_execution` and here.
420    if let Some(sink) = &memory_sink {
421        pm_registry.register(Arc::new(RecallSessionTool::new(
422            session_id.clone(),
423            sink.socket().to_path_buf(),
424            sink.palace().to_string(),
425        )));
426    }
427
428    let pm_llm: Arc<dyn InferenceAdapter> = Arc::new(RecordingLlmClient::new(
429        wrap_with_debug_capture(Arc::clone(&llm), "pm", debug_sink.as_ref()),
430        "pm",
431        Arc::clone(&transcript),
432    ));
433
434    let pm_loop = AgentLoop::new(
435        AgentLoopConfig {
436            model: pm_model.clone(),
437            max_tokens: resolve_max_tokens(&pm_config),
438            mode: params.mode,
439            timeout_secs: deadline_secs,
440            // #2308: model-aware compaction threshold — see
441            // `CompactionConfig::for_context_window`'s doc for why the
442            // struct-update `..AgentLoopConfig::default()` below must not be
443            // allowed to silently supply the flat, model-blind default here.
444            compaction: CompactionConfig::for_context_window(resolve_context_window(&pm_model)),
445            // #2346: the cadence compressor is opt-in per `AgentLoopConfig`
446            // (defaults to `None`) — this daemon-driven, persistent-session
447            // PM loop is the ONE call site that enables it, resolved from
448            // this project's `.claude/settings.json`/env-var precedence
449            // chain (`resolve_cadence_config`). The delegated engineer's own
450            // loop (`build_engineer_runner` below) and `run_task`'s legacy
451            // one-shot/bake-off path both keep the default `None` — zero
452            // behaviour change there, per #2346's explicit scope.
453            cadence: Some(resolve_cadence_config(&work_root)),
454            // #3902: test-only DI, see `TaskRunParams::telemetry_data_dir`'s
455            // docs. `None` (every production call site) falls through to
456            // `telemetry::default_data_dir()` unchanged.
457            telemetry_data_dir: params.telemetry_data_dir.clone(),
458            ..AgentLoopConfig::default()
459        },
460        pm_llm,
461        Arc::new(pm_registry),
462    )
463    .with_tool_event_sink(Arc::clone(&sink))
464    // (UI Phase 1) Attribute this loop's tool events to the PM. `sink` is the
465    // SAME `Arc` handed to `build_engineer_runner` above, so without this the
466    // PM's and the engineer's tool calls arrive on one stream indistinguishable
467    // from each other. `params.agent_name` (default `"pm"`) is the name the
468    // rest of the taxonomy already uses for this agent.
469    .with_agent(params.agent_name.clone())
470    // (DOC-39 AC-13) The PM/root agent also needs a STABLE id so its
471    // root-attributed events correlate — unlike a delegated engineer (a
472    // fresh UUID per `delegate_to_agent` spawn, see
473    // `runner::in_process::InProcessAgentRunner::run_pipeline`), the PM's
474    // loop is re-entered on EVERY `task.run` against this same session
475    // (`AgentLoop::run_with_transcript` against the persistent
476    // `pm_transcript`), so its id must be SESSION-scoped, not re-minted per
477    // call — otherwise the PM's own tool events would spuriously look like a
478    // new "spawn" on every run. Namespaced with a `pm-` prefix so it reads
479    // distinctly from an engineer's bare UUID in a raw event dump.
480    .with_agent_id(format!("pm-{session_id}"))
481    // (#3867) Stamps this session's real id onto every durable
482    // compression-telemetry JSONL record this loop's cadence/threshold
483    // instrumentation emits — see `AgentLoop::with_session_id`'s docs.
484    .with_session_id(session_id.clone())
485    .with_cancel_flag(Arc::clone(&cancel))
486    // #2279: mirrors `run_task::execute_run_task`'s own wiring — the PM
487    // never calls `bash` itself, so its verify-before-finish gate scans the
488    // delegated engineer's turns via the SAME shared `transcript` the
489    // engineer's `RecordingLlmClient` records into (`build_engineer_runner`
490    // above), rather than the PM's own (bash-less) transcript.
491    .with_finish_gate(crate::verify_gate::pm_finish_gate(Arc::clone(&transcript)));
492
493    // #2345: mark "how much assistant text exists before this run" so the
494    // turn recorder can later scope its durable dual-write to just THIS
495    // run's new response text via `Transcript::assistant_text_since`, even
496    // though `pm_transcript` is the session's whole cumulative (#2344)
497    // conversation. `pm_transcript` was already fetched above (moved up for
498    // #2347's goal-tool wiring — see the comment on that fetch) and
499    // `memory_sink` was already fetched above too (before building
500    // `pm_registry`, #2348) — `SessionRegistry::memory_sink_for` is
501    // idempotent per session, so reusing that same `Option<Arc<..>>` here
502    // needs no second call; this line only marks the current position.
503    let turn_mark = pm_transcript.assistant_text_mark();
504
505    let result = pm_loop
506        .run_with_transcript(&mut pm_transcript, &params.task)
507        .await;
508
509    // #2345: capture this run's new assistant text BEFORE `pm_transcript` is
510    // moved into `store_pm_transcript` below. Per-turn (not per-run) enqueue
511    // is the ideal granularity (#2346 upgrade path — the loop currently has
512    // no per-turn callback/event seam to hook synchronously); a per-RUN batch
513    // of "this run's prompt -> this run's aggregated response text" is the
514    // documented, acceptable fallback for this ticket.
515    let turn_response = pm_transcript.assistant_text_since(turn_mark);
516
517    // #2344: persist the (possibly partial) conversation back onto the
518    // session UNCONDITIONALLY — success, failure, cancellation, or
519    // timeout — so the NEXT `task.run` on this session continues from
520    // exactly where this one left off, rather than silently re-seeding.
521    registry.store_pm_transcript(&session_id, pm_transcript);
522
523    // #2345: durably record this run's turn (fire-and-forget, never blocks
524    // or fails this run — see `session::memory_sink` module docs). Recorded
525    // regardless of `result` (success/failure/cancellation/timeout all still
526    // produce a real prompt and whatever response text WAS generated before
527    // interruption) so the durable record matches `pm_transcript`'s own
528    // "persist unconditionally" contract above. `memory_sink` is `None` only
529    // if the session vanished between `begin_execution` and here.
530    if let Some(sink) = memory_sink {
531        sink.enqueue(session_id.clone(), params.task.clone(), turn_response);
532    }
533
534    // #2206: usage/cost are aggregated from every turn that DID complete
535    // regardless of `result` — this call already ran unconditionally before
536    // the terminal-status match below, so a `Failed`/`DeadlineExceeded`
537    // outcome still persists real telemetry, not zeroed placeholders.
538    let turns = transcript.lock().map(|g| g.clone()).unwrap_or_default();
539    let (usage, cost) = aggregate_usage_per_role(&turns, &pm_model, &engineer_model);
540    registry.set_run_outcome(&session_id, turns, usage, Some(cost));
541
542    // #2207/#3888: matched EXHAUSTIVELY over every `AgentLoopError` variant
543    // (not a catch-all) so the compiler forces a decision the next time that
544    // enum grows one — a catch-all is exactly how #3888 happened the first
545    // time (`TurnCapExceeded` silently absorbed into `Failed`). `Llm` is a
546    // genuine failure. `Timeout`/`TurnCapExceeded` are cooperative pauses,
547    // not failures — `pm_transcript` was already persisted unconditionally
548    // above, so the next `task.run` continues right where this one left off;
549    // `DeadlineExceeded`/`TurnCapExceeded` are distinct resumable statuses so
550    // a consumer can tell "timed out" from "used its turn budget".
551    // `StoppedBySignal` is NOT wired into this `pm_loop` today (no
552    // `.with_stop_signal(...)` call below), so this arm is dead code for now
553    // — but its mapping still matters for whoever wires it in later.
554    // Deliberately grouped with `Llm` as `Failed` rather than assumed
555    // resumable: `AgentLoop::with_stop_signal` has exactly one caller in the
556    // crate today (`run_task::mod`, wired to
557    // `RedelegationCapSignal::is_cap_reached()`), and that signal's own doc
558    // (`run_task::redelegation`) is explicit that it fires for "a genuinely
559    // broken run whose delegations keep failing" and "stopping really is
560    // correct" at that point — a stop-and-stay-stopped condition, not a
561    // cooperative pause like the turn cap. Whoever wires a DIFFERENT signal
562    // into this loop must revisit this arm on its own merits rather than
563    // inherit this default.
564    let terminal_status = match result {
565        Ok(_output) => SessionStatus::Finished,
566        Err(crate::agent_loop::AgentLoopError::Cancelled { .. }) => SessionStatus::Cancelled,
567        Err(e @ crate::agent_loop::AgentLoopError::Timeout { .. }) => {
568            let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
569            SessionStatus::DeadlineExceeded
570        }
571        Err(e @ crate::agent_loop::AgentLoopError::TurnCapExceeded { .. }) => {
572            let _ =
573                registry.record_log(&session_id, "info", &format!("run paused (resumable): {e}"));
574            SessionStatus::TurnCapExceeded
575        }
576        Err(
577            e @ (crate::agent_loop::AgentLoopError::Llm(_)
578            | crate::agent_loop::AgentLoopError::StoppedBySignal { .. }),
579        ) => {
580            let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
581            SessionStatus::Failed
582        }
583    };
584    let _ = registry.finish(&session_id, terminal_status);
585    registry.finish_execution(&session_id);
586}
587
588/// Build the in-process engineer runner with project-scoped fs/bash tools,
589/// the #2056 sink, the shared cancel flag, and (#2059) the SAME resolved
590/// `HarnessMode` as the delegating PM (mirrors `run_task::build_engineer_runner`,
591/// which is private to that module).
592///
593/// `skills_catalog` (#2069) is the same rendered metadata catalog the PM's own
594/// prompt gets, threaded through so the delegated engineer's DailyDriver
595/// prompt also sees it. #2152/#2942: the `use_skill` *tool* is now also wired
596/// into the engineer's own per-delegation registry (`ProjectToolFactory::build`)
597/// against the SAME resolver instance the PM's own `use_skill` tool and catalog
598/// were built from — see [`EngineerPromptContext::skill_resolver`]. #2207: resolves the SAME wall-clock
599/// budget applied to the delegating PM's own loop via
600/// `crate::provider::resolve_deadline_secs(params.deadline_secs)` — called
601/// again here (rather than threaded in as an extra argument) purely to keep
602/// this function's arity under clippy's `too_many_arguments` gate; the
603/// resolver is pure given the same `params.deadline_secs`/env state, so a
604/// second call is not a correctness risk.
605///
606/// `work_root` is the directory the engineer's fs/bash tools are scoped to: the
607/// bound project root, or — when projectless — the run's ephemeral scratch dir
608/// (see [`run_and_record`]). It is passed explicitly rather than read off
609/// `params` because the scratch root does not exist until the run begins.
610/// [`EngineerPromptContext`] bundles the two prompt strings that already
611/// travelled together, keeping this function's arity under clippy's
612/// `too_many_arguments` gate now that `work_root` is threaded in.
613fn build_engineer_runner(
614    llm: Arc<dyn InferenceAdapter>,
615    params: &TaskRunParams,
616    work_root: &Path,
617    prompt: EngineerPromptContext,
618    transcript: SharedTranscript,
619    sink: Arc<dyn ToolEventSink>,
620    cancel: Arc<AtomicBool>,
621) -> Arc<dyn AgentRunner> {
622    let EngineerPromptContext {
623        project_context,
624        skills_catalog,
625        skill_resolver,
626    } = prompt;
627    let engineer_llm: Arc<dyn InferenceAdapter> = Arc::new(RecordingLlmClient::new(
628        llm,
629        ENGINEER_AGENT_NAME,
630        transcript,
631    ));
632
633    let factory: Arc<dyn RegistryFactory> = Arc::new(ProjectToolFactory {
634        project: work_root.to_path_buf(),
635        mode: params.mode,
636        skill_resolver,
637    });
638
639    let mut runner = InProcessAgentRunner::new(engineer_llm, factory, params.agents_dir.clone())
640        .with_tool_event_sink(sink)
641        .with_cancel_flag(cancel)
642        .with_mode(params.mode)
643        .with_timeout_secs(resolve_deadline_secs(params.deadline_secs));
644    if let Some(ctx) = project_context {
645        runner = runner.with_project_context(ctx);
646    }
647    if let Some(catalog) = skills_catalog {
648        runner = runner.with_skills_catalog(catalog);
649    }
650    apply_engineer_model_override(Arc::new(runner), params)
651}
652
653/// The prompt-context strings (plus the skill resolver the `use_skill` tool
654/// needs) the delegated engineer's system prompt and registry are assembled
655/// from.
656///
657/// Why: `project_context`/`skills_catalog` are always produced and consumed
658/// together and are positionally adjacent — bundling them removes a real
659/// easy-to-transpose-the-arguments hazard and keeps
660/// [`build_engineer_runner`]'s arity under clippy's `too_many_arguments` gate
661/// now that `work_root` must also be threaded through for projectless runs.
662/// #2152: `skill_resolver` joined the bundle so `ProjectToolFactory::build`
663/// can register `use_skill` against the SAME resolver instance backing
664/// `skills_catalog` and the PM's own `use_skill` tool, rather than the
665/// engineer's registry omitting the tool its prompt explicitly advertises
666/// (closes the gap PR #2942 fixed in the legacy `run_task/mod.rs` path but
667/// left open here).
668/// What: `project_context` is the project's `CLAUDE.md` (`None` when absent —
669/// always the case projectless, since the scratch root has none);
670/// `skills_catalog` is the rendered skill-metadata catalog from either the
671/// project's `.claude/skills/` or, when that is empty or absent,
672/// `crate::assets::DEFAULT_SKILLS` — the embedded default catalog
673/// (`skills::discover_skill_metadata`'s embedded-fallback, #2895). `None`
674/// only in `HarnessMode::Parity` (which never discovers skills at all, disk
675/// or embedded); in `DailyDriver` the embedded fallback means this is
676/// effectively always `Some`. `skill_resolver` is `Some` under the exact same
677/// condition as `skills_catalog` (both come from the same
678/// `daily_driver_skills_catalog` call at the sole construction site).
679/// Test: exercised via `task::executor::tests::*`'s engineer-runner paths;
680/// `engineer_registry_includes_use_skill_when_catalog_present` pins the
681/// registry-side contract.
682struct EngineerPromptContext {
683    project_context: Option<String>,
684    skills_catalog: Option<String>,
685    skill_resolver: Option<Arc<dyn SkillResolver>>,
686}
687
688/// Discover the (cheap, metadata-only) skill catalog under `work_root` and
689/// build a resolver over it — but only in `HarnessMode::DailyDriver`.
690///
691/// Why: #2069's scope note is explicit — "Parity mode should NOT
692/// progressively disclose" — so `Parity` runs must never discover
693/// `.claude/skills/` at all, let alone advertise the `use_skill` tool or
694/// inject the catalog into the prompt.
695/// What: Returns `None` for `HarnessMode::Parity`; otherwise
696/// `Some((rendered_catalog, resolver))` — the resolver backs the `use_skill`
697/// tool registration. `skills::discover_skill_metadata` (the source behind
698/// `resolver.metadata()`) falls back to the embedded default skill catalog
699/// (`crate::assets::DEFAULT_SKILLS`, #2895) when the project has no (or an
700/// empty) `.claude/skills/` directory, so in `HarnessMode::DailyDriver` the
701/// catalog is no longer ever empty — a projectless run (scratch root, no
702/// `.claude/skills/`) now resolves to the embedded catalog rather than
703/// `None`, the same as any other project with no disk skills.
704/// Test: `task::executor::tests::daily_driver_skills_catalog_*`.
705fn daily_driver_skills_catalog(
706    params: &TaskRunParams,
707    work_root: &Path,
708) -> Option<(String, Arc<dyn SkillResolver>)> {
709    if params.mode != HarnessMode::DailyDriver {
710        return None;
711    }
712    let skills_dir = locate_skills_dir(work_root);
713    let resolver: Arc<dyn SkillResolver> = Arc::new(FsSkillResolver::new(skills_dir));
714    let catalog = format_skill_catalog(&resolver.metadata());
715    if catalog.is_empty() {
716        None
717    } else {
718        Some((catalog, resolver))
719    }
720}
721
722/// Builds the engineer's project-scoped tool registry for each delegation
723/// (mirrors `run_task::ProjectToolFactory`, which is private to that module).
724struct ProjectToolFactory {
725    project: PathBuf,
726    /// #2073: the delegating run's resolved `HarnessMode`, threaded onto the
727    /// engineer's `EditTool` so `HarnessMode::Parity` selects edit-format
728    /// order the same way regardless of which model is delegated to (§5.9's
729    /// edit-format reconciliation). `run_task::ProjectToolFactory` (the
730    /// legacy CLI path, which never resolves a `HarnessMode`) intentionally
731    /// does not carry this field — its `EditTool` stays on the pre-#2073
732    /// plain per-model order, unchanged.
733    mode: HarnessMode,
734    /// #2152: the SAME `Arc<dyn SkillResolver>` the PM's own `use_skill` tool
735    /// and the rendered skills catalog were built from (threaded through
736    /// [`EngineerPromptContext::skill_resolver`]). `None` under the same
737    /// condition `skills_catalog` is `None` (`HarnessMode::Parity`, which
738    /// never discovers skills). Mirrors `run_task::ProjectToolFactory`'s
739    /// `skill_resolver` field, which PR #2942 wired up on the legacy path.
740    skill_resolver: Option<Arc<dyn SkillResolver>>,
741}
742
743#[async_trait]
744impl RegistryFactory for ProjectToolFactory {
745    async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
746        // #2068: resolve the engineer's model slug so `EditTool` can pick its
747        // per-model edit-format fallback order (mirrors
748        // `run_task::ProjectToolFactory::build`, which is private to that module).
749        let model_slug = resolve_model(agent, Some(ctx));
750        let mut reg = ToolRegistry::new();
751        reg.register(Arc::new(ReadFileTool::new(&self.project)));
752        reg.register(Arc::new(WriteFileTool::new(&self.project)));
753        // #2681: batch-write decouples turn-count from file-count.
754        reg.register(Arc::new(WriteFilesTool::new(&self.project)));
755        reg.register(Arc::new(
756            EditTool::new(&self.project)
757                .with_model_slug(model_slug)
758                .with_mode(self.mode),
759        ));
760        // #1027: native file discovery so the engineer stops shelling out to
761        // find/grep/ls (the dominant bake-off agent-turn sink).
762        reg.register(Arc::new(GlobTool::new(&self.project)));
763        reg.register(Arc::new(GrepTool::new(&self.project)));
764        reg.register(Arc::new(ListDirTool::new(&self.project)));
765        // PR A (#2689): trusty-search-backed conceptual discovery as the PRIMARY
766        // path, with the local glob/grep tools above as the fail-open FALLBACK.
767        // DailyDriver ONLY — Parity must keep a byte-identical tool surface for
768        // benchmark fairness (it never sees MCP-backed tools), so this is gated
769        // on the delegating run's resolved `HarnessMode`.
770        if self.mode == HarnessMode::DailyDriver {
771            reg.register(Arc::new(TrustySearchTool::new(&self.project)));
772        }
773        reg.register(Arc::new(BashTool::new(
774            Some(self.project.clone()),
775            Duration::from_secs(ENGINEER_BASH_TIMEOUT_SECS),
776        )));
777        reg.register(Arc::new(FinishTaskTool::new()));
778        // #2152: mirrors the PM's own conditional `use_skill` registration —
779        // only when a skill catalog actually resolved for this delegation, so
780        // the engineer's prompt (which advertises `use_skill` whenever
781        // `with_skills_catalog` was applied) and its registry stay in sync.
782        if let Some(resolver) = &self.skill_resolver {
783            reg.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
784        }
785        Arc::new(reg)
786    }
787}
788
789/// Apply the per-run engineer-model override, if any (mirrors
790/// `run_task::apply_engineer_model_override` / `ModelPinningRunner`, both
791/// private to that module).
792fn apply_engineer_model_override(
793    runner: Arc<dyn AgentRunner>,
794    params: &TaskRunParams,
795) -> Arc<dyn AgentRunner> {
796    match &params.model_override {
797        Some(model) => Arc::new(ModelPinningRunner {
798            inner: runner,
799            model: model.clone(),
800        }),
801        None => runner,
802    }
803}
804
805/// An `AgentRunner` decorator pinning a fixed model for every delegation
806/// (mirrors `run_task::ModelPinningRunner`).
807struct ModelPinningRunner {
808    inner: Arc<dyn AgentRunner>,
809    model: String,
810}
811
812#[async_trait]
813impl AgentRunner for ModelPinningRunner {
814    async fn run(&self, agent_name: &str, task: &str) -> anyhow::Result<AgentOutput> {
815        let ctx = RunContext {
816            model: Some(self.model.clone()),
817            ..Default::default()
818        };
819        self.inner.run_with_context(agent_name, task, &ctx).await
820    }
821
822    async fn run_with_context(
823        &self,
824        agent_name: &str,
825        task: &str,
826        ctx: &RunContext,
827    ) -> anyhow::Result<AgentOutput> {
828        let mut ctx = ctx.clone();
829        ctx.model = Some(self.model.clone());
830        self.inner.run_with_context(agent_name, task, &ctx).await
831    }
832}
833
834/// Resolve the engineer's model the SAME way `InProcessAgentRunner` does
835/// internally, purely so the cost split below can price the engineer's
836/// turns against its own slug rather than blending everything under the PM
837/// model.
838///
839/// Why: `InProcessAgentRunner` resolves the engineer's model internally and
840/// does not expose it; `run_task::resolve_agent_model_slug` (#2061's #1475
841/// bug 1 fix) is the ONE shared implementation of "load config, apply
842/// override else resolve from config, degrade to `unknown` on load
843/// failure" this daemon path and `run_task::execute_run_task`'s legacy CLI
844/// path both now call, so they can never independently drift.
845/// What: thin wrapper binding this module's `ENGINEER_AGENT_NAME` constant
846/// and `params.model_override`.
847fn resolve_engineer_model(params: &TaskRunParams) -> String {
848    resolve_agent_model_slug(
849        &params.agents_dir,
850        ENGINEER_AGENT_NAME,
851        params.model_override.as_deref(),
852    )
853}
854
855/// Record a diagnostic log line and transition the session to `Failed`.
856///
857/// Why: a PM-config load failure happens before any loop runs, so there is
858/// no transcript/usage to persist — just the terminal state and a reason an
859/// operator (or a future `session.get_transcript`) can see.
860async fn finish_with_failure(registry: &SessionRegistry, session_id: &str, message: &str) {
861    let _ = registry.record_log(session_id, "error", message);
862    let _ = registry.finish(session_id, SessionStatus::Failed);
863    registry.finish_execution(session_id);
864}
865
866#[cfg(test)]
867#[path = "executor_tests.rs"]
868mod tests;