trusty-code 0.2.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Daemon-owned background task execution (#2056): wires the session/event
//! layer (#2054/#2055) to the existing engine (`agent_loop`/`runner`/`tools`/
//! `llm`) — the M1 control-plane cut line.
//!
//! Why: `run_task` (the CLI's `tcode run-task`) already proves this engine
//! end-to-end, but it runs synchronously, in the calling process, and
//! renders a `RunReport` for a terminal. A daemon-driven task must instead
//! run as a background task the triggering RPC does NOT block on, stream
//! its progress live to `session.attach`ed clients via the #2055 event
//! envelope, and persist its outcome onto the `Session` for a future
//! `session.get_transcript` (#2058). This module is new glue, NOT a fork of
//! the engine: it builds the exact same PM-delegates-to-engineer shape
//! `run_task::execute_run_task` does (see that module's doc comment), reusing
//! `agent_loop::AgentLoop`, `runner::InProcessAgentRunner`, `tools::*`, and
//! `run_task`'s own public `RecordingLlmClient`/`TurnRecord`/
//! `aggregate_usage_per_role`/`resolve_agent_model_slug` machinery — only the
//! orchestration shell (spawn-and-report vs. run-and-render) differs.
//! What: [`TaskRunParams`] carries one run's inputs; [`spawn_task_run`] is
//! the single entry point `task::protocol::task_run` calls — it reserves the
//! session's execution slot synchronously (rejecting a second overlapping
//! run before any background work starts), then hands the actual run off to
//! a `tokio::spawn`'d task that builds both loops (attaching the #2056
//! `SessionToolEventSink` + a shared cancel flag to BOTH the PM's and the
//! delegated engineer's `AgentLoop`), drives the PM loop, prices the
//! transcript PER ROLE against each role's own resolved model via
//! `run_task::aggregate_usage_per_role` (#1475 bug 1 — this daemon path and
//! the legacy CLI path now share the ONE implementation, so they can never
//! independently drift), persists the outcome, and transitions the session
//! to its terminal state.
//! Test: `task::executor::tests::*`; the full flow end-to-end (a real
//! subprocess) in `tests/task_e2e.rs`.

use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;

use crate::agent_loop::{
    AgentLoop, AgentLoopConfig, CompactionConfig, ToolEventSink, resolve_cadence_config,
};
use crate::agents::AgentConfig;
use crate::jsonrpc::RpcError;
use crate::llm::{DebugCaptureSink, LlmClientTrait, wrap_with_debug_capture};
use crate::mode::HarnessMode;
use crate::project_context::load_project_context;
use crate::prompt::assemble_system_prompt_for_mode;
use crate::provider::{
    resolve_context_window, resolve_deadline_secs, resolve_max_tokens, resolve_model,
};
use crate::run_task::{
    RecordingLlmClient, SharedTranscript, aggregate_usage_per_role, resolve_agent_model_slug,
};
use crate::runner::{InProcessAgentRunner, RegistryFactory};
use crate::session::{SessionRegistry, SessionStatus};
use crate::skills::{FsSkillResolver, format_skill_catalog, locate_skills_dir};
use crate::tools::{
    AgentOutput, AgentRunner, BashTool, ClearGoalTool, DelegateToAgentTool, EditTool,
    FinishTaskTool, GlobTool, GrepTool, ListDirTool, ReadFileTool, RecallSessionTool, RunContext,
    SetGoalTool, SkillResolver, ToolRegistry, TrustySearchTool, UseSkillTool, WriteFileTool,
    WriteFilesTool,
};

use super::sink::SessionToolEventSink;

/// Default bash timeout for the engineer's tools, in seconds (mirrors
/// `run_task::ENGINEER_BASH_TIMEOUT_SECS` — not exported, so duplicated as a
/// small constant rather than restructuring that module's visibility).
const ENGINEER_BASH_TIMEOUT_SECS: u64 = 120;

/// Hardcoded delegated engineer agent name, matching the `run_task`/fixture
/// convention used across this crate (`<agents_dir>/python-engineer.toml`).
/// A future ticket may make this configurable per `task.run` call.
pub const ENGINEER_AGENT_NAME: &str = "python-engineer";

/// Inputs to start one background task execution.
///
/// Why: bundles everything `spawn_task_run` needs so `task::protocol`'s
/// handler stays a thin params-parsing shim.
/// What: `session_id` must already exist in the registry (created by the
/// caller — see `task::protocol::task_run`); `agent_name` is the top-level
/// (PM) agent, `task` is the free-form request text, `project`/`agents_dir`
/// mirror `run_task::RunTaskParams`, and `model_override` pins the
/// DELEGATED ENGINEER's model for this run only (mirrors `run_task`'s
/// `--engineer-model`). `mode` (#2059) is the ALREADY-RESOLVED `HarnessMode`
/// (`task::protocol::task_run` resolves it via `crate::mode::resolve_mode`
/// before constructing this — resolution is a request-parsing concern, not
/// an execution one).
#[derive(Debug, Clone)]
pub struct TaskRunParams {
    pub session_id: String,
    pub task: String,
    pub agent_name: String,
    pub project: PathBuf,
    pub agents_dir: PathBuf,
    pub model_override: Option<String>,
    pub mode: HarnessMode,
    /// Per-run wall-clock deadline override, in seconds (#2207). `None`
    /// falls through to `crate::provider::resolve_deadline_secs`'s env-var
    /// and default tiers — resolved once in `run_and_record` and applied to
    /// BOTH the PM's own loop and the delegated engineer's loop.
    pub deadline_secs: Option<u64>,
}

/// Reserve the session's execution slot and spawn the background run.
///
/// Why: the single entry point `task::protocol::task_run` calls. Reserving
/// the slot SYNCHRONOUSLY (before any `tokio::spawn`) is what makes "a
/// second overlapping `task.run` on the same session is rejected"
/// observable to the CALLER of the second request, not just internally.
/// What: calls `registry.begin_execution` (propagating `session_not_found`/
/// `invalid_argument` — already terminal / already running — verbatim),
/// then spawns [`run_and_record`] and immediately attaches the real
/// `JoinHandle` back onto the registry (see `SessionRegistry::attach_execution_handle`'s
/// docs for why that is a separate call).
/// Test: `task::executor::tests::spawn_task_run_rejects_second_overlapping_run`;
/// the full run is exercised by `tests/task_e2e.rs`.
pub fn spawn_task_run(
    registry: Arc<SessionRegistry>,
    llm: Arc<dyn LlmClientTrait>,
    params: TaskRunParams,
) -> Result<(), RpcError> {
    let cancel = registry.begin_execution(&params.session_id)?;
    let session_id = params.session_id.clone();
    let registry_for_task = Arc::clone(&registry);

    let handle = tokio::spawn(async move {
        run_and_record(registry_for_task, llm, params, cancel).await;
    });
    registry.attach_execution_handle(&session_id, handle);
    Ok(())
}

/// The actual PM -> engineer run, executed entirely inside the spawned task.
///
/// Why: kept as one function (rather than splitting further) because every
/// step depends on state built by the previous one; the doc comment on
/// `spawn_task_run` and the module docs carry the "why this shape" framing.
/// What: loads the PM config (a failure here is recorded as a `Failed`
/// outcome, not a panic); builds the engineer runner + PM registry with the
/// SAME shape `run_task::execute_run_task` uses; (#2344) retrieves this
/// session's persistent PM `Transcript` via
/// `SessionRegistry::begin_pm_transcript` (seeding it fresh on the session's
/// first run, or appending `params.task` onto its existing history on every
/// run after that) and drives the PM `AgentLoop` against it via
/// `AgentLoop::run_with_transcript` instead of the fresh-seeding `run` (both
/// the PM and the delegated engineer share the #2056 sink + cancel flag);
/// persists that transcript back UNCONDITIONALLY via
/// `SessionRegistry::store_pm_transcript` so a future run continues from
/// here even on failure/cancellation/timeout; prices the accounting
/// transcript per-role; persists that run outcome (now CUMULATIVE, #2344);
/// and transitions the session to `Finished`/`Cancelled`/`Failed` before
/// clearing the execution slot. (#2344) `Finished` is no longer a dead end —
/// `SessionRegistry::begin_execution` resumes a `Finished` session back to
/// `Running` on its next `task.run`, which is what makes this whole
/// persistence chain observable across repeated calls. (#2345) after this
/// run's turn (prompt + whatever response text it produced, even on
/// failure/cancellation/timeout) is captured, it is durably enqueued onto the
/// session's lazily-constructed `session::TurnMemorySink` — fire-and-forget,
/// never able to block or fail this run — for the ONE-time-per-session dual
/// write to trusty-memory (`chat_turn_append` + `memory_remember`); see
/// `session::memory_sink` module docs for the fail-open contract and the
/// per-run (not yet per-turn) enqueue granularity this ticket settles for.
async fn run_and_record(
    registry: Arc<SessionRegistry>,
    llm: Arc<dyn LlmClientTrait>,
    params: TaskRunParams,
    cancel: Arc<AtomicBool>,
) {
    // Trusty-search-first discovery (PR B): at task START, best-effort/detached,
    // ensure the working project is indexed so the delegated engineer's
    // `search`/`grep` tools are useful while this run proceeds. Fail-open,
    // non-blocking, and git-optional (git is a nice-to-have, not required) —
    // reuses the ONE shared helper (see
    // `run_task::ensure_project_indexed_in_background`) so the daemon and CLI
    // paths can never diverge.
    crate::run_task::ensure_project_indexed_in_background(params.project.clone());

    let session_id = params.session_id.clone();
    let transcript: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
    let sink: Arc<dyn ToolEventSink> = Arc::new(SessionToolEventSink::new(
        Arc::clone(&registry),
        session_id.clone(),
    ));

    // #2264: mirrors `run_task::execute_run_task`'s own resolution — one
    // shared (optional) debug-capture sink for the whole run, so pm and
    // engineer turns land in one globally-ordered JSONL file when
    // `TCODE_DEBUG_TRANSCRIPT` is set, and cost nothing when it is not.
    let debug_sink: Option<Arc<DebugCaptureSink>> = DebugCaptureSink::from_env();

    let pm_config_path = params
        .agents_dir
        .join(format!("{}.toml", params.agent_name));
    let pm_config = match AgentConfig::load(&pm_config_path) {
        Ok(cfg) => cfg,
        Err(e) => {
            finish_with_failure(&registry, &session_id, &format!("PM config error: {e:#}")).await;
            return;
        }
    };

    let project_context = load_project_context(&params.project);
    let pm_model = resolve_model(&pm_config, None);
    let engineer_model = resolve_engineer_model(&params);

    // #2207: resolve the run's wall-clock deadline once, applied to BOTH the
    // PM's own loop (below) and the delegated engineer's loop
    // (`build_engineer_runner`, via `with_timeout_secs`).
    let deadline_secs = resolve_deadline_secs(params.deadline_secs);

    // #2069: discover the (cheap, metadata-only) skill catalog and, in
    // DailyDriver mode only, register `use_skill` so the PM can lazily fetch
    // a skill's full body on demand. Parity never sees the catalog or the
    // tool — see `assemble_system_prompt_for_mode`'s docs.
    let skills_catalog = daily_driver_skills_catalog(&params);

    let engineer_runner = build_engineer_runner(
        wrap_with_debug_capture(Arc::clone(&llm), ENGINEER_AGENT_NAME, debug_sink.as_ref()),
        &params,
        project_context.clone(),
        skills_catalog.as_ref().map(|(catalog, _)| catalog.clone()),
        Arc::clone(&transcript),
        Arc::clone(&sink),
        Arc::clone(&cancel),
    );

    let catchup_ctx = crate::catchup::pm_catchup_context(&params.project).await;
    let pm_system = assemble_system_prompt_for_mode(
        params.mode,
        &pm_config,
        project_context.as_deref(),
        catchup_ctx.as_deref(),
        skills_catalog.as_ref().map(|(catalog, _)| catalog.as_str()),
    );

    // #2344: seed the PM's persistent conversation on this session's FIRST
    // run, or append `params.task` as a new user turn onto its EXISTING,
    // already-growing history on every run after that — see
    // `SessionRegistry::begin_pm_transcript`'s docs. A failure here can only
    // be `session_not_found` (the session vanished between `begin_execution`
    // and here), handled the same way a PM-config load failure is above.
    // (#2347) Fetched BEFORE `pm_registry` is built (moved up from its
    // original post-registry position) so `set_goal`/`clear_goal` can be
    // registered against this SAME transcript's live goal slots via
    // `goals_handle` — see that method's docs for why the tools and the
    // transcript must share one `Arc<Mutex<GoalSlots>>`.
    let mut pm_transcript =
        match registry.begin_pm_transcript(&session_id, &pm_system, &params.task) {
            Ok(t) => t,
            Err(e) => {
                finish_with_failure(&registry, &session_id, &format!("PM transcript error: {e}"))
                    .await;
                return;
            }
        };
    let goals = pm_transcript.goals_handle();

    // #2345/#2348: fetch (lazily constructing on the session's first run)
    // this session's turn-recorder sink BEFORE building the PM registry, so
    // its already-resolved base_url/palace can be reused by #2348's
    // `recall_session` tool below rather than re-derived. Fetching this
    // early (rather than only once, right before the run, as the #2345
    // comment near `turn_mark` below still does for its OWN purpose) is
    // safe: `SessionRegistry::memory_sink_for` is idempotent per session, so
    // calling it twice in one run just returns the same `Arc` both times.
    // Independent of the `pm_transcript`/`goals` fetch above (#2347) — the
    // two features don't touch each other's state, so either order works.
    let memory_sink = registry.memory_sink_for(&session_id, &params.project);

    // #2072: `finish_task` gives the PM a structured, schema-validated way to
    // signal completion alongside the delegate tool. (#2347) `set_goal`/
    // `clear_goal` are registered ONLY on this daemon-session PM registry —
    // never on `run_task`'s one-shot/bake-off registry or a delegated
    // engineer's registry — since goal slots are a session, not sub-agent,
    // feature.
    let mut pm_registry = ToolRegistry::new();
    pm_registry.register(Arc::new(
        DelegateToAgentTool::new(engineer_runner).with_config_dir(params.agents_dir.clone()),
    ));
    pm_registry.register(Arc::new(FinishTaskTool::new()));
    pm_registry.register(Arc::new(SetGoalTool::new(Arc::clone(&goals))));
    pm_registry.register(Arc::new(ClearGoalTool::new(Arc::clone(&goals))));
    if let Some((_, resolver)) = &skills_catalog {
        pm_registry.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
    }
    // #2348: `recall_session` is registered ONLY on this daemon-session
    // path — never on `run_task::execute_run_task`'s one-shot/bake-off path,
    // which has no session to scope a memory query to and must keep
    // Parity-mode prompts byte-identical to the pre-#2343 baseline (epic
    // #2343 scope note). `None` only when the session vanished between
    // `begin_execution` and here.
    if let Some(sink) = &memory_sink {
        pm_registry.register(Arc::new(RecallSessionTool::new(
            session_id.clone(),
            sink.base_url().to_string(),
            sink.palace().to_string(),
        )));
    }

    let pm_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
        wrap_with_debug_capture(Arc::clone(&llm), "pm", debug_sink.as_ref()),
        "pm",
        Arc::clone(&transcript),
    ));

    let pm_loop = AgentLoop::new(
        AgentLoopConfig {
            model: pm_model.clone(),
            max_tokens: resolve_max_tokens(&pm_config),
            mode: params.mode,
            timeout_secs: deadline_secs,
            // #2308: model-aware compaction threshold — see
            // `CompactionConfig::for_context_window`'s doc for why the
            // struct-update `..AgentLoopConfig::default()` below must not be
            // allowed to silently supply the flat, model-blind default here.
            compaction: CompactionConfig::for_context_window(resolve_context_window(&pm_model)),
            // #2346: the cadence compressor is opt-in per `AgentLoopConfig`
            // (defaults to `None`) — this daemon-driven, persistent-session
            // PM loop is the ONE call site that enables it, resolved from
            // this project's `.claude/settings.json`/env-var precedence
            // chain (`resolve_cadence_config`). The delegated engineer's own
            // loop (`build_engineer_runner` below) and `run_task`'s legacy
            // one-shot/bake-off path both keep the default `None` — zero
            // behaviour change there, per #2346's explicit scope.
            cadence: Some(resolve_cadence_config(&params.project)),
            ..AgentLoopConfig::default()
        },
        pm_llm,
        Arc::new(pm_registry),
    )
    .with_tool_event_sink(Arc::clone(&sink))
    .with_cancel_flag(Arc::clone(&cancel))
    // #2279: mirrors `run_task::execute_run_task`'s own wiring — the PM
    // never calls `bash` itself, so its verify-before-finish gate scans the
    // delegated engineer's turns via the SAME shared `transcript` the
    // engineer's `RecordingLlmClient` records into (`build_engineer_runner`
    // above), rather than the PM's own (bash-less) transcript.
    .with_finish_gate(crate::verify_gate::pm_finish_gate(Arc::clone(&transcript)));

    // #2345: mark "how much assistant text exists before this run" so the
    // turn recorder can later scope its durable dual-write to just THIS
    // run's new response text via `Transcript::assistant_text_since`, even
    // though `pm_transcript` is the session's whole cumulative (#2344)
    // conversation. `pm_transcript` was already fetched above (moved up for
    // #2347's goal-tool wiring — see the comment on that fetch) and
    // `memory_sink` was already fetched above too (before building
    // `pm_registry`, #2348) — `SessionRegistry::memory_sink_for` is
    // idempotent per session, so reusing that same `Option<Arc<..>>` here
    // needs no second call; this line only marks the current position.
    let turn_mark = pm_transcript.assistant_text_mark();

    let result = pm_loop
        .run_with_transcript(&mut pm_transcript, &params.task)
        .await;

    // #2345: capture this run's new assistant text BEFORE `pm_transcript` is
    // moved into `store_pm_transcript` below. Per-turn (not per-run) enqueue
    // is the ideal granularity (#2346 upgrade path — the loop currently has
    // no per-turn callback/event seam to hook synchronously); a per-RUN batch
    // of "this run's prompt -> this run's aggregated response text" is the
    // documented, acceptable fallback for this ticket.
    let turn_response = pm_transcript.assistant_text_since(turn_mark);

    // #2344: persist the (possibly partial) conversation back onto the
    // session UNCONDITIONALLY — success, failure, cancellation, or
    // timeout — so the NEXT `task.run` on this session continues from
    // exactly where this one left off, rather than silently re-seeding.
    registry.store_pm_transcript(&session_id, pm_transcript);

    // #2345: durably record this run's turn (fire-and-forget, never blocks
    // or fails this run — see `session::memory_sink` module docs). Recorded
    // regardless of `result` (success/failure/cancellation/timeout all still
    // produce a real prompt and whatever response text WAS generated before
    // interruption) so the durable record matches `pm_transcript`'s own
    // "persist unconditionally" contract above. `memory_sink` is `None` only
    // if the session vanished between `begin_execution` and here.
    if let Some(sink) = memory_sink {
        sink.enqueue(session_id.clone(), params.task.clone(), turn_response);
    }

    // #2206: usage/cost are aggregated from every turn that DID complete
    // regardless of `result` — this call already ran unconditionally before
    // the terminal-status match below, so a `Failed`/`DeadlineExceeded`
    // outcome still persists real telemetry, not zeroed placeholders.
    let turns = transcript.lock().map(|g| g.clone()).unwrap_or_default();
    let (usage, cost) = aggregate_usage_per_role(&turns, &pm_model, &engineer_model);
    registry.set_run_outcome(&session_id, turns, usage, Some(cost));

    // #2207: a wall-clock deadline is distinct from a genuine run failure —
    // `SessionStatus::DeadlineExceeded` lets a `session.status`/`task.run`
    // consumer tell "timed out, possibly close to done" from "errored".
    let terminal_status = match result {
        Ok(_output) => SessionStatus::Finished,
        Err(crate::agent_loop::AgentLoopError::Cancelled { .. }) => SessionStatus::Cancelled,
        Err(e @ crate::agent_loop::AgentLoopError::Timeout { .. }) => {
            let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
            SessionStatus::DeadlineExceeded
        }
        Err(e) => {
            let _ = registry.record_log(&session_id, "error", &format!("run failed: {e}"));
            SessionStatus::Failed
        }
    };
    let _ = registry.finish(&session_id, terminal_status);
    registry.finish_execution(&session_id);
}

/// Build the in-process engineer runner with project-scoped fs/bash tools,
/// the #2056 sink, the shared cancel flag, and (#2059) the SAME resolved
/// `HarnessMode` as the delegating PM (mirrors `run_task::build_engineer_runner`,
/// which is private to that module).
///
/// `skills_catalog` (#2069) is the same rendered metadata catalog the PM's own
/// prompt gets, threaded through so the delegated engineer's DailyDriver
/// prompt also sees it. Wiring the `use_skill` *tool* into the engineer's own
/// per-delegation registry (`ProjectToolFactory::build`) is deferred — see
/// this crate's #2069 delivery notes. #2207: resolves the SAME wall-clock
/// budget applied to the delegating PM's own loop via
/// `crate::provider::resolve_deadline_secs(params.deadline_secs)` — called
/// again here (rather than threaded in as an extra argument) purely to keep
/// this function's arity under clippy's `too_many_arguments` gate; the
/// resolver is pure given the same `params.deadline_secs`/env state, so a
/// second call is not a correctness risk.
fn build_engineer_runner(
    llm: Arc<dyn LlmClientTrait>,
    params: &TaskRunParams,
    project_context: Option<String>,
    skills_catalog: Option<String>,
    transcript: SharedTranscript,
    sink: Arc<dyn ToolEventSink>,
    cancel: Arc<AtomicBool>,
) -> Arc<dyn AgentRunner> {
    let engineer_llm: Arc<dyn LlmClientTrait> = Arc::new(RecordingLlmClient::new(
        llm,
        ENGINEER_AGENT_NAME,
        transcript,
    ));

    let factory: Arc<dyn RegistryFactory> = Arc::new(ProjectToolFactory {
        project: params.project.clone(),
        mode: params.mode,
    });

    let mut runner = InProcessAgentRunner::new(engineer_llm, factory, params.agents_dir.clone())
        .with_tool_event_sink(sink)
        .with_cancel_flag(cancel)
        .with_mode(params.mode)
        .with_timeout_secs(resolve_deadline_secs(params.deadline_secs));
    if let Some(ctx) = project_context {
        runner = runner.with_project_context(ctx);
    }
    if let Some(catalog) = skills_catalog {
        runner = runner.with_skills_catalog(catalog);
    }
    apply_engineer_model_override(Arc::new(runner), params)
}

/// Discover the (cheap, metadata-only) skill catalog for `params.project` and
/// build a resolver over it — but only in `HarnessMode::DailyDriver`.
///
/// Why: #2069's scope note is explicit — "Parity mode should NOT
/// progressively disclose" — so `Parity` runs must never discover
/// `.claude/skills/` at all, let alone advertise the `use_skill` tool or
/// inject the catalog into the prompt.
/// What: Returns `None` for `HarnessMode::Parity` or when the project has no
/// (or an empty) skill catalog; otherwise `Some((rendered_catalog,
/// resolver))` — the resolver backs the `use_skill` tool registration.
/// Test: `task::executor::tests::daily_driver_skills_catalog_*`.
fn daily_driver_skills_catalog(params: &TaskRunParams) -> Option<(String, Arc<dyn SkillResolver>)> {
    if params.mode != HarnessMode::DailyDriver {
        return None;
    }
    let skills_dir = locate_skills_dir(&params.project);
    let resolver: Arc<dyn SkillResolver> = Arc::new(FsSkillResolver::new(skills_dir));
    let catalog = format_skill_catalog(&resolver.metadata());
    if catalog.is_empty() {
        None
    } else {
        Some((catalog, resolver))
    }
}

/// Builds the engineer's project-scoped tool registry for each delegation
/// (mirrors `run_task::ProjectToolFactory`, which is private to that module).
struct ProjectToolFactory {
    project: PathBuf,
    /// #2073: the delegating run's resolved `HarnessMode`, threaded onto the
    /// engineer's `EditTool` so `HarnessMode::Parity` selects edit-format
    /// order the same way regardless of which model is delegated to (§5.9's
    /// edit-format reconciliation). `run_task::ProjectToolFactory` (the
    /// legacy CLI path, which never resolves a `HarnessMode`) intentionally
    /// does not carry this field — its `EditTool` stays on the pre-#2073
    /// plain per-model order, unchanged.
    mode: HarnessMode,
}

#[async_trait]
impl RegistryFactory for ProjectToolFactory {
    async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
        // #2068: resolve the engineer's model slug so `EditTool` can pick its
        // per-model edit-format fallback order (mirrors
        // `run_task::ProjectToolFactory::build`, which is private to that module).
        let model_slug = resolve_model(agent, Some(ctx));
        let mut reg = ToolRegistry::new();
        reg.register(Arc::new(ReadFileTool::new(&self.project)));
        reg.register(Arc::new(WriteFileTool::new(&self.project)));
        // #2681: batch-write decouples turn-count from file-count.
        reg.register(Arc::new(WriteFilesTool::new(&self.project)));
        reg.register(Arc::new(
            EditTool::new(&self.project)
                .with_model_slug(model_slug)
                .with_mode(self.mode),
        ));
        // #1027: native file discovery so the engineer stops shelling out to
        // find/grep/ls (the dominant bake-off agent-turn sink).
        reg.register(Arc::new(GlobTool::new(&self.project)));
        reg.register(Arc::new(GrepTool::new(&self.project)));
        reg.register(Arc::new(ListDirTool::new(&self.project)));
        // PR A (#2689): trusty-search-backed conceptual discovery as the PRIMARY
        // path, with the local glob/grep tools above as the fail-open FALLBACK.
        // DailyDriver ONLY — Parity must keep a byte-identical tool surface for
        // benchmark fairness (it never sees MCP-backed tools), so this is gated
        // on the delegating run's resolved `HarnessMode`.
        if self.mode == HarnessMode::DailyDriver {
            reg.register(Arc::new(TrustySearchTool::new(&self.project)));
        }
        reg.register(Arc::new(BashTool::new(
            Some(self.project.clone()),
            Duration::from_secs(ENGINEER_BASH_TIMEOUT_SECS),
        )));
        reg.register(Arc::new(FinishTaskTool::new()));
        Arc::new(reg)
    }
}

/// Apply the per-run engineer-model override, if any (mirrors
/// `run_task::apply_engineer_model_override` / `ModelPinningRunner`, both
/// private to that module).
fn apply_engineer_model_override(
    runner: Arc<dyn AgentRunner>,
    params: &TaskRunParams,
) -> Arc<dyn AgentRunner> {
    match &params.model_override {
        Some(model) => Arc::new(ModelPinningRunner {
            inner: runner,
            model: model.clone(),
        }),
        None => runner,
    }
}

/// An `AgentRunner` decorator pinning a fixed model for every delegation
/// (mirrors `run_task::ModelPinningRunner`).
struct ModelPinningRunner {
    inner: Arc<dyn AgentRunner>,
    model: String,
}

#[async_trait]
impl AgentRunner for ModelPinningRunner {
    async fn run(&self, agent_name: &str, task: &str) -> anyhow::Result<AgentOutput> {
        let ctx = RunContext {
            model: Some(self.model.clone()),
            ..Default::default()
        };
        self.inner.run_with_context(agent_name, task, &ctx).await
    }

    async fn run_with_context(
        &self,
        agent_name: &str,
        task: &str,
        ctx: &RunContext,
    ) -> anyhow::Result<AgentOutput> {
        let mut ctx = ctx.clone();
        ctx.model = Some(self.model.clone());
        self.inner.run_with_context(agent_name, task, &ctx).await
    }
}

/// Resolve the engineer's model the SAME way `InProcessAgentRunner` does
/// internally, purely so the cost split below can price the engineer's
/// turns against its own slug rather than blending everything under the PM
/// model.
///
/// Why: `InProcessAgentRunner` resolves the engineer's model internally and
/// does not expose it; `run_task::resolve_agent_model_slug` (#2061's #1475
/// bug 1 fix) is the ONE shared implementation of "load config, apply
/// override else resolve from config, degrade to `unknown` on load
/// failure" this daemon path and `run_task::execute_run_task`'s legacy CLI
/// path both now call, so they can never independently drift.
/// What: thin wrapper binding this module's `ENGINEER_AGENT_NAME` constant
/// and `params.model_override`.
fn resolve_engineer_model(params: &TaskRunParams) -> String {
    resolve_agent_model_slug(
        &params.agents_dir,
        ENGINEER_AGENT_NAME,
        params.model_override.as_deref(),
    )
}

/// Record a diagnostic log line and transition the session to `Failed`.
///
/// Why: a PM-config load failure happens before any loop runs, so there is
/// no transcript/usage to persist — just the terminal state and a reason an
/// operator (or a future `session.get_transcript`) can see.
async fn finish_with_failure(registry: &SessionRegistry, session_id: &str, message: &str) {
    let _ = registry.record_log(session_id, "error", message);
    let _ = registry.finish(session_id, SessionStatus::Failed);
    registry.finish_execution(session_id);
}

#[cfg(test)]
#[path = "executor_tests.rs"]
mod tests;