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