trusty-code 0.5.1

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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! 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::{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::binding::ProjectBinding;
use crate::jsonrpc::RpcError;
use crate::llm::{DebugCaptureSink, InferenceAdapter, 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.md`).
/// 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, `agents_dir` mirrors
/// `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). `binding` replaces what was a required `project:
/// PathBuf`; see [`run_and_record`]'s docs for what each of its three states
/// does to indexing, the memory palace, and the tools' working root.
#[derive(Debug, Clone)]
pub struct TaskRunParams {
    pub session_id: String,
    pub task: String,
    pub agent_name: String,
    /// This run's project binding — projectless, a non-git directory, or a git
    /// repo. `ProjectBinding::None` is a fully supported state, not an error.
    pub binding: ProjectBinding,
    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>,
    /// Test-only override for the PM loop's `AgentLoopConfig::telemetry_data_dir`
    /// (issue #3902). `None` on every production call site
    /// (`task::protocol::task_run`) — falls through to
    /// `telemetry::default_data_dir()` exactly as before this field existed.
    /// A `spawn_task_run` test that runs enough turns to trip a real
    /// cadence/threshold fire (this daemon path always sets `cadence:
    /// Some(_)` on the PM loop, see the `cadence` field's docs below) MUST
    /// set this — `AgentLoop::telemetry_data_dir`'s `#[cfg(test)]` guard
    /// panics on the first un-injected fire rather than risk the #3902 race.
    /// `spawn_task_run` immediately `tokio::spawn`s the actual run, which
    /// outlives the caller's own stack frame, so the
    /// `telemetry::with_data_dir_env_fut` pattern
    /// `compression_telemetry_tests.rs` uses (hold a lock across one
    /// `.await`) does not fit here — injecting through this field is the
    /// only mechanism that reaches a detached background task correctly.
    pub telemetry_data_dir: Option<PathBuf>,
}

/// 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 InferenceAdapter>,
    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.
///
/// **Projectless (`ProjectBinding::None`).** Three things assume a project, and
/// each gets a DEFINED behaviour rather than a panic: indexing is **skipped**
/// (nothing to index); the project-scoped memory palace is **skipped** (no
/// project to scope one to — `memory_sink_for` takes `Option<&Path>` and returns
/// `None`); and the fs/bash tools, which need a real directory to be
/// constructible at all, are rooted at an **ephemeral scratch dir** discarded
/// when the run ends. The scratch root is the deliberate choice over dropping
/// the tools entirely: an engineer with no file tools fails in confusing ways,
/// whereas a throwaway root keeps chat/planning coherent while guaranteeing
/// nothing lands in a project the operator never chose. It is logged at `warn`
/// (stderr) so a projectless write is observable, never silent. `CLAUDE.md`,
/// catch-up, skills, and the settings.json mode tier all already degrade to
/// "absent" for a directory that has none, so they need no projectless
/// special-casing — they simply find nothing in the scratch root.
async fn run_and_record(
    registry: Arc<SessionRegistry>,
    llm: Arc<dyn InferenceAdapter>,
    params: TaskRunParams,
    cancel: Arc<AtomicBool>,
) {
    let session_id = params.session_id.clone();

    // Resolve the working root BEFORE anything else: every step below needs a
    // real directory, and projectless has none. `_scratch` must stay alive for
    // the whole run — dropping a `TempDir` deletes it — so it is bound here,
    // not inside the `else` arm.
    let _scratch = match params.binding.root() {
        Some(_) => None,
        None => match tempfile::tempdir() {
            Ok(dir) => {
                tracing::warn!(
                    session_id = %session_id,
                    scratch_root = %dir.path().display(),
                    "projectless run: no project bound — file tools are rooted at an \
                     ephemeral scratch dir that is DISCARDED when this run ends, and \
                     nothing is indexed. Bind a project to persist work."
                );
                Some(dir)
            }
            Err(e) => {
                finish_with_failure(
                    &registry,
                    &session_id,
                    &format!("projectless scratch root error: {e}"),
                )
                .await;
                return;
            }
        },
    };
    let work_root: PathBuf = match (params.binding.root(), &_scratch) {
        (Some(root), _) => root.to_path_buf(),
        (None, Some(dir)) => dir.path().to_path_buf(),
        // Unreachable: the match above binds `_scratch` to `Some` for exactly
        // the `None` root case, returning early on failure. Handled rather than
        // `unwrap`ped per the crate's no-panic-in-library rule.
        (None, None) => {
            finish_with_failure(&registry, &session_id, "projectless scratch root missing").await;
            return;
        }
    };

    // 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.
    //
    // Unlike the CLI path, this daemon path OWNS a session, so it also
    // publishes the resulting readiness as an `Event::IndexReadiness` (#2784
    // UI Phase-1): the UI is a thin client over this daemon, so a warming
    // index is only renderable if it arrives as an event. Without it a
    // mid-warm-up empty search is indistinguishable from a ready index with
    // genuinely zero hits — opposite meanings, identical wire shape.
    //
    // Gated on `should_index` so a projectless run never indexes its
    // throwaway scratch root — note the gate is `should_index`, i.e. "is a
    // project bound", NOT "is it git": a non-git directory DOES index
    // (#2728/#2747).
    if params.binding.should_index() {
        let registry = Arc::clone(&registry);
        let session_id = session_id.clone();
        crate::run_task::ensure_project_indexed_in_background(
            work_root.clone(),
            Some(Box::new(move |readiness| {
                let summary = match &readiness {
                    Some(r) => r.summary(),
                    None => "trusty-search index readiness unknown: no reachable daemon — \
                             search results may be incomplete and an empty result is not \
                             evidence of absence"
                        .to_string(),
                };
                if let Err(e) =
                    registry.record_index_readiness(&session_id, readiness.as_ref(), &summary)
                {
                    // The session finishing before this detached probe lands is
                    // an ordinary race, not a fault — log and drop, exactly as
                    // the tool-event sink does.
                    tracing::debug!(session_id = %session_id, "record_index_readiness skipped: {e}");
                }
            })),
        );
    }
    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();

    // (#3046) Routes through the shared disk-then-embedded resolver —
    // mirrors `run_task::execute_run_task`'s own PM-config load — so a
    // top-level agent name that only exists in the embedded roster (e.g.
    // `engineer`, `rust-engineer`) resolves here too, on the daemon-driven
    // session path.
    let pm_config = match crate::agents::resolve_agent(&params.agents_dir, &params.agent_name) {
        Ok(cfg) => cfg,
        Err(e) => {
            finish_with_failure(&registry, &session_id, &format!("PM config error: {e}")).await;
            return;
        }
    };

    let project_context = load_project_context(&work_root);
    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, &work_root);

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

    // Catch-up is already git-optional and fail-open (it degrades to `None` for
    // a directory with no history), so the projectless scratch root needs no
    // special-casing here — it simply yields no digest.
    let catchup_ctx = crate::catchup::pm_catchup_context(&work_root).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.
    // Projectless has no project to scope a memory palace to, so this yields
    // `None` — see `memory_sink_for`'s `Option<&Path>` contract. The scratch
    // root is deliberately NOT passed: deriving a palace id from a throwaway
    // temp path would mint a fresh, orphaned palace on every projectless run.
    let memory_sink = registry.memory_sink_for(&session_id, params.binding.root());

    // #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.socket().to_path_buf(),
            sink.palace().to_string(),
        )));
    }

    let pm_llm: Arc<dyn InferenceAdapter> = 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(&work_root)),
            // #3902: test-only DI, see `TaskRunParams::telemetry_data_dir`'s
            // docs. `None` (every production call site) falls through to
            // `telemetry::default_data_dir()` unchanged.
            telemetry_data_dir: params.telemetry_data_dir.clone(),
            ..AgentLoopConfig::default()
        },
        pm_llm,
        Arc::new(pm_registry),
    )
    .with_tool_event_sink(Arc::clone(&sink))
    // (UI Phase 1) Attribute this loop's tool events to the PM. `sink` is the
    // SAME `Arc` handed to `build_engineer_runner` above, so without this the
    // PM's and the engineer's tool calls arrive on one stream indistinguishable
    // from each other. `params.agent_name` (default `"pm"`) is the name the
    // rest of the taxonomy already uses for this agent.
    .with_agent(params.agent_name.clone())
    // (DOC-39 AC-13) The PM/root agent also needs a STABLE id so its
    // root-attributed events correlate — unlike a delegated engineer (a
    // fresh UUID per `delegate_to_agent` spawn, see
    // `runner::in_process::InProcessAgentRunner::run_pipeline`), the PM's
    // loop is re-entered on EVERY `task.run` against this same session
    // (`AgentLoop::run_with_transcript` against the persistent
    // `pm_transcript`), so its id must be SESSION-scoped, not re-minted per
    // call — otherwise the PM's own tool events would spuriously look like a
    // new "spawn" on every run. Namespaced with a `pm-` prefix so it reads
    // distinctly from an engineer's bare UUID in a raw event dump.
    .with_agent_id(format!("pm-{session_id}"))
    // (#3867) Stamps this session's real id onto every durable
    // compression-telemetry JSONL record this loop's cadence/threshold
    // instrumentation emits — see `AgentLoop::with_session_id`'s docs.
    .with_session_id(session_id.clone())
    .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/#3888: matched EXHAUSTIVELY over every `AgentLoopError` variant
    // (not a catch-all) so the compiler forces a decision the next time that
    // enum grows one — a catch-all is exactly how #3888 happened the first
    // time (`TurnCapExceeded` silently absorbed into `Failed`). `Llm` is a
    // genuine failure. `Timeout`/`TurnCapExceeded` are cooperative pauses,
    // not failures — `pm_transcript` was already persisted unconditionally
    // above, so the next `task.run` continues right where this one left off;
    // `DeadlineExceeded`/`TurnCapExceeded` are distinct resumable statuses so
    // a consumer can tell "timed out" from "used its turn budget".
    // `StoppedBySignal` is NOT wired into this `pm_loop` today (no
    // `.with_stop_signal(...)` call below), so this arm is dead code for now
    // — but its mapping still matters for whoever wires it in later.
    // Deliberately grouped with `Llm` as `Failed` rather than assumed
    // resumable: `AgentLoop::with_stop_signal` has exactly one caller in the
    // crate today (`run_task::mod`, wired to
    // `RedelegationCapSignal::is_cap_reached()`), and that signal's own doc
    // (`run_task::redelegation`) is explicit that it fires for "a genuinely
    // broken run whose delegations keep failing" and "stopping really is
    // correct" at that point — a stop-and-stay-stopped condition, not a
    // cooperative pause like the turn cap. Whoever wires a DIFFERENT signal
    // into this loop must revisit this arm on its own merits rather than
    // inherit this default.
    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 @ crate::agent_loop::AgentLoopError::TurnCapExceeded { .. }) => {
            let _ =
                registry.record_log(&session_id, "info", &format!("run paused (resumable): {e}"));
            SessionStatus::TurnCapExceeded
        }
        Err(
            e @ (crate::agent_loop::AgentLoopError::Llm(_)
            | crate::agent_loop::AgentLoopError::StoppedBySignal { .. }),
        ) => {
            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. #2152/#2942: the `use_skill` *tool* is now also wired
/// into the engineer's own per-delegation registry (`ProjectToolFactory::build`)
/// against the SAME resolver instance the PM's own `use_skill` tool and catalog
/// were built from — see [`EngineerPromptContext::skill_resolver`]. #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.
///
/// `work_root` is the directory the engineer's fs/bash tools are scoped to: the
/// bound project root, or — when projectless — the run's ephemeral scratch dir
/// (see [`run_and_record`]). It is passed explicitly rather than read off
/// `params` because the scratch root does not exist until the run begins.
/// [`EngineerPromptContext`] bundles the two prompt strings that already
/// travelled together, keeping this function's arity under clippy's
/// `too_many_arguments` gate now that `work_root` is threaded in.
fn build_engineer_runner(
    llm: Arc<dyn InferenceAdapter>,
    params: &TaskRunParams,
    work_root: &Path,
    prompt: EngineerPromptContext,
    transcript: SharedTranscript,
    sink: Arc<dyn ToolEventSink>,
    cancel: Arc<AtomicBool>,
) -> Arc<dyn AgentRunner> {
    let EngineerPromptContext {
        project_context,
        skills_catalog,
        skill_resolver,
    } = prompt;
    let engineer_llm: Arc<dyn InferenceAdapter> = Arc::new(RecordingLlmClient::new(
        llm,
        ENGINEER_AGENT_NAME,
        transcript,
    ));

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

    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)
}

/// The prompt-context strings (plus the skill resolver the `use_skill` tool
/// needs) the delegated engineer's system prompt and registry are assembled
/// from.
///
/// Why: `project_context`/`skills_catalog` are always produced and consumed
/// together and are positionally adjacent — bundling them removes a real
/// easy-to-transpose-the-arguments hazard and keeps
/// [`build_engineer_runner`]'s arity under clippy's `too_many_arguments` gate
/// now that `work_root` must also be threaded through for projectless runs.
/// #2152: `skill_resolver` joined the bundle so `ProjectToolFactory::build`
/// can register `use_skill` against the SAME resolver instance backing
/// `skills_catalog` and the PM's own `use_skill` tool, rather than the
/// engineer's registry omitting the tool its prompt explicitly advertises
/// (closes the gap PR #2942 fixed in the legacy `run_task/mod.rs` path but
/// left open here).
/// What: `project_context` is the project's `CLAUDE.md` (`None` when absent —
/// always the case projectless, since the scratch root has none);
/// `skills_catalog` is the rendered skill-metadata catalog from either the
/// project's `.claude/skills/` or, when that is empty or absent,
/// `crate::assets::DEFAULT_SKILLS` — the embedded default catalog
/// (`skills::discover_skill_metadata`'s embedded-fallback, #2895). `None`
/// only in `HarnessMode::Parity` (which never discovers skills at all, disk
/// or embedded); in `DailyDriver` the embedded fallback means this is
/// effectively always `Some`. `skill_resolver` is `Some` under the exact same
/// condition as `skills_catalog` (both come from the same
/// `daily_driver_skills_catalog` call at the sole construction site).
/// Test: exercised via `task::executor::tests::*`'s engineer-runner paths;
/// `engineer_registry_includes_use_skill_when_catalog_present` pins the
/// registry-side contract.
struct EngineerPromptContext {
    project_context: Option<String>,
    skills_catalog: Option<String>,
    skill_resolver: Option<Arc<dyn SkillResolver>>,
}

/// Discover the (cheap, metadata-only) skill catalog under `work_root` 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`; otherwise
/// `Some((rendered_catalog, resolver))` — the resolver backs the `use_skill`
/// tool registration. `skills::discover_skill_metadata` (the source behind
/// `resolver.metadata()`) falls back to the embedded default skill catalog
/// (`crate::assets::DEFAULT_SKILLS`, #2895) when the project has no (or an
/// empty) `.claude/skills/` directory, so in `HarnessMode::DailyDriver` the
/// catalog is no longer ever empty — a projectless run (scratch root, no
/// `.claude/skills/`) now resolves to the embedded catalog rather than
/// `None`, the same as any other project with no disk skills.
/// Test: `task::executor::tests::daily_driver_skills_catalog_*`.
fn daily_driver_skills_catalog(
    params: &TaskRunParams,
    work_root: &Path,
) -> Option<(String, Arc<dyn SkillResolver>)> {
    if params.mode != HarnessMode::DailyDriver {
        return None;
    }
    let skills_dir = locate_skills_dir(work_root);
    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,
    /// #2152: the SAME `Arc<dyn SkillResolver>` the PM's own `use_skill` tool
    /// and the rendered skills catalog were built from (threaded through
    /// [`EngineerPromptContext::skill_resolver`]). `None` under the same
    /// condition `skills_catalog` is `None` (`HarnessMode::Parity`, which
    /// never discovers skills). Mirrors `run_task::ProjectToolFactory`'s
    /// `skill_resolver` field, which PR #2942 wired up on the legacy path.
    skill_resolver: Option<Arc<dyn SkillResolver>>,
}

#[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()));
        // #2152: mirrors the PM's own conditional `use_skill` registration —
        // only when a skill catalog actually resolved for this delegation, so
        // the engineer's prompt (which advertises `use_skill` whenever
        // `with_skills_catalog` was applied) and its registry stay in sync.
        if let Some(resolver) = &self.skill_resolver {
            reg.register(Arc::new(UseSkillTool::new(Arc::clone(resolver))));
        }
        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;