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