Skip to main content

trusty_code/serve/
mod.rs

1//! `tcode serve` daemon: STDIO + HTTP JSON-RPC transports + proof-of-life,
2//! `session.*`, and `task.*` methods (#2053, #2054, #2056, #2058,
3//! M1 control-plane cut line).
4//!
5//! Why: this module is the foundation the `tcode serve` binary subcommand
6//! delegates to. It owns assembling the [`crate::jsonrpc::Router`] (and,
7//! since #2054, the [`crate::session::SessionRegistry`] every `session.*`/
8//! `task.*` method shares) and entering whichever transport loop was
9//! requested; `main.rs` stays a thin clap-to-handler shim, matching the rest
10//! of the crate's CLI wiring.
11//! What: [`build_router`] registers every currently-known method group
12//! (today: [`methods::register`]'s `ping`/`health` proof-of-life pair,
13//! `crate::session::protocol::register`'s eight `session.*` methods
14//! (including #2058's read-only `session.get_transcript`), and (#2056)
15//! `crate::task::protocol::register`'s `task.run` — later tickets add
16//! `harness.describe` #2066 here, one line each). [`run_stdio`] and
17//! [`run_http`] both build a router + registry via `build_router` and hand
18//! them to their respective transport ([`transport::run_stdio_loop`] /
19//! [`http::run_http`]) — every method behaves identically over either
20//! transport because both dispatch through the same `Router` against the
21//! same `SessionRegistry`. Both also call
22//! `SessionRegistry::shutdown_executions` before returning, so a graceful
23//! stop (SIGTERM/stdin EOF) gives any in-flight `task.run` execution a
24//! bounded chance to unwind — the same connection-safe-restart discipline
25//! (issue #534) this crate's daemons already apply to connections, now
26//! extended to background tasks.
27//!
28//! What's NOT here yet: the transports are independent modes (`--stdio` xor
29//! `--http`), not simultaneous; running both at once would need a shared
30//! `Arc<Router>`/`Arc<SessionRegistry>` across two concurrently-spawned
31//! tasks, which no current ticket requires (the registry is already `Arc`,
32//! so this is a small extension when it's needed).
33//!
34//! Test: `serve::tests::*`.
35//!
36//! [`build_router`]: crate::serve::build_router
37//! [`methods::register`]: crate::serve::methods::register
38//! [`run_stdio`]: crate::serve::run_stdio
39//! [`run_http`]: crate::serve::run_http
40//! [`transport::run_stdio_loop`]: crate::serve::transport::run_stdio_loop
41//! [`http::run_http`]: crate::serve::http::run_http
42
43pub mod discovery;
44pub mod http;
45pub mod methods;
46pub mod rest;
47pub mod transport;
48
49use std::sync::Arc;
50use std::time::Duration;
51
52use anyhow::{Context, Result};
53use tokio::sync::Mutex;
54use tracing::info;
55
56use crate::binding::ProjectBinding;
57use crate::jsonrpc::Router;
58use crate::session::SessionRegistry;
59use crate::workstreams::{SharedWorkstreamStore, WorkstreamStore};
60
61/// How long a graceful stop waits for in-flight `task.run` executions to
62/// observe cancellation and unwind before the process exits anyway.
63///
64/// Why: bounds shutdown latency — an operator restarting the daemon should
65/// not wait indefinitely on a stuck tool call; best-effort, not a hard
66/// guarantee (see `SessionRegistry::shutdown_executions`'s docs).
67const SHUTDOWN_GRACE: Duration = Duration::from_secs(10);
68
69/// Default TCP port for `tcode serve --http` when `--port` is omitted.
70///
71/// Why: the trusty-* family reserves a block of fixed local ports so
72/// operators/tooling can find a daemon without a discovery file
73/// (`trusty-search` 7878,
74/// `trusty-mpm` daemon 7880, `trusty-embedderd` `--http` mode 7890).
75/// `trusty-review` used to hold 7891 and no longer does — #6277 moved it to a
76/// Unix socket. This constant previously reused `7881`, which turned
77/// out to collide with `trusty-mpm`'s supervisor metrics listener — the two
78/// defaults were picked independently and nothing pinned them apart, so a
79/// fresh install with both `tm supervisor` and `tcode serve` running answered
80/// `/health` on `tcode`'s port with the supervisor's generic
81/// `{"status":"ok"}`, masking a real 404 for every other route (#3364). That
82/// listener is retired (#6288 — the supervisor publishes to a file), so 7881
83/// is free again; this constant stays on `7882` because a released value is
84/// not reused. `7882` is verified free against
85/// the full known-sibling table in
86/// `docs/architecture/port-assignments.md` and matches the session-local
87/// workaround used to confirm the fix (`tcode serve --http --port 7882`).
88/// Pass `--port 0` to bind an OS-assigned ephemeral port instead (e.g. for
89/// tests or running multiple instances side by side); the real bound port
90/// is always logged to stderr regardless of which is used.
91/// What: `7882`.
92/// Test: `default_http_port_is_documented_value`,
93/// `default_http_port_does_not_collide_with_known_siblings`.
94pub const DEFAULT_HTTP_PORT: u16 = 7882;
95
96/// Assemble the router (+ its session registry) with every method this
97/// build of `tcode` knows about, scoped to `project`.
98///
99/// Why: single place that lists which method groups are wired in, so a new
100/// ticket adding `harness.describe` touches exactly one line here plus its
101/// own `register` function. Both transports (`run_stdio`, `run_http`) call
102/// this so they can never drift into different method surfaces, and both
103/// need the SAME `SessionRegistry` instance — `run_http` hands it separately
104/// to the `GET /sessions/{id}/events` SSE route, which bypasses the `Router`
105/// entirely (see `crate::serve::http` module docs). `task.run` (#2056) is
106/// the first method that needs `project` for more than logging — it resolves
107/// `agents_dir` from it via `crate::agents::locate_agents_dir` (the same
108/// `.claude/agents` / `.open-mpm/agents` convention `tcode run-task` uses)
109/// and passes both down to spawned executions.
110/// `fs.list_dir` (UI Phase-1) is the one group that needs NO shared state — a
111/// directory listing is a pure function of the filesystem at call time — so it
112/// registers with neither `sessions` nor `project`.
113/// `agents.*`/`skills.*` (issue #3449) are the Foundry GUI's catalog
114/// management surface — list/create/delete over the disk tier
115/// `crate::agents::resolve_agent` and `crate::skills::discover_skill_metadata`
116/// already recognise, plus the embedded/bundled roster each falls back to.
117/// Both register with immutable state resolved once here from `binding`
118/// (`AgentsCatalogState`/`SkillsCatalogState` — no `Mutex`, every operation is
119/// a stateless filesystem call at request time).
120/// What: builds an empty `Router` + a fresh `SessionRegistry`, calls
121/// `methods::register`, `crate::session::protocol::register`,
122/// `crate::fs_browse::protocol::register`, and
123/// `crate::task::protocol::register` on them, and returns both.
124///
125/// (DOC-48, issues #3294/#3295) also loads this project's
126/// [`crate::workstreams::WorkstreamStore`] (`~/.trusty-code/workstreams-....json`,
127/// derived from `binding` per DOC-48 §3.1), runs its boot reconciliation
128/// (§3.3 — restores the persisted active pointer, or clears it if the
129/// workstream it named was deleted; never destructive), wraps it in a
130/// `tokio::sync::Mutex` (the store's mutating methods take `&mut self`, and
131/// its file I/O is `async` — mirrors `SessionRegistry`'s `Arc`-shared-state
132/// convention, see `crate::workstreams::activation::SharedWorkstreamStore`'s
133/// docs for why `tokio`'s `Mutex` specifically), and registers
134/// `crate::workstreams::protocol::register` — all six `workstream.*` methods
135/// (`create`/`get`/`list`/`close` from #3295, `activate`/`deactivate` from
136/// #3294) sharing this one store handle — alongside every other method
137/// group. This is why `build_router` is now `async` and fallible — the
138/// prior synchronous, infallible signature had no way to load persisted
139/// state before the router starts answering requests, and a corrupt store
140/// file must fail daemon startup loudly rather than silently discard the
141/// user's workstreams (see `WorkstreamStore::load`'s docs).
142///
143/// `binding` is the daemon's project binding. Its `None` (projectless) state is
144/// what makes the shell's entry screen implementable: previously `build_router`
145/// took a required `PathBuf`, so a daemon could not even START without a
146/// project, and `task.run` could not be called without one. `agents_dir` now
147/// resolves via `ProjectBinding::agents_dir`, which falls back to the
148/// user-level `~/.claude/agents` when projectless rather than to the process
149/// CWD (which would silently bind a directory nobody chose).
150/// (issue #3297) Also returns the [`SharedWorkstreamStore`] itself (not just
151/// the `Router` it registered `workstream.*` against) — `run_http` needs the
152/// SAME handle to hand to `crate::serve::http::run_http`, which merges
153/// `crate::workstreams::sse::routes` (the `GET /workstreams/{id}/events`
154/// aggregation route) alongside the JSON-RPC-backed REST surface. This is
155/// why the return type grew a third element rather than staying a 2-tuple.
156///
157/// Test: `run_stdio_router_recognises_proof_of_life_methods`,
158/// `build_router_wires_session_methods`, `build_router_wires_task_run`,
159/// `build_router_is_projectless_without_a_project`,
160/// `build_router_wires_fs_list_dir`, `build_router_wires_workstream_methods`,
161/// `build_router_wires_agents_and_skills_catalog_methods`,
162/// `build_router_reconciles_dangling_active_pointer_on_boot`.
163pub async fn build_router(
164    binding: ProjectBinding,
165) -> Result<(Router, Arc<SessionRegistry>, SharedWorkstreamStore)> {
166    build_router_at(binding, &crate::workstreams::default_data_dir()).await
167}
168
169/// Like [`build_router`] but takes an explicit workstream data directory
170/// instead of always resolving `~/.trusty-code`.
171///
172/// Why: every unit test in this module builds a router; letting them all
173/// resolve the REAL `~/.trusty-code` would read/write the developer's (or
174/// CI runner's) actual home directory on every `cargo test` run — this seam
175/// lets tests pass a throwaway tempdir instead, while `build_router` (the
176/// only entry point `run_stdio`/`run_http` call) always uses the real
177/// directory.
178/// What: identical to `build_router`'s full docs otherwise — loads (or
179/// creates) the workstream store at `data_dir` via `binding`'s derived
180/// filename, runs boot reconciliation, and registers every method group.
181async fn build_router_at(
182    binding: ProjectBinding,
183    data_dir: &std::path::Path,
184) -> Result<(Router, Arc<SessionRegistry>, SharedWorkstreamStore)> {
185    let sessions = Arc::new(SessionRegistry::new());
186    let agents_dir = binding.agents_dir();
187
188    let mut workstream_store = WorkstreamStore::load_for_binding(data_dir, &binding)
189        .await
190        .context("loading workstream store")?;
191    // #4579: the registry is in-memory, so at boot it is empty and every
192    // persisted session_id is dangling — reconciliation prunes them against
193    // the live set. Deriving the set from `sessions` (rather than passing an
194    // empty one) keeps this correct if a future boot path pre-populates the
195    // registry before reconciling.
196    let live_session_ids: std::collections::HashSet<String> =
197        sessions.list().into_iter().map(|s| s.id).collect();
198    workstream_store
199        .reconcile_on_boot(&live_session_ids)
200        .await
201        .context("reconciling workstream store on boot")?;
202    let workstreams = Arc::new(Mutex::new(workstream_store));
203
204    let mut router = Router::new();
205    // #4512: `health` publishes the binding, so a client that auto-attaches
206    // to a daemon it did not start can tell which project it would drive.
207    methods::register(&mut router, binding.clone());
208    crate::session::protocol::register(&mut router, sessions.clone(), workstreams.clone());
209    crate::fs_browse::protocol::register(&mut router);
210    crate::agents::protocol::register(
211        &mut router,
212        crate::agents::protocol::AgentsCatalogState::new(agents_dir.clone(), binding.is_bound()),
213    );
214    crate::skills::protocol::register(
215        &mut router,
216        crate::skills::protocol::SkillsCatalogState::new(binding.root()),
217    );
218    crate::task::protocol::register(
219        &mut router,
220        sessions.clone(),
221        binding,
222        agents_dir,
223        workstreams.clone(),
224    );
225    crate::workstreams::protocol::register(&mut router, workstreams.clone());
226    Ok((router, sessions, workstreams))
227}
228
229/// Run `tcode serve --stdio` to completion.
230///
231/// Why: the top-level entry point `main.rs` calls for the `serve --stdio`
232/// subcommand.
233/// What: builds the router, logs start/stop to stderr, and enters
234/// [`transport::run_stdio_loop`], returning when it returns (stdin EOF or
235/// SIGTERM/SIGINT). On return, calls `SessionRegistry::shutdown_executions`
236/// (bounded by [`SHUTDOWN_GRACE`]) so an in-flight `task.run` gets a chance
237/// to unwind before the process exits.
238/// Test: `run_stdio_router_recognises_proof_of_life_methods` covers the
239/// router assembly; the transport loop itself is covered by
240/// `transport::tests`.
241pub async fn run_stdio(binding: ProjectBinding) -> Result<()> {
242    info!(
243        binding = binding.state(),
244        project = binding.label().unwrap_or_else(|| "<projectless>".into()),
245        "tcode serve --stdio: starting"
246    );
247    let (router, sessions, _workstreams) = build_router(binding).await?;
248    transport::run_stdio_loop(router).await?;
249    sessions.shutdown_executions(SHUTDOWN_GRACE).await;
250    info!("tcode serve --stdio: stopped");
251    Ok(())
252}
253
254/// Run `tcode serve --http` to completion.
255///
256/// Why: the top-level entry point `main.rs` calls for the `serve --http`
257/// subcommand.
258/// What: builds the router + session registry, logs start/stop to stderr,
259/// and enters [`http::run_http`] bound to `port` (`0` = OS-assigned
260/// ephemeral port), returning when it returns (SIGTERM/SIGINT). On return,
261/// calls `SessionRegistry::shutdown_executions` (bounded by
262/// [`SHUTDOWN_GRACE`]) — see [`run_stdio`]'s docs for why.
263/// Test: `run_stdio_router_recognises_proof_of_life_methods` covers the
264/// shared router assembly; `http::tests` cover the routing/dispatch logic.
265pub async fn run_http(binding: ProjectBinding, port: u16) -> Result<()> {
266    info!(
267        binding = binding.state(),
268        project = binding.label().unwrap_or_else(|| "<projectless>".into()),
269        port,
270        "tcode serve --http: starting"
271    );
272    // #4512: `GET /health` reports this binding, so keep a handle before
273    // `build_router` consumes it.
274    let published_binding = Arc::new(binding.clone());
275    let (router, sessions, workstreams) = build_router(binding).await?;
276    http::run_http(
277        router,
278        sessions.clone(),
279        workstreams,
280        port,
281        published_binding,
282    )
283    .await?;
284    sessions.shutdown_executions(SHUTDOWN_GRACE).await;
285    info!("tcode serve --http: stopped");
286    Ok(())
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use serde_json::{Value, json};
293    use trusty_mcp::Request;
294
295    fn test_ctx() -> crate::jsonrpc::ConnectionContext {
296        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
297        crate::jsonrpc::ConnectionContext::new(tx)
298    }
299
300    /// `build_router` must recognise both proof-of-life methods.
301    #[tokio::test]
302    async fn run_stdio_router_recognises_proof_of_life_methods() {
303        let project = tempfile::tempdir().expect("project tempdir");
304        let data_dir = tempfile::tempdir().expect("data tempdir");
305        let (router, _sessions, _workstreams) = build_router_at(
306            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
307            data_dir.path(),
308        )
309        .await
310        .expect("build_router_at");
311        for method in ["ping", "health"] {
312            let req = Request {
313                jsonrpc: Some("2.0".to_string()),
314                id: Some(json!(1)),
315                method: method.to_string(),
316                params: None,
317            };
318            let resp = router.dispatch(req, &test_ctx()).await;
319            assert!(
320                resp.error.is_none(),
321                "{method} must be registered, got {:?}",
322                resp.error
323            );
324        }
325    }
326
327    /// `build_router` must also wire every `session.*` method (#2054),
328    /// sharing the registry it returns.
329    #[tokio::test]
330    async fn build_router_wires_session_methods() {
331        let project = tempfile::tempdir().expect("project tempdir");
332        let data_dir = tempfile::tempdir().expect("data tempdir");
333        let (router, sessions, _workstreams) = build_router_at(
334            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
335            data_dir.path(),
336        )
337        .await
338        .expect("build_router_at");
339        let session = sessions.create("t".to_string(), None, crate::binding::ProjectBinding::None);
340
341        let req = Request {
342            jsonrpc: Some("2.0".to_string()),
343            id: Some(json!(1)),
344            method: "session.status".to_string(),
345            params: Some(json!({"session_id": session.id})),
346        };
347        let resp = router.dispatch(req, &test_ctx()).await;
348        assert!(
349            resp.error.is_none(),
350            "session.status must be registered, got {:?}",
351            resp.error
352        );
353        assert_eq!(resp.result.unwrap()["id"], session.id);
354    }
355
356    /// `build_router` must also wire `fs.list_dir` (UI Phase-1), so the UI's
357    /// project picker is reachable over the same `/rpc` endpoint as everything
358    /// else.
359    #[tokio::test]
360    async fn build_router_wires_fs_list_dir() {
361        let project = tempfile::tempdir().expect("project tempdir");
362        let data_dir = tempfile::tempdir().expect("data tempdir");
363        let (router, _sessions, _workstreams) = build_router_at(
364            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
365            data_dir.path(),
366        )
367        .await
368        .expect("build_router_at");
369
370        let req = Request {
371            jsonrpc: Some("2.0".to_string()),
372            id: Some(json!(1)),
373            method: "fs.list_dir".to_string(),
374            params: Some(json!({"path": project.path().display().to_string()})),
375        };
376        let resp = router.dispatch(req, &test_ctx()).await;
377        assert!(
378            resp.error.is_none(),
379            "fs.list_dir must be registered, got {:?}",
380            resp.error
381        );
382        assert!(resp.result.expect("result")["entries"].is_array());
383    }
384
385    /// `build_router` must also wire `agents.list`/`skills.list` (issue
386    /// #3449), so the Foundry GUI's Agents/Skills tabs are reachable over
387    /// the same `/rpc` endpoint as everything else.
388    #[tokio::test]
389    async fn build_router_wires_agents_and_skills_catalog_methods() {
390        let project = tempfile::tempdir().expect("project tempdir");
391        let data_dir = tempfile::tempdir().expect("data tempdir");
392        let (router, _sessions, _workstreams) = build_router_at(
393            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
394            data_dir.path(),
395        )
396        .await
397        .expect("build_router_at");
398
399        for method in ["agents.list", "skills.list"] {
400            let req = Request {
401                jsonrpc: Some("2.0".to_string()),
402                id: Some(json!(1)),
403                method: method.to_string(),
404                params: None,
405            };
406            let resp = router.dispatch(req, &test_ctx()).await;
407            assert!(
408                resp.error.is_none(),
409                "{method} must be registered, got {:?}",
410                resp.error
411            );
412        }
413    }
414
415    /// `DEFAULT_HTTP_PORT` must stay the documented value (7882) so a
416    /// change is a deliberate edit to both the constant and its doc comment,
417    /// not an accidental drift.
418    #[test]
419    fn default_http_port_is_documented_value() {
420        assert_eq!(DEFAULT_HTTP_PORT, 7882);
421    }
422
423    /// Cross-crate port-uniqueness contract (#3364).
424    ///
425    /// Why: `DEFAULT_HTTP_PORT` previously reused `7881`, silently colliding
426    /// with `trusty-mpm`'s supervisor metrics listener (since retired, #6288)
427    /// — the supervisor's generic `/health` masked the collision until a real
428    /// `tcode` route 404'd. This mirrors the `default_port_does_not_collide_
429    /// with_known_siblings` guard already used by `trusty-console` and
430    /// `trusty-review` so a future edit here that reintroduces a collision
431    /// fails this test instead of shipping a crash-loop.
432    /// What: asserts `DEFAULT_HTTP_PORT` is absent from the known-sibling
433    /// ports list.
434    /// Test: this is the test.
435    #[test]
436    fn default_http_port_does_not_collide_with_known_siblings() {
437        // (binary, port, source-of-truth pointer)
438        // #6286: trusty-memory has NO ROW either, for the reason the analyze
439        // note below gives — it serves a Unix socket since ADR-0032, so 7070 is
440        // not reserved by anything.
441        let known_siblings: &[(&str, u16, &str)] = &[
442            (
443                "trusty-search",
444                7878,
445                "trusty-search/src/service/constants.rs::DEFAULT_PORT",
446            ),
447            // #6287: trusty-analyze has NO ROW. It no longer binds a TCP port —
448            // it serves a Unix socket (ADR-0032), so 7879 is not reserved by
449            // anything and listing it would forbid a future daemon from a free
450            // port.
451            (
452                "trusty-mpm",
453                7880,
454                "trusty-mpm/src/core/discovery.rs::DEFAULT_DAEMON_ADDR",
455            ),
456            // #6288: no trusty-mpm-supervisor row. The collision that motivated
457            // this guard (#3364) was against its 7881 listener; the supervisor
458            // now publishes to `~/.trusty-mpm/supervisor-metrics.json` and binds
459            // nothing, so 7881 is free and a guard naming it would refuse a
460            // value nothing holds.
461            (
462                "trusty-console",
463                7788,
464                "trusty-console/src/lib.rs::DEFAULT_PORT",
465            ),
466            (
467                "trusty-embedderd",
468                7890,
469                "trusty-embedderd/src/lib.rs::Args::http_addr (--http default_value, manual/dev-run only)",
470            ),
471            // #6277: no trusty-review row. It serves a Unix socket rather
472            // than a TCP port (ADR-0032), so 7891 is free.
473            (
474                "trusty-agents",
475                8080,
476                "trusty-agents/src/runtime/mode_dispatch.rs (--port default 8080)",
477            ),
478        ];
479        for (binary, port, source) in known_siblings {
480            assert_ne!(
481                DEFAULT_HTTP_PORT, *port,
482                "trusty-code DEFAULT_HTTP_PORT {DEFAULT_HTTP_PORT} collides with {binary}'s {port} ({source})"
483            );
484        }
485    }
486
487    /// The daemon must ASSEMBLE with no project bound — `build_router` took a
488    /// required `PathBuf` before, so a projectless daemon could not exist and
489    /// the shell had no entry state to render. `task.run` must be wired just
490    /// the same in that state.
491    #[tokio::test]
492    async fn build_router_is_projectless_without_a_project() {
493        let data_dir = tempfile::tempdir().expect("data tempdir");
494        let (router, _sessions, _workstreams) =
495            build_router_at(ProjectBinding::None, data_dir.path())
496                .await
497                .expect("build_router_at");
498        for method in ["task.run", "session.create", "session.list"] {
499            let req = Request {
500                jsonrpc: Some("2.0".to_string()),
501                id: Some(json!(1)),
502                method: method.to_string(),
503                params: Some(json!({})),
504            };
505            let resp = router.dispatch(req, &test_ctx()).await;
506            // Params are deliberately empty, so an `invalid_params`/
507            // `invalid_argument` is fine and expected — the ONE thing that must
508            // not happen is `-32601 Method not found`, which would mean a
509            // projectless daemon serves a different method surface.
510            if let Some(err) = resp.error {
511                assert_ne!(
512                    err.code, -32601,
513                    "{method} must be wired on a projectless daemon, got method-not-found"
514                );
515            }
516        }
517    }
518
519    #[tokio::test]
520    async fn build_router_wires_task_run() {
521        let project = tempfile::tempdir().expect("project tempdir");
522        std::fs::create_dir_all(project.path().join(".claude").join("agents")).expect("mkdir");
523        std::fs::write(
524            project.path().join(".claude").join("agents").join("pm.md"),
525            "---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nPM\n",
526        )
527        .expect("write pm.md");
528        std::fs::write(
529            project
530                .path()
531                .join(".claude")
532                .join("agents")
533                .join("python-engineer.md"),
534            "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\neng\n",
535        )
536        .expect("write python-engineer.md");
537
538        // SAFETY: test-only env mutation; serialized by the shared crate lock.
539        let _guard = crate::task::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
540        unsafe {
541            std::env::set_var(
542                crate::task::mock_llm::MOCK_LLM_ENV,
543                crate::task::mock_llm::MOCK_LLM_ECHO,
544            );
545        }
546        let data_dir = tempfile::tempdir().expect("data tempdir");
547        let (router, sessions, _workstreams) = build_router_at(
548            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
549            data_dir.path(),
550        )
551        .await
552        .expect("build_router_at");
553        let req = Request {
554            jsonrpc: Some("2.0".to_string()),
555            id: Some(json!(1)),
556            method: "task.run".to_string(),
557            params: Some(json!({"task_description": "say hi"})),
558        };
559        let resp = router.dispatch(req, &test_ctx()).await;
560        sessions
561            .shutdown_executions(std::time::Duration::from_secs(5))
562            .await;
563        unsafe {
564            std::env::remove_var(crate::task::mock_llm::MOCK_LLM_ENV);
565        }
566
567        assert!(
568            resp.error.is_none(),
569            "task.run must be registered, got {:?}",
570            resp.error
571        );
572        assert_eq!(resp.result.unwrap()["status"], "running");
573    }
574
575    /// `build_router` must also wire `workstream.activate`/
576    /// `workstream.deactivate` (DOC-48 §6, issue #3294), and the activation
577    /// pointer they write must be the SAME store a fresh `build_router_at`
578    /// call over the same `data_dir`/`binding` reloads (AC-1.4 boot
579    /// restoration, exercised end-to-end through the daemon's own assembly
580    /// path rather than `workstreams::protocol_tests`' narrower unit tests).
581    #[tokio::test]
582    async fn build_router_wires_workstream_methods() {
583        let project = tempfile::tempdir().expect("project tempdir");
584        let data_dir = tempfile::tempdir().expect("data tempdir");
585        let binding =
586            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");
587
588        let (router, _sessions, _workstreams) = build_router_at(binding.clone(), data_dir.path())
589            .await
590            .expect("build_router_at");
591
592        let create_req = Request {
593            jsonrpc: Some("2.0".to_string()),
594            id: Some(json!(1)),
595            method: "workstream.activate".to_string(),
596            params: Some(json!({"id": crate::workstreams::WorkstreamId::new().to_string()})),
597        };
598        // An id minted here names no existing workstream, so this must map
599        // to `-32002 not_found`, NOT `-32601 method not found` — the point
600        // of this assertion is that the method is REGISTERED, not that this
601        // particular call succeeds (there is no `workstream.create` to seed
602        // one with yet — that is #3295's surface).
603        let resp = router.dispatch(create_req, &test_ctx()).await;
604        let err = resp
605            .error
606            .expect("activating an unknown id must fail, not silently succeed");
607        assert_eq!(err.code, -32002, "workstream.activate must be registered");
608
609        let deactivate_req = Request {
610            jsonrpc: Some("2.0".to_string()),
611            id: Some(json!(2)),
612            method: "workstream.deactivate".to_string(),
613            params: Some(json!({"id": crate::workstreams::WorkstreamId::new().to_string()})),
614        };
615        // Deactivating an unknown id is an idempotent no-op (DOC-48 §4.3),
616        // so this must succeed — proving `workstream.deactivate` is wired
617        // too.
618        let resp = router.dispatch(deactivate_req, &test_ctx()).await;
619        assert!(
620            resp.error.is_none(),
621            "workstream.deactivate must be registered, got {:?}",
622            resp.error
623        );
624
625        // Boot restoration (AC-1.4): a fresh `build_router_at` over the SAME
626        // data_dir/binding must load the store this instance persisted to,
627        // rather than starting from a brand-new empty one — proven here by
628        // reconciliation completing without error on the same file the
629        // first instance created.
630        let (_router2, _sessions2, _workstreams2) = build_router_at(binding, data_dir.path())
631            .await
632            .expect("a second build_router_at over the same data_dir must succeed");
633    }
634
635    /// Boot reconciliation (DOC-48 §3.3, AC-1.4/AC-6.1/AC-6.2) must run
636    /// through the REAL daemon assembly path, not just
637    /// `WorkstreamStore::reconcile_on_boot` called directly (already covered
638    /// by `workstreams::store::store_tests::reconcile_clears_active_when_target_missing`).
639    /// A store file seeded on disk with a DANGLING `active_workstream_id`
640    /// (pointing at a workstream absent from `workstreams[]` — e.g. deleted
641    /// out from under the pointer, or hand-edited) must have that pointer
642    /// cleared by `build_router_at`'s `reconcile_on_boot()` call BEFORE the
643    /// router ever answers a request; `workstream.list` reporting
644    /// `active_workstream_id: null` is the end-to-end proof.
645    #[tokio::test]
646    async fn build_router_reconciles_dangling_active_pointer_on_boot() {
647        let project = tempfile::tempdir().expect("project tempdir");
648        let data_dir = tempfile::tempdir().expect("data tempdir");
649        let binding =
650            ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");
651
652        let store_path = crate::workstreams::store_path(data_dir.path(), &binding);
653        let dangling_id = crate::workstreams::WorkstreamId::new();
654        let raw = json!({
655            "version": "1.0",
656            "active_workstream_id": dangling_id,
657            "workstreams": [],
658        });
659        tokio::fs::create_dir_all(data_dir.path())
660            .await
661            .expect("mkdir data_dir");
662        tokio::fs::write(&store_path, serde_json::to_string_pretty(&raw).unwrap())
663            .await
664            .expect("seed raw store file with a dangling active_workstream_id");
665
666        let (router, _sessions, _workstreams) = build_router_at(binding, data_dir.path())
667            .await
668            .expect("build_router_at must reconcile the dangling pointer, not fail");
669
670        let req = Request {
671            jsonrpc: Some("2.0".to_string()),
672            id: Some(json!(1)),
673            method: "workstream.list".to_string(),
674            params: Some(json!({})),
675        };
676        let resp = router.dispatch(req, &test_ctx()).await;
677        assert!(
678            resp.error.is_none(),
679            "workstream.list must succeed, got {:?}",
680            resp.error
681        );
682        assert_eq!(
683            resp.result.unwrap()["active_workstream_id"],
684            Value::Null,
685            "boot reconciliation through build_router_at must clear a dangling \
686             active_workstream_id before the router answers requests"
687        );
688    }
689}