Skip to main content

velesdb_memory/
service.rs

1//! The memory service: five operations over the in-core Agent Memory SDK.
2
3use std::collections::{HashMap, HashSet};
4#[cfg(feature = "persistence")]
5use std::path::Path;
6
7use serde_json::{Map, Value};
8
9/// Structured metadata attached to a memory (the `ColumnStore` facet): exact-match
10/// fields like `project`, `author`, `type`, `status`, `date`. `content` and
11/// `_veles_expires_at` are reserved keys.
12pub type Metadata = Map<String, Value>;
13
14use crate::embedder::Embedder;
15use crate::error::MemoryError;
16use crate::extract::Extractor;
17use crate::id;
18use crate::model::{ColumnFilter, Explanation, Link, MemoryNode, Recollection};
19#[cfg(feature = "persistence")]
20use crate::storage::NativeStore;
21use crate::storage::{is_reserved_key, strip_reserved_keys, MemoryStore};
22
23/// [`MemoryService::recall_fused`] and its helpers — split out to keep this
24/// file under the crate's 500-NLOC-per-file budget, same pattern as
25/// `velesdb-core`'s `database/*.rs` split. A child module of `service`, so it
26/// shares full access to `MemoryService`'s private fields and methods.
27#[path = "fused_recall.rs"]
28mod fused_recall;
29
30/// [`MemoryService::feedback`] and the recall re-ranking it drives (RL Memory).
31/// A child module of `service`, like [`fused_recall`], so it uses
32/// `MemoryService`'s private `store` directly. Gated on `persistence`: it
33/// builds on `velesdb-core`'s agent SDK (`ReinforcementStrategy`), itself
34/// behind that feature, and a durable learned confidence is meaningless on the
35/// in-memory (WASM) backend.
36#[cfg(feature = "persistence")]
37#[path = "reinforce.rs"]
38mod reinforce;
39
40/// The context compiler's memory bridge (`compile_context`,
41/// `retrieve_context_source`, `context_savings`, working contexts). A child
42/// module of `service`, like [`fused_recall`], so it reuses the private
43/// `store_fact`/`HUB_FIELD` system-fact machinery — compiler system facts
44/// (sources, events, working contexts) are hub-marked so they never surface
45/// in normal recall.
46#[cfg(feature = "context")]
47#[path = "context/memory_bridge.rs"]
48mod memory_bridge;
49
50/// Reserved metadata key marking an entity hub auto-created by
51/// [`MemoryService::remember_extracted`] (value `true`). Namespaced under the
52/// system `_veles_` prefix so it can never collide with a caller's own metadata,
53/// and rejected from caller-supplied metadata/filters (see [`is_reserved_key`]).
54/// Hubs are internal graph scaffolding — they connect facts that share a topic —
55/// so they are excluded from unfiltered recall and from `why` seeds.
56const HUB_FIELD: &str = "_veles_hub";
57/// Salt mixed into a hub's stable id so the hub id space is disjoint from
58/// natural fact ids: a caller fact whose text happens to equal a hub's display
59/// content (`Entity: rust`) can never collide with, or overwrite, the hub.
60const HUB_ID_SALT: &str = "\u{0}_veles_entity_hub\u{0}";
61/// Edge label a hub uses to point back at a fact it tags (the hub → fact
62/// direction). [`fused_recall`] reads this to recognise which edges in a
63/// `why()` walk crossed a hub, so it can weight the reached fact by that
64/// hub's specificity instead of a flat constant.
65const MENTIONS_RELATION: &str = "mentions";
66
67/// Local-first agent memory backed by a single `VelesDB` instance.
68///
69/// Generic over the [`Embedder`] so production can use an on-device model while
70/// tests use a deterministic, network-free one, and over the [`MemoryStore`]
71/// backend `S` so the same orchestration runs over the native, file-backed
72/// engine (the default — nothing changes for existing callers) or any other
73/// backend that implements the trait (e.g. an in-memory one for WASM).
74///
75/// Two definitions, `persistence`-gated: the default type parameter itself
76/// references [`NativeStore`], which doesn't exist as a type at all without
77/// the feature, so a `persistence`-free build (e.g. `velesdb-wasm`) drops the
78/// default and every caller names its own [`MemoryStore`] backend explicitly.
79#[cfg(feature = "persistence")]
80pub struct MemoryService<E: Embedder, S: MemoryStore = NativeStore> {
81    store: S,
82    embedder: E,
83}
84#[cfg(not(feature = "persistence"))]
85pub struct MemoryService<E: Embedder, S: MemoryStore> {
86    store: S,
87    embedder: E,
88}
89
90#[cfg(feature = "persistence")]
91impl<E: Embedder> MemoryService<E, NativeStore> {
92    /// Open (or create) a native, file-backed memory store at `path`, using
93    /// `embedder` for text vectorization. The store never leaves this directory.
94    ///
95    /// # Errors
96    /// Returns [`MemoryError`] if the store cannot be opened or the agent
97    /// memory cannot be initialized for the embedder's dimension.
98    pub fn open<P: AsRef<Path>>(path: P, embedder: E) -> Result<Self, MemoryError> {
99        let store = NativeStore::open(path, embedder.dimension())?;
100        Ok(Self { store, embedder })
101    }
102}
103
104impl<E: Embedder, S: MemoryStore> MemoryService<E, S> {
105    /// Build a service directly over a `store` backend, bypassing
106    /// [`Self::open`]'s filesystem-specific setup — the constructor a
107    /// non-native backend (e.g. `velesdb-wasm`'s in-memory store) uses.
108    pub fn with_store(store: S, embedder: E) -> Self {
109        Self { store, embedder }
110    }
111
112    /// Remember a `fact`, optionally tagging it with structured `metadata`
113    /// (`ColumnStore` facet) and linking it to existing memories (graph facet).
114    /// Returns the stable id of the fact (idempotent on identical content).
115    ///
116    /// Every link is validated — target existence AND relation label —
117    /// *before* the fact is stored, so bad link input never leaves the fact
118    /// half-written. If an edge write itself fails afterwards (e.g. a target
119    /// expiring concurrently), a freshly-created fact is rolled back; a
120    /// re-remembered fact keeps its updated payload (re-remembering updates
121    /// metadata by design, and deleting it would destroy prior state).
122    /// Concurrent `remember`s of identical content are last-writer-wins,
123    /// not transactional.
124    ///
125    /// # Errors
126    /// Returns [`MemoryError::EmptyFact`] for empty/whitespace facts,
127    /// [`MemoryError::ReservedKey`] if `metadata` names a reserved key
128    /// (`content` or any `_veles_`-prefixed system key),
129    /// [`MemoryError::UnknownMemory`] if a link points at a missing memory,
130    /// [`MemoryError::InvalidRelation`] for a bad relation label,
131    /// [`MemoryError::RollbackFailed`] if an edge write failed and the
132    /// compensating delete also failed (the fact remains stored),
133    /// or a storage error if persistence fails.
134    pub fn remember(
135        &self,
136        fact: &str,
137        links: &[Link],
138        metadata: Option<&Metadata>,
139    ) -> Result<u64, MemoryError> {
140        self.remember_with_ttl(fact, links, metadata, None)
141    }
142
143    /// Like [`Self::remember`], but the fact **expires after `ttl_seconds`**.
144    ///
145    /// The expiry is a durable TTL — persisted with the fact (reserved
146    /// `_veles_expires_at` payload field), so it survives a process restart, and
147    /// expired facts stop being recalled. `None` (or `Some(0)`) stores the fact
148    /// permanently, exactly like [`Self::remember`]. Metadata and a TTL combine:
149    /// the metadata is written and the expiry preserved.
150    ///
151    /// # Errors
152    /// Same as [`Self::remember`].
153    pub fn remember_with_ttl(
154        &self,
155        fact: &str,
156        links: &[Link],
157        metadata: Option<&Metadata>,
158        ttl_seconds: Option<u64>,
159    ) -> Result<u64, MemoryError> {
160        let fact = fact.trim();
161        if fact.is_empty() {
162            return Err(MemoryError::EmptyFact);
163        }
164        reject_reserved_keys(metadata)?;
165        // EVERY link property — relation label and target existence — is
166        // validated before any write, so all deterministic link failures
167        // happen while nothing has been stored or overwritten yet.
168        for link in links {
169            validate_relation(&link.relation)?;
170        }
171        self.ensure_link_targets_exist(links)?;
172        let fact_id = id::stable_id(fact);
173        let embedding = self.embedder.embed(fact)?;
174        let existed_before = !links.is_empty() && self.store.get(fact_id)?.is_some();
175        self.store_fact(
176            fact_id,
177            fact,
178            &embedding,
179            metadata,
180            positive_ttl(ttl_seconds),
181        )?;
182        // Links are fully pre-validated above, so an edge write can only
183        // fail here on a race (e.g. a target's TTL lapsing since the
184        // pre-check). Roll a FRESH fact back (delete cascades any edges
185        // already created); a fact that existed before this call is kept —
186        // deleting it would destroy prior state, and its updated payload
187        // stands per re-remember's update semantics. The existence probe
188        // and the delete are not one atomic unit: a concurrent remember of
189        // identical content between them is last-writer-wins (documented
190        // on [`Self::remember`]).
191        if let Err(e) = self.relate_links(fact_id, links) {
192            if !existed_before {
193                if let Err(rollback) = self.store.delete(fact_id) {
194                    return Err(MemoryError::RollbackFailed {
195                        cause: Box::new(e),
196                        rollback: Box::new(rollback),
197                    });
198                }
199            }
200            return Err(e);
201        }
202        Ok(fact_id)
203    }
204
205    /// Create each outgoing link from `fact_id`.
206    ///
207    /// Precondition: every label was already validated by
208    /// [`Self::remember_with_ttl`]'s pre-write pass (its only caller) —
209    /// no re-check here, so the validation rule lives in exactly one
210    /// place on this path.
211    fn relate_links(&self, fact_id: u64, links: &[Link]) -> Result<(), MemoryError> {
212        for link in links {
213            self.store.relate(fact_id, link.target, &link.relation)?;
214        }
215        Ok(())
216    }
217
218    /// Remember a passage of raw `text` by running it through an [`Extractor`]
219    /// and storing every fact it yields, **auto-wiring the fact↔entity graph**.
220    ///
221    /// This is the commodity on top of [`Self::remember`]'s bring-your-own-links
222    /// core: each extracted fact is stored (tagged with `metadata`), each salient
223    /// topic becomes a deduplicated hub memory, and every fact is linked to its
224    /// topics with a bidirectional `about`/`mentions` edge. Two facts sharing a
225    /// topic therefore become reachable from one another, so [`Self::why`] has a
226    /// real graph to traverse with no manual `relate()`.
227    ///
228    /// Entity hubs are content-addressed, so the same topic seen across many
229    /// calls collapses onto one hub. Returns the ids of the stored facts (entity
230    /// hubs excluded), in extraction order.
231    ///
232    /// # Errors
233    /// Returns [`MemoryError::EmptyFact`] for empty/whitespace `text`,
234    /// [`MemoryError::Extract`] if extraction fails, [`MemoryError::ReservedKey`]
235    /// if `metadata` names a reserved key, or a storage error if persistence fails.
236    pub fn remember_extracted<X: Extractor>(
237        &self,
238        text: &str,
239        extractor: &X,
240        metadata: Option<&Metadata>,
241    ) -> Result<Vec<u64>, MemoryError> {
242        let text = text.trim();
243        if text.is_empty() {
244            return Err(MemoryError::EmptyFact);
245        }
246        let facts = extractor.extract(text)?;
247        let mut fact_ids = Vec::with_capacity(facts.len());
248        let mut entity_ids: HashMap<String, u64> = HashMap::new();
249        let mut edges: HashSet<(u64, u64)> = HashSet::new();
250        let mut seeded: HashSet<u64> = HashSet::new();
251        for fact in &facts {
252            let content = fact.text.trim();
253            if content.is_empty() {
254                continue;
255            }
256            let fact_id = self.remember(content, &[], metadata)?;
257            fact_ids.push(fact_id);
258            self.wire_entities(
259                fact_id,
260                &fact.entities,
261                &mut entity_ids,
262                &mut edges,
263                &mut seeded,
264            )?;
265        }
266        Ok(fact_ids)
267    }
268
269    /// Link `fact_id` to each of its topics with a deduplicated edge in *both*
270    /// directions. `why()` only follows outgoing edges, so the fact→topic edge
271    /// alone leaves hubs as dead ends; the topic→fact edge is what lets a walk
272    /// hop from one fact, through a shared topic, to its sibling facts.
273    fn wire_entities(
274        &self,
275        fact_id: u64,
276        entities: &[String],
277        entity_ids: &mut HashMap<String, u64>,
278        edges: &mut HashSet<(u64, u64)>,
279        seeded: &mut HashSet<u64>,
280    ) -> Result<(), MemoryError> {
281        for entity in entities {
282            // Skip blank or punctuation-only topics: they would persist as junk
283            // hubs (`Entity: -`) yet can never carry a meaningful multi-hop link.
284            if entity.chars().any(char::is_alphanumeric) {
285                self.wire_entity(fact_id, entity, entity_ids, edges, seeded)?;
286            }
287        }
288        Ok(())
289    }
290
291    /// Wire one topic to `fact_id`: resolve its hub, then add the deduplicated
292    /// `about`/`mentions` pair (skipping a hub that is the fact itself).
293    fn wire_entity(
294        &self,
295        fact_id: u64,
296        entity: &str,
297        entity_ids: &mut HashMap<String, u64>,
298        edges: &mut HashSet<(u64, u64)>,
299        seeded: &mut HashSet<u64>,
300    ) -> Result<(), MemoryError> {
301        let entity_id = self.entity_hub(entity, entity_ids)?;
302        if entity_id == fact_id {
303            return Ok(());
304        }
305        // Fold already-persisted edges into the dedup set so re-ingesting the
306        // same text never creates duplicate parallel edges (core `relate` does
307        // not dedup by endpoint+label, only by edge id).
308        self.seed_existing_edges(fact_id, edges, seeded)?;
309        self.seed_existing_edges(entity_id, edges, seeded)?;
310        self.add_edge(fact_id, entity_id, "about", edges)?;
311        self.add_edge(entity_id, fact_id, MENTIONS_RELATION, edges)?;
312        Ok(())
313    }
314
315    /// Create the edge `from -> to` labelled `label`, unless `edges` already
316    /// records that endpoint pair (in-call and persisted dedup).
317    fn add_edge(
318        &self,
319        from: u64,
320        to: u64,
321        label: &str,
322        edges: &mut HashSet<(u64, u64)>,
323    ) -> Result<(), MemoryError> {
324        if edges.insert((from, to)) {
325            self.relate(from, to, label)?;
326        }
327        Ok(())
328    }
329
330    /// Load `node`'s already-persisted outgoing edges into `edges` once per call
331    /// (tracked by `seeded`), so the dedup set reflects the stored graph and a
332    /// repeated ingest is idempotent rather than edge-duplicating.
333    fn seed_existing_edges(
334        &self,
335        node: u64,
336        edges: &mut HashSet<(u64, u64)>,
337        seeded: &mut HashSet<u64>,
338    ) -> Result<(), MemoryError> {
339        if !seeded.insert(node) {
340            return Ok(());
341        }
342        for edge in self.store.relations(node)? {
343            edges.insert((node, edge.to));
344        }
345        Ok(())
346    }
347
348    /// Get or create the hub memory for a topic, caching its id per call. The
349    /// hub id is a deterministic function of the (normalized) topic, so the same
350    /// topic resolves to the same hub across calls — never a duplicate.
351    fn entity_hub(
352        &self,
353        entity: &str,
354        entity_ids: &mut HashMap<String, u64>,
355    ) -> Result<u64, MemoryError> {
356        let key = entity.trim().to_lowercase();
357        if let Some(&id) = entity_ids.get(&key) {
358            return Ok(id);
359        }
360        let id = self.remember_hub(&key)?;
361        entity_ids.insert(key, id);
362        Ok(id)
363    }
364
365    /// Idempotently store the hub memory for topic `key`. The id is salted so the
366    /// hub id space is disjoint from natural fact ids (no caller fact can collide
367    /// with or overwrite a hub), while the stored content stays human-readable.
368    /// Marked with the reserved [`HUB_FIELD`] so recall and `why` seeds exclude
369    /// it; goes straight to [`Self::store_fact`] to bypass the caller-facing
370    /// reserved-key rejection in [`Self::remember`].
371    fn remember_hub(&self, key: &str) -> Result<u64, MemoryError> {
372        let id = id::stable_id(&format!("{HUB_ID_SALT}{key}"));
373        let content = format!("Entity: {key}");
374        let embedding = self.embedder.embed(&content)?;
375        let mut meta = Map::new();
376        meta.insert(HUB_FIELD.to_string(), Value::Bool(true));
377        // Topic hubs are graph anchors — they never expire.
378        self.store_fact(id, &content, &embedding, Some(&meta), None)?;
379        Ok(id)
380    }
381
382    /// Fail with [`MemoryError::UnknownMemory`] unless memory `id` exists.
383    fn ensure_exists(&self, id: u64) -> Result<(), MemoryError> {
384        if self.store.get(id)?.is_none() {
385            return Err(MemoryError::UnknownMemory(id));
386        }
387        Ok(())
388    }
389
390    /// Fail unless every link target already exists (keeps `remember` atomic).
391    fn ensure_link_targets_exist(&self, links: &[Link]) -> Result<(), MemoryError> {
392        for link in links {
393            self.ensure_exists(link.target)?;
394        }
395        Ok(())
396    }
397
398    /// Store a fact with any combination of metadata and a durable TTL.
399    fn store_fact(
400        &self,
401        id: u64,
402        fact: &str,
403        embedding: &[f32],
404        metadata: Option<&Metadata>,
405        ttl_seconds: Option<u64>,
406    ) -> Result<(), MemoryError> {
407        match (metadata, ttl_seconds) {
408            (Some(meta), Some(ttl)) => {
409                // store_with_ttl writes the fact + the durable expiry; update_metadata
410                // then merges the metadata while preserving `_veles_expires_at`.
411                self.store.store_with_ttl(id, fact, embedding, ttl)?;
412                self.store.update_metadata(id, meta)?;
413            }
414            (Some(meta), None) => self.store.store_with_metadata(id, fact, embedding, meta)?,
415            (None, Some(ttl)) => self.store.store_with_ttl(id, fact, embedding, ttl)?,
416            (None, None) => self.store.store(id, fact, embedding)?,
417        }
418        Ok(())
419    }
420
421    /// Recall up to `k` memories semantically similar to `query` (vector facet),
422    /// optionally narrowed to an exact-match metadata `filter` (`ColumnStore`
423    /// facet) — e.g. `{ "project": "veles", "status": "resolved" }`.
424    ///
425    /// A highly selective filter may return fewer than `k` hits even when more
426    /// matches exist — raise `k` for fuller coverage with a narrow filter.
427    ///
428    /// Entity hubs created by [`Self::remember_extracted`] are never returned:
429    /// they are internal graph scaffolding, not facts the caller stored.
430    ///
431    /// Each hit carries its caller metadata (`Recollection::metadata`, `None`
432    /// when the fact carries none) — store a date field (e.g. `occurred_at`)
433    /// and it round-trips here, so a caller can sort the result into a
434    /// chronological, date-stamped context without `recall_where`'s explicit
435    /// filters. One extra, single batched lookup covers every returned hit.
436    ///
437    /// # Errors
438    /// Returns [`MemoryError`] if the semantic query or the metadata lookup fails.
439    pub fn recall(
440        &self,
441        query: &str,
442        k: usize,
443        filter: Option<&Metadata>,
444    ) -> Result<Vec<Recollection>, MemoryError> {
445        let query = query.trim();
446        if query.is_empty() {
447            return Ok(Vec::new());
448        }
449        reject_reserved_keys(filter)?;
450        let embedding = self.embedder.embed(query)?;
451        let hits = self.search(&embedding, k, filter)?;
452        let ids: Vec<u64> = hits.iter().map(|(id, _, _)| *id).collect();
453        // One raw batched payload lookup (reserved keys included), reused for
454        // BOTH the RL re-rank and the caller-facing metadata below — a single
455        // round trip, not one per concern.
456        let payloads = self.store.get_metadata_batch(&ids)?;
457        // RL Memory: re-order the recalled set by learned confidence. Facts
458        // that never received `feedback` keep their similarity order exactly.
459        #[cfg(feature = "persistence")]
460        let (hits, payloads) = Self::rl_rerank(hits, payloads);
461        Ok(hits
462            .into_iter()
463            .zip(payloads)
464            .map(|((id, score, content), payload)| Recollection {
465                id,
466                score,
467                content,
468                metadata: strip_reserved_keys(payload),
469            })
470            .collect())
471    }
472
473    /// Vector search for up to `k` ids, optionally narrowed by a metadata
474    /// `filter`. Shared by [`Self::recall`] and [`Self::why`].
475    fn search(
476        &self,
477        embedding: &[f32],
478        k: usize,
479        filter: Option<&Metadata>,
480    ) -> Result<Vec<(u64, f32, String)>, MemoryError> {
481        match filter {
482            // An include filter already excludes hubs: a hub's payload
483            // carries only reserved keys (`content`, `_veles_hub`), and
484            // reserved keys are rejected from caller filters, so a non-empty
485            // filter can never match a hub. An EMPTY-but-present filter (`Some({})`, the
486            // natural `{}` idiom at the JS boundary) matches every payload —
487            // hubs included — so it must take the hub-excluding path below,
488            // exactly like an absent filter (same `Some({})` ≡ `None`
489            // convention as `recall_fused`'s graph-side `matches_filter`).
490            Some(meta) if !meta.is_empty() => self.store.query_filtered(embedding, k, meta, 0),
491            // Unfiltered recall must still drop entity hubs explicitly, or a hub
492            // like `Entity: rust` would rank for the topic and evict a real fact.
493            _ => self
494                .store
495                .query_excluding(embedding, k, &hub_exclude_filter()),
496        }
497    }
498
499    /// Fused recall: semantic `NEAR` search combined with structured
500    /// `ColumnStore` predicates over metadata columns — ranges and comparisons,
501    /// not just the equality of [`Self::recall`]. One query spanning the vector
502    /// and column facets (e.g. "most similar facts **with `timestamp` in this
503    /// window**"), which a vector-only or equality-only recall cannot express.
504    ///
505    /// Filter *values* are bound as query parameters (never interpolated), so
506    /// they cannot inject; filter *field names* are validated to be plain
507    /// identifiers. Results come back in similarity order.
508    ///
509    /// # Errors
510    /// Returns [`MemoryError::InvalidFilter`] if a filter field is not a plain
511    /// identifier, [`MemoryError::Embed`] if the query cannot be embedded, or a
512    /// storage error if the query fails. An empty query or `k == 0` yields `[]`.
513    pub fn recall_where(
514        &self,
515        query: &str,
516        k: usize,
517        filters: &[ColumnFilter],
518    ) -> Result<Vec<Recollection>, MemoryError> {
519        let query = query.trim();
520        if query.is_empty() || k == 0 {
521            return Ok(Vec::new());
522        }
523        // No column predicates = a plain recall: route through [`Self::recall`]
524        // so entity hubs stay excluded — `query_columnar` with an empty filter
525        // set is a bare vector search that would rank internal `Entity:` hub
526        // scaffolding as results (same `[]` ≡ unfiltered convention as
527        // `search`'s empty-map handling).
528        if filters.is_empty() {
529            return self.recall(query, k, None);
530        }
531        let embedding = self.embedder.embed(query)?;
532        self.store.query_columnar(&embedding, k, filters)
533    }
534
535    /// Create a typed edge `from -> to`. Returns the edge id.
536    ///
537    /// Both endpoints are validated to exist first, so the tool reports an
538    /// unknown id as client input (`UnknownMemory`) rather than a generic
539    /// storage fault — and the graph never gains an edge dangling off a memory
540    /// that was never stored.
541    ///
542    /// # Errors
543    /// Returns [`MemoryError::UnknownMemory`] if either endpoint is missing, or
544    /// a storage error if the edge cannot be created.
545    pub fn relate(&self, from: u64, to: u64, relation: &str) -> Result<u64, MemoryError> {
546        validate_relation(relation)?;
547        self.ensure_exists(from)?;
548        self.ensure_exists(to)?;
549        self.store.relate(from, to, relation)
550    }
551
552    /// Forget (delete) the memory with `fact_id`. Returns whether a memory
553    /// actually existed under that id — the underlying store's `delete` is a
554    /// silent no-op on an unknown id (matching most backends' idempotent
555    /// delete semantics), which is indistinguishable from a real deletion
556    /// unless existence is checked first. Every surface that exposes
557    /// `forget` (MCP, Node, WASM, Python) forwards this so a caller can tell
558    /// "I removed something" from "that id was a typo".
559    ///
560    /// The delete always runs, even when `get` reports the id absent: `get`
561    /// filters TTL-expired facts, and an expired-but-unpurged row must still
562    /// be reclaimed (the caller is told `false` — the memory was already
563    /// gone from its perspective). Existence check and delete are two store
564    /// calls, not one atomic operation: two concurrent forgets of one id may
565    /// both report `true`.
566    ///
567    /// # Errors
568    /// Returns [`MemoryError`] if the existence check or the deletion fails.
569    pub fn forget(&self, fact_id: u64) -> Result<bool, MemoryError> {
570        let found = self.store.get(fact_id)?.is_some();
571        self.store.delete(fact_id)?;
572        Ok(found)
573    }
574
575    /// Explain a `decision`: find the best-matching memory (optionally scoped to
576    /// a metadata `filter`, e.g. the current project), then walk its typed links
577    /// up to `max_hops` away — fusing the vector, `ColumnStore`, and graph facets.
578    ///
579    /// Returns an empty [`Explanation`] when nothing matches the decision.
580    ///
581    /// # Errors
582    /// Returns [`MemoryError`] if recall or graph traversal fails.
583    pub fn why(
584        &self,
585        decision: &str,
586        max_hops: usize,
587        filter: Option<&Metadata>,
588    ) -> Result<Explanation, MemoryError> {
589        let decision = decision.trim();
590        if decision.is_empty() {
591            return Ok(Explanation::default());
592        }
593        reject_reserved_keys(filter)?;
594        let embedding = self.embedder.embed(decision)?;
595        let seeds = self.search(&embedding, 1, filter)?;
596        let Some((seed_id, _score, seed_content)) = seeds.into_iter().next() else {
597            return Ok(Explanation::default());
598        };
599        self.traverse(seed_id, seed_content, max_hops)
600    }
601
602    /// Breadth-first walk over outgoing links from `seed_id`, collecting nodes
603    /// and edges up to `max_hops` away.
604    fn traverse(
605        &self,
606        seed_id: u64,
607        seed_content: String,
608        max_hops: usize,
609    ) -> Result<Explanation, MemoryError> {
610        let mut explanation = Explanation {
611            nodes: vec![MemoryNode {
612                id: seed_id,
613                content: seed_content,
614                hop: 0,
615            }],
616            edges: Vec::new(),
617        };
618        let mut visited: HashSet<u64> = HashSet::from([seed_id]);
619        let mut frontier = vec![seed_id];
620        let mut next: Vec<u64> = Vec::new();
621        for hop in 1..=max_hops {
622            next.clear();
623            for node_id in frontier.drain(..) {
624                self.expand(node_id, hop, &mut explanation, &mut visited, &mut next)?;
625            }
626            if next.is_empty() {
627                break;
628            }
629            std::mem::swap(&mut frontier, &mut next);
630        }
631        Ok(explanation)
632    }
633
634    /// Expand a single node: enqueue unseen targets and record edges. An edge is
635    /// only recorded once its target is a resolved node, so the subgraph never
636    /// contains an edge pointing at a node absent from `nodes` (e.g. a forgotten
637    /// target whose edge outlived it).
638    fn expand(
639        &self,
640        node_id: u64,
641        hop: usize,
642        explanation: &mut Explanation,
643        visited: &mut HashSet<u64>,
644        next: &mut Vec<u64>,
645    ) -> Result<(), MemoryError> {
646        for edge in self.store.relations(node_id)? {
647            let target = edge.to;
648            if !visited.contains(&target) {
649                let Some((content, _embedding)) = self.store.get(target)? else {
650                    continue; // target no longer exists → drop the dangling edge too
651                };
652                visited.insert(target);
653                explanation.nodes.push(MemoryNode {
654                    id: target,
655                    content,
656                    hop,
657                });
658                next.push(target);
659            }
660            explanation.edges.push(edge);
661        }
662        Ok(())
663    }
664}
665
666/// The metadata filter that excludes entity hubs from unfiltered recall and
667/// `why` seeds — the negative counterpart [`MemoryService::search`] applies so
668/// internal `_veles_hub` scaffolding never surfaces as a result.
669fn hub_exclude_filter() -> Metadata {
670    let mut exclude = Map::new();
671    exclude.insert(HUB_FIELD.to_string(), Value::Bool(true));
672    exclude
673}
674
675/// Reject caller-supplied metadata/filters that name a reserved key.
676fn reject_reserved_keys(metadata: Option<&Metadata>) -> Result<(), MemoryError> {
677    let Some(meta) = metadata else {
678        return Ok(());
679    };
680    for key in meta.keys() {
681        if is_reserved_key(key) {
682            return Err(MemoryError::ReservedKey(key.clone()));
683        }
684    }
685    Ok(())
686}
687
688/// Normalise a requested TTL: `Some(0)` (and `None`) mean "no expiry" — the fact
689/// is stored permanently. Any positive value is kept as-is.
690fn positive_ttl(ttl_seconds: Option<u64>) -> Option<u64> {
691    ttl_seconds.filter(|&seconds| seconds > 0)
692}
693
694/// Maximum byte length for a relation label (prevents oversized graph edge labels
695/// from reaching the storage layer).
696const MAX_RELATION_BYTES: usize = 512;
697
698/// Validate a caller-supplied relation label: non-empty, within the size cap, and
699/// containing only printable, non-control ASCII characters (32–126) or non-ASCII
700/// Unicode. This prevents null bytes and control characters from reaching the
701/// storage layer while permitting natural-language labels like `"decided_in"` or
702/// `"is a friend of"`.
703fn validate_relation(label: &str) -> Result<(), MemoryError> {
704    if label.is_empty() {
705        return Err(MemoryError::InvalidRelation(
706            "relation label must not be empty".to_owned(),
707        ));
708    }
709    if label.len() > MAX_RELATION_BYTES {
710        return Err(MemoryError::InvalidRelation(format!(
711            "relation label exceeds maximum of {MAX_RELATION_BYTES} bytes ({} given)",
712            label.len()
713        )));
714    }
715    if label.chars().any(|c| c.is_ascii_control()) {
716        return Err(MemoryError::InvalidRelation(
717            "relation label must not contain ASCII control characters".to_owned(),
718        ));
719    }
720    Ok(())
721}