Skip to main content

mnemo_engine/
memory.rs

1//! The agent memory model (Phase 5 of the build plan).
2//!
3//! This is what makes Mnemo a *memory engine* rather than a generic vector
4//! store. Memories are typed (episodic / semantic / procedural / working),
5//! carry lifecycle metadata (importance, access stats, optional TTL), and are
6//! retrieved with a **multi-signal score** that blends semantic similarity
7//! with recency, importance, and access frequency.
8
9use std::time::{SystemTime, UNIX_EPOCH};
10
11use serde::{Deserialize, Serialize};
12use serde_json::{Map, Value};
13use ulid::Ulid;
14
15/// Current unix time in whole seconds.
16pub fn now_secs() -> i64 {
17    SystemTime::now()
18        .duration_since(UNIX_EPOCH)
19        .map(|d| d.as_secs() as i64)
20        .unwrap_or(0)
21}
22
23/// The four kinds of agent memory.
24#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Hash)]
25pub enum MemoryType {
26    /// What happened — conversation turns, events, interactions.
27    Episodic,
28    /// What is known — facts, entities, relationships, beliefs.
29    Semantic,
30    /// What to do — preferences, behavioral patterns, rules.
31    Procedural,
32    /// Right now — current-session context and scratchpad.
33    Working,
34}
35
36impl MemoryType {
37    /// Parse from a lowercase string (used by the CLI / SDK surface).
38    pub fn parse(s: &str) -> Option<MemoryType> {
39        match s.to_ascii_lowercase().as_str() {
40            "episodic" => Some(MemoryType::Episodic),
41            "semantic" => Some(MemoryType::Semantic),
42            "procedural" => Some(MemoryType::Procedural),
43            "working" => Some(MemoryType::Working),
44            _ => None,
45        }
46    }
47
48    /// Lowercase string form.
49    pub fn as_str(&self) -> &'static str {
50        match self {
51            MemoryType::Episodic => "episodic",
52            MemoryType::Semantic => "semantic",
53            MemoryType::Procedural => "procedural",
54            MemoryType::Working => "working",
55        }
56    }
57}
58
59/// Visibility of a memory across agents sharing one `.mnemo` file.
60#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
61pub enum Scope {
62    /// Visible only to the agent that created it.
63    Private,
64    /// Visible to every agent with read access.
65    Shared,
66}
67
68/// A single memory entry.
69#[derive(Serialize, Deserialize, Clone, Debug)]
70pub struct Memory {
71    /// Time-sortable unique ID.
72    pub id: Ulid,
73    /// Cognitive category of this memory.
74    pub memory_type: MemoryType,
75    /// Embedding of `content`.
76    pub vector: Vec<f32>,
77    /// The actual text/data of the memory.
78    pub content: String,
79    /// Free-form structured metadata.
80    pub metadata: Map<String, Value>,
81    /// Which agent created this memory.
82    pub agent_id: String,
83    /// Which session produced it (relevant for episodic memory).
84    pub session_id: Option<String>,
85    /// Visibility scope (private to its agent, or shared).
86    pub scope: Scope,
87    /// Unix seconds at creation.
88    pub created_at: i64,
89    /// Unix seconds of the most recent retrieval. Updated by `recall`.
90    pub accessed_at: i64,
91    /// How many times this memory has been retrieved.
92    pub access_count: u32,
93    /// Importance in `[0.0, 1.0]`; higher importance resists decay.
94    pub importance: f32,
95    /// Optional lifetime in seconds. After expiry the memory is skipped by
96    /// `recall` and removed by `compact`.
97    pub ttl_secs: Option<i64>,
98}
99
100impl Memory {
101    /// Create a new memory with sensible defaults. The ID and timestamps are
102    /// assigned now; tune the rest with the `with_*` builders.
103    pub fn new(content: impl Into<String>, memory_type: MemoryType, vector: Vec<f32>) -> Self {
104        let now = now_secs();
105        Memory {
106            id: Ulid::new(),
107            memory_type,
108            vector,
109            content: content.into(),
110            metadata: Map::new(),
111            agent_id: "default".to_string(),
112            session_id: None,
113            scope: Scope::Private,
114            created_at: now,
115            accessed_at: now,
116            access_count: 0,
117            importance: 0.5,
118            ttl_secs: None,
119        }
120    }
121
122    /// Set the owning agent.
123    pub fn with_agent(mut self, agent_id: impl Into<String>) -> Self {
124        self.agent_id = agent_id.into();
125        self
126    }
127    /// Set the session ID.
128    pub fn with_session(mut self, session_id: impl Into<String>) -> Self {
129        self.session_id = Some(session_id.into());
130        self
131    }
132    /// Set the importance score (clamped to `[0,1]`).
133    pub fn with_importance(mut self, importance: f32) -> Self {
134        self.importance = importance.clamp(0.0, 1.0);
135        self
136    }
137    /// 13a (13.5): `public`, `team` or `private` (checked when it's
138    /// written).
139    pub fn with_visibility(mut self, level: &str) -> Self {
140        self.metadata
141            .insert(MNEMO_META_VISIBILITY.into(), Value::String(level.into()));
142        self
143    }
144    /// 13a (13.6): when the content was true, in unix seconds.
145    pub fn with_as_of(mut self, unix_secs: i64) -> Self {
146        self.metadata
147            .insert(MNEMO_META_AS_OF.into(), Value::Number(unix_secs.into()));
148        self
149    }
150    /// 13a (13.6): when someone should look at it again, in unix seconds.
151    pub fn with_review_by(mut self, unix_secs: i64) -> Self {
152        self.metadata
153            .insert(MNEMO_META_REVIEW_BY.into(), Value::Number(unix_secs.into()));
154        self
155    }
156    /// Set the visibility scope.
157    pub fn with_scope(mut self, scope: Scope) -> Self {
158        self.scope = scope;
159        self
160    }
161    /// Attach a TTL in seconds.
162    pub fn with_ttl(mut self, ttl_secs: i64) -> Self {
163        self.ttl_secs = Some(ttl_secs);
164        self
165    }
166    /// Attach a metadata key/value pair.
167    pub fn with_meta(mut self, key: impl Into<String>, value: Value) -> Self {
168        self.metadata.insert(key.into(), value);
169        self
170    }
171
172    /// True if the memory's TTL has elapsed as of `now`.
173    pub fn is_expired(&self, now: i64) -> bool {
174        match self.ttl_secs {
175            Some(ttl) => now - self.created_at >= ttl,
176            None => false,
177        }
178    }
179
180    /// Build the **canonical scaffold manifest** for a freshly-initialised
181    /// database. This is the default "I am a brand-new MNemo file" memory
182    /// inserted by `mnemo init` (and surfaced by `mnemo about`) so every new
183    /// database is self-describing from birth — no opt-in step required.
184    ///
185    /// The scaffold is a placeholder: the vector is all-zeros (it doesn't
186    /// pretend to carry semantic content), and `metadata.scaffold = true`
187    /// marks it as auto-generated so tooling and humans can tell it apart
188    /// from a hand-written manifest. The expected workflow is for the file's
189    /// author to replace this memory with one that records the project's
190    /// actual embedder, agent_id default, and conventions.
191    ///
192    /// See [`crate::Mnemo::about`] for the rest of the convention.
193    pub fn scaffold_manifest(dimensions: usize) -> Self {
194        let content = format!(
195            "MNEMO MANIFEST (scaffold) — Fresh {}-dimensional database created \
196             by `mnemo init`. This is a placeholder. Replace it with a memory \
197             that records your project's embedder (name, dimensions, normalize), \
198             default agent_id, and metadata conventions; keep the metadata keys \
199             `area=\"onboarding\"` and `topic=\"manifest\"` so `mnemo about` \
200             continues to surface it as the headline orientation point. Drop \
201             `metadata.scaffold` once you've replaced this entry so tooling \
202             knows the manifest has been curated.",
203            dimensions
204        );
205        let mut metadata = Map::new();
206        metadata.insert("area".into(), Value::String("onboarding".into()));
207        metadata.insert("topic".into(), Value::String("manifest".into()));
208        metadata.insert("scaffold".into(), Value::Bool(true));
209        metadata.insert(
210            "engine_version".into(),
211            Value::String(env!("CARGO_PKG_VERSION").into()),
212        );
213        metadata.insert(
214            "dimensions".into(),
215            Value::Number(serde_json::Number::from(dimensions as u64)),
216        );
217        // Sentinel vector: a single-axis unit spike `[1, 0, 0, …]`.
218        // A zero vector would now trip the Phase 3 `put` guard
219        // (all-zero refused — see store/records.rs). This spike is non-zero
220        // (so it passes), unit-normalized (so it reads cleanly to any
221        // downstream inspector), and uncorrelated with any real
222        // embedder's output (so it ranks near-last on any user query —
223        // appropriate for a placeholder the user is expected to
224        // replace).
225        let mut vector = vec![0.0_f32; dimensions];
226        if dimensions > 0 {
227            vector[0] = 1.0;
228        }
229        let now = now_secs();
230        Memory {
231            id: Ulid::new(),
232            memory_type: MemoryType::Semantic,
233            vector,
234            content,
235            metadata,
236            agent_id: "mnemo".to_string(),
237            session_id: None,
238            scope: Scope::Shared,
239            created_at: now,
240            accessed_at: now,
241            access_count: 0,
242            importance: 1.0,
243            ttl_secs: None,
244        }
245    }
246}
247
248// ---------------------------------------------------------------------------
249// Phase 12.1: reserved `_mnemo.*` metadata keys for in-place updates + keyed
250// supersession. These live in `Memory.metadata` (which is already
251// `Map<String, Value>` on the record), so nothing in the on-disk record
252// layout changes — v0.7.x readers see them as ordinary user metadata and
253// ignore them. Format bump to v9 (post-12.1) will promote the ones that
254// pay for a typed catalog column.
255// ---------------------------------------------------------------------------
256
257/// Namespace prefix used for every v0.8.0+ reserved metadata key (R-001.10).
258/// Keys outside this namespace are untouched user metadata.
259pub const MNEMO_META_NS: &str = "_mnemo.";
260
261/// Upsert slot name on a `remember(…, key = K)` write (12.1). Combined with
262/// the memory's `scope` (and `agent_id` for `Private` scope) to identify a
263/// single live memory per slot: a newer `remember(key=K)` supersedes the
264/// prior one.
265pub const MNEMO_META_KEY: &str = "_mnemo.key";
266
267/// Set on the newly-inserted record when a `remember(key=K)` supersedes an
268/// earlier record. Value: the superseded record's ULID string.
269pub const MNEMO_META_SUPERSEDES: &str = "_mnemo.supersedes";
270
271/// Set on the earlier record when a newer `remember(key=K)` has replaced
272/// it. Value: the new record's ULID string. Together with `_mnemo.invalid_at`
273/// this marks the record as "superseded, not current" — default `recall`,
274/// `about` and the key index skip it; `history(key)` walks the chain.
275pub const MNEMO_META_SUPERSEDED_BY: &str = "_mnemo.superseded_by";
276
277/// Set on the earlier record when superseded. Value: unix seconds (i64).
278/// Not interpreted by the engine's scorer — purely for audit / `history`.
279pub const MNEMO_META_INVALID_AT: &str = "_mnemo.invalid_at";
280
281/// Set on a record each time `Mnemo::update` succeeds. Value: unix seconds.
282/// Lets callers distinguish an unchanged-since-creation record from one
283/// that has been edited in place. Not interpreted by the scorer.
284pub const MNEMO_META_UPDATED_AT: &str = "_mnemo.updated_at";
285
286// ---------------------------------------------------------------------------
287// Phase 12.7a: thread archive (ingest / export / forget). Reserved
288// `_mnemo.*` keys that identify thread-turn records. All records with
289// `_mnemo.kind = "turn"` are:
290//   * excluded from default recall (opt in with a 12.6
291//     `_mnemo.kind = "turn"` filter or the `--thread` CLI flag),
292//   * written by `Mnemo::ingest_thread` + the `mnemo thread ingest`
293//     CLI from a transcript file in either a generic JSONL shape or
294//     Claude Code's JSONL (`~/.claude/projects/<p>/<s>.jsonl`),
295//   * grouped by `_mnemo.thread = <id>` for `thread export` /
296//     `thread forget` and the 12.7b essence render.
297// ---------------------------------------------------------------------------
298
299/// Record kind for thread-archive turns (Phase 12.7a). Value: `"turn"`.
300pub const MNEMO_META_KIND: &str = "_mnemo.kind";
301
302/// Thread identifier the record belongs to (Phase 12.7a). Value: a
303/// caller-supplied string, typically the Claude Code session uuid or
304/// the planner-chosen thread slug.
305pub const MNEMO_META_THREAD: &str = "_mnemo.thread";
306
307/// Monotonically increasing sequence number within the thread
308/// (Phase 12.7a). Value: unsigned integer, 0-based. Lets
309/// `thread export` reconstruct the transcript in order.
310pub const MNEMO_META_SEQ: &str = "_mnemo.seq";
311
312/// Role of the turn's author (Phase 12.7a). Value: `"user"`,
313/// `"assistant"`, `"system"`, `"tool"`, or any other string the
314/// source transcript used.
315pub const MNEMO_META_ROLE: &str = "_mnemo.role";
316
317/// Opaque per-turn identifier from the source transcript
318/// (Phase 12.7a). Value: typically a uuid4. Used for idempotence —
319/// `ingest_thread` skips any turn whose `turn_id` already exists on a
320/// record in the target thread.
321pub const MNEMO_META_TURN_ID: &str = "_mnemo.turn_id";
322
323/// Zero-based part number for a turn that was chunked at the 8 KB
324/// boundary during ingest (Phase 12.7a). Absent → the turn fits in a
325/// single record.
326pub const MNEMO_META_PART: &str = "_mnemo.part";
327
328/// Hex-encoded SHA-256 of the original tool-result content
329/// (Phase 12.7a). Set when the content exceeded the 16 KB truncation
330/// cap during ingest; absent otherwise.
331pub const MNEMO_META_SHA256: &str = "_mnemo.sha256";
332
333/// Byte length of the original tool-result content (Phase 12.7a). Set
334/// alongside `_mnemo.sha256` when truncation happened; absent
335/// otherwise.
336pub const MNEMO_META_LENGTH: &str = "_mnemo.length";
337
338/// Marker value for `_mnemo.kind` on thread-turn records.
339pub const MNEMO_META_KIND_TURN: &str = "turn";
340
341/// 13a: `_mnemo.kind` of a message between agents (13.1).
342pub const MNEMO_META_KIND_MESSAGE: &str = "message";
343/// 13a: `_mnemo.kind` of a task in the queue (13.1).
344pub const MNEMO_META_KIND_TASK: &str = "task";
345/// 13a: `_mnemo.kind` of a claim on a topic (13.3).
346pub const MNEMO_META_KIND_CLAIM: &str = "claim";
347/// 13a: `_mnemo.kind` of an agent's presence record (13.3).
348pub const MNEMO_META_KIND_PRESENCE: &str = "presence";
349/// 13a: the coordination kinds. Each is an ordinary record in the shared
350/// scope with the sentinel vector, never embedded, and never a hit in
351/// `recall`, the keyword index, the ANN or `about`: each is read through
352/// its own API (`docs/design/13a-coordination.md`, section 1).
353pub const COORDINATION_KINDS: [&str; 4] = [
354    MNEMO_META_KIND_MESSAGE,
355    MNEMO_META_KIND_TASK,
356    MNEMO_META_KIND_CLAIM,
357    MNEMO_META_KIND_PRESENCE,
358];
359
360/// 13a: who wrote a record, the writing handle's author
361/// ([`crate::Mnemo::set_author`], from `MNEMO_AGENT` in the CLI, the MCP
362/// server and the hooks). Stamped by the engine on new records, never set
363/// by a caller, and unproven until 13.4 signs it.
364pub const MNEMO_META_AUTHOR: &str = "_mnemo.author";
365/// 13a (13.5): `public`, `team` (the default when absent) or `private`. A
366/// filter, not a security boundary, until 13b. A caller may set it.
367pub const MNEMO_META_VISIBILITY: &str = "_mnemo.visibility";
368/// 13a (13.6): when the content was true, in unix seconds. A caller may
369/// set it; absent, it's the record's `created_at` (or `_mnemo.updated_at`).
370pub const MNEMO_META_AS_OF: &str = "_mnemo.as_of";
371/// 13a (13.6): when someone should look at the record again, in unix
372/// seconds. A caller may set it.
373pub const MNEMO_META_REVIEW_BY: &str = "_mnemo.review_by";
374/// 13a (AGENT-DEFAULT): on the manifest, the agent a write that names none
375/// is made for, in place of `default`. Set with
376/// [`crate::Mnemo::set_default_agent`]; a new brain's manifest has none.
377pub const MNEMO_META_DEFAULT_AGENT: &str = "_mnemo.default_agent";
378
379/// 13a (13.5): a record's visibility level: `_mnemo.visibility`, or `team`
380/// when it has none. A filter, not a security boundary: everyone holding
381/// the key reads every record.
382pub fn visibility_of(m: &Memory) -> &str {
383    match m
384        .metadata
385        .get(MNEMO_META_VISIBILITY)
386        .and_then(|v| v.as_str())
387    {
388        Some(v @ ("public" | "team" | "private")) => v,
389        _ => "team",
390    }
391}
392
393/// 13a (13.5): which visibility levels a read shows. By default public and
394/// team; private only when asked.
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
396pub struct VisibilitySet {
397    /// Show `public` records.
398    pub public: bool,
399    /// Show `team` records (and those with no level).
400    pub team: bool,
401    /// Show `private` records.
402    pub private: bool,
403}
404
405impl Default for VisibilitySet {
406    fn default() -> Self {
407        VisibilitySet::DEFAULT
408    }
409}
410
411impl VisibilitySet {
412    /// Public and team: what every read shows unless asked.
413    pub const DEFAULT: VisibilitySet = VisibilitySet {
414        public: true,
415        team: true,
416        private: false,
417    };
418    /// Every level.
419    pub const ALL: VisibilitySet = VisibilitySet {
420        public: true,
421        team: true,
422        private: true,
423    };
424
425    /// From a list of levels (`public`, `team`, `private`) or `all`, as a
426    /// surface's `--visibility` or `"visibility"` names them.
427    pub fn parse<S: AsRef<str>>(levels: &[S]) -> crate::Result<VisibilitySet> {
428        let mut v = VisibilitySet {
429            public: false,
430            team: false,
431            private: false,
432        };
433        for l in levels {
434            for part in l
435                .as_ref()
436                .split(',')
437                .map(str::trim)
438                .filter(|p| !p.is_empty())
439            {
440                match part {
441                    "public" => v.public = true,
442                    "team" => v.team = true,
443                    "private" => v.private = true,
444                    "all" => v = VisibilitySet::ALL,
445                    other => {
446                        return Err(crate::MnemoError::Invalid(format!(
447                            "{other:?} isn't a visibility level: public, team, private or all"
448                        )))
449                    }
450                }
451            }
452        }
453        if !(v.public || v.team || v.private) {
454            return Ok(VisibilitySet::DEFAULT);
455        }
456        Ok(v)
457    }
458
459    /// Whether a record's level is in the set.
460    pub fn shows(&self, m: &Memory) -> bool {
461        self.shows_level(visibility_of(m))
462    }
463
464    /// Whether a level is in the set.
465    pub fn shows_level(&self, level: &str) -> bool {
466        match level {
467            "public" => self.public,
468            "private" => self.private,
469            _ => self.team,
470        }
471    }
472}
473
474/// 13a: `YYYY-MM-DD` (UTC) for unix seconds.
475pub fn date_of(secs: i64) -> String {
476    let days = secs.div_euclid(86_400);
477    let z = days + 719_468;
478    let era = z.div_euclid(146_097);
479    let doe = z.rem_euclid(146_097);
480    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
481    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
482    let mp = (5 * doy + 2) / 153;
483    let d = doy - (153 * mp + 2) / 5 + 1;
484    let m = if mp < 10 { mp + 3 } else { mp - 9 };
485    let y = yoe + era * 400 + i64::from(m <= 2);
486    format!("{y:04}-{m:02}-{d:02}")
487}
488
489/// 13a: `YYYY-MM-DD HH:MM UTC` for unix seconds.
490pub fn date_time_of(secs: i64) -> String {
491    let r = secs.rem_euclid(86_400);
492    format!("{} {:02}:{:02} UTC", date_of(secs), r / 3600, r % 3600 / 60)
493}
494
495/// 13a (13.6): the per-kind freshness defaults, in seconds.
496pub mod stale_after {
497    /// An essence `state` or `next` item.
498    pub const ESSENCE_STATE_NEXT: i64 = 14 * 86_400;
499    /// An essence `open` item.
500    pub const ESSENCE_OPEN: i64 = 30 * 86_400;
501    /// An `active` task with no update.
502    pub const TASK_ACTIVE: i64 = 3 * 86_400;
503    /// A `blocked` task.
504    pub const TASK_BLOCKED: i64 = 7 * 86_400;
505    /// An `unread` message.
506    pub const MESSAGE_UNREAD: i64 = 3 * 86_400;
507}
508
509/// 13a (13.6): when a record went stale at `now`, if it has: past its
510/// `_mnemo.review_by` (which, when set, decides alone), or older than its
511/// kind's default (`stale_after`) measured from `_mnemo.as_of`, else its
512/// last edit, else `created_at`. A fact with no `review_by`, a claim, a
513/// presence record and a resolved or superseded item are never stale.
514pub fn stale_since(m: &Memory, now: i64) -> Option<i64> {
515    if m.metadata.contains_key(MNEMO_META_SUPERSEDED_BY) {
516        return None;
517    }
518    let num = |k: &str| m.metadata.get(k).and_then(|v| v.as_i64());
519    if let Some(r) = num(MNEMO_META_REVIEW_BY) {
520        return (now >= r).then_some(r);
521    }
522    let base = num(MNEMO_META_AS_OF)
523        .or_else(|| num(MNEMO_META_UPDATED_AT))
524        .unwrap_or(m.created_at);
525    let s = |k: &str| m.metadata.get(k).and_then(|v| v.as_str());
526    let after = match s(MNEMO_META_KIND) {
527        Some(MNEMO_META_KIND_ESSENCE) => {
528            if s(MNEMO_META_STATUS) == Some(status::RESOLVED) {
529                return None;
530            }
531            match s(MNEMO_META_SECTION) {
532                Some("state" | "next") => stale_after::ESSENCE_STATE_NEXT,
533                Some("open") => stale_after::ESSENCE_OPEN,
534                _ => return None,
535            }
536        }
537        Some(MNEMO_META_KIND_TASK) => {
538            let last = m
539                .metadata
540                .get(MNEMO_META_STATUS_HISTORY)
541                .and_then(|h| h.as_array())
542                .and_then(|h| h.last())
543                .and_then(|e| e.get("at"))
544                .and_then(|v| v.as_i64())
545                .unwrap_or(m.created_at);
546            let after = match s(MNEMO_META_STATUS) {
547                Some("active") => stale_after::TASK_ACTIVE,
548                Some("blocked") => stale_after::TASK_BLOCKED,
549                _ => return None,
550            };
551            let t = last + after;
552            return (now >= t).then_some(t);
553        }
554        Some(MNEMO_META_KIND_MESSAGE) => {
555            if s(MNEMO_META_STATUS) != Some(MESSAGE_UNREAD) {
556                return None;
557            }
558            let t = m.created_at + stale_after::MESSAGE_UNREAD;
559            return (now >= t).then_some(t);
560        }
561        _ => return None,
562    };
563    let t = base + after;
564    (now >= t).then_some(t)
565}
566
567/// 13a (13.1): a message's recipient: an agent id, `role:<role>`, or `all`.
568pub const MNEMO_META_TO: &str = "_mnemo.to";
569/// 13a (13.1): a message's sender, as it said (unproven until 13b).
570pub const MNEMO_META_FROM: &str = "_mnemo.from";
571/// 13a (13.1): the conversation a message belongs to, so replies share its
572/// hop count. Not `_mnemo.thread`, which names a thread archive.
573pub const MNEMO_META_CONVERSATION: &str = "_mnemo.conversation";
574/// 13a (13.1b): a message's hop count within its conversation (and its
575/// pair, for 10 minutes), for the wake-up hop cap.
576pub const MNEMO_META_HOPS: &str = "_mnemo.hops";
577/// 13a (13.1b): `sent`, `delivered`, `seen` or `done`.
578pub const MNEMO_META_DELIVERY: &str = "_mnemo.delivery";
579/// 13a: when a message was acked, in unix seconds (for pruning).
580pub const MNEMO_META_ACKED_AT: &str = "_mnemo.acked_at";
581/// 13a (13.3): a claim's topic.
582pub const MNEMO_META_TOPIC: &str = "_mnemo.topic";
583/// 13a (13.3): the agent holding a claim.
584pub const MNEMO_META_HOLDER: &str = "_mnemo.holder";
585/// 13a (13.3): a claim's token; `renew`, `release` and `check` need it.
586pub const MNEMO_META_CLAIM_TOKEN: &str = "_mnemo.claim_token";
587/// 13a (13.3): when a claim lapses, in unix seconds.
588pub const MNEMO_META_EXPIRES_AT: &str = "_mnemo.expires_at";
589/// 13a (13.3): a claim's lease, in seconds.
590pub const MNEMO_META_LEASE: &str = "_mnemo.lease";
591/// 13a (13.3): whether the holder had a presence lock when it claimed (the
592/// early lapse applies only then).
593pub const MNEMO_META_HOLDER_LOCK: &str = "_mnemo.holder_lock";
594/// 13a (13.3): when a taker first found the holder not alive.
595pub const MNEMO_META_DEAD_SEEN_AT: &str = "_mnemo.dead_seen_at";
596/// 13a (13.3): a presence record's agent.
597pub const MNEMO_META_AGENT: &str = "_mnemo.agent";
598/// 13a (13.3): the tool a presence record's agent runs in (`mcp`, `cli`).
599pub const MNEMO_META_TOOL: &str = "_mnemo.tool";
600/// 13a (13.3): when the agent last wrote, in unix seconds.
601pub const MNEMO_META_LAST_ACTIVE: &str = "_mnemo.last_active";
602/// 13a (13.3): whether the agent's process holds a presence lock, so `who`
603/// can probe it.
604pub const MNEMO_META_PRESENCE_LOCK: &str = "_mnemo.presence_lock";
605/// 13a (13.3): a claim's default lease (15 minutes).
606pub const CLAIM_TTL_DEFAULT: i64 = 15 * 60;
607/// 13a (13.3): a claim's shortest lease.
608pub const CLAIM_TTL_MIN: i64 = 30;
609/// 13a (13.3): a claim's longest lease (24 hours).
610pub const CLAIM_TTL_MAX: i64 = 24 * 3600;
611/// 13a (13.3): the most often `last_active` is written.
612pub const PRESENCE_EVERY_SECS: i64 = 60;
613/// 13a (13.3): how long a holder must be seen not alive, twice, before its
614/// claim lapses early.
615pub const CLAIM_LAPSE_GRACE_SECS: i64 = 10;
616/// 13a (13.3): a topic's limit, in bytes (one line).
617pub const CLAIM_TOPIC_MAX: usize = 200;
618
619/// 13a (13.1): a task's slug, its name (`step-4-tasks`).
620pub const MNEMO_META_SLUG: &str = "_mnemo.slug";
621/// 13a (13.1): the agent that took a task (`Mnemo::task_next`).
622pub const MNEMO_META_OWNER: &str = "_mnemo.owner";
623/// 13a (13.1): the agent that added a task; `ready → done` is its call.
624pub const MNEMO_META_CREATOR: &str = "_mnemo.creator";
625/// 13a (13.1): the slugs of the tasks a task waits for.
626pub const MNEMO_META_AFTER: &str = "_mnemo.after";
627/// 13a (13.1): the owner may go from `ready` to `done` without a sign-off.
628pub const MNEMO_META_PRE_APPROVED: &str = "_mnemo.pre_approved";
629/// 13a (13.1): a task's claim lease (2 hours), renewed by its owner's
630/// updates.
631pub const TASK_CLAIM_TTL: i64 = 2 * 3600;
632/// 13a: a slug's limit (it's 1 to 64 of `a-z`, `0-9`, `.`, `_`, `-`).
633pub const TASK_SLUG_MAX: usize = 64;
634/// 13a: the brief warns about an own task's claim that lapses within this.
635pub const TASK_CLAIM_WARN_SECS: i64 = 15 * 60;
636/// 13a: `export --git` leaves out tasks done more than this ago (30 days).
637pub const TASK_DONE_EXPORT_KEEP_SECS: i64 = 30 * 86_400;
638
639/// 13a (13.1b): the wake-up guardrails. At most this many wake-ups per
640/// recipient per hour; past it, items stay `sent` and are seen at the next
641/// turn or session start.
642pub const WAKE_PER_HOUR: usize = 12;
643/// 13a (13.1b): a recipient's cooldown between wake-ups, in seconds.
644pub const WAKE_COOLDOWN_SECS: i64 = 60;
645/// 13a (13.1b): a message wakes nobody when its two agents have exchanged
646/// this many messages, either way, in the last [`PAIR_BURST_SECS`].
647pub const PAIR_BURST: usize = 8;
648/// 13a (13.1b): the pair burst's window (10 minutes).
649pub const PAIR_BURST_SECS: i64 = 600;
650/// 13a (13.1b): an explicit reply whose hop count passes this wakes nobody.
651pub const HOP_CAP: u64 = 8;
652/// 13a (13.1b): the kill switch, on the manifest: `{"by", "at"}` while
653/// wake-ups are paused.
654pub const MNEMO_META_WAKE_PAUSED: &str = "_mnemo.wake_paused";
655/// 13a (13.1b): a presence record's recent wake-up times (the last hour).
656pub const MNEMO_META_WAKES: &str = "_mnemo.wakes";
657/// 13a (RB-012.6 item 4): the agents a message to a role or everyone, or a
658/// role's task, has been shown to.
659pub const MNEMO_META_SEEN_BY: &str = "_mnemo.seen_by";
660/// 13a (READY-NOTICE, v0.17.2): the agents a `ready` task has been shown
661/// to as waiting for their `done`. Apart from [`MNEMO_META_SEEN_BY`]: a
662/// creator of the task's own role was shown it while it was queued.
663pub const MNEMO_META_READY_SEEN_BY: &str = "_mnemo.ready_seen_by";
664/// 13a (13.1b): the claim expiry its holder was last warned about.
665pub const MNEMO_META_WARNED_EXPIRY: &str = "_mnemo.warned_expiry";
666
667/// 13a (13.1b): the delivery states, in order.
668pub mod delivery {
669    /// Written, not yet delivered by a wake-up.
670    pub const SENT: &str = "sent";
671    /// A wake-up reached the recipient's session.
672    pub const DELIVERED: &str = "delivered";
673    /// Shown to the recipient (the inbox, the per-turn hook).
674    pub const SEEN: &str = "seen";
675    /// Acked.
676    pub const DONE: &str = "done";
677}
678/// 13a: a message's status: `unread` until acked.
679pub const MESSAGE_UNREAD: &str = "unread";
680/// 13a: a message's status once acked.
681pub const MESSAGE_ACKED: &str = "acked";
682/// 13a: a message body's limit, in bytes; a bigger one belongs in a fact,
683/// named in `refs`.
684pub const MESSAGE_BODY_MAX: usize = 8 * 1024;
685/// 13a: a subject's limit, in bytes (one line).
686pub const MESSAGE_SUBJECT_MAX: usize = 200;
687/// 13a: a new message between the same two parties within this many seconds
688/// carries their last hop count on (the pair carry).
689pub const MESSAGE_PAIR_CARRY_SECS: i64 = 600;
690/// 13a: acked messages older than this are dropped by `compact` and
691/// `prune_messages` (30 days).
692pub const MESSAGE_ACKED_KEEP_SECS: i64 = 30 * 86_400;
693
694/// The visibility levels (13.5).
695pub const VISIBILITY_LEVELS: [&str; 3] = ["public", "team", "private"];
696
697/// 13a: the reserved keys a caller may set on a write (visibility and
698/// freshness), each checked by [`check_caller_key`]. Every other
699/// `_mnemo.*` key stays the engine's.
700pub const CALLER_KEYS: [&str; 3] = [
701    MNEMO_META_VISIBILITY,
702    MNEMO_META_AS_OF,
703    MNEMO_META_REVIEW_BY,
704];
705
706/// 13a: an agent id (`MNEMO_AGENT`, `_mnemo.default_agent`, a message's
707/// `to`): 1 to 64 of `[A-Za-z0-9._-]`. A role (`MNEMO_ROLE`) follows the
708/// same rule.
709pub fn valid_agent_id(s: &str) -> bool {
710    (1..=64).contains(&s.len())
711        && s.bytes()
712            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
713}
714
715/// Whether `key` is one of [`CALLER_KEYS`].
716pub fn is_caller_key(key: &str) -> bool {
717    CALLER_KEYS.contains(&key)
718}
719
720/// Check a caller-settable reserved key's value: a visibility level, or a
721/// whole number of unix seconds that isn't negative.
722pub fn check_caller_key(key: &str, value: &Value) -> std::result::Result<(), String> {
723    match key {
724        MNEMO_META_VISIBILITY => match value.as_str() {
725            Some(v) if VISIBILITY_LEVELS.contains(&v) => Ok(()),
726            _ => Err(format!(
727                "{key} must be one of public, team or private (got {value})"
728            )),
729        },
730        MNEMO_META_AS_OF | MNEMO_META_REVIEW_BY => match value.as_i64() {
731            Some(t) if t >= 0 => Ok(()),
732            _ => Err(format!(
733                "{key} must be a time in unix seconds, 0 or more (got {value})"
734            )),
735        },
736        _ => Err(format!("{key} isn't a key a caller may set")),
737    }
738}
739
740/// Whether a record is one of the coordination kinds ([`COORDINATION_KINDS`]).
741pub fn is_coordination(m: &Memory) -> bool {
742    m.metadata
743        .get(MNEMO_META_KIND)
744        .and_then(Value::as_str)
745        .is_some_and(|k| COORDINATION_KINDS.contains(&k))
746}
747
748/// v0.16.1: `true` on a turn whose content is only the markers a
749/// transcript reader makes for blocks it doesn't keep (`[thinking]`,
750/// `[tool_use name=…]`, `[tool_result ok, N bytes]`, `[image]`). Such a
751/// turn is kept in the thread, so `thread export` shows the whole flow,
752/// but it isn't embedded (it carries the sentinel vector) and `recall`
753/// never returns it, since it would match any query weakly. `recall`
754/// leaves out a marker-only turn written before v0.16.1 too, by its
755/// content.
756pub const MNEMO_META_MARKERS_ONLY: &str = "_mnemo.markers_only";
757
758/// Maximum content size for a single turn record before chunking kicks
759/// in (Phase 12.7a). 8 KB per chunk keeps each record small enough
760/// that the per-record page cost dominates — and so that a thread of
761/// mostly short messages ingests as one record each.
762pub const THREAD_TURN_CHUNK_BYTES: usize = 8 * 1024;
763
764/// Maximum content size for a tool-result turn before truncation
765/// (Phase 12.7a). Tool results frequently run tens of kilobytes;
766/// stored truncated with `_mnemo.sha256` + `_mnemo.length` so the
767/// original can be recovered (or verified) out-of-band.
768pub const THREAD_TOOL_RESULT_TRUNCATE_BYTES: usize = 16 * 1024;
769
770// ---------------------------------------------------------------------------
771// Phase 12.7b: status-record core + essence (timeline + sections). The
772// essence layer rides on the same reserved-metadata namespace as the
773// thread archive, so a file keeps the single `_mnemo.*` convention:
774//
775// - `_mnemo.kind = "essence"` identifies an essence record. Section
776//   is in `_mnemo.section`. Scope — thread or project — is in
777//   `_mnemo.thread` (string) or absent (`None` means project scope).
778// - `_mnemo.status` carries the lifecycle for section items
779//   (`"open"` → `"resolved"`). Timeline entries never get a status.
780// - `_mnemo.status_history` records the status transitions. One
781//   element per transition: `{"status": "...", "at": <unix_secs>}`.
782// - `_mnemo.refs` is an optional array of free-form reference
783//   strings (turn ids, memory ids, commits, paths).
784// ---------------------------------------------------------------------------
785
786/// Reserved `_mnemo.section` key — which essence section an item
787/// belongs to (Phase 12.7b). Values: `"timeline"`, `"intent"`,
788/// `"conventions"`, `"decisions"`, `"state"`, `"open"`, `"next"`,
789/// `"lessons"`. Timeline entries are append-only.
790pub const MNEMO_META_SECTION: &str = "_mnemo.section";
791
792/// Reserved `_mnemo.status` key — current status of a status-record.
793/// Values are per-kind (Phase 12.7b: essence uses `"open"` and
794/// `"resolved"`). Timeline entries never carry this.
795pub const MNEMO_META_STATUS: &str = "_mnemo.status";
796
797/// Reserved `_mnemo.status_history` key — array of status transitions,
798/// each `{"status": <str>, "at": <unix_secs>}`. Append-only — the
799/// first entry records creation, each later entry records a
800/// transition.
801pub const MNEMO_META_STATUS_HISTORY: &str = "_mnemo.status_history";
802
803/// Reserved `_mnemo.refs` key — optional array of free-form reference
804/// strings (turn ids, memory ids, commits, paths) attached to an
805/// essence record (Phase 12.7b).
806pub const MNEMO_META_REFS: &str = "_mnemo.refs";
807
808/// Marker value for `_mnemo.kind` on essence records (Phase 12.7b).
809pub const MNEMO_META_KIND_ESSENCE: &str = "essence";
810
811/// Maximum content length for a timeline entry (Phase 12.7b).
812/// Entries over this are rejected, not truncated — the planner's
813/// spec is explicit about this because truncation would lose the
814/// narrative, and splitting across records would lose ordering.
815pub const ESSENCE_TIMELINE_MAX_BYTES: usize = 600;
816
817/// Maximum content length for a section item (Phase 12.7b).
818/// intent / conventions / decisions / state / open / next / lessons
819/// all share the same single-line cap. Items over this are rejected.
820pub const ESSENCE_SECTION_MAX_BYTES: usize = 280;
821
822/// Default byte budget for [`crate::Mnemo::essence`] rendering
823/// (Phase 12.7b). Matches the planner's "max_bytes = 6144" spec,
824/// which sits comfortably below a 4K-token context window.
825pub const ESSENCE_DEFAULT_RENDER_BYTES: usize = 6144;
826
827/// Which essence section an item belongs to.
828///
829/// Rendering order is fixed at this type's declaration order:
830/// intent → conventions → decisions → state → open → next → lessons
831/// → timeline. See [`EssenceSection::render_order`] for the explicit
832/// list and the [`crate::Mnemo::essence`] docs for per-section rules
833/// (timeline is append-only, every other section is item-edited).
834#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
835pub enum EssenceSection {
836    /// What the thread is trying to do.
837    Intent,
838    /// How the user works — conventions that survive across threads.
839    Conventions,
840    /// Decisions made and why (newest first on render).
841    Decisions,
842    /// The current state of the work.
843    State,
844    /// Open problems.
845    Open,
846    /// What to do next.
847    Next,
848    /// Lessons learned — mistakes caught and their fixes.
849    Lessons,
850    /// Append-only milestone timeline. Entries capped at
851    /// [`ESSENCE_TIMELINE_MAX_BYTES`] and never editable.
852    Timeline,
853}
854
855impl EssenceSection {
856    /// Section → stable `_mnemo.section` string.
857    pub fn as_str(&self) -> &'static str {
858        match self {
859            EssenceSection::Intent => "intent",
860            EssenceSection::Conventions => "conventions",
861            EssenceSection::Decisions => "decisions",
862            EssenceSection::State => "state",
863            EssenceSection::Open => "open",
864            EssenceSection::Next => "next",
865            EssenceSection::Lessons => "lessons",
866            EssenceSection::Timeline => "timeline",
867        }
868    }
869
870    /// Parse a string from `_mnemo.section` into the typed enum.
871    /// Case-insensitive; returns `None` on unknown input.
872    pub fn parse(s: &str) -> Option<EssenceSection> {
873        match s.to_ascii_lowercase().as_str() {
874            "intent" => Some(EssenceSection::Intent),
875            "conventions" => Some(EssenceSection::Conventions),
876            "decisions" => Some(EssenceSection::Decisions),
877            "state" => Some(EssenceSection::State),
878            "open" => Some(EssenceSection::Open),
879            "next" => Some(EssenceSection::Next),
880            "lessons" => Some(EssenceSection::Lessons),
881            "timeline" => Some(EssenceSection::Timeline),
882            _ => None,
883        }
884    }
885
886    /// Fixed render order (intent → conventions → decisions → state
887    /// → open → next → lessons → timeline). The [`crate::Mnemo::essence`]
888    /// render walks this list, allocating a per-section byte budget
889    /// proportional to section importance in the user-centric order.
890    pub fn render_order() -> &'static [EssenceSection] {
891        &[
892            EssenceSection::Intent,
893            EssenceSection::Conventions,
894            EssenceSection::Decisions,
895            EssenceSection::State,
896            EssenceSection::Open,
897            EssenceSection::Next,
898            EssenceSection::Lessons,
899            EssenceSection::Timeline,
900        ]
901    }
902
903    /// `true` for sections whose items carry an `open → resolved`
904    /// status lifecycle (every section except [`EssenceSection::Timeline`]).
905    pub fn has_status_lifecycle(&self) -> bool {
906        !matches!(self, EssenceSection::Timeline)
907    }
908
909    /// Per-section byte cap for new items. Timeline: 600 bytes.
910    /// Every other section: 280 bytes.
911    pub fn item_max_bytes(&self) -> usize {
912        match self {
913            EssenceSection::Timeline => ESSENCE_TIMELINE_MAX_BYTES,
914            _ => ESSENCE_SECTION_MAX_BYTES,
915        }
916    }
917}
918
919/// Scope selector for an essence item (Phase 12.7b). Thread-scoped
920/// items belong to one `_mnemo.thread`; project-scoped items are
921/// shared across every thread in the file.
922#[derive(Debug, Clone, PartialEq, Eq, Hash)]
923pub enum EssenceScope {
924    /// Belongs to one thread (the string). Shows up in that
925    /// thread's render only.
926    Thread(String),
927    /// Shared across every thread in the file. Shows up in every
928    /// thread's render, and in the `about` briefing: the CLI and MCP
929    /// `about` append the project render after the manifest, from
930    /// `Mnemo::about_essence()` (12.7d).
931    Project,
932}
933
934/// Status values the essence section supports (Phase 12.7b). More
935/// kinds (tasks: `queued → active → ready → done | blocked`;
936/// findings: `open → accepted | deferred | rejected | needs-user →
937/// verified`) ship with Phase 13 reusing the same status-record
938/// core; the transition tables for those are declared as constants
939/// in this crate but currently unused.
940pub mod status {
941    /// Freshly-added section item.
942    pub const OPEN: &str = "open";
943    /// The user-facing concern has been addressed.
944    pub const RESOLVED: &str = "resolved";
945}
946
947/// Task transition table (13a step 4, `Mnemo::task_update`).
948/// `queued → active → ready → done`, or `active → blocked`; the back
949/// edges are `blocked → active` and (R-010.7, RB-012.3) `active → queued`
950/// and `blocked → queued`, for an owner handing a task back or anyone
951/// requeueing an abandoned one.
952/// `queued → active` happens only through `Mnemo::task_next`.
953pub const TASK_TRANSITIONS: &[(&str, &str)] = &[
954    ("queued", "active"),
955    ("active", "ready"),
956    ("active", "blocked"),
957    ("blocked", "active"),
958    ("active", "queued"),
959    ("blocked", "queued"),
960    ("ready", "done"),
961];
962
963/// 13a (13.1): the task statuses.
964pub mod task_status {
965    /// Waiting for an agent of its role to take it.
966    pub const QUEUED: &str = "queued";
967    /// Taken: its owner holds its claim.
968    pub const ACTIVE: &str = "active";
969    /// Its owner finished; waiting for its creator's `done`.
970    pub const READY: &str = "ready";
971    /// Done.
972    pub const DONE: &str = "done";
973    /// Its owner is stuck.
974    pub const BLOCKED: &str = "blocked";
975}
976
977/// Finding transition table (declared for Phase 13; currently unused
978/// in the engine). `open → {accepted | deferred | rejected |
979/// needs-user} → verified`.
980pub const FINDING_TRANSITIONS: &[(&str, &str)] = &[
981    ("open", "accepted"),
982    ("open", "deferred"),
983    ("open", "rejected"),
984    ("open", "needs-user"),
985    ("accepted", "verified"),
986    ("deferred", "verified"),
987    ("needs-user", "verified"),
988];
989
990/// Essence transition table for Phase 12.7b. Only `open → resolved`
991/// is allowed. Timeline entries don't use this (they're append-only
992/// and have no status).
993pub const ESSENCE_TRANSITIONS: &[(&str, &str)] = &[(status::OPEN, status::RESOLVED)];
994
995// ---------------------------------------------------------------------------
996// Phase 12.7c: continuation + commit_deltas
997// ---------------------------------------------------------------------------
998
999/// Reserved `_mnemo.continues` key (Phase 12.7c). Set on a
1000/// thread-start marker record to point at the previous thread whose
1001/// context the new thread continues from. Value: the prior thread id
1002/// (string). Rendering a continued thread pulls the prior thread's
1003/// open items, `next` and last-N timeline entries ahead of the new
1004/// thread's own essence.
1005pub const MNEMO_META_CONTINUES: &str = "_mnemo.continues";
1006
1007/// Marker value for `_mnemo.kind` on a thread-start record (one per
1008/// `thread_start(new, --from old)` call, carrying the link in
1009/// `_mnemo.continues`).
1010pub const MNEMO_META_KIND_THREAD_LINK: &str = "thread_link";
1011
1012/// How many timeline entries from the predecessor thread the
1013/// continuation render pulls in (Phase 12.7c). Small enough to keep
1014/// the render under the default 6 KB budget, large enough to carry a
1015/// handful of milestones.
1016pub const CONTINUATION_TIMELINE_ENTRIES: usize = 10;
1017
1018/// What [`crate::Mnemo::commit_deltas`] does with the `turns` carried
1019/// in the batch (Phase 12.7c).
1020#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1021pub enum TurnPolicy {
1022    /// Archive every turn in the batch via
1023    /// [`crate::Mnemo::ingest_thread`]. Default — matches the
1024    /// "lossless flow preservation" story of 12.7.
1025    #[default]
1026    Archive,
1027    /// Store turns with a TTL (unix-seconds expiry).
1028    ExpireAfter(i64),
1029    /// Drop turns on the floor (no archive record written).
1030    Drop,
1031}
1032
1033/// Which op a [`EssenceOp`] carries. Mirrors the per-method
1034/// `Mnemo::essence_*` surface so one batch can mix section + timeline
1035/// edits in one call.
1036#[derive(Debug, Clone, PartialEq, Eq)]
1037pub enum EssenceOpKind {
1038    /// Section item add (any section except timeline).
1039    Add,
1040    /// Append-only timeline entry.
1041    AppendTimeline,
1042    /// In-place update of an existing section item.
1043    Update,
1044    /// Transition an item `open → resolved`.
1045    Resolve,
1046    /// Soft-delete an item.
1047    Remove,
1048}
1049
1050/// One essence op inside a [`CommitBatch`] (Phase 12.7c). Validation
1051/// (missing/extra fields per kind) runs up front in
1052/// [`crate::Mnemo::commit_deltas`] — a single bad op aborts the
1053/// whole batch before any write lands.
1054#[derive(Debug, Clone)]
1055pub struct EssenceOp {
1056    /// Which op to apply.
1057    pub kind: EssenceOpKind,
1058    /// Scope — required for [`EssenceOpKind::Add`] and
1059    /// [`EssenceOpKind::AppendTimeline`].
1060    pub scope: Option<EssenceScope>,
1061    /// Section — required for [`EssenceOpKind::Add`].
1062    pub section: Option<EssenceSection>,
1063    /// Target record id — required for [`EssenceOpKind::Update`],
1064    /// [`EssenceOpKind::Resolve`], [`EssenceOpKind::Remove`].
1065    pub id: Option<Ulid>,
1066    /// Content text — required for [`EssenceOpKind::Add`],
1067    /// [`EssenceOpKind::AppendTimeline`], [`EssenceOpKind::Update`].
1068    pub text: Option<String>,
1069    /// Optional refs for ops that carry text.
1070    pub refs: Option<Vec<String>>,
1071}
1072
1073/// One keyed fact inside a [`CommitBatch`] (Phase 12.7c).
1074#[derive(Debug, Clone)]
1075pub struct KeyedMemory {
1076    /// The memory to store. An **empty `vector`** means "embed
1077    /// `content` with the registered embedder" (12.7d): every such fact
1078    /// in a batch is embedded together in one `Embedder::embed` call.
1079    pub memory: Memory,
1080    /// Optional 12.1 upsert key.
1081    pub key: Option<String>,
1082}
1083
1084/// Atomic write batch for [`crate::Mnemo::commit_deltas`]
1085/// (Phase 12.7c). The planner's "one call that composes facts +
1086/// essence + turns" shape: everything validates up front, then every
1087/// write runs under a single `flush()`.
1088#[derive(Debug, Clone, Default)]
1089pub struct CommitBatch {
1090    /// Keyed-or-not facts to remember (12.1).
1091    pub facts: Vec<KeyedMemory>,
1092    /// Essence ops to apply (12.7b).
1093    pub essence_ops: Vec<EssenceOp>,
1094    /// Thread archive turns to ingest (12.7a).
1095    pub turns: Vec<ThreadTurn>,
1096    /// Destination thread id for `turns`. Required when `turns` is
1097    /// non-empty.
1098    pub thread_id: Option<String>,
1099    /// What to do with `turns` — defaults to `Archive`.
1100    pub turn_policy: TurnPolicy,
1101}
1102
1103/// Result of [`crate::Mnemo::commit_deltas`] (Phase 12.7c).
1104#[derive(Debug, Clone, Default, PartialEq, Eq)]
1105pub struct CommitReport {
1106    /// Facts added (plain or `WriteOutcome::Added`).
1107    pub facts_added: usize,
1108    /// Facts whose keyed write superseded a prior record.
1109    pub facts_superseded: usize,
1110    /// Keyed facts whose write was a no-op (matched live record).
1111    pub facts_unchanged: usize,
1112    /// Essence ops that produced an Added/Updated result.
1113    pub essence_ops_applied: usize,
1114    /// Essence ops that were no-ops (e.g. `resolve` on resolved).
1115    pub essence_ops_unchanged: usize,
1116    /// Turn records written to the archive.
1117    pub turns_added: usize,
1118    /// Source turns skipped by the archive's idempotence check.
1119    pub turns_skipped: usize,
1120    /// Source turns whose content was truncated at the 16 KB cap.
1121    pub turns_truncated: usize,
1122    /// Source turns split into multiple 8 KB chunks.
1123    pub turns_chunked: usize,
1124}
1125
1126/// Patch body for [`crate::Mnemo::update`] (Phase 12.1): every field is
1127/// optional, and only the `Some(...)` fields overwrite the corresponding
1128/// field on the target memory. All fields can be set independently.
1129///
1130/// `content` paired with `vector` updates both at once — the engine does
1131/// not re-embed under `update` (use `update_text` for that). A `content`
1132/// change without a new `vector` is rejected to prevent the embedding
1133/// drifting silently out of sync with the text.
1134///
1135/// `metadata` **replaces** the full user-metadata map — the engine's own
1136/// `_mnemo.*` reserved keys on the target record are preserved across
1137/// the replacement (updated-at timestamp, supersession markers, etc.).
1138/// Passing an empty map drops every user-visible metadata key but keeps
1139/// the reserved ones.
1140///
1141/// `ttl_secs` is `Option<Option<i64>>` so a caller can distinguish
1142/// "leave it alone" (`None`) from "set it to a value" (`Some(Some(s))`)
1143/// and "clear it" (`Some(None)`).
1144#[derive(Debug, Clone, Default)]
1145pub struct MemoryPatch {
1146    /// New text content. If set, a matching `vector` must also be set
1147    /// (or call `update_text`, which re-embeds through the registered
1148    /// embedder).
1149    pub content: Option<String>,
1150    /// New embedding. Must match the database's dimensionality.
1151    pub vector: Option<Vec<f32>>,
1152    /// New importance in `[0, 1]`.
1153    pub importance: Option<f32>,
1154    /// Replace the memory type.
1155    pub memory_type: Option<MemoryType>,
1156    /// Replace the user-visible metadata (preserves `_mnemo.*` reserved
1157    /// keys).
1158    pub metadata: Option<Map<String, Value>>,
1159    /// Change the TTL. Outer `None` → leave unchanged; `Some(Some(s))` →
1160    /// set TTL to `s`; `Some(None)` → clear any existing TTL.
1161    pub ttl_secs: Option<Option<i64>>,
1162    /// 13a: set these caller keys ([`CALLER_KEYS`]: visibility, `as_of`,
1163    /// `review_by`), each checked, without replacing the user metadata. A
1164    /// `null` value removes the key.
1165    pub caller_keys: Option<Map<String, Value>>,
1166}
1167
1168/// One turn fed into [`crate::Mnemo::ingest_thread`] (Phase 12.7a).
1169///
1170/// The caller supplies `turn_id` (opaque, for idempotence), `role`
1171/// (the transcript's author tag; no interpretation), and `content`
1172/// (UTF-8 text; chunked at 8 KB, or truncated at 16 KB when `role ==
1173/// "tool"`). The ingest path assigns `_mnemo.seq` monotonically within
1174/// the destination thread and embeds through the registered embedder.
1175///
1176/// Tool messages whose content exceeds [`THREAD_TOOL_RESULT_TRUNCATE_BYTES`]
1177/// are stored truncated. Other roles over [`THREAD_TURN_CHUNK_BYTES`]
1178/// are chunked.
1179#[derive(Debug, Clone)]
1180pub struct ThreadTurn {
1181    /// Opaque per-turn id from the source transcript (e.g. a Claude
1182    /// Code message uuid). Used for `ingest_thread`'s idempotence
1183    /// check: a turn whose `turn_id` already exists in the target
1184    /// thread is skipped.
1185    pub turn_id: String,
1186    /// Author role verbatim from the transcript (`"user"`,
1187    /// `"assistant"`, `"system"`, `"tool"`, …). `"tool"` triggers
1188    /// the 16 KB truncation branch; all other roles go through the
1189    /// 8 KB chunking branch.
1190    pub role: String,
1191    /// UTF-8 message content.
1192    pub content: String,
1193    /// Optional caller-supplied creation timestamp (unix seconds).
1194    /// If `None`, the ingest path uses `now_secs()` so the record's
1195    /// `created_at` still sorts the thread in order. Transcripts
1196    /// that carry a per-turn timestamp should pass it through so a
1197    /// future `thread export --by-time` can honour it.
1198    pub timestamp: Option<i64>,
1199}
1200
1201/// One turn of a thread's archive in the **ingest shape** (Phase 12.7d),
1202/// as returned by [`crate::Mnemo::thread_export_turns`] and by Python
1203/// `db.thread_export`, MCP `thread_export` and `mnemo thread export`.
1204///
1205/// Turns come back in `_mnemo.seq` order, one entry per source turn: the
1206/// 8 KB chunks of a long turn are joined back into one `content`, so
1207/// feeding the list to `ingest_thread` (same thread: every turn is
1208/// skipped; a new thread: the turns are re-chunked identically) round
1209/// trips. A tool result that was truncated at 16 KB carries `sha256` and
1210/// `original_length` of the original content.
1211#[derive(Debug, Clone, PartialEq, Eq)]
1212pub struct ExportedTurn {
1213    /// Source `turn_id` (`_mnemo.turn_id`).
1214    pub turn_id: String,
1215    /// Author role (`_mnemo.role`).
1216    pub role: String,
1217    /// Stored text, with chunks joined in `_mnemo.part` order.
1218    pub content: String,
1219    /// The turn's timestamp (unix seconds; the record's `created_at`).
1220    pub timestamp: i64,
1221    /// Hex SHA-256 of the original content, set only for a truncated
1222    /// tool result.
1223    pub sha256: Option<String>,
1224    /// Byte length of the original content, set only for a truncated
1225    /// tool result.
1226    pub original_length: Option<u64>,
1227}
1228
1229impl ExportedTurn {
1230    /// The JSON object shared by the MCP tool and the CLI JSONL export:
1231    /// `{turn_id, role, content, timestamp}` plus `sha256` and
1232    /// `original_length` when the turn was truncated.
1233    pub fn to_json(&self) -> serde_json::Value {
1234        let mut obj = serde_json::json!({
1235            "turn_id": self.turn_id,
1236            "role": self.role,
1237            "content": self.content,
1238            "timestamp": self.timestamp,
1239        });
1240        if let Some(sha) = &self.sha256 {
1241            obj["sha256"] = serde_json::Value::String(sha.clone());
1242        }
1243        if let Some(len) = self.original_length {
1244            obj["original_length"] = serde_json::Value::Number(len.into());
1245        }
1246        obj
1247    }
1248}
1249
1250/// Result of one [`crate::Mnemo::ingest_thread`] call (Phase 12.7a).
1251#[derive(Debug, Clone, Default, PartialEq, Eq)]
1252pub struct IngestReport {
1253    /// Number of **new** records written (turn chunks after chunking
1254    /// / truncation). A long turn counts as however many chunks it
1255    /// produced.
1256    pub added_records: usize,
1257    /// Number of **source turns** that already had a record in the
1258    /// target thread and were skipped by the idempotence check.
1259    pub skipped_existing_turns: usize,
1260    /// Number of turns whose content was truncated at the 16 KB cap.
1261    /// Only `role == "tool"` turns can trigger this branch.
1262    pub truncated_turns: usize,
1263    /// Number of turns that were split into multiple chunks at the
1264    /// 8 KB boundary. A truncated turn counts as 0 here even if its
1265    /// pre-truncation content would have chunked.
1266    pub chunked_turns: usize,
1267}
1268
1269/// Scope selector for a keyed slot (Phase 12.1.1). A keyed
1270/// `remember`'s slot is always identified by `(scope_owner, key)`:
1271/// `Private(agent_id)` slots are per-agent, `Shared` slots are per-file.
1272/// `history_in(key, scope)` uses the same selector so the lookup matches
1273/// the write exactly.
1274///
1275/// The convenience [`crate::Mnemo::history`] is equivalent to
1276/// `history_in(key, KeyScope::Private(agent.unwrap_or("default")))` —
1277/// i.e. `history(key, None)` resolves to the default agent's private
1278/// slot, matching the `remember(…, agent_id=None, scope=Private, key=K)`
1279/// write path. Use [`crate::Mnemo::history_in`] with
1280/// [`KeyScope::Shared`] when you need the shared slot.
1281#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1282pub enum KeyScope {
1283    /// Per-agent slot. The agent id is the one carried on `Memory.agent_id`
1284    /// at write time; `remember` with no explicit agent uses `"default"`.
1285    Private(String),
1286    /// Per-file slot shared across every agent.
1287    Shared,
1288}
1289
1290impl KeyScope {
1291    /// Default agent id used when `Memory::new(...)` is called without
1292    /// `.with_agent(...)` — same `"default"` the [`Memory::new`]
1293    /// constructor seeds into `Memory.agent_id`.
1294    pub const DEFAULT_AGENT: &'static str = "default";
1295
1296    /// Build the private slot for the default agent. Shorthand for
1297    /// `KeyScope::Private(KeyScope::DEFAULT_AGENT.to_string())`.
1298    pub fn private_default() -> Self {
1299        KeyScope::Private(Self::DEFAULT_AGENT.to_string())
1300    }
1301}
1302
1303/// Outcome of a 12.1 write operation (`remember` with `key`, or `update`).
1304///
1305/// Plain `remember` without a key always returns a ULID, not a
1306/// `WriteOutcome`, because supersession and NOOP detection are tied to
1307/// the key slot.
1308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1309pub enum WriteOutcome {
1310    /// Keyed write with no prior record for this slot. A brand-new record
1311    /// was inserted, no record was superseded.
1312    Added,
1313    /// Keyed write whose content / type / importance / user metadata
1314    /// differs from the live record for this slot. A new record was
1315    /// inserted and the prior one was marked
1316    /// `_mnemo.superseded_by` / `_mnemo.invalid_at`.
1317    Superseded,
1318    /// No-op: the incoming keyed write is byte-equal to the live record
1319    /// for this slot (content, memory type, importance, user metadata).
1320    /// No record was written and no catalog page was dirtied. The
1321    /// returned id is the existing record's id.
1322    Unchanged,
1323    /// In-place `update`: fields changed on the target record. The record
1324    /// was rewritten copy-on-write so the previous version remains
1325    /// visible through snapshots.
1326    Updated,
1327}
1328
1329// ---------------------------------------------------------------------------
1330// Phase 12.6: recall filters (session_id + per-metadata-key conditions)
1331// ---------------------------------------------------------------------------
1332
1333/// One AND-ed condition applied to a candidate memory's metadata during
1334/// filtered recall (Phase 12.6). Terms are combined conjunctively — a
1335/// memory passes the filter only if *every* term evaluates true against
1336/// its `metadata` map. See [`Filter`] for the surface API.
1337///
1338/// Values use `serde_json::Value` so the same term shape serializes
1339/// cleanly through the MCP / Python / CLI bridges without a parallel
1340/// enum per surface.
1341#[derive(Debug, Clone)]
1342pub enum FilterTerm {
1343    /// The memory's `metadata[key]` must be set to any value.
1344    Exists(String),
1345    /// `metadata[key]` must equal this JSON value (strict JSON equality:
1346    /// strings compare case-sensitively, numbers compare as f64).
1347    Eq(String, Value),
1348    /// `metadata[key]` must equal one of these JSON values.
1349    In(String, Vec<Value>),
1350    /// `metadata[key]` must be a number in `[min, max]` (inclusive on
1351    /// both ends; `None` on either bound means "no bound on that side").
1352    /// A non-numeric metadata value fails the term.
1353    Range {
1354        /// Metadata key.
1355        key: String,
1356        /// Lower bound (inclusive) — `None` means unbounded below.
1357        min: Option<f64>,
1358        /// Upper bound (inclusive) — `None` means unbounded above.
1359        max: Option<f64>,
1360    },
1361}
1362
1363/// Pre-scoring filter applied by [`crate::Mnemo::recall`] (Phase 12.6).
1364///
1365/// `session_id` restricts candidates to a single session (when the
1366/// memory's `session_id` is set). The `terms` are AND-ed metadata
1367/// conditions evaluated against each candidate's `metadata` map; see
1368/// [`FilterTerm`] for the shapes.
1369///
1370/// When an ANN index is present, the filter is applied *after* the ANN
1371/// shortlist step, so a selective filter can starve the result below
1372/// `top_k`. Recall handles that automatically via the Phase 12.1
1373/// short-results-on-indexed-path fix (widen 2×, then exact scan).
1374#[derive(Debug, Clone, Default)]
1375pub struct Filter {
1376    /// Only candidates whose `Memory.session_id` equals this value.
1377    /// Candidates without a session_id are excluded when this is set.
1378    pub session_id: Option<String>,
1379    /// AND-ed metadata conditions. Empty → no metadata constraints.
1380    pub terms: Vec<FilterTerm>,
1381}
1382
1383impl Filter {
1384    /// Builder helper: a filter that keeps only memories in `session`.
1385    pub fn new_session(session: impl Into<String>) -> Self {
1386        Self {
1387            session_id: Some(session.into()),
1388            terms: Vec::new(),
1389        }
1390    }
1391
1392    /// Restrict to one session_id (builder form).
1393    pub fn with_session(mut self, session: impl Into<String>) -> Self {
1394        self.session_id = Some(session.into());
1395        self
1396    }
1397
1398    /// Require `metadata[key]` to exist (any value).
1399    pub fn metadata_exists(mut self, key: impl Into<String>) -> Self {
1400        self.terms.push(FilterTerm::Exists(key.into()));
1401        self
1402    }
1403
1404    /// Require `metadata[key]` to equal `value`.
1405    pub fn metadata_eq(mut self, key: impl Into<String>, value: Value) -> Self {
1406        self.terms.push(FilterTerm::Eq(key.into(), value));
1407        self
1408    }
1409
1410    /// Require `metadata[key]` to be one of `values`.
1411    pub fn metadata_in(mut self, key: impl Into<String>, values: Vec<Value>) -> Self {
1412        self.terms.push(FilterTerm::In(key.into(), values));
1413        self
1414    }
1415
1416    /// Require `metadata[key]` to be a number in `[min, max]`.
1417    pub fn metadata_range(
1418        mut self,
1419        key: impl Into<String>,
1420        min: Option<f64>,
1421        max: Option<f64>,
1422    ) -> Self {
1423        self.terms.push(FilterTerm::Range {
1424            key: key.into(),
1425            min,
1426            max,
1427        });
1428        self
1429    }
1430
1431    /// `true` iff the filter has no terms and no `session_id`. The
1432    /// recall hot path uses this to skip the per-candidate filter
1433    /// check entirely.
1434    pub fn is_empty(&self) -> bool {
1435        self.session_id.is_none() && self.terms.is_empty()
1436    }
1437
1438    /// Phase 12.7a: `true` iff the filter mentions any reserved
1439    /// `_mnemo.*` metadata key. Used by `recall` to decide whether
1440    /// to default-exclude thread-archive turns
1441    /// (`_mnemo.kind = "turn"`). A caller that wants turns in the
1442    /// result opts in by adding any `_mnemo.*` term to the filter
1443    /// — equality, `$in`, `$exists`, or range — because those are the
1444    /// only queries that can usefully target turn records.
1445    pub fn mentions_mnemo_meta(&self) -> bool {
1446        self.terms.iter().any(|term| {
1447            let key = match term {
1448                FilterTerm::Exists(k) => k,
1449                FilterTerm::Eq(k, _) => k,
1450                FilterTerm::In(k, _) => k,
1451                FilterTerm::Range { key, .. } => key,
1452            };
1453            key.starts_with(MNEMO_META_NS)
1454        })
1455    }
1456
1457    /// Evaluate the filter against one memory. Returns `true` if the
1458    /// memory passes every term.
1459    pub fn matches(&self, m: &Memory) -> bool {
1460        if let Some(s) = &self.session_id {
1461            match &m.session_id {
1462                Some(ms) if ms == s => {}
1463                _ => return false,
1464            }
1465        }
1466        for term in &self.terms {
1467            if !term_matches(term, &m.metadata) {
1468                return false;
1469            }
1470        }
1471        true
1472    }
1473}
1474
1475fn term_matches(term: &FilterTerm, metadata: &Map<String, Value>) -> bool {
1476    match term {
1477        FilterTerm::Exists(key) => metadata.contains_key(key),
1478        FilterTerm::Eq(key, v) => metadata.get(key).is_some_and(|got| values_equal(got, v)),
1479        FilterTerm::In(key, options) => metadata
1480            .get(key)
1481            .is_some_and(|got| options.iter().any(|opt| values_equal(got, opt))),
1482        FilterTerm::Range { key, min, max } => metadata
1483            .get(key)
1484            .and_then(|v| v.as_f64())
1485            .is_some_and(|n| min.is_none_or(|m_| n >= m_) && max.is_none_or(|m_| n <= m_)),
1486    }
1487}
1488
1489/// JSON value equality for filter terms. serde_json's `Value: PartialEq`
1490/// compares numbers by exact representation (integer vs float). The
1491/// filter surface should treat `5` and `5.0` as equal, so we compare
1492/// numbers through `as_f64` when both sides are numbers; everything
1493/// else falls back to structural equality.
1494fn values_equal(a: &Value, b: &Value) -> bool {
1495    match (a, b) {
1496        (Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
1497            (Some(xf), Some(yf)) => (xf - yf).abs() < f64::EPSILON,
1498            _ => x == y,
1499        },
1500        (x, y) => x == y,
1501    }
1502}
1503
1504/// Distance/similarity metric for vector comparison.
1505#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1506pub enum Metric {
1507    /// Cosine similarity (orientation only).
1508    Cosine,
1509    /// Negative Euclidean distance, mapped into a `(0,1]` similarity.
1510    L2,
1511    /// Raw dot product.
1512    Dot,
1513}
1514
1515/// Compute a *similarity* (higher = more relevant) under the given metric.
1516pub fn similarity(metric: Metric, a: &[f32], b: &[f32]) -> f32 {
1517    match metric {
1518        Metric::Cosine => cosine(a, b),
1519        Metric::Dot => dot(a, b),
1520        Metric::L2 => {
1521            let d = euclidean(a, b);
1522            1.0 / (1.0 + d)
1523        }
1524    }
1525}
1526
1527fn dot(a: &[f32], b: &[f32]) -> f32 {
1528    a.iter().zip(b).map(|(x, y)| x * y).sum()
1529}
1530
1531/// Cosine similarity in `[-1.0, 1.0]`; returns `0.0` if either vector
1532/// has zero magnitude. `pub(crate)` so [`crate::Mnemo::cache_get_semantic`]
1533/// (Phase 10.2) can reuse the same scoring routine that recall uses,
1534/// keeping the two paths semantically identical.
1535pub(crate) fn cosine(a: &[f32], b: &[f32]) -> f32 {
1536    let na = dot(a, a).sqrt();
1537    let nb = dot(b, b).sqrt();
1538    if na == 0.0 || nb == 0.0 {
1539        0.0
1540    } else {
1541        dot(a, b) / (na * nb)
1542    }
1543}
1544
1545fn euclidean(a: &[f32], b: &[f32]) -> f32 {
1546    a.iter()
1547        .zip(b)
1548        .map(|(x, y)| (x - y) * (x - y))
1549        .sum::<f32>()
1550        .sqrt()
1551}
1552
1553/// Weights for the multi-signal recall score (scoring v2, shipped in
1554/// v0.7.0).
1555///
1556/// ```text
1557/// score = similarity
1558///       + max(similarity, 0)
1559///         · ( β · recency
1560///           + γ · (importance − 0.5)
1561///           + δ · tanh(access_count / 5) )
1562///
1563/// recency = exp( -ln(2) · age_secs / half_life_secs )
1564/// age_secs = now - memory.created_at
1565/// ```
1566///
1567/// Design notes (from the 2026-11-06 scoring-v2 bake-off; see the
1568/// `ranking_v2` harness at `mnemo/examples/ranking_v2.rs`):
1569/// * **Similarity-gated.** The recency / importance / usage terms are
1570///   multiplied by `max(similarity, 0)`, so a stale-but-semantically-off
1571///   memory can't ride recency or importance past a semantically-on-point
1572///   one. Pre-v0.7.0 scoring was purely additive.
1573/// * **Importance is centered at 0.5.** A default-importance memory
1574///   contributes zero importance bonus; importance only pushes a score up
1575///   or down from that reference point.
1576/// * **Usage is saturating.** `tanh(uses/5)` caps the feedback bonus so
1577///   a heavily-returned memory can't keep accumulating weight past a
1578///   plateau. At 5 uses the bonus is ~76% of its asymptote; at 10, ~96%.
1579/// * **Recency is decoupled from the feedback loop.** Age is measured
1580///   from `created_at`, not `accessed_at`, so a `recall()` call does not
1581///   bump its own results' recency scores on later queries.
1582///
1583/// The output of this scorer is on a **different scale** from the
1584/// pre-v0.7.0 formula. Callers that compared raw scores to a fixed
1585/// threshold should re-pick the threshold against the new scale.
1586#[derive(Clone, Copy, Debug)]
1587pub struct ScoreWeights {
1588    /// Weight on semantic similarity. Kept in the struct for calibration
1589    /// hooks and symmetry with the other weights; scoring v2 always uses
1590    /// it as `1.0` because the leading `similarity` term is ungated and
1591    /// the whole score sits on the cosine-similarity scale by design.
1592    pub alpha: f32,
1593    /// Weight on the recency bonus (multiplied by `max(sim, 0)`).
1594    pub beta: f32,
1595    /// Weight on the importance bonus `(importance − 0.5)`, centered at
1596    /// the default-importance 0.5 (multiplied by `max(sim, 0)`).
1597    pub gamma: f32,
1598    /// Weight on the saturating usage bonus `tanh(access_count / 5)`
1599    /// (multiplied by `max(sim, 0)`).
1600    pub delta: f32,
1601    /// Half-life of the recency term, in seconds.
1602    pub half_life_secs: f32,
1603}
1604
1605impl Default for ScoreWeights {
1606    fn default() -> Self {
1607        // Tuned on the Phase 6 corpus + the ranking_v2 age-spread
1608        // fixture; see `ranking_v2.checks` in perf_v0.5.0.json.
1609        Self {
1610            alpha: 1.0,
1611            beta: 0.3,
1612            gamma: 0.2,
1613            delta: 0.1,
1614            half_life_secs: 7.0 * 24.0 * 3600.0,
1615        }
1616    }
1617}
1618
1619/// Saturation constant K for the usage term `tanh(access_count / K)`.
1620/// K = 5 means ~76% of the asymptote at 5 uses and ~96% at 10 — matches
1621/// the "a few repeats is signal; past that it's a habit" intuition.
1622const USAGE_SAT_K: f32 = 5.0;
1623
1624impl ScoreWeights {
1625    /// Combine the four signals into a single score. See the struct docs
1626    /// for the full formula and the scoring-v2 rationale.
1627    pub fn score(&self, similarity: f32, age_secs: f32, importance: f32, access_count: u32) -> f32 {
1628        // Recency is in [0, 1]: 1.0 at age 0, 0.5 at one half-life, etc.
1629        let recency = (-std::f32::consts::LN_2 * age_secs.max(0.0) / self.half_life_secs).exp();
1630        // Saturating usage in [0, 1); tanh caps feedback-loop drift.
1631        let usage = (access_count as f32 / USAGE_SAT_K).tanh();
1632        // Gate the non-similarity bonuses by `max(sim, 0)` so a
1633        // negative-cosine candidate (should be rare after the metric
1634        // layer, but possible with `Metric::Dot` or short-text L2)
1635        // can't collect positive bonuses, and a zero-similarity
1636        // candidate collects no bonus either.
1637        let gate = similarity.max(0.0);
1638        self.alpha * similarity
1639            + gate * (self.beta * recency + self.gamma * (importance - 0.5) + self.delta * usage)
1640    }
1641}