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::agents::skill_refs::user_skill_refs_dir;
45use crate::binding::ProjectBinding;
46use crate::jsonrpc::RpcError;
47use crate::llm::{DebugCaptureSink, InferenceAdapter, wrap_with_debug_capture};
48use crate::mode::HarnessMode;
49use crate::project_context::load_project_context;
50use crate::prompt::assemble_system_prompt_for_mode;
51use crate::provider::{
52    resolve_context_window, resolve_deadline_secs, resolve_max_tokens, resolve_model,
53    resolve_model_with_override,
54};
55use crate::run_task::{
56    RecordingLlmClient, SharedTranscript, aggregate_usage_per_role, resolve_agent_model_slug,
57};
58use crate::runner::{InProcessAgentRunner, RegistryFactory};
59use crate::session::{SessionRegistry, SessionStatus, TaskResult, TaskResultStatus};
60use crate::skills::{FsSkillResolver, format_skill_catalog, locate_skills_dir};
61use crate::task::result_capture;
62use crate::tools::{
63    AgentOutput, AgentRunner, BashTool, ClearGoalTool, DelegateToAgentTool, EditTool,
64    FinishTaskTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, RecallSessionTool, RunContext,
65    SetGoalTool, SkillResolver, TodoWriteTool, ToolRegistry, TrustySearchTool, UseSkillTool,
66    WriteFileTool, WriteFilesTool,
67};
68
69use super::sink::SessionToolEventSink;
70use super::todo_store::SessionTodoStore;
71
72/// Default bash timeout for the engineer's tools, in seconds (mirrors
73/// `run_task::ENGINEER_BASH_TIMEOUT_SECS` — not exported, so duplicated as a
74/// small constant rather than restructuring that module's visibility).
75const ENGINEER_BASH_TIMEOUT_SECS: u64 = 120;
76
77/// Hardcoded delegated engineer agent name, matching the `run_task`/fixture
78/// convention used across this crate (`<agents_dir>/python-engineer.md`).
79/// A future ticket may make this configurable per `task.run` call.
80pub const ENGINEER_AGENT_NAME: &str = "python-engineer";
81
82/// Inputs to start one background task execution.
83///
84/// Why: bundles everything `spawn_task_run` needs so `task::protocol`'s
85/// handler stays a thin params-parsing shim.
86/// What: `session_id` must already exist in the registry (created by the
87/// caller — see `task::protocol::task_run`); `agent_name` is the top-level
88/// (PM) agent, `task` is the free-form request text, `agents_dir` mirrors
89/// `run_task::RunTaskParams`, and `model_override` pins the
90/// DELEGATED ENGINEER's model for this run only (mirrors `run_task`'s
91/// `--engineer-model`). `mode` (#2059) is the ALREADY-RESOLVED `HarnessMode`
92/// (`task::protocol::task_run` resolves it via `crate::mode::resolve_mode`
93/// before constructing this — resolution is a request-parsing concern, not
94/// an execution one). `binding` replaces what was a required `project:
95/// PathBuf`; see [`run_and_record`]'s docs for what each of its three states
96/// does to indexing, the memory palace, and the tools' working root.
97#[derive(Debug, Clone)]
98pub struct TaskRunParams {
99    pub session_id: String,
100    pub task: String,
101    pub agent_name: String,
102    /// This run's project binding — projectless, a non-git directory, or a git
103    /// repo. `ProjectBinding::None` is a fully supported state, not an error.
104    pub binding: ProjectBinding,
105    pub agents_dir: PathBuf,
106    pub model_override: Option<String>,
107    /// (#8030) Per-run override for the TOP-LEVEL agent's own model, carried
108    /// from `task.run`'s `pm_model` field (which the CLI's `--pm-model` flag
109    /// and `TCODE_PM_MODEL` feed). `None` leaves
110    /// [`crate::provider::resolve_model`]'s own ladder — the agent's front
111    /// matter, then `DEFAULT_MODEL` — exactly as it was before #8030. A short
112    /// alias (`opus`/`sonnet`/`haiku`) is normalised at the point of use.
113    /// Test: `task::executor::tests::pm_model_override_pins_the_top_level_model`,
114    /// `task::executor::tests::absent_pm_model_override_uses_the_agent_config_model_on_the_daemon_path`.
115    pub pm_model: Option<String>,
116    /// (#8128) Per-run override for this PM loop's turn cap, carried from
117    /// `task.run`'s `max_turns` field. `None` keeps
118    /// [`crate::agent_loop::AgentLoopConfig`]'s built-in 8, so an omitted
119    /// field is byte-for-byte the pre-#8128 behaviour. Rejected as
120    /// `invalid_argument` at the protocol layer when zero.
121    /// Test: `task::executor::tests::max_turns_override_reaches_the_pm_loop`.
122    pub max_turns: Option<u32>,
123    pub mode: HarnessMode,
124    /// Per-run wall-clock deadline override, in seconds (#2207). `None`
125    /// falls through to `crate::provider::resolve_deadline_secs`'s env-var
126    /// and default tiers — resolved once in `run_and_record` and applied to
127    /// BOTH the PM's own loop and the delegated engineer's loop.
128    pub deadline_secs: Option<u64>,
129    /// Test-only override for the PM loop's `AgentLoopConfig::telemetry_data_dir`
130    /// (issue #3902). `None` on every production call site
131    /// (`task::protocol::task_run`) — falls through to
132    /// `telemetry::default_data_dir()` exactly as before this field existed.
133    /// A `spawn_task_run` test that runs enough turns to trip a real
134    /// cadence/threshold fire (this daemon path always sets `cadence:
135    /// Some(_)` on the PM loop, see the `cadence` field's docs below) MUST
136    /// set this — `AgentLoop::telemetry_data_dir`'s `#[cfg(test)]` guard
137    /// panics on the first un-injected fire rather than risk the #3902 race.
138    /// `spawn_task_run` immediately `tokio::spawn`s the actual run, which
139    /// outlives the caller's own stack frame, so the
140    /// `telemetry::with_data_dir_env_fut` pattern
141    /// `compression_telemetry_tests.rs` uses (hold a lock across one
142    /// `.await`) does not fit here — injecting through this field is the
143    /// only mechanism that reaches a detached background task correctly.
144    pub telemetry_data_dir: Option<PathBuf>,
145    /// (#7948) The daemon-wide broker this run's `ask` rules suspend against
146    /// and `session.permission.respond` answers into. `None` makes the run
147    /// HEADLESS: an `ask` resolves at once per `permission_mode`.
148    pub permission_broker: Option<Arc<crate::permissions::PermissionBroker>>,
149    /// (#7948) What this run does with an `ask` it cannot put to a client.
150    pub permission_mode: crate::permissions::PermissionMode,
151    /// (#8031) Run `agent_name` ALONE: `true` swaps [`DelegateToAgentTool`]
152    /// on this run's registry for `agent_name`'s own tcode tools.
153    ///
154    /// Why: `tcode run-task engineer <task>` still advertised
155    /// `delegate_to_agent`, and the model self-delegated read/write work
156    /// instead of doing it — a guaranteed single-agent run was not
157    /// expressible. Dropping the tool alone is not enough: `read_file`,
158    /// `write_file`, `edit` and `bash` only ever existed on the DELEGATED
159    /// agent's per-delegation registry, so the top-level loop would have had
160    /// nothing to do the work with. Carried from `task.run`'s own
161    /// `no_delegate` request field, which the CLI's `--no-delegate` flag sets.
162    /// What: `true` skips the delegate tool and merges in the set
163    /// [`crate::runner::agent_registry`] builds for `agent_name` — the SAME
164    /// `ProjectToolFactory` output, narrowed by the SAME `tools.allowed` gate,
165    /// a delegation of that agent would get; the loop's existing
166    /// `PermissionGate` (already minted from this agent's config) then decides
167    /// each call. `false` (the default every pre-#8031 caller and every
168    /// omitted request field gets) registers the delegate tool exactly as
169    /// before and merges nothing.
170    /// Test: `task::executor::tests::no_delegate_run_omits_delegate_tool`,
171    /// `task::executor::tests::no_delegate_run_writes_the_file_without_delegating`,
172    /// `task::executor::tests::no_delegate_run_respects_the_agents_tools_allowlist`,
173    /// `task::executor::tests::session_path_registers_delegate_tool_by_default`.
174    pub no_delegate: bool,
175}
176
177/// Reserve the session's execution slot and spawn the background run.
178///
179/// Why: the single entry point `task::protocol::task_run` calls. Reserving
180/// the slot SYNCHRONOUSLY (before any `tokio::spawn`) is what makes "a
181/// second overlapping `task.run` on the same session is rejected"
182/// observable to the CALLER of the second request, not just internally.
183/// What: calls `registry.begin_execution` (propagating `session_not_found`/
184/// `invalid_argument` — already terminal / already running — verbatim),
185/// then spawns [`run_and_record`] and immediately attaches the real
186/// `JoinHandle` back onto the registry (see `SessionRegistry::attach_execution_handle`'s
187/// docs for why that is a separate call).
188/// Test: `task::executor::tests::spawn_task_run_rejects_second_overlapping_run`;
189/// the full run is exercised by `tests/task_e2e.rs`.
190pub fn spawn_task_run(
191    registry: Arc<SessionRegistry>,
192    llm: Arc<dyn InferenceAdapter>,
193    params: TaskRunParams,
194) -> Result<(), RpcError> {
195    let cancel = registry.begin_execution(&params.session_id)?;
196    let session_id = params.session_id.clone();
197    let registry_for_task = Arc::clone(&registry);
198
199    let handle = tokio::spawn(async move {
200        run_and_record(registry_for_task, llm, params, cancel).await;
201    });
202    registry.attach_execution_handle(&session_id, handle);
203    Ok(())
204}
205
206/// The actual PM -> engineer run, executed entirely inside the spawned task.
207///
208/// Why: kept as one function (rather than splitting further) because every
209/// step depends on state built by the previous one; the doc comment on
210/// `spawn_task_run` and the module docs carry the "why this shape" framing.
211/// What: loads the PM config (a failure here is recorded as a `Failed`
212/// outcome, not a panic); builds the engineer runner + PM registry with the
213/// SAME shape `run_task::execute_run_task` uses; (#2344) retrieves this
214/// session's persistent PM `Transcript` via
215/// `SessionRegistry::begin_pm_transcript` (seeding it fresh on the session's
216/// first run, or appending `params.task` onto its existing history on every
217/// run after that) and drives the PM `AgentLoop` against it via
218/// `AgentLoop::run_with_transcript` instead of the fresh-seeding `run` (both
219/// the PM and the delegated engineer share the #2056 sink + cancel flag);
220/// persists that transcript back UNCONDITIONALLY via
221/// `SessionRegistry::store_pm_transcript` so a future run continues from
222/// here even on failure/cancellation/timeout; prices the accounting
223/// transcript per-role; persists that run outcome (now CUMULATIVE, #2344);
224/// and transitions the session to `Finished`/`Cancelled`/`Failed` before
225/// clearing the execution slot. (#2344) `Finished` is no longer a dead end —
226/// `SessionRegistry::begin_execution` resumes a `Finished` session back to
227/// `Running` on its next `task.run`, which is what makes this whole
228/// persistence chain observable across repeated calls. (#2345) after this
229/// run's turn (prompt + whatever response text it produced, even on
230/// failure/cancellation/timeout) is captured, it is durably enqueued onto the
231/// session's lazily-constructed `session::TurnMemorySink` — fire-and-forget,
232/// never able to block or fail this run — for the ONE-time-per-session dual
233/// write to trusty-memory (`chat_turn_append` + `memory_remember`); see
234/// `session::memory_sink` module docs for the fail-open contract and the
235/// per-run (not yet per-turn) enqueue granularity this ticket settles for.
236///
237/// **Projectless (`ProjectBinding::None`).** Three things assume a project, and
238/// each gets a DEFINED behaviour rather than a panic: indexing is **skipped**
239/// (nothing to index); the project-scoped memory palace is **skipped** (no
240/// project to scope one to — `memory_sink_for` takes `Option<&Path>` and returns
241/// `None`); and the fs/bash tools, which need a real directory to be
242/// constructible at all, are rooted at an **ephemeral scratch dir** discarded
243/// when the run ends. The scratch root is the deliberate choice over dropping
244/// the tools entirely: an engineer with no file tools fails in confusing ways,
245/// whereas a throwaway root keeps chat/planning coherent while guaranteeing
246/// nothing lands in a project the operator never chose. It is logged at `warn`
247/// (stderr) so a projectless write is observable, never silent. `CLAUDE.md`,
248/// catch-up, skills, and the settings.json mode tier all already degrade to
249/// "absent" for a directory that has none, so they need no projectless
250/// special-casing — they simply find nothing in the scratch root.
251async fn run_and_record(
252    registry: Arc<SessionRegistry>,
253    llm: Arc<dyn InferenceAdapter>,
254    params: TaskRunParams,
255    cancel: Arc<AtomicBool>,
256) {
257    let session_id = params.session_id.clone();
258
259    // Resolve the working root BEFORE anything else: every step below needs a
260    // real directory, and projectless has none. `_scratch` must stay alive for
261    // the whole run — dropping a `TempDir` deletes it — so it is bound here,
262    // not inside the `else` arm.
263    let _scratch = match params.binding.root() {
264        Some(_) => None,
265        None => match tempfile::tempdir() {
266            Ok(dir) => {
267                tracing::warn!(
268                    session_id = %session_id,
269                    scratch_root = %dir.path().display(),
270                    "projectless run: no project bound — file tools are rooted at an \
271                     ephemeral scratch dir that is DISCARDED when this run ends, and \
272                     nothing is indexed. Bind a project to persist work."
273                );
274                Some(dir)
275            }
276            Err(e) => {
277                finish_with_failure(
278                    &registry,
279                    &session_id,
280                    &format!("projectless scratch root error: {e}"),
281                )
282                .await;
283                return;
284            }
285        },
286    };
287    let work_root: PathBuf = match (params.binding.root(), &_scratch) {
288        (Some(root), _) => root.to_path_buf(),
289        (None, Some(dir)) => dir.path().to_path_buf(),
290        // Unreachable: the match above binds `_scratch` to `Some` for exactly
291        // the `None` root case, returning early on failure. Handled rather than
292        // `unwrap`ped per the crate's no-panic-in-library rule.
293        (None, None) => {
294            finish_with_failure(&registry, &session_id, "projectless scratch root missing").await;
295            return;
296        }
297    };
298
299    // #4351: the "before" half of the run's on-disk footprint, taken before a
300    // single turn executes so the after-comparison names THIS run's change and
301    // not pre-existing dirty-tree noise. Non-mutating (see `run_task::diff`).
302    let before_snapshot = crate::run_task::diff::capture_snapshot(&work_root);
303
304    // Trusty-search-first discovery (PR B): at task START, best-effort/detached,
305    // ensure the working project is indexed so the delegated engineer's
306    // `search`/`grep` tools are useful while this run proceeds. Fail-open,
307    // non-blocking, and git-optional (git is a nice-to-have, not required) —
308    // reuses the ONE shared helper (see
309    // `run_task::ensure_project_indexed_in_background`) so the daemon and CLI
310    // paths can never diverge.
311    //
312    // Unlike the CLI path, this daemon path OWNS a session, so it also
313    // publishes the resulting readiness as an `Event::IndexReadiness` (#2784
314    // UI Phase-1): the UI is a thin client over this daemon, so a warming
315    // index is only renderable if it arrives as an event. Without it a
316    // mid-warm-up empty search is indistinguishable from a ready index with
317    // genuinely zero hits — opposite meanings, identical wire shape.
318    //
319    // Gated on `should_index` so a projectless run never indexes its
320    // throwaway scratch root — note the gate is `should_index`, i.e. "is a
321    // project bound", NOT "is it git": a non-git directory DOES index
322    // (#2728/#2747).
323    if params.binding.should_index() {
324        let registry = Arc::clone(&registry);
325        let session_id = session_id.clone();
326        crate::run_task::ensure_project_indexed_in_background(
327            work_root.clone(),
328            Some(Box::new(move |readiness| {
329                let summary = match &readiness {
330                    Some(r) => r.summary(),
331                    None => "trusty-search index readiness unknown: no reachable daemon — \
332                             search results may be incomplete and an empty result is not \
333                             evidence of absence"
334                        .to_string(),
335                };
336                if let Err(e) =
337                    registry.record_index_readiness(&session_id, readiness.as_ref(), &summary)
338                {
339                    // The session finishing before this detached probe lands is
340                    // an ordinary race, not a fault — log and drop, exactly as
341                    // the tool-event sink does.
342                    tracing::debug!(session_id = %session_id, "record_index_readiness skipped: {e}");
343                }
344            })),
345        );
346    }
347    let transcript: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
348    let sink: Arc<dyn ToolEventSink> = Arc::new(SessionToolEventSink::new(
349        Arc::clone(&registry),
350        session_id.clone(),
351    ));
352
353    // #2264: mirrors `run_task::execute_run_task`'s own resolution — one
354    // shared (optional) debug-capture sink for the whole run, so pm and
355    // engineer turns land in one globally-ordered JSONL file when
356    // `TCODE_DEBUG_TRANSCRIPT` is set, and cost nothing when it is not.
357    let debug_sink: Option<Arc<DebugCaptureSink>> = DebugCaptureSink::from_env();
358
359    // (#3046) Routes through the shared disk-then-embedded resolver —
360    // mirrors `run_task::execute_run_task`'s own PM-config load — so a
361    // top-level agent name that only exists in the embedded roster (e.g.
362    // `engineer`, `rust-engineer`) resolves here too, on the daemon-driven
363    // session path.
364    let pm_config = match crate::agents::resolve_agent(&params.agents_dir, &params.agent_name) {
365        Ok(cfg) => cfg,
366        Err(e) => {
367            finish_with_failure(&registry, &session_id, &format!("PM config error: {e}")).await;
368            return;
369        }
370    };
371
372    // #7948: one context per run, shared by the PM's gate and every delegated
373    // sub-agent's. `ask` is this session's slot in the broker — the state
374    // `session.permission.respond` writes into. No broker means headless.
375    let permission_ctx = crate::permissions::PermissionContext {
376        mode: params.permission_mode,
377        timeout: std::time::Duration::from_secs(crate::permissions::DEFAULT_ASK_TIMEOUT_SECS),
378        session_id: session_id.clone(),
379        ask: params
380            .permission_broker
381            .as_ref()
382            .map(|broker| broker.session(&session_id)),
383        events: Some(Arc::clone(&registry) as Arc<dyn crate::permissions::PermissionEvents>),
384        // #7948: the run's working root, so a relative path rule also decides
385        // the absolute in-root spelling `tools::fs::scoped_path` accepts.
386        root: Some(work_root.clone()),
387    };
388
389    let project_context = load_project_context(&work_root);
390    // #8030: the top-level agent's model, with `task.run`'s `pm_model`
391    // (`--pm-model`/`TCODE_PM_MODEL`) ahead of its front matter.
392    let pm_model = resolve_model_with_override(&pm_config, params.pm_model.as_deref());
393    let engineer_model = resolve_engineer_model(&params);
394
395    // #2207: resolve the run's wall-clock deadline once, applied to BOTH the
396    // PM's own loop (below) and the delegated engineer's loop
397    // (`build_engineer_runner`, via `with_timeout_secs`).
398    let deadline_secs = resolve_deadline_secs(params.deadline_secs);
399
400    // #2069: discover the (cheap, metadata-only) skill catalog and, in
401    // DailyDriver mode only, register `use_skill` so the PM can lazily fetch
402    // a skill's full body on demand. Parity never sees the catalog or the
403    // tool — see `assemble_system_prompt_for_mode`'s docs.
404    let skills_catalog = daily_driver_skills_catalog(&params, &work_root);
405
406    // #4602: resolved HERE, before the prompt is assembled, so the prompt can
407    // be scoped to the tools this run actually registers for the top-level
408    // agent — and reused below as the registry to merge, so the factory runs
409    // exactly once.
410    let pm_tools = pm_prompt_tools(
411        &params,
412        &work_root,
413        &pm_config,
414        skills_catalog
415            .as_ref()
416            .map(|(_, resolver)| Arc::clone(resolver)),
417    )
418    .await;
419
420    let engineer_runner = build_engineer_runner(
421        wrap_with_debug_capture(Arc::clone(&llm), ENGINEER_AGENT_NAME, debug_sink.as_ref()),
422        &params,
423        &work_root,
424        EngineerPromptContext {
425            project_context: project_context.clone(),
426            skills_catalog: skills_catalog.as_ref().map(|(catalog, _)| catalog.clone()),
427            skill_resolver: skills_catalog
428                .as_ref()
429                .map(|(_, resolver)| Arc::clone(resolver)),
430        },
431        Arc::clone(&transcript),
432        Arc::clone(&sink),
433        Arc::clone(&cancel),
434        permission_ctx.clone(),
435    );
436
437    // Catch-up is already git-optional and fail-open (it degrades to `None` for
438    // a directory with no history), so the projectless scratch root needs no
439    // special-casing here — it simply yields no digest.
440    let catchup_ctx = crate::catchup::pm_catchup_context(&work_root).await;
441    let pm_system = assemble_system_prompt_for_mode(
442        params.mode,
443        &pm_config,
444        project_context.as_deref(),
445        catchup_ctx.as_deref(),
446        skills_catalog.as_ref().map(|(catalog, _)| catalog.as_str()),
447        // #4602: `None` on the delegating path — this PM has no filesystem
448        // tool, so its prompt must name none.
449        pm_tools.as_deref(),
450    );
451
452    // #2344: seed the PM's persistent conversation on this session's FIRST
453    // run, or append `params.task` as a new user turn onto its EXISTING,
454    // already-growing history on every run after that — see
455    // `SessionRegistry::begin_pm_transcript`'s docs. A failure here can only
456    // be `session_not_found` (the session vanished between `begin_execution`
457    // and here), handled the same way a PM-config load failure is above.
458    // (#2347) Fetched BEFORE `pm_registry` is built (moved up from its
459    // original post-registry position) so `set_goal`/`clear_goal` can be
460    // registered against this SAME transcript's live goal slots via
461    // `goals_handle` — see that method's docs for why the tools and the
462    // transcript must share one `Arc<Mutex<GoalSlots>>`.
463    let mut pm_transcript =
464        match registry.begin_pm_transcript(&session_id, &pm_system, &params.task) {
465            Ok(t) => t,
466            Err(e) => {
467                finish_with_failure(&registry, &session_id, &format!("PM transcript error: {e}"))
468                    .await;
469                return;
470            }
471        };
472    let goals = pm_transcript.goals_handle();
473
474    // #2345/#2348: fetch (lazily constructing on the session's first run)
475    // this session's turn-recorder sink BEFORE building the PM registry, so
476    // its already-resolved base_url/palace can be reused by #2348's
477    // `recall_session` tool below rather than re-derived. Fetching this
478    // early (rather than only once, right before the run, as the #2345
479    // comment near `turn_mark` below still does for its OWN purpose) is
480    // safe: `SessionRegistry::memory_sink_for` is idempotent per session, so
481    // calling it twice in one run just returns the same `Arc` both times.
482    // Independent of the `pm_transcript`/`goals` fetch above (#2347) — the
483    // two features don't touch each other's state, so either order works.
484    // Projectless has no project to scope a memory palace to, so this yields
485    // `None` — see `memory_sink_for`'s `Option<&Path>` contract. The scratch
486    // root is deliberately NOT passed: deriving a palace id from a throwaway
487    // temp path would mint a fresh, orphaned palace on every projectless run.
488    let memory_sink = registry.memory_sink_for(&session_id, params.binding.root());
489
490    // #2072: `finish_task` gives the PM a structured, schema-validated way to
491    // signal completion alongside the delegate tool. (#2347) `set_goal`/
492    // `clear_goal` are registered ONLY on this daemon-session PM registry —
493    // never on `run_task`'s one-shot/bake-off registry or a delegated
494    // engineer's registry — since goal slots are a session, not sub-agent,
495    // feature.
496    let mut pm_registry = ToolRegistry::new();
497    // #8031: `no_delegate` makes this a single-agent run — the tool is never
498    // registered, so the named agent cannot hand the task to the engineer.
499    if !params.no_delegate {
500        pm_registry.register(Arc::new(
501            DelegateToAgentTool::new(engineer_runner).with_config_dir(params.agents_dir.clone()),
502        ));
503    }
504    pm_registry.register(Arc::new(FinishTaskTool::new()));
505    pm_registry.register(Arc::new(SetGoalTool::new(Arc::clone(&goals))));
506    pm_registry.register(Arc::new(ClearGoalTool::new(Arc::clone(&goals))));
507    // #8235: the session checklist, registered on this daemon-session registry
508    // only — same restriction as the goal tools above. The store is bound to
509    // THIS agent's `agent_id` (the same `pm-{session_id}` the loop below
510    // stamps on its events), so the tool cannot address another agent's list.
511    pm_registry.register(Arc::new(TodoWriteTool::new(Arc::new(
512        SessionTodoStore::new(
513            Arc::clone(&registry),
514            session_id.clone(),
515            params.agent_name.clone(),
516            format!("pm-{session_id}"),
517        ),
518    ))));
519    if let Some((_, resolver)) = &skills_catalog {
520        pm_registry.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
521    }
522    // #2348: `recall_session` is registered ONLY on this daemon-session
523    // path — never on `run_task::execute_run_task`'s one-shot/bake-off path,
524    // which has no session to scope a memory query to and must keep
525    // Parity-mode prompts byte-identical to the pre-#2343 baseline (epic
526    // #2343 scope note). `None` only when the session vanished between
527    // `begin_execution` and here.
528    if let Some(sink) = &memory_sink {
529        pm_registry.register(Arc::new(RecallSessionTool::new(
530            session_id.clone(),
531            sink.socket().to_path_buf(),
532            sink.palace().to_string(),
533        )));
534    }
535    // #8031: with no engineer to delegate to, the named agent must carry its
536    // OWN tcode tools or the run has nothing to work with. Merged AFTER the
537    // harness tools above so they win the `finish_task`/`use_skill` overlap.
538    // #4602: the SAME registry the prompt above was scoped to, so the two can
539    // never disagree about what this agent can call.
540    if let Some(tools) = &pm_tools {
541        pm_registry.merge_missing(tools);
542    }
543
544    let pm_llm: Arc<dyn InferenceAdapter> = Arc::new(RecordingLlmClient::new(
545        wrap_with_debug_capture(Arc::clone(&llm), "pm", debug_sink.as_ref()),
546        "pm",
547        Arc::clone(&transcript),
548    ));
549
550    let mut pm_loop_config = AgentLoopConfig {
551        model: pm_model.clone(),
552        max_tokens: resolve_max_tokens(&pm_config),
553        mode: params.mode,
554        timeout_secs: deadline_secs,
555        // #2308: model-aware compaction threshold — see
556        // `CompactionConfig::for_context_window`'s doc for why the
557        // struct-update `..AgentLoopConfig::default()` below must not be
558        // allowed to silently supply the flat, model-blind default here.
559        compaction: CompactionConfig::for_context_window(resolve_context_window(&pm_model)),
560        // #2346: the cadence compressor is opt-in per `AgentLoopConfig`
561        // (defaults to `None`) — this daemon-driven, persistent-session
562        // PM loop is the ONE call site that enables it, resolved from
563        // this project's `.claude/settings.json`/env-var precedence
564        // chain (`resolve_cadence_config`). The delegated engineer's own
565        // loop (`build_engineer_runner` below) and `run_task`'s legacy
566        // one-shot/bake-off path both keep the default `None` — zero
567        // behaviour change there, per #2346's explicit scope.
568        cadence: Some(resolve_cadence_config(&work_root)),
569        // #3902: test-only DI, see `TaskRunParams::telemetry_data_dir`'s
570        // docs. `None` (every production call site) falls through to
571        // `telemetry::default_data_dir()` unchanged.
572        telemetry_data_dir: params.telemetry_data_dir.clone(),
573        ..AgentLoopConfig::default()
574    };
575    // #8128: `task.run`'s `max_turns` (`--max-turns`/`TCODE_MAX_TURNS`).
576    // Applied after the literal so an ABSENT override leaves
577    // `AgentLoopConfig::default()`'s own cap of 8 untouched.
578    if let Some(turns) = params.max_turns {
579        pm_loop_config.max_turns = turns;
580    }
581
582    let pm_loop = AgentLoop::new(pm_loop_config, pm_llm, Arc::new(pm_registry))
583        .with_tool_event_sink(Arc::clone(&sink))
584        // (UI Phase 1) Attribute this loop's tool events to the PM. `sink` is the
585        // SAME `Arc` handed to `build_engineer_runner` above, so without this the
586        // PM's and the engineer's tool calls arrive on one stream indistinguishable
587        // from each other. `params.agent_name` (default `"pm"`) is the name the
588        // rest of the taxonomy already uses for this agent.
589        .with_agent(params.agent_name.clone())
590        // (DOC-39 AC-13) The PM/root agent also needs a STABLE id so its
591        // root-attributed events correlate — unlike a delegated engineer (a
592        // fresh UUID per `delegate_to_agent` spawn, see
593        // `runner::in_process::InProcessAgentRunner::run_pipeline`), the PM's
594        // loop is re-entered on EVERY `task.run` against this same session
595        // (`AgentLoop::run_with_transcript` against the persistent
596        // `pm_transcript`), so its id must be SESSION-scoped, not re-minted per
597        // call — otherwise the PM's own tool events would spuriously look like a
598        // new "spawn" on every run. Namespaced with a `pm-` prefix so it reads
599        // distinctly from an engineer's bare UUID in a raw event dump.
600        .with_agent_id(format!("pm-{session_id}"))
601        // (#3867) Stamps this session's real id onto every durable
602        // compression-telemetry JSONL record this loop's cadence/threshold
603        // instrumentation emits — see `AgentLoop::with_session_id`'s docs.
604        .with_session_id(session_id.clone())
605        // #7948: the PM's own calls are gated by the PM agent's `permissions:`
606        // block, under the same session-scoped context as its delegations.
607        .with_permission_gate(Arc::new(
608            permission_ctx.gate_for(Arc::new(pm_config.clone()), format!("pm-{session_id}")),
609        ))
610        .with_cancel_flag(Arc::clone(&cancel))
611        // #2279: mirrors `run_task::execute_run_task`'s own wiring — the PM
612        // never calls `bash` itself, so its verify-before-finish gate scans the
613        // delegated engineer's turns via the SAME shared `transcript` the
614        // engineer's `RecordingLlmClient` records into (`build_engineer_runner`
615        // above), rather than the PM's own (bash-less) transcript.
616        // #8206: the work root the engineer's tools are scoped to, so the PM's
617        // gate cannot refuse a finish on a root with no detectable test suite.
618        .with_finish_gate(crate::verify_gate::pm_finish_gate(
619            Arc::clone(&transcript),
620            Some(work_root.clone()),
621        ));
622
623    // #2345: mark "how much assistant text exists before this run" so the
624    // turn recorder can later scope its durable dual-write to just THIS
625    // run's new response text via `Transcript::assistant_text_since`, even
626    // though `pm_transcript` is the session's whole cumulative (#2344)
627    // conversation. `pm_transcript` was already fetched above (moved up for
628    // #2347's goal-tool wiring — see the comment on that fetch) and
629    // `memory_sink` was already fetched above too (before building
630    // `pm_registry`, #2348) — `SessionRegistry::memory_sink_for` is
631    // idempotent per session, so reusing that same `Option<Arc<..>>` here
632    // needs no second call; this line only marks the current position.
633    let turn_mark = pm_transcript.assistant_text_mark();
634
635    let result = pm_loop
636        .run_with_transcript(&mut pm_transcript, &params.task)
637        .await;
638
639    // #2345: capture this run's new assistant text BEFORE `pm_transcript` is
640    // moved into `store_pm_transcript` below. Per-turn (not per-run) enqueue
641    // is the ideal granularity (#2346 upgrade path — the loop currently has
642    // no per-turn callback/event seam to hook synchronously); a per-RUN batch
643    // of "this run's prompt -> this run's aggregated response text" is the
644    // documented, acceptable fallback for this ticket.
645    let turn_response = pm_transcript.assistant_text_since(turn_mark);
646
647    // #2344: persist the (possibly partial) conversation back onto the
648    // session UNCONDITIONALLY — success, failure, cancellation, or
649    // timeout — so the NEXT `task.run` on this session continues from
650    // exactly where this one left off, rather than silently re-seeding.
651    registry.store_pm_transcript(&session_id, pm_transcript);
652
653    // #2345: durably record this run's turn (fire-and-forget, never blocks
654    // or fails this run — see `session::memory_sink` module docs). Recorded
655    // regardless of `result` (success/failure/cancellation/timeout all still
656    // produce a real prompt and whatever response text WAS generated before
657    // interruption) so the durable record matches `pm_transcript`'s own
658    // "persist unconditionally" contract above. `memory_sink` is `None` only
659    // if the session vanished between `begin_execution` and here.
660    if let Some(sink) = memory_sink {
661        sink.enqueue(session_id.clone(), params.task.clone(), turn_response);
662    }
663
664    // #2206: usage/cost are aggregated from every turn that DID complete
665    // regardless of `result` — this call already ran unconditionally before
666    // the terminal-status match below, so a `Failed`/`DeadlineExceeded`
667    // outcome still persists real telemetry, not zeroed placeholders.
668    let turns = transcript.lock().map(|g| g.clone()).unwrap_or_default();
669    let (usage, cost) = aggregate_usage_per_role(&turns, &pm_model, &engineer_model);
670    registry.set_run_outcome(&session_id, turns, usage, Some(cost));
671
672    // #2207/#3888: matched EXHAUSTIVELY over every `AgentLoopError` variant
673    // (not a catch-all) so the compiler forces a decision the next time that
674    // enum grows one — a catch-all is exactly how #3888 happened the first
675    // time (`TurnCapExceeded` silently absorbed into `Failed`). `Llm` is a
676    // genuine failure. `Timeout`/`TurnCapExceeded` are cooperative pauses,
677    // not failures — `pm_transcript` was already persisted unconditionally
678    // above, so the next `task.run` continues right where this one left off;
679    // `DeadlineExceeded`/`TurnCapExceeded` are distinct resumable statuses so
680    // a consumer can tell "timed out" from "used its turn budget".
681    // `StoppedBySignal` is NOT wired into this `pm_loop` today (no
682    // `.with_stop_signal(...)` call below), so this arm is dead code for now
683    // — but its mapping still matters for whoever wires it in later.
684    // Deliberately grouped with `Llm` as `Failed` rather than assumed
685    // resumable: `AgentLoop::with_stop_signal` has exactly one caller in the
686    // crate today (`run_task::mod`, wired to
687    // `RedelegationCapSignal::is_cap_reached()`), and that signal's own doc
688    // (`run_task::redelegation`) is explicit that it fires for "a genuinely
689    // broken run whose delegations keep failing" and "stopping really is
690    // correct" at that point — a stop-and-stay-stopped condition, not a
691    // cooperative pause like the turn cap. Whoever wires a DIFFERENT signal
692    // into this loop must revisit this arm on its own merits rather than
693    // inherit this default.
694    let terminal_status = match result {
695        Ok(_output) => SessionStatus::Finished,
696        Err(crate::agent_loop::AgentLoopError::Cancelled { .. }) => SessionStatus::Cancelled,
697        Err(e @ crate::agent_loop::AgentLoopError::Timeout { .. }) => {
698            let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
699            SessionStatus::DeadlineExceeded
700        }
701        Err(e @ crate::agent_loop::AgentLoopError::TurnCapExceeded { .. }) => {
702            let _ =
703                registry.record_log(&session_id, "info", &format!("run paused (resumable): {e}"));
704            SessionStatus::TurnCapExceeded
705        }
706        Err(
707            e @ (crate::agent_loop::AgentLoopError::Llm(_)
708            | crate::agent_loop::AgentLoopError::StoppedBySignal { .. }),
709        ) => {
710            let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
711            SessionStatus::Failed
712        }
713    };
714    // #4351: record the actionable result BEFORE `finish`, so the terminal
715    // status and the refs that go with it become visible in the same
716    // `session.status` snapshot rather than in two observable steps.
717    registry.set_task_result(
718        &session_id,
719        result_capture::build_task_result(terminal_status, &before_snapshot, &work_root),
720    );
721    let _ = registry.finish(&session_id, terminal_status);
722    registry.finish_execution(&session_id);
723}
724
725/// Build the in-process engineer runner with project-scoped fs/bash tools,
726/// the #2056 sink, the shared cancel flag, and (#2059) the SAME resolved
727/// `HarnessMode` as the delegating PM (mirrors `run_task::build_engineer_runner`,
728/// which is private to that module).
729///
730/// `skills_catalog` (#2069) is the same rendered metadata catalog the PM's own
731/// prompt gets, threaded through so the delegated engineer's DailyDriver
732/// prompt also sees it. #2152/#2942: the `use_skill` *tool* is now also wired
733/// into the engineer's own per-delegation registry (`ProjectToolFactory::build`)
734/// against the SAME resolver instance the PM's own `use_skill` tool and catalog
735/// were built from — see [`EngineerPromptContext::skill_resolver`]. #2207: resolves the SAME wall-clock
736/// budget applied to the delegating PM's own loop via
737/// `crate::provider::resolve_deadline_secs(params.deadline_secs)` — called
738/// again here (rather than threaded in as an extra argument) purely to keep
739/// this function's arity under clippy's `too_many_arguments` gate; the
740/// resolver is pure given the same `params.deadline_secs`/env state, so a
741/// second call is not a correctness risk.
742///
743/// `work_root` is the directory the engineer's fs/bash tools are scoped to: the
744/// bound project root, or — when projectless — the run's ephemeral scratch dir
745/// (see [`run_and_record`]). It is passed explicitly rather than read off
746/// `params` because the scratch root does not exist until the run begins.
747/// [`EngineerPromptContext`] bundles the two prompt strings that already
748/// travelled together, keeping this function's arity under clippy's
749/// `too_many_arguments` gate now that `work_root` is threaded in.
750// #7948: the permission context is an eighth argument; it belongs to neither
751// the prompt bundle nor the run's lifecycle handles, so bundling it would group
752// unrelated concerns only to satisfy the arity lint.
753#[allow(clippy::too_many_arguments)]
754fn build_engineer_runner(
755    llm: Arc<dyn InferenceAdapter>,
756    params: &TaskRunParams,
757    work_root: &Path,
758    prompt: EngineerPromptContext,
759    transcript: SharedTranscript,
760    sink: Arc<dyn ToolEventSink>,
761    cancel: Arc<AtomicBool>,
762    permissions: crate::permissions::PermissionContext,
763) -> Arc<dyn AgentRunner> {
764    let EngineerPromptContext {
765        project_context,
766        skills_catalog,
767        skill_resolver,
768    } = prompt;
769    let engineer_llm: Arc<dyn InferenceAdapter> = Arc::new(RecordingLlmClient::new(
770        llm,
771        ENGINEER_AGENT_NAME,
772        transcript,
773    ));
774
775    let factory: Arc<dyn RegistryFactory> =
776        Arc::new(project_tool_factory(params, work_root, skill_resolver));
777
778    let mut runner = InProcessAgentRunner::new(engineer_llm, factory, params.agents_dir.clone())
779        .with_tool_event_sink(sink)
780        .with_cancel_flag(cancel)
781        .with_mode(params.mode)
782        // #7948: each delegated sub-agent is gated by its own `permissions:`.
783        .with_permissions(permissions)
784        // #8206: the same root the tools above are scoped to, so the delegated
785        // engineer's own verify-before-finish gate probes the right directory.
786        .with_work_root(work_root.to_path_buf())
787        .with_timeout_secs(resolve_deadline_secs(params.deadline_secs));
788    if let Some(ctx) = project_context {
789        runner = runner.with_project_context(ctx);
790    }
791    if let Some(catalog) = skills_catalog {
792        runner = runner.with_skills_catalog(catalog);
793    }
794    apply_engineer_model_override(Arc::new(runner), params)
795}
796
797/// The prompt-context strings (plus the skill resolver the `use_skill` tool
798/// needs) the delegated engineer's system prompt and registry are assembled
799/// from.
800///
801/// Why: `project_context`/`skills_catalog` are always produced and consumed
802/// together and are positionally adjacent — bundling them removes a real
803/// easy-to-transpose-the-arguments hazard and keeps
804/// [`build_engineer_runner`]'s arity under clippy's `too_many_arguments` gate
805/// now that `work_root` must also be threaded through for projectless runs.
806/// #2152: `skill_resolver` joined the bundle so `ProjectToolFactory::build`
807/// can register `use_skill` against the SAME resolver instance backing
808/// `skills_catalog` and the PM's own `use_skill` tool, rather than the
809/// engineer's registry omitting the tool its prompt explicitly advertises
810/// (closes the gap PR #2942 fixed in the legacy `run_task/mod.rs` path but
811/// left open here).
812/// What: `project_context` is the project's `CLAUDE.md` (`None` when absent —
813/// always the case projectless, since the scratch root has none);
814/// `skills_catalog` is the rendered skill-metadata catalog from either the
815/// project's `.claude/skills/` or, when that is empty or absent,
816/// `crate::assets::DEFAULT_SKILLS` — the embedded default catalog
817/// (`skills::discover_skill_metadata`'s embedded-fallback, #2895). `None`
818/// only in `HarnessMode::Parity` (which never discovers skills at all, disk
819/// or embedded); in `DailyDriver` the embedded fallback means this is
820/// effectively always `Some`. `skill_resolver` is `Some` under the exact same
821/// condition as `skills_catalog` (both come from the same
822/// `daily_driver_skills_catalog` call at the sole construction site).
823/// Test: exercised via `task::executor::tests::*`'s engineer-runner paths;
824/// `engineer_registry_includes_use_skill_when_catalog_present` pins the
825/// registry-side contract.
826struct EngineerPromptContext {
827    project_context: Option<String>,
828    skills_catalog: Option<String>,
829    skill_resolver: Option<Arc<dyn SkillResolver>>,
830}
831
832/// Discover the (cheap, metadata-only) skill catalog under `work_root` and
833/// build a resolver over it — but only in `HarnessMode::DailyDriver`.
834///
835/// Why: #2069's scope note is explicit — "Parity mode should NOT
836/// progressively disclose" — so `Parity` runs must never discover
837/// `.claude/skills/` at all, let alone advertise the `use_skill` tool or
838/// inject the catalog into the prompt.
839/// What: Returns `None` for `HarnessMode::Parity`; otherwise
840/// `Some((rendered_catalog, resolver))` — the resolver backs the `use_skill`
841/// tool registration. `skills::discover_skill_metadata` (the source behind
842/// `resolver.metadata()`) falls back to the embedded default skill catalog
843/// (`crate::assets::DEFAULT_SKILLS`, #2895) when the project has no (or an
844/// empty) `.claude/skills/` directory, so in `HarnessMode::DailyDriver` the
845/// catalog is no longer ever empty — a projectless run (scratch root, no
846/// `.claude/skills/`) now resolves to the embedded catalog rather than
847/// `None`, the same as any other project with no disk skills.
848/// Test: `task::executor::tests::daily_driver_skills_catalog_*`.
849fn daily_driver_skills_catalog(
850    params: &TaskRunParams,
851    work_root: &Path,
852) -> Option<(String, Arc<dyn SkillResolver>)> {
853    if params.mode != HarnessMode::DailyDriver {
854        return None;
855    }
856    let skills_dir = locate_skills_dir(work_root);
857    let resolver: Arc<dyn SkillResolver> = Arc::new(FsSkillResolver::new(skills_dir));
858    let catalog = format_skill_catalog(&resolver.metadata());
859    if catalog.is_empty() {
860        None
861    } else {
862        Some((catalog, resolver))
863    }
864}
865
866/// The registry that scopes the top-level agent's own system prompt (#4602).
867///
868/// Why: the delegating PM's registry carries harness tools only — no `glob`,
869/// `grep`, `list_dir`, `search_code` or `write_files` — so a prompt instructing
870/// it to call them makes the model emit a call `ToolCallExtractor::validate`
871/// rejects as `ToolCallExtractError::UnknownTool`, which `tcode tui` renders as
872/// `<name>(<invalid-arguments>)`. Those tools reach this agent only on the
873/// `--no-delegate` branch, and resolving that branch's registry BEFORE the
874/// prompt is assembled is what lets prompt and registry agree.
875/// What: `None` when the run delegates; otherwise the named agent's own gated
876/// tcode registry, built through the same [`crate::runner::agent_registry`]
877/// helper the caller then merges, so the factory (and its one-shot MCP load)
878/// runs exactly once per run.
879/// Test: `task::executor::tests::delegating_pm_prompt_names_no_gated_tool`,
880/// `task::executor::tests::no_delegate_pm_prompt_names_its_gated_tools`.
881async fn pm_prompt_tools(
882    params: &TaskRunParams,
883    work_root: &Path,
884    pm_config: &AgentConfig,
885    skill_resolver: Option<Arc<dyn SkillResolver>>,
886) -> Option<Arc<ToolRegistry>> {
887    if !params.no_delegate {
888        return None;
889    }
890    let factory = project_tool_factory(params, work_root, skill_resolver);
891    Some(crate::runner::agent_registry(&factory, pm_config, &RunContext::default()).await)
892}
893
894/// The project-scoped tool factory for this run.
895///
896/// Why (#8031): two call sites now need the identical factory — the delegated
897/// engineer's runner, and a `--no-delegate` run assembling the top-level
898/// agent's own tools — so its four fields are constructed in one place rather
899/// than transcribed twice.
900/// What: binds `work_root` as the fs/bash scope, the run's `HarnessMode`, the
901/// shared skill resolver, and a fresh per-factory MCP `OnceCell`.
902/// Test: `task::executor::tests::no_delegate_run_writes_the_file_without_delegating`.
903fn project_tool_factory(
904    params: &TaskRunParams,
905    work_root: &Path,
906    skill_resolver: Option<Arc<dyn SkillResolver>>,
907) -> ProjectToolFactory {
908    ProjectToolFactory {
909        project: work_root.to_path_buf(),
910        mode: params.mode,
911        skill_resolver,
912        mcp: tokio::sync::OnceCell::new(),
913    }
914}
915
916/// Builds the engineer's project-scoped tool registry for each delegation
917/// (mirrors `run_task::ProjectToolFactory`, which is private to that module).
918struct ProjectToolFactory {
919    project: PathBuf,
920    /// #2073: the delegating run's resolved `HarnessMode`, threaded onto the
921    /// engineer's `EditTool` so `HarnessMode::Parity` selects edit-format
922    /// order the same way regardless of which model is delegated to (§5.9's
923    /// edit-format reconciliation). `run_task::ProjectToolFactory` (the
924    /// legacy CLI path, which never resolves a `HarnessMode`) intentionally
925    /// does not carry this field — its `EditTool` stays on the pre-#2073
926    /// plain per-model order, unchanged.
927    mode: HarnessMode,
928    /// #2152: the SAME `Arc<dyn SkillResolver>` the PM's own `use_skill` tool
929    /// and the rendered skills catalog were built from (threaded through
930    /// [`EngineerPromptContext::skill_resolver`]). `None` under the same
931    /// condition `skills_catalog` is `None` (`HarnessMode::Parity`, which
932    /// never discovers skills). Mirrors `run_task::ProjectToolFactory`'s
933    /// `skill_resolver` field, which PR #2942 wired up on the legacy path.
934    skill_resolver: Option<Arc<dyn SkillResolver>>,
935    /// #5428: the operator's configured MCP servers, spawned at most ONCE per
936    /// run and shared by every delegation's registry. Mirrors
937    /// `run_task::ProjectToolFactory`'s field, which is private to that module.
938    mcp: tokio::sync::OnceCell<crate::mcp::McpToolSet>,
939}
940
941#[async_trait]
942impl RegistryFactory for ProjectToolFactory {
943    async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
944        // #2068: resolve the engineer's model slug so `EditTool` can pick its
945        // per-model edit-format fallback order (mirrors
946        // `run_task::ProjectToolFactory::build`, which is private to that module).
947        let model_slug = resolve_model(agent, Some(ctx));
948        let mut reg = ToolRegistry::new();
949        // #7727: embedded agents' skill pointers resolve outside the project.
950        reg.register(Arc::new(
951            ReadFileTool::new(&self.project).with_skill_refs(user_skill_refs_dir()),
952        ));
953        reg.register(Arc::new(WriteFileTool::new(&self.project)));
954        // #2681: batch-write decouples turn-count from file-count.
955        reg.register(Arc::new(WriteFilesTool::new(&self.project)));
956        reg.register(Arc::new(
957            EditTool::new(&self.project)
958                .with_model_slug(model_slug)
959                .with_mode(self.mode),
960        ));
961        // #1027: native file discovery so the engineer stops shelling out to
962        // find/grep/ls (the dominant bake-off agent-turn sink).
963        reg.register(Arc::new(GlobTool::new(&self.project)));
964        reg.register(Arc::new(GrepTool::new(&self.project)));
965        reg.register(Arc::new(ListDirTool::new(&self.project)));
966        // PR A (#2689): trusty-search-backed conceptual discovery as the PRIMARY
967        // path, with the local glob/grep tools above as the fail-open FALLBACK.
968        // DailyDriver ONLY — Parity must keep a byte-identical tool surface for
969        // benchmark fairness (it never sees MCP-backed tools), so this is gated
970        // on the delegating run's resolved `HarnessMode`.
971        if self.mode == HarnessMode::DailyDriver {
972            reg.register(Arc::new(TrustySearchTool::new(&self.project)));
973            // #5428: the operator's configured MCP servers. DailyDriver ONLY,
974            // for the same reason `search_code` is — Parity must keep a
975            // byte-identical tool surface for benchmark fairness, and a
976            // machine's MCP config is not part of that surface.
977            let mcp = self
978                .mcp
979                .get_or_init(|| crate::mcp::McpToolSet::load(&self.project))
980                .await;
981            crate::mcp::register_configured_tools(&mut reg, mcp).log();
982        }
983        reg.register(Arc::new(BashTool::new(
984            Some(self.project.clone()),
985            Duration::from_secs(ENGINEER_BASH_TIMEOUT_SECS),
986        )));
987        reg.register(Arc::new(FinishTaskTool::new()));
988        // #2152: mirrors the PM's own conditional `use_skill` registration —
989        // only when a skill catalog actually resolved for this delegation, so
990        // the engineer's prompt (which advertises `use_skill` whenever
991        // `with_skills_catalog` was applied) and its registry stay in sync.
992        if let Some(resolver) = &self.skill_resolver {
993            reg.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
994        }
995        Arc::new(reg)
996    }
997}
998
999/// Apply the per-run engineer-model override, if any (mirrors
1000/// `run_task::apply_engineer_model_override` / `ModelPinningRunner`, both
1001/// private to that module).
1002fn apply_engineer_model_override(
1003    runner: Arc<dyn AgentRunner>,
1004    params: &TaskRunParams,
1005) -> Arc<dyn AgentRunner> {
1006    match &params.model_override {
1007        Some(model) => Arc::new(ModelPinningRunner {
1008            inner: runner,
1009            model: model.clone(),
1010        }),
1011        None => runner,
1012    }
1013}
1014
1015/// An `AgentRunner` decorator pinning a fixed model for every delegation
1016/// (mirrors `run_task::ModelPinningRunner`).
1017struct ModelPinningRunner {
1018    inner: Arc<dyn AgentRunner>,
1019    model: String,
1020}
1021
1022#[async_trait]
1023impl AgentRunner for ModelPinningRunner {
1024    async fn run(&self, agent_name: &str, task: &str) -> anyhow::Result<AgentOutput> {
1025        let ctx = RunContext {
1026            model: Some(self.model.clone()),
1027            ..Default::default()
1028        };
1029        self.inner.run_with_context(agent_name, task, &ctx).await
1030    }
1031
1032    async fn run_with_context(
1033        &self,
1034        agent_name: &str,
1035        task: &str,
1036        ctx: &RunContext,
1037    ) -> anyhow::Result<AgentOutput> {
1038        let mut ctx = ctx.clone();
1039        ctx.model = Some(self.model.clone());
1040        self.inner.run_with_context(agent_name, task, &ctx).await
1041    }
1042}
1043
1044/// Resolve the engineer's model the SAME way `InProcessAgentRunner` does
1045/// internally, purely so the cost split below can price the engineer's
1046/// turns against its own slug rather than blending everything under the PM
1047/// model.
1048///
1049/// Why: `InProcessAgentRunner` resolves the engineer's model internally and
1050/// does not expose it; `run_task::resolve_agent_model_slug` (#2061's #1475
1051/// bug 1 fix) is the ONE shared implementation of "load config, apply
1052/// override else resolve from config, degrade to `unknown` on load
1053/// failure" this daemon path and `run_task::execute_run_task`'s legacy CLI
1054/// path both now call, so they can never independently drift.
1055/// What: thin wrapper binding this module's `ENGINEER_AGENT_NAME` constant
1056/// and `params.model_override`.
1057fn resolve_engineer_model(params: &TaskRunParams) -> String {
1058    resolve_agent_model_slug(
1059        &params.agents_dir,
1060        ENGINEER_AGENT_NAME,
1061        params.model_override.as_deref(),
1062    )
1063}
1064
1065/// Record a diagnostic log line and transition the session to `Failed`.
1066///
1067/// Why: a PM-config load failure happens before any loop runs, so there is
1068/// no transcript/usage to persist — just the terminal state and a reason an
1069/// operator (or a future `session.get_transcript`) can see.
1070///
1071/// #4351: also records a refless `Failed` `TaskResult` carrying `message`, so
1072/// a caller reading `session.status` gets the same shaped answer here as it
1073/// does from a run that actually executed. No turn ran, so there is nothing on
1074/// disk to point at — every ref stays `None` rather than being guessed.
1075async fn finish_with_failure(registry: &SessionRegistry, session_id: &str, message: &str) {
1076    let _ = registry.record_log(session_id, "error", message);
1077    registry.set_task_result(
1078        session_id,
1079        TaskResult::new(TaskResultStatus::Failed).with_summary(Some(message.to_string())),
1080    );
1081    let _ = registry.finish(session_id, SessionStatus::Failed);
1082    registry.finish_execution(session_id);
1083}
1084
1085#[cfg(test)]
1086#[path = "executor_tests.rs"]
1087mod tests;