Skip to main content

velesdb_memory/context/
memory_bridge.rs

1//! The context compiler's memory bridge: memory-backed fragment selection,
2//! recoverable sources, aggregatable compilation events, and persisted
3//! working contexts — the `MemoryService` half of EPIC-P-070's US-002.
4//!
5//! Everything the bridge persists is a **system fact**: hub-marked
6//! (`_veles_hub`) and carrying **only reserved `_veles_*` metadata keys**, so
7//! it is invisible to unfiltered recall (hub exclusion), can never match a
8//! caller's include filter (callers cannot name reserved keys), and can never
9//! be forged by a caller fact (reserved keys are rejected at `remember`).
10//! Stored ids are salted, and both the source writer and the handle resolver
11//! verify the `_veles_ctx_source` marker, so a caller fact squatting a salt
12//! preimage is neither overwritten nor ever served back as a source. Events
13//! carry metadata and hashes only — never fragment content. Event recording
14//! stamps wall-clock time; the compile pipeline itself stays clock-free and
15//! deterministic.
16
17use std::collections::BTreeMap;
18use std::sync::atomic::{AtomicU64, Ordering};
19#[cfg(not(target_arch = "wasm32"))]
20use std::time::{SystemTime, UNIX_EPOCH};
21
22/// Wall-clock nanos since the Unix epoch, stamped on savings events only —
23/// never in the compile pipeline. On `wasm32-unknown-unknown`
24/// `SystemTime::now()` aborts (`std` has no clock there), so events carry 0:
25/// the per-process sequence alone uniquifies their ids, and wasm stats are
26/// per-session by design (in-memory store).
27fn now_nanos() -> u128 {
28    #[cfg(target_arch = "wasm32")]
29    {
30        0
31    }
32    #[cfg(not(target_arch = "wasm32"))]
33    {
34        SystemTime::now()
35            .duration_since(UNIX_EPOCH)
36            .map(|elapsed| elapsed.as_nanos())
37            .unwrap_or(0)
38    }
39}
40
41/// Current Unix time in seconds — used only by
42/// [`MemoryService::should_upgrade_ttl`]'s extension-only comparison (the
43/// storage/expiry layer; the `compile` pipeline itself stays clock-free). On
44/// `wasm32-unknown-unknown` this is 0 (no clock, mirrors [`now_nanos`]); the
45/// wasm `MemoryStore` is in-memory only, so a stored durable expiry (a real
46/// epoch second count) never actually exists there for 0 to be compared
47/// against.
48fn now_unix_secs() -> u64 {
49    #[cfg(target_arch = "wasm32")]
50    {
51        0
52    }
53    #[cfg(not(target_arch = "wasm32"))]
54    {
55        SystemTime::now()
56            .duration_since(UNIX_EPOCH)
57            .map(|elapsed| elapsed.as_secs())
58            .unwrap_or(0)
59    }
60}
61
62use serde_json::{Map, Number, Value};
63
64use super::{positive_ttl, MemoryService, Metadata, HUB_FIELD};
65use crate::context::model::{
66    CompileRequest, CompiledContext, ContextFragment, ContextSavings, ContextSource,
67    ImportanceWeights, MediaRef, MemoryScope, WorkingContext, WorkingContextIndex,
68    WorkingContextSession,
69};
70use crate::context::{media, provenance, ContextCompiler};
71use crate::embedder::Embedder;
72use crate::error::MemoryError;
73use crate::id::stable_id;
74use crate::model::FusionOptions;
75use crate::storage::MemoryStore;
76
77/// Salt for stored source ids — disjoint from natural fact ids, so a caller
78/// later remembering the same text can never overwrite a stored source (or
79/// inherit its system marker).
80const SOURCE_ID_SALT: &str = "veles-ctx-source:";
81/// Salt for compilation-event ids.
82const EVENT_ID_SALT: &str = "veles-ctx-event:";
83/// Salt for working-context ids (deterministic per project+session, so a
84/// save is an idempotent upsert).
85const WORKING_ID_SALT: &str = "veles-ctx-working:";
86/// Salt for a project's working-context index id (deterministic per
87/// project, so every `save_working_context` call updates the SAME system
88/// fact rather than minting a new one).
89const WORKING_INDEX_ID_SALT: &str = "veles-ctx-working-index:";
90
91/// The constant lexical anchor every event's content starts with, so one
92/// vector query can sweep the event family for aggregation.
93const EVENT_ANCHOR: &str = "veles context compilation event";
94
95/// Reserved metadata keys of the bridge's system facts. Reserved (`_veles_`)
96/// on purpose: callers can neither set them (forgery) nor filter on them, so
97/// system facts are invisible to every caller-facing recall path and
98/// [`MemoryService::context_savings`] aggregates only genuine events (it
99/// filters at the storage layer, below the caller-facing validation).
100const CTX_EVENT_FIELD: &str = "_veles_ctx_event";
101const CTX_PROJECT_FIELD: &str = "_veles_ctx_project";
102const CTX_MODEL_FIELD: &str = "_veles_ctx_model";
103const CTX_SOURCE_FIELD: &str = "_veles_ctx_source";
104/// A stored source's media payload (US-009, PR2): `{"mime", "bytes_b64"}`,
105/// the exact [`MediaRef`] shape, set only when the source fragment carried
106/// one. Reserved like every other `_veles_ctx_*` key — a caller can neither
107/// set nor filter on it.
108const CTX_SOURCE_MEDIA_FIELD: &str = "_veles_ctx_source_media";
109/// The durable-TTL payload key set by [`super::positive_ttl`]-backed writes
110/// (`store_with_ttl`, via `store_fact`). Mirrors `velesdb_core::EXPIRES_AT_KEY`
111/// as a literal rather than an import: that re-export is `persistence`-gated,
112/// and this module (unlike `NativeStore`) must keep compiling under `context`
113/// alone (e.g. `velesdb-wasm`, which never enables `persistence`).
114const EXPIRES_AT_FIELD: &str = "_veles_expires_at";
115const CTX_WORKING_FIELD: &str = "_veles_ctx_working";
116/// Marks a project's working-context index fact (V2a-1's
117/// `list_working_contexts`), symmetric to [`CTX_WORKING_FIELD`].
118const CTX_WORKING_INDEX_FIELD: &str = "_veles_ctx_working_index";
119const CTX_SESSION_FIELD: &str = "_veles_ctx_session";
120const CTX_TOKENS_IN_FIELD: &str = "_veles_ctx_tokens_in";
121const CTX_TOKENS_OUT_FIELD: &str = "_veles_ctx_tokens_out";
122const CTX_TOKENS_SAVED_FIELD: &str = "_veles_ctx_tokens_saved";
123const CTX_COST_FIELD: &str = "_veles_ctx_cost_micros";
124const CTX_CURRENCY_FIELD: &str = "_veles_ctx_currency";
125const CTX_AT_FIELD: &str = "_veles_ctx_at";
126
127/// Per-process sequence folded into event ids so two compilations landing on
128/// the same clock tick (coarse timers, concurrent calls) never collide.
129static EVENT_SEQ: AtomicU64 = AtomicU64::new(0);
130
131impl<E: Embedder, S: MemoryStore> MemoryService<E, S> {
132    /// [`ContextCompiler::compile`] with this service's memory folded in:
133    /// when the request carries a [`MemoryScope`], relevant memories are
134    /// pulled through the fused vector+graph recall and compiled alongside
135    /// the caller's fragments, each with its `memory_id` and a normalised
136    /// fused-ranking relevance recorded in provenance. Afterwards (policy
137    /// permitting) the distinct originals are stored so every
138    /// `ctx://source/<hash>` handle round-trips, and a metadata-only
139    /// compilation event is recorded for [`Self::context_savings`].
140    ///
141    /// # Errors
142    /// Returns [`MemoryError`] if compilation itself fails (budget, caps),
143    /// or if recall, embedding, or storage fails.
144    pub fn compile_context(
145        &self,
146        compiler: &ContextCompiler,
147        request: &CompileRequest,
148    ) -> Result<CompiledContext, MemoryError> {
149        let importance = compiler.effective_policy(request).importance.clone();
150        let memories = self.context_memories(request, &importance)?;
151        self.compile_with_memories(compiler, request, memories)
152    }
153
154    /// [`Self::compile_context`] with a caller-supplied [`crate::Reranker`] driving
155    /// memory selection: the reranker receives the FULL fused candidate pool
156    /// (vector + graph, before the `k` cutoff) and its ordering decides
157    /// which `k` memories are compiled in — the seam for a semantic
158    /// cross-encoder or LLM judge a Rust embedder brings along. Not exposed
159    /// on the wire (a reranker is code, not JSON), and never a default: the
160    /// shipped [`crate::context::DeterministicReranker`] is *lexical*, and a
161    /// lexical second stage demotes exactly the zero-vocabulary-overlap
162    /// evidence the graph walk rescues (measured in the BDD suite) — bring
163    /// a semantic one.
164    ///
165    /// # Errors
166    /// Returns [`MemoryError`] if compilation, recall, the reranker itself,
167    /// or storage fails.
168    pub fn compile_context_reranked<R: crate::Reranker>(
169        &self,
170        compiler: &ContextCompiler,
171        request: &CompileRequest,
172        reranker: &R,
173    ) -> Result<CompiledContext, MemoryError> {
174        let importance = compiler.effective_policy(request).importance.clone();
175        let memories = self.context_memories_reranked(request, reranker, &importance)?;
176        self.compile_with_memories(compiler, request, memories)
177    }
178
179    /// The shared back half of every compile flavour: augment the request
180    /// with the pulled memories, compile, annotate provenance, persist
181    /// sources/events per policy.
182    fn compile_with_memories(
183        &self,
184        compiler: &ContextCompiler,
185        request: &CompileRequest,
186        memories: Vec<PulledMemory>,
187    ) -> Result<CompiledContext, MemoryError> {
188        let mut augmented = request.clone();
189        let mut pulled: BTreeMap<u64, PulledMemory> = BTreeMap::new();
190        for memory in memories {
191            augmented.fragments.push(memory.fragment.clone());
192            pulled.insert(stable_id(&memory.fragment.content), memory);
193        }
194        // `compile_raw`, not `compile`: annotating memory provenance below
195        // can rewrite a pulled fragment's `relevance`/`reason` (and thus
196        // whether it crosses the `warnings` threshold), so `decisions` must
197        // stay full until that has happened and `warnings` is recomputed —
198        // `slim_response` (if requested) is applied as the LAST step.
199        let mut out = compiler.compile_raw(&augmented)?;
200        annotate_memory_provenance(&mut out, &pulled);
201        out.warnings = crate::context::warnings_for(&out.decisions);
202        let policy = compiler.effective_policy(request);
203        if policy.store_sources {
204            self.store_context_sources(&augmented, &out, policy.source_ttl_seconds)?;
205        }
206        if policy.record_events {
207            self.record_context_event(request, &out, policy.event_ttl_seconds)?;
208        }
209        Ok(crate::context::apply_slim(out, policy))
210    }
211
212    /// The memories a request's scope pulls in, as compile fragments plus
213    /// their id and normalised fused relevance, importance-blended
214    /// ([`Self::blend_importance`]) when the policy's weights are active.
215    fn context_memories(
216        &self,
217        request: &CompileRequest,
218        importance: &ImportanceWeights,
219    ) -> Result<Vec<PulledMemory>, MemoryError> {
220        let Some((scope, k)) = scope_and_k(request) else {
221            return Ok(Vec::new());
222        };
223        let filter = scope_filter(scope);
224        // The scope's fusion knobs (clamped by from_knobs); absent ones fall
225        // back to the crate defaults — raising graph_boost lets a curated
226        // relate-chain out-rank lexically-noisy near-misses (see MemoryScope).
227        let opts = FusionOptions::from_knobs(scope.hops, scope.graph_boost, None);
228        let scored = self.recall_fused_scored(&request.query, k, filter.as_ref(), opts)?;
229        let max_fused = scored
230            .iter()
231            .map(|s| s.fused)
232            .fold(f64::MIN, f64::max)
233            .max(f64::EPSILON);
234        let candidates = scored
235            .into_iter()
236            .map(|scored| {
237                // Sanitise a non-finite fused score to 0 before normalising:
238                // `f32::clamp` returns NaN for a NaN input (it does not clamp),
239                // which would put a non-`[0, 1]` value — serialising as JSON
240                // `null` — into an output sold as deterministic and auditable.
241                let fused = if scored.fused.is_finite() {
242                    scored.fused
243                } else {
244                    0.0
245                };
246                MemoryCandidate {
247                    memory_id: scored.recollection.id,
248                    base: (fused / max_fused).clamp(0.0, 1.0),
249                    vector_norm: scored.vector_norm,
250                    graph_weight: scored.graph_weight,
251                    metadata: scored.recollection.metadata,
252                    content: scored.recollection.content,
253                }
254            })
255            .collect();
256        self.blend_importance(candidates, importance)
257    }
258
259    /// Memory selection driven by a caller-supplied reranker: the fused
260    /// candidate pool (at pool depth, vector + graph) is handed to the
261    /// reranker whole, its ordering is truncated to `k`, and relevance is
262    /// rank-based (the reranker defines the ranking; the fused ventilation
263    /// no longer describes it, so vector/graph read 0 in provenance). The
264    /// importance blend then composes with the seam: it re-ranks INSIDE the
265    /// reranker-selected pool, exactly as it does over the fused pool.
266    fn context_memories_reranked<R: crate::Reranker>(
267        &self,
268        request: &CompileRequest,
269        reranker: &R,
270        importance: &ImportanceWeights,
271    ) -> Result<Vec<PulledMemory>, MemoryError> {
272        let Some((scope, k)) = scope_and_k(request) else {
273            return Ok(Vec::new());
274        };
275        let filter = scope_filter(scope);
276        let opts = FusionOptions::from_knobs(scope.hops, scope.graph_boost, None);
277        let ranked =
278            self.recall_fused_reranked(&request.query, k, filter.as_ref(), opts, reranker)?;
279        let count = ranked.len().max(1);
280        let candidates = ranked
281            .into_iter()
282            .enumerate()
283            .map(|(rank, recollection)| {
284                // Computed in f32 exactly as 0.8.0 did, so inactive weights
285                // reproduce the historical relevance bytes.
286                #[allow(clippy::cast_precision_loss)] // rank/count are tiny
287                let relevance = 1.0 - (rank as f32 / count as f32);
288                MemoryCandidate {
289                    memory_id: recollection.id,
290                    base: f64::from(relevance),
291                    vector_norm: 0.0,
292                    graph_weight: 0.0,
293                    metadata: recollection.metadata,
294                    content: recollection.content,
295                }
296            })
297            .collect();
298        self.blend_importance(candidates, importance)
299    }
300
301    /// Fold usage-driven importance into an already-selected memory pool —
302    /// the one ranking the whole engine stack shares (US-002 of EPIC-P-071):
303    /// per candidate the key becomes `base + w_c·(confidence − 0.5)·2 +
304    /// w_r·recency_norm`, where `base` is the fused (or rank-based)
305    /// similarity in `[0, 1]`. Selection is untouched on purpose: confidence
306    /// is not relevance, so a reinforced-but-off-topic fact can never buy
307    /// its way into the pool here. Inactive weights take the zero-cost path
308    /// and reproduce the 0.8.0 output byte for byte (golden-pinned). The
309    /// stable sort keeps equal keys in selection order, and no clock is ever
310    /// read — recency is min-max normalised within the batch.
311    fn blend_importance(
312        &self,
313        candidates: Vec<MemoryCandidate>,
314        weights: &ImportanceWeights,
315    ) -> Result<Vec<PulledMemory>, MemoryError> {
316        if !importance_active(weights) {
317            return Ok(candidates
318                .into_iter()
319                .map(MemoryCandidate::into_pulled)
320                .collect());
321        }
322        let ids: Vec<u64> = candidates.iter().map(|c| c.memory_id).collect();
323        // Raw payloads (reserved keys included): the learned confidence
324        // lives under `_veles_rl_confidence`, which caller-facing metadata
325        // strips.
326        let raw = self.store.get_metadata_batch(&ids)?;
327        let recencies = recency_norms(&candidates, weights);
328        let mut blended: Vec<(f64, PulledMemory)> = candidates
329            .into_iter()
330            .zip(raw)
331            .zip(recencies)
332            .map(|((candidate, payload), recency)| {
333                let confidence = payload_confidence(payload.as_ref());
334                let score = candidate.base
335                    + weights.confidence * (confidence - NEUTRAL_CONFIDENCE) * 2.0
336                    + weights.recency * recency;
337                let mut pulled = candidate.into_pulled();
338                #[allow(clippy::cast_possible_truncation)] // clamped into [0, 1]
339                {
340                    pulled.relevance = score.clamp(0.0, 1.0) as f32;
341                }
342                pulled.confidence = confidence;
343                pulled.recency = recency;
344                pulled.ventilated = true;
345                (score, pulled)
346            })
347            .collect();
348        // Stable: equal blended keys keep the selection order.
349        blended.sort_by(|a, b| b.0.total_cmp(&a.0));
350        Ok(blended.into_iter().map(|(_, pulled)| pulled).collect())
351    }
352
353    /// Store every distinct fragment's original as a hub-marked system fact
354    /// keyed by its salted handle hash, so its handle can be resolved later.
355    /// A fragment carrying media (US-009, PR2) has its base64 payload
356    /// persisted alongside the caption under the reserved
357    /// [`CTX_SOURCE_MEDIA_FIELD`] key.
358    ///
359    /// **Identity**: the key mirrors what the compiler mints handles from
360    /// (`Analysis::handle_hash` in `context.rs`) — the caption's
361    /// [`stable_id`] for text, the raw decoded bytes' hash
362    /// ([`media::MediaAnalysis::raw_hash`]) for media, the same identity
363    /// PR1's dedup keys on. Keying media on the caption instead was the PR2
364    /// review's proven blocker: every captionless image collided onto one
365    /// slot and one handle, serving arbitrary wrong bytes back. The slot
366    /// stays inside the salted system-fact namespace ([`source_id`] applies
367    /// `SOURCE_ID_SALT` to the hash) — same salt, no new namespace. On a
368    /// same-key collision (byte-identical images with different captions)
369    /// the FIRST occurrence wins, matching the dedup twin the compiler
370    /// keeps — a divergent duplicate caption does not survive, exactly as
371    /// its decision reason already says.
372    ///
373    /// Size: [`crate::limits::MAX_MEDIA_BYTES`] /
374    /// [`crate::limits::MAX_TOTAL_MEDIA_BYTES`] already bounded every
375    /// fragment's `bytes_b64` before `compiler.compile` ever ran (see
376    /// `validate_media`, called from `compile`'s `validate`) — `augmented`
377    /// here is exactly the request that passed that check, so no separate
378    /// size guard is needed on the write path itself
379    /// ([`crate::limits::MAX_FACT_BYTES`] governs the unrelated MCP
380    /// `remember`/`extract` text ceiling, not this one).
381    fn store_context_sources(
382        &self,
383        augmented: &CompileRequest,
384        out: &CompiledContext,
385        ttl_seconds: Option<u64>,
386    ) -> Result<(), MemoryError> {
387        let mut by_hash: BTreeMap<u64, &ContextFragment> = BTreeMap::new();
388        for fragment in &augmented.fragments {
389            // First occurrence wins (see the identity note above): `entry`
390            // + `or_insert`, never a blind overwrite.
391            by_hash
392                .entry(fragment_handle_hash(fragment))
393                .or_insert(fragment);
394        }
395        let ttl_seconds = positive_ttl(ttl_seconds);
396        for source in &out.sources {
397            let Some(hash) = provenance::parse_handle(&source.handle) else {
398                continue;
399            };
400            let Some(fragment) = by_hash.get(&hash) else {
401                continue;
402            };
403            let slot = source_id(hash);
404            // A slot never marked as ours is never rewritten: it is a caller
405            // fact squatting the salt preimage, and clobbering it would
406            // destroy user data. A slot already marked as ours holds these
407            // exact bytes — sources are content-addressed — so content and
408            // embedding never change; only durability can, and only upward
409            // (never-downgrade TTL upgrade, `should_store_source`) so a
410            // handle sold as permanent never silently expires just because
411            // an earlier compile first wrote it under a TTL.
412            if !self.should_store_source(slot, ttl_seconds)? {
413                continue;
414            }
415            // Upgrading to permanent needs the old point gone, not merely
416            // overwritten: velesdb-core's store path preserves every
417            // `_veles_*` key from a prior version of a re-stored id unless
418            // the new write explicitly sets it (semantic_memory.rs's
419            // `store_internal` carry-forward, so plain `remember` doesn't
420            // silently wipe learned state), and a permanent write has no
421            // expiry to explicitly set (`attach_expiry` is a no-op without
422            // one) — so without this delete, `_veles_expires_at` would
423            // survive the "upgrade" untouched. A TTL-to-TTL extension needs
424            // no delete: its new expiry always overwrites the old one.
425            if ttl_seconds.is_none() && self.store.get(slot)?.is_some() {
426                self.store.delete(slot)?;
427            }
428            let content = fragment.content.as_str();
429            let mut extra: Vec<(&str, Value)> = vec![(CTX_SOURCE_FIELD, Value::Bool(true))];
430            let embedding = if let Some(media_ref) = &fragment.media {
431                extra.push((
432                    CTX_SOURCE_MEDIA_FIELD,
433                    serde_json::to_value(media_ref).unwrap_or(Value::Null),
434                ));
435                // Deterministic, derived from the DECODED bytes — never the
436                // text embedder over `content` (often blank) or over the
437                // base64 payload itself (opaque, not language). Correct
438                // because `retrieve_context_source` resolves a media source
439                // EXCLUSIVELY by its content-addressed hash/slot, never by
440                // vector search — this vector only needs to be well-formed
441                // and non-degenerate for the underlying index, never
442                // semantically meaningful. For a media fragment `hash` IS
443                // the raw-bytes hash (see `fragment_handle_hash`), so no
444                // re-decode is needed here.
445                self.media_placeholder_embedding(hash)
446            } else {
447                self.embedder.embed(content)?
448            };
449            self.store_fact(
450                slot,
451                content,
452                &embedding,
453                Some(&system_meta(&extra)),
454                ttl_seconds,
455            )?;
456        }
457        Ok(())
458    }
459
460    /// Whether [`Self::store_context_sources`] should (re-)write `slot` for
461    /// this compile's requested (already [`positive_ttl`]-normalized —
462    /// `None` means permanent) TTL.
463    ///
464    /// - Not marked as ours (absent, or a caller fact squatting the salt
465    ///   preimage): store only if the slot is genuinely empty.
466    /// - Marked as ours: never re-embed or change content (content-addressed);
467    ///   only [`Self::should_upgrade_ttl`] decides whether durability changes.
468    fn should_store_source(
469        &self,
470        slot: u64,
471        requested_ttl: Option<u64>,
472    ) -> Result<bool, MemoryError> {
473        match self.context_source_metadata(slot)? {
474            Some(existing) => Ok(Self::should_upgrade_ttl(&existing, requested_ttl)),
475            None => Ok(self.store.get(slot)?.is_none()),
476        }
477    }
478
479    /// Never-downgrade TTL upgrade rule for an already-stored source: permanent
480    /// once requested stays permanent, and a TTL only ever extends, never
481    /// shortens. The clock read here is fine — this is the storage/expiry
482    /// layer, not the clock-free `compile` pipeline.
483    fn should_upgrade_ttl(existing: &Metadata, requested_ttl: Option<u64>) -> bool {
484        let existing_expiry = existing.get(EXPIRES_AT_FIELD).and_then(Value::as_u64);
485        match (requested_ttl, existing_expiry) {
486            // Permanent requested, slot still carries a TTL: upgrade.
487            (None, Some(_)) => true,
488            // Already permanent, or a TTL requested against a permanent slot:
489            // never downgrade.
490            (None | Some(_), None) => false,
491            // Both carry a TTL: extend only if the new one outlives what
492            // remains — never shorten.
493            (Some(ttl), Some(existing_exp)) => now_unix_secs().saturating_add(ttl) > existing_exp,
494        }
495    }
496
497    /// A deterministic, non-degenerate embedding for a media source (US-009,
498    /// PR2) — see [`Self::store_context_sources`] for why it is bytes-hash
499    /// derived rather than text-embedded.
500    fn media_placeholder_embedding(&self, raw_hash: u64) -> Vec<f32> {
501        let dim = self.embedder.dimension();
502        let mut vector = vec![0.0_f32; dim];
503        let Ok(dim_u64) = u64::try_from(dim) else {
504            return vector;
505        };
506        if dim_u64 == 0 {
507            return vector;
508        }
509        let bucket = usize::try_from(raw_hash % dim_u64).unwrap_or(0);
510        vector[bucket] = 1.0;
511        velesdb_core::simd_native::normalize_inplace_native(&mut vector);
512        vector
513    }
514
515    /// The fact at `slot`'s metadata, when it carries the stored-source
516    /// marker (`None` otherwise — absent, or a caller fact squatting the
517    /// slot).
518    fn context_source_metadata(&self, slot: u64) -> Result<Option<Metadata>, MemoryError> {
519        let payloads = self.store.get_metadata_batch(&[slot])?;
520        Ok(payloads
521            .into_iter()
522            .next()
523            .flatten()
524            .filter(|meta| meta.get(CTX_SOURCE_FIELD) == Some(&Value::Bool(true))))
525    }
526
527    /// The original content — and media, when the fragment carried one —
528    /// behind a `ctx://source/<hash>` handle.
529    ///
530    /// # Errors
531    /// Returns [`MemoryError::UnknownHandle`] when the handle is malformed
532    /// or nothing is stored under it (never stored, expired, or forgotten).
533    pub fn retrieve_context_source(&self, handle: &str) -> Result<ContextSource, MemoryError> {
534        let unknown = || MemoryError::UnknownHandle(handle.to_owned());
535        let hash = provenance::parse_handle(handle).ok_or_else(unknown)?;
536        let slot = source_id(hash);
537        // Only marker-bearing facts are sources: a caller fact squatting the
538        // salted slot is never served back as compiled provenance.
539        let meta = self.context_source_metadata(slot)?.ok_or_else(unknown)?;
540        let content = self
541            .store
542            .get(slot)?
543            .map(|(content, _embedding)| content)
544            .ok_or_else(unknown)?;
545        Ok(ContextSource {
546            content,
547            media: source_media(&meta),
548        })
549    }
550
551    /// Record one compilation's savings as a metadata-only system fact
552    /// (hashes and token counts — never fragment content). Wall-clock time
553    /// is stamped here, outside the deterministic compile pipeline.
554    fn record_context_event(
555        &self,
556        request: &CompileRequest,
557        out: &CompiledContext,
558        ttl_seconds: Option<u64>,
559    ) -> Result<(), MemoryError> {
560        let occurred_at_nanos = now_nanos();
561        // The per-process sequence keeps ids unique even when two compiles
562        // land on the same (possibly coarse) clock tick.
563        let seq = EVENT_SEQ.fetch_add(1, Ordering::Relaxed);
564        let content = format!("{EVENT_ANCHOR} {occurred_at_nanos}-{seq}");
565        let id = stable_id(&format!("{EVENT_ID_SALT}{occurred_at_nanos}:{seq}"));
566        let embedding = self.embedder.embed(&content)?;
567        let meta = event_meta(request, out, occurred_at_nanos);
568        self.store_fact(
569            id,
570            &content,
571            &embedding,
572            Some(&meta),
573            positive_ttl(ttl_seconds),
574        )?;
575        Ok(())
576    }
577
578    /// Aggregate the recorded compilation events, optionally per project.
579    /// Sweeps at most [`crate::limits::MAX_RECALL_LIMIT`] events (newest
580    /// need not be first — the sweep is similarity-ordered over a constant
581    /// anchor, i.e. effectively the whole family until the cap);
582    /// [`ContextSavings::truncated`] reports when the cap was hit.
583    ///
584    /// # Errors
585    /// Returns [`MemoryError`] if the underlying filtered recall fails.
586    pub fn context_savings(&self, project: Option<&str>) -> Result<ContextSavings, MemoryError> {
587        // Filter at the STORAGE layer on the reserved event marker: callers
588        // can neither set nor query `_veles_*` keys, so only genuine bridge
589        // events can ever match — a caller fact posing as an event counts
590        // for nothing.
591        let mut filter = Map::new();
592        filter.insert(CTX_EVENT_FIELD.to_owned(), Value::Bool(true));
593        if let Some(project) = project {
594            filter.insert(
595                CTX_PROJECT_FIELD.to_owned(),
596                Value::String(project.to_owned()),
597            );
598        }
599        let embedding = self.embedder.embed(EVENT_ANCHOR)?;
600        let hits =
601            self.store
602                .query_filtered(&embedding, crate::limits::MAX_RECALL_LIMIT, &filter, 0)?;
603        let ids: Vec<u64> = hits.iter().map(|(id, _, _)| *id).collect();
604        let payloads = self.store.get_metadata_batch(&ids)?;
605        Ok(aggregate_events(&payloads))
606    }
607
608    /// Persist `working` under `project` + `session` (idempotent upsert:
609    /// saving again replaces the previous state). Returns the system fact id.
610    ///
611    /// Serialized size is capped at [`crate::limits::MAX_FACT_BYTES`] (1
612    /// MiB) — the same ceiling every other stored fact honors — checked
613    /// BEFORE anything is written, so an oversized working context is never
614    /// partially stored.
615    ///
616    /// # Errors
617    /// Returns [`MemoryError::WorkingContextCodec`] if serialization fails,
618    /// [`MemoryError::ContextOverLimit`] if the serialized `working` exceeds
619    /// [`crate::limits::MAX_FACT_BYTES`], or a storage/embedding error.
620    pub fn save_working_context(
621        &self,
622        project: &str,
623        session: &str,
624        working: &WorkingContext,
625    ) -> Result<u64, MemoryError> {
626        let content = serde_json::to_string(working)
627            .map_err(|err| MemoryError::WorkingContextCodec(err.to_string()))?;
628        if content.len() > crate::limits::MAX_FACT_BYTES {
629            return Err(MemoryError::ContextOverLimit(format!(
630                "working context of {} bytes exceeds the cap of {} bytes",
631                content.len(),
632                crate::limits::MAX_FACT_BYTES
633            )));
634        }
635        let id = working_id(project, session);
636        let embedding = self
637            .embedder
638            .embed(&format!("working context {project} {session}"))?;
639        let meta = system_meta(&[
640            (CTX_WORKING_FIELD, Value::Bool(true)),
641            (CTX_PROJECT_FIELD, Value::String(project.to_owned())),
642            (CTX_SESSION_FIELD, Value::String(session.to_owned())),
643        ]);
644        self.store_fact(id, &content, &embedding, Some(&meta), None)?;
645        self.update_working_index(project, session)?;
646        Ok(id)
647    }
648
649    /// The working context previously saved under `project` + `session`,
650    /// `None` when there is none.
651    ///
652    /// Symmetric to [`Self::context_source_metadata`]'s squatter guard: the
653    /// slot is only ever served back when its metadata carries the reserved
654    /// [`CTX_WORKING_FIELD`] marker (set exclusively by
655    /// [`Self::save_working_context`]). A slot occupied by an unmarked caller
656    /// fact — one that happened to land on this salted id, or a forged
657    /// probe — is indistinguishable from "nothing saved" on purpose: `None`,
658    /// never the forged content, and never an error (the caller cannot tell
659    /// a squatted slot from a genuinely empty one, which is the point — it
660    /// must never learn that *something* occupies this id).
661    ///
662    /// # Errors
663    /// Returns [`MemoryError::WorkingContextCodec`] if the stored payload
664    /// does not parse, or a storage error.
665    pub fn load_working_context(
666        &self,
667        project: &str,
668        session: &str,
669    ) -> Result<Option<WorkingContext>, MemoryError> {
670        let slot = working_id(project, session);
671        let payloads = self.store.get_metadata_batch(&[slot])?;
672        let marked = payloads
673            .into_iter()
674            .next()
675            .flatten()
676            .is_some_and(|meta| meta.get(CTX_WORKING_FIELD) == Some(&Value::Bool(true)));
677        if !marked {
678            return Ok(None);
679        }
680        match self.store.get(slot)? {
681            Some((content, _)) => serde_json::from_str(&content)
682                .map(Some)
683                .map_err(|err| MemoryError::WorkingContextCodec(err.to_string())),
684            None => Ok(None),
685        }
686    }
687
688    /// Every session ever saved under `project`'s working-context index
689    /// (V2a-1 quick win), most-recently-saved first. Empty (never an error)
690    /// when the project never saved anything — reading the index is O(1),
691    /// never a store scan.
692    ///
693    /// # Errors
694    /// Returns a storage error if the index fact cannot be read, or
695    /// [`MemoryError::WorkingContextCodec`] if it does not parse (should
696    /// never happen for a payload this bridge wrote itself).
697    pub fn list_working_contexts(
698        &self,
699        project: &str,
700    ) -> Result<Vec<WorkingContextSession>, MemoryError> {
701        let mut sessions = self
702            .working_index(project)?
703            .map(|index| index.sessions)
704            .unwrap_or_default();
705        sessions.sort_by(|a, b| {
706            b.saved_at
707                .cmp(&a.saved_at)
708                .then_with(|| a.session.cmp(&b.session))
709        });
710        Ok(sessions)
711    }
712
713    /// The raw working-context index fact for `project`, `None` when nothing
714    /// was ever saved under it. Symmetric squatter guard to
715    /// [`Self::load_working_context`]: a slot occupied without the reserved
716    /// [`CTX_WORKING_INDEX_FIELD`] marker is treated as empty, never as a
717    /// forged index.
718    fn working_index(&self, project: &str) -> Result<Option<WorkingContextIndex>, MemoryError> {
719        let slot = working_index_id(project);
720        let payloads = self.store.get_metadata_batch(&[slot])?;
721        let marked = payloads
722            .into_iter()
723            .next()
724            .flatten()
725            .is_some_and(|meta| meta.get(CTX_WORKING_INDEX_FIELD) == Some(&Value::Bool(true)));
726        if !marked {
727            return Ok(None);
728        }
729        match self.store.get(slot)? {
730            Some((content, _)) => serde_json::from_str(&content)
731                .map(Some)
732                .map_err(|err| MemoryError::WorkingContextCodec(err.to_string())),
733            None => Ok(None),
734        }
735    }
736
737    /// Append (or refresh) `session`'s entry in `project`'s working-context
738    /// index — called by every [`Self::save_working_context`], so the index
739    /// is always current without a separate maintenance step. A resave of
740    /// the same project+session updates `saved_at` in place rather than
741    /// duplicating the entry.
742    fn update_working_index(&self, project: &str, session: &str) -> Result<(), MemoryError> {
743        let mut index = self.working_index(project)?.unwrap_or_default();
744        let now = now_unix_secs();
745        if let Some(entry) = index.sessions.iter_mut().find(|s| s.session == session) {
746            entry.saved_at = now;
747        } else {
748            index.sessions.push(WorkingContextSession {
749                session: session.to_owned(),
750                saved_at: now,
751            });
752        }
753        let content = serde_json::to_string(&index)
754            .map_err(|err| MemoryError::WorkingContextCodec(err.to_string()))?;
755        let slot = working_index_id(project);
756        let embedding = self
757            .embedder
758            .embed(&format!("working context index {project}"))?;
759        let meta = system_meta(&[
760            (CTX_WORKING_INDEX_FIELD, Value::Bool(true)),
761            (CTX_PROJECT_FIELD, Value::String(project.to_owned())),
762        ]);
763        self.store_fact(slot, &content, &embedding, Some(&meta), None)?;
764        Ok(())
765    }
766}
767
768/// How many memories a scope pulls when it does not say (`k` absent).
769const DEFAULT_MEMORY_K: usize = 5;
770
771/// The request's memory scope plus the clamped pull count — `None` when
772/// there is no scope or no room: pulled memories must never push the
773/// request over the fragment cap (the cap is validated after augmentation,
774/// and a rejection there would blame the caller for fragments the bridge
775/// itself added).
776fn scope_and_k(request: &CompileRequest) -> Option<(&MemoryScope, usize)> {
777    let scope = request.memory_scope.as_ref()?;
778    let room = crate::limits::MAX_FRAGMENTS.saturating_sub(request.fragments.len());
779    let k = crate::limits::clamp_recall_limit(scope.k.unwrap_or(DEFAULT_MEMORY_K)).min(room);
780    (k > 0).then_some((scope, k))
781}
782
783/// The recall filter a scope narrows to (its project facet), if any.
784fn scope_filter(scope: &MemoryScope) -> Option<Metadata> {
785    scope.project.as_ref().map(|project| {
786        let mut meta = Map::new();
787        meta.insert("project".to_owned(), Value::String(project.clone()));
788        meta
789    })
790}
791
792/// One memory the scope pulled in, with its full ranking ventilation.
793struct PulledMemory {
794    fragment: ContextFragment,
795    memory_id: u64,
796    /// Fused score normalised over the pulled batch, in `[0, 1]` — the
797    /// importance-blended key (clamped) when the blend is active.
798    relevance: f32,
799    /// Normalised vector term of the fused score.
800    vector_norm: f64,
801    /// Graph promotion weight of the fused score.
802    graph_weight: f64,
803    /// Learned RL confidence the blend used (neutral `0.5` when the memory
804    /// never received feedback).
805    confidence: f64,
806    /// Batch-relative recency contribution in `[0, 1]` (`0` when the term
807    /// is inactive, the key is absent, or the batch is degenerate).
808    recency: f64,
809    /// Whether the importance blend ran — drives the extended four-signal
810    /// reason ventilation; `false` keeps the exact 0.8.0 reason bytes.
811    ventilated: bool,
812}
813
814/// A selected memory before the importance blend: its similarity base, its
815/// fused ventilation, and the caller-visible metadata the recency term reads.
816struct MemoryCandidate {
817    memory_id: u64,
818    /// Fused-normalised (or rank-based) similarity in `[0, 1]`.
819    base: f64,
820    vector_norm: f64,
821    graph_weight: f64,
822    metadata: Option<Metadata>,
823    content: String,
824}
825
826impl MemoryCandidate {
827    /// The unblended [`PulledMemory`] — bytes identical to the 0.8.0 pull.
828    fn into_pulled(self) -> PulledMemory {
829        #[allow(clippy::cast_possible_truncation)] // base is clamped into [0, 1]
830        let relevance = self.base as f32;
831        PulledMemory {
832            fragment: ContextFragment {
833                id: None,
834                content: self.content,
835                kind: Some("memory".to_owned()),
836                priority: None,
837                metadata: None,
838                media: None,
839            },
840            memory_id: self.memory_id,
841            relevance,
842            vector_norm: self.vector_norm,
843            graph_weight: self.graph_weight,
844            confidence: NEUTRAL_CONFIDENCE,
845            recency: 0.0,
846            ventilated: false,
847        }
848    }
849}
850
851/// The neutral confidence of a memory with no feedback history — mirrors
852/// `reinforce::RL_NEUTRAL_CONFIDENCE`, whose module is `persistence`-gated:
853/// its contribution to the blend is exactly `0`.
854const NEUTRAL_CONFIDENCE: f64 = 0.5;
855
856/// The learned RL confidence off a raw payload, in `[0, 1]`. Without the
857/// `persistence` feature the RL module (and thus `feedback`) does not exist,
858/// so every memory reads neutral.
859#[cfg(feature = "persistence")]
860fn payload_confidence(payload: Option<&Metadata>) -> f64 {
861    f64::from(payload.map_or(
862        super::reinforce::RL_NEUTRAL_CONFIDENCE,
863        super::reinforce::read_confidence,
864    ))
865}
866
867/// See the `persistence` twin: no RL module, always neutral.
868#[cfg(not(feature = "persistence"))]
869fn payload_confidence(_payload: Option<&Metadata>) -> f64 {
870    NEUTRAL_CONFIDENCE
871}
872
873/// Whether the policy's importance weights change anything at all: a
874/// non-zero confidence weight, or a non-zero recency weight WITH a field to
875/// read. Zero weights must cost nothing and change nothing (0.8.0 parity).
876#[allow(
877    clippy::float_cmp,
878    reason = "an exact zero weight is the documented off switch; any non-zero weight, however small, is active"
879)]
880fn importance_active(weights: &ImportanceWeights) -> bool {
881    weights.confidence != 0.0 || (weights.recency != 0.0 && weights.recency_field.is_some())
882}
883
884/// The batch-relative recency contribution of every candidate, in `[0, 1]`:
885/// min-max over the candidates that carry the policy's `recency_field` as a
886/// number (one monotone scale per batch — `YYYYMMDD` or an epoch, the
887/// caller's choice). A candidate without the key contributes `0` (never
888/// penalised), and a degenerate batch (`max == min`) contributes `0` for
889/// all. No clock: recency is relative to the newest of the batch.
890#[allow(
891    clippy::float_cmp,
892    reason = "an exact zero weight is the documented off switch for the recency term"
893)]
894fn recency_norms(candidates: &[MemoryCandidate], weights: &ImportanceWeights) -> Vec<f64> {
895    let field = weights
896        .recency_field
897        .as_ref()
898        .filter(|_| weights.recency != 0.0);
899    let Some(field) = field else {
900        return vec![0.0; candidates.len()];
901    };
902    let values: Vec<Option<f64>> = candidates
903        .iter()
904        .map(|candidate| {
905            candidate
906                .metadata
907                .as_ref()
908                .and_then(|meta| meta.get(field.as_str()))
909                .and_then(Value::as_f64)
910                .filter(|value| value.is_finite())
911        })
912        .collect();
913    let (min, max) = values
914        .iter()
915        .flatten()
916        .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &v| {
917            (lo.min(v), hi.max(v))
918        });
919    if max <= min {
920        return vec![0.0; candidates.len()];
921    }
922    values
923        .into_iter()
924        .map(|value| value.map_or(0.0, |v| ((v - min) / (max - min)).clamp(0.0, 1.0)))
925        .collect()
926}
927
928/// Stamp pulled memories into the compiled provenance: their decisions and
929/// sources gain the backing `memory_id`, the decision's relevance becomes
930/// the normalised (importance-blended, when active) ranking score, and the
931/// reason spells out the full score ventilation — vector and graph always,
932/// plus confidence and recency when the blend ran — so `why this memory` is
933/// answerable from the decision alone.
934fn annotate_memory_provenance(out: &mut CompiledContext, pulled: &BTreeMap<u64, PulledMemory>) {
935    for decision in &mut out.decisions {
936        if let Some(memory) = pulled.get(&decision.content_hash) {
937            decision.memory_id = Some(memory.memory_id);
938            decision.relevance = memory.relevance;
939            decision.reason = if memory.ventilated {
940                format!(
941                    "{} — pulled from memory {} (vector {:.2}, graph {:.2}, confidence {:.2}, recency {:.2})",
942                    decision.reason,
943                    memory.memory_id,
944                    memory.vector_norm,
945                    memory.graph_weight,
946                    memory.confidence,
947                    memory.recency
948                )
949            } else {
950                format!(
951                    "{} — pulled from memory {} (vector {:.2}, graph {:.2})",
952                    decision.reason, memory.memory_id, memory.vector_norm, memory.graph_weight
953                )
954            };
955        }
956    }
957    for source in &mut out.sources {
958        if let Some(hash) = provenance::parse_handle(&source.handle) {
959            if let Some(memory) = pulled.get(&hash) {
960                source.memory_id = Some(memory.memory_id);
961            }
962        }
963    }
964}
965
966/// Base metadata of every bridge-stored system fact: hub-marked (invisible
967/// to normal recall) plus the given extra keys.
968fn system_meta(extra: &[(&str, Value)]) -> Metadata {
969    let mut meta = Map::new();
970    meta.insert(HUB_FIELD.to_owned(), Value::Bool(true));
971    for (key, value) in extra {
972        meta.insert((*key).to_owned(), value.clone());
973    }
974    meta
975}
976
977/// The metadata of one compilation event — counts and identifiers only,
978/// every key reserved.
979fn event_meta(request: &CompileRequest, out: &CompiledContext, nanos: u128) -> Metadata {
980    let mut extra: Vec<(&str, Value)> = vec![
981        (CTX_EVENT_FIELD, Value::Bool(true)),
982        (
983            CTX_TOKENS_IN_FIELD,
984            Value::Number(out.insights.tokens_in.into()),
985        ),
986        (
987            CTX_TOKENS_OUT_FIELD,
988            Value::Number(out.insights.tokens_out.into()),
989        ),
990        (
991            CTX_TOKENS_SAVED_FIELD,
992            Value::Number(out.insights.tokens_saved.into()),
993        ),
994        (
995            CTX_AT_FIELD,
996            Value::Number(Number::from(
997                u64::try_from(nanos / 1_000_000_000).unwrap_or(u64::MAX),
998            )),
999        ),
1000    ];
1001    if let Some(project) = &request.project {
1002        extra.push((CTX_PROJECT_FIELD, Value::String(project.clone())));
1003    }
1004    if let Some(model) = &request.target_model {
1005        extra.push((CTX_MODEL_FIELD, Value::String(model.clone())));
1006    }
1007    if let (Some(micros), Some(currency)) = (
1008        out.insights.estimated_cost_saved_micros,
1009        out.insights.currency.as_ref(),
1010    ) {
1011        extra.push((CTX_COST_FIELD, Value::Number(micros.into())));
1012        extra.push((CTX_CURRENCY_FIELD, Value::String(currency.clone())));
1013    }
1014    system_meta(&extra)
1015}
1016
1017/// Fold raw event payloads (reserved keys included) into one
1018/// [`ContextSavings`]. Every accumulation saturates — an aggregate must
1019/// never panic, whatever the stored numbers.
1020fn aggregate_events(payloads: &[Option<Metadata>]) -> ContextSavings {
1021    let mut savings = ContextSavings {
1022        events: payloads.len() as u64,
1023        truncated: payloads.len() >= crate::limits::MAX_RECALL_LIMIT,
1024        ..ContextSavings::default()
1025    };
1026    for payload in payloads {
1027        let Some(meta) = payload else { continue };
1028        savings.tokens_in = savings
1029            .tokens_in
1030            .saturating_add(meta_u64(meta, CTX_TOKENS_IN_FIELD));
1031        savings.tokens_out = savings
1032            .tokens_out
1033            .saturating_add(meta_u64(meta, CTX_TOKENS_OUT_FIELD));
1034        savings.tokens_saved = savings
1035            .tokens_saved
1036            .saturating_add(meta_u64(meta, CTX_TOKENS_SAVED_FIELD));
1037        if let (Some(Value::String(currency)), micros) =
1038            (meta.get(CTX_CURRENCY_FIELD), meta_u64(meta, CTX_COST_FIELD))
1039        {
1040            if micros > 0 {
1041                let entry = savings
1042                    .cost_saved_micros_by_currency
1043                    .entry(currency.clone())
1044                    .or_insert(0);
1045                *entry = entry.saturating_add(micros);
1046            }
1047        }
1048    }
1049    savings
1050}
1051
1052/// A `u64` metadata field, `0` when absent or non-numeric.
1053fn meta_u64(meta: &Metadata, key: &str) -> u64 {
1054    meta.get(key).and_then(Value::as_u64).unwrap_or(0)
1055}
1056
1057/// The salted system-fact id of a stored source.
1058fn source_id(content_hash: u64) -> u64 {
1059    stable_id(&format!("{SOURCE_ID_SALT}{content_hash}"))
1060}
1061
1062/// The handle-identity hash of one request fragment — the bridge-side twin
1063/// of `Analysis::handle_hash` in `context.rs` (kept in lockstep; the two
1064/// must key the same identity or stored slots and minted handles drift
1065/// apart): raw decoded media bytes for a media fragment, caption/content
1066/// [`stable_id`] otherwise.
1067fn fragment_handle_hash(fragment: &ContextFragment) -> u64 {
1068    fragment.media.as_ref().map_or_else(
1069        || stable_id(&fragment.content),
1070        |media_ref| media::analyze(media_ref).raw_hash,
1071    )
1072}
1073
1074/// A stored source's media payload (US-009, PR2), when its metadata carries
1075/// one — absent (or malformed, which should never happen for a payload this
1076/// bridge wrote itself) round-trips as `None` rather than an error, so a
1077/// media decode hiccup degrades to "text-only", never breaks the whole
1078/// retrieval.
1079fn source_media(meta: &Metadata) -> Option<MediaRef> {
1080    meta.get(CTX_SOURCE_MEDIA_FIELD)
1081        .cloned()
1082        .and_then(|value| serde_json::from_value(value).ok())
1083}
1084
1085/// The salted, deterministic system-fact id of a working context.
1086fn working_id(project: &str, session: &str) -> u64 {
1087    stable_id(&format!("{WORKING_ID_SALT}{project}\u{1f}{session}"))
1088}
1089
1090/// The salted, deterministic system-fact id of a project's working-context
1091/// index — one per project, so every save updates the same slot.
1092fn working_index_id(project: &str) -> u64 {
1093    stable_id(&format!("{WORKING_INDEX_ID_SALT}{project}"))
1094}
1095
1096#[cfg(all(test, feature = "persistence"))]
1097#[path = "memory_bridge_tests.rs"]
1098mod tests;