Skip to main content

trusty_memory/
lib.rs

1//! MCP server (HTTP/SSE + UDS) for trusty-memory.
2//!
3//! Why: Claude Code and other MCP-aware clients integrate with trusty-memory
4//! through the standardized Model Context Protocol; we expose memory + KG
5//! tools so they can be called by name. Claude Code itself speaks stdio,
6//! but the in-process `serve --stdio` path was removed in issue #150
7//! because it deadlocked on the redb exclusive write lock whenever a
8//! long-lived daemon was already running — the canonical stdio integration
9//! is now the `trusty-memory-mcp-bridge` binary (PR #149), which pipes
10//! Claude Code's stdio over a Unix domain socket to the daemon.
11//! What: Provides `run_http` / `run_http_dynamic` / `run_http_on` (axum
12//! HTTP/SSE + REST + UI) and the `transport::uds` module (Unix-domain
13//! socket transport for the MCP bridge), plus an `AppState` that carries
14//! the shared `PalaceRegistry`, on-disk data root, and a lazily-initialized
15//! embedder.
16//! Test: `cargo test -p trusty-memory` validates handshake + dispatch via
17//! the in-process `handle_message` unit tests and the `tests/uds_roundtrip.rs`
18//! end-to-end harness.
19
20use anyhow::Result;
21use serde_json::{json, Value};
22use std::net::SocketAddr;
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicUsize, Ordering};
25use std::sync::{Arc, OnceLock};
26use tokio::sync::{broadcast, OnceCell, RwLock};
27use trusty_common::bm25_client::Bm25Client;
28use trusty_common::mcp::initialize_response;
29use trusty_common::memory_core::embed::FastEmbedder;
30use trusty_common::memory_core::store::ChatSessionStore;
31use trusty_common::memory_core::PalaceRegistry;
32use trusty_common::ChatProvider;
33
34// Why: `tracing::info` is only used by the axum HTTP-serving helpers
35//      (`run_http_on`, `spawn_uds_listener`). Pulling it in unconditionally
36//      would trigger `unused_imports` warnings when the `axum-server`
37//      feature is disabled. `SocketAddr` is still used by `bound_addr` on
38//      `AppState` so it stays unconditional.
39#[cfg(feature = "axum-server")]
40use tracing::info;
41
42pub mod activity;
43pub mod attribution;
44pub mod bm25_supervisor;
45pub mod bootstrap;
46/// File-descriptor usage and limit reporting for `/health`.
47///
48/// Why: expose `open_fds` / `fd_soft_limit` so operators can see the fd
49/// ceiling and current consumption without needing lsof or shell access.
50/// Test: `fd_metrics::tests::fd_metrics_returns_sane_values`.
51pub mod fd_metrics;
52// Why (issue #226): `chat` and `web` are pure axum HTTP/SSE handler
53//      surfaces. Gating them behind the `axum-server` feature is what lets
54//      library consumers (e.g. `open-mpm` linking only `MemoryMcpService`)
55//      drop axum + tower-http entirely from their build graph.
56#[cfg(feature = "axum-server")]
57pub mod chat;
58pub mod commands;
59pub mod discovery;
60pub mod hook_emit;
61pub mod kg_extract;
62pub mod mcp_service;
63pub mod messaging;
64pub mod openrpc;
65/// Issue #88: project-root detection and palace-slug enforcement.
66///
67/// Why: prevents unbounded palace creation by anchoring palace names to the
68/// canonical slug of the project directory that contains the CWD, or to the
69/// `personal` sentinel for non-project contexts.
70/// What: exports `find_project_root`, `project_slug_at`, `project_slug`,
71/// `validate_palace_name`, `PERSONAL_PALACE`, and `PROJECT_MARKERS`.
72/// Test: see unit tests inside this module.
73pub mod project_root;
74pub mod prompt_facts;
75pub mod prompt_log;
76pub mod service;
77/// Single-pass startup pin-file scanner (issue #470).
78///
79/// Why: builds the `palace_id → project_path` map at daemon startup without
80/// eager palace opens. One readdir sweep over the standard search roots is
81/// cheaper than the O(#palaces) per-id loop used by the doctor path and runs
82/// before the first HTTP request arrives.
83/// What: exports `scan_pin_map` and `default_search_dirs`.
84/// Test: see `startup_scan::tests`.
85pub mod startup_scan;
86pub mod tools;
87pub mod transport;
88#[cfg(feature = "axum-server")]
89pub mod web;
90
91pub use activity::{ActivityEntry, ActivityFilter, ActivityLog, ActivitySource};
92pub use attribution::{CreatorInfo, CreatorSource};
93
94/// Maximum bytes retained in the trigger-prompt excerpt embedded on a
95/// `HookFired` event.
96///
97/// Why: the full triggering prompt is sensitive and already lives in the
98/// JSONL prompt log; the activity feed only needs enough text to give an
99/// operator a glance — a single-line ~80 char preview matches the existing
100/// `drawer_content_preview` convention so dashboard rows render uniformly.
101/// What: 80 characters; longer prompts are truncated with a trailing `…`.
102/// Test: `hook_excerpt_truncates_long_prompts`.
103pub const HOOK_PROMPT_EXCERPT_CHARS: usize = 80;
104
105/// Reduce a triggering prompt to the short excerpt embedded on a
106/// `HookFired` activity event.
107///
108/// Why: see [`HOOK_PROMPT_EXCERPT_CHARS`]. Centralising the truncation rule
109/// keeps every emitter (HTTP, hook CLI handlers, future tests) producing
110/// the same preview shape so UI rendering is uniform.
111/// What: whitespace-collapses `prompt` and trims to
112/// [`HOOK_PROMPT_EXCERPT_CHARS`] chars with `…` when cut. Empty input
113/// returns an empty string.
114/// Test: `hook_excerpt_truncates_long_prompts`,
115/// `hook_excerpt_collapses_whitespace`.
116pub fn hook_prompt_excerpt(prompt: &str) -> String {
117    let normalised: String = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
118    if normalised.chars().count() <= HOOK_PROMPT_EXCERPT_CHARS {
119        normalised
120    } else {
121        let kept: String = normalised
122            .chars()
123            .take(HOOK_PROMPT_EXCERPT_CHARS.saturating_sub(1))
124            .collect();
125        format!("{kept}…")
126    }
127}
128
129pub use mcp_service::MemoryMcpService;
130pub use tools::MemoryMcpServer;
131
132/// Resolve the directory that actually holds the per-palace subdirectories.
133///
134/// Why: there are two on-disk layouts in the wild. The current monorepo code
135/// treats the registry directory *itself* as the parent of per-palace dirs
136/// (`<dir>/<id>/palace.json`). The legacy standalone `trusty-memory` repo
137/// nested everything one level deeper under a `palaces/` subdirectory
138/// (`<data_dir>/palaces/<id>/palace.json`) — and that is where existing
139/// installs' data lives (e.g. 88 palaces under
140/// `~/Library/Application Support/trusty-memory/palaces/`). A daemon that uses
141/// the bare data dir as its registry root finds zero palaces because every
142/// `palace.json` sits one level below where it looked — the "palaces lost on
143/// restart" bug.
144/// What: given the standard data dir, returns `<data_dir>/palaces` when that
145/// subdirectory exists, otherwise `<data_dir>` itself. Resolving this once in
146/// `main.rs` and using the result as `AppState::data_root` keeps every call
147/// site (`status`, `palace_list`, `open_palace`, `palace_create`,
148/// `load_palaces_from_disk`) consistent without forcing a data migration.
149/// Test: `tests::resolve_palace_registry_dir_prefers_palaces_subdir` and
150/// `resolve_palace_registry_dir_falls_back_to_data_dir`.
151pub fn resolve_palace_registry_dir(data_dir: PathBuf) -> PathBuf {
152    let nested = data_dir.join("palaces");
153    if nested.is_dir() {
154        nested
155    } else {
156        data_dir
157    }
158}
159
160/// Hook type — labels the Claude Code hook that triggered a submission.
161///
162/// Why: every hook firing produces an activity-feed entry tagged with the
163/// originating hook so operators can tell whether activity came from a user
164/// prompt (`UserPromptSubmit`), a new session (`SessionStart`), or a future
165/// hook variant. Threading this through `DaemonEvent::HookFired` lets the
166/// dashboard badge each row with the hook label.
167/// What: serde-serialised in PascalCase so the wire format matches Claude
168/// Code's own hook-name strings exactly (e.g. `"UserPromptSubmit"`).
169/// Test: `hook_type_serde_round_trips`.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
171pub enum HookType {
172    /// Claude Code's `UserPromptSubmit` hook — fires on every user prompt.
173    UserPromptSubmit,
174    /// Claude Code's `SessionStart` hook — fires once at session open.
175    SessionStart,
176}
177
178impl HookType {
179    /// Stable string label used for the wire format.
180    pub fn as_str(&self) -> &'static str {
181        match self {
182            Self::UserPromptSubmit => "UserPromptSubmit",
183            Self::SessionStart => "SessionStart",
184        }
185    }
186}
187
188/// Injection kind — labels what the hook actually injected (or attempted).
189///
190/// Why: distinct from `HookType` because one hook could in principle render
191/// more than one kind of injection (e.g. SessionStart can deliver both an
192/// inbox check and bootstrap context). Tagging the rendered kind explicitly
193/// keeps the activity log searchable when that fan-out lands.
194/// What: serde-serialised as kebab-case so it matches the labels already
195/// used in the JSONL prompt log (`prompt-context-facts`,
196/// `inbox-check-messages`).
197/// Test: `injection_kind_serde_round_trips`.
198#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
199#[serde(rename_all = "kebab-case")]
200pub enum InjectionKind {
201    /// `prompt-context` hook rendered the prompt-facts block.
202    PromptContext,
203    /// `inbox-check` hook delivered unread messages.
204    InboxCheck,
205}
206
207impl InjectionKind {
208    /// Stable string label used for the wire format.
209    pub fn as_str(&self) -> &'static str {
210        match self {
211            Self::PromptContext => "prompt-context",
212            Self::InboxCheck => "inbox-check",
213        }
214    }
215}
216
217/// Live daemon events broadcast to connected SSE subscribers.
218///
219/// Why: The dashboard needs push-driven updates so palace creation, drawer
220/// add/delete, dream cycles, and aggregate status changes are visible without
221/// polling. A single broadcast channel fans out to every connected browser.
222/// What: Tagged enum serialized as `{"type": "...", ...fields}` over SSE.
223/// Test: `web::tests::sse_stream_emits_events` subscribes, triggers a
224/// mutation, and asserts the frame arrives.
225#[derive(Clone, Debug, serde::Serialize)]
226#[serde(tag = "type", rename_all = "snake_case")]
227pub enum DaemonEvent {
228    PalaceCreated {
229        id: String,
230        name: String,
231        /// Originating subsystem (HTTP, MCP, Hook). Why (issue #96): the
232        /// UI badges each row with its source so operators can tell at a
233        /// glance whether a write came from the dashboard form, an MCP
234        /// tool call, or a hook-driven path. The wire-format key is
235        /// `source` (lower-case strings via serde rename_all on
236        /// `ActivitySource`).
237        source: ActivitySource,
238    },
239    DrawerAdded {
240        palace_id: String,
241        /// Friendly palace name (Palace.name) at write time. Why: lets SSE
242        /// consumers (the dashboard activity feed) render the human-readable
243        /// label without a separate id→name lookup. Empty string if the
244        /// emitter could not resolve the name.
245        #[serde(default)]
246        palace_name: String,
247        drawer_count: usize,
248        /// Wall-clock timestamp when the drawer was added. Why: SSE
249        /// receivers want to render "just now / 2m ago" relative to the
250        /// daemon's clock, not the time the SSE frame happens to arrive.
251        timestamp: chrono::DateTime<chrono::Utc>,
252        /// Short preview of the drawer's content (whitespace-collapsed,
253        /// truncated to ~80 chars with an ellipsis when cut). Why: the TUI
254        /// activity feed and dashboard ticker want to show *what* was
255        /// stored, not just the running drawer count. Empty when the
256        /// emitter could not resolve the content (legacy clients tolerate
257        /// the missing field via `#[serde(default)]`).
258        #[serde(default)]
259        content_preview: String,
260        /// Originating subsystem (issue #96).
261        source: ActivitySource,
262    },
263    DrawerDeleted {
264        palace_id: String,
265        drawer_count: usize,
266        /// Originating subsystem (issue #96).
267        source: ActivitySource,
268    },
269    DreamCompleted {
270        palace_id: Option<String>,
271        merged: usize,
272        pruned: usize,
273        compacted: usize,
274        closets_updated: usize,
275        duration_ms: u64,
276        /// Originating subsystem (issue #96).
277        source: ActivitySource,
278    },
279    StatusChanged {
280        total_drawers: usize,
281        total_vectors: usize,
282        total_kg_triples: usize,
283    },
284    /// A Claude Code hook completed and rendered (or attempted to render) an
285    /// injection block.
286    ///
287    /// Why: pre-#XXX the activity feed only fired on drawer / palace / dream
288    /// writes, which meant a normal Claude Code session — whose only daemon
289    /// traffic is hook invocations — left the feed empty. Surfacing every
290    /// hook firing answers the user complaint "no activity in the TUI" and
291    /// gives operators a way to see how often each project palace is
292    /// actually picking up prompt-context / inbox-check work.
293    /// What: carries the resolved palace (or `None` if cwd resolution
294    /// failed), the [`HookType`] label, the [`InjectionKind`] label, the
295    /// rendered injection byte length, a short excerpt of the triggering
296    /// prompt (capped at ~80 chars; the full content stays in the JSONL
297    /// prompt log only), the timestamp, the hook's wall-clock duration,
298    /// and the [`ActivitySource`] tag (always `Hook` for this variant).
299    /// Backwards-compatible: SSE clients that do not recognise the
300    /// `hook_fired` `type` tag can safely ignore the frame.
301    HookFired {
302        /// Resolved palace id (slug) — `None` if cwd resolution failed.
303        #[serde(default)]
304        palace_id: Option<String>,
305        /// Friendly palace name at hook time — `None` if the registry
306        /// could not be consulted (HTTP path uses `palace_id` here when
307        /// no separate name is known).
308        #[serde(default)]
309        palace_name: Option<String>,
310        hook_type: HookType,
311        injection_kind: InjectionKind,
312        /// Rendered injection size in bytes (`0` when no injection was
313        /// emitted, e.g. SessionStart with an empty inbox).
314        injection_length: u64,
315        /// Short excerpt of the triggering prompt for the activity feed
316        /// display. Capped at ~80 chars with a trailing `…` when cut.
317        /// Why: the activity feed renders this directly; full prompt
318        /// content (which may be sensitive) stays in the JSONL log.
319        #[serde(default)]
320        trigger_prompt_excerpt: String,
321        timestamp: chrono::DateTime<chrono::Utc>,
322        /// Hook wall-clock duration in milliseconds.
323        duration_ms: u64,
324        /// Always `ActivitySource::Hook` for this variant; encoded explicitly
325        /// so the same dispatch path (`emit`) can persist + broadcast it.
326        source: ActivitySource,
327    },
328}
329
330/// Open the activity log under `data_root`, falling back to a per-process
331/// tempdir and finally to a no-op `Discard` variant when no writable
332/// directory is available.
333///
334/// Why (issues #96, #225): the activity log is a best-effort feature — if
335/// the data root is on a read-only mount, missing, or locked by another
336/// process, the daemon should still come up and serve every other endpoint.
337/// The first fallback is a `std::env::temp_dir()`-anchored subdirectory
338/// keyed by the daemon's process id. Issue #225: a previous version called
339/// `expect()` on the tempdir fallback, which crashed the daemon on hosts
340/// where neither `data_root` nor `std::env::temp_dir()` is writable
341/// (read-only containers, locked-down sandboxes). The contract is
342/// "best-effort", so the final fallback is now `ActivityLog::discard()` —
343/// a no-op variant that drops every append and returns empty reads. The
344/// dashboard's activity feed simply shows up empty in that degraded state.
345/// What: tries `ActivityLog::open(data_root)`; on error logs a warning and
346/// retries against `<temp>/trusty-memory-activity-<pid>/`. If both fail,
347/// emits a final warning and returns `ActivityLog::discard()`.
348/// Test: `open_activity_log_with_fallback_returns_discard_when_unwritable`
349/// covers the discard branch; existing `AppState` construction tests cover
350/// the happy and tempdir-fallback paths.
351fn open_activity_log_with_fallback(data_root: &Path) -> Arc<ActivityLog> {
352    match ActivityLog::open(data_root) {
353        Ok(log) => Arc::new(log),
354        Err(primary_err) => {
355            tracing::warn!(
356                "could not open activity log at {}: {primary_err:#}; falling back to per-process tempdir",
357                data_root.display()
358            );
359            let fallback =
360                std::env::temp_dir().join(format!("trusty-memory-activity-{}", std::process::id()));
361            match ActivityLog::open(&fallback) {
362                Ok(log) => Arc::new(log),
363                Err(fallback_err) => {
364                    tracing::warn!(
365                        "activity log tempdir fallback at {} also failed: {fallback_err:#}; \
366                         activity feed disabled for this process (no-op log)",
367                        fallback.display()
368                    );
369                    Arc::new(ActivityLog::discard())
370                }
371            }
372        }
373    }
374}
375
376impl DaemonEvent {
377    /// Short discriminant label matching the SSE `type` field.
378    ///
379    /// Why: the persisted activity log stores `event_type` as a string so
380    /// the UI can render the row without re-parsing the payload. Sharing
381    /// the same labels the SSE serializer uses keeps the wire and the
382    /// stored history consistent.
383    /// What: returns one of `palace_created`, `drawer_added`,
384    /// `drawer_deleted`, `dream_completed`, `status_changed`.
385    /// Test: `daemon_event_type_str_matches_sse_tag` in the lib tests.
386    pub fn type_str(&self) -> &'static str {
387        match self {
388            Self::PalaceCreated { .. } => "palace_created",
389            Self::DrawerAdded { .. } => "drawer_added",
390            Self::DrawerDeleted { .. } => "drawer_deleted",
391            Self::DreamCompleted { .. } => "dream_completed",
392            Self::StatusChanged { .. } => "status_changed",
393            Self::HookFired { .. } => "hook_fired",
394        }
395    }
396
397    /// `palace_id` if the event is scoped to a single palace.
398    ///
399    /// Why: the activity log indexes entries by palace id so the UI can
400    /// filter by palace; daemon-wide events (`status_changed`,
401    /// dream-across-all-palaces) return `None`.
402    /// What: returns a borrowed string when the variant carries a palace
403    /// id, otherwise `None`.
404    /// Test: `daemon_event_palace_id_extraction`.
405    pub fn palace_id(&self) -> Option<&str> {
406        match self {
407            Self::PalaceCreated { id, .. } => Some(id),
408            Self::DrawerAdded { palace_id, .. } | Self::DrawerDeleted { palace_id, .. } => {
409                Some(palace_id)
410            }
411            Self::DreamCompleted { palace_id, .. } => palace_id.as_deref(),
412            Self::HookFired { palace_id, .. } => palace_id.as_deref(),
413            Self::StatusChanged { .. } => None,
414        }
415    }
416
417    /// Originating subsystem if the event carries one.
418    ///
419    /// Why: only mutation events carry a `source`; the aggregate
420    /// `StatusChanged` is recomputed by the daemon and has no caller, so
421    /// it returns `None`.
422    /// What: returns the variant's `source` field where present.
423    /// Test: `daemon_event_source_extraction`.
424    pub fn source(&self) -> Option<ActivitySource> {
425        match self {
426            Self::PalaceCreated { source, .. }
427            | Self::DrawerAdded { source, .. }
428            | Self::DrawerDeleted { source, .. }
429            | Self::DreamCompleted { source, .. }
430            | Self::HookFired { source, .. } => Some(*source),
431            Self::StatusChanged { .. } => None,
432        }
433    }
434}
435
436/// Shared application state passed to every request handler.
437///
438/// Why: The stdio loop and HTTP server need the same handles to the registry,
439/// data root, and embedder so MCP tools can perform real reads/writes against
440/// the live trusty-memory core. The embedder is heavy (loads ONNX weights) so
441/// we hold it behind a `OnceCell` and initialize lazily on first use.
442/// What: `Clone`-able via `Arc` fields. The registry / data root are eager;
443/// `embedder` is `Arc<OnceCell<Arc<FastEmbedder>>>` so concurrent first-use
444/// races resolve to a single shared instance.
445/// Test: `app_state_default_constructs` confirms construction without panic.
446#[derive(Clone)]
447pub struct AppState {
448    pub version: String,
449    pub registry: Arc<PalaceRegistry>,
450    pub data_root: PathBuf,
451    pub embedder: Arc<OnceCell<Arc<FastEmbedder>>>,
452    /// Optional default palace applied to MCP tool calls when the caller
453    /// omits the `palace` argument. Set via `trusty-memory serve --palace`.
454    pub default_palace: Option<String>,
455    /// Active chat provider selected at startup. `None` means no upstream is
456    /// configured (no Ollama detected and no OpenRouter key) — callers must
457    /// degrade gracefully (chat endpoint returns 412).
458    pub chat_provider: Arc<OnceCell<Option<Arc<dyn ChatProvider>>>>,
459    /// Per-palace chat-session stores, opened lazily so cold-start cost is
460    /// paid only when chat-history endpoints are hit.
461    pub session_stores: Arc<dashmap::DashMap<String, Arc<ChatSessionStore>>>,
462    /// Broadcast sender for live `DaemonEvent` pushes to SSE subscribers.
463    ///
464    /// Why: Lets mutating handlers emit events that any connected dashboard
465    /// receives instantly. Cap of 128 buffers transient slow readers; if a
466    /// receiver lags it gets `RecvError::Lagged` and we emit a `lag` frame.
467    pub events: Arc<broadcast::Sender<DaemonEvent>>,
468    /// Instant the daemon started, used to compute `uptime_secs` on `/health`.
469    ///
470    /// Why (issue #35): `GET /health` reports how long the daemon has been
471    /// up. Capturing a monotonic `Instant` at `AppState` construction lets the
472    /// handler compute the elapsed seconds cheaply and without a clock-skew
473    /// hazard.
474    /// What: a wall-monotonic `Instant`; `AppState::new` stamps it at startup.
475    /// Test: `health_endpoint_includes_resource_fields`.
476    pub started_at: std::time::Instant,
477    /// In-memory ring buffer of recent tracing log lines (issue #35).
478    ///
479    /// Why: the `GET /api/v1/logs/tail` endpoint serves the last N log lines
480    /// so operators can inspect a running daemon without tailing a file. The
481    /// buffer is shared between the tracing `LogBufferLayer` (writer) and the
482    /// HTTP handler (reader).
483    /// What: a cheap `Arc`-backed clone of the buffer the subscriber writes
484    /// to. Defaults to an empty buffer for states that never install the
485    /// layer (tests, the stdio path).
486    /// Test: `logs_tail_returns_recent_lines`.
487    pub log_buffer: trusty_common::log_buffer::LogBuffer,
488    /// Bug-capture ERROR store (bug-reporting #478, Phase 1).
489    ///
490    /// Why: Phase 2 MCP / HTTP endpoints need to query captured errors; stashing
491    ///      the `ErrorStore` handle here lets any handler reach it cheaply without
492    ///      a second global or per-request construction.
493    /// What: populated by `run_serve` from the `init_tracing_with_buffer_and_capture`
494    ///      result; the layer writes to this store automatically so every
495    ///      `tracing::error!` call site contributes without any changes to call
496    ///      sites. `None` in states that do not install the layer (tests, the
497    ///      stdio path).
498    /// Test: compile-presence is verified by the `trusty-memory` build; Phase 2
499    ///      will add query tests in `web.rs`.
500    pub error_store: Option<trusty_common::error_capture::ErrorStore>,
501    /// Most recent on-disk footprint of `data_root`, in bytes (issue #35).
502    ///
503    /// Why: `GET /health` reports `disk_bytes`. Walking the data directory on
504    /// every health request would make a frequent health poll do unbounded
505    /// I/O; a background task recomputes it every 10 s and stores it here so
506    /// the handler reads it lock-free.
507    /// What: an `AtomicU64` updated by the ticker spawned in `run_http_on`.
508    /// `0` until the first walk completes.
509    /// Test: `health_endpoint_includes_resource_fields`.
510    pub disk_bytes: Arc<std::sync::atomic::AtomicU64>,
511    /// Per-process RSS + CPU sampler, refreshed on each `/health` request
512    /// (issue #35).
513    ///
514    /// Why: CPU usage is a delta between two `sysinfo` refreshes, so the
515    /// sampler must persist between requests — hence the shared `Mutex`.
516    /// What: a `tokio::sync::Mutex<SysMetrics>` so the async health handler
517    /// can sample without blocking the runtime.
518    /// Test: `health_endpoint_includes_resource_fields`.
519    pub sys_metrics: Arc<tokio::sync::Mutex<trusty_common::sys_metrics::SysMetrics>>,
520    /// HTTP listener address the daemon bound to, once `run_http_on` is running.
521    ///
522    /// Why: clients (and `/health` responses) need to advertise the live
523    /// `host:port` even though port selection happens dynamically (7070–7079
524    /// walk + OS fallback). Stashing it on `AppState` lets request handlers
525    /// surface the discovery value without re-querying the listener.
526    /// What: a `OnceLock<SocketAddr>` so `run_http_on` writes it exactly once
527    /// at bind time and every handler reads it lock-free thereafter. Empty
528    /// (`None` from `get()`) on the stdio path where no listener exists.
529    /// Test: `health_endpoint_reports_bound_addr` (added below).
530    pub bound_addr: Arc<OnceLock<SocketAddr>>,
531    /// Cached prompt-facts surface served by the MCP `get_prompt_context`
532    /// tool (issue #42).
533    ///
534    /// Why: The original session-init `prompts/get` design loaded context
535    /// once per connection; switching to a per-message tool lets the model
536    /// pull fresh, query-filtered context on demand. The cache holds both
537    /// the raw triples (for filtered lookups) and a pre-formatted Markdown
538    /// block (for the unfiltered hot path) so neither code path re-walks
539    /// the KG. The cache is rebuilt by
540    /// `prompt_facts::rebuild_prompt_cache` after any write that touches a
541    /// hot predicate (`kg_assert`, `add_alias`, `remove_prompt_fact`).
542    /// What: An `Arc<tokio::sync::RwLock<PromptFactsCache>>` so the hot
543    /// read path takes a brief read lock and clones the cache; rebuilds
544    /// take a write lock for the assignment only. The async-aware lock
545    /// (issue #229) yields to the tokio runtime instead of blocking a
546    /// runtime thread for the rebuild duration. An empty `triples` vec ↔
547    /// "no context stored yet" (the tool handler renders a hint).
548    /// Test: `get_prompt_context_returns_cached_or_hint`,
549    /// `get_prompt_context_filters_by_query`.
550    pub prompt_context_cache: Arc<RwLock<prompt_facts::PromptFactsCache>>,
551    /// Persistent activity log (issue #96).
552    ///
553    /// Why: the dashboard activity feed used to be a pure live-stream over
554    /// `/sse` — opening the UI showed an empty feed and any mutation from
555    /// the MCP path was invisible. Holding an `ActivityLog` on `AppState`
556    /// lets `emit` record an entry on every push so the
557    /// `GET /api/v1/activity` handler can return historical rows on mount
558    /// and the live SSE stream can continue prepending events on top of
559    /// the loaded history. `None` on builds that opt out (tests that use
560    /// `AppState::new` get a real log under their tempdir so behaviour
561    /// matches production).
562    /// What: an `Arc<ActivityLog>` shared with every emitter.
563    /// Test: `web::tests::activity_endpoint_lists_recent_emits`.
564    pub activity_log: Arc<ActivityLog>,
565    /// Optional per-palace BM25 lexical search lane (issue #156).
566    ///
567    /// Why: in-process BM25 would serialise the recall hot path on disk
568    /// I/O during writes and contend with the redb/usearch locks. Delegating
569    /// to the `trusty-bm25-daemon` subprocess (one socket per palace) keeps
570    /// BM25 ingestion and search off the critical path while still feeding
571    /// hits into the recall RRF fusion.
572    /// What: `Some(client)` only when `TRUSTY_BM25_DAEMON=1` at startup —
573    /// every code path that uses this field is gated on `is_some()` and
574    /// falls back to vector-only behaviour otherwise so existing deployments
575    /// see zero behavioural change.
576    /// Test: `bm25_client_disabled_by_default`,
577    /// `bm25_client_enabled_when_env_set`.
578    pub bm25_client: Option<Arc<Bm25Client>>,
579    /// Optional per-palace BM25 daemon spawn supervisor (issue #193).
580    ///
581    /// Why: without an in-process supervisor the BM25 daemon must be
582    /// launched out-of-band (launchd, manual `trusty-bm25-daemon`), which
583    /// is the same UX trap PR #190 fixed for trusty-embedderd. Holding a
584    /// supervisor here lets us spawn the daemon on first BM25 use for a
585    /// palace, restart it if it dies, and reap it on clean shutdown.
586    /// `Some` only when `TRUSTY_BM25_DAEMON=1` at startup — the same gate
587    /// that enables `bm25_client`. When set but `TRUSTY_BM25_EXTERNAL=1`,
588    /// the supervisor's `ensure_running` becomes a no-op that just returns
589    /// the canonical socket path so operators can keep using their own
590    /// process manager.
591    /// Test: covered by `bm25_supervisor_present_when_env_set` and the
592    /// `bm25_supervisor::tests` unit tests.
593    pub bm25_supervisor: Option<Arc<bm25_supervisor::Bm25Supervisor>>,
594    /// Per-palace write serialisation locks (issue #230).
595    ///
596    /// Why: the dedup gate in `tools.rs` previously read a snapshot of
597    /// existing drawers, checked for near-duplicates via Jaro-Winkler, and
598    /// then issued the write — a classic time-of-check/time-of-use race.
599    /// Two concurrent `memory_remember` calls with the same content could
600    /// both see the pre-write snapshot, both pass the gate, and both land
601    /// duplicate drawers. Serialising the gate-then-write sequence per
602    /// palace closes the window: while one task holds the mutex, any
603    /// concurrent writer for the same palace blocks until the first write
604    /// finishes and is visible to `list_drawers`. The lock is **per
605    /// palace** (not global) so writes to different palaces continue to
606    /// run in parallel.
607    /// What: a `DashMap` keyed by palace id, where each entry is an
608    /// `Arc<tokio::sync::Mutex<()>>`. The mutex is constructed lazily by
609    /// `palace_write_lock` on first access. `Arc` lets callers hold a
610    /// clone of the lock past the lifetime of the `DashMap` entry so the
611    /// map never needs to be held across an `.await`.
612    /// Test: `tools::tests::dedup_gate_blocks_concurrent_duplicate_writes`.
613    pub palace_write_locks: Arc<dashmap::DashMap<String, Arc<tokio::sync::Mutex<()>>>>,
614    /// Counter of in-flight activity-log writes spawned by `emit`
615    /// (issue #232).
616    ///
617    /// Why: `emit` offloads the synchronous redb append to the tokio blocking
618    /// pool via `spawn_blocking` so the async runtime is never parked waiting
619    /// on fsync. The write is fire-and-forget — `emit` returns immediately
620    /// after spawning. Tests that observe the activity log right after a
621    /// burst of `emit` calls need a deterministic synchronization point;
622    /// holding an in-flight counter lets `flush_activity_writes` poll until
623    /// every spawned append has settled, which keeps the assertions
624    /// race-free without forcing every caller to `.await`.
625    /// What: an `Arc<AtomicUsize>` incremented before each `spawn_blocking`
626    /// and decremented inside the closure (after the append completes, even
627    /// if it errored). The counter is cheap (one atomic add per emit) and
628    /// stays at zero in steady-state production traffic.
629    /// Test: `web::tests::activity_endpoint_lists_recent_emits` and
630    /// `tests::emit_persists_mutations_but_skips_status_changed` call
631    /// `flush_activity_writes` to drain the counter before reading the log.
632    pub pending_activity_writes: Arc<AtomicUsize>,
633    /// In-memory cache mapping palace id → `Palace.name` (issue #228).
634    ///
635    /// Why: every `memory_remember` / `memory_note` write used to call
636    /// `PalaceRegistry::list_palaces` (a synchronous filesystem walk of the
637    /// data root) just to resolve a friendly palace name for the SSE
638    /// `DrawerAdded` event. With N palaces on disk the cost was O(N) opendirs
639    /// plus `palace.json` reads on every write, blocking the async runtime.
640    /// Caching the name in-memory turns the lookup into a `DashMap::get`.
641    /// What: `DashMap<String, String>` populated by `create_palace` and
642    /// `load_palaces_from_disk`, kept in sync by rename / delete paths.
643    /// Missing entries are treated as "name unknown" so callers fall back to
644    /// the palace id and the emit path never fails.
645    /// Test: `palace_name_cache_populated_after_hydration` and
646    /// `palace_name_cache_updates_on_create`.
647    pub palace_names: Arc<dashmap::DashMap<String, String>>,
648    /// Single-pass startup pin-file map: palace id → project root path (issue #470).
649    ///
650    /// Why: after daemon startup we have no record of which on-disk project
651    /// directories correspond to which palace ids — that information only
652    /// existed inside the pin files on disk. Eager-opening every palace on
653    /// startup is too expensive. This field captures the scan-only result of
654    /// `startup_scan::scan_pin_map` so handlers that want to locate a project
655    /// by its palace id (e.g. future cwd-inference, project-health checks)
656    /// can do a single `DashMap::get` instead of a filesystem walk.
657    /// Populated once, shortly after `load_palaces_from_disk` returns, by
658    /// `spawn_startup_tasks`. Never mutated after population — it is a
659    /// snapshot of what the filesystem looked like at startup.
660    /// What: `DashMap<String (palace_id), PathBuf (project root)>`.
661    /// The outer `Arc` lets `spawn_startup_tasks` (which holds only a clone
662    /// of `AppState`) write to the same backing map that request handlers
663    /// read. Population is asynchronous so callers must treat an absent entry
664    /// as "not yet scanned" (or "no pin found"), never as "palace unknown".
665    /// Test: `startup_scan::tests::scan_pin_map_*` validate the underlying
666    /// scanner function; the wiring in `spawn_startup_tasks` is covered by
667    /// the integration-test daemon start path.
668    pub pin_project_map: Arc<dashmap::DashMap<String, PathBuf>>,
669    /// Bounded sender for the BM25 index worker (issue #231).
670    ///
671    /// Why: the previous fire-and-forget design `tokio::spawn`ed one task per
672    /// `memory_remember` / `memory_note` call, so a write burst against a slow
673    /// or unreachable BM25 daemon grew an unbounded in-flight task queue. A
674    /// single long-lived worker draining a bounded mpsc channel caps that
675    /// back-pressure: writers `try_send` (never block), full-queue requests
676    /// are dropped with a `warn!`, and the worker exits cleanly when the last
677    /// sender is dropped on shutdown.
678    /// What: an `mpsc::Sender` cloned to every `AppState` clone (cheap). The
679    /// matching receiver is consumed by the worker spawned in
680    /// [`AppState::new`] via [`tools::spawn_bm25_index_worker`]. Capacity is
681    /// [`tools::BM25_INDEX_QUEUE_CAPACITY`] (256).
682    /// Test: `bm25_index_queue_drops_when_full` exercises the full-queue
683    /// branch via `bm25_index_enqueue`.
684    pub bm25_index_tx: tokio::sync::mpsc::Sender<tools::Bm25IndexRequest>,
685}
686
687impl AppState {
688    /// Construct an `AppState` rooted at the given on-disk data directory.
689    ///
690    /// Why: The CLI (`serve`) and integration tests need to point the MCP
691    /// server at different roots — production at `dirs::data_dir`, tests at a
692    /// `tempfile::tempdir()`.
693    /// What: Builds an empty `PalaceRegistry`, captures the version, and
694    /// allocates an empty `OnceCell` for the embedder. `default_palace` is
695    /// `None`; use `with_default_palace` to set it.
696    /// Test: `tools::tests::dispatch_palace_create_persists` constructs an
697    /// AppState pointed at a tempdir and round-trips a palace through it.
698    pub fn new(data_root: PathBuf) -> Self {
699        let (events_tx, _) = broadcast::channel::<DaemonEvent>(128);
700        // Issue #96: open (or create) the persistent activity log under the
701        // daemon data root. Open failure is logged but never crashes the
702        // daemon — we fall back to a per-process tempdir so emits remain
703        // best-effort and the rest of the daemon keeps working.
704        let activity_log = open_activity_log_with_fallback(&data_root);
705        // Issue #231: bounded mpsc channel + single long-lived worker
706        // replaces the per-write `tokio::spawn` fire-and-forget pattern so
707        // BM25 indexing back-pressure is capped. The worker is spawned here
708        // unconditionally so the channel always has a drain — even when
709        // `bm25_client` is `None`, the worker just consumes and discards
710        // each request so senders never block on a full queue.
711        let (bm25_index_tx, bm25_index_rx) =
712            tokio::sync::mpsc::channel::<tools::Bm25IndexRequest>(tools::BM25_INDEX_QUEUE_CAPACITY);
713        // `bm25_client` / `bm25_supervisor` start as `None`; the builder
714        // `with_bm25_client_from_env` rebuilds the worker with the real
715        // client + supervisor once env-gated opt-in is resolved.
716        tools::spawn_bm25_index_worker(bm25_index_rx, None, None);
717        Self {
718            version: env!("CARGO_PKG_VERSION").to_string(),
719            registry: Arc::new(PalaceRegistry::new()),
720            data_root,
721            embedder: Arc::new(OnceCell::new()),
722            default_palace: None,
723            chat_provider: Arc::new(OnceCell::new()),
724            session_stores: Arc::new(dashmap::DashMap::new()),
725            events: Arc::new(events_tx),
726            started_at: std::time::Instant::now(),
727            // Default to an empty buffer — `with_log_buffer` overrides this
728            // when the daemon installs the `LogBufferLayer` (HTTP mode).
729            log_buffer: trusty_common::log_buffer::LogBuffer::new(
730                trusty_common::log_buffer::DEFAULT_LOG_CAPACITY,
731            ),
732            // Bug-reporting #478: `None` until `with_error_store` is called
733            // during daemon startup (HTTP mode). Tests keep `None` so no
734            // unexpected files are written to the OS data dir.
735            error_store: None,
736            disk_bytes: Arc::new(std::sync::atomic::AtomicU64::new(0)),
737            sys_metrics: Arc::new(tokio::sync::Mutex::new(
738                trusty_common::sys_metrics::SysMetrics::new(),
739            )),
740            bound_addr: Arc::new(OnceLock::new()),
741            prompt_context_cache: Arc::new(RwLock::new(prompt_facts::PromptFactsCache::default())),
742            activity_log,
743            bm25_client: None,
744            bm25_supervisor: None,
745            palace_write_locks: Arc::new(dashmap::DashMap::new()),
746            pending_activity_writes: Arc::new(AtomicUsize::new(0)),
747            palace_names: Arc::new(dashmap::DashMap::new()),
748            pin_project_map: Arc::new(dashmap::DashMap::new()),
749            bm25_index_tx,
750        }
751    }
752
753    /// Acquire (lazily, then clone) the per-palace write mutex.
754    ///
755    /// Why (issue #230): the dedup-check + `remember_with_options` write
756    /// sequence in `tools.rs` must be atomic per palace to prevent two
757    /// concurrent identical writes from both passing the dedup gate.
758    /// Callers hold the returned `Arc<Mutex<()>>`'s guard across the gate
759    /// check and the write so the second writer blocks until the first
760    /// write is visible to `list_drawers`. Returning a clone of the `Arc`
761    /// rather than a borrow into the `DashMap` lets the caller `.await`
762    /// while holding the lock without risking a deadlock against any
763    /// future map mutation (DashMap shards are sync mutexes).
764    /// What: looks up the palace id in `palace_write_locks` and returns
765    /// a clone of the existing mutex; on the first call for a palace,
766    /// inserts a freshly-constructed `tokio::sync::Mutex<()>` first. The
767    /// `DashMap::entry().or_insert_with` API guarantees the lazy
768    /// construction is racy-safe — only one mutex is ever inserted per
769    /// palace id.
770    /// Test: `tools::tests::dedup_gate_blocks_concurrent_duplicate_writes`.
771    pub fn palace_write_lock(&self, palace_id: &str) -> Arc<tokio::sync::Mutex<()>> {
772        if let Some(existing) = self.palace_write_locks.get(palace_id) {
773            return existing.clone();
774        }
775        self.palace_write_locks
776            .entry(palace_id.to_string())
777            .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
778            .clone()
779    }
780
781    /// Look up a project root path by palace id in the startup pin-scan map.
782    ///
783    /// Why: provides a stable, cheap accessor so handlers do not reach directly
784    /// into the `DashMap` field and so the accessor can be mocked in future
785    /// tests without touching `AppState` internals. The map is populated
786    /// asynchronously by `spawn_startup_tasks` — an absent entry means either
787    /// the scan has not completed yet or no pin file claimed that id.
788    /// What: returns `Some(project_path)` when the palace id was found during
789    /// startup scan; `None` otherwise.
790    /// Test: covered indirectly via the startup-scan integration path; the
791    /// underlying map data is validated by `startup_scan::tests`.
792    pub fn pinned_project_path(&self, palace_id: &str) -> Option<PathBuf> {
793        self.pin_project_map.get(palace_id).map(|e| e.clone())
794    }
795
796    /// Builder-style: opt-in to the BM25 lexical lane (issue #156).
797    ///
798    /// Why: the BM25 subprocess is gated behind `TRUSTY_BM25_DAEMON=1` so
799    /// the default `cargo install trusty-memory` / launchd plist deployment
800    /// stays vector-only and existing test fixtures keep passing without
801    /// having to provision a daemon. Reading the env var here keeps the
802    /// gating logic in one place (the helper in `main.rs` just plumbs the
803    /// result through).
804    /// What: when `TRUSTY_BM25_DAEMON=1`, constructs one `Bm25Client` per
805    /// palace by lazy-resolving the socket path the first time the palace
806    /// id is observed. Currently we install a shared `default` client up
807    /// front and re-key on the palace id at the call site — palaces with no
808    /// daemon socket simply see search/index errors which we log + ignore.
809    /// Returns `self` unchanged when the env var is unset or set to anything
810    /// other than `1`.
811    /// Test: `bm25_client_disabled_by_default`,
812    /// `bm25_client_enabled_when_env_set`.
813    #[must_use]
814    pub fn with_bm25_client_from_env(mut self) -> Self {
815        if std::env::var("TRUSTY_BM25_DAEMON").as_deref() == Ok("1") {
816            // Install the default-palace client; per-palace clients are
817            // constructed on demand via `Bm25Client::for_palace`.
818            let default_palace = self.default_palace.as_deref().unwrap_or("default");
819            self.bm25_client = Some(Arc::new(Bm25Client::for_palace(default_palace)));
820            // Issue #193: hand-in-hand with the client, attach a spawn
821            // supervisor so the BM25 daemon is auto-started on first use
822            // for any palace. Operators who want to manage daemons
823            // out-of-band (launchd, systemd, manual) set
824            // TRUSTY_BM25_EXTERNAL=1 which makes the supervisor a no-op.
825            self.bm25_supervisor = Some(Arc::new(bm25_supervisor::Bm25Supervisor::new()));
826            // Issue #231: rebuild the bounded indexer channel + worker so
827            // the worker holds the now-populated client + supervisor. The
828            // placeholder worker installed by `AppState::new` (with `None`
829            // / `None`) drained the channel into the void — replacing the
830            // sender here closes the placeholder receiver and the
831            // placeholder worker exits cleanly. The new worker takes over
832            // as the sole drain for the indexer queue.
833            let (tx, rx) = tokio::sync::mpsc::channel::<tools::Bm25IndexRequest>(
834                tools::BM25_INDEX_QUEUE_CAPACITY,
835            );
836            tools::spawn_bm25_index_worker(
837                rx,
838                self.bm25_client.clone(),
839                self.bm25_supervisor.clone(),
840            );
841            self.bm25_index_tx = tx;
842            tracing::info!(
843                palace = default_palace,
844                "BM25 daemon client + spawn supervisor enabled (TRUSTY_BM25_DAEMON=1)"
845            );
846        }
847        self
848    }
849
850    /// Scan the palace registry directory and re-register every persisted
851    /// palace into the in-memory [`PalaceRegistry`].
852    ///
853    /// Why: `AppState::new` builds an *empty* registry, so after a daemon
854    /// restart `palace_list` / the dashboard reported zero palaces even though
855    /// dozens existed on disk — palace metadata was persisted by
856    /// `palace_create` but never re-hydrated on startup. This method closes
857    /// that gap by walking the on-disk layout (each subdirectory holding a
858    /// `palace.json` is one palace) and rebuilding a live `PalaceHandle` for
859    /// each, so recall paths see the full set immediately after a restart.
860    /// What: runs the blocking filesystem walk + per-palace `PalaceHandle::open`
861    /// on a `spawn_blocking` thread (so it never stalls the async runtime),
862    /// registers each successfully opened palace via `register_arc`, logs every
863    /// load at `debug!`, and returns the count loaded. A palace that fails to
864    /// open (corrupt index, unreadable `kg.db`, etc.) is logged at `warn!` and
865    /// skipped — one bad palace must not abort startup or crash the daemon.
866    /// `data_root` is expected to already be the palace registry directory —
867    /// `main.rs` resolves it via [`resolve_palace_registry_dir`] before
868    /// constructing the `AppState`, so the flat / legacy-`palaces/` layout
869    /// difference is handled exactly once.
870    /// Test: `tests::load_palaces_from_disk_rehydrates_registry` writes two
871    /// palaces into a tempdir, constructs an `AppState`, calls this method, and
872    /// asserts the returned count and registry contents.
873    pub async fn load_palaces_from_disk(&self) -> Result<usize> {
874        let registry_dir = self.data_root.clone();
875        let registry = self.registry.clone();
876        let palace_names = self.palace_names.clone();
877        // The directory walk and each `PalaceHandle::open` perform blocking
878        // filesystem + redb/usearch I/O — run the whole hydration on the
879        // blocking pool so it never parks an async worker thread.
880        let count = tokio::task::spawn_blocking(move || -> Result<usize> {
881            let palaces = PalaceRegistry::list_palaces(&registry_dir)?;
882            let total = palaces.len();
883            let mut loaded = 0usize;
884            let mut skipped = 0usize;
885            for palace in palaces {
886                match trusty_common::memory_core::PalaceHandle::open(&palace) {
887                    Ok(handle) => {
888                        tracing::debug!(
889                            palace = %palace.id,
890                            data_dir = %palace.data_dir.display(),
891                            "loaded palace from disk"
892                        );
893                        // Issue #228: seed the in-memory name cache so write
894                        // hot paths (memory_remember / memory_note) can resolve
895                        // the friendly palace name without re-walking the data
896                        // root. Insert here (during hydration) is the single
897                        // point of truth for restart-time population.
898                        palace_names.insert(palace.id.0.clone(), palace.name.clone());
899                        registry.register_arc(handle);
900                        loaded += 1;
901                    }
902                    Err(e) => {
903                        // Why (issue #467): a single bad palace (corrupt kg.db,
904                        // stale WAL, EMFILE — "Too many open files", permissions)
905                        // must never abort startup or block the HTTP server from
906                        // binding. Log per-palace and keep going; the summary
907                        // below tells operators how many were skipped without
908                        // trawling the log.
909                        // The palace is NOT registered in the in-memory registry,
910                        // so the next `open_palace` call for this id will attempt
911                        // a fresh open from disk — the lazy-reopen path. If the
912                        // root cause was EMFILE and the fd-limit fix (#462) raised
913                        // the soft limit to 8192, that first request will succeed.
914                        tracing::warn!(
915                            palace = %palace.id,
916                            data_dir = %palace.data_dir.display(),
917                            "skipping palace during startup hydration: {e:#}; \
918                             will retry lazily on first access"
919                        );
920                        skipped += 1;
921                    }
922                }
923            }
924            tracing::info!(
925                "palace hydration summary: loaded {loaded}/{total} ({skipped} skipped due to errors)"
926            );
927            Ok(loaded)
928        })
929        .await
930        .map_err(|e| anyhow::anyhow!("join load_palaces_from_disk: {e}"))??;
931        Ok(count)
932    }
933
934    /// Builder-style: attach the daemon's shared [`LogBuffer`] so the
935    /// `GET /api/v1/logs/tail` endpoint serves the same lines the tracing
936    /// subscriber captures (issue #35).
937    ///
938    /// Why: `main` builds the buffer (via `init_tracing_with_buffer`) before
939    /// constructing the `AppState`, then hands a clone here so the HTTP
940    /// handler and the tracing layer observe the same ring.
941    /// What: replaces the empty default buffer with the supplied one.
942    /// Test: `logs_tail_returns_recent_lines`.
943    #[must_use]
944    pub fn with_log_buffer(mut self, buffer: trusty_common::log_buffer::LogBuffer) -> Self {
945        self.log_buffer = buffer;
946        self
947    }
948
949    /// Builder-style: attach the bug-capture `ErrorStore` handle (bug-reporting #478).
950    ///
951    /// Why: Phase 2 MCP / HTTP endpoints need a handle to the in-memory error
952    ///      ring so they can serve `recent_errors` / `errors_by_fingerprint`
953    ///      without disk I/O on the hot path. Installing it here — rather than
954    ///      adding it as a separate global — keeps the state graph explicit and
955    ///      lets tests skip it by never calling this method.
956    /// What: stores `Some(store)` in `AppState::error_store`; the `BugCaptureLayer`
957    ///      that writes to this store is already installed in the tracing
958    ///      subscriber by `init_tracing_with_buffer_and_capture`. The store is
959    ///      `Clone` (cheap `Arc` clone internally) so both the layer and this
960    ///      field share the same underlying ring.
961    /// Test: Phase 2 will add `error_store_captures_and_queries` in `web.rs`.
962    #[must_use]
963    pub fn with_error_store(mut self, store: trusty_common::error_capture::ErrorStore) -> Self {
964        self.error_store = Some(store);
965        self
966    }
967
968    /// Send a `DaemonEvent` to all connected SSE subscribers and persist
969    /// it to the activity log when the variant carries a source.
970    ///
971    /// Why: Mutating handlers call this after a successful write so the
972    /// dashboard can update without polling. The send is best-effort —
973    /// `broadcast::Sender::send` returns `Err` only when there are no live
974    /// receivers, which is fine (no listeners == no work to do). Issue
975    /// #96 additionally writes the entry to the persistent activity log
976    /// so the feed can serve historical rows on page load and so MCP /
977    /// HTTP / Hook origins are visible to the operator. Persistence is
978    /// also best-effort — a write failure is logged but never blocks the
979    /// SSE broadcast.
980    ///
981    /// Issue #232: the activity-log append is a synchronous redb write +
982    /// fsync. Calling it directly on the async caller's task parked a tokio
983    /// worker thread on disk I/O for every SSE event. We now offload the
984    /// append to the blocking thread pool via `spawn_blocking` and return
985    /// immediately — `emit` stays synchronous so every existing caller
986    /// (including the sync `dispatch_hook_fired` JSON-RPC handler) keeps
987    /// compiling unchanged. The fire-and-forget pattern matches the
988    /// pre-fix semantics (best-effort, never blocks the SSE broadcast)
989    /// while freeing the async runtime to do real work during the write.
990    /// What: serialises the event for the log (skipping `StatusChanged`
991    /// which is a recomputed aggregate, not a mutation), spawns the redb
992    /// append on `tokio::task::spawn_blocking` keyed by a clone of the
993    /// `Arc<ActivityLog>` and the cloned event, then sends the event over
994    /// the broadcast channel. A `pending_activity_writes` counter is bumped
995    /// before the spawn and decremented inside the closure so
996    /// [`Self::flush_activity_writes`] can drain in tests.
997    /// Test: `web::tests::sse_stream_receives_palace_created` confirms a
998    /// subscriber observes the emitted event;
999    /// `activity_endpoint_lists_recent_emits` confirms persistence via
1000    /// `flush_activity_writes`.
1001    pub fn emit(&self, event: DaemonEvent) {
1002        if let Some(source) = event.source() {
1003            let event_type = event.type_str();
1004            let palace_id = event.palace_id().map(|s| s.to_string());
1005            let log = Arc::clone(&self.activity_log);
1006            let event_for_log = event.clone();
1007            let pending = Arc::clone(&self.pending_activity_writes);
1008            // Pre-allocate the sequence id in the emitting thread so the
1009            // persisted order matches the emission order even when blocking-pool
1010            // workers execute the writes concurrently (issue #247). Without
1011            // this, four rapid emits would assign IDs inside their respective
1012            // `spawn_blocking` closures in a non-deterministic order.
1013            let id = log.alloc_id();
1014            pending.fetch_add(1, Ordering::SeqCst);
1015            // Why: the synchronous redb append + fsync must not park an
1016            // async worker thread (issue #232). Spawn the write on the
1017            // blocking pool; the JoinHandle is intentionally dropped —
1018            // the write is best-effort and any failure is logged below.
1019            tokio::task::spawn_blocking(move || {
1020                let result = log.append_with_id(id, source, palace_id, event_type, &event_for_log);
1021                if let Err(e) = result {
1022                    tracing::warn!("activity_log.append failed for {event_type}: {e:#}");
1023                }
1024                pending.fetch_sub(1, Ordering::SeqCst);
1025            });
1026        }
1027        let _ = self.events.send(event);
1028    }
1029
1030    /// Block (asynchronously) until every in-flight activity-log write
1031    /// spawned by [`Self::emit`] has settled.
1032    ///
1033    /// Why: `emit` offloads its redb append to `tokio::task::spawn_blocking`
1034    /// and returns immediately (issue #232). Tests that observe the
1035    /// activity log right after a burst of emits would otherwise race the
1036    /// blocking-pool worker; this helper gives them a deterministic
1037    /// synchronization point. Production code never needs to call this —
1038    /// the dashboard reads through `GET /api/v1/activity`, which already
1039    /// tolerates writes settling asynchronously.
1040    /// What: spins on `pending_activity_writes` with a 1 ms yield until the
1041    /// counter is zero. Cheap: tests typically emit a handful of events
1042    /// and the loop exits within a single scheduler tick.
1043    /// Test: covered indirectly by `emit_persists_mutations_but_skips_status_changed`
1044    /// and `web::tests::activity_endpoint_lists_recent_emits`.
1045    pub async fn flush_activity_writes(&self) {
1046        while self.pending_activity_writes.load(Ordering::SeqCst) > 0 {
1047            tokio::time::sleep(std::time::Duration::from_millis(1)).await;
1048        }
1049    }
1050
1051    /// Open (or return cached) the chat-session store for a palace.
1052    ///
1053    /// Why: Chat session persistence lives in a dedicated SQLite file under
1054    /// the palace's data dir (`chat_sessions.db`) so it doesn't intermingle
1055    /// with the KG's transactional load. The store is cheap to clone via
1056    /// `Arc` but the underlying r2d2 pool should be reused, so cache by id.
1057    /// What: Creates the palace data dir if missing, opens (or reuses) a
1058    /// `ChatSessionStore` and stashes an `Arc` in the DashMap.
1059    /// Test: Indirectly via the session HTTP handlers in `web::tests`.
1060    pub fn session_store(&self, palace_id: &str) -> Result<Arc<ChatSessionStore>> {
1061        if let Some(entry) = self.session_stores.get(palace_id) {
1062            return Ok(entry.clone());
1063        }
1064        let dir = self.data_root.join(palace_id);
1065        std::fs::create_dir_all(&dir)
1066            .map_err(|e| anyhow::anyhow!("create palace dir {}: {e}", dir.display()))?;
1067        let store = Arc::new(ChatSessionStore::open(&dir.join("chat_sessions.db"))?);
1068        self.session_stores
1069            .insert(palace_id.to_string(), store.clone());
1070        Ok(store)
1071    }
1072
1073    /// Builder-style setter for the default palace name.
1074    ///
1075    /// Why: `serve --palace <name>` wants to bind every tool call to a
1076    /// project-scoped namespace without forcing every MCP request to repeat
1077    /// the palace argument.
1078    /// What: Returns `self` with `default_palace = Some(name)`.
1079    /// Test: `default_palace_used_when_arg_omitted` covers the resolution
1080    /// path; this setter is exercised there.
1081    pub fn with_default_palace(mut self, name: Option<String>) -> Self {
1082        self.default_palace = name;
1083        self
1084    }
1085
1086    /// Resolve (or initialize) the shared embedder.
1087    ///
1088    /// Why: FastEmbedder load is expensive — we share one instance across all
1089    /// tool calls; the `OnceCell` ensures concurrent first-use races collapse
1090    /// to a single load.
1091    /// What: Returns `Arc<FastEmbedder>` on success. Errors propagate from the
1092    /// underlying ONNX load.
1093    /// Test: Indirectly via `dispatch_remember_then_recall`.
1094    /// Resolve the active chat provider, auto-detecting on first call.
1095    ///
1096    /// Why: Provider selection depends on filesystem-loaded config plus a
1097    /// network probe (Ollama liveness), so it must be lazily initialised at
1098    /// runtime. Caching the choice in a `OnceCell` keeps it stable across
1099    /// concurrent requests without re-probing on every chat call.
1100    /// What: On first use loads `~/.trusty-memory/config.toml`, prefers an
1101    /// auto-detected Ollama instance (when `local_model.enabled`), and falls
1102    /// back to OpenRouter when an API key is set. Returns `Ok(None)` when
1103    /// neither is available so the caller can emit a 412.
1104    /// Test: `web::tests::providers_endpoint_returns_payload` covers the
1105    /// detection path indirectly through `/api/v1/chat/providers`.
1106    pub async fn chat_provider(&self) -> Option<Arc<dyn ChatProvider>> {
1107        self.chat_provider
1108            .get_or_init(|| async {
1109                // Why (issue #226): `service::load_user_config` is the
1110                //      axum-free home of the loader; the `web::load_user_config`
1111                //      re-export only exists for the HTTP handlers. Going
1112                //      direct to `service` keeps this method usable when
1113                //      the `axum-server` feature is disabled.
1114                let cfg = crate::service::load_user_config().unwrap_or_default();
1115                if cfg.local_model.enabled {
1116                    if let Some(mut p) =
1117                        trusty_common::auto_detect_local_provider(&cfg.local_model.base_url).await
1118                    {
1119                        // auto_detect returns an empty model id; callers must
1120                        // set the configured model name themselves.
1121                        p.model = cfg.local_model.model.clone();
1122                        return Some(Arc::new(p) as Arc<dyn ChatProvider>);
1123                    }
1124                }
1125                if !cfg.openrouter_api_key.is_empty() {
1126                    return Some(Arc::new(trusty_common::OpenRouterProvider::new(
1127                        cfg.openrouter_api_key,
1128                        cfg.openrouter_model,
1129                    )) as Arc<dyn ChatProvider>);
1130                }
1131                None
1132            })
1133            .await
1134            .clone()
1135    }
1136
1137    /// Spawn a fire-and-forget background task that auto-discovers project
1138    /// aliases under `project_root` and asserts new ones into `palace`.
1139    ///
1140    /// Why (issue #42): Projects carry implicit shorthand — cargo package
1141    /// names that differ from their directory, binary names that differ
1142    /// from packages, first-letter abbreviations — that should be surfaced
1143    /// without a user ever calling `add_alias`. Running discovery as a
1144    /// detached task on palace-open keeps startup latency unchanged: the
1145    /// daemon binds and starts serving immediately while the discovery scan
1146    /// completes in the background, and any newly-asserted aliases land in
1147    /// the prompt cache before the model's next `get_prompt_context` call.
1148    /// What: clones `self` (cheap; `Arc`-backed), spawns a tokio task that
1149    /// invokes the `discover_aliases` tool handler directly so the
1150    /// dedup + cache-rebuild logic runs exactly the same path as the MCP
1151    /// tool call. Errors are logged at `warn!`; one failed discovery never
1152    /// destabilises the daemon.
1153    /// Test: not unit-tested (timing-dependent fire-and-forget); the
1154    /// underlying `discover_aliases` dispatch is covered by
1155    /// `dispatch_discover_aliases_inserts_new_and_dedupes` in `tools::tests`.
1156    pub fn spawn_alias_discovery(&self, palace: String, project_root: PathBuf) {
1157        let state = self.clone();
1158        tokio::spawn(async move {
1159            let args = serde_json::json!({
1160                "palace": palace,
1161                "project_root": project_root.to_string_lossy(),
1162            });
1163            match tools::dispatch_tool(&state, "discover_aliases", args).await {
1164                Ok(result) => tracing::info!(
1165                    new = ?result.get("new"),
1166                    already_known = ?result.get("already_known"),
1167                    "alias discovery complete"
1168                ),
1169                Err(e) => tracing::warn!("alias discovery failed: {e:#}"),
1170            }
1171        });
1172    }
1173
1174    pub async fn embedder(&self) -> Result<Arc<FastEmbedder>> {
1175        let cell = self.embedder.clone();
1176        let embedder = cell
1177            .get_or_try_init(|| async {
1178                let e = FastEmbedder::new().await?;
1179                Ok::<Arc<FastEmbedder>, anyhow::Error>(Arc::new(e))
1180            })
1181            .await?
1182            .clone();
1183        Ok(embedder)
1184    }
1185}
1186
1187impl std::fmt::Debug for AppState {
1188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1189        f.debug_struct("AppState")
1190            .field("version", &self.version)
1191            .field("data_root", &self.data_root)
1192            .field("registry_len", &self.registry.len())
1193            .finish()
1194    }
1195}
1196
1197/// Handle a single MCP JSON-RPC message and produce its response.
1198///
1199/// Why: Pulled out of the stdio loop so unit tests can drive every method
1200/// without touching real stdin/stdout.
1201/// What: Routes `initialize`, `tools/list`, `tools/call`, `ping`, and the
1202/// `notifications/initialized` notification (which returns `Value::Null`).
1203/// Test: See unit tests below — initialize/list/call all return expected
1204/// JSON-RPC envelopes; notifications return `Null` (no response written).
1205pub async fn handle_message(state: &AppState, msg: Value) -> Value {
1206    let id = msg.get("id").cloned().unwrap_or(Value::Null);
1207    let method = msg.get("method").and_then(|m| m.as_str()).unwrap_or("");
1208
1209    match method {
1210        "initialize" => {
1211            let extra = state
1212                .default_palace
1213                .as_ref()
1214                .map(|dp| json!({ "default_palace": dp }));
1215            let result = initialize_response("trusty-memory", &state.version, extra);
1216            // Why (issue #42): prompt-facts now flow through the
1217            // per-message `get_prompt_context` tool rather than MCP
1218            // prompts, so we no longer advertise the `prompts` capability.
1219            json!({
1220                "jsonrpc": "2.0",
1221                "id": id,
1222                "result": result,
1223            })
1224        }
1225        // Notifications must NOT receive a response.
1226        "notifications/initialized" | "notifications/cancelled" => Value::Null,
1227        "tools/list" => json!({
1228            "jsonrpc": "2.0",
1229            "id": id,
1230            "result": tools::tool_definitions_with(state.default_palace.is_some())
1231        }),
1232        // OpenRPC 1.3.2 discovery — see `openrpc.rs`. Returns the full
1233        // service description so orchestrators (open-mpm, etc.) can
1234        // introspect every tool and its required `memory.read`/`memory.write`
1235        // scope without bespoke per-server adapters.
1236        "rpc.discover" => json!({
1237            "jsonrpc": "2.0",
1238            "id": id,
1239            "result": openrpc::build_discover_response(
1240                &state.version,
1241                state.default_palace.is_some(),
1242            ),
1243        }),
1244        "tools/call" => {
1245            let params = msg.get("params").cloned().unwrap_or_default();
1246            let tool_name = params
1247                .get("name")
1248                .and_then(|n| n.as_str())
1249                .unwrap_or("")
1250                .to_string();
1251            let args = params.get("arguments").cloned().unwrap_or_default();
1252            match tools::dispatch_tool(state, &tool_name, args).await {
1253                Ok(content) => {
1254                    // Why: tools that return a bare JSON string (e.g.
1255                    // `get_prompt_context` returning the formatted
1256                    // Markdown block) should surface as plain text in the
1257                    // MCP `content[0].text` field — wrapping in
1258                    // `Value::to_string()` would re-quote the payload and
1259                    // force every caller to strip outer quotes.
1260                    let text = match &content {
1261                        Value::String(s) => s.clone(),
1262                        other => other.to_string(),
1263                    };
1264                    json!({
1265                        "jsonrpc": "2.0",
1266                        "id": id,
1267                        "result": {
1268                            "content": [{"type": "text", "text": text}]
1269                        }
1270                    })
1271                }
1272                Err(e) => json!({
1273                    "jsonrpc": "2.0",
1274                    "id": id,
1275                    // Why: anyhow's `{:#}` alternate format walks the full
1276                    // `Caused by:` chain so MCP clients see actionable
1277                    // detail (e.g. "PalaceHandle::remember_with_options:
1278                    // filter rejected: too short") instead of just the
1279                    // outermost context label.
1280                    "error": {"code": -32603, "message": format!("{e:#}")}
1281                }),
1282            }
1283        }
1284        "ping" => json!({"jsonrpc": "2.0", "id": id, "result": {}}),
1285        _ => json!({
1286            "jsonrpc": "2.0",
1287            "id": id,
1288            "error": {
1289                "code": -32601,
1290                "message": format!("Method not found: {method}")
1291            }
1292        }),
1293    }
1294}
1295
1296/// Preferred starting port for the trusty-memory HTTP daemon.
1297///
1298/// Why: keeps the well-known default stable for clients that have hard-coded
1299/// `127.0.0.1:7070` in their configuration, while still allowing dynamic
1300/// walking when the port is in use (`DYNAMIC_PORT_RANGE` ports starting here).
1301/// What: `7070` — historic default, matches the launchd plist's prior value.
1302/// Test: covered indirectly by `bind_dynamic_port_returns_listener`.
1303pub const DEFAULT_HTTP_PORT: u16 = 7070;
1304
1305/// Number of consecutive ports `bind_dynamic_port` walks before falling back
1306/// to the OS-assigned port. Matches the trusty-search convention.
1307const DYNAMIC_PORT_RANGE: u16 = 10;
1308
1309/// Path to the canonical address-discovery file for the trusty-memory daemon.
1310///
1311/// Why: clients (CLI, MCP tools, dashboards) need to find the running daemon
1312/// without configuration when the port was selected dynamically. Using
1313/// `trusty_common::resolve_data_dir` aligns this path with the location
1314/// that `trusty_common::read_daemon_addr("trusty-memory")` reads from, so
1315/// `prompt-context`, `doctor`, and `start`'s probe all find the running daemon.
1316/// The old `~/.trusty-memory/http_addr` path and the new
1317/// `~/Library/Application Support/trusty-memory/http_addr` (macOS) path were
1318/// divergent — the daemon wrote one; readers expected the other.
1319/// What: returns `{resolve_data_dir("trusty-memory")}/http_addr`, or `None` if
1320/// the data dir cannot be resolved (locked-down container, no passwd entry).
1321/// Test: `http_addr_path_uses_resolve_data_dir`.
1322pub fn http_addr_path() -> Option<PathBuf> {
1323    trusty_common::resolve_data_dir("trusty-memory")
1324        .ok()
1325        .map(|d| d.join("http_addr"))
1326}
1327
1328/// Bind a `TcpListener` to `127.0.0.1`, dynamically selecting a port.
1329///
1330/// Why: the historic default `7070` is convenient for clients but a stale
1331/// process or a second daemon must not produce a noisy failure. Walking
1332/// `DEFAULT_HTTP_PORT..DEFAULT_HTTP_PORT+DYNAMIC_PORT_RANGE` first preserves
1333/// backwards compatibility for the common case; OS-assigned fallback (`:0`)
1334/// guarantees the daemon always comes up even when every preferred port is
1335/// busy.
1336/// What: returns the first successful `TcpListener`. Tries 7070..=7079
1337/// in order, then falls back to OS-assigned. Caller inspects
1338/// `local_addr()` to learn the chosen port.
1339/// Test: `bind_dynamic_port_returns_listener` confirms it always binds *some*
1340/// port even after another listener occupies the preferred one.
1341pub async fn bind_dynamic_port() -> Result<tokio::net::TcpListener> {
1342    let preferred: SocketAddr = SocketAddr::from(([127, 0, 0, 1], DEFAULT_HTTP_PORT));
1343    // First: walk the preferred range (7070..=7079).
1344    if let Ok(listener) =
1345        trusty_common::bind_with_auto_port(preferred, DYNAMIC_PORT_RANGE - 1).await
1346    {
1347        return Ok(listener);
1348    }
1349    // Last resort: ask the kernel for any free port. `bind_with_auto_port`
1350    // with `:0` resolves immediately to the OS-assigned port.
1351    tracing::warn!(
1352        "all ports {DEFAULT_HTTP_PORT}..{} in use; requesting OS-assigned port",
1353        DEFAULT_HTTP_PORT + DYNAMIC_PORT_RANGE - 1
1354    );
1355    let any: SocketAddr = SocketAddr::from(([127, 0, 0, 1], 0));
1356    trusty_common::bind_with_auto_port(any, 0).await
1357}
1358
1359/// Write the bound `host:port` to `~/.trusty-memory/http_addr` atomically.
1360///
1361/// Why: clients must read the file mid-write without observing a partial
1362/// value. Writing to a `.tmp` sibling and renaming over the target gives
1363/// POSIX atomicity, matching the trusty-search implementation.
1364/// What: creates the parent directory if missing; writes `addr` followed by a
1365/// trailing newline (avoids the "no newline at end of file" warnings from
1366/// `cat`); renames `.tmp` → `http_addr`. Best-effort: I/O errors are
1367/// returned to the caller so `run_http_on` can log without panicking.
1368/// Test: `http_addr_file_round_trip_via_helpers`.
1369#[cfg(feature = "axum-server")]
1370fn write_http_addr_file(path: &Path, addr: &SocketAddr) -> std::io::Result<()> {
1371    use std::io::Write;
1372    if let Some(parent) = path.parent() {
1373        std::fs::create_dir_all(parent)?;
1374    }
1375    let tmp = path.with_extension("addr.tmp");
1376    {
1377        let mut f = std::fs::File::create(&tmp)?;
1378        writeln!(f, "{addr}")?;
1379        f.sync_all()?;
1380    }
1381    std::fs::rename(&tmp, path)?;
1382    Ok(())
1383}
1384
1385/// Resolve the dotfile discovery path `~/.trusty-memory/http_addr`.
1386///
1387/// Why (issue #498): external tooling such as claude-mpm's `migrate_trusty_autodetect`
1388/// reads `~/.trusty-memory/http_addr` to find the running daemon's port. On
1389/// macOS, `resolve_data_dir("trusty-memory")` returns
1390/// `~/Library/Application Support/trusty-memory/`, not `~/.trusty-memory/`,
1391/// so the daemon was writing to the OS-standard location while readers expected
1392/// the dotfile location. Writing to both locations keeps every reader happy
1393/// regardless of which convention they follow.
1394/// What: returns `$HOME/.trusty-memory/http_addr`, or `None` when
1395/// `dirs::home_dir()` is unavailable.
1396/// Test: `dotfile_http_addr_path_uses_home_dir`.
1397#[cfg(feature = "axum-server")]
1398fn dotfile_http_addr_path() -> Option<PathBuf> {
1399    dirs::home_dir().map(|h| h.join(".trusty-memory").join("http_addr"))
1400}
1401
1402/// Run the optional HTTP/SSE + web admin server.
1403///
1404/// Why: A long-running daemon mode lets non-stdio clients (browsers, curl,
1405/// future remote agents) hit `/health`, the `/api/v1/*` REST surface, and the
1406/// embedded admin SPA.
1407/// What: axum router built from `web::router()` plus a `/sse` stub for the
1408/// existing MCP-over-SSE clients. Caller provides a pre-bound listener so
1409/// port auto-detection lives at the call site. Before accepting connections
1410/// the daemon stamps the bound `host:port` onto `AppState.bound_addr` and
1411/// writes `~/.trusty-memory/http_addr` so clients can discover the live port.
1412/// On shutdown the file is removed best-effort (a stale file with the wrong
1413/// port is worse than a missing one).
1414/// Test: `cargo test -p trusty-memory web::tests` exercises the router shape;
1415/// manual: `curl http://127.0.0.1:<port>/health` returns `ok` with `addr`.
1416#[cfg(feature = "axum-server")]
1417pub async fn run_http_on(state: AppState, listener: tokio::net::TcpListener) -> Result<()> {
1418    use axum::routing::get;
1419
1420    // Issue #35: recompute the `data_root` disk footprint every 10 s on a
1421    // background task so `GET /health` reports `disk_bytes` without doing a
1422    // recursive directory walk on the request path.
1423    spawn_disk_size_ticker(state.clone());
1424
1425    // Issue #228: emit aggregate `StatusChanged` on a fixed cadence rather
1426    // than on every drawer write. The previous design called
1427    // `aggregate_status_event` from every `memory_remember` / `memory_note`
1428    // / `memory_forget` (and the matching HTTP handlers), each of which
1429    // walked the data root + opened every palace handle. Coalescing the
1430    // emit to a 30 s ticker keeps dashboards live without dragging an
1431    // O(N palaces) recompute onto the write hot path.
1432    spawn_status_event_ticker(state.clone());
1433
1434    // Capture and advertise the bound address BEFORE serving so the first
1435    // request handler — and the http_addr discovery file — see the real port
1436    // even if `local_addr()` would otherwise be racy.
1437    let local = listener.local_addr().ok();
1438    let (written_path, written_dotfile_path) = if let Some(a) = local {
1439        // Stash on state for handlers (e.g. /health) to surface.
1440        let _ = state.bound_addr.set(a);
1441        info!("HTTP server listening on http://{a}");
1442        eprintln!("HTTP server listening on http://{a}");
1443        // Primary: write to the OS-standard data dir (`~/Library/Application
1444        // Support/trusty-memory/http_addr` on macOS, `~/.local/share/…` on
1445        // Linux). This is what `trusty_common::read_daemon_addr` reads.
1446        // Best-effort: a missing $HOME or read-only fs is non-fatal.
1447        let primary = match http_addr_path() {
1448            Some(p) => match write_http_addr_file(&p, &a) {
1449                Ok(()) => {
1450                    info!("wrote daemon address to {}", p.display());
1451                    Some(p)
1452                }
1453                Err(e) => {
1454                    tracing::warn!("could not write {}: {e}", p.display());
1455                    None
1456                }
1457            },
1458            None => {
1459                tracing::warn!("no $HOME — skipping http_addr discovery file");
1460                None
1461            }
1462        };
1463        // Issue #498: also write to `~/.trusty-memory/http_addr` so external
1464        // tools (e.g. claude-mpm's `migrate_trusty_autodetect`) that read the
1465        // dotfile path can discover the daemon's port. On macOS the OS-standard
1466        // path differs from the dotfile path; writing both ensures consumers
1467        // using either convention find the file. Best-effort: failures are
1468        // logged but do not block startup.
1469        let dotfile = match dotfile_http_addr_path() {
1470            Some(p) => match write_http_addr_file(&p, &a) {
1471                Ok(()) => {
1472                    info!("wrote daemon address to dotfile {}", p.display());
1473                    Some(p)
1474                }
1475                Err(e) => {
1476                    tracing::warn!("could not write dotfile {}: {e}", p.display());
1477                    None
1478                }
1479            },
1480            None => None,
1481        };
1482        (primary, dotfile)
1483    } else {
1484        (None, None)
1485    };
1486
1487    // Multi-transport refactor: bind the Unix domain socket alongside
1488    // the HTTP listener. The UDS serves NDJSON JSON-RPC 2.0 for the
1489    // `trusty-memory-mcp-bridge` binary (and any local CLI that wants
1490    // to skip HTTP overhead). Failures are logged but never block the
1491    // HTTP server from coming up — UDS is best-effort on hosts where
1492    // it's unsupported (e.g. some Docker overlays).
1493    let uds_sock_path = spawn_uds_listener(state.clone()).await;
1494
1495    // Keep a handle to the BM25 supervisor (if any) so we can call
1496    // `shutdown()` on the exit path. Cloning here is cheap (`Arc`) and
1497    // detaches the lifetime of the supervisor from the `state` move into
1498    // the router below.
1499    let bm25_supervisor = state.bm25_supervisor.clone();
1500
1501    let app = web::router()
1502        .route("/sse", get(sse_handler))
1503        .with_state(state);
1504
1505    let serve_result = axum::serve(listener, app).await;
1506
1507    // Best-effort cleanup: remove `http_addr` files so stale clients fail fast
1508    // instead of timing out against a dead port. Remove both the OS-standard
1509    // path and the dotfile path (#498).
1510    if let Some(p) = written_path.as_ref() {
1511        let _ = std::fs::remove_file(p);
1512    }
1513    if let Some(p) = written_dotfile_path.as_ref() {
1514        let _ = std::fs::remove_file(p);
1515    }
1516    if let Some(p) = uds_sock_path.as_ref() {
1517        let _ = std::fs::remove_file(p);
1518    }
1519
1520    // Issue #193: gracefully reap every spawned BM25 daemon before the
1521    // process exits so each one gets a chance to flush its snapshot and
1522    // unlink its socket. `kill_on_drop=true` on the children would
1523    // SIGKILL them on Drop anyway, but that skips the daemon's own
1524    // shutdown sequence and leaves stale sockets behind.
1525    if let Some(supervisor) = bm25_supervisor {
1526        supervisor.shutdown().await;
1527    }
1528
1529    serve_result?;
1530    Ok(())
1531}
1532
1533/// Spawn the UDS accept loop alongside the HTTP server.
1534///
1535/// Why: UDS is an additive transport — failing to bind it (unusual
1536/// $TMPDIR layout, permission error on macOS) should not block the
1537/// HTTP daemon from coming up. Logging the failure and returning
1538/// `None` lets the caller skip cleanup later.
1539/// What: resolves [`transport::uds::socket_path`], cleans any stale
1540/// file, binds, writes the `<data_root>/uds_addr` discovery file, and
1541/// spawns the accept loop on a background tokio task. Returns the
1542/// bound path so the caller can clean it up on shutdown.
1543/// Test: covered by `uds_ndjson_roundtrip` in the integration tests
1544/// and the unit tests in [`transport::uds`].
1545#[cfg(feature = "axum-server")]
1546async fn spawn_uds_listener(state: AppState) -> Option<PathBuf> {
1547    // Use a data-root-scoped socket path so multiple daemons (typical
1548    // in tests) don't collide on the shared `$TMPDIR/trusty-memory.sock`.
1549    // Production daemons (those rooted at the canonical data dir) still
1550    // get the canonical socket path so the bridge can find it without
1551    // reading the discovery file.
1552    let sock_path = transport::uds::socket_path_for(&state.data_root);
1553    let listener = match transport::uds::bind_uds(&sock_path).await {
1554        Ok(l) => l,
1555        Err(e) => {
1556            tracing::warn!(
1557                "UDS bind at {} failed: {e:#}; continuing without UDS transport",
1558                sock_path.display()
1559            );
1560            return None;
1561        }
1562    };
1563    info!("UDS listener bound at {}", sock_path.display());
1564    eprintln!("UDS listener bound at {}", sock_path.display());
1565    // Best-effort: write the address discovery file so the bridge can
1566    // find the live socket even when the daemon was started with an
1567    // unusual $TMPDIR.
1568    if let Err(e) = transport::uds::write_uds_addr_file(&state.data_root, &sock_path) {
1569        tracing::warn!(
1570            "could not write {}/{}: {e:#}",
1571            state.data_root.display(),
1572            transport::uds::UDS_ADDR_FILE
1573        );
1574    }
1575    let task_state = state.clone();
1576    tokio::spawn(async move {
1577        if let Err(e) = transport::uds::run_uds(task_state, listener).await {
1578            tracing::error!("UDS accept loop exited: {e:#}");
1579        }
1580    });
1581    Some(sock_path)
1582}
1583
1584/// Convenience: bind `addr` and serve via [`run_http_on`].
1585#[cfg(feature = "axum-server")]
1586pub async fn run_http(state: AppState, addr: std::net::SocketAddr) -> Result<()> {
1587    let listener = tokio::net::TcpListener::bind(addr).await?;
1588    run_http_on(state, listener).await
1589}
1590
1591/// Convenience: bind dynamically (7070..=7079, OS fallback) and serve.
1592///
1593/// Why: `trusty-memory serve` with no `--http` flag is the canonical
1594/// launchd-managed daemon entry point. Dynamic binding lets a stale daemon
1595/// or a hand-spawned `serve --http 127.0.0.1:7070` coexist without breaking
1596/// the launchd-managed instance.
1597/// What: calls [`bind_dynamic_port`] then [`run_http_on`].
1598/// Test: integration via `trusty-memory serve` + `cat ~/.trusty-memory/http_addr`.
1599#[cfg(feature = "axum-server")]
1600pub async fn run_http_dynamic(state: AppState) -> Result<()> {
1601    let listener = bind_dynamic_port().await?;
1602    run_http_on(state, listener).await
1603}
1604
1605/// Spawn a background ticker that recomputes the `data_root` disk footprint
1606/// every 10 seconds and stores it in `state.disk_bytes` (issue #35).
1607///
1608/// Why: `GET /health` reports `disk_bytes`. Walking the data directory on
1609/// every health request would turn a frequent health poll into unbounded
1610/// recursive I/O. Computing it off the request path on a fixed cadence keeps
1611/// `/health` cheap and bounds the staleness to ~10 s — fine for an
1612/// at-a-glance footprint figure.
1613/// What: spawns a detached tokio task. `AppState` is cheap to `Clone` (all
1614/// `Arc` fields), so the task holds a full clone; the daemon process lives
1615/// for the lifetime of the server anyway, so no `Weak` downgrade is needed.
1616/// Each tick runs the blocking directory walk on `spawn_blocking` so it never
1617/// stalls the async runtime, then stores the byte total atomically.
1618/// Test: `health_endpoint_includes_resource_fields` asserts the field shape;
1619/// the ticker cadence is not unit-tested (timing-dependent).
1620#[cfg(feature = "axum-server")]
1621fn spawn_disk_size_ticker(state: AppState) {
1622    tokio::spawn(async move {
1623        let mut interval = tokio::time::interval(std::time::Duration::from_secs(10));
1624        loop {
1625            interval.tick().await;
1626            let dir = state.data_root.clone();
1627            // The directory walk is blocking filesystem I/O — run it on the
1628            // blocking pool so it never parks an async worker thread.
1629            let bytes = tokio::task::spawn_blocking(move || {
1630                trusty_common::sys_metrics::dir_size_bytes(&dir)
1631            })
1632            .await
1633            .unwrap_or(0);
1634            state
1635                .disk_bytes
1636                .store(bytes, std::sync::atomic::Ordering::Relaxed);
1637        }
1638    });
1639}
1640
1641/// Interval between aggregate-status snapshot emits on the SSE bus.
1642///
1643/// Why (issue #228): mutations used to fire `StatusChanged` synchronously on
1644/// the write path, which forced an O(N palaces) sum of drawer / vector / KG
1645/// counts on every `memory_remember`. Coalescing into a fixed-cadence ticker
1646/// lets dashboards stay current (a 30 s lag is invisible at human scale)
1647/// while keeping the write path free of aggregate work.
1648/// What: 30 seconds — short enough that the operator UI doesn't feel stale
1649/// between manual writes, long enough that the recompute cost (in-memory
1650/// registry walk plus the redb `count_active_triples` per palace) is a
1651/// rounding error on the daemon's CPU budget.
1652/// Test: covered indirectly — the math has not changed, only the cadence.
1653#[allow(dead_code)]
1654const STATUS_EVENT_TICK_SECS: u64 = 30;
1655
1656/// Spawn a background ticker that emits `DaemonEvent::StatusChanged` every
1657/// [`STATUS_EVENT_TICK_SECS`] seconds (issue #228).
1658///
1659/// Why: replaces the per-write `state.emit(self.aggregate_status_event())`
1660/// call sites that used to recompute the aggregate every time a drawer was
1661/// created or deleted. Walking N palaces on every write blocks the async
1662/// runtime; coalescing the emit onto a ticker keeps dashboards up-to-date
1663/// without that cost.
1664/// What: spawns a detached tokio task that holds a full `AppState` clone
1665/// (cheap — every field is `Arc`-backed) and ticks every
1666/// [`STATUS_EVENT_TICK_SECS`] seconds. Each tick computes
1667/// `MemoryService::aggregate_status_event` (which now iterates the
1668/// in-memory registry, not disk) and broadcasts it via `state.emit`. If
1669/// no SSE subscribers are connected the broadcast `send` is a cheap no-op,
1670/// so the ticker imposes no cost when nobody is listening.
1671/// Test: not unit-tested (timing-dependent fire-and-forget); the underlying
1672/// `aggregate_status_event` math is exercised by the existing
1673/// `status_endpoint_returns_payload` path.
1674#[allow(dead_code)]
1675fn spawn_status_event_ticker(state: AppState) {
1676    tokio::spawn(async move {
1677        let mut interval =
1678            tokio::time::interval(std::time::Duration::from_secs(STATUS_EVENT_TICK_SECS));
1679        // The first tick fires immediately, which is fine: it gives SSE
1680        // subscribers a baseline `StatusChanged` shortly after they connect.
1681        loop {
1682            interval.tick().await;
1683            let event = service::MemoryService::new(state.clone()).aggregate_status_event();
1684            state.emit(event);
1685        }
1686    });
1687}
1688
1689/// Live SSE event stream — pushes `DaemonEvent` frames to dashboard clients.
1690///
1691/// Why: The dashboard subscribes once and reacts to live pushes (palace
1692/// created, drawer added/deleted, dream completed, status changed) instead of
1693/// polling `/api/v1/*` endpoints.
1694/// What: Subscribes to `state.events`, emits an initial `connected` frame,
1695/// then forwards every `DaemonEvent` as `data: <json>\n\n`. Lagged
1696/// subscribers receive a `lag` frame indicating skipped events; channel
1697/// closure ends the stream.
1698/// Test: `web::tests::sse_stream_emits_palace_created` (covers subscribe +
1699/// emit + receive); manual: `curl -N http://.../sse`.
1700#[cfg(feature = "axum-server")]
1701pub(crate) async fn sse_handler(
1702    axum::extract::State(state): axum::extract::State<AppState>,
1703) -> impl axum::response::IntoResponse {
1704    use futures::StreamExt;
1705    use tokio_stream::wrappers::BroadcastStream;
1706
1707    let rx = state.events.subscribe();
1708    let initial = futures::stream::once(async {
1709        Ok::<axum::body::Bytes, std::io::Error>(axum::body::Bytes::from(
1710            "data: {\"type\":\"connected\"}\n\n",
1711        ))
1712    });
1713    let events = BroadcastStream::new(rx).map(|res| {
1714        let frame = match res {
1715            Ok(event) => match serde_json::to_string(&event) {
1716                Ok(json) => format!("data: {json}\n\n"),
1717                Err(e) => format!("data: {{\"type\":\"error\",\"message\":\"{e}\"}}\n\n"),
1718            },
1719            Err(tokio_stream::wrappers::errors::BroadcastStreamRecvError::Lagged(n)) => {
1720                format!("data: {{\"type\":\"lag\",\"skipped\":{n}}}\n\n")
1721            }
1722        };
1723        Ok::<axum::body::Bytes, std::io::Error>(axum::body::Bytes::from(frame))
1724    });
1725    let stream = initial.chain(events);
1726
1727    axum::response::Response::builder()
1728        .header("Content-Type", "text/event-stream")
1729        .header("Cache-Control", "no-cache")
1730        .header("X-Accel-Buffering", "no")
1731        .body(axum::body::Body::from_stream(stream))
1732        .expect("valid SSE response")
1733}
1734
1735#[cfg(test)]
1736mod tests {
1737    use super::*;
1738
1739    /// Why: Issue #234 — previously we `mem::forget`ed the `TempDir` so tests
1740    /// could keep using `AppState` without juggling the directory handle, but
1741    /// that leaked one temp directory per test (262+ accumulated each run).
1742    /// What: Returns the `TempDir` alongside the `AppState` so the caller can
1743    /// bind it (`let (state, _tmp) = ...;`) and let drop semantics clean up
1744    /// when the test scope ends.
1745    /// Test: Every test in this module that constructs state.
1746    fn test_state() -> (AppState, tempfile::TempDir) {
1747        let tmp = tempfile::tempdir().expect("tempdir");
1748        let root = tmp.path().to_path_buf();
1749        // Issue #88: bypass palace-slug enforcement so lib tests that call
1750        // `palace_create` with arbitrary names keep passing.
1751        // SAFETY: constant idempotent write; safe across test threads.
1752        unsafe {
1753            std::env::set_var("TRUSTY_SKIP_PALACE_ENFORCEMENT", "1");
1754        }
1755        (AppState::new(root), tmp)
1756    }
1757
1758    #[tokio::test]
1759    async fn initialize_returns_protocol_version_and_capabilities() {
1760        let (state, _tmp) = test_state();
1761        let req = json!({
1762            "jsonrpc": "2.0",
1763            "id": 1,
1764            "method": "initialize",
1765            "params": {
1766                "protocolVersion": "2024-11-05",
1767                "capabilities": {},
1768                "clientInfo": {"name": "test", "version": "0"}
1769            }
1770        });
1771        let resp = handle_message(&state, req).await;
1772        assert_eq!(resp["jsonrpc"], "2.0");
1773        assert_eq!(resp["id"], 1);
1774        assert_eq!(resp["result"]["protocolVersion"], "2024-11-05");
1775        assert!(resp["result"]["capabilities"]["tools"].is_object());
1776        assert_eq!(resp["result"]["serverInfo"]["name"], "trusty-memory");
1777    }
1778
1779    #[tokio::test]
1780    async fn initialized_notification_returns_null() {
1781        let (state, _tmp) = test_state();
1782        let req = json!({
1783            "jsonrpc": "2.0",
1784            "method": "notifications/initialized",
1785            "params": {}
1786        });
1787        let resp = handle_message(&state, req).await;
1788        assert!(resp.is_null());
1789    }
1790
1791    #[tokio::test]
1792    async fn tools_list_returns_all_tools() {
1793        let (state, _tmp) = test_state();
1794        let req = json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"});
1795        let resp = handle_message(&state, req).await;
1796        let tools = resp["result"]["tools"].as_array().expect("tools array");
1797        // Issue #99 added `memory_send_message`; issue #180 added
1798        // `palace_delete`; the #180 follow-up adds `palace_update` on top
1799        // of the 22-tool baseline.
1800        assert_eq!(tools.len(), 23);
1801    }
1802
1803    #[tokio::test]
1804    async fn unknown_method_returns_error() {
1805        let (state, _tmp) = test_state();
1806        let req = json!({"jsonrpc": "2.0", "id": 4, "method": "wat"});
1807        let resp = handle_message(&state, req).await;
1808        assert_eq!(resp["error"]["code"], -32601);
1809    }
1810
1811    #[tokio::test]
1812    async fn ping_returns_empty_result() {
1813        let (state, _tmp) = test_state();
1814        let req = json!({"jsonrpc": "2.0", "id": 5, "method": "ping"});
1815        let resp = handle_message(&state, req).await;
1816        assert!(resp["result"].is_object());
1817    }
1818
1819    #[tokio::test]
1820    async fn app_state_default_constructs() {
1821        let (s, _tmp) = test_state();
1822        assert!(!s.version.is_empty());
1823        assert!(s.registry.is_empty());
1824        assert!(s.default_palace.is_none());
1825    }
1826
1827    /// Why (issue #225): the previous implementation called `.expect()` on the
1828    /// tempdir fallback, which panicked the daemon at startup on hosts where
1829    /// neither the data root nor `std::env::temp_dir()` is writable
1830    /// (read-only Docker overlays, locked-down sandboxes). The activity log
1831    /// is documented as best-effort, so the fix returns a no-op `Discard`
1832    /// variant instead. This test forces both paths to fail and asserts the
1833    /// helper returns the discard variant rather than panicking.
1834    ///
1835    /// Skipped when running as root because `chmod 000` is a no-op for the
1836    /// root user — the kernel grants root access regardless of mode bits.
1837    /// CI typically runs as non-root, so coverage is preserved in the
1838    /// common case; local root invocations simply skip with a warning.
1839    #[test]
1840    #[cfg(unix)]
1841    fn open_activity_log_with_fallback_returns_discard_when_unwritable() {
1842        // Skip when running as root — chmod is ignored.
1843        // SAFETY: libc::geteuid is a thread-safe syscall with no preconditions.
1844        if unsafe { libc::geteuid() } == 0 {
1845            eprintln!(
1846                "skipping open_activity_log_with_fallback_returns_discard_when_unwritable: running as root"
1847            );
1848            return;
1849        }
1850
1851        use std::os::unix::fs::PermissionsExt;
1852
1853        // Build two unwritable directories: the primary "data root" and a
1854        // shadow "TMPDIR" so the tempdir fallback also fails.
1855        let outer = tempfile::tempdir().expect("outer tempdir");
1856        let primary = outer.path().join("primary");
1857        let tmpdir = outer.path().join("fake-tmp");
1858        std::fs::create_dir(&primary).expect("create primary");
1859        std::fs::create_dir(&tmpdir).expect("create tmpdir");
1860
1861        // chmod 000 on both — neither can be opened for write.
1862        std::fs::set_permissions(&primary, std::fs::Permissions::from_mode(0o000))
1863            .expect("chmod primary");
1864        std::fs::set_permissions(&tmpdir, std::fs::Permissions::from_mode(0o000))
1865            .expect("chmod tmpdir");
1866
1867        // Override the tempdir lookup so `open_activity_log_with_fallback`
1868        // hits our unwritable fake-tmp instead of the real system temp.
1869        // Note: env var mutation is process-global; this test is the only
1870        // accessor for `TMPDIR` in this test binary, and we restore the
1871        // previous value before returning.
1872        let prev_tmpdir = std::env::var_os("TMPDIR");
1873        std::env::set_var("TMPDIR", &tmpdir);
1874
1875        let log = open_activity_log_with_fallback(&primary);
1876
1877        // Restore TMPDIR ASAP so a panic later in the test doesn't leak it.
1878        match prev_tmpdir {
1879            Some(v) => std::env::set_var("TMPDIR", v),
1880            None => std::env::remove_var("TMPDIR"),
1881        }
1882
1883        // Restore permissions so the outer tempdir can clean up.
1884        let _ = std::fs::set_permissions(&primary, std::fs::Permissions::from_mode(0o700));
1885        let _ = std::fs::set_permissions(&tmpdir, std::fs::Permissions::from_mode(0o700));
1886
1887        assert!(
1888            log.is_discard(),
1889            "expected ActivityLog::Discard when both data root and tempdir are unwritable"
1890        );
1891
1892        // The Discard variant must still satisfy the public contract: no
1893        // panic on append/count/list.
1894        let id = log
1895            .append(
1896                ActivitySource::Http,
1897                None,
1898                "drawer_added",
1899                json!({"smoke": true}),
1900            )
1901            .expect("discard append must succeed");
1902        assert_eq!(id, 0);
1903        assert_eq!(log.count().expect("discard count"), 0);
1904        assert!(log
1905            .list(&ActivityFilter::default(), 10, 0)
1906            .expect("discard list")
1907            .is_empty());
1908    }
1909
1910    /// Why: Issue #26 — when `serve --palace <name>` is set, the MCP server
1911    /// must (a) report the default in the `initialize` `serverInfo`, (b)
1912    /// drop `palace` from the required schema in `tools/list`, and (c) let
1913    /// `tools/call` use the default when the caller omits `palace`.
1914    /// Test: Construct an AppState with a default palace, create that palace
1915    /// on disk via the registry, then call `memory_remember` without a
1916    /// `palace` argument and confirm it resolves to the default.
1917    #[tokio::test]
1918    async fn default_palace_used_when_arg_omitted() {
1919        let tmp = tempfile::tempdir().expect("tempdir");
1920        let root = tmp.path().to_path_buf();
1921
1922        // Pre-create the default palace so remember has somewhere to land.
1923        let registry = trusty_common::memory_core::PalaceRegistry::new();
1924        let palace = trusty_common::memory_core::Palace {
1925            id: trusty_common::memory_core::PalaceId::new("default-pal"),
1926            name: "default-pal".to_string(),
1927            description: None,
1928            created_at: chrono::Utc::now(),
1929            data_dir: root.join("default-pal"),
1930        };
1931        registry
1932            .create_palace(&root, palace)
1933            .expect("create_palace");
1934
1935        let state = AppState::new(root).with_default_palace(Some("default-pal".to_string()));
1936
1937        // (a) initialize advertises the default.
1938        let init = handle_message(
1939            &state,
1940            json!({"jsonrpc": "2.0", "id": 1, "method": "initialize"}),
1941        )
1942        .await;
1943        assert_eq!(
1944            init["result"]["serverInfo"]["default_palace"], "default-pal",
1945            "initialize must echo default_palace in serverInfo"
1946        );
1947
1948        // (b) tools/list drops `palace` from required when default is set.
1949        let list = handle_message(
1950            &state,
1951            json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
1952        )
1953        .await;
1954        let tools = list["result"]["tools"].as_array().expect("tools array");
1955        let remember = tools
1956            .iter()
1957            .find(|t| t["name"] == "memory_remember")
1958            .expect("memory_remember tool");
1959        let required: Vec<&str> = remember["inputSchema"]["required"]
1960            .as_array()
1961            .expect("required array")
1962            .iter()
1963            .filter_map(|v| v.as_str())
1964            .collect();
1965        assert!(
1966            !required.contains(&"palace"),
1967            "palace must not be required when default is configured; got {required:?}"
1968        );
1969        assert!(required.contains(&"text"));
1970
1971        // (c) tools/call resolves the default when arg is omitted.
1972        let call = handle_message(
1973            &state,
1974            json!({
1975                "jsonrpc": "2.0",
1976                "id": 3,
1977                "method": "tools/call",
1978                "params": {
1979                    "name": "memory_remember",
1980                    "arguments": {"text": "default palace test memory content with several tokens"},
1981                },
1982            }),
1983        )
1984        .await;
1985        // Successful dispatch returns `result.content[0].text` JSON.
1986        let text = call["result"]["content"][0]["text"]
1987            .as_str()
1988            .unwrap_or_else(|| panic!("expected success result, got {call}"));
1989        let parsed: Value = serde_json::from_str(text).expect("parse content json");
1990        assert_eq!(parsed["palace"], "default-pal");
1991        assert_eq!(parsed["status"], "stored");
1992        assert!(parsed["drawer_id"].as_str().is_some());
1993    }
1994
1995    /// Why: When no default is set, `tools/call` for a palace-bound tool
1996    /// without a `palace` argument should error helpfully rather than panic.
1997    #[tokio::test]
1998    async fn missing_palace_without_default_errors() {
1999        let (state, _tmp) = test_state();
2000        let resp = handle_message(
2001            &state,
2002            json!({
2003                "jsonrpc": "2.0",
2004                "id": 7,
2005                "method": "tools/call",
2006                "params": {
2007                    "name": "memory_recall",
2008                    "arguments": {"query": "anything"},
2009                },
2010            }),
2011        )
2012        .await;
2013        assert_eq!(resp["error"]["code"], -32603);
2014        let msg = resp["error"]["message"].as_str().unwrap_or("");
2015        assert!(
2016            msg.contains("missing 'palace'"),
2017            "expected helpful error, got: {msg}"
2018        );
2019    }
2020
2021    /// Why: regression for the "palaces lost on restart" bug — `AppState::new`
2022    /// builds an empty registry, so the daemon must call
2023    /// `load_palaces_from_disk` on startup to re-register palaces persisted by
2024    /// a previous run. Without that call the registry stays empty even though
2025    /// `palace.json` files exist on disk.
2026    /// What: persists two palaces under a tempdir (via the same
2027    /// `create_palace` path the `palace_create` tool uses), constructs a fresh
2028    /// `AppState` rooted there, calls `load_palaces_from_disk`, and asserts the
2029    /// returned count and registry contents.
2030    /// Test: this test itself.
2031    #[tokio::test]
2032    async fn load_palaces_from_disk_rehydrates_registry() {
2033        use trusty_common::memory_core::{Palace, PalaceId, PalaceRegistry};
2034
2035        let tmp = tempfile::tempdir().expect("tempdir");
2036        let root = tmp.path().to_path_buf();
2037
2038        // Phase 1: persist two palaces to disk, then drop the writer registry
2039        // so nothing is held in memory — simulating a prior daemon run.
2040        {
2041            let writer = PalaceRegistry::new();
2042            for id in ["alpha", "beta"] {
2043                let palace = Palace {
2044                    id: PalaceId::new(id),
2045                    name: id.to_string(),
2046                    description: None,
2047                    created_at: chrono::Utc::now(),
2048                    data_dir: root.join(id),
2049                };
2050                writer
2051                    .create_palace(&root, palace)
2052                    .expect("persist palace to disk");
2053            }
2054        }
2055
2056        // Add a stray non-palace subdirectory; the walker must ignore it.
2057        std::fs::create_dir_all(root.join("not-a-palace")).expect("mkdir");
2058
2059        // Phase 2: fresh AppState starts with an empty registry (the bug).
2060        let state = AppState::new(root);
2061        assert!(
2062            state.registry.is_empty(),
2063            "AppState::new must start with an empty registry"
2064        );
2065
2066        // The fix: hydrate from disk.
2067        let count = state
2068            .load_palaces_from_disk()
2069            .await
2070            .expect("load_palaces_from_disk");
2071
2072        assert_eq!(count, 2, "both persisted palaces should be loaded");
2073        assert_eq!(state.registry.len(), 2, "registry should hold both palaces");
2074        let ids: Vec<String> = state.registry.list().into_iter().map(|p| p.0).collect();
2075        assert!(ids.contains(&"alpha".to_string()));
2076        assert!(ids.contains(&"beta".to_string()));
2077    }
2078
2079    /// Why: existing installs (and the legacy standalone `trusty-memory` repo)
2080    /// nest palaces one level deeper under a `palaces/` subdirectory. When that
2081    /// subdirectory exists, `resolve_palace_registry_dir` must descend into it
2082    /// so the daemon scans the level that actually holds the `palace.json`
2083    /// files — otherwise it finds zero palaces, which is the restart bug.
2084    /// What: creates `<dir>/palaces/`, resolves, and asserts the nested path is
2085    /// returned.
2086    /// Test: this test itself.
2087    #[test]
2088    fn resolve_palace_registry_dir_prefers_palaces_subdir() {
2089        let tmp = tempfile::tempdir().expect("tempdir");
2090        let data_dir = tmp.path().to_path_buf();
2091        std::fs::create_dir_all(data_dir.join("palaces")).expect("mkdir palaces");
2092
2093        let resolved = resolve_palace_registry_dir(data_dir.clone());
2094        assert_eq!(resolved, data_dir.join("palaces"));
2095    }
2096
2097    /// Why: a fresh install with no `palaces/` subdirectory must fall back to
2098    /// the data dir itself (the current flat monorepo layout).
2099    #[test]
2100    fn resolve_palace_registry_dir_falls_back_to_data_dir() {
2101        let tmp = tempfile::tempdir().expect("tempdir");
2102        let data_dir = tmp.path().to_path_buf();
2103
2104        let resolved = resolve_palace_registry_dir(data_dir.clone());
2105        assert_eq!(resolved, data_dir);
2106    }
2107
2108    /// Why: end-to-end check that the nested-`palaces/` layout hydrates — the
2109    /// daemon resolves the registry dir via `resolve_palace_registry_dir`, so
2110    /// an `AppState` rooted there must load palaces persisted one level below
2111    /// the bare data dir.
2112    /// What: persists two palaces under `<root>/palaces/<id>/`, constructs an
2113    /// `AppState` rooted at the resolved registry dir, and asserts hydration
2114    /// finds both.
2115    /// Test: this test itself.
2116    #[tokio::test]
2117    async fn load_palaces_from_disk_handles_palaces_subdir() {
2118        use trusty_common::memory_core::{Palace, PalaceId, PalaceRegistry};
2119
2120        let tmp = tempfile::tempdir().expect("tempdir");
2121        let root = tmp.path().to_path_buf();
2122        let nested = root.join("palaces");
2123
2124        {
2125            let writer = PalaceRegistry::new();
2126            for id in ["cto", "engineering"] {
2127                let palace = Palace {
2128                    id: PalaceId::new(id),
2129                    name: id.to_string(),
2130                    description: None,
2131                    created_at: chrono::Utc::now(),
2132                    data_dir: nested.join(id),
2133                };
2134                // create_palace anchors data_dir under the passed root, so
2135                // pass `nested` here to land palaces under `<root>/palaces/`.
2136                writer
2137                    .create_palace(&nested, palace)
2138                    .expect("persist palace under palaces/ subdir");
2139            }
2140        }
2141
2142        // Mirror main.rs: resolve the registry dir, then root AppState there.
2143        let registry_dir = resolve_palace_registry_dir(root);
2144        assert_eq!(registry_dir, nested, "must resolve into palaces/ subdir");
2145        let state = AppState::new(registry_dir);
2146        let count = state
2147            .load_palaces_from_disk()
2148            .await
2149            .expect("load_palaces_from_disk");
2150
2151        assert_eq!(count, 2, "both nested palaces should be loaded");
2152        assert_eq!(state.registry.len(), 2);
2153        let ids: Vec<String> = state.registry.list().into_iter().map(|p| p.0).collect();
2154        assert!(ids.contains(&"cto".to_string()));
2155        assert!(ids.contains(&"engineering".to_string()));
2156    }
2157
2158    /// Why: an empty (or missing) palace registry directory must not error — a
2159    /// brand-new install has nothing to hydrate and should report zero.
2160    #[tokio::test]
2161    async fn load_palaces_from_disk_empty_root_returns_zero() {
2162        let (state, _tmp) = test_state();
2163        let count = state
2164            .load_palaces_from_disk()
2165            .await
2166            .expect("load_palaces_from_disk on empty root");
2167        assert_eq!(count, 0);
2168        assert!(state.registry.is_empty());
2169    }
2170
2171    /// Why (issue #228): hydration must seed `state.palace_names` so the
2172    /// MCP write hot path (`memory_remember` / `memory_note`) can resolve a
2173    /// friendly palace name without re-walking the data root on every call.
2174    /// Regression risk: a future refactor that forgets to populate the cache
2175    /// would silently degrade write latency.
2176    /// What: persists two palaces with distinct `name` values, constructs a
2177    /// fresh `AppState`, hydrates from disk, and asserts the cache holds the
2178    /// expected mappings.
2179    /// Test: this test itself.
2180    #[tokio::test]
2181    async fn palace_name_cache_populated_after_hydration() {
2182        use trusty_common::memory_core::{Palace, PalaceId, PalaceRegistry};
2183
2184        let tmp = tempfile::tempdir().expect("tempdir");
2185        let root = tmp.path().to_path_buf();
2186        {
2187            let writer = PalaceRegistry::new();
2188            for (id, name) in [("alpha", "Alpha Project"), ("beta", "Beta Project")] {
2189                let palace = Palace {
2190                    id: PalaceId::new(id),
2191                    name: name.to_string(),
2192                    description: None,
2193                    created_at: chrono::Utc::now(),
2194                    data_dir: root.join(id),
2195                };
2196                writer.create_palace(&root, palace).expect("persist palace");
2197            }
2198        }
2199
2200        let state = AppState::new(root);
2201        assert!(
2202            state.palace_names.is_empty(),
2203            "fresh AppState must start with an empty name cache"
2204        );
2205        state
2206            .load_palaces_from_disk()
2207            .await
2208            .expect("load_palaces_from_disk");
2209
2210        assert_eq!(state.palace_names.len(), 2, "cache must hold both palaces");
2211        assert_eq!(
2212            state.palace_names.get("alpha").map(|e| e.value().clone()),
2213            Some("Alpha Project".to_string()),
2214        );
2215        assert_eq!(
2216            state.palace_names.get("beta").map(|e| e.value().clone()),
2217            Some("Beta Project".to_string()),
2218        );
2219    }
2220
2221    /// Why (issue #228): `palace_create` (MCP tool) and `MemoryService::create_palace`
2222    /// (HTTP path) both insert into the name cache so a freshly-created palace
2223    /// is resolvable on the very next write — without waiting for the next
2224    /// hydration cycle.
2225    /// What: dispatches the `palace_create` MCP tool against a tempdir and
2226    /// asserts the cache row was written.
2227    /// Test: this test itself.
2228    #[tokio::test]
2229    async fn palace_name_cache_updates_on_create() {
2230        use serde_json::json;
2231
2232        let (state, _tmp) = test_state();
2233        let _ = tools::dispatch_tool(&state, "palace_create", json!({"name": "gamma"}))
2234            .await
2235            .expect("palace_create");
2236        assert_eq!(
2237            state.palace_names.get("gamma").map(|e| e.value().clone()),
2238            Some("gamma".to_string()),
2239            "palace_create must populate the in-memory name cache so writes \
2240             can resolve the friendly name without a disk walk"
2241        );
2242    }
2243
2244    /// Why: initialize without a default palace must omit `default_palace`
2245    /// from `serverInfo` so clients can detect the unbound mode.
2246    #[tokio::test]
2247    async fn initialize_without_default_palace_omits_field() {
2248        let (state, _tmp) = test_state();
2249        let init = handle_message(
2250            &state,
2251            json!({"jsonrpc": "2.0", "id": 1, "method": "initialize"}),
2252        )
2253        .await;
2254        assert!(init["result"]["serverInfo"]["default_palace"].is_null());
2255    }
2256
2257    /// Why: every `~/.trusty-memory/http_addr` consumer (CLI, dashboard,
2258    /// future trusty-mpm wiring) must agree on the path. A regression that
2259    /// moves this file breaks every client relying on `read_daemon_addr`.
2260    /// What: under a stubbed data dir, the path ends in
2261    /// `trusty-memory/http_addr` — matching `trusty_common::read_daemon_addr`'s
2262    /// expected location.
2263    #[tokio::test]
2264    async fn http_addr_path_uses_resolve_data_dir() {
2265        // Hold the env_test_lock so this test does not race with
2266        // `prompt_context::tests::*` which spin a real daemon under
2267        // the same env override and would otherwise observe a
2268        // half-mutated $TRUSTY_DATA_DIR_OVERRIDE.
2269        let _guard = crate::commands::env_test_lock().lock().await;
2270        let tmp = tempfile::tempdir().unwrap();
2271        // SAFETY: test-only env mutation serialised by env_test_lock.
2272        unsafe {
2273            std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, tmp.path());
2274        }
2275        let result = http_addr_path();
2276        unsafe {
2277            std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
2278        }
2279        let p = result.expect("http_addr_path must return Some when data dir is resolvable");
2280        assert!(
2281            p.ends_with("trusty-memory/http_addr"),
2282            "unexpected http_addr path: {}",
2283            p.display()
2284        );
2285    }
2286
2287    /// Why: write+read round-trip pins the disk format: a single line of
2288    /// `host:port\n`. Clients (cat, sh `$(cat ...)`) trim whitespace, so the
2289    /// trailing newline is invisible — but anything else (extra whitespace,
2290    /// multi-line) would break callers.
2291    /// Note (issue #226): `write_http_addr_file` is part of the HTTP-serving
2292    /// surface gated behind `axum-server`; the test follows the same gate.
2293    #[cfg(feature = "axum-server")]
2294    #[test]
2295    fn http_addr_file_round_trip_via_helpers() {
2296        let dir = tempfile::tempdir().unwrap();
2297        let path = dir.path().join("http_addr");
2298        let addr: SocketAddr = "127.0.0.1:7073".parse().unwrap();
2299        write_http_addr_file(&path, &addr).unwrap();
2300        let raw = std::fs::read_to_string(&path).unwrap();
2301        assert_eq!(raw.trim(), "127.0.0.1:7073");
2302        // The trailing newline keeps `cat` and editors happy.
2303        assert!(raw.ends_with('\n'));
2304    }
2305
2306    /// Why: dynamic binding must succeed even when the preferred port is
2307    /// already in use. Walking 7070..=7079 + OS fallback guarantees the
2308    /// daemon never fails to come up just because another process holds 7070.
2309    /// What: pre-bind 7070 (best-effort — skip the test if it's already
2310    /// busy on the host), then call `bind_dynamic_port` and assert we got
2311    /// *some* listener back.
2312    #[tokio::test]
2313    async fn bind_dynamic_port_returns_listener() {
2314        let listener = bind_dynamic_port().await.expect("bind_dynamic_port");
2315        let addr = listener.local_addr().expect("local_addr");
2316        assert_eq!(addr.ip().to_string(), "127.0.0.1");
2317        assert!(addr.port() > 0, "port must be non-zero after bind");
2318    }
2319
2320    /// Why: Issue #42 — prompt-facts are now served by the per-message
2321    /// `get_prompt_context` tool rather than the MCP prompts surface, so the
2322    /// `initialize` handshake must NOT advertise a `prompts` capability and
2323    /// `prompts/list` / `prompts/get` must fall through to the "method not
2324    /// found" path.
2325    #[tokio::test]
2326    async fn initialize_does_not_advertise_prompts_capability() {
2327        let (state, _tmp) = test_state();
2328        let init = handle_message(
2329            &state,
2330            json!({"jsonrpc": "2.0", "id": 1, "method": "initialize"}),
2331        )
2332        .await;
2333        assert!(
2334            init["result"]["capabilities"]["prompts"].is_null(),
2335            "initialize must NOT advertise the prompts capability; got {init}"
2336        );
2337
2338        // Both prompts/* dispatchers should now report method-not-found.
2339        for method in ["prompts/list", "prompts/get"] {
2340            let resp =
2341                handle_message(&state, json!({"jsonrpc": "2.0", "id": 2, "method": method})).await;
2342            assert_eq!(
2343                resp["error"]["code"], -32601,
2344                "{method} should return method-not-found; got {resp}"
2345            );
2346        }
2347    }
2348
2349    /// Why: `AppState::new` must initialise `bound_addr` to an empty
2350    /// `OnceLock` so `/health` reports `addr: None` on the stdio path. A
2351    /// regression that pre-populates this field would advertise a bogus
2352    /// address from a stale clone.
2353    ///
2354    /// Note (issue #231): now async so it runs inside a Tokio runtime —
2355    /// `AppState::new` spawns the bounded BM25 index worker via
2356    /// `tokio::spawn`, which requires an active runtime.
2357    #[tokio::test]
2358    async fn app_state_starts_with_empty_bound_addr() {
2359        let (state, _tmp) = test_state();
2360        assert!(state.bound_addr.get().is_none());
2361    }
2362
2363    /// Why (issue #96): `DaemonEvent::type_str` underpins the persisted
2364    /// activity log's `event_type` column — every variant must map to the
2365    /// exact SSE `type` tag the UI already handles. A drift between the
2366    /// SSE wire format and the stored type would break the feed's icon /
2367    /// label rendering for historical rows.
2368    /// What: constructs one of each variant, serialises via serde, and
2369    /// confirms `type_str()` matches the JSON `type` field.
2370    /// Test: this test.
2371    #[test]
2372    fn daemon_event_type_str_matches_sse_tag() {
2373        let cases = [
2374            DaemonEvent::PalaceCreated {
2375                id: "p".into(),
2376                name: "p".into(),
2377                source: ActivitySource::Http,
2378            },
2379            DaemonEvent::DrawerAdded {
2380                palace_id: "p".into(),
2381                palace_name: "p".into(),
2382                drawer_count: 1,
2383                timestamp: chrono::Utc::now(),
2384                content_preview: String::new(),
2385                source: ActivitySource::Mcp,
2386            },
2387            DaemonEvent::DrawerDeleted {
2388                palace_id: "p".into(),
2389                drawer_count: 0,
2390                source: ActivitySource::Http,
2391            },
2392            DaemonEvent::DreamCompleted {
2393                palace_id: None,
2394                merged: 0,
2395                pruned: 0,
2396                compacted: 0,
2397                closets_updated: 0,
2398                duration_ms: 0,
2399                source: ActivitySource::Http,
2400            },
2401            DaemonEvent::StatusChanged {
2402                total_drawers: 0,
2403                total_vectors: 0,
2404                total_kg_triples: 0,
2405            },
2406            DaemonEvent::HookFired {
2407                palace_id: Some("p".into()),
2408                palace_name: Some("p".into()),
2409                hook_type: HookType::UserPromptSubmit,
2410                injection_kind: InjectionKind::PromptContext,
2411                injection_length: 12,
2412                trigger_prompt_excerpt: "hello".into(),
2413                timestamp: chrono::Utc::now(),
2414                duration_ms: 5,
2415                source: ActivitySource::Hook,
2416            },
2417        ];
2418        for ev in &cases {
2419            let json = serde_json::to_value(ev).unwrap();
2420            assert_eq!(json["type"].as_str(), Some(ev.type_str()));
2421        }
2422    }
2423
2424    /// Why: `HookType` is serialised on every `HookFired` activity row; its
2425    /// wire format must round-trip cleanly so dashboard / TUI consumers can
2426    /// safely parse historic entries written by an older daemon build.
2427    /// What: serde-encodes each variant, asserts the JSON matches the
2428    /// expected PascalCase label, then decodes back.
2429    /// Test: itself.
2430    #[test]
2431    fn hook_type_serde_round_trips() {
2432        let cases = [
2433            (HookType::UserPromptSubmit, "\"UserPromptSubmit\""),
2434            (HookType::SessionStart, "\"SessionStart\""),
2435        ];
2436        for (ht, expected) in cases {
2437            let s = serde_json::to_string(&ht).unwrap();
2438            assert_eq!(s, expected, "{ht:?} should serialise to {expected}");
2439            let back: HookType = serde_json::from_str(&s).unwrap();
2440            assert_eq!(back, ht);
2441            assert_eq!(ht.as_str(), expected.trim_matches('"'));
2442        }
2443    }
2444
2445    /// Why: same as `hook_type_serde_round_trips` but for `InjectionKind`.
2446    /// What: kebab-case round trip on every variant.
2447    /// Test: itself.
2448    #[test]
2449    fn injection_kind_serde_round_trips() {
2450        let cases = [
2451            (InjectionKind::PromptContext, "\"prompt-context\""),
2452            (InjectionKind::InboxCheck, "\"inbox-check\""),
2453        ];
2454        for (ik, expected) in cases {
2455            let s = serde_json::to_string(&ik).unwrap();
2456            assert_eq!(s, expected);
2457            let back: InjectionKind = serde_json::from_str(&s).unwrap();
2458            assert_eq!(back, ik);
2459            assert_eq!(ik.as_str(), expected.trim_matches('"'));
2460        }
2461    }
2462
2463    /// Why: the activity feed renders the trigger prompt excerpt directly;
2464    /// runaway prompts must be capped at [`HOOK_PROMPT_EXCERPT_CHARS`] with
2465    /// a `…` marker so the row stays readable.
2466    /// What: feeds a 200-character prompt and asserts the excerpt is
2467    /// bounded.
2468    /// Test: itself.
2469    #[test]
2470    fn hook_excerpt_truncates_long_prompts() {
2471        let long = "x".repeat(200);
2472        let excerpt = hook_prompt_excerpt(&long);
2473        assert!(excerpt.chars().count() <= HOOK_PROMPT_EXCERPT_CHARS);
2474        assert!(excerpt.ends_with('…'));
2475        assert_eq!(hook_prompt_excerpt(""), "");
2476    }
2477
2478    /// Why: multi-line prompts must collapse to a single line so the
2479    /// activity feed row doesn't blow out vertically.
2480    /// What: feeds a multi-line whitespace-heavy prompt and asserts the
2481    /// output is a single-spaced single line.
2482    /// Test: itself.
2483    #[test]
2484    fn hook_excerpt_collapses_whitespace() {
2485        let input = "hello\n\nworld\t\tfoo";
2486        let excerpt = hook_prompt_excerpt(input);
2487        assert_eq!(excerpt, "hello world foo");
2488    }
2489
2490    /// Why (issue #96): `palace_id()` and `source()` feed the persisted
2491    /// activity log's columns; they must extract the right field per
2492    /// variant. Sloppy refactors could swap two fields and the log would
2493    /// silently mis-attribute writes.
2494    /// What: builds each variant with known field values and asserts the
2495    /// extractor returns them.
2496    /// Test: this test.
2497    #[test]
2498    fn daemon_event_palace_id_and_source_extraction() {
2499        let ev = DaemonEvent::DrawerAdded {
2500            palace_id: "alpha".into(),
2501            palace_name: "alpha".into(),
2502            drawer_count: 1,
2503            timestamp: chrono::Utc::now(),
2504            content_preview: String::new(),
2505            source: ActivitySource::Mcp,
2506        };
2507        assert_eq!(ev.palace_id(), Some("alpha"));
2508        assert_eq!(ev.source(), Some(ActivitySource::Mcp));
2509
2510        let status = DaemonEvent::StatusChanged {
2511            total_drawers: 1,
2512            total_vectors: 2,
2513            total_kg_triples: 3,
2514        };
2515        assert_eq!(status.palace_id(), None);
2516        assert_eq!(status.source(), None);
2517
2518        let dream = DaemonEvent::DreamCompleted {
2519            palace_id: Some("p1".into()),
2520            merged: 0,
2521            pruned: 0,
2522            compacted: 0,
2523            closets_updated: 0,
2524            duration_ms: 10,
2525            source: ActivitySource::Http,
2526        };
2527        assert_eq!(dream.palace_id(), Some("p1"));
2528        assert_eq!(dream.source(), Some(ActivitySource::Http));
2529    }
2530
2531    /// Why (issue #96): `AppState::emit` must persist mutation events to
2532    /// the activity log while keeping `StatusChanged` (a recomputed
2533    /// aggregate, not a mutation) out of the persisted history.
2534    /// What: emits one of each variant under a fresh state and asserts
2535    /// the persisted count matches the number of mutation events.
2536    /// Test: this test.
2537    #[tokio::test]
2538    async fn emit_persists_mutations_but_skips_status_changed() {
2539        let (state, _tmp) = test_state();
2540        state.emit(DaemonEvent::PalaceCreated {
2541            id: "p".into(),
2542            name: "p".into(),
2543            source: ActivitySource::Http,
2544        });
2545        state.emit(DaemonEvent::StatusChanged {
2546            total_drawers: 1,
2547            total_vectors: 0,
2548            total_kg_triples: 0,
2549        });
2550        state.emit(DaemonEvent::DrawerAdded {
2551            palace_id: "p".into(),
2552            palace_name: "p".into(),
2553            drawer_count: 1,
2554            timestamp: chrono::Utc::now(),
2555            content_preview: "x".into(),
2556            source: ActivitySource::Mcp,
2557        });
2558        // Issue #232: `emit` now offloads the redb write to `spawn_blocking`,
2559        // so the test must wait for the background pool to drain before
2560        // asserting on the persisted count.
2561        state.flush_activity_writes().await;
2562        let count = state.activity_log.count().unwrap();
2563        assert_eq!(count, 2, "only PalaceCreated + DrawerAdded must persist");
2564    }
2565
2566    /// Why (issue #156): the BM25 lane must be opt-in — existing deployments
2567    /// that don't set `TRUSTY_BM25_DAEMON=1` must see `bm25_client = None`
2568    /// and the recall hot path must continue to behave exactly as before.
2569    /// What: builds an `AppState` with `with_bm25_client_from_env()` while
2570    /// the env var is unset; asserts the field stays `None`.
2571    /// Test: this test.
2572    #[tokio::test]
2573    async fn bm25_client_disabled_by_default() {
2574        // Serialise with the sibling `bm25_client_enabled_when_env_set` test
2575        // so they don't race on the shared `TRUSTY_BM25_DAEMON` env var.
2576        let _guard = crate::commands::env_test_lock().lock().await;
2577        // SAFETY: this test exercises std::env::remove_var which is unsafe
2578        // in 2024 edition because the global env is shared. We restore the
2579        // pre-test value at the end so neighbours are unaffected.
2580        let prev = std::env::var("TRUSTY_BM25_DAEMON").ok();
2581        unsafe {
2582            std::env::remove_var("TRUSTY_BM25_DAEMON");
2583        }
2584        let (state, _tmp) = test_state();
2585        let state = state.with_bm25_client_from_env();
2586        assert!(
2587            state.bm25_client.is_none(),
2588            "bm25_client must be None when TRUSTY_BM25_DAEMON is unset"
2589        );
2590        // Issue #193: the spawn supervisor is bound to the same env gate as
2591        // the client — opt-out parity matters so we never accidentally
2592        // spawn daemons in deployments that explicitly didn't opt in.
2593        assert!(
2594            state.bm25_supervisor.is_none(),
2595            "bm25_supervisor must be None when TRUSTY_BM25_DAEMON is unset"
2596        );
2597        if let Some(v) = prev {
2598            unsafe {
2599                std::env::set_var("TRUSTY_BM25_DAEMON", v);
2600            }
2601        }
2602    }
2603
2604    /// Why (issue #156): when the operator opts in via `TRUSTY_BM25_DAEMON=1`,
2605    /// the builder must construct a real `Bm25Client` pointed at the canonical
2606    /// per-palace socket path. We don't connect — no daemon need be running —
2607    /// we only assert the client field is populated.
2608    /// What: sets the env var, runs the builder, asserts `Some(_)`.
2609    /// Test: this test.
2610    #[tokio::test]
2611    async fn bm25_client_enabled_when_env_set() {
2612        let _guard = crate::commands::env_test_lock().lock().await;
2613        let prev = std::env::var("TRUSTY_BM25_DAEMON").ok();
2614        unsafe {
2615            std::env::set_var("TRUSTY_BM25_DAEMON", "1");
2616        }
2617        let (state, _tmp) = test_state();
2618        let state = state.with_bm25_client_from_env();
2619        assert!(
2620            state.bm25_client.is_some(),
2621            "bm25_client must be Some when TRUSTY_BM25_DAEMON=1"
2622        );
2623        // Issue #193: opting in to the client must also install the spawn
2624        // supervisor so the daemon is auto-started on first use.
2625        assert!(
2626            state.bm25_supervisor.is_some(),
2627            "bm25_supervisor must be Some when TRUSTY_BM25_DAEMON=1"
2628        );
2629        match prev {
2630            Some(v) => unsafe { std::env::set_var("TRUSTY_BM25_DAEMON", v) },
2631            None => unsafe { std::env::remove_var("TRUSTY_BM25_DAEMON") },
2632        }
2633    }
2634
2635    // -------------------------------------------------------------------------
2636    // Issue #467 — palaces skipped at startup hydration are lazily re-opened
2637    // -------------------------------------------------------------------------
2638
2639    /// Why (issue #467): when `load_palaces_from_disk` fails to open a palace
2640    /// (e.g. EMFILE — "Too many open files"), it logs a warning and does NOT
2641    /// register the palace in the in-memory registry. A subsequent call to
2642    /// `open_palace` for that id must attempt a fresh open from disk, not
2643    /// permanently return "not found". This test verifies the lazy-reopen
2644    /// path: create a palace on disk, remove it from the registry (simulating a
2645    /// startup-hydration skip), then open it via `open_palace` and assert success.
2646    /// What: builds an `AppState` with an on-disk palace that is subsequently
2647    /// removed from the in-memory registry (simulating what happens when
2648    /// `PalaceHandle::open` fails during `load_palaces_from_disk`), calls
2649    /// `registry.open_palace`, and asserts the palace handle is returned.
2650    /// Test: this test.
2651    #[tokio::test]
2652    async fn open_palace_lazy_reopens_hydration_skipped_palace() {
2653        let (state, _tmp) = test_state();
2654        // Create a palace on disk.
2655        let pid = trusty_common::memory_core::palace::PalaceId::new("hydration-skip");
2656        let palace = trusty_common::memory_core::Palace {
2657            id: pid.clone(),
2658            name: "hydration-skip".to_string(),
2659            description: None,
2660            created_at: chrono::Utc::now(),
2661            data_dir: state.data_root.join("hydration-skip"),
2662        };
2663        state
2664            .registry
2665            .create_palace(&state.data_root, palace)
2666            .expect("create_palace");
2667
2668        // Simulate a startup-hydration skip by removing the just-registered handle.
2669        // In production, the palace is simply never registered because
2670        // PalaceHandle::open failed during load_palaces_from_disk (EMFILE etc.).
2671        state.registry.remove(&pid);
2672
2673        // The registry must now report no in-memory handle for this palace.
2674        assert!(
2675            state.registry.get(&pid).is_none(),
2676            "palace must appear absent (simulating hydration skip) before the lazy-reopen"
2677        );
2678
2679        // Calling open_palace should attempt a fresh open from disk and succeed.
2680        let handle = state
2681            .registry
2682            .open_palace(&state.data_root, &pid)
2683            .expect("open_palace must lazily reopen a hydration-skipped palace");
2684        assert_eq!(handle.id.as_str(), "hydration-skip");
2685    }
2686
2687    // -------------------------------------------------------------------------
2688    // Issue #498 — dotfile http_addr path uses $HOME/.trusty-memory/http_addr
2689    // -------------------------------------------------------------------------
2690
2691    /// Why (issue #498): claude-mpm's `migrate_trusty_autodetect` reads
2692    /// `~/.trusty-memory/http_addr` to discover the daemon's port. On macOS
2693    /// the OS-standard data dir differs from the dotfile path, so the daemon
2694    /// was writing to the wrong location and claude-mpm always fell back to the
2695    /// hardcoded port `7070`. This test confirms `dotfile_http_addr_path()`
2696    /// returns a path rooted at `$HOME/.trusty-memory/http_addr`.
2697    /// What: under a known HOME, calls `dotfile_http_addr_path` and asserts the
2698    /// returned path ends in `.trusty-memory/http_addr`.
2699    /// Test: this test.
2700    #[cfg(feature = "axum-server")]
2701    #[test]
2702    fn dotfile_http_addr_path_uses_home_dir() {
2703        // `dirs::home_dir()` is not redirectable via env on macOS, but we can
2704        // at least assert that when it returns Some, the suffix is correct.
2705        if let Some(p) = dotfile_http_addr_path() {
2706            assert!(
2707                p.ends_with(".trusty-memory/http_addr"),
2708                "dotfile path must end in .trusty-memory/http_addr; got {}",
2709                p.display()
2710            );
2711        }
2712        // If home_dir() returns None (locked-down env), the function returns None —
2713        // that's acceptable; we just skip the assertion.
2714    }
2715
2716    /// Why (issue #498): the daemon must write to the dotfile path so that
2717    /// claude-mpm's `_resolve_base_url` finds the running port. This round-trip
2718    /// test exercises `write_http_addr_file` at a dotfile-shaped path and
2719    /// confirms the content is readable after the atomic rename.
2720    /// What: picks a tempdir as a stand-in for $HOME, writes an addr to
2721    /// `.trusty-memory/http_addr`, and reads it back.
2722    /// Test: this test.
2723    #[cfg(feature = "axum-server")]
2724    #[test]
2725    fn dotfile_http_addr_write_read_round_trip() {
2726        let home = tempfile::tempdir().unwrap();
2727        let dotfile_dir = home.path().join(".trusty-memory");
2728        let path = dotfile_dir.join("http_addr");
2729        let addr: SocketAddr = "127.0.0.1:7099".parse().unwrap();
2730        write_http_addr_file(&path, &addr).expect("write_http_addr_file to dotfile path");
2731        let raw = std::fs::read_to_string(&path).unwrap();
2732        assert_eq!(
2733            raw.trim(),
2734            "127.0.0.1:7099",
2735            "dotfile round-trip content mismatch"
2736        );
2737        assert!(raw.ends_with('\n'), "dotfile must end with a newline");
2738    }
2739}