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    CompilePolicy, CompileRequest, CompiledContext, ContextDecision, ContextFragment,
67    ContextSavings, ContextSource, ImportanceWeights, MediaRef, MemoryScope, WorkingContext,
68    WorkingContextIndex, 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
131/// Serializes the read-modify-write of the per-project working-context index.
132///
133/// The index is ONE fact per project, rewritten wholesale on every
134/// `save_working_context`. Without this, two saves racing on the same project
135/// both read the same pre-state and the second write erases the first
136/// session's entry — a silent loss: the erased session's own fact is still on
137/// disk and still loadable by exact id, but `list_working_contexts` (and
138/// therefore `load_working_context`'s `other_sessions` recovery hint) no
139/// longer knows it exists, and nothing anywhere returns an error.
140///
141/// **Scope, honestly: this is an INTRA-PROCESS lock only.** Two processes
142/// opening the same store still race, because nothing below this layer offers
143/// a compare-and-swap. The durable fix is a CAS or a transaction on the
144/// [`MemoryStore`] trait itself; until then, the single-process case (the MCP
145/// server, whose `spawn_blocking` handlers are exactly what made this
146/// reachable) is covered and the multi-process case is not.
147///
148/// One global lock rather than one per project: index writes are rare (one
149/// per `save_working_context`), so the contention is negligible, whereas a
150/// `HashMap<String, _>` keyed by caller-supplied project names is an unbounded
151/// slow leak for no measurable gain. Per-project striping is the obvious
152/// upgrade if index writes ever become hot.
153static WORKING_INDEX_WRITE: std::sync::Mutex<()> = std::sync::Mutex::new(());
154
155impl<E: Embedder, S: MemoryStore> MemoryService<E, S> {
156    /// [`ContextCompiler::compile`] with this service's memory folded in:
157    /// when the request carries a [`MemoryScope`], relevant memories are
158    /// pulled through the fused vector+graph recall and compiled alongside
159    /// the caller's fragments, each with its `memory_id` and a normalised
160    /// fused-ranking relevance recorded in provenance. Afterwards (policy
161    /// permitting) the distinct originals are stored so every
162    /// `ctx://source/<hash>` handle round-trips, and a metadata-only
163    /// compilation event is recorded for [`Self::context_savings`].
164    ///
165    /// # Errors
166    /// Returns [`MemoryError`] if compilation itself fails (budget, caps),
167    /// or if recall, embedding, or storage fails.
168    pub fn compile_context(
169        &self,
170        compiler: &ContextCompiler,
171        request: &CompileRequest,
172    ) -> Result<CompiledContext, MemoryError> {
173        let importance = compiler.effective_policy(request).importance.clone();
174        let memories = self.context_memories(request, &importance)?;
175        self.compile_with_memories(compiler, request, memories)
176    }
177
178    /// [`Self::compile_context`] with a caller-supplied [`crate::Reranker`] driving
179    /// memory selection: the reranker receives the FULL fused candidate pool
180    /// (vector + graph, before the `k` cutoff) and its ordering decides
181    /// which `k` memories are compiled in — the seam for a semantic
182    /// cross-encoder or LLM judge a Rust embedder brings along. Not exposed
183    /// on the wire (a reranker is code, not JSON), and never a default: the
184    /// shipped [`crate::context::DeterministicReranker`] is *lexical*, and a
185    /// lexical second stage demotes exactly the zero-vocabulary-overlap
186    /// evidence the graph walk rescues (measured in the BDD suite) — bring
187    /// a semantic one.
188    ///
189    /// # Errors
190    /// Returns [`MemoryError`] if compilation, recall, the reranker itself,
191    /// or storage fails.
192    pub fn compile_context_reranked<R: crate::Reranker>(
193        &self,
194        compiler: &ContextCompiler,
195        request: &CompileRequest,
196        reranker: &R,
197    ) -> Result<CompiledContext, MemoryError> {
198        let importance = compiler.effective_policy(request).importance.clone();
199        let memories = self.context_memories_reranked(request, reranker, &importance)?;
200        self.compile_with_memories(compiler, request, memories)
201    }
202
203    /// The shared back half of every compile flavour: augment the request
204    /// with the pulled memories, compile, annotate provenance, persist
205    /// sources/events per policy.
206    fn compile_with_memories(
207        &self,
208        compiler: &ContextCompiler,
209        request: &CompileRequest,
210        memories: Vec<PulledMemory>,
211    ) -> Result<CompiledContext, MemoryError> {
212        let mut augmented = request.clone();
213        let mut pulled: BTreeMap<u64, PulledMemory> = BTreeMap::new();
214        for memory in memories {
215            augmented.fragments.push(memory.fragment.clone());
216            pulled.insert(stable_id(&memory.fragment.content), memory);
217        }
218        // `compile_raw`, not `compile`: annotating memory provenance below
219        // can rewrite a pulled fragment's `relevance`/`reason` (and thus
220        // whether it crosses the `warnings` threshold), so `decisions` must
221        // stay full until that has happened and `warnings` is recomputed —
222        // `slim_response` (if requested) is applied as the LAST step.
223        let mut out = compiler.compile_raw(&augmented)?;
224        annotate_memory_provenance(&mut out, &pulled);
225        out.warnings = crate::context::warnings_for(&out.decisions);
226        let policy = compiler.effective_policy(request);
227        if policy.store_sources {
228            self.store_context_sources(&augmented, &out, policy.source_ttl_seconds)?;
229        }
230        if policy.record_events {
231            self.record_context_event(request, &out, policy.event_ttl_seconds)?;
232        }
233        Ok(crate::context::apply_slim(out, policy))
234    }
235
236    /// The memories a request's scope pulls in, as compile fragments plus
237    /// their id and normalised fused relevance, importance-blended
238    /// ([`Self::blend_importance`]) when the policy's weights are active.
239    fn context_memories(
240        &self,
241        request: &CompileRequest,
242        importance: &ImportanceWeights,
243    ) -> Result<Vec<PulledMemory>, MemoryError> {
244        let Some((scope, k)) = scope_and_k(request) else {
245            return Ok(Vec::new());
246        };
247        let filter = scope_filter(scope);
248        // The scope's fusion knobs (clamped by from_knobs); absent ones fall
249        // back to the crate defaults — raising graph_boost lets a curated
250        // relate-chain out-rank lexically-noisy near-misses (see MemoryScope).
251        let opts = FusionOptions::from_knobs(scope.hops, scope.graph_boost, None);
252        let scored = self.recall_fused_scored(&request.query, k, filter.as_ref(), opts)?;
253        let max_fused = scored
254            .iter()
255            .map(|s| s.fused)
256            .fold(f64::MIN, f64::max)
257            .max(f64::EPSILON);
258        let candidates = scored
259            .into_iter()
260            .map(|scored| {
261                // Sanitise a non-finite fused score to 0 before normalising:
262                // `f32::clamp` returns NaN for a NaN input (it does not clamp),
263                // which would put a non-`[0, 1]` value — serialising as JSON
264                // `null` — into an output sold as deterministic and auditable.
265                let fused = if scored.fused.is_finite() {
266                    scored.fused
267                } else {
268                    0.0
269                };
270                MemoryCandidate {
271                    memory_id: scored.recollection.id,
272                    base: (fused / max_fused).clamp(0.0, 1.0),
273                    vector_norm: scored.vector_norm,
274                    graph_weight: scored.graph_weight,
275                    metadata: scored.recollection.metadata,
276                    content: scored.recollection.content,
277                }
278            })
279            .collect();
280        self.blend_importance(candidates, importance)
281    }
282
283    /// Memory selection driven by a caller-supplied reranker: the fused
284    /// candidate pool (at pool depth, vector + graph) is handed to the
285    /// reranker whole, its ordering is truncated to `k`, and relevance is
286    /// rank-based (the reranker defines the ranking; the fused ventilation
287    /// no longer describes it, so vector/graph read 0 in provenance). The
288    /// importance blend then composes with the seam: it re-ranks INSIDE the
289    /// reranker-selected pool, exactly as it does over the fused pool.
290    fn context_memories_reranked<R: crate::Reranker>(
291        &self,
292        request: &CompileRequest,
293        reranker: &R,
294        importance: &ImportanceWeights,
295    ) -> Result<Vec<PulledMemory>, MemoryError> {
296        let Some((scope, k)) = scope_and_k(request) else {
297            return Ok(Vec::new());
298        };
299        let filter = scope_filter(scope);
300        let opts = FusionOptions::from_knobs(scope.hops, scope.graph_boost, None);
301        let ranked =
302            self.recall_fused_reranked(&request.query, k, filter.as_ref(), opts, reranker)?;
303        let count = ranked.len().max(1);
304        let candidates = ranked
305            .into_iter()
306            .enumerate()
307            .map(|(rank, recollection)| {
308                // Computed in f32 exactly as 0.8.0 did, so inactive weights
309                // reproduce the historical relevance bytes.
310                #[allow(clippy::cast_precision_loss)] // rank/count are tiny
311                let relevance = 1.0 - (rank as f32 / count as f32);
312                MemoryCandidate {
313                    memory_id: recollection.id,
314                    base: f64::from(relevance),
315                    vector_norm: 0.0,
316                    graph_weight: 0.0,
317                    metadata: recollection.metadata,
318                    content: recollection.content,
319                }
320            })
321            .collect();
322        self.blend_importance(candidates, importance)
323    }
324
325    /// Fold usage-driven importance into an already-selected memory pool —
326    /// the one ranking the whole engine stack shares (US-002 of EPIC-P-071):
327    /// per candidate the key becomes `base + w_c·(confidence − 0.5)·2 +
328    /// w_r·recency_norm`, where `base` is the fused (or rank-based)
329    /// similarity in `[0, 1]`. Selection is untouched on purpose: confidence
330    /// is not relevance, so a reinforced-but-off-topic fact can never buy
331    /// its way into the pool here. Inactive weights take the zero-cost path
332    /// and reproduce the 0.8.0 output byte for byte (golden-pinned). The
333    /// stable sort keeps equal keys in selection order, and no clock is ever
334    /// read — recency is min-max normalised within the batch.
335    fn blend_importance(
336        &self,
337        candidates: Vec<MemoryCandidate>,
338        weights: &ImportanceWeights,
339    ) -> Result<Vec<PulledMemory>, MemoryError> {
340        if !importance_active(weights) {
341            return Ok(candidates
342                .into_iter()
343                .map(MemoryCandidate::into_pulled)
344                .collect());
345        }
346        let ids: Vec<u64> = candidates.iter().map(|c| c.memory_id).collect();
347        // Raw payloads (reserved keys included): the learned confidence
348        // lives under `_veles_rl_confidence`, which caller-facing metadata
349        // strips.
350        let raw = self.store.get_metadata_batch(&ids)?;
351        let recencies = recency_norms(&candidates, weights);
352        let mut blended: Vec<(f64, PulledMemory)> = candidates
353            .into_iter()
354            .zip(raw)
355            .zip(recencies)
356            .map(|((candidate, payload), recency)| {
357                let confidence = payload_confidence(payload.as_ref());
358                let score = candidate.base
359                    + weights.confidence * (confidence - NEUTRAL_CONFIDENCE) * 2.0
360                    + weights.recency * recency;
361                let mut pulled = candidate.into_pulled();
362                #[allow(clippy::cast_possible_truncation)] // clamped into [0, 1]
363                {
364                    pulled.relevance = score.clamp(0.0, 1.0) as f32;
365                }
366                pulled.confidence = confidence;
367                pulled.recency = recency;
368                pulled.ventilated = true;
369                (score, pulled)
370            })
371            .collect();
372        // Stable: equal blended keys keep the selection order.
373        blended.sort_by(|a, b| b.0.total_cmp(&a.0));
374        Ok(blended.into_iter().map(|(_, pulled)| pulled).collect())
375    }
376
377    /// Store every distinct fragment's original as a hub-marked system fact
378    /// keyed by its salted handle hash, so its handle can be resolved later.
379    /// A fragment carrying media (US-009, PR2) has its base64 payload
380    /// persisted alongside the caption under the reserved
381    /// [`CTX_SOURCE_MEDIA_FIELD`] key.
382    ///
383    /// **Identity**: the key mirrors what the compiler mints handles from
384    /// (`Analysis::handle_hash` in `context.rs`) — the caption's
385    /// [`stable_id`] for text, the raw decoded bytes' hash
386    /// ([`media::MediaAnalysis::raw_hash`]) for media, the same identity
387    /// PR1's dedup keys on. Keying media on the caption instead was the PR2
388    /// review's proven blocker: every captionless image collided onto one
389    /// slot and one handle, serving arbitrary wrong bytes back. The slot
390    /// stays inside the salted system-fact namespace ([`source_id`] applies
391    /// `SOURCE_ID_SALT` to the hash) — same salt, no new namespace. On a
392    /// same-key collision (byte-identical images with different captions)
393    /// the FIRST occurrence wins, matching the dedup twin the compiler
394    /// keeps — a divergent duplicate caption does not survive, exactly as
395    /// its decision reason already says.
396    ///
397    /// Size: [`crate::limits::MAX_MEDIA_BYTES`] /
398    /// [`crate::limits::MAX_TOTAL_MEDIA_BYTES`] already bounded every
399    /// fragment's `bytes_b64` before `compiler.compile` ever ran (see
400    /// `validate_media`, called from `compile`'s `validate`) — `augmented`
401    /// here is exactly the request that passed that check, so no separate
402    /// size guard is needed on the write path itself
403    /// ([`crate::limits::MAX_FACT_BYTES`] governs the unrelated MCP
404    /// `remember`/`extract` text ceiling, not this one).
405    fn store_context_sources(
406        &self,
407        augmented: &CompileRequest,
408        out: &CompiledContext,
409        ttl_seconds: Option<u64>,
410    ) -> Result<(), MemoryError> {
411        let mut by_hash: BTreeMap<u64, &ContextFragment> = BTreeMap::new();
412        for fragment in &augmented.fragments {
413            // First occurrence wins (see the identity note above): `entry`
414            // + `or_insert`, never a blind overwrite.
415            by_hash
416                .entry(fragment_handle_hash(fragment))
417                .or_insert(fragment);
418        }
419        let ttl_seconds = positive_ttl(ttl_seconds);
420        for source in &out.sources {
421            let Some(hash) = provenance::parse_handle(&source.handle) else {
422                continue;
423            };
424            let Some(fragment) = by_hash.get(&hash) else {
425                continue;
426            };
427            let slot = source_id(hash);
428            // A slot never marked as ours is never rewritten: it is a caller
429            // fact squatting the salt preimage, and clobbering it would
430            // destroy user data. A slot already marked as ours holds these
431            // exact bytes — sources are content-addressed — so content and
432            // embedding never change; only durability can, and only upward
433            // (never-downgrade TTL upgrade, `should_store_source`) so a
434            // handle sold as permanent never silently expires just because
435            // an earlier compile first wrote it under a TTL.
436            if !self.should_store_source(slot, ttl_seconds)? {
437                continue;
438            }
439            // Upgrading to permanent needs the old point gone, not merely
440            // overwritten: velesdb-core's store path preserves every
441            // `_veles_*` key from a prior version of a re-stored id unless
442            // the new write explicitly sets it (semantic_memory.rs's
443            // `store_internal` carry-forward, so plain `remember` doesn't
444            // silently wipe learned state), and a permanent write has no
445            // expiry to explicitly set (`attach_expiry` is a no-op without
446            // one) — so without this delete, `_veles_expires_at` would
447            // survive the "upgrade" untouched. A TTL-to-TTL extension needs
448            // no delete: its new expiry always overwrites the old one.
449            if ttl_seconds.is_none() && self.store.get(slot)?.is_some() {
450                self.store.delete(slot)?;
451            }
452            let content = fragment.content.as_str();
453            let mut extra: Vec<(&str, Value)> = vec![(CTX_SOURCE_FIELD, Value::Bool(true))];
454            let embedding = if let Some(media_ref) = &fragment.media {
455                extra.push((
456                    CTX_SOURCE_MEDIA_FIELD,
457                    serde_json::to_value(media_ref).unwrap_or(Value::Null),
458                ));
459                // Deterministic, derived from the DECODED bytes — never the
460                // text embedder over `content` (often blank) or over the
461                // base64 payload itself (opaque, not language). Correct
462                // because `retrieve_context_source` resolves a media source
463                // EXCLUSIVELY by its content-addressed hash/slot, never by
464                // vector search — this vector only needs to be well-formed
465                // and non-degenerate for the underlying index, never
466                // semantically meaningful. For a media fragment `hash` IS
467                // the raw-bytes hash (see `fragment_handle_hash`), so no
468                // re-decode is needed here.
469                self.media_placeholder_embedding(hash)
470            } else {
471                self.embedder.embed(content)?
472            };
473            self.store_fact(
474                slot,
475                content,
476                &embedding,
477                Some(&system_meta(&extra)),
478                ttl_seconds,
479            )?;
480        }
481        Ok(())
482    }
483
484    /// Whether [`Self::store_context_sources`] should (re-)write `slot` for
485    /// this compile's requested (already [`positive_ttl`]-normalized —
486    /// `None` means permanent) TTL.
487    ///
488    /// - Not marked as ours (absent, or a caller fact squatting the salt
489    ///   preimage): store only if the slot is genuinely empty.
490    /// - Marked as ours: never re-embed or change content (content-addressed);
491    ///   only [`Self::should_upgrade_ttl`] decides whether durability changes.
492    fn should_store_source(
493        &self,
494        slot: u64,
495        requested_ttl: Option<u64>,
496    ) -> Result<bool, MemoryError> {
497        match self.context_source_metadata(slot)? {
498            Some(existing) => Ok(Self::should_upgrade_ttl(&existing, requested_ttl)),
499            None => Ok(self.store.get(slot)?.is_none()),
500        }
501    }
502
503    /// Never-downgrade TTL upgrade rule for an already-stored source: permanent
504    /// once requested stays permanent, and a TTL only ever extends, never
505    /// shortens. The clock read here is fine — this is the storage/expiry
506    /// layer, not the clock-free `compile` pipeline.
507    fn should_upgrade_ttl(existing: &Metadata, requested_ttl: Option<u64>) -> bool {
508        let existing_expiry = existing.get(EXPIRES_AT_FIELD).and_then(Value::as_u64);
509        match (requested_ttl, existing_expiry) {
510            // Permanent requested, slot still carries a TTL: upgrade.
511            (None, Some(_)) => true,
512            // Already permanent, or a TTL requested against a permanent slot:
513            // never downgrade.
514            (None | Some(_), None) => false,
515            // Both carry a TTL: extend only if the new one outlives what
516            // remains — never shorten.
517            (Some(ttl), Some(existing_exp)) => now_unix_secs().saturating_add(ttl) > existing_exp,
518        }
519    }
520
521    /// A deterministic, non-degenerate embedding for a media source (US-009,
522    /// PR2) — see [`Self::store_context_sources`] for why it is bytes-hash
523    /// derived rather than text-embedded.
524    fn media_placeholder_embedding(&self, raw_hash: u64) -> Vec<f32> {
525        let dim = self.embedder.dimension();
526        let mut vector = vec![0.0_f32; dim];
527        let Ok(dim_u64) = u64::try_from(dim) else {
528            return vector;
529        };
530        if dim_u64 == 0 {
531            return vector;
532        }
533        let bucket = usize::try_from(raw_hash % dim_u64).unwrap_or(0);
534        vector[bucket] = 1.0;
535        velesdb_core::simd_native::normalize_inplace_native(&mut vector);
536        vector
537    }
538
539    /// The fact at `slot`'s metadata, when it carries the stored-source
540    /// marker (`None` otherwise — absent, or a caller fact squatting the
541    /// slot).
542    fn context_source_metadata(&self, slot: u64) -> Result<Option<Metadata>, MemoryError> {
543        let payloads = self.store.get_metadata_batch(&[slot])?;
544        Ok(payloads
545            .into_iter()
546            .next()
547            .flatten()
548            .filter(|meta| meta.get(CTX_SOURCE_FIELD) == Some(&Value::Bool(true))))
549    }
550
551    /// The original content — and media, when the fragment carried one —
552    /// behind a `ctx://source/<hash>` handle.
553    ///
554    /// # Errors
555    /// Returns [`MemoryError::UnknownHandle`] when the handle is malformed
556    /// or nothing is stored under it (never stored, expired, or forgotten).
557    pub fn retrieve_context_source(&self, handle: &str) -> Result<ContextSource, MemoryError> {
558        let unknown = || MemoryError::UnknownHandle(handle.to_owned());
559        let hash = provenance::parse_handle(handle).ok_or_else(unknown)?;
560        let slot = source_id(hash);
561        // Only marker-bearing facts are sources: a caller fact squatting the
562        // salted slot is never served back as compiled provenance.
563        let meta = self.context_source_metadata(slot)?.ok_or_else(unknown)?;
564        let content = self
565            .store
566            .get(slot)?
567            .map(|(content, _embedding)| content)
568            .ok_or_else(unknown)?;
569        Ok(ContextSource {
570            content,
571            media: source_media(&meta),
572        })
573    }
574
575    /// Explain why one fragment of `request` was preserved, abstracted,
576    /// externalized, dropped, or cached — the selection primitive the MCP
577    /// `explain_compilation` tool delegates to, extracted here so every
578    /// adapter (MCP, Node, Python) shares one implementation instead of
579    /// reimplementing it. Compilation is deterministic, so `request` is
580    /// simply re-compiled — with event/source recording forced off, since an
581    /// explanation must not have side effects — and the matching decision is
582    /// returned.
583    ///
584    /// `fragment_index` (0-based position in `request.fragments`), when
585    /// given, TAKES PRIORITY over `fragment_id` for locating the decision:
586    /// `compile_context` records exactly one decision per input fragment, in
587    /// order, so `decisions[fragment_index]` is unambiguous even when
588    /// several fragments are byte-identical and therefore share the same
589    /// content-addressed `fragment_id` — a plain `fragment_id` lookup always
590    /// resolves to the FIRST such decision (the deduplication survivor's),
591    /// never a dropped twin's.
592    ///
593    /// Caveat inherited from re-compiling rather than replaying stored
594    /// state: with a `memory_scope` the re-compile recalls from CURRENT
595    /// memory, so the decision reflects memory as it is now, not as it was
596    /// at the original `compile_context` call; a caller that already
597    /// resolved a `path` fragment to `content` is unaffected (this method
598    /// does no I/O of its own).
599    ///
600    /// # Errors
601    /// Returns [`MemoryError::FragmentIndexOutOfBounds`] when `fragment_index`
602    /// is beyond `request.fragments`, [`MemoryError::FragmentNotFound`] when
603    /// no decision matches the selector, or any error [`Self::compile_context`]
604    /// itself can return (budget, caps, recall, embedding, storage).
605    pub fn explain_compilation(
606        &self,
607        request: &CompileRequest,
608        fragment_id: u64,
609        fragment_index: Option<usize>,
610    ) -> Result<ContextDecision, MemoryError> {
611        if let Some(index) = fragment_index {
612            let len = request.fragments.len();
613            if index >= len {
614                return Err(MemoryError::FragmentIndexOutOfBounds { index, len });
615            }
616        }
617        let mut request = request.clone();
618        let mut policy = request.policy.take().unwrap_or_default();
619        policy.record_events = false;
620        policy.store_sources = false;
621        request.policy = Some(policy);
622        let compiled =
623            self.compile_context(&ContextCompiler::new(CompilePolicy::default()), &request)?;
624        let decision = if let Some(index) = fragment_index {
625            compiled.decisions.into_iter().nth(index)
626        } else {
627            compiled
628                .decisions
629                .into_iter()
630                .find(|decision| decision.fragment_id == fragment_id)
631        };
632        decision.ok_or(MemoryError::FragmentNotFound(fragment_id))
633    }
634
635    /// Record one compilation's savings as a metadata-only system fact
636    /// (hashes and token counts — never fragment content). Wall-clock time
637    /// is stamped here, outside the deterministic compile pipeline.
638    fn record_context_event(
639        &self,
640        request: &CompileRequest,
641        out: &CompiledContext,
642        ttl_seconds: Option<u64>,
643    ) -> Result<(), MemoryError> {
644        let occurred_at_nanos = now_nanos();
645        // The per-process sequence keeps ids unique even when two compiles
646        // land on the same (possibly coarse) clock tick.
647        let seq = EVENT_SEQ.fetch_add(1, Ordering::Relaxed);
648        let content = format!("{EVENT_ANCHOR} {occurred_at_nanos}-{seq}");
649        let id = stable_id(&format!("{EVENT_ID_SALT}{occurred_at_nanos}:{seq}"));
650        let embedding = self.embedder.embed(&content)?;
651        let meta = event_meta(request, out, occurred_at_nanos);
652        self.store_fact(
653            id,
654            &content,
655            &embedding,
656            Some(&meta),
657            positive_ttl(ttl_seconds),
658        )?;
659        Ok(())
660    }
661
662    /// Aggregate the recorded compilation events, optionally per project.
663    /// Sweeps at most [`crate::limits::MAX_RECALL_LIMIT`] events (newest
664    /// need not be first — the sweep is similarity-ordered over a constant
665    /// anchor, i.e. effectively the whole family until the cap);
666    /// [`ContextSavings::truncated`] reports when the cap was hit.
667    ///
668    /// # Errors
669    /// Returns [`MemoryError`] if the underlying filtered recall fails.
670    pub fn context_savings(&self, project: Option<&str>) -> Result<ContextSavings, MemoryError> {
671        // Filter at the STORAGE layer on the reserved event marker: callers
672        // can neither set nor query `_veles_*` keys, so only genuine bridge
673        // events can ever match — a caller fact posing as an event counts
674        // for nothing.
675        let mut filter = Map::new();
676        filter.insert(CTX_EVENT_FIELD.to_owned(), Value::Bool(true));
677        if let Some(project) = project {
678            filter.insert(
679                CTX_PROJECT_FIELD.to_owned(),
680                Value::String(project.to_owned()),
681            );
682        }
683        let embedding = self.embedder.embed(EVENT_ANCHOR)?;
684        let hits =
685            self.store
686                .query_filtered(&embedding, crate::limits::MAX_RECALL_LIMIT, &filter, 0)?;
687        let ids: Vec<u64> = hits.iter().map(|(id, _, _)| *id).collect();
688        let payloads = self.store.get_metadata_batch(&ids)?;
689        Ok(aggregate_events(&payloads))
690    }
691
692    /// Persist `working` under `project` + `session` (idempotent upsert:
693    /// saving again replaces the previous state). Returns the system fact id.
694    ///
695    /// Serialized size is capped at [`crate::limits::MAX_FACT_BYTES`] (1
696    /// MiB) — the same ceiling every other stored fact honors — checked
697    /// BEFORE anything is written, so an oversized working context is never
698    /// partially stored.
699    ///
700    /// # Errors
701    /// Returns [`MemoryError::WorkingContextCodec`] if serialization fails,
702    /// [`MemoryError::ContextOverLimit`] if the serialized `working` exceeds
703    /// [`crate::limits::MAX_FACT_BYTES`], or a storage/embedding error.
704    pub fn save_working_context(
705        &self,
706        project: &str,
707        session: &str,
708        working: &WorkingContext,
709    ) -> Result<u64, MemoryError> {
710        let content = serde_json::to_string(working)
711            .map_err(|err| MemoryError::WorkingContextCodec(err.to_string()))?;
712        if content.len() > crate::limits::MAX_FACT_BYTES {
713            return Err(MemoryError::ContextOverLimit(format!(
714                "working context of {} bytes exceeds the cap of {} bytes",
715                content.len(),
716                crate::limits::MAX_FACT_BYTES
717            )));
718        }
719        let id = working_id(project, session);
720        let embedding = self
721            .embedder
722            .embed(&format!("working context {project} {session}"))?;
723        let meta = system_meta(&[
724            (CTX_WORKING_FIELD, Value::Bool(true)),
725            (CTX_PROJECT_FIELD, Value::String(project.to_owned())),
726            (CTX_SESSION_FIELD, Value::String(session.to_owned())),
727        ]);
728        self.store_fact(id, &content, &embedding, Some(&meta), None)?;
729        self.update_working_index(project, session)?;
730        Ok(id)
731    }
732
733    /// The working context previously saved under `project` + `session`,
734    /// `None` when there is none.
735    ///
736    /// Symmetric to [`Self::context_source_metadata`]'s squatter guard: the
737    /// slot is only ever served back when its metadata carries the reserved
738    /// [`CTX_WORKING_FIELD`] marker (set exclusively by
739    /// [`Self::save_working_context`]). A slot occupied by an unmarked caller
740    /// fact — one that happened to land on this salted id, or a forged
741    /// probe — is indistinguishable from "nothing saved" on purpose: `None`,
742    /// never the forged content, and never an error (the caller cannot tell
743    /// a squatted slot from a genuinely empty one, which is the point — it
744    /// must never learn that *something* occupies this id).
745    ///
746    /// A pure read: it never writes, never prunes, never heals. Index
747    /// convergence happens on the WRITE path
748    /// ([`Self::update_working_index`]) — a lookup that rewrites shared state
749    /// turns every transient miss into permanent data loss and cannot safely
750    /// be retried.
751    ///
752    /// # Errors
753    /// Returns [`MemoryError::WorkingContextCodec`] if the stored payload
754    /// does not parse, or if the slot is marked but its body is gone (a torn
755    /// fact is corruption — reporting it as "nothing saved" would tell the
756    /// caller the one thing that is certainly false), or a storage error.
757    pub fn load_working_context(
758        &self,
759        project: &str,
760        session: &str,
761    ) -> Result<Option<WorkingContext>, MemoryError> {
762        let slot = working_id(project, session);
763        let payloads = self.store.get_metadata_batch(&[slot])?;
764        let marked = payloads
765            .into_iter()
766            .next()
767            .flatten()
768            .is_some_and(|meta| meta.get(CTX_WORKING_FIELD) == Some(&Value::Bool(true)));
769        if !marked {
770            // The squatter/never-saved guard documented above: silent by
771            // design, and the branch a `forget` lands on (deleting a fact
772            // removes its metadata with it).
773            return Ok(None);
774        }
775        let Some((content, _)) = self.store.get(slot)? else {
776            return Err(MemoryError::WorkingContextCodec(format!(
777                "working context for project '{project}', session '{session}' is corrupt: \
778                 the reserved marker is present but the stored body is gone"
779            )));
780        };
781        serde_json::from_str(&content)
782            .map(Some)
783            .map_err(|err| MemoryError::WorkingContextCodec(err.to_string()))
784    }
785
786    /// The sessions of `sessions` whose working-context fact is still there,
787    /// in the same order. One batched metadata lookup for the whole set — not
788    /// a store scan, but not free either (see
789    /// [`Self::list_working_contexts`]'s cost note).
790    ///
791    /// Shared by the read path (filter, persist nothing) and the write path
792    /// (filter, and persist the result), so both agree on what "alive" means.
793    fn live_sessions(
794        &self,
795        project: &str,
796        sessions: Vec<WorkingContextSession>,
797    ) -> Result<Vec<WorkingContextSession>, MemoryError> {
798        if sessions.is_empty() {
799            return Ok(sessions);
800        }
801        let ids: Vec<u64> = sessions
802            .iter()
803            .map(|entry| working_id(project, &entry.session))
804            .collect();
805        let payloads = self.store.get_metadata_batch(&ids)?;
806        if payloads.len() != ids.len() {
807            // The trait promises one result per id. A backend that breaks
808            // that promise must not be silently read as "these sessions are
809            // dead" — that would delete real entries on the write path.
810            return Err(MemoryError::WorkingContextCodec(format!(
811                "storage returned {} metadata rows for {} working-context ids",
812                payloads.len(),
813                ids.len()
814            )));
815        }
816        Ok(sessions
817            .into_iter()
818            .zip(payloads)
819            .filter(|(_, meta)| {
820                meta.as_ref()
821                    .is_some_and(|meta| meta.get(CTX_WORKING_FIELD) == Some(&Value::Bool(true)))
822            })
823            .map(|(entry, _)| entry)
824            .collect())
825    }
826
827    /// Every session still resumable under `project`'s working-context index
828    /// (V2a-1 quick win), most-recently-saved first. Empty when the project
829    /// never saved anything — that, and only that, is the empty case.
830    ///
831    /// Cost: one O(1) index read plus ONE batched metadata lookup of the
832    /// listed ids — never a store scan, but no longer a single read either.
833    /// The lookup is what drops sessions whose fact was forgotten since;
834    /// unlike the previous read-path prune it persists nothing, so a listing
835    /// can be retried and a transient miss costs nothing durable.
836    ///
837    /// # Errors
838    /// Returns a storage error if the index fact cannot be read, or
839    /// [`MemoryError::WorkingContextCodec`] if it does not parse or is
840    /// corrupt (marked, but with no body).
841    pub fn list_working_contexts(
842        &self,
843        project: &str,
844    ) -> Result<Vec<WorkingContextSession>, MemoryError> {
845        let Some(index) = self.working_index(project)? else {
846            // The genuine "this project never saved anything" case — the only
847            // one that reaches here now that a corrupt index is an `Err`.
848            return Ok(Vec::new());
849        };
850        let mut sessions = self.live_sessions(project, index.sessions)?;
851        sessions.sort_by(|a, b| {
852            b.saved_at
853                .cmp(&a.saved_at)
854                .then_with(|| a.session.cmp(&b.session))
855        });
856        Ok(sessions)
857    }
858
859    /// The raw working-context index fact for `project`, `None` when nothing
860    /// was ever saved under it. Symmetric squatter guard to
861    /// [`Self::load_working_context`]: a slot occupied without the reserved
862    /// [`CTX_WORKING_INDEX_FIELD`] marker is treated as empty, never as a
863    /// forged index.
864    ///
865    /// `None` means "absent". "Corrupt" is an `Err` — collapsing the two
866    /// would report a store that lost the index body as a project that never
867    /// saved anything, and an agent told that starts over instead of raising
868    /// a problem a human could fix.
869    fn working_index(&self, project: &str) -> Result<Option<WorkingContextIndex>, MemoryError> {
870        let slot = working_index_id(project);
871        let payloads = self.store.get_metadata_batch(&[slot])?;
872        let marked = payloads
873            .into_iter()
874            .next()
875            .flatten()
876            .is_some_and(|meta| meta.get(CTX_WORKING_INDEX_FIELD) == Some(&Value::Bool(true)));
877        if !marked {
878            return Ok(None);
879        }
880        match self.store.get(slot)? {
881            Some((content, _)) => serde_json::from_str(&content)
882                .map(Some)
883                .map_err(|err| MemoryError::WorkingContextCodec(err.to_string())),
884            None => Err(MemoryError::WorkingContextCodec(format!(
885                "working-context index for project '{project}' is corrupt: the index \
886                 marker is present but the stored body is gone"
887            ))),
888        }
889    }
890
891    /// Append (or refresh) `session`'s entry in `project`'s working-context
892    /// index — called by every [`Self::save_working_context`], so the index
893    /// is always current without a separate maintenance step. A resave of
894    /// the same project+session updates `saved_at` in place rather than
895    /// duplicating the entry.
896    ///
897    /// This is also where the index CONVERGES: entries whose working-context
898    /// fact was forgotten since are dropped here, on the write path, under
899    /// the same lock and in the same read-modify-write that was already
900    /// paid for. Reads never mutate it.
901    fn update_working_index(&self, project: &str, session: &str) -> Result<(), MemoryError> {
902        // Read-modify-write of a single shared fact: held for the whole
903        // sequence, otherwise a concurrent save silently erases this entry.
904        // The guarded data is `()`, so a poisoned lock carries no broken
905        // invariant — recover rather than propagate someone else's panic.
906        let _guard = WORKING_INDEX_WRITE
907            .lock()
908            .unwrap_or_else(std::sync::PoisonError::into_inner);
909        // A corrupt index must not brick saving for the whole project. The
910        // read path surfaces the error — that is where a human can act on it
911        // — but propagating it here would make every future save of every
912        // session under this project fail forever, with no way back: the
913        // only writer of the index is this function. Rebuild instead.
914        let mut index = match self.working_index(project) {
915            Ok(index) => index.unwrap_or_default(),
916            Err(MemoryError::WorkingContextCodec(_)) => WorkingContextIndex::default(),
917            Err(err) => return Err(err),
918        };
919        let now = now_unix_secs();
920        if let Some(entry) = index.sessions.iter_mut().find(|s| s.session == session) {
921            entry.saved_at = now;
922        } else {
923            index.sessions.push(WorkingContextSession {
924                session: session.to_owned(),
925                saved_at: now,
926            });
927        }
928        // The entry just appended is alive by construction (its fact was
929        // stored moments ago, before this call); this only sheds the ones a
930        // `forget` orphaned.
931        index.sessions = self.live_sessions(project, index.sessions)?;
932        let content = serde_json::to_string(&index)
933            .map_err(|err| MemoryError::WorkingContextCodec(err.to_string()))?;
934        self.write_working_index(project, &content)
935    }
936
937    /// Persist a serialized index into `project`'s reserved index slot —
938    /// always with the [`CTX_WORKING_INDEX_FIELD`] marker, since an index
939    /// written without it would be treated as a squatter and read back as
940    /// empty. Only [`Self::update_working_index`] (which holds
941    /// [`WORKING_INDEX_WRITE`]) calls this.
942    fn write_working_index(&self, project: &str, content: &str) -> Result<(), MemoryError> {
943        let slot = working_index_id(project);
944        let embedding = self
945            .embedder
946            .embed(&format!("working context index {project}"))?;
947        let meta = system_meta(&[
948            (CTX_WORKING_INDEX_FIELD, Value::Bool(true)),
949            (CTX_PROJECT_FIELD, Value::String(project.to_owned())),
950        ]);
951        self.store_fact(slot, content, &embedding, Some(&meta), None)?;
952        Ok(())
953    }
954}
955
956/// How many memories a scope pulls when it does not say (`k` absent).
957const DEFAULT_MEMORY_K: usize = 5;
958
959/// The request's memory scope plus the clamped pull count — `None` when
960/// there is no scope or no room: pulled memories must never push the
961/// request over the fragment cap (the cap is validated after augmentation,
962/// and a rejection there would blame the caller for fragments the bridge
963/// itself added).
964fn scope_and_k(request: &CompileRequest) -> Option<(&MemoryScope, usize)> {
965    let scope = request.memory_scope.as_ref()?;
966    let room = crate::limits::MAX_FRAGMENTS.saturating_sub(request.fragments.len());
967    let k = crate::limits::clamp_recall_limit(scope.k.unwrap_or(DEFAULT_MEMORY_K)).min(room);
968    (k > 0).then_some((scope, k))
969}
970
971/// The recall filter a scope narrows to (its project facet), if any.
972fn scope_filter(scope: &MemoryScope) -> Option<Metadata> {
973    scope.project.as_ref().map(|project| {
974        let mut meta = Map::new();
975        meta.insert("project".to_owned(), Value::String(project.clone()));
976        meta
977    })
978}
979
980/// One memory the scope pulled in, with its full ranking ventilation.
981struct PulledMemory {
982    fragment: ContextFragment,
983    memory_id: u64,
984    /// Fused score normalised over the pulled batch, in `[0, 1]` — the
985    /// importance-blended key (clamped) when the blend is active.
986    relevance: f32,
987    /// Normalised vector term of the fused score.
988    vector_norm: f64,
989    /// Graph promotion weight of the fused score.
990    graph_weight: f64,
991    /// Learned RL confidence the blend used (neutral `0.5` when the memory
992    /// never received feedback).
993    confidence: f64,
994    /// Batch-relative recency contribution in `[0, 1]` (`0` when the term
995    /// is inactive, the key is absent, or the batch is degenerate).
996    recency: f64,
997    /// Whether the importance blend ran — drives the extended four-signal
998    /// reason ventilation; `false` keeps the exact 0.8.0 reason bytes.
999    ventilated: bool,
1000}
1001
1002/// A selected memory before the importance blend: its similarity base, its
1003/// fused ventilation, and the caller-visible metadata the recency term reads.
1004struct MemoryCandidate {
1005    memory_id: u64,
1006    /// Fused-normalised (or rank-based) similarity in `[0, 1]`.
1007    base: f64,
1008    vector_norm: f64,
1009    graph_weight: f64,
1010    metadata: Option<Metadata>,
1011    content: String,
1012}
1013
1014impl MemoryCandidate {
1015    /// The unblended [`PulledMemory`] — bytes identical to the 0.8.0 pull.
1016    fn into_pulled(self) -> PulledMemory {
1017        #[allow(clippy::cast_possible_truncation)] // base is clamped into [0, 1]
1018        let relevance = self.base as f32;
1019        PulledMemory {
1020            fragment: ContextFragment {
1021                id: None,
1022                content: self.content,
1023                path: None,
1024                kind: Some("memory".to_owned()),
1025                priority: None,
1026                metadata: None,
1027                media: None,
1028            },
1029            memory_id: self.memory_id,
1030            relevance,
1031            vector_norm: self.vector_norm,
1032            graph_weight: self.graph_weight,
1033            confidence: NEUTRAL_CONFIDENCE,
1034            recency: 0.0,
1035            ventilated: false,
1036        }
1037    }
1038}
1039
1040/// The neutral confidence of a memory with no feedback history — mirrors
1041/// `reinforce::RL_NEUTRAL_CONFIDENCE`, whose module is `persistence`-gated:
1042/// its contribution to the blend is exactly `0`.
1043const NEUTRAL_CONFIDENCE: f64 = 0.5;
1044
1045/// The learned RL confidence off a raw payload, in `[0, 1]`. Without the
1046/// `persistence` feature the RL module (and thus `feedback`) does not exist,
1047/// so every memory reads neutral.
1048#[cfg(feature = "persistence")]
1049fn payload_confidence(payload: Option<&Metadata>) -> f64 {
1050    f64::from(payload.map_or(
1051        super::reinforce::RL_NEUTRAL_CONFIDENCE,
1052        super::reinforce::read_confidence,
1053    ))
1054}
1055
1056/// See the `persistence` twin: no RL module, always neutral.
1057#[cfg(not(feature = "persistence"))]
1058fn payload_confidence(_payload: Option<&Metadata>) -> f64 {
1059    NEUTRAL_CONFIDENCE
1060}
1061
1062/// Whether the policy's importance weights change anything at all: a
1063/// non-zero confidence weight, or a non-zero recency weight WITH a field to
1064/// read. Zero weights must cost nothing and change nothing (0.8.0 parity).
1065#[allow(
1066    clippy::float_cmp,
1067    reason = "an exact zero weight is the documented off switch; any non-zero weight, however small, is active"
1068)]
1069fn importance_active(weights: &ImportanceWeights) -> bool {
1070    weights.confidence != 0.0 || (weights.recency != 0.0 && weights.recency_field.is_some())
1071}
1072
1073/// The batch-relative recency contribution of every candidate, in `[0, 1]`:
1074/// min-max over the candidates that carry the policy's `recency_field` as a
1075/// number (one monotone scale per batch — `YYYYMMDD` or an epoch, the
1076/// caller's choice). A candidate without the key contributes `0` (never
1077/// penalised), and a degenerate batch (`max == min`) contributes `0` for
1078/// all. No clock: recency is relative to the newest of the batch.
1079#[allow(
1080    clippy::float_cmp,
1081    reason = "an exact zero weight is the documented off switch for the recency term"
1082)]
1083fn recency_norms(candidates: &[MemoryCandidate], weights: &ImportanceWeights) -> Vec<f64> {
1084    let field = weights
1085        .recency_field
1086        .as_ref()
1087        .filter(|_| weights.recency != 0.0);
1088    let Some(field) = field else {
1089        return vec![0.0; candidates.len()];
1090    };
1091    let values: Vec<Option<f64>> = candidates
1092        .iter()
1093        .map(|candidate| {
1094            candidate
1095                .metadata
1096                .as_ref()
1097                .and_then(|meta| meta.get(field.as_str()))
1098                .and_then(Value::as_f64)
1099                .filter(|value| value.is_finite())
1100        })
1101        .collect();
1102    let (min, max) = values
1103        .iter()
1104        .flatten()
1105        .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &v| {
1106            (lo.min(v), hi.max(v))
1107        });
1108    if max <= min {
1109        return vec![0.0; candidates.len()];
1110    }
1111    values
1112        .into_iter()
1113        .map(|value| value.map_or(0.0, |v| ((v - min) / (max - min)).clamp(0.0, 1.0)))
1114        .collect()
1115}
1116
1117/// Stamp pulled memories into the compiled provenance: their decisions and
1118/// sources gain the backing `memory_id`, the decision's relevance becomes
1119/// the normalised (importance-blended, when active) ranking score, and the
1120/// reason spells out the full score ventilation — vector and graph always,
1121/// plus confidence and recency when the blend ran — so `why this memory` is
1122/// answerable from the decision alone.
1123fn annotate_memory_provenance(out: &mut CompiledContext, pulled: &BTreeMap<u64, PulledMemory>) {
1124    for decision in &mut out.decisions {
1125        if let Some(memory) = pulled.get(&decision.content_hash) {
1126            decision.memory_id = Some(memory.memory_id);
1127            decision.relevance = memory.relevance;
1128            decision.reason = if memory.ventilated {
1129                format!(
1130                    "{} — pulled from memory {} (vector {:.2}, graph {:.2}, confidence {:.2}, recency {:.2})",
1131                    decision.reason,
1132                    memory.memory_id,
1133                    memory.vector_norm,
1134                    memory.graph_weight,
1135                    memory.confidence,
1136                    memory.recency
1137                )
1138            } else {
1139                format!(
1140                    "{} — pulled from memory {} (vector {:.2}, graph {:.2})",
1141                    decision.reason, memory.memory_id, memory.vector_norm, memory.graph_weight
1142                )
1143            };
1144        }
1145    }
1146    for source in &mut out.sources {
1147        if let Some(hash) = provenance::parse_handle(&source.handle) {
1148            if let Some(memory) = pulled.get(&hash) {
1149                source.memory_id = Some(memory.memory_id);
1150            }
1151        }
1152    }
1153}
1154
1155/// Base metadata of every bridge-stored system fact: hub-marked (invisible
1156/// to normal recall) plus the given extra keys.
1157fn system_meta(extra: &[(&str, Value)]) -> Metadata {
1158    let mut meta = Map::new();
1159    meta.insert(HUB_FIELD.to_owned(), Value::Bool(true));
1160    for (key, value) in extra {
1161        meta.insert((*key).to_owned(), value.clone());
1162    }
1163    meta
1164}
1165
1166/// The metadata of one compilation event — counts and identifiers only,
1167/// every key reserved.
1168fn event_meta(request: &CompileRequest, out: &CompiledContext, nanos: u128) -> Metadata {
1169    let mut extra: Vec<(&str, Value)> = vec![
1170        (CTX_EVENT_FIELD, Value::Bool(true)),
1171        (
1172            CTX_TOKENS_IN_FIELD,
1173            Value::Number(out.insights.tokens_in.into()),
1174        ),
1175        (
1176            CTX_TOKENS_OUT_FIELD,
1177            Value::Number(out.insights.tokens_out.into()),
1178        ),
1179        (
1180            CTX_TOKENS_SAVED_FIELD,
1181            Value::Number(out.insights.tokens_saved.into()),
1182        ),
1183        (
1184            CTX_AT_FIELD,
1185            Value::Number(Number::from(
1186                u64::try_from(nanos / 1_000_000_000).unwrap_or(u64::MAX),
1187            )),
1188        ),
1189    ];
1190    if let Some(project) = &request.project {
1191        extra.push((CTX_PROJECT_FIELD, Value::String(project.clone())));
1192    }
1193    if let Some(model) = &request.target_model {
1194        extra.push((CTX_MODEL_FIELD, Value::String(model.clone())));
1195    }
1196    if let (Some(micros), Some(currency)) = (
1197        out.insights.estimated_cost_saved_micros,
1198        out.insights.currency.as_ref(),
1199    ) {
1200        extra.push((CTX_COST_FIELD, Value::Number(micros.into())));
1201        extra.push((CTX_CURRENCY_FIELD, Value::String(currency.clone())));
1202    }
1203    system_meta(&extra)
1204}
1205
1206/// Fold raw event payloads (reserved keys included) into one
1207/// [`ContextSavings`]. Every accumulation saturates — an aggregate must
1208/// never panic, whatever the stored numbers.
1209fn aggregate_events(payloads: &[Option<Metadata>]) -> ContextSavings {
1210    let mut savings = ContextSavings {
1211        events: payloads.len() as u64,
1212        truncated: payloads.len() >= crate::limits::MAX_RECALL_LIMIT,
1213        ..ContextSavings::default()
1214    };
1215    for payload in payloads {
1216        let Some(meta) = payload else { continue };
1217        savings.tokens_in = savings
1218            .tokens_in
1219            .saturating_add(meta_u64(meta, CTX_TOKENS_IN_FIELD));
1220        savings.tokens_out = savings
1221            .tokens_out
1222            .saturating_add(meta_u64(meta, CTX_TOKENS_OUT_FIELD));
1223        savings.tokens_saved = savings
1224            .tokens_saved
1225            .saturating_add(meta_u64(meta, CTX_TOKENS_SAVED_FIELD));
1226        if let (Some(Value::String(currency)), micros) =
1227            (meta.get(CTX_CURRENCY_FIELD), meta_u64(meta, CTX_COST_FIELD))
1228        {
1229            if micros > 0 {
1230                let entry = savings
1231                    .cost_saved_micros_by_currency
1232                    .entry(currency.clone())
1233                    .or_insert(0);
1234                *entry = entry.saturating_add(micros);
1235            }
1236        }
1237    }
1238    savings
1239}
1240
1241/// A `u64` metadata field, `0` when absent or non-numeric.
1242fn meta_u64(meta: &Metadata, key: &str) -> u64 {
1243    meta.get(key).and_then(Value::as_u64).unwrap_or(0)
1244}
1245
1246/// The salted system-fact id of a stored source.
1247fn source_id(content_hash: u64) -> u64 {
1248    stable_id(&format!("{SOURCE_ID_SALT}{content_hash}"))
1249}
1250
1251/// The handle-identity hash of one request fragment — the bridge-side twin
1252/// of `Analysis::handle_hash` in `context.rs` (kept in lockstep; the two
1253/// must key the same identity or stored slots and minted handles drift
1254/// apart): raw decoded media bytes for a media fragment, caption/content
1255/// [`stable_id`] otherwise.
1256fn fragment_handle_hash(fragment: &ContextFragment) -> u64 {
1257    fragment.media.as_ref().map_or_else(
1258        || stable_id(&fragment.content),
1259        |media_ref| media::analyze(media_ref).raw_hash,
1260    )
1261}
1262
1263/// A stored source's media payload (US-009, PR2), when its metadata carries
1264/// one — absent (or malformed, which should never happen for a payload this
1265/// bridge wrote itself) round-trips as `None` rather than an error, so a
1266/// media decode hiccup degrades to "text-only", never breaks the whole
1267/// retrieval.
1268fn source_media(meta: &Metadata) -> Option<MediaRef> {
1269    meta.get(CTX_SOURCE_MEDIA_FIELD)
1270        .cloned()
1271        .and_then(|value| serde_json::from_value(value).ok())
1272}
1273
1274/// The salted, deterministic system-fact id of a working context.
1275fn working_id(project: &str, session: &str) -> u64 {
1276    stable_id(&format!("{WORKING_ID_SALT}{project}\u{1f}{session}"))
1277}
1278
1279/// The salted, deterministic system-fact id of a project's working-context
1280/// index — one per project, so every save updates the same slot.
1281fn working_index_id(project: &str) -> u64 {
1282    stable_id(&format!("{WORKING_INDEX_ID_SALT}{project}"))
1283}
1284
1285#[cfg(all(test, feature = "persistence"))]
1286#[path = "memory_bridge_tests.rs"]
1287mod tests;