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::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/// Two-phase daemon readiness state (issues #910/#911, revised by #1970).
32///
33/// Why: The embedder cold-init (CoreML compile, 30-120 s) must never block
34/// the fast text/KG/BM25 paths that don't need it. Originally (#910/#911)
35/// this state gated a hard-error preflight that rejected every
36/// `memory_remember`/`memory_recall` call outright while `Warming` — mirrored
37/// from trusty-search's staged pipeline, #1970 replaced that with graceful
38/// degradation: writes persist immediately and defer embedding to a
39/// background task, reads return BM25 + L0/L1 results and simply omit the
40/// vector lane, all keyed off this same state.
41/// What: Two stable values stored atomically.  `Warming` (0) is the initial
42/// state; `Ready` (1) is set once the embedder has been successfully
43/// initialised by `spawn_startup_tasks`.  The transition is one-way and
44/// lock-free: a single `AtomicU8` compare-and-swap.
45/// Test: `daemon_readiness_transitions_warming_to_ready` in this module;
46///       degraded-path coverage in `tools::tests`
47///       (`remember_succeeds_and_defers_embedding_while_state_is_warming`,
48///       `recall_falls_back_to_bm25_and_l0_l1_while_warming`).
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum DaemonReadiness {
51    /// Embedder cold-init (and/or pin scan) still in progress.
52    Warming = 0,
53    /// Embedder initialised; all handlers may proceed normally.
54    Ready = 1,
55}
56
57impl DaemonReadiness {
58    /// Decode the raw atomic value.
59    ///
60    /// Why: centralises the `0 → Warming, else Ready` mapping so every
61    /// caller loads a meaningful enum rather than comparing raw integers.
62    /// What: returns `Warming` for `0`, `Ready` for any other value (only
63    /// `1` is ever written).
64    /// Test: `daemon_readiness_from_u8` in this module.
65    pub fn from_u8(v: u8) -> Self {
66        if v == 0 {
67            Self::Warming
68        } else {
69            Self::Ready
70        }
71    }
72}
73
74pub mod activity;
75pub mod attribution;
76pub mod authz;
77pub mod bm25_supervisor;
78pub mod bootstrap;
79/// Autonomous Dreamer scheduler — spawns per-palace dream loops on daemon startup.
80///
81/// Why: issue #1529 — `Dreamer::start_with_shutdown()` was fully implemented
82/// but never called. This module wires it into the daemon so each palace gets
83/// a background dream loop that fires every 5 minutes of idle time.
84/// What: exports `spawn_dream_scheduler`, `make_shutdown_watch`, and
85/// `spawn_shutdown_bridge`. Disable with `TRUSTY_DREAM_DISABLED=1`.
86/// Test: see unit tests inside this module.
87pub mod dream_scheduler;
88/// File-descriptor usage and limit reporting for `/health`.
89///
90/// Why: expose `open_fds` / `fd_soft_limit` so operators can see the fd
91/// ceiling and current consumption without needing lsof or shell access.
92/// Test: `fd_metrics::tests::fd_metrics_returns_sane_values`.
93pub mod fd_metrics;
94/// Idle-to-disk eviction ticker: periodically drops cold palace handles to
95/// bound resident RSS. Wired in `spawn_startup_tasks` next to the dream
96/// scheduler; configured via `TRUSTY_MEMORY_IDLE_EVICT_SECS`.
97pub mod idle_evict;
98// Why (issue #226): `chat` and `web` are pure axum HTTP/SSE handler
99//      surfaces. Gating them behind the `axum-server` feature is what lets
100//      library consumers (e.g. `open-mpm` linking only `MemoryMcpService`)
101//      drop axum + tower-http entirely from their build graph.
102#[cfg(feature = "axum-server")]
103pub mod chat;
104pub mod commands;
105pub mod console_metrics;
106pub mod discovery;
107/// Daemon activity events (`DaemonEvent`, `HookType`, `InjectionKind`) plus
108/// the best-effort activity-log open fallback. Split from `lib.rs` to stay
109/// under the SLOC cap (#1195); the types are re-exported at the crate root so
110/// existing `trusty_memory::DaemonEvent` paths are unchanged.
111mod events;
112/// Supervised `serve --foreground` entry point (issue #787).
113///
114/// Why: launchd supervisors need loud failure on port collision, not silent
115/// port-walking to 7071+. Extracted to stay under the 500-line ratchet cap.
116/// What: exports `bind_foreground_port` (Fix C — abort on EADDRINUSE) and
117/// `run_http_foreground` (Fix A lock + Fix B http_addr + Fix C combined).
118/// Test: `foreground::tests::bind_foreground_port_refuses_collision`;
119/// `daemon_lock` module tests cover the lock-file logic.
120pub mod foreground;
121pub mod hook_emit;
122/// HTTP/SSE serving surface (`run_http*`, `bind_dynamic_port`, address-file
123/// helpers, `sse_handler`). Split from `lib.rs` to stay under the SLOC cap
124/// (#1195); its public entry points are re-exported at the crate root so
125/// existing `trusty_memory::run_http_on` paths are unchanged.
126mod http_server;
127pub mod kg_extract;
128pub mod mcp_service;
129pub mod messaging;
130pub mod openrpc;
131/// Issue #1217: default palace-ID derivation from project identity.
132///
133/// Why: the default palace ID should reflect the project's identity
134/// (git `owner/repo`, else `parent/dir`) rather than the bare directory
135/// basename, so the same repo resolves to the same palace across checkouts.
136/// What: exports the pure `derive_palace_id` core plus
137/// `owner_repo_from_git_remote`, `parent_dir_slug`, and the
138/// `TRUSTY_MEMORY_PALACE` env-override helpers.
139/// Test: see unit tests inside this module.
140pub mod palace_id_derive;
141/// Issue #88: project-root detection and palace-slug enforcement.
142///
143/// Why: prevents unbounded palace creation by anchoring palace names to the
144/// canonical slug of the project directory that contains the CWD, or to the
145/// `personal` sentinel for non-project contexts.
146/// What: exports `find_project_root`, `project_slug_at`, `project_slug`,
147/// `validate_palace_name`, `PERSONAL_PALACE`, and `PROJECT_MARKERS`.
148/// Test: see unit tests inside this module.
149pub mod project_root;
150pub mod prompt_facts;
151pub mod prompt_log;
152pub mod service;
153pub mod startup_scan;
154pub mod tools;
155pub mod transport;
156#[cfg(feature = "axum-server")]
157pub mod web;
158
159pub use activity::{ActivityEntry, ActivityFilter, ActivityLog, ActivitySource};
160pub use attribution::{CreatorInfo, CreatorSource};
161
162// Re-export the event types so the crate's public API is unchanged after the
163// #1195 split (`trusty_memory::DaemonEvent`, etc.). `open_activity_log_with_fallback`
164// stays crate-internal but is re-exported so `AppState::new` and `lib_tests`
165// reach it by its bare name via `super::*`.
166pub(crate) use events::open_activity_log_with_fallback;
167pub use events::{DaemonEvent, HookType, InjectionKind};
168
169// Re-export the HTTP-serving surface so the crate's public API is unchanged
170// after the #1195 split (`trusty_memory::run_http_on`, etc.). The address-file
171// helpers stay crate-internal but are re-exported for `lib_tests`' `super::*`.
172pub use http_server::{
173    bind_dynamic_port, http_addr_path, is_data_dir_override_active, DEFAULT_HTTP_PORT,
174};
175#[cfg(feature = "axum-server")]
176pub use http_server::{run_http, run_http_dynamic, run_http_on};
177// These crate-internal HTTP helpers are consumed only by test modules
178// (`lib_tests`, `web::tests`), so gate the re-export on `cfg(test)` to avoid an
179// unused-import warning in the normal (non-test) build.
180#[cfg(all(test, feature = "axum-server"))]
181pub(crate) use http_server::{dotfile_http_addr_path, sse_handler, write_http_addr_file};
182
183/// Maximum bytes retained in the trigger-prompt excerpt embedded on a
184/// `HookFired` event.
185///
186/// Why: the full triggering prompt is sensitive and already lives in the
187/// JSONL prompt log; the activity feed only needs enough text to give an
188/// operator a glance — a single-line ~80 char preview matches the existing
189/// `drawer_content_preview` convention so dashboard rows render uniformly.
190/// What: 80 characters; longer prompts are truncated with a trailing `…`.
191/// Test: `hook_excerpt_truncates_long_prompts`.
192pub const HOOK_PROMPT_EXCERPT_CHARS: usize = 80;
193
194/// Reduce a triggering prompt to the short excerpt embedded on a
195/// `HookFired` activity event.
196///
197/// Why: see [`HOOK_PROMPT_EXCERPT_CHARS`]. Centralising the truncation rule
198/// keeps every emitter (HTTP, hook CLI handlers, future tests) producing
199/// the same preview shape so UI rendering is uniform.
200/// What: whitespace-collapses `prompt` and trims to
201/// [`HOOK_PROMPT_EXCERPT_CHARS`] chars with `…` when cut. Empty input
202/// returns an empty string.
203/// Test: `hook_excerpt_truncates_long_prompts`,
204/// `hook_excerpt_collapses_whitespace`.
205pub fn hook_prompt_excerpt(prompt: &str) -> String {
206    let normalised: String = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
207    if normalised.chars().count() <= HOOK_PROMPT_EXCERPT_CHARS {
208        normalised
209    } else {
210        let kept: String = normalised
211            .chars()
212            .take(HOOK_PROMPT_EXCERPT_CHARS.saturating_sub(1))
213            .collect();
214        format!("{kept}…")
215    }
216}
217
218pub use mcp_service::MemoryMcpService;
219pub use tools::MemoryMcpServer;
220
221/// Resolve the directory that actually holds the per-palace subdirectories.
222///
223/// Why: there are two on-disk layouts in the wild. The current monorepo code
224/// treats the registry directory *itself* as the parent of per-palace dirs
225/// (`<dir>/<id>/palace.json`). The legacy standalone `trusty-memory` repo
226/// nested everything one level deeper under a `palaces/` subdirectory
227/// (`<data_dir>/palaces/<id>/palace.json`) — and that is where existing
228/// installs' data lives (e.g. 88 palaces under
229/// `~/Library/Application Support/trusty-memory/palaces/`). A daemon that uses
230/// the bare data dir as its registry root finds zero palaces because every
231/// `palace.json` sits one level below where it looked — the "palaces lost on
232/// restart" bug.
233/// What: given the standard data dir, returns `<data_dir>/palaces` when that
234/// subdirectory exists, otherwise `<data_dir>` itself. Resolving this once in
235/// `main.rs` and using the result as `AppState::data_root` keeps every call
236/// site (`status`, `palace_list`, `open_palace`, `palace_create`,
237/// `load_palaces_from_disk`) consistent without forcing a data migration.
238/// Test: `tests::resolve_palace_registry_dir_prefers_palaces_subdir` and
239/// `resolve_palace_registry_dir_falls_back_to_data_dir`.
240pub fn resolve_palace_registry_dir(data_dir: PathBuf) -> PathBuf {
241    // Issue #1939: the subdir-choice logic is hoisted into trusty-common
242    // (`palace_alias::palace_registry_dir_from`) so trusty-mpm's alias-registration
243    // path and this daemon path can never disagree on WHERE the registry (and the
244    // alias file beside it) lives. This delegates to keep a single implementation.
245    trusty_common::palace_alias::palace_registry_dir_from(data_dir)
246}
247
248/// Shared application state passed to every request handler.
249///
250/// Why: The stdio loop and HTTP server need the same handles to the registry,
251/// data root, and embedder so MCP tools can perform real reads/writes against
252/// the live trusty-memory core. The embedder is heavy (loads ONNX weights) so
253/// we hold it behind a `OnceCell` and initialize lazily on first use.
254/// What: `Clone`-able via `Arc` fields. The registry / data root are eager;
255/// `embedder` is `Arc<OnceCell<Arc<FastEmbedder>>>` so concurrent first-use
256/// races resolve to a single shared instance.
257/// Test: `app_state_default_constructs` confirms construction without panic.
258#[derive(Clone)]
259pub struct AppState {
260    pub version: String,
261    pub registry: Arc<PalaceRegistry>,
262    pub data_root: PathBuf,
263    pub embedder: Arc<OnceCell<Arc<FastEmbedder>>>,
264    /// Optional default palace applied to MCP tool calls when the caller
265    /// omits the `palace` argument. Set via `trusty-memory serve --palace`.
266    pub default_palace: Option<String>,
267    /// Active chat provider selected at startup. `None` means no upstream is
268    /// configured (no Ollama detected and no OpenRouter key) — callers must
269    /// degrade gracefully (chat endpoint returns 412).
270    pub chat_provider: Arc<OnceCell<Option<Arc<dyn ChatProvider>>>>,
271    /// Per-palace chat-session stores, opened lazily so cold-start cost is
272    /// paid only when chat-history endpoints are hit.
273    pub session_stores: Arc<dashmap::DashMap<String, Arc<ChatSessionStore>>>,
274    /// Broadcast sender for live `DaemonEvent` pushes to SSE subscribers.
275    ///
276    /// Why: Lets mutating handlers emit events that any connected dashboard
277    /// receives instantly. Cap of 128 buffers transient slow readers; if a
278    /// receiver lags it gets `RecvError::Lagged` and we emit a `lag` frame.
279    pub events: Arc<broadcast::Sender<DaemonEvent>>,
280    /// Instant the daemon started, used to compute `uptime_secs` on `/health`.
281    ///
282    /// Why (issue #35): `GET /health` reports how long the daemon has been
283    /// up. Capturing a monotonic `Instant` at `AppState` construction lets the
284    /// handler compute the elapsed seconds cheaply and without a clock-skew
285    /// hazard.
286    /// What: a wall-monotonic `Instant`; `AppState::new` stamps it at startup.
287    /// Test: `health_endpoint_includes_resource_fields`.
288    pub started_at: std::time::Instant,
289    /// In-memory ring buffer of recent tracing log lines (issue #35).
290    ///
291    /// Why: the `GET /api/v1/logs/tail` endpoint serves the last N log lines
292    /// so operators can inspect a running daemon without tailing a file. The
293    /// buffer is shared between the tracing `LogBufferLayer` (writer) and the
294    /// HTTP handler (reader).
295    /// What: a cheap `Arc`-backed clone of the buffer the subscriber writes
296    /// to. Defaults to an empty buffer for states that never install the
297    /// layer (tests, the stdio path).
298    /// Test: `logs_tail_returns_recent_lines`.
299    pub log_buffer: trusty_common::log_buffer::LogBuffer,
300    /// Bug-capture ERROR store (bug-reporting #478, Phase 1).
301    ///
302    /// Why: Phase 2 MCP / HTTP endpoints need to query captured errors; stashing
303    ///      the `ErrorStore` handle here lets any handler reach it cheaply without
304    ///      a second global or per-request construction.
305    /// What: populated by `run_serve` from the `init_tracing_with_buffer_and_capture`
306    ///      result; the layer writes to this store automatically so every
307    ///      `tracing::error!` call site contributes without any changes to call
308    ///      sites. `None` in states that do not install the layer (tests, the
309    ///      stdio path).
310    /// Test: compile-presence is verified by the `trusty-memory` build; Phase 2
311    ///      will add query tests in `web.rs`.
312    pub error_store: Option<trusty_common::error_capture::ErrorStore>,
313    /// Minimal multi-tenant authorization seam (issue #1714). `false`
314    /// (single-tenant, the default) preserves today's behaviour — every
315    /// existing caller of `palace_create force=true` keeps working. `true`
316    /// opts into `authz::authorize_force_palace_create` failing closed on
317    /// every `force=true` request until a real capability check lands. Set
318    /// via `with_multi_tenant_mode_from_env` (`TRUSTY_MEMORY_MULTI_TENANT=1`);
319    /// see the `authz` module docs for the full design rationale.
320    pub multi_tenant_mode: bool,
321    /// Most recent on-disk footprint of `data_root`, in bytes (issue #35).
322    ///
323    /// Why: `GET /health` reports `disk_bytes`. Walking the data directory on
324    /// every health request would make a frequent health poll do unbounded
325    /// I/O; a background task recomputes it every 10 s and stores it here so
326    /// the handler reads it lock-free.
327    /// What: an `AtomicU64` updated by the ticker spawned in `run_http_on`.
328    /// `0` until the first walk completes.
329    /// Test: `health_endpoint_includes_resource_fields`.
330    pub disk_bytes: Arc<std::sync::atomic::AtomicU64>,
331    /// Per-process RSS + CPU sampler, refreshed on each `/health` request
332    /// (issue #35).
333    ///
334    /// Why: CPU usage is a delta between two `sysinfo` refreshes, so the
335    /// sampler must persist between requests — hence the shared `Mutex`.
336    /// What: a `tokio::sync::Mutex<SysMetrics>` so the async health handler
337    /// can sample without blocking the runtime.
338    /// Test: `health_endpoint_includes_resource_fields`.
339    pub sys_metrics: Arc<tokio::sync::Mutex<trusty_common::sys_metrics::SysMetrics>>,
340    /// HTTP listener address the daemon bound to, once `run_http_on` is running.
341    ///
342    /// Why: clients (and `/health` responses) need to advertise the live
343    /// `host:port` even though port selection happens dynamically (7070–7079
344    /// walk + OS fallback). Stashing it on `AppState` lets request handlers
345    /// surface the discovery value without re-querying the listener.
346    /// What: a `OnceLock<SocketAddr>` so `run_http_on` writes it exactly once
347    /// at bind time and every handler reads it lock-free thereafter. Empty
348    /// (`None` from `get()`) on the stdio path where no listener exists.
349    /// Test: `health_endpoint_reports_bound_addr` (added below).
350    pub bound_addr: Arc<OnceLock<SocketAddr>>,
351    /// Cached prompt-facts surface served by the MCP `get_prompt_context`
352    /// tool (issue #42).
353    ///
354    /// Why: The original session-init `prompts/get` design loaded context
355    /// once per connection; switching to a per-message tool lets the model
356    /// pull fresh, query-filtered context on demand. The cache holds both
357    /// the raw triples (for filtered lookups) and a pre-formatted Markdown
358    /// block (for the unfiltered hot path) so neither code path re-walks
359    /// the KG. The cache is rebuilt by
360    /// `prompt_facts::rebuild_prompt_cache` after any write that touches a
361    /// hot predicate (`kg_assert`, `add_alias`, `remove_prompt_fact`).
362    /// What: An `Arc<tokio::sync::RwLock<PromptFactsCache>>` so the hot
363    /// read path takes a brief read lock and clones the cache; rebuilds
364    /// take a write lock for the assignment only. The async-aware lock
365    /// (issue #229) yields to the tokio runtime instead of blocking a
366    /// runtime thread for the rebuild duration. An empty `triples` vec ↔
367    /// "no context stored yet" (the tool handler renders a hint).
368    /// Test: `get_prompt_context_returns_cached_or_hint`,
369    /// `get_prompt_context_filters_by_query`.
370    pub prompt_context_cache: Arc<RwLock<prompt_facts::PromptFactsCache>>,
371    /// Persistent activity log (issue #96).
372    ///
373    /// Why: the dashboard activity feed used to be a pure live-stream over
374    /// `/sse` — opening the UI showed an empty feed and any mutation from
375    /// the MCP path was invisible. Holding an `ActivityLog` on `AppState`
376    /// lets `emit` record an entry on every push so the
377    /// `GET /api/v1/activity` handler can return historical rows on mount
378    /// and the live SSE stream can continue prepending events on top of
379    /// the loaded history. `None` on builds that opt out (tests that use
380    /// `AppState::new` get a real log under their tempdir so behaviour
381    /// matches production).
382    /// What: an `Arc<ActivityLog>` shared with every emitter.
383    /// Test: `web::tests::activity_endpoint_lists_recent_emits`.
384    pub activity_log: Arc<ActivityLog>,
385    /// Optional per-palace BM25 lexical search lane (issue #156).
386    ///
387    /// Why: in-process BM25 would serialise the recall hot path on disk
388    /// I/O during writes and contend with the redb/usearch locks. Delegating
389    /// to the `trusty-bm25-daemon` subprocess (one socket per palace) keeps
390    /// BM25 ingestion and search off the critical path while still feeding
391    /// hits into the recall RRF fusion.
392    /// What: `Some(client)` only when `TRUSTY_BM25_DAEMON=1` at startup —
393    /// every code path that uses this field is gated on `is_some()` and
394    /// falls back to vector-only behaviour otherwise so existing deployments
395    /// see zero behavioural change.
396    /// Test: `bm25_client_disabled_by_default`,
397    /// `bm25_client_enabled_when_env_set`.
398    pub bm25_client: Option<Arc<Bm25Client>>,
399    /// Optional per-palace BM25 daemon spawn supervisor (issue #193).
400    ///
401    /// Why: without an in-process supervisor the BM25 daemon must be
402    /// launched out-of-band (launchd, manual `trusty-bm25-daemon`), which
403    /// is the same UX trap PR #190 fixed for trusty-embedderd. Holding a
404    /// supervisor here lets us spawn the daemon on first BM25 use for a
405    /// palace, restart it if it dies, and reap it on clean shutdown.
406    /// `Some` only when `TRUSTY_BM25_DAEMON=1` at startup — the same gate
407    /// that enables `bm25_client`. When set but `TRUSTY_BM25_EXTERNAL=1`,
408    /// the supervisor's `ensure_running` becomes a no-op that just returns
409    /// the canonical socket path so operators can keep using their own
410    /// process manager.
411    /// Test: covered by `bm25_supervisor_present_when_env_set` and the
412    /// `bm25_supervisor::tests` unit tests.
413    pub bm25_supervisor: Option<Arc<bm25_supervisor::Bm25Supervisor>>,
414    /// Per-palace write serialisation locks (issue #230).
415    ///
416    /// Why: the dedup gate in `tools.rs` previously read a snapshot of
417    /// existing drawers, checked for near-duplicates via Jaro-Winkler, and
418    /// then issued the write — a classic time-of-check/time-of-use race.
419    /// Two concurrent `memory_remember` calls with the same content could
420    /// both see the pre-write snapshot, both pass the gate, and both land
421    /// duplicate drawers. Serialising the gate-then-write sequence per
422    /// palace closes the window: while one task holds the mutex, any
423    /// concurrent writer for the same palace blocks until the first write
424    /// finishes and is visible to `list_drawers`. The lock is **per
425    /// palace** (not global) so writes to different palaces continue to
426    /// run in parallel.
427    /// What: a `DashMap` keyed by palace id, where each entry is an
428    /// `Arc<tokio::sync::Mutex<()>>`. The mutex is constructed lazily by
429    /// `palace_write_lock` on first access. `Arc` lets callers hold a
430    /// clone of the lock past the lifetime of the `DashMap` entry so the
431    /// map never needs to be held across an `.await`.
432    /// Test: `tools::tests::dedup_gate_blocks_concurrent_duplicate_writes`.
433    pub palace_write_locks: Arc<dashmap::DashMap<String, Arc<tokio::sync::Mutex<()>>>>,
434    /// Counter of in-flight activity-log writes spawned by `emit`
435    /// (issue #232).
436    ///
437    /// Why: `emit` offloads the synchronous redb append to the tokio blocking
438    /// pool via `spawn_blocking` so the async runtime is never parked waiting
439    /// on fsync. The write is fire-and-forget — `emit` returns immediately
440    /// after spawning. Tests that observe the activity log right after a
441    /// burst of `emit` calls need a deterministic synchronization point;
442    /// holding an in-flight counter lets `flush_activity_writes` poll until
443    /// every spawned append has settled, which keeps the assertions
444    /// race-free without forcing every caller to `.await`.
445    /// What: an `Arc<AtomicUsize>` incremented before each `spawn_blocking`
446    /// and decremented inside the closure (after the append completes, even
447    /// if it errored). The counter is cheap (one atomic add per emit) and
448    /// stays at zero in steady-state production traffic.
449    /// Test: `web::tests::activity_endpoint_lists_recent_emits` and
450    /// `tests::emit_persists_mutations_but_skips_status_changed` call
451    /// `flush_activity_writes` to drain the counter before reading the log.
452    pub pending_activity_writes: Arc<AtomicUsize>,
453    /// In-memory cache mapping palace id → `Palace.name` (issue #228).
454    ///
455    /// Why: every `memory_remember` / `memory_note` write used to call
456    /// `PalaceRegistry::list_palaces` (a synchronous filesystem walk of the
457    /// data root) just to resolve a friendly palace name for the SSE
458    /// `DrawerAdded` event. With N palaces on disk the cost was O(N) opendirs
459    /// plus `palace.json` reads on every write, blocking the async runtime.
460    /// Caching the name in-memory turns the lookup into a `DashMap::get`.
461    /// What: `DashMap<String, String>` populated by `create_palace` and
462    /// `load_palaces_from_disk`, kept in sync by rename / delete paths.
463    /// Missing entries are treated as "name unknown" so callers fall back to
464    /// the palace id and the emit path never fails.
465    /// Test: `palace_name_cache_populated_after_hydration` and
466    /// `palace_name_cache_updates_on_create`.
467    pub palace_names: Arc<dashmap::DashMap<String, String>>,
468    /// Single-pass startup pin-file map: palace id → project root path (issue #470).
469    ///
470    /// Why: after daemon startup we have no record of which on-disk project
471    /// directories correspond to which palace ids — that information only
472    /// existed inside the pin files on disk. Eager-opening every palace on
473    /// startup is too expensive. This field captures the scan-only result of
474    /// `startup_scan::scan_pin_map` so handlers that want to locate a project
475    /// by its palace id (e.g. future cwd-inference, project-health checks)
476    /// can do a single `DashMap::get` instead of a filesystem walk.
477    /// Populated once, shortly after `load_palaces_from_disk` returns, by
478    /// `spawn_startup_tasks`. Never mutated after population — it is a
479    /// snapshot of what the filesystem looked like at startup.
480    /// What: `DashMap<String (palace_id), PathBuf (project root)>`.
481    /// The outer `Arc` lets `spawn_startup_tasks` (which holds only a clone
482    /// of `AppState`) write to the same backing map that request handlers
483    /// read. Population is asynchronous so callers must treat an absent entry
484    /// as "not yet scanned" (or "no pin found"), never as "palace unknown".
485    /// Test: `startup_scan::tests::scan_pin_map_*` validate the underlying
486    /// scanner function; the wiring in `spawn_startup_tasks` is covered by
487    /// the integration-test daemon start path.
488    pub pin_project_map: Arc<dashmap::DashMap<String, PathBuf>>,
489    /// Bounded sender for the BM25 index worker (issue #231).
490    ///
491    /// Why: the previous fire-and-forget design `tokio::spawn`ed one task per
492    /// `memory_remember` / `memory_note` call, so a write burst against a slow
493    /// or unreachable BM25 daemon grew an unbounded in-flight task queue. A
494    /// single long-lived worker draining a bounded mpsc channel caps that
495    /// back-pressure: writers `try_send` (never block), full-queue requests
496    /// are dropped with a `warn!`, and the worker exits cleanly when the last
497    /// sender is dropped on shutdown.
498    /// What: an `mpsc::Sender` cloned to every `AppState` clone (cheap). The
499    /// matching receiver is consumed by the worker spawned in
500    /// [`AppState::new`] via [`tools::spawn_bm25_index_worker`]. Capacity is
501    /// [`tools::BM25_INDEX_QUEUE_CAPACITY`] (256).
502    /// Test: `bm25_index_queue_drops_when_full` exercises the full-queue
503    /// branch via `bm25_index_enqueue`.
504    pub bm25_index_tx: tokio::sync::mpsc::Sender<tools::Bm25IndexRequest>,
505    /// Cached result of the startup update check (issue #537).
506    ///
507    /// Why: `/health` should report `update_available` without hitting crates.io
508    /// on every probe. A single background check at daemon startup stores the
509    /// result here; the health handler reads it lock-free (well, a brief mutex
510    /// lock) without a network call.
511    /// What: `None` = up-to-date or check not yet done; `Some("x.y.z")` = newer
512    /// version available. The field is populated by a `tokio::spawn` in
513    /// `spawn_startup_tasks` (main.rs) after the daemon binds.
514    /// Test: indirectly by the `/health` endpoint tests in `web.rs`.
515    pub update_available: Arc<std::sync::Mutex<Option<String>>>,
516    /// Two-phase readiness state — `Warming` until the embedder is initialised,
517    /// then `Ready` (issues #910 / #911).
518    ///
519    /// Why: `AppState::embedder()` used to call `FastEmbedder::new()` without
520    /// any timeout, so the first `memory_recall`/`memory_remember` that arrived
521    /// before CoreML finished compiling would block for 5–11 hours until the
522    /// OnceCell resolved (issue #910). Exposing this state lets the preflight
523    /// guards in `tools.rs` return an explicit fast error immediately —
524    /// `"trusty-memory is warming up, retry shortly"` — instead of queueing
525    /// behind an open-ended init.
526    /// What: An `AtomicU8` starting at `DaemonReadiness::Warming` (0) and flipped
527    /// to `DaemonReadiness::Ready` (1) by `spawn_startup_tasks` after the embedder
528    /// warm-up succeeds.  The transition is one-way and lock-free.
529    /// Test: `daemon_readiness_transitions_warming_to_ready`.
530    pub daemon_readiness: Arc<AtomicU8>,
531}
532
533impl AppState {
534    /// Construct an `AppState` rooted at the given on-disk data directory.
535    ///
536    /// Why: The CLI (`serve`) and integration tests need to point the MCP
537    /// server at different roots — production at `dirs::data_dir`, tests at a
538    /// `tempfile::tempdir()`.
539    /// What: Builds an empty `PalaceRegistry`, captures the version, and
540    /// allocates an empty `OnceCell` for the embedder. `default_palace` is
541    /// `None`; use `with_default_palace` to set it.
542    /// Test: `tools::tests::dispatch_palace_create_persists` constructs an
543    /// AppState pointed at a tempdir and round-trips a palace through it.
544    pub fn new(data_root: PathBuf) -> Self {
545        let (events_tx, _) = broadcast::channel::<DaemonEvent>(128);
546        // Issue #96: open (or create) the persistent activity log under the
547        // daemon data root. Open failure is logged but never crashes the
548        // daemon — we fall back to a per-process tempdir so emits remain
549        // best-effort and the rest of the daemon keeps working.
550        let activity_log = open_activity_log_with_fallback(&data_root);
551        // Issue #231: bounded mpsc channel + single long-lived worker
552        // replaces the per-write `tokio::spawn` fire-and-forget pattern so
553        // BM25 indexing back-pressure is capped. The worker is spawned here
554        // unconditionally so the channel always has a drain — even when
555        // `bm25_client` is `None`, the worker just consumes and discards
556        // each request so senders never block on a full queue.
557        let (bm25_index_tx, bm25_index_rx) =
558            tokio::sync::mpsc::channel::<tools::Bm25IndexRequest>(tools::BM25_INDEX_QUEUE_CAPACITY);
559        // `bm25_client` / `bm25_supervisor` start as `None`; the builder
560        // `with_bm25_client_from_env` rebuilds the worker with the real
561        // client + supervisor once env-gated opt-in is resolved.
562        tools::spawn_bm25_index_worker(bm25_index_rx, None, None);
563        Self {
564            version: env!("CARGO_PKG_VERSION").to_string(),
565            // Idle-to-disk: honour TRUSTY_MEMORY_MAX_OPEN_PALACES (default 64)
566            // so operators can bound resident-palace RAM without a rebuild.
567            registry: Arc::new(PalaceRegistry::from_env()),
568            data_root,
569            embedder: Arc::new(OnceCell::new()),
570            default_palace: None,
571            chat_provider: Arc::new(OnceCell::new()),
572            session_stores: Arc::new(dashmap::DashMap::new()),
573            events: Arc::new(events_tx),
574            started_at: std::time::Instant::now(),
575            // Default to an empty buffer — `with_log_buffer` overrides this
576            // when the daemon installs the `LogBufferLayer` (HTTP mode).
577            log_buffer: trusty_common::log_buffer::LogBuffer::new(
578                trusty_common::log_buffer::DEFAULT_LOG_CAPACITY,
579            ),
580            // Bug-reporting #478: `None` until `with_error_store` is called
581            // during daemon startup (HTTP mode). Tests keep `None` so no
582            // unexpected files are written to the OS data dir.
583            error_store: None,
584            multi_tenant_mode: false,
585            disk_bytes: Arc::new(std::sync::atomic::AtomicU64::new(0)),
586            sys_metrics: Arc::new(tokio::sync::Mutex::new(
587                trusty_common::sys_metrics::SysMetrics::new(),
588            )),
589            bound_addr: Arc::new(OnceLock::new()),
590            prompt_context_cache: Arc::new(RwLock::new(prompt_facts::PromptFactsCache::default())),
591            activity_log,
592            bm25_client: None,
593            bm25_supervisor: None,
594            palace_write_locks: Arc::new(dashmap::DashMap::new()),
595            pending_activity_writes: Arc::new(AtomicUsize::new(0)),
596            palace_names: Arc::new(dashmap::DashMap::new()),
597            pin_project_map: Arc::new(dashmap::DashMap::new()),
598            bm25_index_tx,
599            update_available: Arc::new(std::sync::Mutex::new(None)),
600            // Start in Warming state; flipped to Ready by spawn_startup_tasks
601            // once the embedder warm-up succeeds (issues #910/#911).
602            daemon_readiness: Arc::new(AtomicU8::new(DaemonReadiness::Warming as u8)),
603        }
604    }
605
606    /// Acquire (lazily, then clone) the per-palace write mutex.
607    ///
608    /// Why (issue #230): the dedup-check + `remember_with_options` write
609    /// sequence in `tools.rs` must be atomic per palace to prevent two
610    /// concurrent identical writes from both passing the dedup gate.
611    /// Callers hold the returned `Arc<Mutex<()>>`'s guard across the gate
612    /// check and the write so the second writer blocks until the first
613    /// write is visible to `list_drawers`. Returning a clone of the `Arc`
614    /// rather than a borrow into the `DashMap` lets the caller `.await`
615    /// while holding the lock without risking a deadlock against any
616    /// future map mutation (DashMap shards are sync mutexes).
617    /// What: looks up the palace id in `palace_write_locks` and returns
618    /// a clone of the existing mutex; on the first call for a palace,
619    /// inserts a freshly-constructed `tokio::sync::Mutex<()>` first. The
620    /// `DashMap::entry().or_insert_with` API guarantees the lazy
621    /// construction is racy-safe — only one mutex is ever inserted per
622    /// palace id.
623    /// Test: `tools::tests::dedup_gate_blocks_concurrent_duplicate_writes`.
624    pub fn palace_write_lock(&self, palace_id: &str) -> Arc<tokio::sync::Mutex<()>> {
625        if let Some(existing) = self.palace_write_locks.get(palace_id) {
626            return existing.clone();
627        }
628        self.palace_write_locks
629            .entry(palace_id.to_string())
630            .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
631            .clone()
632    }
633
634    /// Look up a project root path by palace id in the startup pin-scan map.
635    ///
636    /// Why: provides a stable, cheap accessor so handlers do not reach directly
637    /// into the `DashMap` field and so the accessor can be mocked in future
638    /// tests without touching `AppState` internals. The map is populated
639    /// asynchronously by `spawn_startup_tasks` — an absent entry means either
640    /// the scan has not completed yet or no pin file claimed that id.
641    /// What: returns `Some(project_path)` when the palace id was found during
642    /// startup scan; `None` otherwise.
643    /// Test: covered indirectly via the startup-scan integration path; the
644    /// underlying map data is validated by `startup_scan::tests`.
645    pub fn pinned_project_path(&self, palace_id: &str) -> Option<PathBuf> {
646        self.pin_project_map.get(palace_id).map(|e| e.clone())
647    }
648
649    /// Builder-style: opt-in to the BM25 lexical lane (issue #156).
650    ///
651    /// Why: the BM25 subprocess is gated behind `TRUSTY_BM25_DAEMON=1` so
652    /// the default `cargo install trusty-memory` / launchd plist deployment
653    /// stays vector-only and existing test fixtures keep passing without
654    /// having to provision a daemon. Reading the env var here keeps the
655    /// gating logic in one place (the helper in `main.rs` just plumbs the
656    /// result through).
657    /// What: when `TRUSTY_BM25_DAEMON=1`, constructs one `Bm25Client` per
658    /// palace by lazy-resolving the socket path the first time the palace
659    /// id is observed. Currently we install a shared `default` client up
660    /// front and re-key on the palace id at the call site — palaces with no
661    /// daemon socket simply see search/index errors which we log + ignore.
662    /// Returns `self` unchanged when the env var is unset or set to anything
663    /// other than `1`.
664    /// Test: `bm25_client_disabled_by_default`,
665    /// `bm25_client_enabled_when_env_set`.
666    #[must_use]
667    pub fn with_bm25_client_from_env(mut self) -> Self {
668        if std::env::var("TRUSTY_BM25_DAEMON").as_deref() == Ok("1") {
669            // Install the default-palace client; per-palace clients are
670            // constructed on demand via `Bm25Client::for_palace`.
671            let default_palace = self.default_palace.as_deref().unwrap_or("default");
672            self.bm25_client = Some(Arc::new(Bm25Client::for_palace(default_palace)));
673            // Issue #193: hand-in-hand with the client, attach a spawn
674            // supervisor so the BM25 daemon is auto-started on first use
675            // for any palace. Operators who want to manage daemons
676            // out-of-band (launchd, systemd, manual) set
677            // TRUSTY_BM25_EXTERNAL=1 which makes the supervisor a no-op.
678            self.bm25_supervisor = Some(Arc::new(bm25_supervisor::Bm25Supervisor::new()));
679            // Issue #231: rebuild the bounded indexer channel + worker so
680            // the worker holds the now-populated client + supervisor. The
681            // placeholder worker installed by `AppState::new` (with `None`
682            // / `None`) drained the channel into the void — replacing the
683            // sender here closes the placeholder receiver and the
684            // placeholder worker exits cleanly. The new worker takes over
685            // as the sole drain for the indexer queue.
686            let (tx, rx) = tokio::sync::mpsc::channel::<tools::Bm25IndexRequest>(
687                tools::BM25_INDEX_QUEUE_CAPACITY,
688            );
689            tools::spawn_bm25_index_worker(
690                rx,
691                self.bm25_client.clone(),
692                self.bm25_supervisor.clone(),
693            );
694            self.bm25_index_tx = tx;
695            tracing::info!(
696                palace = default_palace,
697                "BM25 daemon client + spawn supervisor enabled (TRUSTY_BM25_DAEMON=1)"
698            );
699        }
700        self
701    }
702
703    /// Scan the palace registry directory and re-register every persisted
704    /// palace into the in-memory [`PalaceRegistry`].
705    ///
706    /// Why: `AppState::new` builds an *empty* registry, so after a daemon
707    /// restart `palace_list` / the dashboard reported zero palaces even though
708    /// dozens existed on disk — palace metadata was persisted by
709    /// `palace_create` but never re-hydrated on startup. This method closes
710    /// that gap by walking the on-disk layout (each subdirectory holding a
711    /// `palace.json` is one palace) and rebuilding a live `PalaceHandle` for
712    /// each, so recall paths see the full set immediately after a restart.
713    /// What: runs the blocking filesystem walk + per-palace `PalaceHandle::open`
714    /// on a `spawn_blocking` thread (so it never stalls the async runtime),
715    /// registers each successfully opened palace via `register_arc`, logs every
716    /// load at `debug!`, and returns the count loaded. A palace that fails to
717    /// open (corrupt index, unreadable `kg.db`, etc.) is logged at `warn!` and
718    /// skipped — one bad palace must not abort startup or crash the daemon.
719    /// `data_root` is expected to already be the palace registry directory —
720    /// `main.rs` resolves it via [`resolve_palace_registry_dir`] before
721    /// constructing the `AppState`, so the flat / legacy-`palaces/` layout
722    /// difference is handled exactly once.
723    /// Test: `tests::load_palaces_from_disk_rehydrates_registry` writes two
724    /// palaces into a tempdir, constructs an `AppState`, calls this method, and
725    /// asserts the returned count and registry contents.
726    pub async fn load_palaces_from_disk(&self) -> Result<usize> {
727        let registry_dir = self.data_root.clone();
728        let registry = self.registry.clone();
729        let palace_names = self.palace_names.clone();
730        // The directory walk and each `PalaceHandle::open` perform blocking
731        // filesystem + redb/usearch I/O — run the whole hydration on the
732        // blocking pool so it never parks an async worker thread.
733        let count = tokio::task::spawn_blocking(move || -> Result<usize> {
734            let palaces = PalaceRegistry::list_palaces(&registry_dir)?;
735            let total = palaces.len();
736            let mut loaded = 0usize;
737            let mut skipped = 0usize;
738            for palace in palaces {
739                match trusty_common::memory_core::PalaceHandle::open(&palace) {
740                    Ok(handle) => {
741                        tracing::debug!(
742                            palace = %palace.id,
743                            data_dir = %palace.data_dir.display(),
744                            "loaded palace from disk"
745                        );
746                        // Issue #228: seed the in-memory name cache so write
747                        // hot paths (memory_remember / memory_note) can resolve
748                        // the friendly palace name without re-walking the data
749                        // root. Insert here (during hydration) is the single
750                        // point of truth for restart-time population.
751                        palace_names.insert(palace.id.0.clone(), palace.name.clone());
752                        registry.register_arc(handle);
753                        loaded += 1;
754                    }
755                    Err(e) => {
756                        // Why (issue #467): a single bad palace (corrupt kg.db,
757                        // stale WAL, EMFILE — "Too many open files", permissions)
758                        // must never abort startup or block the HTTP server from
759                        // binding. Log per-palace and keep going; the summary
760                        // below tells operators how many were skipped without
761                        // trawling the log.
762                        // The palace is NOT registered in the in-memory registry,
763                        // so the next `open_palace` call for this id will attempt
764                        // a fresh open from disk — the lazy-reopen path. If the
765                        // root cause was EMFILE and the fd-limit fix (#462) raised
766                        // the soft limit to 8192, that first request will succeed.
767                        tracing::warn!(
768                            palace = %palace.id,
769                            data_dir = %palace.data_dir.display(),
770                            "skipping palace during startup hydration: {e:#}; \
771                             will retry lazily on first access"
772                        );
773                        skipped += 1;
774                    }
775                }
776            }
777            tracing::info!(
778                "palace hydration summary: loaded {loaded}/{total} ({skipped} skipped due to errors)"
779            );
780            Ok(loaded)
781        })
782        .await
783        .map_err(|e| anyhow::anyhow!("join load_palaces_from_disk: {e}"))??;
784        Ok(count)
785    }
786
787    /// Builder-style: attach the daemon's shared [`LogBuffer`] so the
788    /// `GET /api/v1/logs/tail` endpoint serves the same lines the tracing
789    /// subscriber captures (issue #35).
790    ///
791    /// Why: `main` builds the buffer (via `init_tracing_with_buffer`) before
792    /// constructing the `AppState`, then hands a clone here so the HTTP
793    /// handler and the tracing layer observe the same ring.
794    /// What: replaces the empty default buffer with the supplied one.
795    /// Test: `logs_tail_returns_recent_lines`.
796    #[must_use]
797    pub fn with_log_buffer(mut self, buffer: trusty_common::log_buffer::LogBuffer) -> Self {
798        self.log_buffer = buffer;
799        self
800    }
801
802    /// Builder-style: mark this daemon as the sole palace writer so palace
803    /// redb files open with `OpenIntent::Writer` (issue #1487).
804    ///
805    /// Why: The HTTP daemon owns the write lock on every palace's `kg.redb`
806    /// and `index.usearch.redb`. Before this fix, when a *second* daemon
807    /// instance opened the same store it silently degraded to a read-only
808    /// snapshot and rejected every `memory_remember` for its lifetime —
809    /// effectively silent data loss when an MCP client routed a write to the
810    /// rogue instance. Opening as `Writer` makes the second instance fail
811    /// loud (after a short handoff-retry window that absorbs a graceful
812    /// launchd `bootout`→`bootstrap` overlap) instead of serving broken
813    /// reads-only. CLI, stdio-proxy, and test code paths never call this, so
814    /// they keep the snapshot read-fallback (issue #59).
815    /// What: Replaces `self.registry` with a fresh `PalaceRegistry` carrying
816    /// `OpenIntent::Writer`.
817    ///
818    /// Invariant: MUST be called on a fresh, unhydrated, unshared registry —
819    /// during startup, before `spawn_startup_tasks`/`load_palaces_from_disk`
820    /// registers any `PalaceHandle` and before the `AppState` (hence its
821    /// `Arc<PalaceRegistry>`) is cloned to a handler. Replacing the registry
822    /// discards the prior `Arc`; doing so after hydration would silently drop
823    /// live handles (data loss), and doing so after the state is shared would
824    /// leave other clones on the stale read-only registry. The guard is a
825    /// `debug_assert!` on the strongest cheap signals the registry exposes —
826    /// `is_empty()` (no handles hydrated) and `Arc::strong_count == 1` (not yet
827    /// shared) — so an ordering violation fails fast as the programmer error it
828    /// is (the call site is startup-only and fixed). Release builds elide the
829    /// assert; the real call site (`run_serve`) always satisfies it.
830    /// Test: `with_writer_intent_marks_registry_writer` and
831    /// `with_writer_intent_panics_on_hydrated_registry` in `lib_tests`.
832    #[must_use]
833    pub fn with_writer_intent(mut self) -> Self {
834        // Fail fast on an ordering bug: a hydrated registry (`!is_empty`) or a
835        // shared one (`strong_count > 1`) would silently drop live handles or
836        // strand other clones on the stale read-only registry (issue #1487).
837        debug_assert!(self.registry.is_empty() && Arc::strong_count(&self.registry) == 1);
838        // Idle-to-disk: preserve the configurable open-handle cap
839        // (TRUSTY_MEMORY_MAX_OPEN_PALACES) while marking the registry a writer.
840        self.registry = Arc::new(PalaceRegistry::from_env().with_writer_intent());
841        self
842    }
843
844    /// Builder-style: attach the bug-capture `ErrorStore` handle (bug-reporting #478).
845    ///
846    /// Why: Phase 2 MCP / HTTP endpoints need a handle to the in-memory error
847    ///      ring so they can serve `recent_errors` / `errors_by_fingerprint`
848    ///      without disk I/O on the hot path. Installing it here — rather than
849    ///      adding it as a separate global — keeps the state graph explicit and
850    ///      lets tests skip it by never calling this method.
851    /// What: stores `Some(store)` in `AppState::error_store`; the `BugCaptureLayer`
852    ///      that writes to this store is already installed in the tracing
853    ///      subscriber by `init_tracing_with_buffer_and_capture`. The store is
854    ///      `Clone` (cheap `Arc` clone internally) so both the layer and this
855    ///      field share the same underlying ring.
856    /// Test: Phase 2 will add `error_store_captures_and_queries` in `web.rs`.
857    #[must_use]
858    pub fn with_error_store(mut self, store: trusty_common::error_capture::ErrorStore) -> Self {
859        self.error_store = Some(store);
860        self
861    }
862
863    /// Builder-style: opt into multi-tenant authorization mode (issue #1714).
864    ///
865    /// Why: mirrors `with_bm25_client_from_env`'s pattern of keeping env-var
866    /// gating in one place. Unset (the default) preserves today's
867    /// single-tenant behaviour with zero change for existing callers.
868    /// What: sets `multi_tenant_mode` from `TRUSTY_MEMORY_MULTI_TENANT=1`; see
869    /// the `authz` module for what the flag then enforces.
870    /// Test: `authorize_force_palace_create_denies_multi_tenant_without_capability`.
871    #[must_use]
872    pub fn with_multi_tenant_mode_from_env(mut self) -> Self {
873        self.multi_tenant_mode = std::env::var("TRUSTY_MEMORY_MULTI_TENANT").as_deref() == Ok("1");
874        self
875    }
876
877    /// Send a `DaemonEvent` to all connected SSE subscribers and persist
878    /// it to the activity log when the variant carries a source.
879    ///
880    /// Why: Mutating handlers call this after a successful write so the
881    /// dashboard can update without polling. The send is best-effort —
882    /// `broadcast::Sender::send` returns `Err` only when there are no live
883    /// receivers, which is fine (no listeners == no work to do). Issue
884    /// #96 additionally writes the entry to the persistent activity log
885    /// so the feed can serve historical rows on page load and so MCP /
886    /// HTTP / Hook origins are visible to the operator. Persistence is
887    /// also best-effort — a write failure is logged but never blocks the
888    /// SSE broadcast.
889    ///
890    /// Issue #232: the activity-log append is a synchronous redb write +
891    /// fsync. Calling it directly on the async caller's task parked a tokio
892    /// worker thread on disk I/O for every SSE event. We now offload the
893    /// append to the blocking thread pool via `spawn_blocking` and return
894    /// immediately — `emit` stays synchronous so every existing caller
895    /// (including the sync `dispatch_hook_fired` JSON-RPC handler) keeps
896    /// compiling unchanged. The fire-and-forget pattern matches the
897    /// pre-fix semantics (best-effort, never blocks the SSE broadcast)
898    /// while freeing the async runtime to do real work during the write.
899    /// What: serialises the event for the log (skipping `StatusChanged`
900    /// which is a recomputed aggregate, not a mutation), spawns the redb
901    /// append on `tokio::task::spawn_blocking` keyed by a clone of the
902    /// `Arc<ActivityLog>` and the cloned event, then sends the event over
903    /// the broadcast channel. A `pending_activity_writes` counter is bumped
904    /// before the spawn and decremented inside the closure so
905    /// [`Self::flush_activity_writes`] can drain in tests.
906    /// Test: `web::tests::sse_stream_receives_palace_created` confirms a
907    /// subscriber observes the emitted event;
908    /// `activity_endpoint_lists_recent_emits` confirms persistence via
909    /// `flush_activity_writes`.
910    pub fn emit(&self, event: DaemonEvent) {
911        if let Some(source) = event.source() {
912            let event_type = event.type_str();
913            let palace_id = event.palace_id().map(|s| s.to_string());
914            let log = Arc::clone(&self.activity_log);
915            let event_for_log = event.clone();
916            let pending = Arc::clone(&self.pending_activity_writes);
917            // Pre-allocate the sequence id in the emitting thread so the
918            // persisted order matches the emission order even when blocking-pool
919            // workers execute the writes concurrently (issue #247). Without
920            // this, four rapid emits would assign IDs inside their respective
921            // `spawn_blocking` closures in a non-deterministic order.
922            let id = log.alloc_id();
923            pending.fetch_add(1, Ordering::SeqCst);
924            // Why: the synchronous redb append + fsync must not park an
925            // async worker thread (issue #232). Spawn the write on the
926            // blocking pool; the JoinHandle is intentionally dropped —
927            // the write is best-effort and any failure is logged below.
928            tokio::task::spawn_blocking(move || {
929                let result = log.append_with_id(id, source, palace_id, event_type, &event_for_log);
930                if let Err(e) = result {
931                    tracing::warn!("activity_log.append failed for {event_type}: {e:#}");
932                }
933                pending.fetch_sub(1, Ordering::SeqCst);
934            });
935        }
936        let _ = self.events.send(event);
937    }
938
939    /// Block (asynchronously) until every in-flight activity-log write
940    /// spawned by [`Self::emit`] has settled.
941    ///
942    /// Why: `emit` offloads its redb append to `tokio::task::spawn_blocking`
943    /// and returns immediately (issue #232). Tests that observe the
944    /// activity log right after a burst of emits would otherwise race the
945    /// blocking-pool worker; this helper gives them a deterministic
946    /// synchronization point. Production code never needs to call this —
947    /// the dashboard reads through `GET /api/v1/activity`, which already
948    /// tolerates writes settling asynchronously.
949    /// What: spins on `pending_activity_writes` with a 1 ms yield until the
950    /// counter is zero. Cheap: tests typically emit a handful of events
951    /// and the loop exits within a single scheduler tick.
952    /// Test: covered indirectly by `emit_persists_mutations_but_skips_status_changed`
953    /// and `web::tests::activity_endpoint_lists_recent_emits`.
954    pub async fn flush_activity_writes(&self) {
955        while self.pending_activity_writes.load(Ordering::SeqCst) > 0 {
956            tokio::time::sleep(std::time::Duration::from_millis(1)).await;
957        }
958    }
959
960    /// Open (or return cached) the chat-session store for a palace.
961    ///
962    /// Why: Chat session persistence lives in a dedicated redb file under
963    /// the palace's data dir (`chat_sessions.redb`) so it doesn't intermingle
964    /// with the KG's transactional load. The store is cheap to clone via
965    /// `Arc` but the underlying connection should be reused, so cache by id.
966    /// What: Creates the palace data dir if missing, opens (or reuses) a
967    /// `ChatSessionStore` and stashes an `Arc` in the DashMap.
968    /// Test: Indirectly via the session HTTP handlers in `web::tests`.
969    pub fn session_store(&self, palace_id: &str) -> Result<Arc<ChatSessionStore>> {
970        if let Some(entry) = self.session_stores.get(palace_id) {
971            return Ok(entry.clone());
972        }
973        let dir = self.data_root.join(palace_id);
974        std::fs::create_dir_all(&dir)
975            .map_err(|e| anyhow::anyhow!("create palace dir {}: {e}", dir.display()))?;
976        let store = Arc::new(ChatSessionStore::open(&dir.join("chat_sessions.db"))?);
977        self.session_stores
978            .insert(palace_id.to_string(), store.clone());
979        Ok(store)
980    }
981
982    /// Builder-style setter for the default palace name.
983    ///
984    /// Why: `serve --palace <name>` wants to bind every tool call to a
985    /// project-scoped namespace without forcing every MCP request to repeat
986    /// the palace argument.
987    /// What: Returns `self` with `default_palace = Some(name)`.
988    /// Test: `default_palace_used_when_arg_omitted` covers the resolution
989    /// path; this setter is exercised there.
990    pub fn with_default_palace(mut self, name: Option<String>) -> Self {
991        self.default_palace = name;
992        self
993    }
994
995    /// Resolve (or initialize) the shared embedder.
996    ///
997    /// Why: FastEmbedder load is expensive — we share one instance across all
998    /// tool calls; the `OnceCell` ensures concurrent first-use races collapse
999    /// to a single load.
1000    /// What: Returns `Arc<FastEmbedder>` on success. Errors propagate from the
1001    /// underlying ONNX load.
1002    /// Test: Indirectly via `dispatch_remember_then_recall`.
1003    /// Resolve the active chat provider, auto-detecting on first call.
1004    ///
1005    /// Why: Provider selection depends on filesystem-loaded config plus a
1006    /// network probe (Ollama liveness), so it must be lazily initialised at
1007    /// runtime. Caching the choice in a `OnceCell` keeps it stable across
1008    /// concurrent requests without re-probing on every chat call.
1009    /// What: On first use loads `~/.trusty-memory/config.toml`, prefers an
1010    /// auto-detected Ollama instance (when `local_model.enabled`), and falls
1011    /// back to OpenRouter when an API key is set. Returns `Ok(None)` when
1012    /// neither is available so the caller can emit a 412.
1013    /// Test: `web::tests::providers_endpoint_returns_payload` covers the
1014    /// detection path indirectly through `/api/v1/chat/providers`.
1015    pub async fn chat_provider(&self) -> Option<Arc<dyn ChatProvider>> {
1016        self.chat_provider
1017            .get_or_init(|| async {
1018                // Why (issue #226): `service::load_user_config` is the
1019                //      axum-free home of the loader; the `web::load_user_config`
1020                //      re-export only exists for the HTTP handlers. Going
1021                //      direct to `service` keeps this method usable when
1022                //      the `axum-server` feature is disabled.
1023                let cfg = crate::service::load_user_config().unwrap_or_default();
1024                if cfg.local_model.enabled {
1025                    if let Some(mut p) =
1026                        trusty_common::auto_detect_local_provider(&cfg.local_model.base_url).await
1027                    {
1028                        // auto_detect returns an empty model id; callers must
1029                        // set the configured model name themselves.
1030                        p.model = cfg.local_model.model.clone();
1031                        return Some(Arc::new(p) as Arc<dyn ChatProvider>);
1032                    }
1033                }
1034                if !cfg.openrouter_api_key.is_empty() {
1035                    return Some(Arc::new(trusty_common::OpenRouterProvider::new(
1036                        cfg.openrouter_api_key,
1037                        cfg.openrouter_model,
1038                    )) as Arc<dyn ChatProvider>);
1039                }
1040                None
1041            })
1042            .await
1043            .clone()
1044    }
1045
1046    /// Spawn a fire-and-forget background task that auto-discovers project
1047    /// aliases under `project_root` and asserts new ones into `palace`.
1048    ///
1049    /// Why (issue #42): Projects carry implicit shorthand — cargo package
1050    /// names that differ from their directory, binary names that differ
1051    /// from packages, first-letter abbreviations — that should be surfaced
1052    /// without a user ever calling `add_alias`. Running discovery as a
1053    /// detached task on palace-open keeps startup latency unchanged: the
1054    /// daemon binds and starts serving immediately while the discovery scan
1055    /// completes in the background, and any newly-asserted aliases land in
1056    /// the prompt cache before the model's next `get_prompt_context` call.
1057    /// What: clones `self` (cheap; `Arc`-backed), spawns a tokio task that
1058    /// invokes the `discover_aliases` tool handler directly so the
1059    /// dedup + cache-rebuild logic runs exactly the same path as the MCP
1060    /// tool call. Errors are logged at `warn!`; one failed discovery never
1061    /// destabilises the daemon.
1062    /// Test: not unit-tested (timing-dependent fire-and-forget); the
1063    /// underlying `discover_aliases` dispatch is covered by
1064    /// `dispatch_discover_aliases_inserts_new_and_dedupes` in `tools::tests`.
1065    pub fn spawn_alias_discovery(&self, palace: String, project_root: PathBuf) {
1066        let state = self.clone();
1067        tokio::spawn(async move {
1068            let args = serde_json::json!({
1069                "palace": palace,
1070                "project_root": project_root.to_string_lossy(),
1071            });
1072            match tools::dispatch_tool(&state, "discover_aliases", args).await {
1073                Ok(result) => tracing::info!(
1074                    new = ?result.get("new"),
1075                    already_known = ?result.get("already_known"),
1076                    "alias discovery complete"
1077                ),
1078                Err(e) => tracing::warn!("alias discovery failed: {e:#}"),
1079            }
1080        });
1081    }
1082
1083    /// Return the current readiness state.
1084    ///
1085    /// Why: tool handlers and the `/health` endpoint need a cheap, lock-free
1086    /// way to check whether the embedder has been initialised yet.
1087    /// What: loads `daemon_readiness` with `Acquire` ordering so the caller
1088    /// sees all writes the startup task made before setting the state.
1089    /// Test: `daemon_readiness_transitions_warming_to_ready`.
1090    pub fn readiness(&self) -> DaemonReadiness {
1091        DaemonReadiness::from_u8(self.daemon_readiness.load(Ordering::Acquire))
1092    }
1093
1094    /// Flip the readiness state from `Warming` to `Ready`.
1095    ///
1096    /// Why: called by `spawn_startup_tasks` in `main.rs` once the embedder
1097    /// warm-up succeeds — this is the single state-transition site.
1098    /// What: `store(Ready, Release)` so subsequent `Acquire` loads in handlers
1099    /// observe a consistent state.  Idempotent: calling it multiple times is
1100    /// harmless.
1101    /// Test: `daemon_readiness_transitions_warming_to_ready`.
1102    pub fn set_ready(&self) {
1103        self.daemon_readiness
1104            .store(DaemonReadiness::Ready as u8, Ordering::Release);
1105    }
1106
1107    /// Obtain the shared `FastEmbedder` instance, initialising it on first call.
1108    ///
1109    /// Why: centralises lazy embedder access so every tool handler goes through
1110    /// one bounded init path (tracks #910 internally).
1111    /// What: wraps `OnceCell::get_or_try_init` with a timeout so a slow
1112    /// CoreML/CUDA first-compile cannot block a handler indefinitely.  On
1113    /// timeout the `OnceCell` is left unresolved and the next caller retries.
1114    ///
1115    /// **Callers on the request path SHOULD check `readiness()` before this
1116    /// method** (issue #1970) — every recall handler now checks
1117    /// `readiness() == Ready` first and only calls `embedder()` on that
1118    /// branch, falling back to a BM25/L0/L1-only path while `Warming` instead
1119    /// of paying this method's cold-init cost. Reaching this method while
1120    /// still `Warming` is not a bug (the warm-up task itself calls
1121    /// `embedder()` while in `Warming` state), just unusual on the request
1122    /// path.
1123    ///
1124    /// This timeout is a backstop against a pathological init delay (e.g. the
1125    /// warm-up task's own call, or a handler that skips the `readiness()`
1126    /// check). If this timeout fires the `OnceCell` is left in the unresolved
1127    /// state and the next call retries from scratch.
1128    pub async fn embedder(&self) -> Result<Arc<FastEmbedder>> {
1129        use trusty_common::memory_core::timeouts;
1130        let cell = self.embedder.clone();
1131        let timeout = timeouts::embedder_init_timeout();
1132        let embedder = tokio::time::timeout(
1133            timeout,
1134            cell.get_or_try_init(|| async {
1135                let e = FastEmbedder::new().await?;
1136                Ok::<Arc<FastEmbedder>, anyhow::Error>(Arc::new(e))
1137            }),
1138        )
1139        .await
1140        .map_err(|_| {
1141            anyhow::anyhow!(
1142                "AppState::embedder() timed out after {:?}; \
1143                 the CoreML/CUDA model is taking unusually long to compile — \
1144                 increase TRUSTY_EMBEDDER_INIT_TIMEOUT_SECS if needed",
1145                timeout
1146            )
1147        })??
1148        .clone();
1149        Ok(embedder)
1150    }
1151}
1152
1153impl std::fmt::Debug for AppState {
1154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1155        f.debug_struct("AppState")
1156            .field("version", &self.version)
1157            .field("data_root", &self.data_root)
1158            .field("registry_len", &self.registry.len())
1159            .finish()
1160    }
1161}
1162
1163/// Handle a single MCP JSON-RPC message and produce its response.
1164///
1165/// Why: Pulled out of the stdio loop so unit tests can drive every method
1166/// without touching real stdin/stdout.
1167/// What: Routes `initialize`, `tools/list`, `tools/call`, `ping`, and the
1168/// `notifications/initialized` notification (which returns `Value::Null`).
1169/// Test: See unit tests below — initialize/list/call all return expected
1170/// JSON-RPC envelopes; notifications return `Null` (no response written).
1171pub async fn handle_message(state: &AppState, msg: Value) -> Value {
1172    let id = msg.get("id").cloned().unwrap_or(Value::Null);
1173    let method = msg.get("method").and_then(|m| m.as_str()).unwrap_or("");
1174
1175    match method {
1176        "initialize" => {
1177            let extra = state
1178                .default_palace
1179                .as_ref()
1180                .map(|dp| json!({ "default_palace": dp }));
1181            let result = initialize_response("trusty-memory", &state.version, extra);
1182            // Why (issue #42): prompt-facts now flow through the
1183            // per-message `get_prompt_context` tool rather than MCP
1184            // prompts, so we no longer advertise the `prompts` capability.
1185            json!({
1186                "jsonrpc": "2.0",
1187                "id": id,
1188                "result": result,
1189            })
1190        }
1191        // Notifications must NOT receive a response.
1192        "notifications/initialized" | "notifications/cancelled" => Value::Null,
1193        "tools/list" => json!({
1194            "jsonrpc": "2.0",
1195            "id": id,
1196            "result": tools::tool_definitions_with(state.default_palace.is_some())
1197        }),
1198        // OpenRPC 1.3.2 discovery — see `openrpc.rs`. Returns the full
1199        // service description so orchestrators (open-mpm, etc.) can
1200        // introspect every tool and its required `memory.read`/`memory.write`
1201        // scope without bespoke per-server adapters.
1202        "rpc.discover" => json!({
1203            "jsonrpc": "2.0",
1204            "id": id,
1205            "result": openrpc::build_discover_response(
1206                &state.version,
1207                state.default_palace.is_some(),
1208            ),
1209        }),
1210        "tools/call" => {
1211            let params = msg.get("params").cloned().unwrap_or_default();
1212            let tool_name = params
1213                .get("name")
1214                .and_then(|n| n.as_str())
1215                .unwrap_or("")
1216                .to_string();
1217            let args = params.get("arguments").cloned().unwrap_or_default();
1218            match tools::dispatch_tool(state, &tool_name, args).await {
1219                Ok(content) => {
1220                    // Why: tools that return a bare JSON string (e.g.
1221                    // `get_prompt_context` returning the formatted
1222                    // Markdown block) should surface as plain text in the
1223                    // MCP `content[0].text` field — wrapping in
1224                    // `Value::to_string()` would re-quote the payload and
1225                    // force every caller to strip outer quotes.
1226                    let text = match &content {
1227                        Value::String(s) => s.clone(),
1228                        other => other.to_string(),
1229                    };
1230                    json!({
1231                        "jsonrpc": "2.0",
1232                        "id": id,
1233                        "result": {
1234                            "content": [{"type": "text", "text": text}]
1235                        }
1236                    })
1237                }
1238                Err(e) => json!({
1239                    "jsonrpc": "2.0",
1240                    "id": id,
1241                    // Why: anyhow's `{:#}` alternate format walks the full
1242                    // `Caused by:` chain so MCP clients see actionable
1243                    // detail (e.g. "PalaceHandle::remember_with_options:
1244                    // filter rejected: too short") instead of just the
1245                    // outermost context label.
1246                    "error": {"code": -32603, "message": format!("{e:#}")}
1247                }),
1248            }
1249        }
1250        "ping" => json!({"jsonrpc": "2.0", "id": id, "result": {}}),
1251        _ => json!({
1252            "jsonrpc": "2.0",
1253            "id": id,
1254            "error": {
1255                "code": -32601,
1256                "message": format!("Method not found: {method}")
1257            }
1258        }),
1259    }
1260}
1261
1262#[cfg(test)]
1263mod lib_tests;