trusty_memory/lib.rs
1//! MCP server (HTTP/SSE + stdio) for trusty-memory.
2//!
3//! Why: Claude Code and other MCP-aware clients integrate with trusty-memory
4//! through the standardized Model Context Protocol; we expose memory + KG
5//! tools so they can be called by name. The canonical stdio integration is
6//! `trusty-memory serve --stdio` (PR1 #919 of the #914 cutover epic), a
7//! self-contained direct MCP server that binds no HTTP port or UDS socket.
8//! The former `trusty-memory-mcp-bridge` binary and Unix-domain-socket
9//! transport were removed in PR3 (#914) once `serve --stdio` made them dead
10//! code.
11//! What: Provides `run_http` / `run_http_dynamic` / `run_http_on` (axum
12//! HTTP/SSE + REST + UI) plus an `AppState` that carries the shared
13//! `PalaceRegistry`, on-disk data root, and a lazily-initialized embedder.
14//! Test: `cargo test -p trusty-memory` validates handshake + dispatch via
15//! the in-process `handle_message` unit tests and the
16//! `tests/serve_stdio_e2e.rs` end-to-end harness.
17
18use anyhow::Result;
19use serde_json::{json, Value};
20use std::net::SocketAddr;
21use std::path::{Path, PathBuf};
22use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
23use std::sync::{Arc, OnceLock};
24use tokio::sync::{broadcast, OnceCell, RwLock};
25use trusty_common::bm25_client::Bm25Client;
26use trusty_common::mcp::initialize_response;
27use trusty_common::memory_core::embed::FastEmbedder;
28use trusty_common::memory_core::{store::ChatSessionStore, PalaceRegistry};
29use trusty_common::ChatProvider;
30
31// Why: `tracing::info` is only used by the axum HTTP-serving helpers
32// (`run_http_on`, `spawn_uds_listener`). Pulling it in unconditionally
33// would trigger `unused_imports` warnings when the `axum-server`
34// feature is disabled. `SocketAddr` is still used by `bound_addr` on
35// `AppState` so it stays unconditional.
36#[cfg(feature = "axum-server")]
37use tracing::info;
38
39/// Two-phase daemon readiness state (issues #910/#911, revised by #1970).
40///
41/// Why: The embedder cold-init (CoreML compile, 30-120 s) must never block
42/// the fast text/KG/BM25 paths that don't need it. Originally (#910/#911)
43/// this state gated a hard-error preflight that rejected every
44/// `memory_remember`/`memory_recall` call outright while `Warming` — mirrored
45/// from trusty-search's staged pipeline, #1970 replaced that with graceful
46/// degradation: writes persist immediately and defer embedding to a
47/// background task, reads return BM25 + L0/L1 results and simply omit the
48/// vector lane, all keyed off this same state.
49/// What: Two stable values stored atomically. `Warming` (0) is the initial
50/// state; `Ready` (1) is set once the embedder has been successfully
51/// initialised by `spawn_startup_tasks`. The transition is one-way and
52/// lock-free: a single `AtomicU8` compare-and-swap.
53/// Test: `daemon_readiness_transitions_warming_to_ready` in this module;
54/// degraded-path coverage in `tools::tests`
55/// (`remember_succeeds_and_defers_embedding_while_state_is_warming`,
56/// `recall_falls_back_to_bm25_and_l0_l1_while_warming`).
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum DaemonReadiness {
59 /// Embedder cold-init (and/or pin scan) still in progress.
60 Warming = 0,
61 /// Embedder initialised; all handlers may proceed normally.
62 Ready = 1,
63}
64
65impl DaemonReadiness {
66 /// Decode the raw atomic value.
67 ///
68 /// Why: centralises the `0 → Warming, else Ready` mapping so every
69 /// caller loads a meaningful enum rather than comparing raw integers.
70 /// What: returns `Warming` for `0`, `Ready` for any other value (only
71 /// `1` is ever written).
72 /// Test: `daemon_readiness_from_u8` in this module.
73 pub fn from_u8(v: u8) -> Self {
74 if v == 0 {
75 Self::Warming
76 } else {
77 Self::Ready
78 }
79 }
80}
81
82pub mod activity;
83pub mod attribution;
84pub mod authz;
85pub mod bm25_supervisor;
86pub mod bootstrap;
87/// Autonomous Dreamer scheduler — spawns per-palace dream loops on daemon startup.
88///
89/// Why: issue #1529 — `Dreamer::start_with_shutdown()` was fully implemented
90/// but never called. This module wires it into the daemon so each palace gets
91/// a background dream loop that fires every 5 minutes of idle time.
92/// What: exports `spawn_dream_scheduler`, `make_shutdown_watch`, and
93/// `spawn_shutdown_bridge`. Disable with `TRUSTY_DREAM_DISABLED=1`.
94/// Test: see unit tests inside this module.
95pub mod dream_scheduler;
96/// File-descriptor usage and limit reporting for `/health`.
97///
98/// Why: expose `open_fds` / `fd_soft_limit` so operators can see the fd
99/// ceiling and current consumption without needing lsof or shell access.
100/// Test: `fd_metrics::tests::fd_metrics_returns_sane_values`.
101pub mod fd_metrics;
102// Why (issue #226): `chat` and `web` are pure axum HTTP/SSE handler
103// surfaces. Gating them behind the `axum-server` feature is what lets
104// library consumers (e.g. `open-mpm` linking only `MemoryMcpService`)
105// drop axum + tower-http entirely from their build graph.
106#[cfg(feature = "axum-server")]
107pub mod chat;
108pub mod commands;
109pub mod console_metrics;
110pub mod discovery;
111/// Supervised `serve --foreground` entry point (issue #787).
112///
113/// Why: launchd supervisors need loud failure on port collision, not silent
114/// port-walking to 7071+. Extracted to stay under the 500-line ratchet cap.
115/// What: exports `bind_foreground_port` (Fix C — abort on EADDRINUSE) and
116/// `run_http_foreground` (Fix A lock + Fix B http_addr + Fix C combined).
117/// Test: `foreground::tests::bind_foreground_port_refuses_collision`;
118/// `daemon_lock` module tests cover the lock-file logic.
119pub mod foreground;
120pub mod hook_emit;
121pub mod kg_extract;
122pub mod mcp_service;
123pub mod messaging;
124pub mod openrpc;
125/// Issue #1217: default palace-ID derivation from project identity.
126///
127/// Why: the default palace ID should reflect the project's identity
128/// (git `owner/repo`, else `parent/dir`) rather than the bare directory
129/// basename, so the same repo resolves to the same palace across checkouts.
130/// What: exports the pure `derive_palace_id` core plus
131/// `owner_repo_from_git_remote`, `parent_dir_slug`, and the
132/// `TRUSTY_MEMORY_PALACE` env-override helpers.
133/// Test: see unit tests inside this module.
134pub mod palace_id_derive;
135/// Issue #88: project-root detection and palace-slug enforcement.
136///
137/// Why: prevents unbounded palace creation by anchoring palace names to the
138/// canonical slug of the project directory that contains the CWD, or to the
139/// `personal` sentinel for non-project contexts.
140/// What: exports `find_project_root`, `project_slug_at`, `project_slug`,
141/// `validate_palace_name`, `PERSONAL_PALACE`, and `PROJECT_MARKERS`.
142/// Test: see unit tests inside this module.
143pub mod project_root;
144pub mod prompt_facts;
145pub mod prompt_log;
146pub mod service;
147pub mod startup_scan;
148pub mod tools;
149pub mod transport;
150#[cfg(feature = "axum-server")]
151pub mod web;
152
153pub use activity::{ActivityEntry, ActivityFilter, ActivityLog, ActivitySource};
154pub use attribution::{CreatorInfo, CreatorSource};
155
156/// Maximum bytes retained in the trigger-prompt excerpt embedded on a
157/// `HookFired` event.
158///
159/// Why: the full triggering prompt is sensitive and already lives in the
160/// JSONL prompt log; the activity feed only needs enough text to give an
161/// operator a glance — a single-line ~80 char preview matches the existing
162/// `drawer_content_preview` convention so dashboard rows render uniformly.
163/// What: 80 characters; longer prompts are truncated with a trailing `…`.
164/// Test: `hook_excerpt_truncates_long_prompts`.
165pub const HOOK_PROMPT_EXCERPT_CHARS: usize = 80;
166
167/// Reduce a triggering prompt to the short excerpt embedded on a
168/// `HookFired` activity event.
169///
170/// Why: see [`HOOK_PROMPT_EXCERPT_CHARS`]. Centralising the truncation rule
171/// keeps every emitter (HTTP, hook CLI handlers, future tests) producing
172/// the same preview shape so UI rendering is uniform.
173/// What: whitespace-collapses `prompt` and trims to
174/// [`HOOK_PROMPT_EXCERPT_CHARS`] chars with `…` when cut. Empty input
175/// returns an empty string.
176/// Test: `hook_excerpt_truncates_long_prompts`,
177/// `hook_excerpt_collapses_whitespace`.
178pub fn hook_prompt_excerpt(prompt: &str) -> String {
179 let normalised: String = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
180 if normalised.chars().count() <= HOOK_PROMPT_EXCERPT_CHARS {
181 normalised
182 } else {
183 let kept: String = normalised
184 .chars()
185 .take(HOOK_PROMPT_EXCERPT_CHARS.saturating_sub(1))
186 .collect();
187 format!("{kept}…")
188 }
189}
190
191pub use mcp_service::MemoryMcpService;
192pub use tools::MemoryMcpServer;
193
194/// Resolve the directory that actually holds the per-palace subdirectories.
195///
196/// Why: there are two on-disk layouts in the wild. The current monorepo code
197/// treats the registry directory *itself* as the parent of per-palace dirs
198/// (`<dir>/<id>/palace.json`). The legacy standalone `trusty-memory` repo
199/// nested everything one level deeper under a `palaces/` subdirectory
200/// (`<data_dir>/palaces/<id>/palace.json`) — and that is where existing
201/// installs' data lives (e.g. 88 palaces under
202/// `~/Library/Application Support/trusty-memory/palaces/`). A daemon that uses
203/// the bare data dir as its registry root finds zero palaces because every
204/// `palace.json` sits one level below where it looked — the "palaces lost on
205/// restart" bug.
206/// What: given the standard data dir, returns `<data_dir>/palaces` when that
207/// subdirectory exists, otherwise `<data_dir>` itself. Resolving this once in
208/// `main.rs` and using the result as `AppState::data_root` keeps every call
209/// site (`status`, `palace_list`, `open_palace`, `palace_create`,
210/// `load_palaces_from_disk`) consistent without forcing a data migration.
211/// Test: `tests::resolve_palace_registry_dir_prefers_palaces_subdir` and
212/// `resolve_palace_registry_dir_falls_back_to_data_dir`.
213pub fn resolve_palace_registry_dir(data_dir: PathBuf) -> PathBuf {
214 // Issue #1939: the subdir-choice logic is hoisted into trusty-common
215 // (`palace_alias::palace_registry_dir_from`) so trusty-mpm's alias-registration
216 // path and this daemon path can never disagree on WHERE the registry (and the
217 // alias file beside it) lives. This delegates to keep a single implementation.
218 trusty_common::palace_alias::palace_registry_dir_from(data_dir)
219}
220
221/// Hook type — labels the Claude Code hook that triggered a submission.
222///
223/// Why: every hook firing produces an activity-feed entry tagged with the
224/// originating hook so operators can tell whether activity came from a user
225/// prompt (`UserPromptSubmit`), a new session (`SessionStart`), or a future
226/// hook variant. Threading this through `DaemonEvent::HookFired` lets the
227/// dashboard badge each row with the hook label.
228/// What: serde-serialised in PascalCase so the wire format matches Claude
229/// Code's own hook-name strings exactly (e.g. `"UserPromptSubmit"`).
230/// Test: `hook_type_serde_round_trips`.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
232pub enum HookType {
233 /// Claude Code's `UserPromptSubmit` hook — fires on every user prompt.
234 UserPromptSubmit,
235 /// Claude Code's `SessionStart` hook — fires once at session open.
236 SessionStart,
237}
238
239impl HookType {
240 /// Stable string label used for the wire format.
241 pub fn as_str(&self) -> &'static str {
242 match self {
243 Self::UserPromptSubmit => "UserPromptSubmit",
244 Self::SessionStart => "SessionStart",
245 }
246 }
247}
248
249/// Injection kind — labels what the hook actually injected (or attempted).
250///
251/// Why: distinct from `HookType` because one hook could in principle render
252/// more than one kind of injection (e.g. SessionStart can deliver both an
253/// inbox check and bootstrap context). Tagging the rendered kind explicitly
254/// keeps the activity log searchable when that fan-out lands.
255/// What: serde-serialised as kebab-case so it matches the labels already
256/// used in the JSONL prompt log (`prompt-context-facts`,
257/// `inbox-check-messages`).
258/// Test: `injection_kind_serde_round_trips`.
259#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
260#[serde(rename_all = "kebab-case")]
261pub enum InjectionKind {
262 /// `prompt-context` hook rendered the prompt-facts block.
263 PromptContext,
264 /// `inbox-check` hook delivered unread messages.
265 InboxCheck,
266}
267
268impl InjectionKind {
269 /// Stable string label used for the wire format.
270 pub fn as_str(&self) -> &'static str {
271 match self {
272 Self::PromptContext => "prompt-context",
273 Self::InboxCheck => "inbox-check",
274 }
275 }
276}
277
278/// Live daemon events broadcast to connected SSE subscribers.
279///
280/// Why: The dashboard needs push-driven updates so palace creation, drawer
281/// add/delete, dream cycles, and aggregate status changes are visible without
282/// polling. A single broadcast channel fans out to every connected browser.
283/// What: Tagged enum serialized as `{"type": "...", ...fields}` over SSE.
284/// Test: `web::tests::sse_stream_emits_events` subscribes, triggers a
285/// mutation, and asserts the frame arrives.
286#[derive(Clone, Debug, serde::Serialize)]
287#[serde(tag = "type", rename_all = "snake_case")]
288pub enum DaemonEvent {
289 PalaceCreated {
290 id: String,
291 name: String,
292 /// Originating subsystem (HTTP, MCP, Hook). Why (issue #96): the
293 /// UI badges each row with its source so operators can tell at a
294 /// glance whether a write came from the dashboard form, an MCP
295 /// tool call, or a hook-driven path. The wire-format key is
296 /// `source` (lower-case strings via serde rename_all on
297 /// `ActivitySource`).
298 source: ActivitySource,
299 },
300 DrawerAdded {
301 palace_id: String,
302 /// Friendly palace name (Palace.name) at write time. Why: lets SSE
303 /// consumers (the dashboard activity feed) render the human-readable
304 /// label without a separate id→name lookup. Empty string if the
305 /// emitter could not resolve the name.
306 #[serde(default)]
307 palace_name: String,
308 drawer_count: usize,
309 /// Wall-clock timestamp when the drawer was added. Why: SSE
310 /// receivers want to render "just now / 2m ago" relative to the
311 /// daemon's clock, not the time the SSE frame happens to arrive.
312 timestamp: chrono::DateTime<chrono::Utc>,
313 /// Short preview of the drawer's content (whitespace-collapsed,
314 /// truncated to ~80 chars with an ellipsis when cut). Why: the TUI
315 /// activity feed and dashboard ticker want to show *what* was
316 /// stored, not just the running drawer count. Empty when the
317 /// emitter could not resolve the content (legacy clients tolerate
318 /// the missing field via `#[serde(default)]`).
319 #[serde(default)]
320 content_preview: String,
321 /// Originating subsystem (issue #96).
322 source: ActivitySource,
323 },
324 DrawerDeleted {
325 palace_id: String,
326 drawer_count: usize,
327 /// Originating subsystem (issue #96).
328 source: ActivitySource,
329 },
330 DreamCompleted {
331 palace_id: Option<String>,
332 merged: usize,
333 pruned: usize,
334 compacted: usize,
335 closets_updated: usize,
336 duration_ms: u64,
337 /// Originating subsystem (issue #96).
338 source: ActivitySource,
339 },
340 StatusChanged {
341 total_drawers: usize,
342 total_vectors: usize,
343 total_kg_triples: usize,
344 },
345 /// A Claude Code hook completed and rendered (or attempted to render) an
346 /// injection block.
347 ///
348 /// Why: pre-#XXX the activity feed only fired on drawer / palace / dream
349 /// writes, which meant a normal Claude Code session — whose only daemon
350 /// traffic is hook invocations — left the feed empty. Surfacing every
351 /// hook firing answers the user complaint "no activity in the TUI" and
352 /// gives operators a way to see how often each project palace is
353 /// actually picking up prompt-context / inbox-check work.
354 /// What: carries the resolved palace (or `None` if cwd resolution
355 /// failed), the [`HookType`] label, the [`InjectionKind`] label, the
356 /// rendered injection byte length, a short excerpt of the triggering
357 /// prompt (capped at ~80 chars; the full content stays in the JSONL
358 /// prompt log only), the timestamp, the hook's wall-clock duration,
359 /// and the [`ActivitySource`] tag (always `Hook` for this variant).
360 /// Backwards-compatible: SSE clients that do not recognise the
361 /// `hook_fired` `type` tag can safely ignore the frame.
362 HookFired {
363 /// Resolved palace id (slug) — `None` if cwd resolution failed.
364 #[serde(default)]
365 palace_id: Option<String>,
366 /// Friendly palace name at hook time — `None` if the registry
367 /// could not be consulted (HTTP path uses `palace_id` here when
368 /// no separate name is known).
369 #[serde(default)]
370 palace_name: Option<String>,
371 hook_type: HookType,
372 injection_kind: InjectionKind,
373 /// Rendered injection size in bytes (`0` when no injection was
374 /// emitted, e.g. SessionStart with an empty inbox).
375 injection_length: u64,
376 /// Short excerpt of the triggering prompt for the activity feed
377 /// display. Capped at ~80 chars with a trailing `…` when cut.
378 /// Why: the activity feed renders this directly; full prompt
379 /// content (which may be sensitive) stays in the JSONL log.
380 #[serde(default)]
381 trigger_prompt_excerpt: String,
382 timestamp: chrono::DateTime<chrono::Utc>,
383 /// Hook wall-clock duration in milliseconds.
384 duration_ms: u64,
385 /// Always `ActivitySource::Hook` for this variant; encoded explicitly
386 /// so the same dispatch path (`emit`) can persist + broadcast it.
387 source: ActivitySource,
388 },
389}
390
391/// Open the activity log under `data_root`, falling back to a per-process
392/// tempdir and finally to a no-op `Discard` variant when no writable
393/// directory is available.
394///
395/// Why (issues #96, #225): the activity log is a best-effort feature — if
396/// the data root is on a read-only mount, missing, or locked by another
397/// process, the daemon should still come up and serve every other endpoint.
398/// The first fallback is a `std::env::temp_dir()`-anchored subdirectory
399/// keyed by the daemon's process id. Issue #225: a previous version called
400/// `expect()` on the tempdir fallback, which crashed the daemon on hosts
401/// where neither `data_root` nor `std::env::temp_dir()` is writable
402/// (read-only containers, locked-down sandboxes). The contract is
403/// "best-effort", so the final fallback is now `ActivityLog::discard()` —
404/// a no-op variant that drops every append and returns empty reads. The
405/// dashboard's activity feed simply shows up empty in that degraded state.
406/// What: tries `ActivityLog::open(data_root)`; on error logs a warning and
407/// retries against `<temp>/trusty-memory-activity-<pid>/`. If both fail,
408/// emits a final warning and returns `ActivityLog::discard()`.
409/// Test: `open_activity_log_with_fallback_returns_discard_when_unwritable`
410/// covers the discard branch; existing `AppState` construction tests cover
411/// the happy and tempdir-fallback paths.
412fn open_activity_log_with_fallback(data_root: &Path) -> Arc<ActivityLog> {
413 match ActivityLog::open(data_root) {
414 Ok(log) => Arc::new(log),
415 Err(primary_err) => {
416 tracing::warn!(
417 "could not open activity log at {}: {primary_err:#}; falling back to per-process tempdir",
418 data_root.display()
419 );
420 let fallback =
421 std::env::temp_dir().join(format!("trusty-memory-activity-{}", std::process::id()));
422 match ActivityLog::open(&fallback) {
423 Ok(log) => Arc::new(log),
424 Err(fallback_err) => {
425 tracing::warn!(
426 "activity log tempdir fallback at {} also failed: {fallback_err:#}; \
427 activity feed disabled for this process (no-op log)",
428 fallback.display()
429 );
430 Arc::new(ActivityLog::discard())
431 }
432 }
433 }
434 }
435}
436
437impl DaemonEvent {
438 /// Short discriminant label matching the SSE `type` field.
439 ///
440 /// Why: the persisted activity log stores `event_type` as a string so
441 /// the UI can render the row without re-parsing the payload. Sharing
442 /// the same labels the SSE serializer uses keeps the wire and the
443 /// stored history consistent.
444 /// What: returns one of `palace_created`, `drawer_added`,
445 /// `drawer_deleted`, `dream_completed`, `status_changed`.
446 /// Test: `daemon_event_type_str_matches_sse_tag` in the lib tests.
447 pub fn type_str(&self) -> &'static str {
448 match self {
449 Self::PalaceCreated { .. } => "palace_created",
450 Self::DrawerAdded { .. } => "drawer_added",
451 Self::DrawerDeleted { .. } => "drawer_deleted",
452 Self::DreamCompleted { .. } => "dream_completed",
453 Self::StatusChanged { .. } => "status_changed",
454 Self::HookFired { .. } => "hook_fired",
455 }
456 }
457
458 /// `palace_id` if the event is scoped to a single palace.
459 ///
460 /// Why: the activity log indexes entries by palace id so the UI can
461 /// filter by palace; daemon-wide events (`status_changed`,
462 /// dream-across-all-palaces) return `None`.
463 /// What: returns a borrowed string when the variant carries a palace
464 /// id, otherwise `None`.
465 /// Test: `daemon_event_palace_id_extraction`.
466 pub fn palace_id(&self) -> Option<&str> {
467 match self {
468 Self::PalaceCreated { id, .. } => Some(id),
469 Self::DrawerAdded { palace_id, .. } | Self::DrawerDeleted { palace_id, .. } => {
470 Some(palace_id)
471 }
472 Self::DreamCompleted { palace_id, .. } => palace_id.as_deref(),
473 Self::HookFired { palace_id, .. } => palace_id.as_deref(),
474 Self::StatusChanged { .. } => None,
475 }
476 }
477
478 /// Originating subsystem if the event carries one.
479 ///
480 /// Why: only mutation events carry a `source`; the aggregate
481 /// `StatusChanged` is recomputed by the daemon and has no caller, so
482 /// it returns `None`.
483 /// What: returns the variant's `source` field where present.
484 /// Test: `daemon_event_source_extraction`.
485 pub fn source(&self) -> Option<ActivitySource> {
486 match self {
487 Self::PalaceCreated { source, .. }
488 | Self::DrawerAdded { source, .. }
489 | Self::DrawerDeleted { source, .. }
490 | Self::DreamCompleted { source, .. }
491 | Self::HookFired { source, .. } => Some(*source),
492 Self::StatusChanged { .. } => None,
493 }
494 }
495}
496
497/// Shared application state passed to every request handler.
498///
499/// Why: The stdio loop and HTTP server need the same handles to the registry,
500/// data root, and embedder so MCP tools can perform real reads/writes against
501/// the live trusty-memory core. The embedder is heavy (loads ONNX weights) so
502/// we hold it behind a `OnceCell` and initialize lazily on first use.
503/// What: `Clone`-able via `Arc` fields. The registry / data root are eager;
504/// `embedder` is `Arc<OnceCell<Arc<FastEmbedder>>>` so concurrent first-use
505/// races resolve to a single shared instance.
506/// Test: `app_state_default_constructs` confirms construction without panic.
507#[derive(Clone)]
508pub struct AppState {
509 pub version: String,
510 pub registry: Arc<PalaceRegistry>,
511 pub data_root: PathBuf,
512 pub embedder: Arc<OnceCell<Arc<FastEmbedder>>>,
513 /// Optional default palace applied to MCP tool calls when the caller
514 /// omits the `palace` argument. Set via `trusty-memory serve --palace`.
515 pub default_palace: Option<String>,
516 /// Active chat provider selected at startup. `None` means no upstream is
517 /// configured (no Ollama detected and no OpenRouter key) — callers must
518 /// degrade gracefully (chat endpoint returns 412).
519 pub chat_provider: Arc<OnceCell<Option<Arc<dyn ChatProvider>>>>,
520 /// Per-palace chat-session stores, opened lazily so cold-start cost is
521 /// paid only when chat-history endpoints are hit.
522 pub session_stores: Arc<dashmap::DashMap<String, Arc<ChatSessionStore>>>,
523 /// Broadcast sender for live `DaemonEvent` pushes to SSE subscribers.
524 ///
525 /// Why: Lets mutating handlers emit events that any connected dashboard
526 /// receives instantly. Cap of 128 buffers transient slow readers; if a
527 /// receiver lags it gets `RecvError::Lagged` and we emit a `lag` frame.
528 pub events: Arc<broadcast::Sender<DaemonEvent>>,
529 /// Instant the daemon started, used to compute `uptime_secs` on `/health`.
530 ///
531 /// Why (issue #35): `GET /health` reports how long the daemon has been
532 /// up. Capturing a monotonic `Instant` at `AppState` construction lets the
533 /// handler compute the elapsed seconds cheaply and without a clock-skew
534 /// hazard.
535 /// What: a wall-monotonic `Instant`; `AppState::new` stamps it at startup.
536 /// Test: `health_endpoint_includes_resource_fields`.
537 pub started_at: std::time::Instant,
538 /// In-memory ring buffer of recent tracing log lines (issue #35).
539 ///
540 /// Why: the `GET /api/v1/logs/tail` endpoint serves the last N log lines
541 /// so operators can inspect a running daemon without tailing a file. The
542 /// buffer is shared between the tracing `LogBufferLayer` (writer) and the
543 /// HTTP handler (reader).
544 /// What: a cheap `Arc`-backed clone of the buffer the subscriber writes
545 /// to. Defaults to an empty buffer for states that never install the
546 /// layer (tests, the stdio path).
547 /// Test: `logs_tail_returns_recent_lines`.
548 pub log_buffer: trusty_common::log_buffer::LogBuffer,
549 /// Bug-capture ERROR store (bug-reporting #478, Phase 1).
550 ///
551 /// Why: Phase 2 MCP / HTTP endpoints need to query captured errors; stashing
552 /// the `ErrorStore` handle here lets any handler reach it cheaply without
553 /// a second global or per-request construction.
554 /// What: populated by `run_serve` from the `init_tracing_with_buffer_and_capture`
555 /// result; the layer writes to this store automatically so every
556 /// `tracing::error!` call site contributes without any changes to call
557 /// sites. `None` in states that do not install the layer (tests, the
558 /// stdio path).
559 /// Test: compile-presence is verified by the `trusty-memory` build; Phase 2
560 /// will add query tests in `web.rs`.
561 pub error_store: Option<trusty_common::error_capture::ErrorStore>,
562 /// Minimal multi-tenant authorization seam (issue #1714). `false`
563 /// (single-tenant, the default) preserves today's behaviour — every
564 /// existing caller of `palace_create force=true` keeps working. `true`
565 /// opts into `authz::authorize_force_palace_create` failing closed on
566 /// every `force=true` request until a real capability check lands. Set
567 /// via `with_multi_tenant_mode_from_env` (`TRUSTY_MEMORY_MULTI_TENANT=1`);
568 /// see the `authz` module docs for the full design rationale.
569 pub multi_tenant_mode: bool,
570 /// Most recent on-disk footprint of `data_root`, in bytes (issue #35).
571 ///
572 /// Why: `GET /health` reports `disk_bytes`. Walking the data directory on
573 /// every health request would make a frequent health poll do unbounded
574 /// I/O; a background task recomputes it every 10 s and stores it here so
575 /// the handler reads it lock-free.
576 /// What: an `AtomicU64` updated by the ticker spawned in `run_http_on`.
577 /// `0` until the first walk completes.
578 /// Test: `health_endpoint_includes_resource_fields`.
579 pub disk_bytes: Arc<std::sync::atomic::AtomicU64>,
580 /// Per-process RSS + CPU sampler, refreshed on each `/health` request
581 /// (issue #35).
582 ///
583 /// Why: CPU usage is a delta between two `sysinfo` refreshes, so the
584 /// sampler must persist between requests — hence the shared `Mutex`.
585 /// What: a `tokio::sync::Mutex<SysMetrics>` so the async health handler
586 /// can sample without blocking the runtime.
587 /// Test: `health_endpoint_includes_resource_fields`.
588 pub sys_metrics: Arc<tokio::sync::Mutex<trusty_common::sys_metrics::SysMetrics>>,
589 /// HTTP listener address the daemon bound to, once `run_http_on` is running.
590 ///
591 /// Why: clients (and `/health` responses) need to advertise the live
592 /// `host:port` even though port selection happens dynamically (7070–7079
593 /// walk + OS fallback). Stashing it on `AppState` lets request handlers
594 /// surface the discovery value without re-querying the listener.
595 /// What: a `OnceLock<SocketAddr>` so `run_http_on` writes it exactly once
596 /// at bind time and every handler reads it lock-free thereafter. Empty
597 /// (`None` from `get()`) on the stdio path where no listener exists.
598 /// Test: `health_endpoint_reports_bound_addr` (added below).
599 pub bound_addr: Arc<OnceLock<SocketAddr>>,
600 /// Cached prompt-facts surface served by the MCP `get_prompt_context`
601 /// tool (issue #42).
602 ///
603 /// Why: The original session-init `prompts/get` design loaded context
604 /// once per connection; switching to a per-message tool lets the model
605 /// pull fresh, query-filtered context on demand. The cache holds both
606 /// the raw triples (for filtered lookups) and a pre-formatted Markdown
607 /// block (for the unfiltered hot path) so neither code path re-walks
608 /// the KG. The cache is rebuilt by
609 /// `prompt_facts::rebuild_prompt_cache` after any write that touches a
610 /// hot predicate (`kg_assert`, `add_alias`, `remove_prompt_fact`).
611 /// What: An `Arc<tokio::sync::RwLock<PromptFactsCache>>` so the hot
612 /// read path takes a brief read lock and clones the cache; rebuilds
613 /// take a write lock for the assignment only. The async-aware lock
614 /// (issue #229) yields to the tokio runtime instead of blocking a
615 /// runtime thread for the rebuild duration. An empty `triples` vec ↔
616 /// "no context stored yet" (the tool handler renders a hint).
617 /// Test: `get_prompt_context_returns_cached_or_hint`,
618 /// `get_prompt_context_filters_by_query`.
619 pub prompt_context_cache: Arc<RwLock<prompt_facts::PromptFactsCache>>,
620 /// Persistent activity log (issue #96).
621 ///
622 /// Why: the dashboard activity feed used to be a pure live-stream over
623 /// `/sse` — opening the UI showed an empty feed and any mutation from
624 /// the MCP path was invisible. Holding an `ActivityLog` on `AppState`
625 /// lets `emit` record an entry on every push so the
626 /// `GET /api/v1/activity` handler can return historical rows on mount
627 /// and the live SSE stream can continue prepending events on top of
628 /// the loaded history. `None` on builds that opt out (tests that use
629 /// `AppState::new` get a real log under their tempdir so behaviour
630 /// matches production).
631 /// What: an `Arc<ActivityLog>` shared with every emitter.
632 /// Test: `web::tests::activity_endpoint_lists_recent_emits`.
633 pub activity_log: Arc<ActivityLog>,
634 /// Optional per-palace BM25 lexical search lane (issue #156).
635 ///
636 /// Why: in-process BM25 would serialise the recall hot path on disk
637 /// I/O during writes and contend with the redb/usearch locks. Delegating
638 /// to the `trusty-bm25-daemon` subprocess (one socket per palace) keeps
639 /// BM25 ingestion and search off the critical path while still feeding
640 /// hits into the recall RRF fusion.
641 /// What: `Some(client)` only when `TRUSTY_BM25_DAEMON=1` at startup —
642 /// every code path that uses this field is gated on `is_some()` and
643 /// falls back to vector-only behaviour otherwise so existing deployments
644 /// see zero behavioural change.
645 /// Test: `bm25_client_disabled_by_default`,
646 /// `bm25_client_enabled_when_env_set`.
647 pub bm25_client: Option<Arc<Bm25Client>>,
648 /// Optional per-palace BM25 daemon spawn supervisor (issue #193).
649 ///
650 /// Why: without an in-process supervisor the BM25 daemon must be
651 /// launched out-of-band (launchd, manual `trusty-bm25-daemon`), which
652 /// is the same UX trap PR #190 fixed for trusty-embedderd. Holding a
653 /// supervisor here lets us spawn the daemon on first BM25 use for a
654 /// palace, restart it if it dies, and reap it on clean shutdown.
655 /// `Some` only when `TRUSTY_BM25_DAEMON=1` at startup — the same gate
656 /// that enables `bm25_client`. When set but `TRUSTY_BM25_EXTERNAL=1`,
657 /// the supervisor's `ensure_running` becomes a no-op that just returns
658 /// the canonical socket path so operators can keep using their own
659 /// process manager.
660 /// Test: covered by `bm25_supervisor_present_when_env_set` and the
661 /// `bm25_supervisor::tests` unit tests.
662 pub bm25_supervisor: Option<Arc<bm25_supervisor::Bm25Supervisor>>,
663 /// Per-palace write serialisation locks (issue #230).
664 ///
665 /// Why: the dedup gate in `tools.rs` previously read a snapshot of
666 /// existing drawers, checked for near-duplicates via Jaro-Winkler, and
667 /// then issued the write — a classic time-of-check/time-of-use race.
668 /// Two concurrent `memory_remember` calls with the same content could
669 /// both see the pre-write snapshot, both pass the gate, and both land
670 /// duplicate drawers. Serialising the gate-then-write sequence per
671 /// palace closes the window: while one task holds the mutex, any
672 /// concurrent writer for the same palace blocks until the first write
673 /// finishes and is visible to `list_drawers`. The lock is **per
674 /// palace** (not global) so writes to different palaces continue to
675 /// run in parallel.
676 /// What: a `DashMap` keyed by palace id, where each entry is an
677 /// `Arc<tokio::sync::Mutex<()>>`. The mutex is constructed lazily by
678 /// `palace_write_lock` on first access. `Arc` lets callers hold a
679 /// clone of the lock past the lifetime of the `DashMap` entry so the
680 /// map never needs to be held across an `.await`.
681 /// Test: `tools::tests::dedup_gate_blocks_concurrent_duplicate_writes`.
682 pub palace_write_locks: Arc<dashmap::DashMap<String, Arc<tokio::sync::Mutex<()>>>>,
683 /// Counter of in-flight activity-log writes spawned by `emit`
684 /// (issue #232).
685 ///
686 /// Why: `emit` offloads the synchronous redb append to the tokio blocking
687 /// pool via `spawn_blocking` so the async runtime is never parked waiting
688 /// on fsync. The write is fire-and-forget — `emit` returns immediately
689 /// after spawning. Tests that observe the activity log right after a
690 /// burst of `emit` calls need a deterministic synchronization point;
691 /// holding an in-flight counter lets `flush_activity_writes` poll until
692 /// every spawned append has settled, which keeps the assertions
693 /// race-free without forcing every caller to `.await`.
694 /// What: an `Arc<AtomicUsize>` incremented before each `spawn_blocking`
695 /// and decremented inside the closure (after the append completes, even
696 /// if it errored). The counter is cheap (one atomic add per emit) and
697 /// stays at zero in steady-state production traffic.
698 /// Test: `web::tests::activity_endpoint_lists_recent_emits` and
699 /// `tests::emit_persists_mutations_but_skips_status_changed` call
700 /// `flush_activity_writes` to drain the counter before reading the log.
701 pub pending_activity_writes: Arc<AtomicUsize>,
702 /// In-memory cache mapping palace id → `Palace.name` (issue #228).
703 ///
704 /// Why: every `memory_remember` / `memory_note` write used to call
705 /// `PalaceRegistry::list_palaces` (a synchronous filesystem walk of the
706 /// data root) just to resolve a friendly palace name for the SSE
707 /// `DrawerAdded` event. With N palaces on disk the cost was O(N) opendirs
708 /// plus `palace.json` reads on every write, blocking the async runtime.
709 /// Caching the name in-memory turns the lookup into a `DashMap::get`.
710 /// What: `DashMap<String, String>` populated by `create_palace` and
711 /// `load_palaces_from_disk`, kept in sync by rename / delete paths.
712 /// Missing entries are treated as "name unknown" so callers fall back to
713 /// the palace id and the emit path never fails.
714 /// Test: `palace_name_cache_populated_after_hydration` and
715 /// `palace_name_cache_updates_on_create`.
716 pub palace_names: Arc<dashmap::DashMap<String, String>>,
717 /// Single-pass startup pin-file map: palace id → project root path (issue #470).
718 ///
719 /// Why: after daemon startup we have no record of which on-disk project
720 /// directories correspond to which palace ids — that information only
721 /// existed inside the pin files on disk. Eager-opening every palace on
722 /// startup is too expensive. This field captures the scan-only result of
723 /// `startup_scan::scan_pin_map` so handlers that want to locate a project
724 /// by its palace id (e.g. future cwd-inference, project-health checks)
725 /// can do a single `DashMap::get` instead of a filesystem walk.
726 /// Populated once, shortly after `load_palaces_from_disk` returns, by
727 /// `spawn_startup_tasks`. Never mutated after population — it is a
728 /// snapshot of what the filesystem looked like at startup.
729 /// What: `DashMap<String (palace_id), PathBuf (project root)>`.
730 /// The outer `Arc` lets `spawn_startup_tasks` (which holds only a clone
731 /// of `AppState`) write to the same backing map that request handlers
732 /// read. Population is asynchronous so callers must treat an absent entry
733 /// as "not yet scanned" (or "no pin found"), never as "palace unknown".
734 /// Test: `startup_scan::tests::scan_pin_map_*` validate the underlying
735 /// scanner function; the wiring in `spawn_startup_tasks` is covered by
736 /// the integration-test daemon start path.
737 pub pin_project_map: Arc<dashmap::DashMap<String, PathBuf>>,
738 /// Bounded sender for the BM25 index worker (issue #231).
739 ///
740 /// Why: the previous fire-and-forget design `tokio::spawn`ed one task per
741 /// `memory_remember` / `memory_note` call, so a write burst against a slow
742 /// or unreachable BM25 daemon grew an unbounded in-flight task queue. A
743 /// single long-lived worker draining a bounded mpsc channel caps that
744 /// back-pressure: writers `try_send` (never block), full-queue requests
745 /// are dropped with a `warn!`, and the worker exits cleanly when the last
746 /// sender is dropped on shutdown.
747 /// What: an `mpsc::Sender` cloned to every `AppState` clone (cheap). The
748 /// matching receiver is consumed by the worker spawned in
749 /// [`AppState::new`] via [`tools::spawn_bm25_index_worker`]. Capacity is
750 /// [`tools::BM25_INDEX_QUEUE_CAPACITY`] (256).
751 /// Test: `bm25_index_queue_drops_when_full` exercises the full-queue
752 /// branch via `bm25_index_enqueue`.
753 pub bm25_index_tx: tokio::sync::mpsc::Sender<tools::Bm25IndexRequest>,
754 /// Cached result of the startup update check (issue #537).
755 ///
756 /// Why: `/health` should report `update_available` without hitting crates.io
757 /// on every probe. A single background check at daemon startup stores the
758 /// result here; the health handler reads it lock-free (well, a brief mutex
759 /// lock) without a network call.
760 /// What: `None` = up-to-date or check not yet done; `Some("x.y.z")` = newer
761 /// version available. The field is populated by a `tokio::spawn` in
762 /// `spawn_startup_tasks` (main.rs) after the daemon binds.
763 /// Test: indirectly by the `/health` endpoint tests in `web.rs`.
764 pub update_available: Arc<std::sync::Mutex<Option<String>>>,
765 /// Two-phase readiness state — `Warming` until the embedder is initialised,
766 /// then `Ready` (issues #910 / #911).
767 ///
768 /// Why: `AppState::embedder()` used to call `FastEmbedder::new()` without
769 /// any timeout, so the first `memory_recall`/`memory_remember` that arrived
770 /// before CoreML finished compiling would block for 5–11 hours until the
771 /// OnceCell resolved (issue #910). Exposing this state lets the preflight
772 /// guards in `tools.rs` return an explicit fast error immediately —
773 /// `"trusty-memory is warming up, retry shortly"` — instead of queueing
774 /// behind an open-ended init.
775 /// What: An `AtomicU8` starting at `DaemonReadiness::Warming` (0) and flipped
776 /// to `DaemonReadiness::Ready` (1) by `spawn_startup_tasks` after the embedder
777 /// warm-up succeeds. The transition is one-way and lock-free.
778 /// Test: `daemon_readiness_transitions_warming_to_ready`.
779 pub daemon_readiness: Arc<AtomicU8>,
780}
781
782impl AppState {
783 /// Construct an `AppState` rooted at the given on-disk data directory.
784 ///
785 /// Why: The CLI (`serve`) and integration tests need to point the MCP
786 /// server at different roots — production at `dirs::data_dir`, tests at a
787 /// `tempfile::tempdir()`.
788 /// What: Builds an empty `PalaceRegistry`, captures the version, and
789 /// allocates an empty `OnceCell` for the embedder. `default_palace` is
790 /// `None`; use `with_default_palace` to set it.
791 /// Test: `tools::tests::dispatch_palace_create_persists` constructs an
792 /// AppState pointed at a tempdir and round-trips a palace through it.
793 pub fn new(data_root: PathBuf) -> Self {
794 let (events_tx, _) = broadcast::channel::<DaemonEvent>(128);
795 // Issue #96: open (or create) the persistent activity log under the
796 // daemon data root. Open failure is logged but never crashes the
797 // daemon — we fall back to a per-process tempdir so emits remain
798 // best-effort and the rest of the daemon keeps working.
799 let activity_log = open_activity_log_with_fallback(&data_root);
800 // Issue #231: bounded mpsc channel + single long-lived worker
801 // replaces the per-write `tokio::spawn` fire-and-forget pattern so
802 // BM25 indexing back-pressure is capped. The worker is spawned here
803 // unconditionally so the channel always has a drain — even when
804 // `bm25_client` is `None`, the worker just consumes and discards
805 // each request so senders never block on a full queue.
806 let (bm25_index_tx, bm25_index_rx) =
807 tokio::sync::mpsc::channel::<tools::Bm25IndexRequest>(tools::BM25_INDEX_QUEUE_CAPACITY);
808 // `bm25_client` / `bm25_supervisor` start as `None`; the builder
809 // `with_bm25_client_from_env` rebuilds the worker with the real
810 // client + supervisor once env-gated opt-in is resolved.
811 tools::spawn_bm25_index_worker(bm25_index_rx, None, None);
812 Self {
813 version: env!("CARGO_PKG_VERSION").to_string(),
814 registry: Arc::new(PalaceRegistry::new()),
815 data_root,
816 embedder: Arc::new(OnceCell::new()),
817 default_palace: None,
818 chat_provider: Arc::new(OnceCell::new()),
819 session_stores: Arc::new(dashmap::DashMap::new()),
820 events: Arc::new(events_tx),
821 started_at: std::time::Instant::now(),
822 // Default to an empty buffer — `with_log_buffer` overrides this
823 // when the daemon installs the `LogBufferLayer` (HTTP mode).
824 log_buffer: trusty_common::log_buffer::LogBuffer::new(
825 trusty_common::log_buffer::DEFAULT_LOG_CAPACITY,
826 ),
827 // Bug-reporting #478: `None` until `with_error_store` is called
828 // during daemon startup (HTTP mode). Tests keep `None` so no
829 // unexpected files are written to the OS data dir.
830 error_store: None,
831 multi_tenant_mode: false,
832 disk_bytes: Arc::new(std::sync::atomic::AtomicU64::new(0)),
833 sys_metrics: Arc::new(tokio::sync::Mutex::new(
834 trusty_common::sys_metrics::SysMetrics::new(),
835 )),
836 bound_addr: Arc::new(OnceLock::new()),
837 prompt_context_cache: Arc::new(RwLock::new(prompt_facts::PromptFactsCache::default())),
838 activity_log,
839 bm25_client: None,
840 bm25_supervisor: None,
841 palace_write_locks: Arc::new(dashmap::DashMap::new()),
842 pending_activity_writes: Arc::new(AtomicUsize::new(0)),
843 palace_names: Arc::new(dashmap::DashMap::new()),
844 pin_project_map: Arc::new(dashmap::DashMap::new()),
845 bm25_index_tx,
846 update_available: Arc::new(std::sync::Mutex::new(None)),
847 // Start in Warming state; flipped to Ready by spawn_startup_tasks
848 // once the embedder warm-up succeeds (issues #910/#911).
849 daemon_readiness: Arc::new(AtomicU8::new(DaemonReadiness::Warming as u8)),
850 }
851 }
852
853 /// Acquire (lazily, then clone) the per-palace write mutex.
854 ///
855 /// Why (issue #230): the dedup-check + `remember_with_options` write
856 /// sequence in `tools.rs` must be atomic per palace to prevent two
857 /// concurrent identical writes from both passing the dedup gate.
858 /// Callers hold the returned `Arc<Mutex<()>>`'s guard across the gate
859 /// check and the write so the second writer blocks until the first
860 /// write is visible to `list_drawers`. Returning a clone of the `Arc`
861 /// rather than a borrow into the `DashMap` lets the caller `.await`
862 /// while holding the lock without risking a deadlock against any
863 /// future map mutation (DashMap shards are sync mutexes).
864 /// What: looks up the palace id in `palace_write_locks` and returns
865 /// a clone of the existing mutex; on the first call for a palace,
866 /// inserts a freshly-constructed `tokio::sync::Mutex<()>` first. The
867 /// `DashMap::entry().or_insert_with` API guarantees the lazy
868 /// construction is racy-safe — only one mutex is ever inserted per
869 /// palace id.
870 /// Test: `tools::tests::dedup_gate_blocks_concurrent_duplicate_writes`.
871 pub fn palace_write_lock(&self, palace_id: &str) -> Arc<tokio::sync::Mutex<()>> {
872 if let Some(existing) = self.palace_write_locks.get(palace_id) {
873 return existing.clone();
874 }
875 self.palace_write_locks
876 .entry(palace_id.to_string())
877 .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
878 .clone()
879 }
880
881 /// Look up a project root path by palace id in the startup pin-scan map.
882 ///
883 /// Why: provides a stable, cheap accessor so handlers do not reach directly
884 /// into the `DashMap` field and so the accessor can be mocked in future
885 /// tests without touching `AppState` internals. The map is populated
886 /// asynchronously by `spawn_startup_tasks` — an absent entry means either
887 /// the scan has not completed yet or no pin file claimed that id.
888 /// What: returns `Some(project_path)` when the palace id was found during
889 /// startup scan; `None` otherwise.
890 /// Test: covered indirectly via the startup-scan integration path; the
891 /// underlying map data is validated by `startup_scan::tests`.
892 pub fn pinned_project_path(&self, palace_id: &str) -> Option<PathBuf> {
893 self.pin_project_map.get(palace_id).map(|e| e.clone())
894 }
895
896 /// Builder-style: opt-in to the BM25 lexical lane (issue #156).
897 ///
898 /// Why: the BM25 subprocess is gated behind `TRUSTY_BM25_DAEMON=1` so
899 /// the default `cargo install trusty-memory` / launchd plist deployment
900 /// stays vector-only and existing test fixtures keep passing without
901 /// having to provision a daemon. Reading the env var here keeps the
902 /// gating logic in one place (the helper in `main.rs` just plumbs the
903 /// result through).
904 /// What: when `TRUSTY_BM25_DAEMON=1`, constructs one `Bm25Client` per
905 /// palace by lazy-resolving the socket path the first time the palace
906 /// id is observed. Currently we install a shared `default` client up
907 /// front and re-key on the palace id at the call site — palaces with no
908 /// daemon socket simply see search/index errors which we log + ignore.
909 /// Returns `self` unchanged when the env var is unset or set to anything
910 /// other than `1`.
911 /// Test: `bm25_client_disabled_by_default`,
912 /// `bm25_client_enabled_when_env_set`.
913 #[must_use]
914 pub fn with_bm25_client_from_env(mut self) -> Self {
915 if std::env::var("TRUSTY_BM25_DAEMON").as_deref() == Ok("1") {
916 // Install the default-palace client; per-palace clients are
917 // constructed on demand via `Bm25Client::for_palace`.
918 let default_palace = self.default_palace.as_deref().unwrap_or("default");
919 self.bm25_client = Some(Arc::new(Bm25Client::for_palace(default_palace)));
920 // Issue #193: hand-in-hand with the client, attach a spawn
921 // supervisor so the BM25 daemon is auto-started on first use
922 // for any palace. Operators who want to manage daemons
923 // out-of-band (launchd, systemd, manual) set
924 // TRUSTY_BM25_EXTERNAL=1 which makes the supervisor a no-op.
925 self.bm25_supervisor = Some(Arc::new(bm25_supervisor::Bm25Supervisor::new()));
926 // Issue #231: rebuild the bounded indexer channel + worker so
927 // the worker holds the now-populated client + supervisor. The
928 // placeholder worker installed by `AppState::new` (with `None`
929 // / `None`) drained the channel into the void — replacing the
930 // sender here closes the placeholder receiver and the
931 // placeholder worker exits cleanly. The new worker takes over
932 // as the sole drain for the indexer queue.
933 let (tx, rx) = tokio::sync::mpsc::channel::<tools::Bm25IndexRequest>(
934 tools::BM25_INDEX_QUEUE_CAPACITY,
935 );
936 tools::spawn_bm25_index_worker(
937 rx,
938 self.bm25_client.clone(),
939 self.bm25_supervisor.clone(),
940 );
941 self.bm25_index_tx = tx;
942 tracing::info!(
943 palace = default_palace,
944 "BM25 daemon client + spawn supervisor enabled (TRUSTY_BM25_DAEMON=1)"
945 );
946 }
947 self
948 }
949
950 /// Scan the palace registry directory and re-register every persisted
951 /// palace into the in-memory [`PalaceRegistry`].
952 ///
953 /// Why: `AppState::new` builds an *empty* registry, so after a daemon
954 /// restart `palace_list` / the dashboard reported zero palaces even though
955 /// dozens existed on disk — palace metadata was persisted by
956 /// `palace_create` but never re-hydrated on startup. This method closes
957 /// that gap by walking the on-disk layout (each subdirectory holding a
958 /// `palace.json` is one palace) and rebuilding a live `PalaceHandle` for
959 /// each, so recall paths see the full set immediately after a restart.
960 /// What: runs the blocking filesystem walk + per-palace `PalaceHandle::open`
961 /// on a `spawn_blocking` thread (so it never stalls the async runtime),
962 /// registers each successfully opened palace via `register_arc`, logs every
963 /// load at `debug!`, and returns the count loaded. A palace that fails to
964 /// open (corrupt index, unreadable `kg.db`, etc.) is logged at `warn!` and
965 /// skipped — one bad palace must not abort startup or crash the daemon.
966 /// `data_root` is expected to already be the palace registry directory —
967 /// `main.rs` resolves it via [`resolve_palace_registry_dir`] before
968 /// constructing the `AppState`, so the flat / legacy-`palaces/` layout
969 /// difference is handled exactly once.
970 /// Test: `tests::load_palaces_from_disk_rehydrates_registry` writes two
971 /// palaces into a tempdir, constructs an `AppState`, calls this method, and
972 /// asserts the returned count and registry contents.
973 pub async fn load_palaces_from_disk(&self) -> Result<usize> {
974 let registry_dir = self.data_root.clone();
975 let registry = self.registry.clone();
976 let palace_names = self.palace_names.clone();
977 // The directory walk and each `PalaceHandle::open` perform blocking
978 // filesystem + redb/usearch I/O — run the whole hydration on the
979 // blocking pool so it never parks an async worker thread.
980 let count = tokio::task::spawn_blocking(move || -> Result<usize> {
981 let palaces = PalaceRegistry::list_palaces(®istry_dir)?;
982 let total = palaces.len();
983 let mut loaded = 0usize;
984 let mut skipped = 0usize;
985 for palace in palaces {
986 match trusty_common::memory_core::PalaceHandle::open(&palace) {
987 Ok(handle) => {
988 tracing::debug!(
989 palace = %palace.id,
990 data_dir = %palace.data_dir.display(),
991 "loaded palace from disk"
992 );
993 // Issue #228: seed the in-memory name cache so write
994 // hot paths (memory_remember / memory_note) can resolve
995 // the friendly palace name without re-walking the data
996 // root. Insert here (during hydration) is the single
997 // point of truth for restart-time population.
998 palace_names.insert(palace.id.0.clone(), palace.name.clone());
999 registry.register_arc(handle);
1000 loaded += 1;
1001 }
1002 Err(e) => {
1003 // Why (issue #467): a single bad palace (corrupt kg.db,
1004 // stale WAL, EMFILE — "Too many open files", permissions)
1005 // must never abort startup or block the HTTP server from
1006 // binding. Log per-palace and keep going; the summary
1007 // below tells operators how many were skipped without
1008 // trawling the log.
1009 // The palace is NOT registered in the in-memory registry,
1010 // so the next `open_palace` call for this id will attempt
1011 // a fresh open from disk — the lazy-reopen path. If the
1012 // root cause was EMFILE and the fd-limit fix (#462) raised
1013 // the soft limit to 8192, that first request will succeed.
1014 tracing::warn!(
1015 palace = %palace.id,
1016 data_dir = %palace.data_dir.display(),
1017 "skipping palace during startup hydration: {e:#}; \
1018 will retry lazily on first access"
1019 );
1020 skipped += 1;
1021 }
1022 }
1023 }
1024 tracing::info!(
1025 "palace hydration summary: loaded {loaded}/{total} ({skipped} skipped due to errors)"
1026 );
1027 Ok(loaded)
1028 })
1029 .await
1030 .map_err(|e| anyhow::anyhow!("join load_palaces_from_disk: {e}"))??;
1031 Ok(count)
1032 }
1033
1034 /// Builder-style: attach the daemon's shared [`LogBuffer`] so the
1035 /// `GET /api/v1/logs/tail` endpoint serves the same lines the tracing
1036 /// subscriber captures (issue #35).
1037 ///
1038 /// Why: `main` builds the buffer (via `init_tracing_with_buffer`) before
1039 /// constructing the `AppState`, then hands a clone here so the HTTP
1040 /// handler and the tracing layer observe the same ring.
1041 /// What: replaces the empty default buffer with the supplied one.
1042 /// Test: `logs_tail_returns_recent_lines`.
1043 #[must_use]
1044 pub fn with_log_buffer(mut self, buffer: trusty_common::log_buffer::LogBuffer) -> Self {
1045 self.log_buffer = buffer;
1046 self
1047 }
1048
1049 /// Builder-style: mark this daemon as the sole palace writer so palace
1050 /// redb files open with `OpenIntent::Writer` (issue #1487).
1051 ///
1052 /// Why: The HTTP daemon owns the write lock on every palace's `kg.redb`
1053 /// and `index.usearch.redb`. Before this fix, when a *second* daemon
1054 /// instance opened the same store it silently degraded to a read-only
1055 /// snapshot and rejected every `memory_remember` for its lifetime —
1056 /// effectively silent data loss when an MCP client routed a write to the
1057 /// rogue instance. Opening as `Writer` makes the second instance fail
1058 /// loud (after a short handoff-retry window that absorbs a graceful
1059 /// launchd `bootout`→`bootstrap` overlap) instead of serving broken
1060 /// reads-only. CLI, stdio-proxy, and test code paths never call this, so
1061 /// they keep the snapshot read-fallback (issue #59).
1062 /// What: Replaces `self.registry` with a fresh `PalaceRegistry` carrying
1063 /// `OpenIntent::Writer`.
1064 ///
1065 /// Invariant: MUST be called on a fresh, unhydrated, unshared registry —
1066 /// during startup, before `spawn_startup_tasks`/`load_palaces_from_disk`
1067 /// registers any `PalaceHandle` and before the `AppState` (hence its
1068 /// `Arc<PalaceRegistry>`) is cloned to a handler. Replacing the registry
1069 /// discards the prior `Arc`; doing so after hydration would silently drop
1070 /// live handles (data loss), and doing so after the state is shared would
1071 /// leave other clones on the stale read-only registry. The guard is a
1072 /// `debug_assert!` on the strongest cheap signals the registry exposes —
1073 /// `is_empty()` (no handles hydrated) and `Arc::strong_count == 1` (not yet
1074 /// shared) — so an ordering violation fails fast as the programmer error it
1075 /// is (the call site is startup-only and fixed). Release builds elide the
1076 /// assert; the real call site (`run_serve`) always satisfies it.
1077 /// Test: `with_writer_intent_marks_registry_writer` and
1078 /// `with_writer_intent_panics_on_hydrated_registry` in `lib_tests`.
1079 #[must_use]
1080 pub fn with_writer_intent(mut self) -> Self {
1081 // Fail fast on an ordering bug: a hydrated registry (`!is_empty`) or a
1082 // shared one (`strong_count > 1`) would silently drop live handles or
1083 // strand other clones on the stale read-only registry (issue #1487).
1084 debug_assert!(self.registry.is_empty() && Arc::strong_count(&self.registry) == 1);
1085 self.registry = Arc::new(PalaceRegistry::new().with_writer_intent());
1086 self
1087 }
1088
1089 /// Builder-style: attach the bug-capture `ErrorStore` handle (bug-reporting #478).
1090 ///
1091 /// Why: Phase 2 MCP / HTTP endpoints need a handle to the in-memory error
1092 /// ring so they can serve `recent_errors` / `errors_by_fingerprint`
1093 /// without disk I/O on the hot path. Installing it here — rather than
1094 /// adding it as a separate global — keeps the state graph explicit and
1095 /// lets tests skip it by never calling this method.
1096 /// What: stores `Some(store)` in `AppState::error_store`; the `BugCaptureLayer`
1097 /// that writes to this store is already installed in the tracing
1098 /// subscriber by `init_tracing_with_buffer_and_capture`. The store is
1099 /// `Clone` (cheap `Arc` clone internally) so both the layer and this
1100 /// field share the same underlying ring.
1101 /// Test: Phase 2 will add `error_store_captures_and_queries` in `web.rs`.
1102 #[must_use]
1103 pub fn with_error_store(mut self, store: trusty_common::error_capture::ErrorStore) -> Self {
1104 self.error_store = Some(store);
1105 self
1106 }
1107
1108 /// Builder-style: opt into multi-tenant authorization mode (issue #1714).
1109 ///
1110 /// Why: mirrors `with_bm25_client_from_env`'s pattern of keeping env-var
1111 /// gating in one place. Unset (the default) preserves today's
1112 /// single-tenant behaviour with zero change for existing callers.
1113 /// What: sets `multi_tenant_mode` from `TRUSTY_MEMORY_MULTI_TENANT=1`; see
1114 /// the `authz` module for what the flag then enforces.
1115 /// Test: `authorize_force_palace_create_denies_multi_tenant_without_capability`.
1116 #[must_use]
1117 pub fn with_multi_tenant_mode_from_env(mut self) -> Self {
1118 self.multi_tenant_mode = std::env::var("TRUSTY_MEMORY_MULTI_TENANT").as_deref() == Ok("1");
1119 self
1120 }
1121
1122 /// Send a `DaemonEvent` to all connected SSE subscribers and persist
1123 /// it to the activity log when the variant carries a source.
1124 ///
1125 /// Why: Mutating handlers call this after a successful write so the
1126 /// dashboard can update without polling. The send is best-effort —
1127 /// `broadcast::Sender::send` returns `Err` only when there are no live
1128 /// receivers, which is fine (no listeners == no work to do). Issue
1129 /// #96 additionally writes the entry to the persistent activity log
1130 /// so the feed can serve historical rows on page load and so MCP /
1131 /// HTTP / Hook origins are visible to the operator. Persistence is
1132 /// also best-effort — a write failure is logged but never blocks the
1133 /// SSE broadcast.
1134 ///
1135 /// Issue #232: the activity-log append is a synchronous redb write +
1136 /// fsync. Calling it directly on the async caller's task parked a tokio
1137 /// worker thread on disk I/O for every SSE event. We now offload the
1138 /// append to the blocking thread pool via `spawn_blocking` and return
1139 /// immediately — `emit` stays synchronous so every existing caller
1140 /// (including the sync `dispatch_hook_fired` JSON-RPC handler) keeps
1141 /// compiling unchanged. The fire-and-forget pattern matches the
1142 /// pre-fix semantics (best-effort, never blocks the SSE broadcast)
1143 /// while freeing the async runtime to do real work during the write.
1144 /// What: serialises the event for the log (skipping `StatusChanged`
1145 /// which is a recomputed aggregate, not a mutation), spawns the redb
1146 /// append on `tokio::task::spawn_blocking` keyed by a clone of the
1147 /// `Arc<ActivityLog>` and the cloned event, then sends the event over
1148 /// the broadcast channel. A `pending_activity_writes` counter is bumped
1149 /// before the spawn and decremented inside the closure so
1150 /// [`Self::flush_activity_writes`] can drain in tests.
1151 /// Test: `web::tests::sse_stream_receives_palace_created` confirms a
1152 /// subscriber observes the emitted event;
1153 /// `activity_endpoint_lists_recent_emits` confirms persistence via
1154 /// `flush_activity_writes`.
1155 pub fn emit(&self, event: DaemonEvent) {
1156 if let Some(source) = event.source() {
1157 let event_type = event.type_str();
1158 let palace_id = event.palace_id().map(|s| s.to_string());
1159 let log = Arc::clone(&self.activity_log);
1160 let event_for_log = event.clone();
1161 let pending = Arc::clone(&self.pending_activity_writes);
1162 // Pre-allocate the sequence id in the emitting thread so the
1163 // persisted order matches the emission order even when blocking-pool
1164 // workers execute the writes concurrently (issue #247). Without
1165 // this, four rapid emits would assign IDs inside their respective
1166 // `spawn_blocking` closures in a non-deterministic order.
1167 let id = log.alloc_id();
1168 pending.fetch_add(1, Ordering::SeqCst);
1169 // Why: the synchronous redb append + fsync must not park an
1170 // async worker thread (issue #232). Spawn the write on the
1171 // blocking pool; the JoinHandle is intentionally dropped —
1172 // the write is best-effort and any failure is logged below.
1173 tokio::task::spawn_blocking(move || {
1174 let result = log.append_with_id(id, source, palace_id, event_type, &event_for_log);
1175 if let Err(e) = result {
1176 tracing::warn!("activity_log.append failed for {event_type}: {e:#}");
1177 }
1178 pending.fetch_sub(1, Ordering::SeqCst);
1179 });
1180 }
1181 let _ = self.events.send(event);
1182 }
1183
1184 /// Block (asynchronously) until every in-flight activity-log write
1185 /// spawned by [`Self::emit`] has settled.
1186 ///
1187 /// Why: `emit` offloads its redb append to `tokio::task::spawn_blocking`
1188 /// and returns immediately (issue #232). Tests that observe the
1189 /// activity log right after a burst of emits would otherwise race the
1190 /// blocking-pool worker; this helper gives them a deterministic
1191 /// synchronization point. Production code never needs to call this —
1192 /// the dashboard reads through `GET /api/v1/activity`, which already
1193 /// tolerates writes settling asynchronously.
1194 /// What: spins on `pending_activity_writes` with a 1 ms yield until the
1195 /// counter is zero. Cheap: tests typically emit a handful of events
1196 /// and the loop exits within a single scheduler tick.
1197 /// Test: covered indirectly by `emit_persists_mutations_but_skips_status_changed`
1198 /// and `web::tests::activity_endpoint_lists_recent_emits`.
1199 pub async fn flush_activity_writes(&self) {
1200 while self.pending_activity_writes.load(Ordering::SeqCst) > 0 {
1201 tokio::time::sleep(std::time::Duration::from_millis(1)).await;
1202 }
1203 }
1204
1205 /// Open (or return cached) the chat-session store for a palace.
1206 ///
1207 /// Why: Chat session persistence lives in a dedicated redb file under
1208 /// the palace's data dir (`chat_sessions.redb`) so it doesn't intermingle
1209 /// with the KG's transactional load. The store is cheap to clone via
1210 /// `Arc` but the underlying connection should be reused, so cache by id.
1211 /// What: Creates the palace data dir if missing, opens (or reuses) a
1212 /// `ChatSessionStore` and stashes an `Arc` in the DashMap.
1213 /// Test: Indirectly via the session HTTP handlers in `web::tests`.
1214 pub fn session_store(&self, palace_id: &str) -> Result<Arc<ChatSessionStore>> {
1215 if let Some(entry) = self.session_stores.get(palace_id) {
1216 return Ok(entry.clone());
1217 }
1218 let dir = self.data_root.join(palace_id);
1219 std::fs::create_dir_all(&dir)
1220 .map_err(|e| anyhow::anyhow!("create palace dir {}: {e}", dir.display()))?;
1221 let store = Arc::new(ChatSessionStore::open(&dir.join("chat_sessions.db"))?);
1222 self.session_stores
1223 .insert(palace_id.to_string(), store.clone());
1224 Ok(store)
1225 }
1226
1227 /// Builder-style setter for the default palace name.
1228 ///
1229 /// Why: `serve --palace <name>` wants to bind every tool call to a
1230 /// project-scoped namespace without forcing every MCP request to repeat
1231 /// the palace argument.
1232 /// What: Returns `self` with `default_palace = Some(name)`.
1233 /// Test: `default_palace_used_when_arg_omitted` covers the resolution
1234 /// path; this setter is exercised there.
1235 pub fn with_default_palace(mut self, name: Option<String>) -> Self {
1236 self.default_palace = name;
1237 self
1238 }
1239
1240 /// Resolve (or initialize) the shared embedder.
1241 ///
1242 /// Why: FastEmbedder load is expensive — we share one instance across all
1243 /// tool calls; the `OnceCell` ensures concurrent first-use races collapse
1244 /// to a single load.
1245 /// What: Returns `Arc<FastEmbedder>` on success. Errors propagate from the
1246 /// underlying ONNX load.
1247 /// Test: Indirectly via `dispatch_remember_then_recall`.
1248 /// Resolve the active chat provider, auto-detecting on first call.
1249 ///
1250 /// Why: Provider selection depends on filesystem-loaded config plus a
1251 /// network probe (Ollama liveness), so it must be lazily initialised at
1252 /// runtime. Caching the choice in a `OnceCell` keeps it stable across
1253 /// concurrent requests without re-probing on every chat call.
1254 /// What: On first use loads `~/.trusty-memory/config.toml`, prefers an
1255 /// auto-detected Ollama instance (when `local_model.enabled`), and falls
1256 /// back to OpenRouter when an API key is set. Returns `Ok(None)` when
1257 /// neither is available so the caller can emit a 412.
1258 /// Test: `web::tests::providers_endpoint_returns_payload` covers the
1259 /// detection path indirectly through `/api/v1/chat/providers`.
1260 pub async fn chat_provider(&self) -> Option<Arc<dyn ChatProvider>> {
1261 self.chat_provider
1262 .get_or_init(|| async {
1263 // Why (issue #226): `service::load_user_config` is the
1264 // axum-free home of the loader; the `web::load_user_config`
1265 // re-export only exists for the HTTP handlers. Going
1266 // direct to `service` keeps this method usable when
1267 // the `axum-server` feature is disabled.
1268 let cfg = crate::service::load_user_config().unwrap_or_default();
1269 if cfg.local_model.enabled {
1270 if let Some(mut p) =
1271 trusty_common::auto_detect_local_provider(&cfg.local_model.base_url).await
1272 {
1273 // auto_detect returns an empty model id; callers must
1274 // set the configured model name themselves.
1275 p.model = cfg.local_model.model.clone();
1276 return Some(Arc::new(p) as Arc<dyn ChatProvider>);
1277 }
1278 }
1279 if !cfg.openrouter_api_key.is_empty() {
1280 return Some(Arc::new(trusty_common::OpenRouterProvider::new(
1281 cfg.openrouter_api_key,
1282 cfg.openrouter_model,
1283 )) as Arc<dyn ChatProvider>);
1284 }
1285 None
1286 })
1287 .await
1288 .clone()
1289 }
1290
1291 /// Spawn a fire-and-forget background task that auto-discovers project
1292 /// aliases under `project_root` and asserts new ones into `palace`.
1293 ///
1294 /// Why (issue #42): Projects carry implicit shorthand — cargo package
1295 /// names that differ from their directory, binary names that differ
1296 /// from packages, first-letter abbreviations — that should be surfaced
1297 /// without a user ever calling `add_alias`. Running discovery as a
1298 /// detached task on palace-open keeps startup latency unchanged: the
1299 /// daemon binds and starts serving immediately while the discovery scan
1300 /// completes in the background, and any newly-asserted aliases land in
1301 /// the prompt cache before the model's next `get_prompt_context` call.
1302 /// What: clones `self` (cheap; `Arc`-backed), spawns a tokio task that
1303 /// invokes the `discover_aliases` tool handler directly so the
1304 /// dedup + cache-rebuild logic runs exactly the same path as the MCP
1305 /// tool call. Errors are logged at `warn!`; one failed discovery never
1306 /// destabilises the daemon.
1307 /// Test: not unit-tested (timing-dependent fire-and-forget); the
1308 /// underlying `discover_aliases` dispatch is covered by
1309 /// `dispatch_discover_aliases_inserts_new_and_dedupes` in `tools::tests`.
1310 pub fn spawn_alias_discovery(&self, palace: String, project_root: PathBuf) {
1311 let state = self.clone();
1312 tokio::spawn(async move {
1313 let args = serde_json::json!({
1314 "palace": palace,
1315 "project_root": project_root.to_string_lossy(),
1316 });
1317 match tools::dispatch_tool(&state, "discover_aliases", args).await {
1318 Ok(result) => tracing::info!(
1319 new = ?result.get("new"),
1320 already_known = ?result.get("already_known"),
1321 "alias discovery complete"
1322 ),
1323 Err(e) => tracing::warn!("alias discovery failed: {e:#}"),
1324 }
1325 });
1326 }
1327
1328 /// Return the current readiness state.
1329 ///
1330 /// Why: tool handlers and the `/health` endpoint need a cheap, lock-free
1331 /// way to check whether the embedder has been initialised yet.
1332 /// What: loads `daemon_readiness` with `Acquire` ordering so the caller
1333 /// sees all writes the startup task made before setting the state.
1334 /// Test: `daemon_readiness_transitions_warming_to_ready`.
1335 pub fn readiness(&self) -> DaemonReadiness {
1336 DaemonReadiness::from_u8(self.daemon_readiness.load(Ordering::Acquire))
1337 }
1338
1339 /// Flip the readiness state from `Warming` to `Ready`.
1340 ///
1341 /// Why: called by `spawn_startup_tasks` in `main.rs` once the embedder
1342 /// warm-up succeeds — this is the single state-transition site.
1343 /// What: `store(Ready, Release)` so subsequent `Acquire` loads in handlers
1344 /// observe a consistent state. Idempotent: calling it multiple times is
1345 /// harmless.
1346 /// Test: `daemon_readiness_transitions_warming_to_ready`.
1347 pub fn set_ready(&self) {
1348 self.daemon_readiness
1349 .store(DaemonReadiness::Ready as u8, Ordering::Release);
1350 }
1351
1352 /// Obtain the shared `FastEmbedder` instance, initialising it on first call.
1353 ///
1354 /// Why: centralises lazy embedder access so every tool handler goes through
1355 /// one bounded init path (tracks #910 internally).
1356 /// What: wraps `OnceCell::get_or_try_init` with a timeout so a slow
1357 /// CoreML/CUDA first-compile cannot block a handler indefinitely. On
1358 /// timeout the `OnceCell` is left unresolved and the next caller retries.
1359 ///
1360 /// **Callers on the request path SHOULD check `readiness()` before this
1361 /// method** (issue #1970) — every recall handler now checks
1362 /// `readiness() == Ready` first and only calls `embedder()` on that
1363 /// branch, falling back to a BM25/L0/L1-only path while `Warming` instead
1364 /// of paying this method's cold-init cost. Reaching this method while
1365 /// still `Warming` is not a bug (the warm-up task itself calls
1366 /// `embedder()` while in `Warming` state), just unusual on the request
1367 /// path.
1368 ///
1369 /// This timeout is a backstop against a pathological init delay (e.g. the
1370 /// warm-up task's own call, or a handler that skips the `readiness()`
1371 /// check). If this timeout fires the `OnceCell` is left in the unresolved
1372 /// state and the next call retries from scratch.
1373 pub async fn embedder(&self) -> Result<Arc<FastEmbedder>> {
1374 use trusty_common::memory_core::timeouts;
1375 let cell = self.embedder.clone();
1376 let timeout = timeouts::embedder_init_timeout();
1377 let embedder = tokio::time::timeout(
1378 timeout,
1379 cell.get_or_try_init(|| async {
1380 let e = FastEmbedder::new().await?;
1381 Ok::<Arc<FastEmbedder>, anyhow::Error>(Arc::new(e))
1382 }),
1383 )
1384 .await
1385 .map_err(|_| {
1386 anyhow::anyhow!(
1387 "AppState::embedder() timed out after {:?}; \
1388 the CoreML/CUDA model is taking unusually long to compile — \
1389 increase TRUSTY_EMBEDDER_INIT_TIMEOUT_SECS if needed",
1390 timeout
1391 )
1392 })??
1393 .clone();
1394 Ok(embedder)
1395 }
1396}
1397
1398impl std::fmt::Debug for AppState {
1399 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1400 f.debug_struct("AppState")
1401 .field("version", &self.version)
1402 .field("data_root", &self.data_root)
1403 .field("registry_len", &self.registry.len())
1404 .finish()
1405 }
1406}
1407
1408/// Handle a single MCP JSON-RPC message and produce its response.
1409///
1410/// Why: Pulled out of the stdio loop so unit tests can drive every method
1411/// without touching real stdin/stdout.
1412/// What: Routes `initialize`, `tools/list`, `tools/call`, `ping`, and the
1413/// `notifications/initialized` notification (which returns `Value::Null`).
1414/// Test: See unit tests below — initialize/list/call all return expected
1415/// JSON-RPC envelopes; notifications return `Null` (no response written).
1416pub async fn handle_message(state: &AppState, msg: Value) -> Value {
1417 let id = msg.get("id").cloned().unwrap_or(Value::Null);
1418 let method = msg.get("method").and_then(|m| m.as_str()).unwrap_or("");
1419
1420 match method {
1421 "initialize" => {
1422 let extra = state
1423 .default_palace
1424 .as_ref()
1425 .map(|dp| json!({ "default_palace": dp }));
1426 let result = initialize_response("trusty-memory", &state.version, extra);
1427 // Why (issue #42): prompt-facts now flow through the
1428 // per-message `get_prompt_context` tool rather than MCP
1429 // prompts, so we no longer advertise the `prompts` capability.
1430 json!({
1431 "jsonrpc": "2.0",
1432 "id": id,
1433 "result": result,
1434 })
1435 }
1436 // Notifications must NOT receive a response.
1437 "notifications/initialized" | "notifications/cancelled" => Value::Null,
1438 "tools/list" => json!({
1439 "jsonrpc": "2.0",
1440 "id": id,
1441 "result": tools::tool_definitions_with(state.default_palace.is_some())
1442 }),
1443 // OpenRPC 1.3.2 discovery — see `openrpc.rs`. Returns the full
1444 // service description so orchestrators (open-mpm, etc.) can
1445 // introspect every tool and its required `memory.read`/`memory.write`
1446 // scope without bespoke per-server adapters.
1447 "rpc.discover" => json!({
1448 "jsonrpc": "2.0",
1449 "id": id,
1450 "result": openrpc::build_discover_response(
1451 &state.version,
1452 state.default_palace.is_some(),
1453 ),
1454 }),
1455 "tools/call" => {
1456 let params = msg.get("params").cloned().unwrap_or_default();
1457 let tool_name = params
1458 .get("name")
1459 .and_then(|n| n.as_str())
1460 .unwrap_or("")
1461 .to_string();
1462 let args = params.get("arguments").cloned().unwrap_or_default();
1463 match tools::dispatch_tool(state, &tool_name, args).await {
1464 Ok(content) => {
1465 // Why: tools that return a bare JSON string (e.g.
1466 // `get_prompt_context` returning the formatted
1467 // Markdown block) should surface as plain text in the
1468 // MCP `content[0].text` field — wrapping in
1469 // `Value::to_string()` would re-quote the payload and
1470 // force every caller to strip outer quotes.
1471 let text = match &content {
1472 Value::String(s) => s.clone(),
1473 other => other.to_string(),
1474 };
1475 json!({
1476 "jsonrpc": "2.0",
1477 "id": id,
1478 "result": {
1479 "content": [{"type": "text", "text": text}]
1480 }
1481 })
1482 }
1483 Err(e) => json!({
1484 "jsonrpc": "2.0",
1485 "id": id,
1486 // Why: anyhow's `{:#}` alternate format walks the full
1487 // `Caused by:` chain so MCP clients see actionable
1488 // detail (e.g. "PalaceHandle::remember_with_options:
1489 // filter rejected: too short") instead of just the
1490 // outermost context label.
1491 "error": {"code": -32603, "message": format!("{e:#}")}
1492 }),
1493 }
1494 }
1495 "ping" => json!({"jsonrpc": "2.0", "id": id, "result": {}}),
1496 _ => json!({
1497 "jsonrpc": "2.0",
1498 "id": id,
1499 "error": {
1500 "code": -32601,
1501 "message": format!("Method not found: {method}")
1502 }
1503 }),
1504 }
1505}
1506
1507/// Preferred starting port for the trusty-memory HTTP daemon.
1508///
1509/// Why: keeps the well-known default stable for clients that have hard-coded
1510/// `127.0.0.1:7070` in their configuration, while still allowing dynamic
1511/// walking when the port is in use (`DYNAMIC_PORT_RANGE` ports starting here).
1512/// What: `7070` — historic default, matches the launchd plist's prior value.
1513/// Test: covered indirectly by `bind_dynamic_port_returns_listener`.
1514pub const DEFAULT_HTTP_PORT: u16 = 7070;
1515
1516/// Number of consecutive ports `bind_dynamic_port` walks before falling back
1517/// to the OS-assigned port. Matches the trusty-search convention.
1518const DYNAMIC_PORT_RANGE: u16 = 10;
1519
1520/// Path to the canonical address-discovery file for the trusty-memory daemon.
1521///
1522/// Why: clients (CLI, MCP tools, dashboards) need to find the running daemon
1523/// without configuration when the port was selected dynamically. Using
1524/// `trusty_common::resolve_data_dir` aligns this path with the location
1525/// that `trusty_common::read_daemon_addr("trusty-memory")` reads from, so
1526/// `prompt-context`, `doctor`, and `start`'s probe all find the running daemon.
1527/// The old `~/.trusty-memory/http_addr` path and the new
1528/// `~/Library/Application Support/trusty-memory/http_addr` (macOS) path were
1529/// divergent — the daemon wrote one; readers expected the other.
1530/// What: returns `{resolve_data_dir("trusty-memory")}/http_addr`, or `None` if
1531/// the data dir cannot be resolved (locked-down container, no passwd entry).
1532/// Test: `http_addr_path_uses_resolve_data_dir`.
1533pub fn http_addr_path() -> Option<PathBuf> {
1534 trusty_common::resolve_data_dir("trusty-memory")
1535 .ok()
1536 .map(|d| d.join("http_addr"))
1537}
1538
1539/// Bind a `TcpListener` to `127.0.0.1`, dynamically selecting a port.
1540///
1541/// Why: the historic default `7070` is convenient for clients but a stale
1542/// process or a second daemon must not produce a noisy failure. Walking
1543/// `DEFAULT_HTTP_PORT..DEFAULT_HTTP_PORT+DYNAMIC_PORT_RANGE` first preserves
1544/// backwards compatibility for the common case; OS-assigned fallback (`:0`)
1545/// guarantees the daemon always comes up even when every preferred port is
1546/// busy.
1547/// What: returns the first successful `TcpListener` (7070..=7079, then
1548/// OS-assigned); caller inspects `local_addr()` to learn the chosen port.
1549/// Test: `bind_dynamic_port_returns_listener` confirms it always binds *some*
1550/// port even after another listener occupies the preferred one.
1551pub async fn bind_dynamic_port() -> Result<tokio::net::TcpListener> {
1552 let preferred: SocketAddr = SocketAddr::from(([127, 0, 0, 1], DEFAULT_HTTP_PORT));
1553 // First: walk the preferred range (7070..=7079).
1554 if let Ok(listener) =
1555 trusty_common::bind_with_auto_port(preferred, DYNAMIC_PORT_RANGE - 1).await
1556 {
1557 return Ok(listener);
1558 }
1559 // Last resort: ask the kernel for any free port. `bind_with_auto_port`
1560 // with `:0` resolves immediately to the OS-assigned port.
1561 tracing::warn!(
1562 "all ports {DEFAULT_HTTP_PORT}..{} in use; requesting OS-assigned port",
1563 DEFAULT_HTTP_PORT + DYNAMIC_PORT_RANGE - 1
1564 );
1565 let any: SocketAddr = SocketAddr::from(([127, 0, 0, 1], 0));
1566 trusty_common::bind_with_auto_port(any, 0).await
1567}
1568
1569/// Write the bound `host:port` to `~/.trusty-memory/http_addr` atomically.
1570///
1571/// Why: clients must read the file mid-write without observing a partial
1572/// value. Writing to a `.tmp` sibling and renaming over the target gives
1573/// POSIX atomicity, matching the trusty-search implementation.
1574/// What: creates the parent directory if missing; writes `addr` followed by a
1575/// trailing newline (avoids the "no newline at end of file" warnings from
1576/// `cat`); renames `.tmp` → `http_addr`. Best-effort: I/O errors are
1577/// returned to the caller so `run_http_on` can log without panicking.
1578/// Test: `http_addr_file_round_trip_via_helpers`.
1579#[cfg(feature = "axum-server")]
1580fn write_http_addr_file(path: &Path, addr: &SocketAddr) -> std::io::Result<()> {
1581 use std::io::Write;
1582 if let Some(parent) = path.parent() {
1583 std::fs::create_dir_all(parent)?;
1584 }
1585 let tmp = path.with_extension("addr.tmp");
1586 {
1587 let mut f = std::fs::File::create(&tmp)?;
1588 writeln!(f, "{addr}")?;
1589 f.sync_all()?;
1590 }
1591 std::fs::rename(&tmp, path)?;
1592 Ok(())
1593}
1594
1595/// Return `true` when a non-default data directory is in effect.
1596///
1597/// Why (issue #880): two startup side-effects must be suppressed when the
1598/// daemon runs with an isolated/overridden data root:
1599/// 1. The legacy `~/.trusty-memory/http_addr` dotfile write — it would
1600/// overwrite the real production daemon's discovery file with the isolated
1601/// instance's throwaway address.
1602/// 2. The startup pin-scan — it reads project pin files from the **real**
1603/// user environment (~/Projects, ~/Developer, …) and imports palaces from
1604/// the real environment into the isolated data root, defeating isolation.
1605///
1606/// A "non-default data dir" means `TRUSTY_DATA_DIR_OVERRIDE` is set to a
1607/// non-empty, non-whitespace value. Empty or whitespace-only values are
1608/// treated as unset (same rule as `resolve_data_dir`), so an accidental blank
1609/// env var does not suppress the dotfile write on real production instances.
1610/// What: reads `TRUSTY_DATA_DIR_OVERRIDE`; returns `true` when it contains a
1611/// non-empty, non-whitespace string. Returns `false` otherwise.
1612/// Test: `is_data_dir_override_active_when_set`,
1613/// `is_data_dir_override_inactive_when_unset`,
1614/// `is_data_dir_override_inactive_when_blank`.
1615#[inline]
1616pub fn is_data_dir_override_active() -> bool {
1617 matches!(
1618 std::env::var(trusty_common::DATA_DIR_OVERRIDE_ENV),
1619 Ok(v) if !v.trim().is_empty()
1620 )
1621}
1622
1623/// Resolve the dotfile discovery path `~/.trusty-memory/http_addr`.
1624///
1625/// Why (issue #498): external tooling such as claude-mpm's `migrate_trusty_autodetect`
1626/// reads `~/.trusty-memory/http_addr` to find the running daemon's port. On
1627/// macOS, `resolve_data_dir("trusty-memory")` returns
1628/// `~/Library/Application Support/trusty-memory/`, not `~/.trusty-memory/`,
1629/// so the daemon was writing to the OS-standard location while readers expected
1630/// the dotfile location. Writing to both locations keeps every reader happy
1631/// regardless of which convention they follow.
1632///
1633/// Fix #880: returns `None` when `TRUSTY_DATA_DIR_OVERRIDE` is active so an
1634/// isolated instance (test rig, CI, parallel run) never overwrites the real
1635/// production daemon's discovery dotfile.
1636///
1637/// What: returns `$HOME/.trusty-memory/http_addr` in the default (production)
1638/// case, or `None` when `dirs::home_dir()` is unavailable OR when a data-dir
1639/// override is active (see `is_data_dir_override_active`).
1640/// Test: `dotfile_http_addr_path_uses_home_dir`,
1641/// `dotfile_suppressed_when_override_active`.
1642#[cfg(feature = "axum-server")]
1643fn dotfile_http_addr_path() -> Option<PathBuf> {
1644 // Fix #880: never write to the shared dotfile when an override is active.
1645 if is_data_dir_override_active() {
1646 return None;
1647 }
1648 dirs::home_dir().map(|h| h.join(".trusty-memory").join("http_addr"))
1649}
1650
1651/// Run the optional HTTP/SSE + web admin server.
1652///
1653/// Why: A long-running daemon mode lets non-stdio clients (browsers, curl,
1654/// future remote agents) hit `/health`, the `/api/v1/*` REST surface, and the
1655/// embedded admin SPA. The Unix-domain-socket transport and the
1656/// `trusty-memory-mcp-bridge` binary were removed in PR3 of the #914
1657/// stdio-cutover epic; the canonical MCP integration is now
1658/// `trusty-memory serve --stdio` (PR1 #919).
1659/// What: axum router built from `web::router()` plus a `/sse` stub for the
1660/// existing MCP-over-SSE clients. Caller provides a pre-bound listener so
1661/// port auto-detection lives at the call site. Before accepting connections
1662/// the daemon stamps the bound `host:port` onto `AppState.bound_addr` and
1663/// writes `~/.trusty-memory/http_addr` so clients can discover the live port.
1664/// On shutdown the file is removed best-effort (a stale file with the wrong
1665/// port is worse than a missing one).
1666/// Test: `cargo test -p trusty-memory web::tests` exercises the router shape;
1667/// manual: `curl http://127.0.0.1:<port>/health` returns `ok` with `addr`.
1668#[cfg(feature = "axum-server")]
1669pub async fn run_http_on(state: AppState, listener: tokio::net::TcpListener) -> Result<()> {
1670 use axum::routing::get;
1671
1672 // Issue #35: recompute the `data_root` disk footprint every 10 s on a
1673 // background task so `GET /health` reports `disk_bytes` without doing a
1674 // recursive directory walk on the request path.
1675 spawn_disk_size_ticker(state.clone());
1676
1677 // Issue #228: emit aggregate `StatusChanged` on a fixed cadence rather
1678 // than on every drawer write. The previous design called
1679 // `aggregate_status_event` from every `memory_remember` / `memory_note`
1680 // / `memory_forget` (and the matching HTTP handlers), each of which
1681 // walked the data root + opened every palace handle. Coalescing the
1682 // emit to a 30 s ticker keeps dashboards live without dragging an
1683 // O(N palaces) recompute onto the write hot path.
1684 spawn_status_event_ticker(state.clone());
1685
1686 // Capture and advertise the bound address BEFORE serving so the first
1687 // request handler — and the http_addr discovery file — see the real port
1688 // even if `local_addr()` would otherwise be racy.
1689 let local = listener.local_addr().ok();
1690 let (written_path, written_dotfile_path) = if let Some(a) = local {
1691 // Stash on state for handlers (e.g. /health) to surface.
1692 let _ = state.bound_addr.set(a);
1693 info!("HTTP server listening on http://{a}");
1694 eprintln!("HTTP server listening on http://{a}");
1695 // Primary: write to the OS-standard data dir (`~/Library/Application
1696 // Support/trusty-memory/http_addr` on macOS, `~/.local/share/…` on
1697 // Linux). This is what `trusty_common::read_daemon_addr` reads.
1698 // Best-effort: a missing $HOME or read-only fs is non-fatal.
1699 let primary = match http_addr_path() {
1700 Some(p) => match write_http_addr_file(&p, &a) {
1701 Ok(()) => {
1702 info!("wrote daemon address to {}", p.display());
1703 Some(p)
1704 }
1705 Err(e) => {
1706 tracing::warn!("could not write {}: {e}", p.display());
1707 None
1708 }
1709 },
1710 None => {
1711 tracing::warn!("no $HOME — skipping http_addr discovery file");
1712 None
1713 }
1714 };
1715 // Issue #498: also write to `~/.trusty-memory/http_addr` so external
1716 // tools (e.g. claude-mpm's `migrate_trusty_autodetect`) that read the
1717 // dotfile path can discover the daemon's port. On macOS the OS-standard
1718 // path differs from the dotfile path; writing both ensures consumers
1719 // using either convention find the file. Best-effort: failures are
1720 // logged but do not block startup.
1721 let dotfile = match dotfile_http_addr_path() {
1722 Some(p) => match write_http_addr_file(&p, &a) {
1723 Ok(()) => {
1724 info!("wrote daemon address to dotfile {}", p.display());
1725 Some(p)
1726 }
1727 Err(e) => {
1728 tracing::warn!("could not write dotfile {}: {e}", p.display());
1729 None
1730 }
1731 },
1732 None => None,
1733 };
1734 (primary, dotfile)
1735 } else {
1736 (None, None)
1737 };
1738
1739 // Keep a handle to the BM25 supervisor (if any) so we can call
1740 // `shutdown()` on the exit path. Cloning here is cheap (`Arc`) and
1741 // detaches the lifetime of the supervisor from the `state` move into
1742 // the router below.
1743 let bm25_supervisor = state.bm25_supervisor.clone();
1744
1745 let app = web::router()
1746 .route("/sse", get(sse_handler))
1747 .with_state(state);
1748
1749 // Why (issue #534): bare axum::serve exits only on an internal error; SIGTERM
1750 // (launchctl bootout) would kill the process before the cleanup below had a
1751 // chance to run, leaving stale addr/socket files behind and dropping any
1752 // in-flight request without draining. `with_graceful_shutdown` installs a
1753 // SIGTERM + SIGINT watcher; when either fires axum stops accepting new
1754 // connections, drains active requests, then returns here so cleanup runs.
1755 let serve_result = axum::serve(listener, app)
1756 .with_graceful_shutdown(trusty_common::shutdown_signal())
1757 .await;
1758
1759 // Best-effort cleanup: remove `http_addr` files so stale clients fail fast
1760 // instead of timing out against a dead port. Remove both the OS-standard
1761 // path and the dotfile path (#498).
1762 if let Some(p) = written_path.as_ref() {
1763 let _ = std::fs::remove_file(p);
1764 }
1765 if let Some(p) = written_dotfile_path.as_ref() {
1766 let _ = std::fs::remove_file(p);
1767 }
1768
1769 // Issue #193: gracefully reap every spawned BM25 daemon before the
1770 // process exits so each one gets a chance to flush its snapshot and
1771 // unlink its socket. `kill_on_drop=true` on the children would
1772 // SIGKILL them on Drop anyway, but that skips the daemon's own
1773 // shutdown sequence and leaves stale sockets behind.
1774 if let Some(supervisor) = bm25_supervisor {
1775 supervisor.shutdown().await;
1776 }
1777
1778 serve_result?;
1779 Ok(())
1780}
1781
1782/// Convenience: bind `addr` and serve via [`run_http_on`].
1783#[cfg(feature = "axum-server")]
1784pub async fn run_http(state: AppState, addr: std::net::SocketAddr) -> Result<()> {
1785 let listener = tokio::net::TcpListener::bind(addr).await?;
1786 run_http_on(state, listener).await
1787}
1788
1789/// Convenience: bind dynamically (7070..=7079, OS fallback) and serve.
1790///
1791/// Why: `trusty-memory serve` with no `--http` flag is the canonical
1792/// launchd-managed daemon entry point. Dynamic binding lets a stale daemon
1793/// or a hand-spawned `serve --http 127.0.0.1:7070` coexist without breaking
1794/// the launchd-managed instance.
1795/// What: calls [`bind_dynamic_port`] then [`run_http_on`].
1796/// Test: integration via `trusty-memory serve` + `cat ~/.trusty-memory/http_addr`.
1797#[cfg(feature = "axum-server")]
1798pub async fn run_http_dynamic(state: AppState) -> Result<()> {
1799 let listener = bind_dynamic_port().await?;
1800 run_http_on(state, listener).await
1801}
1802
1803/// Spawn a background ticker that recomputes the `data_root` disk footprint
1804/// every 10 seconds and stores it in `state.disk_bytes` (issue #35).
1805///
1806/// Why: `GET /health` reports `disk_bytes`. Walking the data directory on
1807/// every health request would turn a frequent health poll into unbounded
1808/// recursive I/O. Computing it off the request path on a fixed cadence keeps
1809/// `/health` cheap and bounds the staleness to ~10 s — fine for an
1810/// at-a-glance footprint figure.
1811/// What: spawns a detached tokio task. `AppState` is cheap to `Clone` (all
1812/// `Arc` fields), so the task holds a full clone; the daemon process lives
1813/// for the lifetime of the server anyway, so no `Weak` downgrade is needed.
1814/// Each tick runs the blocking directory walk on `spawn_blocking` so it never
1815/// stalls the async runtime, then stores the byte total atomically.
1816/// Test: `health_endpoint_includes_resource_fields` asserts the field shape;
1817/// the ticker cadence is not unit-tested (timing-dependent).
1818#[cfg(feature = "axum-server")]
1819fn spawn_disk_size_ticker(state: AppState) {
1820 tokio::spawn(async move {
1821 let mut interval = tokio::time::interval(std::time::Duration::from_secs(10));
1822 loop {
1823 interval.tick().await;
1824 let dir = state.data_root.clone();
1825 // The directory walk is blocking filesystem I/O — run it on the
1826 // blocking pool so it never parks an async worker thread.
1827 let bytes = tokio::task::spawn_blocking(move || {
1828 trusty_common::sys_metrics::dir_size_bytes(&dir)
1829 })
1830 .await
1831 .unwrap_or(0);
1832 state
1833 .disk_bytes
1834 .store(bytes, std::sync::atomic::Ordering::Relaxed);
1835 }
1836 });
1837}
1838
1839/// Interval between aggregate-status snapshot emits on the SSE bus.
1840///
1841/// Why (issue #228): mutations used to fire `StatusChanged` synchronously on
1842/// the write path, which forced an O(N palaces) sum of drawer / vector / KG
1843/// counts on every `memory_remember`. Coalescing into a fixed-cadence ticker
1844/// lets dashboards stay current (a 30 s lag is invisible at human scale)
1845/// while keeping the write path free of aggregate work.
1846/// What: 30 seconds — short enough that the operator UI doesn't feel stale
1847/// between manual writes, long enough that the recompute cost (in-memory
1848/// registry walk plus the redb `count_active_triples` per palace) is a
1849/// rounding error on the daemon's CPU budget.
1850/// Test: covered indirectly — the math has not changed, only the cadence.
1851#[allow(dead_code)]
1852const STATUS_EVENT_TICK_SECS: u64 = 30;
1853
1854/// Spawn a background ticker that emits `DaemonEvent::StatusChanged` every
1855/// [`STATUS_EVENT_TICK_SECS`] seconds (issue #228).
1856///
1857/// Why: replaces the per-write `state.emit(self.aggregate_status_event())`
1858/// call sites that used to recompute the aggregate every time a drawer was
1859/// created or deleted. Walking N palaces on every write blocks the async
1860/// runtime; coalescing the emit onto a ticker keeps dashboards up-to-date
1861/// without that cost.
1862/// What: spawns a detached tokio task that holds a full `AppState` clone
1863/// (cheap — every field is `Arc`-backed) and ticks every
1864/// [`STATUS_EVENT_TICK_SECS`] seconds. Each tick computes
1865/// `MemoryService::aggregate_status_event` (which now iterates the
1866/// in-memory registry, not disk) and broadcasts it via `state.emit`. If
1867/// no SSE subscribers are connected the broadcast `send` is a cheap no-op,
1868/// so the ticker imposes no cost when nobody is listening.
1869/// Test: not unit-tested (timing-dependent fire-and-forget); the underlying
1870/// `aggregate_status_event` math is exercised by the existing
1871/// `status_endpoint_returns_payload` path.
1872#[allow(dead_code)]
1873fn spawn_status_event_ticker(state: AppState) {
1874 tokio::spawn(async move {
1875 let mut interval =
1876 tokio::time::interval(std::time::Duration::from_secs(STATUS_EVENT_TICK_SECS));
1877 // The first tick fires immediately, which is fine: it gives SSE
1878 // subscribers a baseline `StatusChanged` shortly after they connect.
1879 loop {
1880 interval.tick().await;
1881 let event = service::MemoryService::new(state.clone()).aggregate_status_event();
1882 state.emit(event);
1883 }
1884 });
1885}
1886
1887/// Live SSE event stream — pushes `DaemonEvent` frames to dashboard clients.
1888///
1889/// Why: The dashboard subscribes once and reacts to live pushes (palace
1890/// created, drawer added/deleted, dream completed, status changed) instead of
1891/// polling `/api/v1/*` endpoints.
1892/// What: Subscribes to `state.events`, emits an initial `connected` frame,
1893/// then forwards every `DaemonEvent` as `data: <json>\n\n`. Lagged
1894/// subscribers receive a `lag` frame indicating skipped events; channel
1895/// closure ends the stream.
1896/// Test: `web::tests::sse_stream_emits_palace_created` (covers subscribe +
1897/// emit + receive); manual: `curl -N http://.../sse`.
1898#[cfg(feature = "axum-server")]
1899pub(crate) async fn sse_handler(
1900 axum::extract::State(state): axum::extract::State<AppState>,
1901) -> impl axum::response::IntoResponse {
1902 use futures::StreamExt;
1903 use tokio_stream::wrappers::BroadcastStream;
1904
1905 let rx = state.events.subscribe();
1906 let initial = futures::stream::once(async {
1907 Ok::<axum::body::Bytes, std::io::Error>(axum::body::Bytes::from(
1908 "data: {\"type\":\"connected\"}\n\n",
1909 ))
1910 });
1911 let events = BroadcastStream::new(rx).map(|res| {
1912 let frame = match res {
1913 Ok(event) => match serde_json::to_string(&event) {
1914 Ok(json) => format!("data: {json}\n\n"),
1915 Err(e) => format!("data: {{\"type\":\"error\",\"message\":\"{e}\"}}\n\n"),
1916 },
1917 Err(tokio_stream::wrappers::errors::BroadcastStreamRecvError::Lagged(n)) => {
1918 format!("data: {{\"type\":\"lag\",\"skipped\":{n}}}\n\n")
1919 }
1920 };
1921 Ok::<axum::body::Bytes, std::io::Error>(axum::body::Bytes::from(frame))
1922 });
1923 let stream = initial.chain(events);
1924
1925 axum::response::Response::builder()
1926 .header("Content-Type", "text/event-stream")
1927 .header("Cache-Control", "no-cache")
1928 .header("X-Accel-Buffering", "no")
1929 .body(axum::body::Body::from_stream(stream))
1930 .expect("valid SSE response") // Why: invariant — SSE headers are compile-time constants; builder cannot fail
1931}
1932
1933#[cfg(test)]
1934mod lib_tests;