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