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 (13.1b): the claim expiry its holder was last warned about.
661pub const MNEMO_META_WARNED_EXPIRY: &str = "_mnemo.warned_expiry";
662
663/// 13a (13.1b): the delivery states, in order.
664pub mod delivery {
665    /// Written, not yet delivered by a wake-up.
666    pub const SENT: &str = "sent";
667    /// A wake-up reached the recipient's session.
668    pub const DELIVERED: &str = "delivered";
669    /// Shown to the recipient (the inbox, the per-turn hook).
670    pub const SEEN: &str = "seen";
671    /// Acked.
672    pub const DONE: &str = "done";
673}
674/// 13a: a message's status: `unread` until acked.
675pub const MESSAGE_UNREAD: &str = "unread";
676/// 13a: a message's status once acked.
677pub const MESSAGE_ACKED: &str = "acked";
678/// 13a: a message body's limit, in bytes; a bigger one belongs in a fact,
679/// named in `refs`.
680pub const MESSAGE_BODY_MAX: usize = 8 * 1024;
681/// 13a: a subject's limit, in bytes (one line).
682pub const MESSAGE_SUBJECT_MAX: usize = 200;
683/// 13a: a new message between the same two parties within this many seconds
684/// carries their last hop count on (the pair carry).
685pub const MESSAGE_PAIR_CARRY_SECS: i64 = 600;
686/// 13a: acked messages older than this are dropped by `compact` and
687/// `prune_messages` (30 days).
688pub const MESSAGE_ACKED_KEEP_SECS: i64 = 30 * 86_400;
689
690/// The visibility levels (13.5).
691pub const VISIBILITY_LEVELS: [&str; 3] = ["public", "team", "private"];
692
693/// 13a: the reserved keys a caller may set on a write (visibility and
694/// freshness), each checked by [`check_caller_key`]. Every other
695/// `_mnemo.*` key stays the engine's.
696pub const CALLER_KEYS: [&str; 3] = [
697    MNEMO_META_VISIBILITY,
698    MNEMO_META_AS_OF,
699    MNEMO_META_REVIEW_BY,
700];
701
702/// 13a: an agent id (`MNEMO_AGENT`, `_mnemo.default_agent`, a message's
703/// `to`): 1 to 64 of `[A-Za-z0-9._-]`. A role (`MNEMO_ROLE`) follows the
704/// same rule.
705pub fn valid_agent_id(s: &str) -> bool {
706    (1..=64).contains(&s.len())
707        && s.bytes()
708            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
709}
710
711/// Whether `key` is one of [`CALLER_KEYS`].
712pub fn is_caller_key(key: &str) -> bool {
713    CALLER_KEYS.contains(&key)
714}
715
716/// Check a caller-settable reserved key's value: a visibility level, or a
717/// whole number of unix seconds that isn't negative.
718pub fn check_caller_key(key: &str, value: &Value) -> std::result::Result<(), String> {
719    match key {
720        MNEMO_META_VISIBILITY => match value.as_str() {
721            Some(v) if VISIBILITY_LEVELS.contains(&v) => Ok(()),
722            _ => Err(format!(
723                "{key} must be one of public, team or private (got {value})"
724            )),
725        },
726        MNEMO_META_AS_OF | MNEMO_META_REVIEW_BY => match value.as_i64() {
727            Some(t) if t >= 0 => Ok(()),
728            _ => Err(format!(
729                "{key} must be a time in unix seconds, 0 or more (got {value})"
730            )),
731        },
732        _ => Err(format!("{key} isn't a key a caller may set")),
733    }
734}
735
736/// Whether a record is one of the coordination kinds ([`COORDINATION_KINDS`]).
737pub fn is_coordination(m: &Memory) -> bool {
738    m.metadata
739        .get(MNEMO_META_KIND)
740        .and_then(Value::as_str)
741        .is_some_and(|k| COORDINATION_KINDS.contains(&k))
742}
743
744/// v0.16.1: `true` on a turn whose content is only the markers a
745/// transcript reader makes for blocks it doesn't keep (`[thinking]`,
746/// `[tool_use name=…]`, `[tool_result ok, N bytes]`, `[image]`). Such a
747/// turn is kept in the thread, so `thread export` shows the whole flow,
748/// but it isn't embedded (it carries the sentinel vector) and `recall`
749/// never returns it, since it would match any query weakly. `recall`
750/// leaves out a marker-only turn written before v0.16.1 too, by its
751/// content.
752pub const MNEMO_META_MARKERS_ONLY: &str = "_mnemo.markers_only";
753
754/// Maximum content size for a single turn record before chunking kicks
755/// in (Phase 12.7a). 8 KB per chunk keeps each record small enough
756/// that the per-record page cost dominates — and so that a thread of
757/// mostly short messages ingests as one record each.
758pub const THREAD_TURN_CHUNK_BYTES: usize = 8 * 1024;
759
760/// Maximum content size for a tool-result turn before truncation
761/// (Phase 12.7a). Tool results frequently run tens of kilobytes;
762/// stored truncated with `_mnemo.sha256` + `_mnemo.length` so the
763/// original can be recovered (or verified) out-of-band.
764pub const THREAD_TOOL_RESULT_TRUNCATE_BYTES: usize = 16 * 1024;
765
766// ---------------------------------------------------------------------------
767// Phase 12.7b: status-record core + essence (timeline + sections). The
768// essence layer rides on the same reserved-metadata namespace as the
769// thread archive, so a file keeps the single `_mnemo.*` convention:
770//
771// - `_mnemo.kind = "essence"` identifies an essence record. Section
772//   is in `_mnemo.section`. Scope — thread or project — is in
773//   `_mnemo.thread` (string) or absent (`None` means project scope).
774// - `_mnemo.status` carries the lifecycle for section items
775//   (`"open"` → `"resolved"`). Timeline entries never get a status.
776// - `_mnemo.status_history` records the status transitions. One
777//   element per transition: `{"status": "...", "at": <unix_secs>}`.
778// - `_mnemo.refs` is an optional array of free-form reference
779//   strings (turn ids, memory ids, commits, paths).
780// ---------------------------------------------------------------------------
781
782/// Reserved `_mnemo.section` key — which essence section an item
783/// belongs to (Phase 12.7b). Values: `"timeline"`, `"intent"`,
784/// `"conventions"`, `"decisions"`, `"state"`, `"open"`, `"next"`,
785/// `"lessons"`. Timeline entries are append-only.
786pub const MNEMO_META_SECTION: &str = "_mnemo.section";
787
788/// Reserved `_mnemo.status` key — current status of a status-record.
789/// Values are per-kind (Phase 12.7b: essence uses `"open"` and
790/// `"resolved"`). Timeline entries never carry this.
791pub const MNEMO_META_STATUS: &str = "_mnemo.status";
792
793/// Reserved `_mnemo.status_history` key — array of status transitions,
794/// each `{"status": <str>, "at": <unix_secs>}`. Append-only — the
795/// first entry records creation, each later entry records a
796/// transition.
797pub const MNEMO_META_STATUS_HISTORY: &str = "_mnemo.status_history";
798
799/// Reserved `_mnemo.refs` key — optional array of free-form reference
800/// strings (turn ids, memory ids, commits, paths) attached to an
801/// essence record (Phase 12.7b).
802pub const MNEMO_META_REFS: &str = "_mnemo.refs";
803
804/// Marker value for `_mnemo.kind` on essence records (Phase 12.7b).
805pub const MNEMO_META_KIND_ESSENCE: &str = "essence";
806
807/// Maximum content length for a timeline entry (Phase 12.7b).
808/// Entries over this are rejected, not truncated — the planner's
809/// spec is explicit about this because truncation would lose the
810/// narrative, and splitting across records would lose ordering.
811pub const ESSENCE_TIMELINE_MAX_BYTES: usize = 600;
812
813/// Maximum content length for a section item (Phase 12.7b).
814/// intent / conventions / decisions / state / open / next / lessons
815/// all share the same single-line cap. Items over this are rejected.
816pub const ESSENCE_SECTION_MAX_BYTES: usize = 280;
817
818/// Default byte budget for [`crate::Mnemo::essence`] rendering
819/// (Phase 12.7b). Matches the planner's "max_bytes = 6144" spec,
820/// which sits comfortably below a 4K-token context window.
821pub const ESSENCE_DEFAULT_RENDER_BYTES: usize = 6144;
822
823/// Which essence section an item belongs to.
824///
825/// Rendering order is fixed at this type's declaration order:
826/// intent → conventions → decisions → state → open → next → lessons
827/// → timeline. See [`EssenceSection::render_order`] for the explicit
828/// list and the [`crate::Mnemo::essence`] docs for per-section rules
829/// (timeline is append-only, every other section is item-edited).
830#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
831pub enum EssenceSection {
832    /// What the thread is trying to do.
833    Intent,
834    /// How the user works — conventions that survive across threads.
835    Conventions,
836    /// Decisions made and why (newest first on render).
837    Decisions,
838    /// The current state of the work.
839    State,
840    /// Open problems.
841    Open,
842    /// What to do next.
843    Next,
844    /// Lessons learned — mistakes caught and their fixes.
845    Lessons,
846    /// Append-only milestone timeline. Entries capped at
847    /// [`ESSENCE_TIMELINE_MAX_BYTES`] and never editable.
848    Timeline,
849}
850
851impl EssenceSection {
852    /// Section → stable `_mnemo.section` string.
853    pub fn as_str(&self) -> &'static str {
854        match self {
855            EssenceSection::Intent => "intent",
856            EssenceSection::Conventions => "conventions",
857            EssenceSection::Decisions => "decisions",
858            EssenceSection::State => "state",
859            EssenceSection::Open => "open",
860            EssenceSection::Next => "next",
861            EssenceSection::Lessons => "lessons",
862            EssenceSection::Timeline => "timeline",
863        }
864    }
865
866    /// Parse a string from `_mnemo.section` into the typed enum.
867    /// Case-insensitive; returns `None` on unknown input.
868    pub fn parse(s: &str) -> Option<EssenceSection> {
869        match s.to_ascii_lowercase().as_str() {
870            "intent" => Some(EssenceSection::Intent),
871            "conventions" => Some(EssenceSection::Conventions),
872            "decisions" => Some(EssenceSection::Decisions),
873            "state" => Some(EssenceSection::State),
874            "open" => Some(EssenceSection::Open),
875            "next" => Some(EssenceSection::Next),
876            "lessons" => Some(EssenceSection::Lessons),
877            "timeline" => Some(EssenceSection::Timeline),
878            _ => None,
879        }
880    }
881
882    /// Fixed render order (intent → conventions → decisions → state
883    /// → open → next → lessons → timeline). The [`crate::Mnemo::essence`]
884    /// render walks this list, allocating a per-section byte budget
885    /// proportional to section importance in the user-centric order.
886    pub fn render_order() -> &'static [EssenceSection] {
887        &[
888            EssenceSection::Intent,
889            EssenceSection::Conventions,
890            EssenceSection::Decisions,
891            EssenceSection::State,
892            EssenceSection::Open,
893            EssenceSection::Next,
894            EssenceSection::Lessons,
895            EssenceSection::Timeline,
896        ]
897    }
898
899    /// `true` for sections whose items carry an `open → resolved`
900    /// status lifecycle (every section except [`EssenceSection::Timeline`]).
901    pub fn has_status_lifecycle(&self) -> bool {
902        !matches!(self, EssenceSection::Timeline)
903    }
904
905    /// Per-section byte cap for new items. Timeline: 600 bytes.
906    /// Every other section: 280 bytes.
907    pub fn item_max_bytes(&self) -> usize {
908        match self {
909            EssenceSection::Timeline => ESSENCE_TIMELINE_MAX_BYTES,
910            _ => ESSENCE_SECTION_MAX_BYTES,
911        }
912    }
913}
914
915/// Scope selector for an essence item (Phase 12.7b). Thread-scoped
916/// items belong to one `_mnemo.thread`; project-scoped items are
917/// shared across every thread in the file.
918#[derive(Debug, Clone, PartialEq, Eq, Hash)]
919pub enum EssenceScope {
920    /// Belongs to one thread (the string). Shows up in that
921    /// thread's render only.
922    Thread(String),
923    /// Shared across every thread in the file. Shows up in every
924    /// thread's render, and in the `about` briefing: the CLI and MCP
925    /// `about` append the project render after the manifest, from
926    /// `Mnemo::about_essence()` (12.7d).
927    Project,
928}
929
930/// Status values the essence section supports (Phase 12.7b). More
931/// kinds (tasks: `queued → active → ready → done | blocked`;
932/// findings: `open → accepted | deferred | rejected | needs-user →
933/// verified`) ship with Phase 13 reusing the same status-record
934/// core; the transition tables for those are declared as constants
935/// in this crate but currently unused.
936pub mod status {
937    /// Freshly-added section item.
938    pub const OPEN: &str = "open";
939    /// The user-facing concern has been addressed.
940    pub const RESOLVED: &str = "resolved";
941}
942
943/// Task transition table (13a step 4, `Mnemo::task_update`).
944/// `queued → active → ready → done`, or `active → blocked`; the back
945/// edges are `blocked → active` and (R-010.7, RB-012.3) `active → queued`
946/// and `blocked → queued`, for an owner handing a task back or anyone
947/// requeueing an abandoned one.
948/// `queued → active` happens only through `Mnemo::task_next`.
949pub const TASK_TRANSITIONS: &[(&str, &str)] = &[
950    ("queued", "active"),
951    ("active", "ready"),
952    ("active", "blocked"),
953    ("blocked", "active"),
954    ("active", "queued"),
955    ("blocked", "queued"),
956    ("ready", "done"),
957];
958
959/// 13a (13.1): the task statuses.
960pub mod task_status {
961    /// Waiting for an agent of its role to take it.
962    pub const QUEUED: &str = "queued";
963    /// Taken: its owner holds its claim.
964    pub const ACTIVE: &str = "active";
965    /// Its owner finished; waiting for its creator's `done`.
966    pub const READY: &str = "ready";
967    /// Done.
968    pub const DONE: &str = "done";
969    /// Its owner is stuck.
970    pub const BLOCKED: &str = "blocked";
971}
972
973/// Finding transition table (declared for Phase 13; currently unused
974/// in the engine). `open → {accepted | deferred | rejected |
975/// needs-user} → verified`.
976pub const FINDING_TRANSITIONS: &[(&str, &str)] = &[
977    ("open", "accepted"),
978    ("open", "deferred"),
979    ("open", "rejected"),
980    ("open", "needs-user"),
981    ("accepted", "verified"),
982    ("deferred", "verified"),
983    ("needs-user", "verified"),
984];
985
986/// Essence transition table for Phase 12.7b. Only `open → resolved`
987/// is allowed. Timeline entries don't use this (they're append-only
988/// and have no status).
989pub const ESSENCE_TRANSITIONS: &[(&str, &str)] = &[(status::OPEN, status::RESOLVED)];
990
991// ---------------------------------------------------------------------------
992// Phase 12.7c: continuation + commit_deltas
993// ---------------------------------------------------------------------------
994
995/// Reserved `_mnemo.continues` key (Phase 12.7c). Set on a
996/// thread-start marker record to point at the previous thread whose
997/// context the new thread continues from. Value: the prior thread id
998/// (string). Rendering a continued thread pulls the prior thread's
999/// open items, `next` and last-N timeline entries ahead of the new
1000/// thread's own essence.
1001pub const MNEMO_META_CONTINUES: &str = "_mnemo.continues";
1002
1003/// Marker value for `_mnemo.kind` on a thread-start record (one per
1004/// `thread_start(new, --from old)` call, carrying the link in
1005/// `_mnemo.continues`).
1006pub const MNEMO_META_KIND_THREAD_LINK: &str = "thread_link";
1007
1008/// How many timeline entries from the predecessor thread the
1009/// continuation render pulls in (Phase 12.7c). Small enough to keep
1010/// the render under the default 6 KB budget, large enough to carry a
1011/// handful of milestones.
1012pub const CONTINUATION_TIMELINE_ENTRIES: usize = 10;
1013
1014/// What [`crate::Mnemo::commit_deltas`] does with the `turns` carried
1015/// in the batch (Phase 12.7c).
1016#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1017pub enum TurnPolicy {
1018    /// Archive every turn in the batch via
1019    /// [`crate::Mnemo::ingest_thread`]. Default — matches the
1020    /// "lossless flow preservation" story of 12.7.
1021    #[default]
1022    Archive,
1023    /// Store turns with a TTL (unix-seconds expiry).
1024    ExpireAfter(i64),
1025    /// Drop turns on the floor (no archive record written).
1026    Drop,
1027}
1028
1029/// Which op a [`EssenceOp`] carries. Mirrors the per-method
1030/// `Mnemo::essence_*` surface so one batch can mix section + timeline
1031/// edits in one call.
1032#[derive(Debug, Clone, PartialEq, Eq)]
1033pub enum EssenceOpKind {
1034    /// Section item add (any section except timeline).
1035    Add,
1036    /// Append-only timeline entry.
1037    AppendTimeline,
1038    /// In-place update of an existing section item.
1039    Update,
1040    /// Transition an item `open → resolved`.
1041    Resolve,
1042    /// Soft-delete an item.
1043    Remove,
1044}
1045
1046/// One essence op inside a [`CommitBatch`] (Phase 12.7c). Validation
1047/// (missing/extra fields per kind) runs up front in
1048/// [`crate::Mnemo::commit_deltas`] — a single bad op aborts the
1049/// whole batch before any write lands.
1050#[derive(Debug, Clone)]
1051pub struct EssenceOp {
1052    /// Which op to apply.
1053    pub kind: EssenceOpKind,
1054    /// Scope — required for [`EssenceOpKind::Add`] and
1055    /// [`EssenceOpKind::AppendTimeline`].
1056    pub scope: Option<EssenceScope>,
1057    /// Section — required for [`EssenceOpKind::Add`].
1058    pub section: Option<EssenceSection>,
1059    /// Target record id — required for [`EssenceOpKind::Update`],
1060    /// [`EssenceOpKind::Resolve`], [`EssenceOpKind::Remove`].
1061    pub id: Option<Ulid>,
1062    /// Content text — required for [`EssenceOpKind::Add`],
1063    /// [`EssenceOpKind::AppendTimeline`], [`EssenceOpKind::Update`].
1064    pub text: Option<String>,
1065    /// Optional refs for ops that carry text.
1066    pub refs: Option<Vec<String>>,
1067}
1068
1069/// One keyed fact inside a [`CommitBatch`] (Phase 12.7c).
1070#[derive(Debug, Clone)]
1071pub struct KeyedMemory {
1072    /// The memory to store. An **empty `vector`** means "embed
1073    /// `content` with the registered embedder" (12.7d): every such fact
1074    /// in a batch is embedded together in one `Embedder::embed` call.
1075    pub memory: Memory,
1076    /// Optional 12.1 upsert key.
1077    pub key: Option<String>,
1078}
1079
1080/// Atomic write batch for [`crate::Mnemo::commit_deltas`]
1081/// (Phase 12.7c). The planner's "one call that composes facts +
1082/// essence + turns" shape: everything validates up front, then every
1083/// write runs under a single `flush()`.
1084#[derive(Debug, Clone, Default)]
1085pub struct CommitBatch {
1086    /// Keyed-or-not facts to remember (12.1).
1087    pub facts: Vec<KeyedMemory>,
1088    /// Essence ops to apply (12.7b).
1089    pub essence_ops: Vec<EssenceOp>,
1090    /// Thread archive turns to ingest (12.7a).
1091    pub turns: Vec<ThreadTurn>,
1092    /// Destination thread id for `turns`. Required when `turns` is
1093    /// non-empty.
1094    pub thread_id: Option<String>,
1095    /// What to do with `turns` — defaults to `Archive`.
1096    pub turn_policy: TurnPolicy,
1097}
1098
1099/// Result of [`crate::Mnemo::commit_deltas`] (Phase 12.7c).
1100#[derive(Debug, Clone, Default, PartialEq, Eq)]
1101pub struct CommitReport {
1102    /// Facts added (plain or `WriteOutcome::Added`).
1103    pub facts_added: usize,
1104    /// Facts whose keyed write superseded a prior record.
1105    pub facts_superseded: usize,
1106    /// Keyed facts whose write was a no-op (matched live record).
1107    pub facts_unchanged: usize,
1108    /// Essence ops that produced an Added/Updated result.
1109    pub essence_ops_applied: usize,
1110    /// Essence ops that were no-ops (e.g. `resolve` on resolved).
1111    pub essence_ops_unchanged: usize,
1112    /// Turn records written to the archive.
1113    pub turns_added: usize,
1114    /// Source turns skipped by the archive's idempotence check.
1115    pub turns_skipped: usize,
1116    /// Source turns whose content was truncated at the 16 KB cap.
1117    pub turns_truncated: usize,
1118    /// Source turns split into multiple 8 KB chunks.
1119    pub turns_chunked: usize,
1120}
1121
1122/// Patch body for [`crate::Mnemo::update`] (Phase 12.1): every field is
1123/// optional, and only the `Some(...)` fields overwrite the corresponding
1124/// field on the target memory. All fields can be set independently.
1125///
1126/// `content` paired with `vector` updates both at once — the engine does
1127/// not re-embed under `update` (use `update_text` for that). A `content`
1128/// change without a new `vector` is rejected to prevent the embedding
1129/// drifting silently out of sync with the text.
1130///
1131/// `metadata` **replaces** the full user-metadata map — the engine's own
1132/// `_mnemo.*` reserved keys on the target record are preserved across
1133/// the replacement (updated-at timestamp, supersession markers, etc.).
1134/// Passing an empty map drops every user-visible metadata key but keeps
1135/// the reserved ones.
1136///
1137/// `ttl_secs` is `Option<Option<i64>>` so a caller can distinguish
1138/// "leave it alone" (`None`) from "set it to a value" (`Some(Some(s))`)
1139/// and "clear it" (`Some(None)`).
1140#[derive(Debug, Clone, Default)]
1141pub struct MemoryPatch {
1142    /// New text content. If set, a matching `vector` must also be set
1143    /// (or call `update_text`, which re-embeds through the registered
1144    /// embedder).
1145    pub content: Option<String>,
1146    /// New embedding. Must match the database's dimensionality.
1147    pub vector: Option<Vec<f32>>,
1148    /// New importance in `[0, 1]`.
1149    pub importance: Option<f32>,
1150    /// Replace the memory type.
1151    pub memory_type: Option<MemoryType>,
1152    /// Replace the user-visible metadata (preserves `_mnemo.*` reserved
1153    /// keys).
1154    pub metadata: Option<Map<String, Value>>,
1155    /// Change the TTL. Outer `None` → leave unchanged; `Some(Some(s))` →
1156    /// set TTL to `s`; `Some(None)` → clear any existing TTL.
1157    pub ttl_secs: Option<Option<i64>>,
1158    /// 13a: set these caller keys ([`CALLER_KEYS`]: visibility, `as_of`,
1159    /// `review_by`), each checked, without replacing the user metadata. A
1160    /// `null` value removes the key.
1161    pub caller_keys: Option<Map<String, Value>>,
1162}
1163
1164/// One turn fed into [`crate::Mnemo::ingest_thread`] (Phase 12.7a).
1165///
1166/// The caller supplies `turn_id` (opaque, for idempotence), `role`
1167/// (the transcript's author tag; no interpretation), and `content`
1168/// (UTF-8 text; chunked at 8 KB, or truncated at 16 KB when `role ==
1169/// "tool"`). The ingest path assigns `_mnemo.seq` monotonically within
1170/// the destination thread and embeds through the registered embedder.
1171///
1172/// Tool messages whose content exceeds [`THREAD_TOOL_RESULT_TRUNCATE_BYTES`]
1173/// are stored truncated. Other roles over [`THREAD_TURN_CHUNK_BYTES`]
1174/// are chunked.
1175#[derive(Debug, Clone)]
1176pub struct ThreadTurn {
1177    /// Opaque per-turn id from the source transcript (e.g. a Claude
1178    /// Code message uuid). Used for `ingest_thread`'s idempotence
1179    /// check: a turn whose `turn_id` already exists in the target
1180    /// thread is skipped.
1181    pub turn_id: String,
1182    /// Author role verbatim from the transcript (`"user"`,
1183    /// `"assistant"`, `"system"`, `"tool"`, …). `"tool"` triggers
1184    /// the 16 KB truncation branch; all other roles go through the
1185    /// 8 KB chunking branch.
1186    pub role: String,
1187    /// UTF-8 message content.
1188    pub content: String,
1189    /// Optional caller-supplied creation timestamp (unix seconds).
1190    /// If `None`, the ingest path uses `now_secs()` so the record's
1191    /// `created_at` still sorts the thread in order. Transcripts
1192    /// that carry a per-turn timestamp should pass it through so a
1193    /// future `thread export --by-time` can honour it.
1194    pub timestamp: Option<i64>,
1195}
1196
1197/// One turn of a thread's archive in the **ingest shape** (Phase 12.7d),
1198/// as returned by [`crate::Mnemo::thread_export_turns`] and by Python
1199/// `db.thread_export`, MCP `thread_export` and `mnemo thread export`.
1200///
1201/// Turns come back in `_mnemo.seq` order, one entry per source turn: the
1202/// 8 KB chunks of a long turn are joined back into one `content`, so
1203/// feeding the list to `ingest_thread` (same thread: every turn is
1204/// skipped; a new thread: the turns are re-chunked identically) round
1205/// trips. A tool result that was truncated at 16 KB carries `sha256` and
1206/// `original_length` of the original content.
1207#[derive(Debug, Clone, PartialEq, Eq)]
1208pub struct ExportedTurn {
1209    /// Source `turn_id` (`_mnemo.turn_id`).
1210    pub turn_id: String,
1211    /// Author role (`_mnemo.role`).
1212    pub role: String,
1213    /// Stored text, with chunks joined in `_mnemo.part` order.
1214    pub content: String,
1215    /// The turn's timestamp (unix seconds; the record's `created_at`).
1216    pub timestamp: i64,
1217    /// Hex SHA-256 of the original content, set only for a truncated
1218    /// tool result.
1219    pub sha256: Option<String>,
1220    /// Byte length of the original content, set only for a truncated
1221    /// tool result.
1222    pub original_length: Option<u64>,
1223}
1224
1225impl ExportedTurn {
1226    /// The JSON object shared by the MCP tool and the CLI JSONL export:
1227    /// `{turn_id, role, content, timestamp}` plus `sha256` and
1228    /// `original_length` when the turn was truncated.
1229    pub fn to_json(&self) -> serde_json::Value {
1230        let mut obj = serde_json::json!({
1231            "turn_id": self.turn_id,
1232            "role": self.role,
1233            "content": self.content,
1234            "timestamp": self.timestamp,
1235        });
1236        if let Some(sha) = &self.sha256 {
1237            obj["sha256"] = serde_json::Value::String(sha.clone());
1238        }
1239        if let Some(len) = self.original_length {
1240            obj["original_length"] = serde_json::Value::Number(len.into());
1241        }
1242        obj
1243    }
1244}
1245
1246/// Result of one [`crate::Mnemo::ingest_thread`] call (Phase 12.7a).
1247#[derive(Debug, Clone, Default, PartialEq, Eq)]
1248pub struct IngestReport {
1249    /// Number of **new** records written (turn chunks after chunking
1250    /// / truncation). A long turn counts as however many chunks it
1251    /// produced.
1252    pub added_records: usize,
1253    /// Number of **source turns** that already had a record in the
1254    /// target thread and were skipped by the idempotence check.
1255    pub skipped_existing_turns: usize,
1256    /// Number of turns whose content was truncated at the 16 KB cap.
1257    /// Only `role == "tool"` turns can trigger this branch.
1258    pub truncated_turns: usize,
1259    /// Number of turns that were split into multiple chunks at the
1260    /// 8 KB boundary. A truncated turn counts as 0 here even if its
1261    /// pre-truncation content would have chunked.
1262    pub chunked_turns: usize,
1263}
1264
1265/// Scope selector for a keyed slot (Phase 12.1.1). A keyed
1266/// `remember`'s slot is always identified by `(scope_owner, key)`:
1267/// `Private(agent_id)` slots are per-agent, `Shared` slots are per-file.
1268/// `history_in(key, scope)` uses the same selector so the lookup matches
1269/// the write exactly.
1270///
1271/// The convenience [`crate::Mnemo::history`] is equivalent to
1272/// `history_in(key, KeyScope::Private(agent.unwrap_or("default")))` —
1273/// i.e. `history(key, None)` resolves to the default agent's private
1274/// slot, matching the `remember(…, agent_id=None, scope=Private, key=K)`
1275/// write path. Use [`crate::Mnemo::history_in`] with
1276/// [`KeyScope::Shared`] when you need the shared slot.
1277#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1278pub enum KeyScope {
1279    /// Per-agent slot. The agent id is the one carried on `Memory.agent_id`
1280    /// at write time; `remember` with no explicit agent uses `"default"`.
1281    Private(String),
1282    /// Per-file slot shared across every agent.
1283    Shared,
1284}
1285
1286impl KeyScope {
1287    /// Default agent id used when `Memory::new(...)` is called without
1288    /// `.with_agent(...)` — same `"default"` the [`Memory::new`]
1289    /// constructor seeds into `Memory.agent_id`.
1290    pub const DEFAULT_AGENT: &'static str = "default";
1291
1292    /// Build the private slot for the default agent. Shorthand for
1293    /// `KeyScope::Private(KeyScope::DEFAULT_AGENT.to_string())`.
1294    pub fn private_default() -> Self {
1295        KeyScope::Private(Self::DEFAULT_AGENT.to_string())
1296    }
1297}
1298
1299/// Outcome of a 12.1 write operation (`remember` with `key`, or `update`).
1300///
1301/// Plain `remember` without a key always returns a ULID, not a
1302/// `WriteOutcome`, because supersession and NOOP detection are tied to
1303/// the key slot.
1304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1305pub enum WriteOutcome {
1306    /// Keyed write with no prior record for this slot. A brand-new record
1307    /// was inserted, no record was superseded.
1308    Added,
1309    /// Keyed write whose content / type / importance / user metadata
1310    /// differs from the live record for this slot. A new record was
1311    /// inserted and the prior one was marked
1312    /// `_mnemo.superseded_by` / `_mnemo.invalid_at`.
1313    Superseded,
1314    /// No-op: the incoming keyed write is byte-equal to the live record
1315    /// for this slot (content, memory type, importance, user metadata).
1316    /// No record was written and no catalog page was dirtied. The
1317    /// returned id is the existing record's id.
1318    Unchanged,
1319    /// In-place `update`: fields changed on the target record. The record
1320    /// was rewritten copy-on-write so the previous version remains
1321    /// visible through snapshots.
1322    Updated,
1323}
1324
1325// ---------------------------------------------------------------------------
1326// Phase 12.6: recall filters (session_id + per-metadata-key conditions)
1327// ---------------------------------------------------------------------------
1328
1329/// One AND-ed condition applied to a candidate memory's metadata during
1330/// filtered recall (Phase 12.6). Terms are combined conjunctively — a
1331/// memory passes the filter only if *every* term evaluates true against
1332/// its `metadata` map. See [`Filter`] for the surface API.
1333///
1334/// Values use `serde_json::Value` so the same term shape serializes
1335/// cleanly through the MCP / Python / CLI bridges without a parallel
1336/// enum per surface.
1337#[derive(Debug, Clone)]
1338pub enum FilterTerm {
1339    /// The memory's `metadata[key]` must be set to any value.
1340    Exists(String),
1341    /// `metadata[key]` must equal this JSON value (strict JSON equality:
1342    /// strings compare case-sensitively, numbers compare as f64).
1343    Eq(String, Value),
1344    /// `metadata[key]` must equal one of these JSON values.
1345    In(String, Vec<Value>),
1346    /// `metadata[key]` must be a number in `[min, max]` (inclusive on
1347    /// both ends; `None` on either bound means "no bound on that side").
1348    /// A non-numeric metadata value fails the term.
1349    Range {
1350        /// Metadata key.
1351        key: String,
1352        /// Lower bound (inclusive) — `None` means unbounded below.
1353        min: Option<f64>,
1354        /// Upper bound (inclusive) — `None` means unbounded above.
1355        max: Option<f64>,
1356    },
1357}
1358
1359/// Pre-scoring filter applied by [`crate::Mnemo::recall`] (Phase 12.6).
1360///
1361/// `session_id` restricts candidates to a single session (when the
1362/// memory's `session_id` is set). The `terms` are AND-ed metadata
1363/// conditions evaluated against each candidate's `metadata` map; see
1364/// [`FilterTerm`] for the shapes.
1365///
1366/// When an ANN index is present, the filter is applied *after* the ANN
1367/// shortlist step, so a selective filter can starve the result below
1368/// `top_k`. Recall handles that automatically via the Phase 12.1
1369/// short-results-on-indexed-path fix (widen 2×, then exact scan).
1370#[derive(Debug, Clone, Default)]
1371pub struct Filter {
1372    /// Only candidates whose `Memory.session_id` equals this value.
1373    /// Candidates without a session_id are excluded when this is set.
1374    pub session_id: Option<String>,
1375    /// AND-ed metadata conditions. Empty → no metadata constraints.
1376    pub terms: Vec<FilterTerm>,
1377}
1378
1379impl Filter {
1380    /// Builder helper: a filter that keeps only memories in `session`.
1381    pub fn new_session(session: impl Into<String>) -> Self {
1382        Self {
1383            session_id: Some(session.into()),
1384            terms: Vec::new(),
1385        }
1386    }
1387
1388    /// Restrict to one session_id (builder form).
1389    pub fn with_session(mut self, session: impl Into<String>) -> Self {
1390        self.session_id = Some(session.into());
1391        self
1392    }
1393
1394    /// Require `metadata[key]` to exist (any value).
1395    pub fn metadata_exists(mut self, key: impl Into<String>) -> Self {
1396        self.terms.push(FilterTerm::Exists(key.into()));
1397        self
1398    }
1399
1400    /// Require `metadata[key]` to equal `value`.
1401    pub fn metadata_eq(mut self, key: impl Into<String>, value: Value) -> Self {
1402        self.terms.push(FilterTerm::Eq(key.into(), value));
1403        self
1404    }
1405
1406    /// Require `metadata[key]` to be one of `values`.
1407    pub fn metadata_in(mut self, key: impl Into<String>, values: Vec<Value>) -> Self {
1408        self.terms.push(FilterTerm::In(key.into(), values));
1409        self
1410    }
1411
1412    /// Require `metadata[key]` to be a number in `[min, max]`.
1413    pub fn metadata_range(
1414        mut self,
1415        key: impl Into<String>,
1416        min: Option<f64>,
1417        max: Option<f64>,
1418    ) -> Self {
1419        self.terms.push(FilterTerm::Range {
1420            key: key.into(),
1421            min,
1422            max,
1423        });
1424        self
1425    }
1426
1427    /// `true` iff the filter has no terms and no `session_id`. The
1428    /// recall hot path uses this to skip the per-candidate filter
1429    /// check entirely.
1430    pub fn is_empty(&self) -> bool {
1431        self.session_id.is_none() && self.terms.is_empty()
1432    }
1433
1434    /// Phase 12.7a: `true` iff the filter mentions any reserved
1435    /// `_mnemo.*` metadata key. Used by `recall` to decide whether
1436    /// to default-exclude thread-archive turns
1437    /// (`_mnemo.kind = "turn"`). A caller that wants turns in the
1438    /// result opts in by adding any `_mnemo.*` term to the filter
1439    /// — equality, `$in`, `$exists`, or range — because those are the
1440    /// only queries that can usefully target turn records.
1441    pub fn mentions_mnemo_meta(&self) -> bool {
1442        self.terms.iter().any(|term| {
1443            let key = match term {
1444                FilterTerm::Exists(k) => k,
1445                FilterTerm::Eq(k, _) => k,
1446                FilterTerm::In(k, _) => k,
1447                FilterTerm::Range { key, .. } => key,
1448            };
1449            key.starts_with(MNEMO_META_NS)
1450        })
1451    }
1452
1453    /// Evaluate the filter against one memory. Returns `true` if the
1454    /// memory passes every term.
1455    pub fn matches(&self, m: &Memory) -> bool {
1456        if let Some(s) = &self.session_id {
1457            match &m.session_id {
1458                Some(ms) if ms == s => {}
1459                _ => return false,
1460            }
1461        }
1462        for term in &self.terms {
1463            if !term_matches(term, &m.metadata) {
1464                return false;
1465            }
1466        }
1467        true
1468    }
1469}
1470
1471fn term_matches(term: &FilterTerm, metadata: &Map<String, Value>) -> bool {
1472    match term {
1473        FilterTerm::Exists(key) => metadata.contains_key(key),
1474        FilterTerm::Eq(key, v) => metadata.get(key).is_some_and(|got| values_equal(got, v)),
1475        FilterTerm::In(key, options) => metadata
1476            .get(key)
1477            .is_some_and(|got| options.iter().any(|opt| values_equal(got, opt))),
1478        FilterTerm::Range { key, min, max } => metadata
1479            .get(key)
1480            .and_then(|v| v.as_f64())
1481            .is_some_and(|n| min.is_none_or(|m_| n >= m_) && max.is_none_or(|m_| n <= m_)),
1482    }
1483}
1484
1485/// JSON value equality for filter terms. serde_json's `Value: PartialEq`
1486/// compares numbers by exact representation (integer vs float). The
1487/// filter surface should treat `5` and `5.0` as equal, so we compare
1488/// numbers through `as_f64` when both sides are numbers; everything
1489/// else falls back to structural equality.
1490fn values_equal(a: &Value, b: &Value) -> bool {
1491    match (a, b) {
1492        (Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
1493            (Some(xf), Some(yf)) => (xf - yf).abs() < f64::EPSILON,
1494            _ => x == y,
1495        },
1496        (x, y) => x == y,
1497    }
1498}
1499
1500/// Distance/similarity metric for vector comparison.
1501#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1502pub enum Metric {
1503    /// Cosine similarity (orientation only).
1504    Cosine,
1505    /// Negative Euclidean distance, mapped into a `(0,1]` similarity.
1506    L2,
1507    /// Raw dot product.
1508    Dot,
1509}
1510
1511/// Compute a *similarity* (higher = more relevant) under the given metric.
1512pub fn similarity(metric: Metric, a: &[f32], b: &[f32]) -> f32 {
1513    match metric {
1514        Metric::Cosine => cosine(a, b),
1515        Metric::Dot => dot(a, b),
1516        Metric::L2 => {
1517            let d = euclidean(a, b);
1518            1.0 / (1.0 + d)
1519        }
1520    }
1521}
1522
1523fn dot(a: &[f32], b: &[f32]) -> f32 {
1524    a.iter().zip(b).map(|(x, y)| x * y).sum()
1525}
1526
1527/// Cosine similarity in `[-1.0, 1.0]`; returns `0.0` if either vector
1528/// has zero magnitude. `pub(crate)` so [`crate::Mnemo::cache_get_semantic`]
1529/// (Phase 10.2) can reuse the same scoring routine that recall uses,
1530/// keeping the two paths semantically identical.
1531pub(crate) fn cosine(a: &[f32], b: &[f32]) -> f32 {
1532    let na = dot(a, a).sqrt();
1533    let nb = dot(b, b).sqrt();
1534    if na == 0.0 || nb == 0.0 {
1535        0.0
1536    } else {
1537        dot(a, b) / (na * nb)
1538    }
1539}
1540
1541fn euclidean(a: &[f32], b: &[f32]) -> f32 {
1542    a.iter()
1543        .zip(b)
1544        .map(|(x, y)| (x - y) * (x - y))
1545        .sum::<f32>()
1546        .sqrt()
1547}
1548
1549/// Weights for the multi-signal recall score (scoring v2, shipped in
1550/// v0.7.0).
1551///
1552/// ```text
1553/// score = similarity
1554///       + max(similarity, 0)
1555///         · ( β · recency
1556///           + γ · (importance − 0.5)
1557///           + δ · tanh(access_count / 5) )
1558///
1559/// recency = exp( -ln(2) · age_secs / half_life_secs )
1560/// age_secs = now - memory.created_at
1561/// ```
1562///
1563/// Design notes (from the 2026-11-06 scoring-v2 bake-off; see the
1564/// `ranking_v2` harness at `mnemo/examples/ranking_v2.rs`):
1565/// * **Similarity-gated.** The recency / importance / usage terms are
1566///   multiplied by `max(similarity, 0)`, so a stale-but-semantically-off
1567///   memory can't ride recency or importance past a semantically-on-point
1568///   one. Pre-v0.7.0 scoring was purely additive.
1569/// * **Importance is centered at 0.5.** A default-importance memory
1570///   contributes zero importance bonus; importance only pushes a score up
1571///   or down from that reference point.
1572/// * **Usage is saturating.** `tanh(uses/5)` caps the feedback bonus so
1573///   a heavily-returned memory can't keep accumulating weight past a
1574///   plateau. At 5 uses the bonus is ~76% of its asymptote; at 10, ~96%.
1575/// * **Recency is decoupled from the feedback loop.** Age is measured
1576///   from `created_at`, not `accessed_at`, so a `recall()` call does not
1577///   bump its own results' recency scores on later queries.
1578///
1579/// The output of this scorer is on a **different scale** from the
1580/// pre-v0.7.0 formula. Callers that compared raw scores to a fixed
1581/// threshold should re-pick the threshold against the new scale.
1582#[derive(Clone, Copy, Debug)]
1583pub struct ScoreWeights {
1584    /// Weight on semantic similarity. Kept in the struct for calibration
1585    /// hooks and symmetry with the other weights; scoring v2 always uses
1586    /// it as `1.0` because the leading `similarity` term is ungated and
1587    /// the whole score sits on the cosine-similarity scale by design.
1588    pub alpha: f32,
1589    /// Weight on the recency bonus (multiplied by `max(sim, 0)`).
1590    pub beta: f32,
1591    /// Weight on the importance bonus `(importance − 0.5)`, centered at
1592    /// the default-importance 0.5 (multiplied by `max(sim, 0)`).
1593    pub gamma: f32,
1594    /// Weight on the saturating usage bonus `tanh(access_count / 5)`
1595    /// (multiplied by `max(sim, 0)`).
1596    pub delta: f32,
1597    /// Half-life of the recency term, in seconds.
1598    pub half_life_secs: f32,
1599}
1600
1601impl Default for ScoreWeights {
1602    fn default() -> Self {
1603        // Tuned on the Phase 6 corpus + the ranking_v2 age-spread
1604        // fixture; see `ranking_v2.checks` in perf_v0.5.0.json.
1605        Self {
1606            alpha: 1.0,
1607            beta: 0.3,
1608            gamma: 0.2,
1609            delta: 0.1,
1610            half_life_secs: 7.0 * 24.0 * 3600.0,
1611        }
1612    }
1613}
1614
1615/// Saturation constant K for the usage term `tanh(access_count / K)`.
1616/// K = 5 means ~76% of the asymptote at 5 uses and ~96% at 10 — matches
1617/// the "a few repeats is signal; past that it's a habit" intuition.
1618const USAGE_SAT_K: f32 = 5.0;
1619
1620impl ScoreWeights {
1621    /// Combine the four signals into a single score. See the struct docs
1622    /// for the full formula and the scoring-v2 rationale.
1623    pub fn score(&self, similarity: f32, age_secs: f32, importance: f32, access_count: u32) -> f32 {
1624        // Recency is in [0, 1]: 1.0 at age 0, 0.5 at one half-life, etc.
1625        let recency = (-std::f32::consts::LN_2 * age_secs.max(0.0) / self.half_life_secs).exp();
1626        // Saturating usage in [0, 1); tanh caps feedback-loop drift.
1627        let usage = (access_count as f32 / USAGE_SAT_K).tanh();
1628        // Gate the non-similarity bonuses by `max(sim, 0)` so a
1629        // negative-cosine candidate (should be rare after the metric
1630        // layer, but possible with `Metric::Dot` or short-text L2)
1631        // can't collect positive bonuses, and a zero-similarity
1632        // candidate collects no bonus either.
1633        let gate = similarity.max(0.0);
1634        self.alpha * similarity
1635            + gate * (self.beta * recency + self.gamma * (importance - 0.5) + self.delta * usage)
1636    }
1637}