Skip to main content

trusty_memory/
lib.rs

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