trusty-code 0.8.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! `tcode serve` daemon: the Unix-socket and STDIO JSON-RPC transports, plus
//! proof-of-life, `session.*`, and `task.*` methods (#2053, #2054, #2056,
//! #2058, M1 control-plane cut line; socket-only since #6637).
//!
//! Why: this module is the foundation the `tcode serve` binary subcommand
//! delegates to. It owns assembling the [`crate::jsonrpc::Router`] (and,
//! since #2054, the [`crate::session::SessionRegistry`] every `session.*`/
//! `task.*` method shares) and entering whichever transport loop was
//! requested; `main.rs` stays a thin clap-to-handler shim, matching the rest
//! of the crate's CLI wiring.
//! What: [`build_router`] registers every currently-known method group
//! (`ping`/`health`, the `session.*`, `task.*`, `fs.*`, `agents.*`,
//! `skills.*`, `permissions.*` and `workstream.*` groups). [`run_stdio`] and
//! [`uds::run_daemon`] both build a router + registry via `build_router` and
//! hand them to their transport ([`transport::run_stdio_loop`] / the hardened
//! socket) — every method behaves identically over either transport because
//! both dispatch through the same `Router`. Both also call
//! `SessionRegistry::shutdown_executions` before returning, so a graceful
//! stop (SIGTERM/stdin EOF) gives any in-flight `task.run` execution a
//! bounded chance to unwind (issue #534).
//!
//! #6637: the loopback HTTP/SSE listener, its bearer-token and origin-guard
//! stack (#6491), the REST resource routes and the address discovery file
//! are gone. The socket is the only door into the persistent daemon.
//!
//! Test: `serve::tests::*`, `serve::uds::uds_tests::*`.
//!
//! [`build_router`]: crate::serve::build_router
//! [`run_stdio`]: crate::serve::run_stdio
//! [`uds::run_daemon`]: crate::serve::uds::run_daemon
//! [`transport::run_stdio_loop`]: crate::serve::transport::run_stdio_loop

pub mod methods;
pub mod transport;
// #6637: the daemon's only persistent transport.
pub mod uds;

use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result};
use tokio::sync::Mutex;
use tracing::info;

use crate::binding::ProjectBinding;
use crate::jsonrpc::Router;
use crate::session::SessionRegistry;
use crate::workstreams::{SharedWorkstreamStore, WorkstreamStore};

/// How long a graceful stop waits for in-flight `task.run` executions to
/// observe cancellation and unwind before the process exits anyway.
///
/// Why: bounds shutdown latency — an operator restarting the daemon should
/// not wait indefinitely on a stuck tool call; best-effort, not a hard
/// guarantee (see `SessionRegistry::shutdown_executions`'s docs).
const SHUTDOWN_GRACE: Duration = Duration::from_secs(10);

/// Assemble the router (+ its session registry) with every method this
/// build of `tcode` knows about, scoped to `project`.
///
/// Why: single place that lists which method groups are wired in, so a new
/// ticket adding `harness.describe` touches exactly one line here plus its
/// own `register` function. Both transports (`run_stdio`, `uds::run_daemon`)
/// call this so they can never drift into different method surfaces, and the
/// socket needs the SAME `SessionRegistry` instance for its `session.events`
/// stream, which bypasses the `Router` (see `crate::serve::uds`). `task.run` (#2056) is
/// the first method that needs `project` for more than logging — it resolves
/// `agents_dir` from it via `crate::agents::locate_agents_dir` (the same
/// `.claude/agents` / `.open-mpm/agents` convention `tcode run-task` uses)
/// and passes both down to spawned executions.
/// `fs.list_dir` (UI Phase-1) is the one group that needs NO shared state — a
/// directory listing is a pure function of the filesystem at call time — so it
/// registers with neither `sessions` nor `project`.
/// `agents.*`/`skills.*` (issue #3449) are the Foundry GUI's catalog
/// management surface — list/create/delete over the disk tier
/// `crate::agents::resolve_agent` and `crate::skills::discover_skill_metadata`
/// already recognise, plus the embedded/bundled roster each falls back to.
/// Both register with immutable state resolved once here from `binding`
/// (`AgentsCatalogState`/`SkillsCatalogState` — no `Mutex`, every operation is
/// a stateless filesystem call at request time).
/// What: builds an empty `Router` + a fresh `SessionRegistry`, calls
/// `methods::register`, `crate::session::protocol::register`,
/// `crate::fs_browse::protocol::register`, and
/// `crate::task::protocol::register` on them, and returns both.
///
/// (DOC-48, issues #3294/#3295) also loads this project's
/// [`crate::workstreams::WorkstreamStore`] (`~/.trusty-code/workstreams-....json`,
/// derived from `binding` per DOC-48 §3.1), runs its boot reconciliation
/// (§3.3 — restores the persisted active pointer, or clears it if the
/// workstream it named was deleted; never destructive), wraps it in a
/// `tokio::sync::Mutex` (the store's mutating methods take `&mut self`, and
/// its file I/O is `async` — mirrors `SessionRegistry`'s `Arc`-shared-state
/// convention, see `crate::workstreams::activation::SharedWorkstreamStore`'s
/// docs for why `tokio`'s `Mutex` specifically), and registers
/// `crate::workstreams::protocol::register` — all six `workstream.*` methods
/// (`create`/`get`/`list`/`close` from #3295, `activate`/`deactivate` from
/// #3294) sharing this one store handle — alongside every other method
/// group. This is why `build_router` is now `async` and fallible — the
/// prior synchronous, infallible signature had no way to load persisted
/// state before the router starts answering requests, and a corrupt store
/// file must fail daemon startup loudly rather than silently discard the
/// user's workstreams (see `WorkstreamStore::load`'s docs).
///
/// `binding` is the daemon's project binding. Its `None` (projectless) state is
/// what makes the shell's entry screen implementable: previously `build_router`
/// took a required `PathBuf`, so a daemon could not even START without a
/// project, and `task.run` could not be called without one. `agents_dir` now
/// resolves via `ProjectBinding::agents_dir`, which falls back to the
/// user-level `~/.claude/agents` when projectless rather than to the process
/// CWD (which would silently bind a directory nobody chose).
/// (issue #3297) Also returns the [`SharedWorkstreamStore`] itself (not just
/// the `Router` it registered `workstream.*` against) — the socket's
/// `workstream.events` stream needs the SAME handle (#6637). This is why the
/// return type grew a third element rather than staying a 2-tuple.
///
/// Test: `run_stdio_router_recognises_proof_of_life_methods`,
/// `build_router_wires_session_methods`, `build_router_wires_task_run`,
/// `build_router_is_projectless_without_a_project`,
/// `build_router_wires_fs_list_dir`, `build_router_wires_workstream_methods`,
/// `build_router_wires_agents_and_skills_catalog_methods`,
/// `build_router_reconciles_dangling_active_pointer_on_boot`.
pub async fn build_router(
    binding: ProjectBinding,
) -> Result<(Router, Arc<SessionRegistry>, SharedWorkstreamStore)> {
    // #6537: start the log-drain scheduler once, at the daemon's one
    // production entry point (tests go through `build_router_at` directly and
    // never spawn it). `binding.root()` is read before `build_router_at`
    // consumes `binding`. This is the ONE place that resolves the real
    // `~/.trusty-code/log-drain` state directory (#6537 code-review fix
    // round) — every test drives the scheduler's `tick` with a tempdir
    // instead.
    crate::log_drain::spawn(
        binding.root().map(std::path::Path::to_path_buf),
        crate::logging::file_log_dir(),
        crate::paths::private_state::private_state_dir().join("log-drain"),
    );
    build_router_at(binding, &crate::workstreams::default_data_dir()).await
}

/// Like [`build_router`] but takes an explicit workstream data directory
/// instead of always resolving `~/.trusty-code`.
///
/// Why: every unit test in this module builds a router; letting them all
/// resolve the REAL `~/.trusty-code` would read/write the developer's (or
/// CI runner's) actual home directory on every `cargo test` run — this seam
/// lets tests pass a throwaway tempdir instead, while `build_router` (the
/// only entry point `run_stdio`/`uds::run_daemon` call) always uses the real
/// directory.
/// What: identical to `build_router`'s full docs otherwise — loads (or
/// creates) the workstream store at `data_dir` via `binding`'s derived
/// filename, runs boot reconciliation, and registers every method group.
async fn build_router_at(
    binding: ProjectBinding,
    data_dir: &std::path::Path,
) -> Result<(Router, Arc<SessionRegistry>, SharedWorkstreamStore)> {
    let sessions = Arc::new(SessionRegistry::new());
    // #2074: materialize the embedded roster to `<project>/.trusty-code/agents/`
    // before resolving the agents directory, so every shipped role has a file, a
    // manifest entry, and a recorded origin. Projectless daemons write nothing.
    crate::agents::deploy::deploy_and_log(binding.root());
    let agents_dir = binding.agents_dir();

    let mut workstream_store = WorkstreamStore::load_for_binding(data_dir, &binding)
        .await
        .context("loading workstream store")?;
    // #4579: the registry is in-memory, so at boot it is empty and every
    // persisted session_id is dangling — reconciliation prunes them against
    // the live set. Deriving the set from `sessions` (rather than passing an
    // empty one) keeps this correct if a future boot path pre-populates the
    // registry before reconciling.
    let live_session_ids: std::collections::HashSet<String> =
        sessions.list().into_iter().map(|s| s.id).collect();
    workstream_store
        .reconcile_on_boot(&live_session_ids)
        .await
        .context("reconciling workstream store on boot")?;
    let workstreams = Arc::new(Mutex::new(workstream_store));

    let mut router = Router::new();
    // #4512: `health` publishes the binding, so a client that auto-attaches
    // to a daemon it did not start can tell which project it would drive.
    methods::register(&mut router, binding.clone());
    crate::session::protocol::register(&mut router, sessions.clone(), workstreams.clone());
    crate::fs_browse::protocol::register(&mut router);
    crate::agents::protocol::register(
        &mut router,
        crate::agents::protocol::AgentsCatalogState::new(agents_dir.clone(), binding.is_bound()),
    );
    crate::skills::protocol::register(
        &mut router,
        crate::skills::protocol::SkillsCatalogState::new(binding.root()),
    );
    // #7948: ONE broker for the daemon's life — `task.run` hands it to every
    // run and `session.permission.respond` answers into it, so a waiting gate
    // and the answering client meet on the same state.
    let permissions = Arc::new(crate::permissions::PermissionBroker::new());
    crate::permissions::protocol::register(&mut router, Arc::clone(&permissions));
    crate::task::protocol::register_with_permissions(
        &mut router,
        sessions.clone(),
        binding,
        agents_dir,
        workstreams.clone(),
        Some(permissions),
    );
    crate::workstreams::protocol::register(&mut router, workstreams.clone());
    Ok((router, sessions, workstreams))
}

/// Run `tcode serve --stdio` to completion.
///
/// Why: the top-level entry point `main.rs` calls for the `serve --stdio`
/// subcommand.
/// What: builds the router, logs start/stop to stderr, and enters
/// [`transport::run_stdio_loop`], returning when it returns (stdin EOF or
/// SIGTERM/SIGINT). On return, calls `SessionRegistry::shutdown_executions`
/// (bounded by [`SHUTDOWN_GRACE`]) so an in-flight `task.run` gets a chance
/// to unwind before the process exits.
/// Test: `run_stdio_router_recognises_proof_of_life_methods` covers the
/// router assembly; the transport loop itself is covered by
/// `transport::tests`.
pub async fn run_stdio(binding: ProjectBinding) -> Result<()> {
    info!(
        binding = binding.state(),
        project = binding.label().unwrap_or_else(|| "<projectless>".into()),
        "tcode serve --stdio: starting"
    );
    let (router, sessions, _workstreams) = build_router(binding).await?;
    transport::run_stdio_loop(router).await?;
    sessions.shutdown_executions(SHUTDOWN_GRACE).await;
    info!("tcode serve --stdio: stopped");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{Value, json};
    use trusty_mcp::Request;

    fn test_ctx() -> crate::jsonrpc::ConnectionContext {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        crate::jsonrpc::ConnectionContext::new(tx)
    }

    /// `build_router` must recognise both proof-of-life methods.
    #[tokio::test]
    async fn run_stdio_router_recognises_proof_of_life_methods() {
        let project = tempfile::tempdir().expect("project tempdir");
        let data_dir = tempfile::tempdir().expect("data tempdir");
        let (router, _sessions, _workstreams) = build_router_at(
            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
            data_dir.path(),
        )
        .await
        .expect("build_router_at");
        for method in ["ping", "health"] {
            let req = Request {
                jsonrpc: Some("2.0".to_string()),
                id: Some(json!(1)),
                method: method.to_string(),
                params: None,
            };
            let resp = router.dispatch(req, &test_ctx()).await;
            assert!(
                resp.error.is_none(),
                "{method} must be registered, got {:?}",
                resp.error
            );
        }
    }

    /// `build_router` must also wire every `session.*` method (#2054),
    /// sharing the registry it returns.
    #[tokio::test]
    async fn build_router_wires_session_methods() {
        let project = tempfile::tempdir().expect("project tempdir");
        let data_dir = tempfile::tempdir().expect("data tempdir");
        let (router, sessions, _workstreams) = build_router_at(
            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
            data_dir.path(),
        )
        .await
        .expect("build_router_at");
        let session = sessions.create("t".to_string(), None, crate::binding::ProjectBinding::None);

        let req = Request {
            jsonrpc: Some("2.0".to_string()),
            id: Some(json!(1)),
            method: "session.status".to_string(),
            params: Some(json!({"session_id": session.id})),
        };
        let resp = router.dispatch(req, &test_ctx()).await;
        assert!(
            resp.error.is_none(),
            "session.status must be registered, got {:?}",
            resp.error
        );
        assert_eq!(resp.result.unwrap()["id"], session.id);
    }

    /// `build_router` must also wire `fs.list_dir` (UI Phase-1), so the UI's
    /// project picker is reachable over the same `/rpc` endpoint as everything
    /// else.
    #[tokio::test]
    async fn build_router_wires_fs_list_dir() {
        let project = tempfile::tempdir().expect("project tempdir");
        let data_dir = tempfile::tempdir().expect("data tempdir");
        let (router, _sessions, _workstreams) = build_router_at(
            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
            data_dir.path(),
        )
        .await
        .expect("build_router_at");

        let req = Request {
            jsonrpc: Some("2.0".to_string()),
            id: Some(json!(1)),
            method: "fs.list_dir".to_string(),
            params: Some(json!({"path": project.path().display().to_string()})),
        };
        let resp = router.dispatch(req, &test_ctx()).await;
        assert!(
            resp.error.is_none(),
            "fs.list_dir must be registered, got {:?}",
            resp.error
        );
        assert!(resp.result.expect("result")["entries"].is_array());
    }

    /// `build_router` must also wire `agents.list`/`skills.list` (issue
    /// #3449), so the Foundry GUI's Agents/Skills tabs are reachable over
    /// the same `/rpc` endpoint as everything else.
    #[tokio::test]
    async fn build_router_wires_agents_and_skills_catalog_methods() {
        let project = tempfile::tempdir().expect("project tempdir");
        let data_dir = tempfile::tempdir().expect("data tempdir");
        let (router, _sessions, _workstreams) = build_router_at(
            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
            data_dir.path(),
        )
        .await
        .expect("build_router_at");

        for method in ["agents.list", "skills.list"] {
            let req = Request {
                jsonrpc: Some("2.0".to_string()),
                id: Some(json!(1)),
                method: method.to_string(),
                params: None,
            };
            let resp = router.dispatch(req, &test_ctx()).await;
            assert!(
                resp.error.is_none(),
                "{method} must be registered, got {:?}",
                resp.error
            );
        }
    }

    /// The daemon must ASSEMBLE with no project bound — `build_router` took a
    /// required `PathBuf` before, so a projectless daemon could not exist and
    /// the shell had no entry state to render. `task.run` must be wired just
    /// the same in that state.
    #[tokio::test]
    async fn build_router_is_projectless_without_a_project() {
        let data_dir = tempfile::tempdir().expect("data tempdir");
        let (router, _sessions, _workstreams) =
            build_router_at(ProjectBinding::None, data_dir.path())
                .await
                .expect("build_router_at");
        for method in ["task.run", "session.create", "session.list"] {
            let req = Request {
                jsonrpc: Some("2.0".to_string()),
                id: Some(json!(1)),
                method: method.to_string(),
                params: Some(json!({})),
            };
            let resp = router.dispatch(req, &test_ctx()).await;
            // Params are deliberately empty, so an `invalid_params`/
            // `invalid_argument` is fine and expected — the ONE thing that must
            // not happen is `-32601 Method not found`, which would mean a
            // projectless daemon serves a different method surface.
            if let Some(err) = resp.error {
                assert_ne!(
                    err.code, -32601,
                    "{method} must be wired on a projectless daemon, got method-not-found"
                );
            }
        }
    }

    #[tokio::test]
    async fn build_router_wires_task_run() {
        let project = tempfile::tempdir().expect("project tempdir");
        std::fs::create_dir_all(project.path().join(".claude").join("agents")).expect("mkdir");
        std::fs::write(
            project.path().join(".claude").join("agents").join("pm.md"),
            "---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nPM\n",
        )
        .expect("write pm.md");
        std::fs::write(
            project
                .path()
                .join(".claude")
                .join("agents")
                .join("python-engineer.md"),
            "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\neng\n",
        )
        .expect("write python-engineer.md");

        // SAFETY: test-only env mutation; serialized by the shared crate lock.
        let _guard = crate::task::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
        unsafe {
            std::env::set_var(
                crate::task::mock_llm::MOCK_LLM_ENV,
                crate::task::mock_llm::MOCK_LLM_ECHO,
            );
        }
        let data_dir = tempfile::tempdir().expect("data tempdir");
        let (router, sessions, _workstreams) = build_router_at(
            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
            data_dir.path(),
        )
        .await
        .expect("build_router_at");
        let req = Request {
            jsonrpc: Some("2.0".to_string()),
            id: Some(json!(1)),
            method: "task.run".to_string(),
            params: Some(json!({"task_description": "say hi"})),
        };
        let resp = router.dispatch(req, &test_ctx()).await;
        sessions
            .shutdown_executions(std::time::Duration::from_secs(5))
            .await;
        unsafe {
            std::env::remove_var(crate::task::mock_llm::MOCK_LLM_ENV);
        }

        assert!(
            resp.error.is_none(),
            "task.run must be registered, got {:?}",
            resp.error
        );
        assert_eq!(resp.result.unwrap()["status"], "running");
    }

    /// `build_router` must also wire `workstream.activate`/
    /// `workstream.deactivate` (DOC-48 §6, issue #3294), and the activation
    /// pointer they write must be the SAME store a fresh `build_router_at`
    /// call over the same `data_dir`/`binding` reloads (AC-1.4 boot
    /// restoration, exercised end-to-end through the daemon's own assembly
    /// path rather than `workstreams::protocol_tests`' narrower unit tests).
    #[tokio::test]
    async fn build_router_wires_workstream_methods() {
        let project = tempfile::tempdir().expect("project tempdir");
        let data_dir = tempfile::tempdir().expect("data tempdir");
        let binding =
            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");

        let (router, _sessions, _workstreams) = build_router_at(binding.clone(), data_dir.path())
            .await
            .expect("build_router_at");

        let create_req = Request {
            jsonrpc: Some("2.0".to_string()),
            id: Some(json!(1)),
            method: "workstream.activate".to_string(),
            params: Some(json!({"id": crate::workstreams::WorkstreamId::new().to_string()})),
        };
        // An id minted here names no existing workstream, so this must map
        // to `-32002 not_found`, NOT `-32601 method not found` — the point
        // of this assertion is that the method is REGISTERED, not that this
        // particular call succeeds (there is no `workstream.create` to seed
        // one with yet — that is #3295's surface).
        let resp = router.dispatch(create_req, &test_ctx()).await;
        let err = resp
            .error
            .expect("activating an unknown id must fail, not silently succeed");
        assert_eq!(err.code, -32002, "workstream.activate must be registered");

        let deactivate_req = Request {
            jsonrpc: Some("2.0".to_string()),
            id: Some(json!(2)),
            method: "workstream.deactivate".to_string(),
            params: Some(json!({"id": crate::workstreams::WorkstreamId::new().to_string()})),
        };
        // Deactivating an unknown id is an idempotent no-op (DOC-48 §4.3),
        // so this must succeed — proving `workstream.deactivate` is wired
        // too.
        let resp = router.dispatch(deactivate_req, &test_ctx()).await;
        assert!(
            resp.error.is_none(),
            "workstream.deactivate must be registered, got {:?}",
            resp.error
        );

        // Boot restoration (AC-1.4): a fresh `build_router_at` over the SAME
        // data_dir/binding must load the store this instance persisted to,
        // rather than starting from a brand-new empty one — proven here by
        // reconciliation completing without error on the same file the
        // first instance created.
        let (_router2, _sessions2, _workstreams2) = build_router_at(binding, data_dir.path())
            .await
            .expect("a second build_router_at over the same data_dir must succeed");
    }

    /// Boot reconciliation (DOC-48 §3.3, AC-1.4/AC-6.1/AC-6.2) must run
    /// through the REAL daemon assembly path, not just
    /// `WorkstreamStore::reconcile_on_boot` called directly (already covered
    /// by `workstreams::store::store_tests::reconcile_clears_active_when_target_missing`).
    /// A store file seeded on disk with a DANGLING `active_workstream_id`
    /// (pointing at a workstream absent from `workstreams[]` — e.g. deleted
    /// out from under the pointer, or hand-edited) must have that pointer
    /// cleared by `build_router_at`'s `reconcile_on_boot()` call BEFORE the
    /// router ever answers a request; `workstream.list` reporting
    /// `active_workstream_id: null` is the end-to-end proof.
    #[tokio::test]
    async fn build_router_reconciles_dangling_active_pointer_on_boot() {
        let project = tempfile::tempdir().expect("project tempdir");
        let data_dir = tempfile::tempdir().expect("data tempdir");
        let binding =
            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");

        let store_path = crate::workstreams::store_path(data_dir.path(), &binding);
        let dangling_id = crate::workstreams::WorkstreamId::new();
        let raw = json!({
            "version": "1.0",
            "active_workstream_id": dangling_id,
            "workstreams": [],
        });
        tokio::fs::create_dir_all(data_dir.path())
            .await
            .expect("mkdir data_dir");
        tokio::fs::write(&store_path, serde_json::to_string_pretty(&raw).unwrap())
            .await
            .expect("seed raw store file with a dangling active_workstream_id");

        let (router, _sessions, _workstreams) = build_router_at(binding, data_dir.path())
            .await
            .expect("build_router_at must reconcile the dangling pointer, not fail");

        let req = Request {
            jsonrpc: Some("2.0".to_string()),
            id: Some(json!(1)),
            method: "workstream.list".to_string(),
            params: Some(json!({})),
        };
        let resp = router.dispatch(req, &test_ctx()).await;
        assert!(
            resp.error.is_none(),
            "workstream.list must succeed, got {:?}",
            resp.error
        );
        assert_eq!(
            resp.result.unwrap()["active_workstream_id"],
            Value::Null,
            "boot reconciliation through build_router_at must clear a dangling \
             active_workstream_id before the router answers requests"
        );
    }
}