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 workstream_store
192 .reconcile_on_boot()
193 .await
194 .context("reconciling workstream store on boot")?;
195 let workstreams = Arc::new(Mutex::new(workstream_store));
196
197 let mut router = Router::new();
198 // #4512: `health` publishes the binding, so a client that auto-attaches
199 // to a daemon it did not start can tell which project it would drive.
200 methods::register(&mut router, binding.clone());
201 crate::session::protocol::register(&mut router, sessions.clone(), workstreams.clone());
202 crate::fs_browse::protocol::register(&mut router);
203 crate::agents::protocol::register(
204 &mut router,
205 crate::agents::protocol::AgentsCatalogState::new(agents_dir.clone(), binding.is_bound()),
206 );
207 crate::skills::protocol::register(
208 &mut router,
209 crate::skills::protocol::SkillsCatalogState::new(binding.root()),
210 );
211 crate::task::protocol::register(
212 &mut router,
213 sessions.clone(),
214 binding,
215 agents_dir,
216 workstreams.clone(),
217 );
218 crate::workstreams::protocol::register(&mut router, workstreams.clone());
219 Ok((router, sessions, workstreams))
220}
221
222/// Run `tcode serve --stdio` to completion.
223///
224/// Why: the top-level entry point `main.rs` calls for the `serve --stdio`
225/// subcommand.
226/// What: builds the router, logs start/stop to stderr, and enters
227/// [`transport::run_stdio_loop`], returning when it returns (stdin EOF or
228/// SIGTERM/SIGINT). On return, calls `SessionRegistry::shutdown_executions`
229/// (bounded by [`SHUTDOWN_GRACE`]) so an in-flight `task.run` gets a chance
230/// to unwind before the process exits.
231/// Test: `run_stdio_router_recognises_proof_of_life_methods` covers the
232/// router assembly; the transport loop itself is covered by
233/// `transport::tests`.
234pub async fn run_stdio(binding: ProjectBinding) -> Result<()> {
235 info!(
236 binding = binding.state(),
237 project = binding.label().unwrap_or_else(|| "<projectless>".into()),
238 "tcode serve --stdio: starting"
239 );
240 let (router, sessions, _workstreams) = build_router(binding).await?;
241 transport::run_stdio_loop(router).await?;
242 sessions.shutdown_executions(SHUTDOWN_GRACE).await;
243 info!("tcode serve --stdio: stopped");
244 Ok(())
245}
246
247/// Run `tcode serve --http` to completion.
248///
249/// Why: the top-level entry point `main.rs` calls for the `serve --http`
250/// subcommand.
251/// What: builds the router + session registry, logs start/stop to stderr,
252/// and enters [`http::run_http`] bound to `port` (`0` = OS-assigned
253/// ephemeral port), returning when it returns (SIGTERM/SIGINT). On return,
254/// calls `SessionRegistry::shutdown_executions` (bounded by
255/// [`SHUTDOWN_GRACE`]) — see [`run_stdio`]'s docs for why.
256/// Test: `run_stdio_router_recognises_proof_of_life_methods` covers the
257/// shared router assembly; `http::tests` cover the routing/dispatch logic.
258pub async fn run_http(binding: ProjectBinding, port: u16) -> Result<()> {
259 info!(
260 binding = binding.state(),
261 project = binding.label().unwrap_or_else(|| "<projectless>".into()),
262 port,
263 "tcode serve --http: starting"
264 );
265 // #4512: `GET /health` reports this binding, so keep a handle before
266 // `build_router` consumes it.
267 let published_binding = Arc::new(binding.clone());
268 let (router, sessions, workstreams) = build_router(binding).await?;
269 http::run_http(
270 router,
271 sessions.clone(),
272 workstreams,
273 port,
274 published_binding,
275 )
276 .await?;
277 sessions.shutdown_executions(SHUTDOWN_GRACE).await;
278 info!("tcode serve --http: stopped");
279 Ok(())
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use serde_json::{Value, json};
286 use trusty_mcp::Request;
287
288 fn test_ctx() -> crate::jsonrpc::ConnectionContext {
289 let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
290 crate::jsonrpc::ConnectionContext::new(tx)
291 }
292
293 /// `build_router` must recognise both proof-of-life methods.
294 #[tokio::test]
295 async fn run_stdio_router_recognises_proof_of_life_methods() {
296 let project = tempfile::tempdir().expect("project tempdir");
297 let data_dir = tempfile::tempdir().expect("data tempdir");
298 let (router, _sessions, _workstreams) = build_router_at(
299 ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
300 data_dir.path(),
301 )
302 .await
303 .expect("build_router_at");
304 for method in ["ping", "health"] {
305 let req = Request {
306 jsonrpc: Some("2.0".to_string()),
307 id: Some(json!(1)),
308 method: method.to_string(),
309 params: None,
310 };
311 let resp = router.dispatch(req, &test_ctx()).await;
312 assert!(
313 resp.error.is_none(),
314 "{method} must be registered, got {:?}",
315 resp.error
316 );
317 }
318 }
319
320 /// `build_router` must also wire every `session.*` method (#2054),
321 /// sharing the registry it returns.
322 #[tokio::test]
323 async fn build_router_wires_session_methods() {
324 let project = tempfile::tempdir().expect("project tempdir");
325 let data_dir = tempfile::tempdir().expect("data tempdir");
326 let (router, sessions, _workstreams) = build_router_at(
327 ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
328 data_dir.path(),
329 )
330 .await
331 .expect("build_router_at");
332 let session = sessions.create("t".to_string(), None, crate::binding::ProjectBinding::None);
333
334 let req = Request {
335 jsonrpc: Some("2.0".to_string()),
336 id: Some(json!(1)),
337 method: "session.status".to_string(),
338 params: Some(json!({"session_id": session.id})),
339 };
340 let resp = router.dispatch(req, &test_ctx()).await;
341 assert!(
342 resp.error.is_none(),
343 "session.status must be registered, got {:?}",
344 resp.error
345 );
346 assert_eq!(resp.result.unwrap()["id"], session.id);
347 }
348
349 /// `build_router` must also wire `fs.list_dir` (UI Phase-1), so the UI's
350 /// project picker is reachable over the same `/rpc` endpoint as everything
351 /// else.
352 #[tokio::test]
353 async fn build_router_wires_fs_list_dir() {
354 let project = tempfile::tempdir().expect("project tempdir");
355 let data_dir = tempfile::tempdir().expect("data tempdir");
356 let (router, _sessions, _workstreams) = build_router_at(
357 ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
358 data_dir.path(),
359 )
360 .await
361 .expect("build_router_at");
362
363 let req = Request {
364 jsonrpc: Some("2.0".to_string()),
365 id: Some(json!(1)),
366 method: "fs.list_dir".to_string(),
367 params: Some(json!({"path": project.path().display().to_string()})),
368 };
369 let resp = router.dispatch(req, &test_ctx()).await;
370 assert!(
371 resp.error.is_none(),
372 "fs.list_dir must be registered, got {:?}",
373 resp.error
374 );
375 assert!(resp.result.expect("result")["entries"].is_array());
376 }
377
378 /// `build_router` must also wire `agents.list`/`skills.list` (issue
379 /// #3449), so the Foundry GUI's Agents/Skills tabs are reachable over
380 /// the same `/rpc` endpoint as everything else.
381 #[tokio::test]
382 async fn build_router_wires_agents_and_skills_catalog_methods() {
383 let project = tempfile::tempdir().expect("project tempdir");
384 let data_dir = tempfile::tempdir().expect("data tempdir");
385 let (router, _sessions, _workstreams) = build_router_at(
386 ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
387 data_dir.path(),
388 )
389 .await
390 .expect("build_router_at");
391
392 for method in ["agents.list", "skills.list"] {
393 let req = Request {
394 jsonrpc: Some("2.0".to_string()),
395 id: Some(json!(1)),
396 method: method.to_string(),
397 params: None,
398 };
399 let resp = router.dispatch(req, &test_ctx()).await;
400 assert!(
401 resp.error.is_none(),
402 "{method} must be registered, got {:?}",
403 resp.error
404 );
405 }
406 }
407
408 /// `DEFAULT_HTTP_PORT` must stay the documented value (7882) so a
409 /// change is a deliberate edit to both the constant and its doc comment,
410 /// not an accidental drift.
411 #[test]
412 fn default_http_port_is_documented_value() {
413 assert_eq!(DEFAULT_HTTP_PORT, 7882);
414 }
415
416 /// Cross-crate port-uniqueness contract (#3364).
417 ///
418 /// Why: `DEFAULT_HTTP_PORT` previously reused `7881`, silently colliding
419 /// with `trusty-mpm`'s supervisor metrics listener (since retired, #6288)
420 /// — the supervisor's generic `/health` masked the collision until a real
421 /// `tcode` route 404'd. This mirrors the `default_port_does_not_collide_
422 /// with_known_siblings` guard already used by `trusty-console` and
423 /// `trusty-review` so a future edit here that reintroduces a collision
424 /// fails this test instead of shipping a crash-loop.
425 /// What: asserts `DEFAULT_HTTP_PORT` is absent from the known-sibling
426 /// ports list.
427 /// Test: this is the test.
428 #[test]
429 fn default_http_port_does_not_collide_with_known_siblings() {
430 // (binary, port, source-of-truth pointer)
431 // #6286: trusty-memory has NO ROW either, for the reason the analyze
432 // note below gives — it serves a Unix socket since ADR-0032, so 7070 is
433 // not reserved by anything.
434 let known_siblings: &[(&str, u16, &str)] = &[
435 (
436 "trusty-search",
437 7878,
438 "trusty-search/src/service/constants.rs::DEFAULT_PORT",
439 ),
440 // #6287: trusty-analyze has NO ROW. It no longer binds a TCP port —
441 // it serves a Unix socket (ADR-0032), so 7879 is not reserved by
442 // anything and listing it would forbid a future daemon from a free
443 // port.
444 (
445 "trusty-mpm",
446 7880,
447 "trusty-mpm/src/core/discovery.rs::DEFAULT_DAEMON_ADDR",
448 ),
449 // #6288: no trusty-mpm-supervisor row. The collision that motivated
450 // this guard (#3364) was against its 7881 listener; the supervisor
451 // now publishes to `~/.trusty-mpm/supervisor-metrics.json` and binds
452 // nothing, so 7881 is free and a guard naming it would refuse a
453 // value nothing holds.
454 (
455 "trusty-console",
456 7788,
457 "trusty-console/src/lib.rs::DEFAULT_PORT",
458 ),
459 (
460 "trusty-embedderd",
461 7890,
462 "trusty-embedderd/src/lib.rs::Args::http_addr (--http default_value, manual/dev-run only)",
463 ),
464 // #6277: no trusty-review row. It serves a Unix socket rather
465 // than a TCP port (ADR-0032), so 7891 is free.
466 (
467 "trusty-agents",
468 8080,
469 "trusty-agents/src/runtime/mode_dispatch.rs (--port default 8080)",
470 ),
471 ];
472 for (binary, port, source) in known_siblings {
473 assert_ne!(
474 DEFAULT_HTTP_PORT, *port,
475 "trusty-code DEFAULT_HTTP_PORT {DEFAULT_HTTP_PORT} collides with {binary}'s {port} ({source})"
476 );
477 }
478 }
479
480 /// The daemon must ASSEMBLE with no project bound — `build_router` took a
481 /// required `PathBuf` before, so a projectless daemon could not exist and
482 /// the shell had no entry state to render. `task.run` must be wired just
483 /// the same in that state.
484 #[tokio::test]
485 async fn build_router_is_projectless_without_a_project() {
486 let data_dir = tempfile::tempdir().expect("data tempdir");
487 let (router, _sessions, _workstreams) =
488 build_router_at(ProjectBinding::None, data_dir.path())
489 .await
490 .expect("build_router_at");
491 for method in ["task.run", "session.create", "session.list"] {
492 let req = Request {
493 jsonrpc: Some("2.0".to_string()),
494 id: Some(json!(1)),
495 method: method.to_string(),
496 params: Some(json!({})),
497 };
498 let resp = router.dispatch(req, &test_ctx()).await;
499 // Params are deliberately empty, so an `invalid_params`/
500 // `invalid_argument` is fine and expected — the ONE thing that must
501 // not happen is `-32601 Method not found`, which would mean a
502 // projectless daemon serves a different method surface.
503 if let Some(err) = resp.error {
504 assert_ne!(
505 err.code, -32601,
506 "{method} must be wired on a projectless daemon, got method-not-found"
507 );
508 }
509 }
510 }
511
512 #[tokio::test]
513 async fn build_router_wires_task_run() {
514 let project = tempfile::tempdir().expect("project tempdir");
515 std::fs::create_dir_all(project.path().join(".claude").join("agents")).expect("mkdir");
516 std::fs::write(
517 project.path().join(".claude").join("agents").join("pm.md"),
518 "---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nPM\n",
519 )
520 .expect("write pm.md");
521 std::fs::write(
522 project
523 .path()
524 .join(".claude")
525 .join("agents")
526 .join("python-engineer.md"),
527 "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\neng\n",
528 )
529 .expect("write python-engineer.md");
530
531 // SAFETY: test-only env mutation; serialized by the shared crate lock.
532 let _guard = crate::task::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
533 unsafe {
534 std::env::set_var(
535 crate::task::mock_llm::MOCK_LLM_ENV,
536 crate::task::mock_llm::MOCK_LLM_ECHO,
537 );
538 }
539 let data_dir = tempfile::tempdir().expect("data tempdir");
540 let (router, sessions, _workstreams) = build_router_at(
541 ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind"),
542 data_dir.path(),
543 )
544 .await
545 .expect("build_router_at");
546 let req = Request {
547 jsonrpc: Some("2.0".to_string()),
548 id: Some(json!(1)),
549 method: "task.run".to_string(),
550 params: Some(json!({"task_description": "say hi"})),
551 };
552 let resp = router.dispatch(req, &test_ctx()).await;
553 sessions
554 .shutdown_executions(std::time::Duration::from_secs(5))
555 .await;
556 unsafe {
557 std::env::remove_var(crate::task::mock_llm::MOCK_LLM_ENV);
558 }
559
560 assert!(
561 resp.error.is_none(),
562 "task.run must be registered, got {:?}",
563 resp.error
564 );
565 assert_eq!(resp.result.unwrap()["status"], "running");
566 }
567
568 /// `build_router` must also wire `workstream.activate`/
569 /// `workstream.deactivate` (DOC-48 §6, issue #3294), and the activation
570 /// pointer they write must be the SAME store a fresh `build_router_at`
571 /// call over the same `data_dir`/`binding` reloads (AC-1.4 boot
572 /// restoration, exercised end-to-end through the daemon's own assembly
573 /// path rather than `workstreams::protocol_tests`' narrower unit tests).
574 #[tokio::test]
575 async fn build_router_wires_workstream_methods() {
576 let project = tempfile::tempdir().expect("project tempdir");
577 let data_dir = tempfile::tempdir().expect("data tempdir");
578 let binding =
579 ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");
580
581 let (router, _sessions, _workstreams) = build_router_at(binding.clone(), data_dir.path())
582 .await
583 .expect("build_router_at");
584
585 let create_req = Request {
586 jsonrpc: Some("2.0".to_string()),
587 id: Some(json!(1)),
588 method: "workstream.activate".to_string(),
589 params: Some(json!({"id": crate::workstreams::WorkstreamId::new().to_string()})),
590 };
591 // An id minted here names no existing workstream, so this must map
592 // to `-32002 not_found`, NOT `-32601 method not found` — the point
593 // of this assertion is that the method is REGISTERED, not that this
594 // particular call succeeds (there is no `workstream.create` to seed
595 // one with yet — that is #3295's surface).
596 let resp = router.dispatch(create_req, &test_ctx()).await;
597 let err = resp
598 .error
599 .expect("activating an unknown id must fail, not silently succeed");
600 assert_eq!(err.code, -32002, "workstream.activate must be registered");
601
602 let deactivate_req = Request {
603 jsonrpc: Some("2.0".to_string()),
604 id: Some(json!(2)),
605 method: "workstream.deactivate".to_string(),
606 params: Some(json!({"id": crate::workstreams::WorkstreamId::new().to_string()})),
607 };
608 // Deactivating an unknown id is an idempotent no-op (DOC-48 §4.3),
609 // so this must succeed — proving `workstream.deactivate` is wired
610 // too.
611 let resp = router.dispatch(deactivate_req, &test_ctx()).await;
612 assert!(
613 resp.error.is_none(),
614 "workstream.deactivate must be registered, got {:?}",
615 resp.error
616 );
617
618 // Boot restoration (AC-1.4): a fresh `build_router_at` over the SAME
619 // data_dir/binding must load the store this instance persisted to,
620 // rather than starting from a brand-new empty one — proven here by
621 // reconciliation completing without error on the same file the
622 // first instance created.
623 let (_router2, _sessions2, _workstreams2) = build_router_at(binding, data_dir.path())
624 .await
625 .expect("a second build_router_at over the same data_dir must succeed");
626 }
627
628 /// Boot reconciliation (DOC-48 §3.3, AC-1.4/AC-6.1/AC-6.2) must run
629 /// through the REAL daemon assembly path, not just
630 /// `WorkstreamStore::reconcile_on_boot` called directly (already covered
631 /// by `workstreams::store::store_tests::reconcile_clears_active_when_target_missing`).
632 /// A store file seeded on disk with a DANGLING `active_workstream_id`
633 /// (pointing at a workstream absent from `workstreams[]` — e.g. deleted
634 /// out from under the pointer, or hand-edited) must have that pointer
635 /// cleared by `build_router_at`'s `reconcile_on_boot()` call BEFORE the
636 /// router ever answers a request; `workstream.list` reporting
637 /// `active_workstream_id: null` is the end-to-end proof.
638 #[tokio::test]
639 async fn build_router_reconciles_dangling_active_pointer_on_boot() {
640 let project = tempfile::tempdir().expect("project tempdir");
641 let data_dir = tempfile::tempdir().expect("data tempdir");
642 let binding =
643 ProjectBinding::resolve(Some(project.path().to_path_buf())).expect("tempdir must bind");
644
645 let store_path = crate::workstreams::store_path(data_dir.path(), &binding);
646 let dangling_id = crate::workstreams::WorkstreamId::new();
647 let raw = json!({
648 "version": "1.0",
649 "active_workstream_id": dangling_id,
650 "workstreams": [],
651 });
652 tokio::fs::create_dir_all(data_dir.path())
653 .await
654 .expect("mkdir data_dir");
655 tokio::fs::write(&store_path, serde_json::to_string_pretty(&raw).unwrap())
656 .await
657 .expect("seed raw store file with a dangling active_workstream_id");
658
659 let (router, _sessions, _workstreams) = build_router_at(binding, data_dir.path())
660 .await
661 .expect("build_router_at must reconcile the dangling pointer, not fail");
662
663 let req = Request {
664 jsonrpc: Some("2.0".to_string()),
665 id: Some(json!(1)),
666 method: "workstream.list".to_string(),
667 params: Some(json!({})),
668 };
669 let resp = router.dispatch(req, &test_ctx()).await;
670 assert!(
671 resp.error.is_none(),
672 "workstream.list must succeed, got {:?}",
673 resp.error
674 );
675 assert_eq!(
676 resp.result.unwrap()["active_workstream_id"],
677 Value::Null,
678 "boot reconciliation through build_router_at must clear a dangling \
679 active_workstream_id before the router answers requests"
680 );
681 }
682}