Skip to main content

trusty_memory/service/
core.rs

1//! `MemoryService` — the pure business-logic facade over `AppState`.
2//!
3//! Why: lets the axum HTTP handlers stay thin one-liners and lets non-HTTP
4//! callers (chat tool dispatch, RPC bridges) reuse the same code paths without
5//! dragging axum types around (split out of the former monolithic `service.rs`,
6//! issue #607).
7//! What: the `MemoryService` struct + its full async method surface, moved
8//! verbatim. Each method returns `anyhow::Result<Value>` or a typed
9//! `ServiceResult`.
10//! Test: every method is covered by the corresponding handler test in
11//! `web::tests`.
12
13use crate::attribution::CreatorInfo;
14use crate::{ActivitySource, AppState, DaemonEvent};
15use anyhow::{anyhow, Context, Result};
16use serde_json::{json, Value};
17use trusty_common::memory_core::palace::{Palace, PalaceId, RoomType};
18use trusty_common::memory_core::retrieval::{
19    recall_across_palaces_with_default_embedder, recall_deep_with_default_embedder,
20    recall_with_default_embedder, RememberOptions,
21};
22use trusty_common::memory_core::store::PalaceStoreError;
23use trusty_common::memory_core::PalaceRegistry;
24use uuid::Uuid;
25
26use super::helpers::{
27    collect_palace_stats, drawer_content_preview, drawer_snippet, is_reserved_system_palace,
28    list_palaces_blocking, open_palaces_blocking, palace_info_from, recall_entry_json,
29};
30use super::types::{
31    CreateDrawerBody, CreatePalaceBody, ListDrawersQuery, PalaceInfo, ServiceError, ServiceResult,
32    StatusPayload,
33};
34
35/// Hard cap on triples returned by the per-palace graph endpoint.
36pub(super) const KG_GRAPH_MAX_TRIPLES: usize = 5_000;
37
38// ---------------------------------------------------------------------------
39// MemoryService — pure business logic facade.
40// ---------------------------------------------------------------------------
41
42/// Wraps [`AppState`] and exposes one async method per logical operation.
43///
44/// Why: see module docs. Lets HTTP handlers stay thin and lets non-HTTP
45/// callers (chat tool dispatch, RPC bridges) reuse the same code paths.
46/// What: `Clone` (cheap — only the inner `AppState` is shared); construct
47/// with `MemoryService::new(state)`.
48/// Test: every method is covered by the corresponding handler test in
49/// `web::tests`.
50#[derive(Clone)]
51pub struct MemoryService {
52    pub(super) state: AppState,
53}
54
55impl MemoryService {
56    /// Construct a new service wrapper.
57    ///
58    /// Why: handlers cheaply re-wrap their `AppState` on every request; the
59    /// cost is just an `Arc` clone, so we don't bother caching the wrapper.
60    /// What: stores the `AppState` for later method calls.
61    /// Test: trivial — covered indirectly by every handler test.
62    pub fn new(state: AppState) -> Self {
63        Self { state }
64    }
65
66    /// Borrow the inner [`AppState`].
67    ///
68    /// Why: some handlers still need direct access (SSE broadcaster, session
69    /// store, etc.) while we incrementally extract code into the service.
70    /// What: returns a borrowed reference to the wrapped `AppState`.
71    /// Test: not directly tested; surface-level accessor.
72    pub fn state(&self) -> &AppState {
73        &self.state
74    }
75
76    // -----------------------------------------------------------------
77    // Status / config
78    // -----------------------------------------------------------------
79
80    /// Build the aggregate `/api/v1/status` payload.
81    ///
82    /// Why: dashboard widgets and the MCP `get_status` tool need the same
83    /// roll-up; centralising avoids drift between the two surfaces.
84    /// What: walks every persisted palace for `palace_count`, then sums
85    /// drawer/vector/triple counts across the cache-resident subset and
86    /// returns the [`StatusPayload`].
87    /// Why (issue #4637): this used to open every persisted palace to sum
88    /// those three counts. With 5,794 palaces on disk against a 64-slot LRU
89    /// that is ~5,730 cold opens of ~1s each — the endpoint measurably never
90    /// responded. `palace_count` still reflects the true on-disk total (the
91    /// directory walk is cheap and now runs on the blocking pool); the totals
92    /// cover only cache-resident palaces and say so via `cached_palace_count`.
93    /// Test: `status_endpoint_returns_payload`,
94    /// `status_does_not_open_uncached_palaces`.
95    pub async fn status(&self) -> StatusPayload {
96        // The `/status` endpoint is the one place we still want a disk view —
97        // an operator hitting this endpoint right after restart (before
98        // `load_palaces_from_disk` finishes) should still see every persisted
99        // palace counted, even if it isn't in the in-memory registry yet.
100        let palaces = list_palaces_blocking(&self.state).await.unwrap_or_default();
101        let palace_count = palaces.len();
102        // #4637: peek() not open_palace() — full-registry open is O(n) cold disk I/O
103        let stats = collect_palace_stats(&self.state, palaces.iter().map(|p| &p.id));
104        StatusPayload {
105            version: self.state.version.clone(),
106            palace_count,
107            default_palace: self.state.default_palace.clone(),
108            data_root: self.state.data_root.display().to_string(),
109            total_drawers: stats.total_drawers,
110            total_vectors: stats.total_vectors,
111            total_kg_triples: stats.total_kg_triples,
112            cached_palace_count: stats.cached_palace_count,
113        }
114    }
115
116    /// Compute the aggregate `StatusChanged` event used by SSE consumers.
117    ///
118    /// Why: mutating handlers — and the periodic status ticker — push a
119    /// refreshed status snapshot so dashboards stay in sync without an
120    /// extra `/api/v1/status` request.
121    /// Why (issue #228): this used to call `PalaceRegistry::list_palaces`
122    /// (a synchronous disk walk) + `open_palace` (more disk I/O on first
123    /// call) for every palace on every emit. Since every persisted palace
124    /// is already loaded into the in-memory registry by
125    /// `AppState::load_palaces_from_disk` at startup (and every `create_palace`
126    /// keeps it in sync), iterating the in-memory registry returns the same
127    /// counts without touching disk.
128    /// What: iterates `state.registry.list()` (a `DashMap` snapshot) and
129    /// sums the live handle stats via [`collect_palace_stats`]. Returns a
130    /// `DaemonEvent::StatusChanged`. Palaces that fail to resolve in the
131    /// registry (race during shutdown) are silently skipped — the next
132    /// emit will catch them.
133    /// Test: indirectly via SSE integration tests; the math is identical to
134    /// the disk-walk implementation and the `status_endpoint_returns_payload`
135    /// test still passes against `status()` (which keeps the disk view for
136    /// the dedicated endpoint).
137    pub fn aggregate_status_event(&self) -> DaemonEvent {
138        let ids: Vec<PalaceId> = self.state.registry.list();
139        let stats = collect_palace_stats(&self.state, ids.iter());
140        DaemonEvent::StatusChanged {
141            total_drawers: stats.total_drawers,
142            total_vectors: stats.total_vectors,
143            total_kg_triples: stats.total_kg_triples,
144        }
145    }
146
147    // -----------------------------------------------------------------
148    // Palaces
149    // -----------------------------------------------------------------
150
151    /// List every palace on disk, enriched with live handle stats.
152    ///
153    /// Why: shared between the HTTP handler and the chat tool dispatcher;
154    /// both want the same `PalaceInfo` shape. Issue #185 added the
155    /// reserved-prefix filter so internal "system" palaces (e.g. the
156    /// `__health_probe__` palace used by `/health`) never surface in the
157    /// admin UI, TUI, or any user-facing roster.
158    /// What: walks the registry, drops any palace whose id starts with the
159    /// reserved `__` prefix, and builds a `PalaceInfo` per remaining row.
160    /// Why (issue #4637): this used to call `open_palace` per row purely to
161    /// enrich it with counts. At 5,794 palaces against a 64-slot LRU that is
162    /// ~90 minutes of cold, blocking disk I/O inline on the async executor —
163    /// and it evicted the entire working set on every call. Rows now come
164    /// from `PalaceRegistry::peek` (zero I/O, no LRU promotion, mirroring the
165    /// #1924 fix in `console_metrics.rs`). Uncached rows carry `cached: false`
166    /// and zero counts; a client that needs live counts for one palace should
167    /// fetch `GET /api/v1/palaces/{id}`, which still opens it.
168    /// Test: `palace_list_includes_richer_counts`, `palace_list_includes_graph_counts`,
169    /// `health_probe_palace_is_invisible` (in `web::tests`),
170    /// `list_palaces_does_not_open_uncached_palaces`.
171    pub async fn list_palaces(&self) -> ServiceResult<Vec<PalaceInfo>> {
172        let palaces = list_palaces_blocking(&self.state)
173            .await
174            .map_err(|e| ServiceError::internal(format!("{e:#}")))?;
175        let mut out = Vec::with_capacity(palaces.len());
176        for p in palaces {
177            if is_reserved_system_palace(&p.id) {
178                continue;
179            }
180            // #4637: peek() not open_palace() — full-registry open is O(n) cold disk I/O
181            let handle = self.state.registry.peek(&p.id);
182            out.push(palace_info_from(&p, handle.as_ref()));
183        }
184        Ok(out)
185    }
186
187    /// Create a new palace and emit the corresponding activity event.
188    ///
189    /// Why: trims duplicated work between the HTTP handler and any future
190    /// non-HTTP creation flow.
191    /// What: validates the name, builds the `Palace` row, calls
192    /// `PalaceRegistry::create_palace`, and emits `PalaceCreated`. Returns
193    /// the new palace id.
194    /// Test: covered indirectly by `palace_list_includes_richer_counts` (which
195    /// posts a palace through the HTTP layer then reads it back).
196    pub async fn create_palace(
197        &self,
198        body: CreatePalaceBody,
199        source: ActivitySource,
200    ) -> ServiceResult<String> {
201        let name = body.name.trim().to_string();
202        if name.is_empty() {
203            return Err(ServiceError::bad_request("name is required"));
204        }
205        // Issue #88 / Change 2: enforce palace = project mapping for
206        // HTTP-originated palace creation. The validation cwd is, in order of
207        // preference:
208        //   a. `body.cwd` — the caller explicitly supplied their project path
209        //      (correct for any client that is not the daemon itself).
210        //   b. `std::env::current_dir()` — daemon's own cwd, the pre-Change-2
211        //      fallback (rarely meaningful when the daemon is launched from ~).
212        // This keeps older clients that omit `cwd` working without a breaking
213        // change, while letting pin-file-aware clients get accurate validation.
214        // spec-001: `force=true` lets an application bypass the project-slug
215        // gate so it can create palaces under arbitrary slugs (e.g. one per
216        // app/tenant for chat-session storage). The env-var bypass remains for
217        // test contexts; both short-circuit the same validation call.
218        //
219        // Issue #1714: `force=true` bypasses slug validation entirely, so it
220        // is gated behind the minimal authz seam in `crate::authz` before any
221        // other check runs. In the default single-tenant mode this is a
222        // no-op (unchanged behaviour); in multi-tenant mode it fails closed
223        // until a real capability check lands. See `crate::authz` module
224        // docs for the full design rationale.
225        let skip_enforcement =
226            std::env::var("TRUSTY_SKIP_PALACE_ENFORCEMENT").as_deref() == Ok("1");
227        if body.force {
228            crate::authz::authorize_force_palace_create(&self.state)
229                .map_err(|e| ServiceError::forbidden(e.to_string()))?;
230        }
231        if !skip_enforcement && !body.force {
232            let cwd = body
233                .cwd
234                .as_deref()
235                .map(std::path::Path::new)
236                .map(|p| p.to_path_buf())
237                .or_else(|| std::env::current_dir().ok())
238                .unwrap_or_else(|| self.state.data_root.clone());
239            crate::project_root::validate_palace_name(&name, &cwd)
240                .map_err(|e| ServiceError::bad_request(e.to_string()))?;
241        }
242        let id = PalaceId::new(&name);
243        let palace = Palace {
244            id: id.clone(),
245            name: name.clone(),
246            description: body.description.filter(|s| !s.is_empty()),
247            created_at: chrono::Utc::now(),
248            data_dir: self.state.data_root.join(&name),
249        };
250        self.state
251            .registry
252            .create_palace(&self.state.data_root, palace)
253            .map_err(|e| ServiceError::internal(format!("create palace: {e:#}")))?;
254        // Issue #228: keep the in-memory palace-name cache in sync so writes
255        // to this palace can resolve `Palace.name` without a disk walk.
256        self.state.palace_names.insert(name.clone(), name.clone());
257        self.state.emit(DaemonEvent::PalaceCreated {
258            id: name.clone(),
259            name: name.clone(),
260            source,
261        });
262        Ok(name)
263    }
264
265    /// Delete a palace from disk, optionally rejecting non-empty palaces.
266    ///
267    /// Why: Issue #180 — operators need a way to drop an entire palace
268    /// without going through drawer-by-drawer deletion. Defaulting to a
269    /// "must be empty" guard prevents fat-finger destruction of populated
270    /// palaces; `force=true` is the explicit opt-in to the destructive path.
271    /// What: 1) confirms the palace exists on disk (else `NotFound`),
272    /// 2) when `!force`, lists drawers via the live handle and returns
273    /// `BadRequest("Palace has drawers; pass force=true to delete")` if
274    /// the palace is non-empty, 3) drops the in-memory registry entry so
275    /// future opens hit the (now-missing) disk state, 4) removes
276    /// `<data_root>/<palace_id>/` recursively via `tokio::fs::remove_dir_all`,
277    /// and 5) emits an aggregate `StatusChanged` so dashboards refresh.
278    /// Test: `delete_palace_removes_dir_when_empty`,
279    /// `delete_palace_refuses_when_drawers_present`,
280    /// `delete_palace_force_removes_populated_palace`,
281    /// `delete_palace_returns_not_found_for_missing_id` in `web::tests`.
282    pub async fn delete_palace(&self, palace_id: &str, force: bool) -> ServiceResult<()> {
283        let palaces = PalaceRegistry::list_palaces(&self.state.data_root)
284            .map_err(|e| ServiceError::internal(format!("list palaces: {e:#}")))?;
285        if !palaces.iter().any(|p| p.id.0 == palace_id) {
286            return Err(ServiceError::not_found(format!(
287                "palace not found: {palace_id}"
288            )));
289        }
290        if !force {
291            // Open the palace just long enough to count its drawers; we don't
292            // hold the handle past this check because the caller is about to
293            // delete the on-disk directory.
294            if let Ok(handle) = self
295                .state
296                .registry
297                .open_palace(&self.state.data_root, &PalaceId::new(palace_id))
298            {
299                if !handle.drawers.read().is_empty() {
300                    return Err(ServiceError::conflict(
301                        "Palace has drawers; pass force=true to delete",
302                    ));
303                }
304            }
305        }
306        // Drop the cached `Arc<PalaceHandle>` and gap cache before unlinking
307        // the directory so subsequent reads can't be served from the stale
308        // in-memory state. The registry's `remove` is a no-op when the entry
309        // is absent (lazy-open palaces that no caller has touched yet).
310        self.state.registry.remove(&PalaceId::new(palace_id));
311        // #4639: drop the cached chat_sessions.redb handle too — otherwise the
312        // fd survives `remove_dir_all` and pins the deleted inode forever.
313        self.state.session_stores.remove(palace_id);
314        // Issue #228: drop the palace-name cache entry so future writes never
315        // resolve to a stale label.
316        self.state.palace_names.remove(palace_id);
317        let palace_dir = self.state.data_root.join(palace_id);
318        tokio::fs::remove_dir_all(&palace_dir).await.map_err(|e| {
319            ServiceError::internal(format!("remove palace dir {}: {e}", palace_dir.display()))
320        })?;
321        // Recompute aggregate totals so dashboards drop the deleted palace's
322        // counts. There's no dedicated `PalaceDeleted` event variant yet;
323        // `StatusChanged` is enough to keep the UI in sync.
324        self.state.emit(self.aggregate_status_event());
325        Ok(())
326    }
327
328    /// Rename a palace's display name without touching its data.
329    ///
330    /// Why: Operators need to fix typos and rebrand palaces without dropping
331    /// the underlying drawers / vectors / KG. The palace id (the directory
332    /// name on disk) is immutable — only the human-readable `name` field in
333    /// `palace.json` changes — so cached `PalaceHandle`s stay valid and no
334    /// registry invalidation is required.
335    /// What: 1) loads the palace via `PalaceStore::load_palace` (404 when the
336    /// directory or `palace.json` is genuinely missing; a probe that cannot
337    /// determine whether it is there is a 500, not a 404 — #5549), 2) trims the
338    /// new name and
339    /// returns `BadRequest` when empty, 3) mutates `palace.name` and writes
340    /// the metadata back through the atomic `PalaceStore::save_palace`
341    /// (tmp file + rename), 4) emits an aggregate `StatusChanged` so
342    /// dashboards re-render the relabelled palace, 5) returns the updated
343    /// palace as JSON (enriched with the live handle stats, so callers see
344    /// drawer/vector/KG counts in the same shape as `GET /palaces/{id}`).
345    /// Test: `update_palace_name_renames_palace`,
346    /// `update_palace_name_rejects_empty_name`,
347    /// `update_palace_name_returns_not_found_for_missing_id` in `web::tests`.
348    pub async fn update_palace_name(&self, palace_id: &str, name: &str) -> Result<Value> {
349        let trimmed = name.trim();
350        if trimmed.is_empty() {
351            return Err(anyhow!("name must be non-empty after trimming"));
352        }
353        let palace_dir = self.state.data_root.join(palace_id);
354        let mut palace = trusty_common::memory_core::store::PalaceStore::load_palace(&palace_dir)
355            .map_err(|e| {
356            // #5549: only a genuine absence may be reported as "not found".
357            if matches!(&e, PalaceStoreError::NotFound(_)) {
358                anyhow!("palace not found: {palace_id} ({e})")
359            } else {
360                anyhow!("cannot load palace {palace_id}: {e}")
361            }
362        })?;
363        palace.name = trimmed.to_string();
364        trusty_common::memory_core::store::PalaceStore::save_palace(&palace)
365            .with_context(|| format!("save palace metadata for {palace_id}"))?;
366        // Issue #228: refresh the in-memory name cache so subsequent writes
367        // surface the new label without a disk walk.
368        self.state
369            .palace_names
370            .insert(palace_id.to_string(), trimmed.to_string());
371        let handle = self
372            .state
373            .registry
374            .open_palace(&self.state.data_root, &palace.id)
375            .ok();
376        let info = palace_info_from(&palace, handle.as_ref());
377        self.state.emit(self.aggregate_status_event());
378        serde_json::to_value(info).context("serialize palace info")
379    }
380
381    /// Typed variant of [`Self::update_palace_name`] used by the HTTP handler.
382    ///
383    /// Why: HTTP needs to distinguish 400 (empty name) from 404 (missing
384    /// palace) so the right status code is emitted; the chat / MCP tool
385    /// only cares about a `Result<Value>` because both errors are surfaced
386    /// as opaque MCP error strings. Keeping a typed variant alongside the
387    /// untyped one keeps the wire shape correct on both surfaces without
388    /// asking either caller to parse error strings.
389    /// What: same as [`Self::update_palace_name`] but returns
390    /// `ServiceError::BadRequest` for empty names and `ServiceError::NotFound`
391    /// for palace metadata that is genuinely absent. Metadata whose presence
392    /// cannot be determined — a denied or transient stat — is
393    /// `ServiceError::Internal`: a 404 would tell the client the palace does
394    /// not exist when nobody established that (#5549, ADR-0045).
395    /// Test: `update_palace_name_renames_palace`,
396    /// `update_palace_name_rejects_empty_name`,
397    /// `update_palace_name_returns_not_found_for_missing_id`,
398    /// `update_palace_name_reports_an_unstattable_palace_as_internal`.
399    pub async fn update_palace_name_typed(
400        &self,
401        palace_id: &str,
402        name: &str,
403    ) -> ServiceResult<Value> {
404        let trimmed = name.trim();
405        if trimmed.is_empty() {
406            return Err(ServiceError::bad_request(
407                "name must be non-empty after trimming",
408            ));
409        }
410        let palace_dir = self.state.data_root.join(palace_id);
411        let mut palace = trusty_common::memory_core::store::PalaceStore::load_palace(&palace_dir)
412            .map_err(|e| {
413            // #5549: `not_found` on every variant told the client the palace
414            // does not exist for a stat we were merely denied.
415            if matches!(&e, PalaceStoreError::NotFound(_)) {
416                ServiceError::not_found(format!("palace not found: {palace_id} ({e})"))
417            } else {
418                ServiceError::internal(format!("cannot load palace {palace_id}: {e}"))
419            }
420        })?;
421        palace.name = trimmed.to_string();
422        trusty_common::memory_core::store::PalaceStore::save_palace(&palace).map_err(|e| {
423            ServiceError::internal(format!("save palace metadata for {palace_id}: {e}"))
424        })?;
425        // Issue #228: refresh the in-memory name cache so subsequent writes
426        // surface the new label without a disk walk.
427        self.state
428            .palace_names
429            .insert(palace_id.to_string(), trimmed.to_string());
430        let handle = self
431            .state
432            .registry
433            .open_palace(&self.state.data_root, &palace.id)
434            .ok();
435        let info = palace_info_from(&palace, handle.as_ref());
436        self.state.emit(self.aggregate_status_event());
437        serde_json::to_value(info)
438            .map_err(|e| ServiceError::internal(format!("serialize palace info: {e}")))
439    }
440
441    /// Look up a single palace by id and enrich with live handle stats.
442    ///
443    /// Why: distinct 404 vs. 500 path is needed by both HTTP and chat callers.
444    /// What: returns `NotFound` when the id is unknown, otherwise a fully
445    /// populated `PalaceInfo`.
446    /// Test: indirectly via `health_endpoint_round_trip_with_palace_is_ok`.
447    pub async fn get_palace(&self, id: &str) -> ServiceResult<PalaceInfo> {
448        let palaces = PalaceRegistry::list_palaces(&self.state.data_root)
449            .map_err(|e| ServiceError::internal(format!("list palaces: {e:#}")))?;
450        let palace = palaces
451            .into_iter()
452            .find(|p| p.id.0 == id)
453            .ok_or_else(|| ServiceError::not_found(format!("palace not found: {id}")))?;
454        let handle = self
455            .state
456            .registry
457            .open_palace(&self.state.data_root, &palace.id)
458            .ok();
459        Ok(palace_info_from(&palace, handle.as_ref()))
460    }
461
462    // -----------------------------------------------------------------
463    // Drawers
464    // -----------------------------------------------------------------
465
466    /// List drawers in a palace with optional room/tag filters and pagination.
467    ///
468    /// Why: deduplicates the open-handle + listing path between HTTP and chat,
469    /// and (issue #184) lets the TUI activity panel page through drawers in
470    /// creation-date order without breaking the importance-sorted default the
471    /// legacy callers rely on.
472    /// What: opens the palace handle, fetches a window of drawers, optionally
473    /// re-sorts by `created_at` descending when `sort = "created_desc"`
474    /// (leaving the importance-desc default untouched), then drops the
475    /// leading `offset` rows and keeps `limit`. For `created_desc` the
476    /// window must cover the full filtered set (otherwise the importance
477    /// pre-sort hides truly-recent low-importance drawers), so the window
478    /// is widened to a sane ceiling (`MAX_DRAWER_WINDOW`); the default
479    /// importance path keeps a tight `limit+offset` window.
480    /// Returns the serialised JSON array.
481    /// Test: `service::tests::list_drawers_creates_desc_paginates`.
482    pub async fn list_drawers(&self, id: &str, q: ListDrawersQuery) -> ServiceResult<Value> {
483        const MAX_DRAWER_WINDOW: usize = 10_000;
484        let handle = self.open_handle(id)?;
485        let room = q.room.as_deref().map(RoomType::parse);
486        let limit = q.limit.unwrap_or(50);
487        let offset = q.offset.unwrap_or(0);
488        let by_created = matches!(q.sort.as_deref(), Some("created_desc"));
489        // For created_desc the importance pre-sort would hide low-importance
490        // drawers that happen to be the most recent, so we need to fetch the
491        // full filtered set (capped at MAX_DRAWER_WINDOW). For importance
492        // ordering the legacy `limit + offset` window is sufficient.
493        let window = if by_created {
494            MAX_DRAWER_WINDOW
495        } else {
496            limit.saturating_add(offset).min(MAX_DRAWER_WINDOW)
497        };
498        let mut drawers = handle.list_drawers(room, q.tag.clone(), window);
499        if by_created {
500            drawers.sort_by_key(|d| std::cmp::Reverse(d.created_at));
501        }
502        let page: Vec<_> = drawers.into_iter().skip(offset).take(limit).collect();
503        // Issue #202: enrich every row with a short `snippet` derived from
504        // the drawer's content so the TUI activity panel can render a
505        // glanceable summary without re-parsing the full body. The
506        // snippet is whitespace-collapsed and bounded at
507        // `DRAWER_SNIPPET_MAX_CHARS` (60) — shorter than the SSE preview
508        // because the activity panel renders it on a single narrow row.
509        let payload: Vec<Value> = page
510            .into_iter()
511            .map(|drawer| {
512                let snippet = drawer_snippet(&drawer.content);
513                let mut value = serde_json::to_value(&drawer).unwrap_or_else(|_| json!({}));
514                if let Value::Object(ref mut map) = value {
515                    // `null` when the drawer has no usable content so
516                    // clients can distinguish "no body" from "empty body
517                    // after whitespace collapse".
518                    let snippet_value = if snippet.is_empty() {
519                        Value::Null
520                    } else {
521                        Value::String(snippet)
522                    };
523                    map.insert("snippet".to_string(), snippet_value);
524                }
525                value
526            })
527            .collect();
528        Ok(Value::Array(payload))
529    }
530
531    /// Store a new drawer and emit the matching activity events.
532    ///
533    /// Why: HTTP and chat both need the auto-KG-extraction follow-up; this
534    /// method keeps that side-effect chain in one place.
535    /// What: opens the palace, stores the drawer via
536    /// `PalaceHandle::remember_with_options` (issue #3225: `body.force`
537    /// threads through as `RememberOptions::force`, letting a caller bypass
538    /// the QUALITY gates only — `allow_secret_like` is left at its default
539    /// `false`, so secret detection always still runs, `force` or not),
540    /// emits `DrawerAdded` + `StatusChanged`, then triggers
541    /// `tools::auto_extract_and_assert`. Returns the new drawer id.
542    /// Test: `http_create_drawer_runs_auto_kg_extraction`,
543    /// `create_drawer_rejects_json_content_without_force`,
544    /// `create_drawer_force_bypasses_quality_gate_for_json_content`.
545    pub async fn create_drawer(
546        &self,
547        id: &str,
548        body: CreateDrawerBody,
549        creator: CreatorInfo,
550        source: ActivitySource,
551    ) -> ServiceResult<Uuid> {
552        let handle = self.open_handle(id)?;
553        let room = body
554            .room
555            .as_deref()
556            .map(RoomType::parse)
557            .unwrap_or(RoomType::General);
558        let importance = body.importance.unwrap_or(0.5);
559        let force = body.force.unwrap_or(false);
560        let content_preview = drawer_content_preview(&body.content);
561        let mut tags_with_creator = body.tags;
562        // Issue #202: project a bare-UUID session tag (when the caller
563        // passed one in the request body) into the reserved
564        // `creator:session=<first-8>` slot so the activity panel can
565        // surface session attribution without bespoke parsing.
566        if let Some(session_tag) = crate::attribution::session_tag_from_tags(&tags_with_creator) {
567            tags_with_creator.push(session_tag);
568        }
569        creator.merge_into(&mut tags_with_creator);
570        let content_for_kg = body.content.clone();
571        let tags_for_kg = tags_with_creator.clone();
572        let room_label_for_kg = crate::tools::room_label(&room);
573        let drawer_id = handle
574            .remember_with_options(
575                body.content,
576                room,
577                tags_with_creator,
578                importance,
579                RememberOptions {
580                    force,
581                    ..Default::default()
582                },
583            )
584            .await
585            .map_err(|e| ServiceError::internal(format!("remember: {e:#}")))?;
586        let drawer_count = handle.drawers.read().len();
587        // Issue #228: resolve from the in-memory cache instead of re-walking
588        // the data root on every HTTP `create_drawer` call. Same cache the
589        // MCP `lookup_palace_name` helper consults.
590        let palace_name = self
591            .state
592            .palace_names
593            .get(id)
594            .map(|entry| entry.value().clone())
595            .unwrap_or_else(|| id.to_string());
596        self.state.emit(DaemonEvent::DrawerAdded {
597            palace_id: id.to_string(),
598            palace_name,
599            drawer_count,
600            timestamp: chrono::Utc::now(),
601            content_preview,
602            source,
603        });
604        // Issue #228: do NOT emit `StatusChanged` on every drawer create —
605        // the periodic ticker (`run_http_on`) refreshes aggregate totals on
606        // a fixed cadence so dashboards stay current without an O(N palaces)
607        // recompute on the write hot path.
608        crate::tools::auto_extract_and_assert(
609            &handle,
610            drawer_id,
611            &content_for_kg,
612            &tags_for_kg,
613            room_label_for_kg.as_deref(),
614        )
615        .await;
616        Ok(drawer_id)
617    }
618
619    /// Forget (delete) a drawer and emit the matching events.
620    ///
621    /// Why: same dedup story as `create_drawer`. #5231: `DELETE` on a drawer id
622    /// that was never stored used to answer `204 No Content`, the same as a
623    /// real delete — this now 404s, matching `delete_palace`.
624    /// What: parses the drawer UUID, calls `PalaceHandle::forget`, deletes the
625    /// drawer's BM25 document, maps `ForgetOutcome::NotFound` to
626    /// `ServiceError::not_found`, and emits `DrawerDeleted` only when a drawer
627    /// was actually removed. #5053: the lexical delete runs on this path for
628    /// the same reason it runs on the MCP one — `HTTP DELETE` and
629    /// `memory_forget` remove the same drawer, and the backfill indexes it
630    /// whichever way it was written, so a lexical copy left here is the same
631    /// stale document.
632    /// Test: `delete_drawer_404s_for_an_unknown_drawer_id`;
633    /// `tests/bm25_forget_delete.rs` covers the deletion contract itself.
634    pub async fn delete_drawer(
635        &self,
636        id: &str,
637        drawer_id: &str,
638        source: ActivitySource,
639    ) -> ServiceResult<()> {
640        let handle = self.open_handle(id)?;
641        let uuid = Uuid::parse_str(drawer_id)
642            .map_err(|_| ServiceError::bad_request("drawer_id must be a UUID"))?;
643        let outcome = handle
644            .forget(uuid)
645            .await
646            .map_err(|e| ServiceError::internal(format!("forget: {e:#}")))?;
647        // #5053: a drawer the user deleted must stop matching lexical queries.
648        crate::tools::bm25::bm25_delete_document(&self.state, handle.id.as_str(), uuid)
649            .await
650            .map_err(|e| ServiceError::internal(format!("{e:#}")))?;
651        if !outcome.is_deleted() {
652            return Err(ServiceError::not_found(format!(
653                "drawer '{drawer_id}' not found in palace '{id}'"
654            )));
655        }
656        let drawer_count = handle.drawers.read().len();
657        self.state.emit(DaemonEvent::DrawerDeleted {
658            palace_id: id.to_string(),
659            drawer_count,
660            source,
661        });
662        // Issue #228: skip the per-write `StatusChanged` emit — the
663        // periodic ticker handles aggregate roll-ups.
664        Ok(())
665    }
666
667    // -----------------------------------------------------------------
668    // Recall
669    // -----------------------------------------------------------------
670
671    /// Per-palace recall (semantic search), optionally with deep retrieval.
672    ///
673    /// Why: HTTP and chat tools both perform the same fan-out logic.
674    /// What: opens the palace handle and dispatches to the shallow or deep
675    /// recall helper. Returns a JSON array of flattened drawer rows (the
676    /// `recall_entry_json` shape from issue #69).
677    /// Test: `recall_entry_json_hoists_drawer_fields`.
678    pub async fn recall(
679        &self,
680        id: &str,
681        query: &str,
682        top_k: usize,
683        deep: bool,
684    ) -> ServiceResult<Value> {
685        let handle = self.open_handle(id)?;
686        let results = if deep {
687            recall_deep_with_default_embedder(&handle, query, top_k).await
688        } else {
689            recall_with_default_embedder(&handle, query, top_k).await
690        }
691        .map_err(|e| ServiceError::internal(format!("recall: {e:#}")))?;
692        let payload: Vec<Value> = results.into_iter().map(recall_entry_json).collect();
693        Ok(json!(payload))
694    }
695
696    /// Cross-palace recall.
697    ///
698    /// Why: shared between `/api/v1/recall` and the `memory_recall_all` chat
699    /// tool. Encapsulating the open-everything-fanout-merge dance avoids
700    /// drift.
701    /// What: lists every palace, opens handles (skipping failures with a
702    /// `tracing::warn!`), delegates to
703    /// `recall_across_palaces_with_default_embedder`. Returns a JSON array.
704    /// Why (issue #4637): unlike `list_palaces`/`status`, this route is NOT
705    /// converted to `peek()`. A cross-palace recall that answered from
706    /// cache-resident palaces only would silently omit ~98.9% of the corpus —
707    /// a wrong answer that looks like a right one, which is strictly worse
708    /// than a slow correct one. The open loop keeps opening every palace; it
709    /// just no longer does so inline on a tokio worker thread. Making this
710    /// route actually fast needs a different design (a shared cross-palace
711    /// index, or an explicit palace-scoped query), not a cache-only read.
712    /// Test: indirectly via `recall_across_palaces_merges_results` and the
713    /// MCP `memory_recall_all` integration paths;
714    /// `open_palaces_blocking_opens_every_palace` pins that uncached palaces
715    /// are still searched.
716    pub async fn recall_all(&self, query: &str, top_k: usize, deep: bool) -> Value {
717        let palaces = match list_palaces_blocking(&self.state).await {
718            Ok(v) => v,
719            Err(e) => return json!({ "error": format!("{e:#}") }),
720        };
721        // #4637: open_palace (not peek) is deliberate — recall must see every
722        // palace; the spawn_blocking hop keeps it off the async executor.
723        let handles = open_palaces_blocking(&self.state, &palaces, "recall_all").await;
724        if handles.is_empty() {
725            return json!([]);
726        }
727        match recall_across_palaces_with_default_embedder(&handles, query, top_k, deep).await {
728            Ok(results) => json!(results
729                .into_iter()
730                .map(|r| json!({
731                    "palace_id": r.palace_id,
732                    "drawer_id": r.result.drawer.id.to_string(),
733                    "content": r.result.drawer.content,
734                    "importance": r.result.drawer.importance,
735                    "tags": r.result.drawer.tags,
736                    "score": r.result.score,
737                    "layer": r.result.layer,
738                }))
739                .collect::<Vec<_>>()),
740            Err(e) => json!({ "error": format!("recall_across_palaces: {e:#}") }),
741        }
742    }
743}