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 by_hash = index_fragments_by_handle_hash(&augmented.fragments);
412        let ttl_seconds = positive_ttl(ttl_seconds);
413        for source in &out.sources {
414            self.store_one_source(&source.handle, &by_hash, ttl_seconds)?;
415        }
416        Ok(())
417    }
418
419    /// Write the one slot behind `handle`, if this compile owns it.
420    ///
421    /// A handle whose fragment is no longer in the request (or that does not
422    /// parse) is skipped, not an error: `out.sources` is derived from the
423    /// same request, so a miss can only mean the source was externalized
424    /// under a shape this write path has nothing to store.
425    fn store_one_source(
426        &self,
427        handle: &str,
428        by_hash: &BTreeMap<u64, &ContextFragment>,
429        ttl_seconds: Option<u64>,
430    ) -> Result<(), MemoryError> {
431        let Some(hash) = provenance::parse_handle(handle) else {
432            return Ok(());
433        };
434        let Some(fragment) = by_hash.get(&hash) else {
435            return Ok(());
436        };
437        let slot = source_id(hash);
438        if !self.prepare_source_slot(slot, ttl_seconds)? {
439            return Ok(());
440        }
441        let (embedding, media_meta) = self.source_vector(fragment, hash)?;
442        let mut extra: Vec<(&str, Value)> = vec![(CTX_SOURCE_FIELD, Value::Bool(true))];
443        if let Some(media) = media_meta {
444            extra.push((CTX_SOURCE_MEDIA_FIELD, media));
445        }
446        self.store_fact(
447            slot,
448            fragment.content.as_str(),
449            &embedding,
450            Some(&system_meta(&extra)),
451            ttl_seconds,
452        )
453    }
454
455    /// Whether `slot` may be written for this compile, clearing a stale point
456    /// first when the write upgrades it to permanent.
457    ///
458    /// A slot never marked as ours is never rewritten: it is a caller fact
459    /// squatting the salt preimage, and clobbering it would destroy user
460    /// data. A slot already marked as ours holds these exact bytes — sources
461    /// are content-addressed — so content and embedding never change; only
462    /// durability can, and only upward (never-downgrade TTL upgrade, see
463    /// [`Self::should_store_source`]), so a handle sold as permanent never
464    /// silently expires just because an earlier compile first wrote it under
465    /// a TTL.
466    ///
467    /// Upgrading to permanent needs the old point *gone*, not merely
468    /// overwritten: velesdb-core's store path preserves every `_veles_*` key
469    /// from a prior version of a re-stored id unless the new write explicitly
470    /// sets it (`semantic_memory.rs`'s `store_internal` carry-forward, so
471    /// plain `remember` doesn't silently wipe learned state), and a permanent
472    /// write has no expiry to set (`attach_expiry` is a no-op without one) —
473    /// so without this delete, `_veles_expires_at` would survive the
474    /// "upgrade" untouched. A TTL-to-TTL extension needs no delete: its new
475    /// expiry always overwrites the old one.
476    fn prepare_source_slot(
477        &self,
478        slot: u64,
479        ttl_seconds: Option<u64>,
480    ) -> Result<bool, MemoryError> {
481        if !self.should_store_source(slot, ttl_seconds)? {
482            return Ok(false);
483        }
484        if ttl_seconds.is_none() && self.store.get(slot)?.is_some() {
485            self.store.delete(slot)?;
486        }
487        Ok(true)
488    }
489
490    /// The vector a source slot is indexed by, plus the media descriptor to
491    /// stamp on it when the fragment carries one.
492    ///
493    /// A media fragment's vector is deterministic and derived from the
494    /// DECODED bytes — never the text embedder over `content` (often blank)
495    /// nor over the base64 payload itself (opaque, not language). Correct
496    /// because `retrieve_context_source` resolves a media source EXCLUSIVELY
497    /// by its content-addressed hash/slot, never by vector search: the vector
498    /// only has to be well-formed and non-degenerate for the underlying
499    /// index, never semantically meaningful. For a media fragment `hash` IS
500    /// the raw-bytes hash (see `fragment_handle_hash`), so nothing is
501    /// re-decoded here.
502    fn source_vector(
503        &self,
504        fragment: &ContextFragment,
505        hash: u64,
506    ) -> Result<(Vec<f32>, Option<Value>), MemoryError> {
507        let Some(media_ref) = &fragment.media else {
508            return Ok((self.embedder.embed(fragment.content.as_str())?, None));
509        };
510        let descriptor = serde_json::to_value(media_ref).unwrap_or(Value::Null);
511        Ok((self.media_placeholder_embedding(hash), Some(descriptor)))
512    }
513
514    /// Whether [`Self::store_context_sources`] should (re-)write `slot` for
515    /// this compile's requested (already [`positive_ttl`]-normalized —
516    /// `None` means permanent) TTL.
517    ///
518    /// - Not marked as ours (absent, or a caller fact squatting the salt
519    ///   preimage): store only if the slot is genuinely empty.
520    /// - Marked as ours: never re-embed or change content (content-addressed);
521    ///   only [`Self::should_upgrade_ttl`] decides whether durability changes.
522    fn should_store_source(
523        &self,
524        slot: u64,
525        requested_ttl: Option<u64>,
526    ) -> Result<bool, MemoryError> {
527        match self.context_source_metadata(slot)? {
528            Some(existing) => Ok(Self::should_upgrade_ttl(&existing, requested_ttl)),
529            None => Ok(self.store.get(slot)?.is_none()),
530        }
531    }
532
533    /// Never-downgrade TTL upgrade rule for an already-stored source: permanent
534    /// once requested stays permanent, and a TTL only ever extends, never
535    /// shortens. The clock read here is fine — this is the storage/expiry
536    /// layer, not the clock-free `compile` pipeline.
537    fn should_upgrade_ttl(existing: &Metadata, requested_ttl: Option<u64>) -> bool {
538        let existing_expiry = existing.get(EXPIRES_AT_FIELD).and_then(Value::as_u64);
539        match (requested_ttl, existing_expiry) {
540            // Permanent requested, slot still carries a TTL: upgrade.
541            (None, Some(_)) => true,
542            // Already permanent, or a TTL requested against a permanent slot:
543            // never downgrade.
544            (None | Some(_), None) => false,
545            // Both carry a TTL: extend only if the new one outlives what
546            // remains — never shorten.
547            (Some(ttl), Some(existing_exp)) => now_unix_secs().saturating_add(ttl) > existing_exp,
548        }
549    }
550
551    /// A deterministic, non-degenerate embedding for a media source (US-009,
552    /// PR2) — see [`Self::store_context_sources`] for why it is bytes-hash
553    /// derived rather than text-embedded.
554    fn media_placeholder_embedding(&self, raw_hash: u64) -> Vec<f32> {
555        let dim = self.embedder.dimension();
556        let mut vector = vec![0.0_f32; dim];
557        let Ok(dim_u64) = u64::try_from(dim) else {
558            return vector;
559        };
560        if dim_u64 == 0 {
561            return vector;
562        }
563        let bucket = usize::try_from(raw_hash % dim_u64).unwrap_or(0);
564        vector[bucket] = 1.0;
565        velesdb_core::simd_native::normalize_inplace_native(&mut vector);
566        vector
567    }
568
569    /// The fact at `slot`'s metadata, when it carries the stored-source
570    /// marker (`None` otherwise — absent, or a caller fact squatting the
571    /// slot).
572    fn context_source_metadata(&self, slot: u64) -> Result<Option<Metadata>, MemoryError> {
573        let payloads = self.store.get_metadata_batch(&[slot])?;
574        Ok(payloads
575            .into_iter()
576            .next()
577            .flatten()
578            .filter(|meta| meta.get(CTX_SOURCE_FIELD) == Some(&Value::Bool(true))))
579    }
580
581    /// The original content — and media, when the fragment carried one —
582    /// behind a `ctx://source/<hash>` handle.
583    ///
584    /// # Errors
585    /// Returns [`MemoryError::UnknownHandle`] when the handle is malformed
586    /// or nothing is stored under it (never stored, expired, or forgotten).
587    pub fn retrieve_context_source(&self, handle: &str) -> Result<ContextSource, MemoryError> {
588        let unknown = || MemoryError::UnknownHandle(handle.to_owned());
589        let hash = provenance::parse_handle(handle).ok_or_else(unknown)?;
590        let slot = source_id(hash);
591        // Only marker-bearing facts are sources: a caller fact squatting the
592        // salted slot is never served back as compiled provenance.
593        let meta = self.context_source_metadata(slot)?.ok_or_else(unknown)?;
594        let content = self
595            .store
596            .get(slot)?
597            .map(|(content, _embedding)| content)
598            .ok_or_else(unknown)?;
599        Ok(ContextSource {
600            content,
601            media: source_media(&meta),
602        })
603    }
604
605    /// Explain why one fragment of `request` was preserved, abstracted,
606    /// externalized, dropped, or cached — the selection primitive the MCP
607    /// `explain_compilation` tool delegates to, extracted here so every
608    /// adapter (MCP, Node, Python) shares one implementation instead of
609    /// reimplementing it. Compilation is deterministic, so `request` is
610    /// simply re-compiled — with event/source recording forced off, since an
611    /// explanation must not have side effects — and the matching decision is
612    /// returned.
613    ///
614    /// `fragment_index` (0-based position in `request.fragments`), when
615    /// given, TAKES PRIORITY over `fragment_id` for locating the decision:
616    /// `compile_context` records exactly one decision per input fragment, in
617    /// order, so `decisions[fragment_index]` is unambiguous even when
618    /// several fragments are byte-identical and therefore share the same
619    /// content-addressed `fragment_id` — a plain `fragment_id` lookup always
620    /// resolves to the FIRST such decision (the deduplication survivor's),
621    /// never a dropped twin's.
622    ///
623    /// Caveat inherited from re-compiling rather than replaying stored
624    /// state: with a `memory_scope` the re-compile recalls from CURRENT
625    /// memory, so the decision reflects memory as it is now, not as it was
626    /// at the original `compile_context` call; a caller that already
627    /// resolved a `path` fragment to `content` is unaffected (this method
628    /// does no I/O of its own).
629    ///
630    /// # Errors
631    /// Returns [`MemoryError::FragmentIndexOutOfBounds`] when `fragment_index`
632    /// is beyond `request.fragments`, [`MemoryError::FragmentNotFound`] when
633    /// no decision matches the selector, or any error [`Self::compile_context`]
634    /// itself can return (budget, caps, recall, embedding, storage).
635    pub fn explain_compilation(
636        &self,
637        request: &CompileRequest,
638        fragment_id: u64,
639        fragment_index: Option<usize>,
640    ) -> Result<ContextDecision, MemoryError> {
641        if let Some(index) = fragment_index {
642            let len = request.fragments.len();
643            if index >= len {
644                return Err(MemoryError::FragmentIndexOutOfBounds { index, len });
645            }
646        }
647        let mut request = request.clone();
648        let mut policy = request.policy.take().unwrap_or_default();
649        policy.record_events = false;
650        policy.store_sources = false;
651        request.policy = Some(policy);
652        let compiled =
653            self.compile_context(&ContextCompiler::new(CompilePolicy::default()), &request)?;
654        let decision = if let Some(index) = fragment_index {
655            compiled.decisions.into_iter().nth(index)
656        } else {
657            compiled
658                .decisions
659                .into_iter()
660                .find(|decision| decision.fragment_id == fragment_id)
661        };
662        decision.ok_or(MemoryError::FragmentNotFound(fragment_id))
663    }
664
665    /// Record one compilation's savings as a metadata-only system fact
666    /// (hashes and token counts — never fragment content). Wall-clock time
667    /// is stamped here, outside the deterministic compile pipeline.
668    fn record_context_event(
669        &self,
670        request: &CompileRequest,
671        out: &CompiledContext,
672        ttl_seconds: Option<u64>,
673    ) -> Result<(), MemoryError> {
674        let occurred_at_nanos = now_nanos();
675        // The per-process sequence keeps ids unique even when two compiles
676        // land on the same (possibly coarse) clock tick.
677        let seq = EVENT_SEQ.fetch_add(1, Ordering::Relaxed);
678        let content = format!("{EVENT_ANCHOR} {occurred_at_nanos}-{seq}");
679        let id = stable_id(&format!("{EVENT_ID_SALT}{occurred_at_nanos}:{seq}"));
680        let embedding = self.embedder.embed(&content)?;
681        let meta = event_meta(request, out, occurred_at_nanos);
682        self.store_fact(
683            id,
684            &content,
685            &embedding,
686            Some(&meta),
687            positive_ttl(ttl_seconds),
688        )?;
689        Ok(())
690    }
691
692    /// Aggregate the recorded compilation events, optionally per project.
693    /// Sweeps at most [`crate::limits::MAX_RECALL_LIMIT`] events (newest
694    /// need not be first — the sweep is similarity-ordered over a constant
695    /// anchor, i.e. effectively the whole family until the cap);
696    /// [`ContextSavings::truncated`] reports when the cap was hit.
697    ///
698    /// # Errors
699    /// Returns [`MemoryError`] if the underlying filtered recall fails.
700    pub fn context_savings(&self, project: Option<&str>) -> Result<ContextSavings, MemoryError> {
701        // Filter at the STORAGE layer on the reserved event marker: callers
702        // can neither set nor query `_veles_*` keys, so only genuine bridge
703        // events can ever match — a caller fact posing as an event counts
704        // for nothing.
705        let mut filter = Map::new();
706        filter.insert(CTX_EVENT_FIELD.to_owned(), Value::Bool(true));
707        if let Some(project) = project {
708            filter.insert(
709                CTX_PROJECT_FIELD.to_owned(),
710                Value::String(project.to_owned()),
711            );
712        }
713        let embedding = self.embedder.embed(EVENT_ANCHOR)?;
714        let hits =
715            self.store
716                .query_filtered(&embedding, crate::limits::MAX_RECALL_LIMIT, &filter, 0)?;
717        let ids: Vec<u64> = hits.iter().map(|(id, _, _)| *id).collect();
718        let payloads = self.store.get_metadata_batch(&ids)?;
719        Ok(aggregate_events(&payloads))
720    }
721
722    /// Persist `working` under `project` + `session` (idempotent upsert:
723    /// saving again replaces the previous state). Returns the system fact id.
724    ///
725    /// Serialized size is capped at [`crate::limits::MAX_FACT_BYTES`] (1
726    /// MiB) — the same ceiling every other stored fact honors — checked
727    /// BEFORE anything is written, so an oversized working context is never
728    /// partially stored.
729    ///
730    /// An entirely empty `working` ([`WorkingContext::is_empty`]) is refused.
731    /// Because the write is an upsert, saving one would replace — destroy —
732    /// the state a previous save stored under the same project and session,
733    /// and the one tool whose job is surviving a context loss must not be
734    /// able to cause one on a call that carries nothing (issue #1654).
735    ///
736    /// # Errors
737    /// Returns [`MemoryError::EmptyWorkingContext`] if `working` records
738    /// nothing, [`MemoryError::WorkingContextCodec`] if serialization fails,
739    /// [`MemoryError::ContextOverLimit`] if the serialized `working` exceeds
740    /// [`crate::limits::MAX_FACT_BYTES`], or a storage/embedding error.
741    pub fn save_working_context(
742        &self,
743        project: &str,
744        session: &str,
745        working: &WorkingContext,
746    ) -> Result<u64, MemoryError> {
747        if working.is_empty() {
748            return Err(MemoryError::EmptyWorkingContext);
749        }
750        let content = serde_json::to_string(working)
751            .map_err(|err| MemoryError::WorkingContextCodec(err.to_string()))?;
752        if content.len() > crate::limits::MAX_FACT_BYTES {
753            return Err(MemoryError::ContextOverLimit(format!(
754                "working context of {} bytes exceeds the cap of {} bytes",
755                content.len(),
756                crate::limits::MAX_FACT_BYTES
757            )));
758        }
759        let id = working_id(project, session);
760        let embedding = self
761            .embedder
762            .embed(&format!("working context {project} {session}"))?;
763        let meta = system_meta(&[
764            (CTX_WORKING_FIELD, Value::Bool(true)),
765            (CTX_PROJECT_FIELD, Value::String(project.to_owned())),
766            (CTX_SESSION_FIELD, Value::String(session.to_owned())),
767        ]);
768        self.store_fact(id, &content, &embedding, Some(&meta), None)?;
769        self.update_working_index(project, session)?;
770        Ok(id)
771    }
772
773    /// The working context previously saved under `project` + `session`,
774    /// `None` when there is none.
775    ///
776    /// Symmetric to [`Self::context_source_metadata`]'s squatter guard: the
777    /// slot is only ever served back when its metadata carries the reserved
778    /// [`CTX_WORKING_FIELD`] marker (set exclusively by
779    /// [`Self::save_working_context`]). A slot occupied by an unmarked caller
780    /// fact — one that happened to land on this salted id, or a forged
781    /// probe — is indistinguishable from "nothing saved" on purpose: `None`,
782    /// never the forged content, and never an error (the caller cannot tell
783    /// a squatted slot from a genuinely empty one, which is the point — it
784    /// must never learn that *something* occupies this id).
785    ///
786    /// A pure read: it never writes, never prunes, never heals. Index
787    /// convergence happens on the WRITE path
788    /// ([`Self::update_working_index`]) — a lookup that rewrites shared state
789    /// turns every transient miss into permanent data loss and cannot safely
790    /// be retried.
791    ///
792    /// # Errors
793    /// Returns [`MemoryError::WorkingContextCodec`] if the stored payload
794    /// does not parse, or if the slot is marked but its body is gone (a torn
795    /// fact is corruption — reporting it as "nothing saved" would tell the
796    /// caller the one thing that is certainly false), or a storage error.
797    pub fn load_working_context(
798        &self,
799        project: &str,
800        session: &str,
801    ) -> Result<Option<WorkingContext>, MemoryError> {
802        let slot = working_id(project, session);
803        let payloads = self.store.get_metadata_batch(&[slot])?;
804        let marked = payloads
805            .into_iter()
806            .next()
807            .flatten()
808            .is_some_and(|meta| meta.get(CTX_WORKING_FIELD) == Some(&Value::Bool(true)));
809        if !marked {
810            // The squatter/never-saved guard documented above: silent by
811            // design, and the branch a `forget` lands on (deleting a fact
812            // removes its metadata with it).
813            return Ok(None);
814        }
815        let Some((content, _)) = self.store.get(slot)? else {
816            return Err(MemoryError::WorkingContextCodec(format!(
817                "working context for project '{project}', session '{session}' is corrupt: \
818                 the reserved marker is present but the stored body is gone"
819            )));
820        };
821        serde_json::from_str(&content)
822            .map(Some)
823            .map_err(|err| MemoryError::WorkingContextCodec(err.to_string()))
824    }
825
826    /// The sessions of `sessions` whose working-context fact is still there,
827    /// in the same order. One batched metadata lookup for the whole set — not
828    /// a store scan, but not free either (see
829    /// [`Self::list_working_contexts`]'s cost note).
830    ///
831    /// Shared by the read path (filter, persist nothing) and the write path
832    /// (filter, and persist the result), so both agree on what "alive" means.
833    fn live_sessions(
834        &self,
835        project: &str,
836        sessions: Vec<WorkingContextSession>,
837    ) -> Result<Vec<WorkingContextSession>, MemoryError> {
838        if sessions.is_empty() {
839            return Ok(sessions);
840        }
841        let ids: Vec<u64> = sessions
842            .iter()
843            .map(|entry| working_id(project, &entry.session))
844            .collect();
845        let payloads = self.store.get_metadata_batch(&ids)?;
846        if payloads.len() != ids.len() {
847            // The trait promises one result per id. A backend that breaks
848            // that promise must not be silently read as "these sessions are
849            // dead" — that would delete real entries on the write path.
850            return Err(MemoryError::WorkingContextCodec(format!(
851                "storage returned {} metadata rows for {} working-context ids",
852                payloads.len(),
853                ids.len()
854            )));
855        }
856        Ok(sessions
857            .into_iter()
858            .zip(payloads)
859            .filter(|(_, meta)| {
860                meta.as_ref()
861                    .is_some_and(|meta| meta.get(CTX_WORKING_FIELD) == Some(&Value::Bool(true)))
862            })
863            .map(|(entry, _)| entry)
864            .collect())
865    }
866
867    /// Every session still resumable under `project`'s working-context index
868    /// (V2a-1 quick win), most-recently-saved first. Empty when the project
869    /// never saved anything — that, and only that, is the empty case.
870    ///
871    /// Cost: one O(1) index read plus ONE batched metadata lookup of the
872    /// listed ids — never a store scan, but no longer a single read either.
873    /// The lookup is what drops sessions whose fact was forgotten since;
874    /// unlike the previous read-path prune it persists nothing, so a listing
875    /// can be retried and a transient miss costs nothing durable.
876    ///
877    /// # Errors
878    /// Returns a storage error if the index fact cannot be read, or
879    /// [`MemoryError::WorkingContextCodec`] if it does not parse or is
880    /// corrupt (marked, but with no body).
881    pub fn list_working_contexts(
882        &self,
883        project: &str,
884    ) -> Result<Vec<WorkingContextSession>, MemoryError> {
885        let Some(index) = self.working_index(project)? else {
886            // The genuine "this project never saved anything" case — the only
887            // one that reaches here now that a corrupt index is an `Err`.
888            return Ok(Vec::new());
889        };
890        let mut sessions = self.live_sessions(project, index.sessions)?;
891        sessions.sort_by(|a, b| {
892            b.saved_at
893                .cmp(&a.saved_at)
894                .then_with(|| a.session.cmp(&b.session))
895        });
896        Ok(sessions)
897    }
898
899    /// The raw working-context index fact for `project`, `None` when nothing
900    /// was ever saved under it. Symmetric squatter guard to
901    /// [`Self::load_working_context`]: a slot occupied without the reserved
902    /// [`CTX_WORKING_INDEX_FIELD`] marker is treated as empty, never as a
903    /// forged index.
904    ///
905    /// `None` means "absent". "Corrupt" is an `Err` — collapsing the two
906    /// would report a store that lost the index body as a project that never
907    /// saved anything, and an agent told that starts over instead of raising
908    /// a problem a human could fix.
909    fn working_index(&self, project: &str) -> Result<Option<WorkingContextIndex>, MemoryError> {
910        let slot = working_index_id(project);
911        let payloads = self.store.get_metadata_batch(&[slot])?;
912        let marked = payloads
913            .into_iter()
914            .next()
915            .flatten()
916            .is_some_and(|meta| meta.get(CTX_WORKING_INDEX_FIELD) == Some(&Value::Bool(true)));
917        if !marked {
918            return Ok(None);
919        }
920        match self.store.get(slot)? {
921            Some((content, _)) => serde_json::from_str(&content)
922                .map(Some)
923                .map_err(|err| MemoryError::WorkingContextCodec(err.to_string())),
924            None => Err(MemoryError::WorkingContextCodec(format!(
925                "working-context index for project '{project}' is corrupt: the index \
926                 marker is present but the stored body is gone"
927            ))),
928        }
929    }
930
931    /// Append (or refresh) `session`'s entry in `project`'s working-context
932    /// index — called by every [`Self::save_working_context`], so the index
933    /// is always current without a separate maintenance step. A resave of
934    /// the same project+session updates `saved_at` in place rather than
935    /// duplicating the entry.
936    ///
937    /// This is also where the index CONVERGES: entries whose working-context
938    /// fact was forgotten since are dropped here, on the write path, under
939    /// the same lock and in the same read-modify-write that was already
940    /// paid for. Reads never mutate it.
941    fn update_working_index(&self, project: &str, session: &str) -> Result<(), MemoryError> {
942        // Read-modify-write of a single shared fact: held for the whole
943        // sequence, otherwise a concurrent save silently erases this entry.
944        // The guarded data is `()`, so a poisoned lock carries no broken
945        // invariant — recover rather than propagate someone else's panic.
946        let _guard = WORKING_INDEX_WRITE
947            .lock()
948            .unwrap_or_else(std::sync::PoisonError::into_inner);
949        // A corrupt index must not brick saving for the whole project. The
950        // read path surfaces the error — that is where a human can act on it
951        // — but propagating it here would make every future save of every
952        // session under this project fail forever, with no way back: the
953        // only writer of the index is this function. Rebuild instead.
954        let mut index = match self.working_index(project) {
955            Ok(index) => index.unwrap_or_default(),
956            Err(MemoryError::WorkingContextCodec(_)) => WorkingContextIndex::default(),
957            Err(err) => return Err(err),
958        };
959        let now = now_unix_secs();
960        if let Some(entry) = index.sessions.iter_mut().find(|s| s.session == session) {
961            entry.saved_at = now;
962        } else {
963            index.sessions.push(WorkingContextSession {
964                session: session.to_owned(),
965                saved_at: now,
966            });
967        }
968        // The entry just appended is alive by construction (its fact was
969        // stored moments ago, before this call); this only sheds the ones a
970        // `forget` orphaned.
971        index.sessions = self.live_sessions(project, index.sessions)?;
972        let content = serde_json::to_string(&index)
973            .map_err(|err| MemoryError::WorkingContextCodec(err.to_string()))?;
974        self.write_working_index(project, &content)
975    }
976
977    /// Persist a serialized index into `project`'s reserved index slot —
978    /// always with the [`CTX_WORKING_INDEX_FIELD`] marker, since an index
979    /// written without it would be treated as a squatter and read back as
980    /// empty. Only [`Self::update_working_index`] (which holds
981    /// [`WORKING_INDEX_WRITE`]) calls this.
982    fn write_working_index(&self, project: &str, content: &str) -> Result<(), MemoryError> {
983        let slot = working_index_id(project);
984        let embedding = self
985            .embedder
986            .embed(&format!("working context index {project}"))?;
987        let meta = system_meta(&[
988            (CTX_WORKING_INDEX_FIELD, Value::Bool(true)),
989            (CTX_PROJECT_FIELD, Value::String(project.to_owned())),
990        ]);
991        self.store_fact(slot, content, &embedding, Some(&meta), None)?;
992        Ok(())
993    }
994}
995
996/// How many memories a scope pulls when it does not say (`k` absent).
997const DEFAULT_MEMORY_K: usize = 5;
998
999/// The request's memory scope plus the clamped pull count — `None` when
1000/// there is no scope or no room: pulled memories must never push the
1001/// request over the fragment cap (the cap is validated after augmentation,
1002/// and a rejection there would blame the caller for fragments the bridge
1003/// itself added).
1004fn scope_and_k(request: &CompileRequest) -> Option<(&MemoryScope, usize)> {
1005    let scope = request.memory_scope.as_ref()?;
1006    let room = crate::limits::MAX_FRAGMENTS.saturating_sub(request.fragments.len());
1007    let k = crate::limits::clamp_recall_limit(scope.k.unwrap_or(DEFAULT_MEMORY_K)).min(room);
1008    (k > 0).then_some((scope, k))
1009}
1010
1011/// The recall filter a scope narrows to (its project facet), if any.
1012fn scope_filter(scope: &MemoryScope) -> Option<Metadata> {
1013    scope.project.as_ref().map(|project| {
1014        let mut meta = Map::new();
1015        meta.insert("project".to_owned(), Value::String(project.clone()));
1016        meta
1017    })
1018}
1019
1020/// One memory the scope pulled in, with its full ranking ventilation.
1021struct PulledMemory {
1022    fragment: ContextFragment,
1023    memory_id: u64,
1024    /// Fused score normalised over the pulled batch, in `[0, 1]` — the
1025    /// importance-blended key (clamped) when the blend is active.
1026    relevance: f32,
1027    /// Normalised vector term of the fused score.
1028    vector_norm: f64,
1029    /// Graph promotion weight of the fused score.
1030    graph_weight: f64,
1031    /// Learned RL confidence the blend used (neutral `0.5` when the memory
1032    /// never received feedback).
1033    confidence: f64,
1034    /// Batch-relative recency contribution in `[0, 1]` (`0` when the term
1035    /// is inactive, the key is absent, or the batch is degenerate).
1036    recency: f64,
1037    /// Whether the importance blend ran — drives the extended four-signal
1038    /// reason ventilation; `false` keeps the exact 0.8.0 reason bytes.
1039    ventilated: bool,
1040}
1041
1042/// A selected memory before the importance blend: its similarity base, its
1043/// fused ventilation, and the caller-visible metadata the recency term reads.
1044struct MemoryCandidate {
1045    memory_id: u64,
1046    /// Fused-normalised (or rank-based) similarity in `[0, 1]`.
1047    base: f64,
1048    vector_norm: f64,
1049    graph_weight: f64,
1050    metadata: Option<Metadata>,
1051    content: String,
1052}
1053
1054impl MemoryCandidate {
1055    /// The unblended [`PulledMemory`] — bytes identical to the 0.8.0 pull.
1056    fn into_pulled(self) -> PulledMemory {
1057        #[allow(clippy::cast_possible_truncation)] // base is clamped into [0, 1]
1058        let relevance = self.base as f32;
1059        PulledMemory {
1060            fragment: ContextFragment {
1061                id: None,
1062                content: self.content,
1063                path: None,
1064                kind: Some("memory".to_owned()),
1065                priority: None,
1066                metadata: None,
1067                media: None,
1068            },
1069            memory_id: self.memory_id,
1070            relevance,
1071            vector_norm: self.vector_norm,
1072            graph_weight: self.graph_weight,
1073            confidence: NEUTRAL_CONFIDENCE,
1074            recency: 0.0,
1075            ventilated: false,
1076        }
1077    }
1078}
1079
1080/// The neutral confidence of a memory with no feedback history — mirrors
1081/// `reinforce::RL_NEUTRAL_CONFIDENCE`, whose module is `persistence`-gated:
1082/// its contribution to the blend is exactly `0`.
1083const NEUTRAL_CONFIDENCE: f64 = 0.5;
1084
1085/// The learned RL confidence off a raw payload, in `[0, 1]`. Without the
1086/// `persistence` feature the RL module (and thus `feedback`) does not exist,
1087/// so every memory reads neutral.
1088#[cfg(feature = "persistence")]
1089fn payload_confidence(payload: Option<&Metadata>) -> f64 {
1090    f64::from(payload.map_or(
1091        super::reinforce::RL_NEUTRAL_CONFIDENCE,
1092        super::reinforce::read_confidence,
1093    ))
1094}
1095
1096/// See the `persistence` twin: no RL module, always neutral.
1097#[cfg(not(feature = "persistence"))]
1098fn payload_confidence(_payload: Option<&Metadata>) -> f64 {
1099    NEUTRAL_CONFIDENCE
1100}
1101
1102/// Whether the policy's importance weights change anything at all: a
1103/// non-zero confidence weight, or a non-zero recency weight WITH a field to
1104/// read. Zero weights must cost nothing and change nothing (0.8.0 parity).
1105#[allow(
1106    clippy::float_cmp,
1107    reason = "an exact zero weight is the documented off switch; any non-zero weight, however small, is active"
1108)]
1109fn importance_active(weights: &ImportanceWeights) -> bool {
1110    weights.confidence != 0.0 || (weights.recency != 0.0 && weights.recency_field.is_some())
1111}
1112
1113/// The batch-relative recency contribution of every candidate, in `[0, 1]`:
1114/// min-max over the candidates that carry the policy's `recency_field` as a
1115/// number (one monotone scale per batch — `YYYYMMDD` or an epoch, the
1116/// caller's choice). A candidate without the key contributes `0` (never
1117/// penalised), and a degenerate batch (`max == min`) contributes `0` for
1118/// all. No clock: recency is relative to the newest of the batch.
1119#[allow(
1120    clippy::float_cmp,
1121    reason = "an exact zero weight is the documented off switch for the recency term"
1122)]
1123fn recency_norms(candidates: &[MemoryCandidate], weights: &ImportanceWeights) -> Vec<f64> {
1124    let field = weights
1125        .recency_field
1126        .as_ref()
1127        .filter(|_| weights.recency != 0.0);
1128    let Some(field) = field else {
1129        return vec![0.0; candidates.len()];
1130    };
1131    let values: Vec<Option<f64>> = candidates
1132        .iter()
1133        .map(|candidate| {
1134            candidate
1135                .metadata
1136                .as_ref()
1137                .and_then(|meta| meta.get(field.as_str()))
1138                .and_then(Value::as_f64)
1139                .filter(|value| value.is_finite())
1140        })
1141        .collect();
1142    let (min, max) = values
1143        .iter()
1144        .flatten()
1145        .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &v| {
1146            (lo.min(v), hi.max(v))
1147        });
1148    if max <= min {
1149        return vec![0.0; candidates.len()];
1150    }
1151    values
1152        .into_iter()
1153        .map(|value| value.map_or(0.0, |v| ((v - min) / (max - min)).clamp(0.0, 1.0)))
1154        .collect()
1155}
1156
1157/// Stamp pulled memories into the compiled provenance: their decisions and
1158/// sources gain the backing `memory_id`, the decision's relevance becomes
1159/// the normalised (importance-blended, when active) ranking score, and the
1160/// reason spells out the full score ventilation — vector and graph always,
1161/// plus confidence and recency when the blend ran — so `why this memory` is
1162/// answerable from the decision alone.
1163fn annotate_memory_provenance(out: &mut CompiledContext, pulled: &BTreeMap<u64, PulledMemory>) {
1164    for decision in &mut out.decisions {
1165        if let Some(memory) = pulled.get(&decision.content_hash) {
1166            decision.memory_id = Some(memory.memory_id);
1167            decision.relevance = memory.relevance;
1168            decision.reason = if memory.ventilated {
1169                format!(
1170                    "{} — pulled from memory {} (vector {:.2}, graph {:.2}, confidence {:.2}, recency {:.2})",
1171                    decision.reason,
1172                    memory.memory_id,
1173                    memory.vector_norm,
1174                    memory.graph_weight,
1175                    memory.confidence,
1176                    memory.recency
1177                )
1178            } else {
1179                format!(
1180                    "{} — pulled from memory {} (vector {:.2}, graph {:.2})",
1181                    decision.reason, memory.memory_id, memory.vector_norm, memory.graph_weight
1182                )
1183            };
1184        }
1185    }
1186    for source in &mut out.sources {
1187        if let Some(hash) = provenance::parse_handle(&source.handle) {
1188            if let Some(memory) = pulled.get(&hash) {
1189                source.memory_id = Some(memory.memory_id);
1190            }
1191        }
1192    }
1193}
1194
1195/// Base metadata of every bridge-stored system fact: hub-marked (invisible
1196/// to normal recall) plus the given extra keys.
1197fn system_meta(extra: &[(&str, Value)]) -> Metadata {
1198    let mut meta = Map::new();
1199    meta.insert(HUB_FIELD.to_owned(), Value::Bool(true));
1200    for (key, value) in extra {
1201        meta.insert((*key).to_owned(), value.clone());
1202    }
1203    meta
1204}
1205
1206/// The metadata of one compilation event — counts and identifiers only,
1207/// every key reserved.
1208fn event_meta(request: &CompileRequest, out: &CompiledContext, nanos: u128) -> Metadata {
1209    let mut extra: Vec<(&str, Value)> = vec![
1210        (CTX_EVENT_FIELD, Value::Bool(true)),
1211        (
1212            CTX_TOKENS_IN_FIELD,
1213            Value::Number(out.insights.tokens_in.into()),
1214        ),
1215        (
1216            CTX_TOKENS_OUT_FIELD,
1217            Value::Number(out.insights.tokens_out.into()),
1218        ),
1219        (
1220            CTX_TOKENS_SAVED_FIELD,
1221            Value::Number(out.insights.tokens_saved.into()),
1222        ),
1223        (
1224            CTX_AT_FIELD,
1225            Value::Number(Number::from(
1226                u64::try_from(nanos / 1_000_000_000).unwrap_or(u64::MAX),
1227            )),
1228        ),
1229    ];
1230    if let Some(project) = &request.project {
1231        extra.push((CTX_PROJECT_FIELD, Value::String(project.clone())));
1232    }
1233    if let Some(model) = &request.target_model {
1234        extra.push((CTX_MODEL_FIELD, Value::String(model.clone())));
1235    }
1236    if let (Some(micros), Some(currency)) = (
1237        out.insights.estimated_cost_saved_micros,
1238        out.insights.currency.as_ref(),
1239    ) {
1240        extra.push((CTX_COST_FIELD, Value::Number(micros.into())));
1241        extra.push((CTX_CURRENCY_FIELD, Value::String(currency.clone())));
1242    }
1243    system_meta(&extra)
1244}
1245
1246/// Fold raw event payloads (reserved keys included) into one
1247/// [`ContextSavings`]. Every accumulation saturates — an aggregate must
1248/// never panic, whatever the stored numbers.
1249fn aggregate_events(payloads: &[Option<Metadata>]) -> ContextSavings {
1250    let mut savings = ContextSavings {
1251        events: payloads.len() as u64,
1252        truncated: payloads.len() >= crate::limits::MAX_RECALL_LIMIT,
1253        ..ContextSavings::default()
1254    };
1255    for payload in payloads {
1256        let Some(meta) = payload else { continue };
1257        savings.tokens_in = savings
1258            .tokens_in
1259            .saturating_add(meta_u64(meta, CTX_TOKENS_IN_FIELD));
1260        savings.tokens_out = savings
1261            .tokens_out
1262            .saturating_add(meta_u64(meta, CTX_TOKENS_OUT_FIELD));
1263        savings.tokens_saved = savings
1264            .tokens_saved
1265            .saturating_add(meta_u64(meta, CTX_TOKENS_SAVED_FIELD));
1266        if let (Some(Value::String(currency)), micros) =
1267            (meta.get(CTX_CURRENCY_FIELD), meta_u64(meta, CTX_COST_FIELD))
1268        {
1269            if micros > 0 {
1270                let entry = savings
1271                    .cost_saved_micros_by_currency
1272                    .entry(currency.clone())
1273                    .or_insert(0);
1274                *entry = entry.saturating_add(micros);
1275            }
1276        }
1277    }
1278    savings
1279}
1280
1281/// A `u64` metadata field, `0` when absent or non-numeric.
1282fn meta_u64(meta: &Metadata, key: &str) -> u64 {
1283    meta.get(key).and_then(Value::as_u64).unwrap_or(0)
1284}
1285
1286/// The salted system-fact id of a stored source.
1287fn source_id(content_hash: u64) -> u64 {
1288    stable_id(&format!("{SOURCE_ID_SALT}{content_hash}"))
1289}
1290
1291/// The handle-identity hash of one request fragment — the bridge-side twin
1292/// of `Analysis::handle_hash` in `context.rs` (kept in lockstep; the two
1293/// must key the same identity or stored slots and minted handles drift
1294/// apart): raw decoded media bytes for a media fragment, caption/content
1295/// [`stable_id`] otherwise.
1296fn fragment_handle_hash(fragment: &ContextFragment) -> u64 {
1297    fragment.media.as_ref().map_or_else(
1298        || stable_id(&fragment.content),
1299        |media_ref| media::analyze(media_ref).raw_hash,
1300    )
1301}
1302
1303/// Index a request's fragments by the hash their `ctx://source/` handle is
1304/// built from, so a handle can be resolved back to the fragment that produced
1305/// it. First occurrence wins (see the identity note on
1306/// `store_context_sources`): `entry` + `or_insert`, never a blind overwrite.
1307fn index_fragments_by_handle_hash(
1308    fragments: &[ContextFragment],
1309) -> BTreeMap<u64, &ContextFragment> {
1310    let mut by_hash: BTreeMap<u64, &ContextFragment> = BTreeMap::new();
1311    for fragment in fragments {
1312        by_hash
1313            .entry(fragment_handle_hash(fragment))
1314            .or_insert(fragment);
1315    }
1316    by_hash
1317}
1318
1319/// A stored source's media payload (US-009, PR2), when its metadata carries
1320/// one — absent (or malformed, which should never happen for a payload this
1321/// bridge wrote itself) round-trips as `None` rather than an error, so a
1322/// media decode hiccup degrades to "text-only", never breaks the whole
1323/// retrieval.
1324fn source_media(meta: &Metadata) -> Option<MediaRef> {
1325    meta.get(CTX_SOURCE_MEDIA_FIELD)
1326        .cloned()
1327        .and_then(|value| serde_json::from_value(value).ok())
1328}
1329
1330/// The salted, deterministic system-fact id of a working context.
1331fn working_id(project: &str, session: &str) -> u64 {
1332    stable_id(&format!("{WORKING_ID_SALT}{project}\u{1f}{session}"))
1333}
1334
1335/// The salted, deterministic system-fact id of a project's working-context
1336/// index — one per project, so every save updates the same slot.
1337fn working_index_id(project: &str) -> u64 {
1338    stable_id(&format!("{WORKING_INDEX_ID_SALT}{project}"))
1339}
1340
1341#[cfg(all(test, feature = "persistence"))]
1342#[path = "memory_bridge_tests.rs"]
1343mod tests;