Skip to main content

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