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::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::jsonrpc::RpcError;
45use crate::llm::{DebugCaptureSink, LlmClientTrait, wrap_with_debug_capture};
46use crate::mode::HarnessMode;
47use crate::project_context::load_project_context;
48use crate::prompt::assemble_system_prompt_for_mode;
49use crate::provider::{
50 resolve_context_window, resolve_deadline_secs, resolve_max_tokens, resolve_model,
51};
52use crate::run_task::{
53 RecordingLlmClient, SharedTranscript, aggregate_usage_per_role, resolve_agent_model_slug,
54};
55use crate::runner::{InProcessAgentRunner, RegistryFactory};
56use crate::session::{SessionRegistry, SessionStatus};
57use crate::skills::{FsSkillResolver, format_skill_catalog, locate_skills_dir};
58use crate::tools::{
59 AgentOutput, AgentRunner, BashTool, ClearGoalTool, DelegateToAgentTool, EditTool,
60 FinishTaskTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, RecallSessionTool, RunContext,
61 SetGoalTool, SkillResolver, ToolRegistry, TrustySearchTool, UseSkillTool, WriteFileTool,
62 WriteFilesTool,
63};
64
65use super::sink::SessionToolEventSink;
66
67/// Default bash timeout for the engineer's tools, in seconds (mirrors
68/// `run_task::ENGINEER_BASH_TIMEOUT_SECS` — not exported, so duplicated as a
69/// small constant rather than restructuring that module's visibility).
70const ENGINEER_BASH_TIMEOUT_SECS: u64 = 120;
71
72/// Hardcoded delegated engineer agent name, matching the `run_task`/fixture
73/// convention used across this crate (`<agents_dir>/python-engineer.toml`).
74/// A future ticket may make this configurable per `task.run` call.
75pub const ENGINEER_AGENT_NAME: &str = "python-engineer";
76
77/// Inputs to start one background task execution.
78///
79/// Why: bundles everything `spawn_task_run` needs so `task::protocol`'s
80/// handler stays a thin params-parsing shim.
81/// What: `session_id` must already exist in the registry (created by the
82/// caller — see `task::protocol::task_run`); `agent_name` is the top-level
83/// (PM) agent, `task` is the free-form request text, `project`/`agents_dir`
84/// mirror `run_task::RunTaskParams`, and `model_override` pins the
85/// DELEGATED ENGINEER's model for this run only (mirrors `run_task`'s
86/// `--engineer-model`). `mode` (#2059) is the ALREADY-RESOLVED `HarnessMode`
87/// (`task::protocol::task_run` resolves it via `crate::mode::resolve_mode`
88/// before constructing this — resolution is a request-parsing concern, not
89/// an execution one).
90#[derive(Debug, Clone)]
91pub struct TaskRunParams {
92 pub session_id: String,
93 pub task: String,
94 pub agent_name: String,
95 pub project: PathBuf,
96 pub agents_dir: PathBuf,
97 pub model_override: Option<String>,
98 pub mode: HarnessMode,
99 /// Per-run wall-clock deadline override, in seconds (#2207). `None`
100 /// falls through to `crate::provider::resolve_deadline_secs`'s env-var
101 /// and default tiers — resolved once in `run_and_record` and applied to
102 /// BOTH the PM's own loop and the delegated engineer's loop.
103 pub deadline_secs: Option<u64>,
104}
105
106/// Reserve the session's execution slot and spawn the background run.
107///
108/// Why: the single entry point `task::protocol::task_run` calls. Reserving
109/// the slot SYNCHRONOUSLY (before any `tokio::spawn`) is what makes "a
110/// second overlapping `task.run` on the same session is rejected"
111/// observable to the CALLER of the second request, not just internally.
112/// What: calls `registry.begin_execution` (propagating `session_not_found`/
113/// `invalid_argument` — already terminal / already running — verbatim),
114/// then spawns [`run_and_record`] and immediately attaches the real
115/// `JoinHandle` back onto the registry (see `SessionRegistry::attach_execution_handle`'s
116/// docs for why that is a separate call).
117/// Test: `task::executor::tests::spawn_task_run_rejects_second_overlapping_run`;
118/// the full run is exercised by `tests/task_e2e.rs`.
119pub fn spawn_task_run(
120 registry: Arc<SessionRegistry>,
121 llm: Arc<dyn LlmClientTrait>,
122 params: TaskRunParams,
123) -> Result<(), RpcError> {
124 let cancel = registry.begin_execution(¶ms.session_id)?;
125 let session_id = params.session_id.clone();
126 let registry_for_task = Arc::clone(®istry);
127
128 let handle = tokio::spawn(async move {
129 run_and_record(registry_for_task, llm, params, cancel).await;
130 });
131 registry.attach_execution_handle(&session_id, handle);
132 Ok(())
133}
134
135/// The actual PM -> engineer run, executed entirely inside the spawned task.
136///
137/// Why: kept as one function (rather than splitting further) because every
138/// step depends on state built by the previous one; the doc comment on
139/// `spawn_task_run` and the module docs carry the "why this shape" framing.
140/// What: loads the PM config (a failure here is recorded as a `Failed`
141/// outcome, not a panic); builds the engineer runner + PM registry with the
142/// SAME shape `run_task::execute_run_task` uses; (#2344) retrieves this
143/// session's persistent PM `Transcript` via
144/// `SessionRegistry::begin_pm_transcript` (seeding it fresh on the session's
145/// first run, or appending `params.task` onto its existing history on every
146/// run after that) and drives the PM `AgentLoop` against it via
147/// `AgentLoop::run_with_transcript` instead of the fresh-seeding `run` (both
148/// the PM and the delegated engineer share the #2056 sink + cancel flag);
149/// persists that transcript back UNCONDITIONALLY via
150/// `SessionRegistry::store_pm_transcript` so a future run continues from
151/// here even on failure/cancellation/timeout; prices the accounting
152/// transcript per-role; persists that run outcome (now CUMULATIVE, #2344);
153/// and transitions the session to `Finished`/`Cancelled`/`Failed` before
154/// clearing the execution slot. (#2344) `Finished` is no longer a dead end —
155/// `SessionRegistry::begin_execution` resumes a `Finished` session back to
156/// `Running` on its next `task.run`, which is what makes this whole
157/// persistence chain observable across repeated calls. (#2345) after this
158/// run's turn (prompt + whatever response text it produced, even on
159/// failure/cancellation/timeout) is captured, it is durably enqueued onto the
160/// session's lazily-constructed `session::TurnMemorySink` — fire-and-forget,
161/// never able to block or fail this run — for the ONE-time-per-session dual
162/// write to trusty-memory (`chat_turn_append` + `memory_remember`); see
163/// `session::memory_sink` module docs for the fail-open contract and the
164/// per-run (not yet per-turn) enqueue granularity this ticket settles for.
165async fn run_and_record(
166 registry: Arc<SessionRegistry>,
167 llm: Arc<dyn LlmClientTrait>,
168 params: TaskRunParams,
169 cancel: Arc<AtomicBool>,
170) {
171 // Trusty-search-first discovery (PR B): at task START, best-effort/detached,
172 // ensure the working project is indexed so the delegated engineer's
173 // `search`/`grep` tools are useful while this run proceeds. Fail-open,
174 // non-blocking, and git-optional (git is a nice-to-have, not required) —
175 // reuses the ONE shared helper (see
176 // `run_task::ensure_project_indexed_in_background`) so the daemon and CLI
177 // paths can never diverge.
178 crate::run_task::ensure_project_indexed_in_background(params.project.clone());
179
180 let session_id = params.session_id.clone();
181 let transcript: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
182 let sink: Arc<dyn ToolEventSink> = Arc::new(SessionToolEventSink::new(
183 Arc::clone(®istry),
184 session_id.clone(),
185 ));
186
187 // #2264: mirrors `run_task::execute_run_task`'s own resolution — one
188 // shared (optional) debug-capture sink for the whole run, so pm and
189 // engineer turns land in one globally-ordered JSONL file when
190 // `TCODE_DEBUG_TRANSCRIPT` is set, and cost nothing when it is not.
191 let debug_sink: Option<Arc<DebugCaptureSink>> = DebugCaptureSink::from_env();
192
193 let pm_config_path = params
194 .agents_dir
195 .join(format!("{}.toml", params.agent_name));
196 let pm_config = match AgentConfig::load(&pm_config_path) {
197 Ok(cfg) => cfg,
198 Err(e) => {
199 finish_with_failure(®istry, &session_id, &format!("PM config error: {e:#}")).await;
200 return;
201 }
202 };
203
204 let project_context = load_project_context(¶ms.project);
205 let pm_model = resolve_model(&pm_config, None);
206 let engineer_model = resolve_engineer_model(¶ms);
207
208 // #2207: resolve the run's wall-clock deadline once, applied to BOTH the
209 // PM's own loop (below) and the delegated engineer's loop
210 // (`build_engineer_runner`, via `with_timeout_secs`).
211 let deadline_secs = resolve_deadline_secs(params.deadline_secs);
212
213 // #2069: discover the (cheap, metadata-only) skill catalog and, in
214 // DailyDriver mode only, register `use_skill` so the PM can lazily fetch
215 // a skill's full body on demand. Parity never sees the catalog or the
216 // tool — see `assemble_system_prompt_for_mode`'s docs.
217 let skills_catalog = daily_driver_skills_catalog(¶ms);
218
219 let engineer_runner = build_engineer_runner(
220 wrap_with_debug_capture(Arc::clone(&llm), ENGINEER_AGENT_NAME, debug_sink.as_ref()),
221 ¶ms,
222 project_context.clone(),
223 skills_catalog.as_ref().map(|(catalog, _)| catalog.clone()),
224 Arc::clone(&transcript),
225 Arc::clone(&sink),
226 Arc::clone(&cancel),
227 );
228
229 let catchup_ctx = crate::catchup::pm_catchup_context(¶ms.project).await;
230 let pm_system = assemble_system_prompt_for_mode(
231 params.mode,
232 &pm_config,
233 project_context.as_deref(),
234 catchup_ctx.as_deref(),
235 skills_catalog.as_ref().map(|(catalog, _)| catalog.as_str()),
236 );
237
238 // #2344: seed the PM's persistent conversation on this session's FIRST
239 // run, or append `params.task` as a new user turn onto its EXISTING,
240 // already-growing history on every run after that — see
241 // `SessionRegistry::begin_pm_transcript`'s docs. A failure here can only
242 // be `session_not_found` (the session vanished between `begin_execution`
243 // and here), handled the same way a PM-config load failure is above.
244 // (#2347) Fetched BEFORE `pm_registry` is built (moved up from its
245 // original post-registry position) so `set_goal`/`clear_goal` can be
246 // registered against this SAME transcript's live goal slots via
247 // `goals_handle` — see that method's docs for why the tools and the
248 // transcript must share one `Arc<Mutex<GoalSlots>>`.
249 let mut pm_transcript =
250 match registry.begin_pm_transcript(&session_id, &pm_system, ¶ms.task) {
251 Ok(t) => t,
252 Err(e) => {
253 finish_with_failure(®istry, &session_id, &format!("PM transcript error: {e}"))
254 .await;
255 return;
256 }
257 };
258 let goals = pm_transcript.goals_handle();
259
260 // #2345/#2348: fetch (lazily constructing on the session's first run)
261 // this session's turn-recorder sink BEFORE building the PM registry, so
262 // its already-resolved base_url/palace can be reused by #2348's
263 // `recall_session` tool below rather than re-derived. Fetching this
264 // early (rather than only once, right before the run, as the #2345
265 // comment near `turn_mark` below still does for its OWN purpose) is
266 // safe: `SessionRegistry::memory_sink_for` is idempotent per session, so
267 // calling it twice in one run just returns the same `Arc` both times.
268 // Independent of the `pm_transcript`/`goals` fetch above (#2347) — the
269 // two features don't touch each other's state, so either order works.
270 let memory_sink = registry.memory_sink_for(&session_id, ¶ms.project);
271
272 // #2072: `finish_task` gives the PM a structured, schema-validated way to
273 // signal completion alongside the delegate tool. (#2347) `set_goal`/
274 // `clear_goal` are registered ONLY on this daemon-session PM registry —
275 // never on `run_task`'s one-shot/bake-off registry or a delegated
276 // engineer's registry — since goal slots are a session, not sub-agent,
277 // feature.
278 let mut pm_registry = ToolRegistry::new();
279 pm_registry.register(Arc::new(
280 DelegateToAgentTool::new(engineer_runner).with_config_dir(params.agents_dir.clone()),
281 ));
282 pm_registry.register(Arc::new(FinishTaskTool::new()));
283 pm_registry.register(Arc::new(SetGoalTool::new(Arc::clone(&goals))));
284 pm_registry.register(Arc::new(ClearGoalTool::new(Arc::clone(&goals))));
285 if let Some((_, resolver)) = &skills_catalog {
286 pm_registry.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
287 }
288 // #2348: `recall_session` is registered ONLY on this daemon-session
289 // path — never on `run_task::execute_run_task`'s one-shot/bake-off path,
290 // which has no session to scope a memory query to and must keep
291 // Parity-mode prompts byte-identical to the pre-#2343 baseline (epic
292 // #2343 scope note). `None` only when the session vanished between
293 // `begin_execution` and here.
294 if let Some(sink) = &memory_sink {
295 pm_registry.register(Arc::new(RecallSessionTool::new(
296 session_id.clone(),
297 sink.base_url().to_string(),
298 sink.palace().to_string(),
299 )));
300 }
301
302 let pm_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
303 wrap_with_debug_capture(Arc::clone(&llm), "pm", debug_sink.as_ref()),
304 "pm",
305 Arc::clone(&transcript),
306 ));
307
308 let pm_loop = AgentLoop::new(
309 AgentLoopConfig {
310 model: pm_model.clone(),
311 max_tokens: resolve_max_tokens(&pm_config),
312 mode: params.mode,
313 timeout_secs: deadline_secs,
314 // #2308: model-aware compaction threshold — see
315 // `CompactionConfig::for_context_window`'s doc for why the
316 // struct-update `..AgentLoopConfig::default()` below must not be
317 // allowed to silently supply the flat, model-blind default here.
318 compaction: CompactionConfig::for_context_window(resolve_context_window(&pm_model)),
319 // #2346: the cadence compressor is opt-in per `AgentLoopConfig`
320 // (defaults to `None`) — this daemon-driven, persistent-session
321 // PM loop is the ONE call site that enables it, resolved from
322 // this project's `.claude/settings.json`/env-var precedence
323 // chain (`resolve_cadence_config`). The delegated engineer's own
324 // loop (`build_engineer_runner` below) and `run_task`'s legacy
325 // one-shot/bake-off path both keep the default `None` — zero
326 // behaviour change there, per #2346's explicit scope.
327 cadence: Some(resolve_cadence_config(¶ms.project)),
328 ..AgentLoopConfig::default()
329 },
330 pm_llm,
331 Arc::new(pm_registry),
332 )
333 .with_tool_event_sink(Arc::clone(&sink))
334 .with_cancel_flag(Arc::clone(&cancel))
335 // #2279: mirrors `run_task::execute_run_task`'s own wiring — the PM
336 // never calls `bash` itself, so its verify-before-finish gate scans the
337 // delegated engineer's turns via the SAME shared `transcript` the
338 // engineer's `RecordingLlmClient` records into (`build_engineer_runner`
339 // above), rather than the PM's own (bash-less) transcript.
340 .with_finish_gate(crate::verify_gate::pm_finish_gate(Arc::clone(&transcript)));
341
342 // #2345: mark "how much assistant text exists before this run" so the
343 // turn recorder can later scope its durable dual-write to just THIS
344 // run's new response text via `Transcript::assistant_text_since`, even
345 // though `pm_transcript` is the session's whole cumulative (#2344)
346 // conversation. `pm_transcript` was already fetched above (moved up for
347 // #2347's goal-tool wiring — see the comment on that fetch) and
348 // `memory_sink` was already fetched above too (before building
349 // `pm_registry`, #2348) — `SessionRegistry::memory_sink_for` is
350 // idempotent per session, so reusing that same `Option<Arc<..>>` here
351 // needs no second call; this line only marks the current position.
352 let turn_mark = pm_transcript.assistant_text_mark();
353
354 let result = pm_loop
355 .run_with_transcript(&mut pm_transcript, ¶ms.task)
356 .await;
357
358 // #2345: capture this run's new assistant text BEFORE `pm_transcript` is
359 // moved into `store_pm_transcript` below. Per-turn (not per-run) enqueue
360 // is the ideal granularity (#2346 upgrade path — the loop currently has
361 // no per-turn callback/event seam to hook synchronously); a per-RUN batch
362 // of "this run's prompt -> this run's aggregated response text" is the
363 // documented, acceptable fallback for this ticket.
364 let turn_response = pm_transcript.assistant_text_since(turn_mark);
365
366 // #2344: persist the (possibly partial) conversation back onto the
367 // session UNCONDITIONALLY — success, failure, cancellation, or
368 // timeout — so the NEXT `task.run` on this session continues from
369 // exactly where this one left off, rather than silently re-seeding.
370 registry.store_pm_transcript(&session_id, pm_transcript);
371
372 // #2345: durably record this run's turn (fire-and-forget, never blocks
373 // or fails this run — see `session::memory_sink` module docs). Recorded
374 // regardless of `result` (success/failure/cancellation/timeout all still
375 // produce a real prompt and whatever response text WAS generated before
376 // interruption) so the durable record matches `pm_transcript`'s own
377 // "persist unconditionally" contract above. `memory_sink` is `None` only
378 // if the session vanished between `begin_execution` and here.
379 if let Some(sink) = memory_sink {
380 sink.enqueue(session_id.clone(), params.task.clone(), turn_response);
381 }
382
383 // #2206: usage/cost are aggregated from every turn that DID complete
384 // regardless of `result` — this call already ran unconditionally before
385 // the terminal-status match below, so a `Failed`/`DeadlineExceeded`
386 // outcome still persists real telemetry, not zeroed placeholders.
387 let turns = transcript.lock().map(|g| g.clone()).unwrap_or_default();
388 let (usage, cost) = aggregate_usage_per_role(&turns, &pm_model, &engineer_model);
389 registry.set_run_outcome(&session_id, turns, usage, Some(cost));
390
391 // #2207: a wall-clock deadline is distinct from a genuine run failure —
392 // `SessionStatus::DeadlineExceeded` lets a `session.status`/`task.run`
393 // consumer tell "timed out, possibly close to done" from "errored".
394 let terminal_status = match result {
395 Ok(_output) => SessionStatus::Finished,
396 Err(crate::agent_loop::AgentLoopError::Cancelled { .. }) => SessionStatus::Cancelled,
397 Err(e @ crate::agent_loop::AgentLoopError::Timeout { .. }) => {
398 let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
399 SessionStatus::DeadlineExceeded
400 }
401 Err(e) => {
402 let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
403 SessionStatus::Failed
404 }
405 };
406 let _ = registry.finish(&session_id, terminal_status);
407 registry.finish_execution(&session_id);
408}
409
410/// Build the in-process engineer runner with project-scoped fs/bash tools,
411/// the #2056 sink, the shared cancel flag, and (#2059) the SAME resolved
412/// `HarnessMode` as the delegating PM (mirrors `run_task::build_engineer_runner`,
413/// which is private to that module).
414///
415/// `skills_catalog` (#2069) is the same rendered metadata catalog the PM's own
416/// prompt gets, threaded through so the delegated engineer's DailyDriver
417/// prompt also sees it. Wiring the `use_skill` *tool* into the engineer's own
418/// per-delegation registry (`ProjectToolFactory::build`) is deferred — see
419/// this crate's #2069 delivery notes. #2207: resolves the SAME wall-clock
420/// budget applied to the delegating PM's own loop via
421/// `crate::provider::resolve_deadline_secs(params.deadline_secs)` — called
422/// again here (rather than threaded in as an extra argument) purely to keep
423/// this function's arity under clippy's `too_many_arguments` gate; the
424/// resolver is pure given the same `params.deadline_secs`/env state, so a
425/// second call is not a correctness risk.
426fn build_engineer_runner(
427 llm: Arc<dyn LlmClientTrait>,
428 params: &TaskRunParams,
429 project_context: Option<String>,
430 skills_catalog: Option<String>,
431 transcript: SharedTranscript,
432 sink: Arc<dyn ToolEventSink>,
433 cancel: Arc<AtomicBool>,
434) -> Arc<dyn AgentRunner> {
435 let engineer_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
436 llm,
437 ENGINEER_AGENT_NAME,
438 transcript,
439 ));
440
441 let factory: Arc<dyn RegistryFactory> = Arc::new(ProjectToolFactory {
442 project: params.project.clone(),
443 mode: params.mode,
444 });
445
446 let mut runner = InProcessAgentRunner::new(engineer_llm, factory, params.agents_dir.clone())
447 .with_tool_event_sink(sink)
448 .with_cancel_flag(cancel)
449 .with_mode(params.mode)
450 .with_timeout_secs(resolve_deadline_secs(params.deadline_secs));
451 if let Some(ctx) = project_context {
452 runner = runner.with_project_context(ctx);
453 }
454 if let Some(catalog) = skills_catalog {
455 runner = runner.with_skills_catalog(catalog);
456 }
457 apply_engineer_model_override(Arc::new(runner), params)
458}
459
460/// Discover the (cheap, metadata-only) skill catalog for `params.project` and
461/// build a resolver over it — but only in `HarnessMode::DailyDriver`.
462///
463/// Why: #2069's scope note is explicit — "Parity mode should NOT
464/// progressively disclose" — so `Parity` runs must never discover
465/// `.claude/skills/` at all, let alone advertise the `use_skill` tool or
466/// inject the catalog into the prompt.
467/// What: Returns `None` for `HarnessMode::Parity` or when the project has no
468/// (or an empty) skill catalog; otherwise `Some((rendered_catalog,
469/// resolver))` — the resolver backs the `use_skill` tool registration.
470/// Test: `task::executor::tests::daily_driver_skills_catalog_*`.
471fn daily_driver_skills_catalog(params: &TaskRunParams) -> Option<(String, Arc<dyn SkillResolver>)> {
472 if params.mode != HarnessMode::DailyDriver {
473 return None;
474 }
475 let skills_dir = locate_skills_dir(¶ms.project);
476 let resolver: Arc<dyn SkillResolver> = Arc::new(FsSkillResolver::new(skills_dir));
477 let catalog = format_skill_catalog(&resolver.metadata());
478 if catalog.is_empty() {
479 None
480 } else {
481 Some((catalog, resolver))
482 }
483}
484
485/// Builds the engineer's project-scoped tool registry for each delegation
486/// (mirrors `run_task::ProjectToolFactory`, which is private to that module).
487struct ProjectToolFactory {
488 project: PathBuf,
489 /// #2073: the delegating run's resolved `HarnessMode`, threaded onto the
490 /// engineer's `EditTool` so `HarnessMode::Parity` selects edit-format
491 /// order the same way regardless of which model is delegated to (§5.9's
492 /// edit-format reconciliation). `run_task::ProjectToolFactory` (the
493 /// legacy CLI path, which never resolves a `HarnessMode`) intentionally
494 /// does not carry this field — its `EditTool` stays on the pre-#2073
495 /// plain per-model order, unchanged.
496 mode: HarnessMode,
497}
498
499#[async_trait]
500impl RegistryFactory for ProjectToolFactory {
501 async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
502 // #2068: resolve the engineer's model slug so `EditTool` can pick its
503 // per-model edit-format fallback order (mirrors
504 // `run_task::ProjectToolFactory::build`, which is private to that module).
505 let model_slug = resolve_model(agent, Some(ctx));
506 let mut reg = ToolRegistry::new();
507 reg.register(Arc::new(ReadFileTool::new(&self.project)));
508 reg.register(Arc::new(WriteFileTool::new(&self.project)));
509 // #2681: batch-write decouples turn-count from file-count.
510 reg.register(Arc::new(WriteFilesTool::new(&self.project)));
511 reg.register(Arc::new(
512 EditTool::new(&self.project)
513 .with_model_slug(model_slug)
514 .with_mode(self.mode),
515 ));
516 // #1027: native file discovery so the engineer stops shelling out to
517 // find/grep/ls (the dominant bake-off agent-turn sink).
518 reg.register(Arc::new(GlobTool::new(&self.project)));
519 reg.register(Arc::new(GrepTool::new(&self.project)));
520 reg.register(Arc::new(ListDirTool::new(&self.project)));
521 // PR A (#2689): trusty-search-backed conceptual discovery as the PRIMARY
522 // path, with the local glob/grep tools above as the fail-open FALLBACK.
523 // DailyDriver ONLY — Parity must keep a byte-identical tool surface for
524 // benchmark fairness (it never sees MCP-backed tools), so this is gated
525 // on the delegating run's resolved `HarnessMode`.
526 if self.mode == HarnessMode::DailyDriver {
527 reg.register(Arc::new(TrustySearchTool::new(&self.project)));
528 }
529 reg.register(Arc::new(BashTool::new(
530 Some(self.project.clone()),
531 Duration::from_secs(ENGINEER_BASH_TIMEOUT_SECS),
532 )));
533 reg.register(Arc::new(FinishTaskTool::new()));
534 Arc::new(reg)
535 }
536}
537
538/// Apply the per-run engineer-model override, if any (mirrors
539/// `run_task::apply_engineer_model_override` / `ModelPinningRunner`, both
540/// private to that module).
541fn apply_engineer_model_override(
542 runner: Arc<dyn AgentRunner>,
543 params: &TaskRunParams,
544) -> Arc<dyn AgentRunner> {
545 match ¶ms.model_override {
546 Some(model) => Arc::new(ModelPinningRunner {
547 inner: runner,
548 model: model.clone(),
549 }),
550 None => runner,
551 }
552}
553
554/// An `AgentRunner` decorator pinning a fixed model for every delegation
555/// (mirrors `run_task::ModelPinningRunner`).
556struct ModelPinningRunner {
557 inner: Arc<dyn AgentRunner>,
558 model: String,
559}
560
561#[async_trait]
562impl AgentRunner for ModelPinningRunner {
563 async fn run(&self, agent_name: &str, task: &str) -> anyhow::Result<AgentOutput> {
564 let ctx = RunContext {
565 model: Some(self.model.clone()),
566 ..Default::default()
567 };
568 self.inner.run_with_context(agent_name, task, &ctx).await
569 }
570
571 async fn run_with_context(
572 &self,
573 agent_name: &str,
574 task: &str,
575 ctx: &RunContext,
576 ) -> anyhow::Result<AgentOutput> {
577 let mut ctx = ctx.clone();
578 ctx.model = Some(self.model.clone());
579 self.inner.run_with_context(agent_name, task, &ctx).await
580 }
581}
582
583/// Resolve the engineer's model the SAME way `InProcessAgentRunner` does
584/// internally, purely so the cost split below can price the engineer's
585/// turns against its own slug rather than blending everything under the PM
586/// model.
587///
588/// Why: `InProcessAgentRunner` resolves the engineer's model internally and
589/// does not expose it; `run_task::resolve_agent_model_slug` (#2061's #1475
590/// bug 1 fix) is the ONE shared implementation of "load config, apply
591/// override else resolve from config, degrade to `unknown` on load
592/// failure" this daemon path and `run_task::execute_run_task`'s legacy CLI
593/// path both now call, so they can never independently drift.
594/// What: thin wrapper binding this module's `ENGINEER_AGENT_NAME` constant
595/// and `params.model_override`.
596fn resolve_engineer_model(params: &TaskRunParams) -> String {
597 resolve_agent_model_slug(
598 ¶ms.agents_dir,
599 ENGINEER_AGENT_NAME,
600 params.model_override.as_deref(),
601 )
602}
603
604/// Record a diagnostic log line and transition the session to `Failed`.
605///
606/// Why: a PM-config load failure happens before any loop runs, so there is
607/// no transcript/usage to persist — just the terminal state and a reason an
608/// operator (or a future `session.get_transcript`) can see.
609async fn finish_with_failure(registry: &SessionRegistry, session_id: &str, message: &str) {
610 let _ = registry.record_log(session_id, "error", message);
611 let _ = registry.finish(session_id, SessionStatus::Failed);
612 registry.finish_execution(session_id);
613}
614
615#[cfg(test)]
616#[path = "executor_tests.rs"]
617mod tests;