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    /// Set the visibility scope.
138    pub fn with_scope(mut self, scope: Scope) -> Self {
139        self.scope = scope;
140        self
141    }
142    /// Attach a TTL in seconds.
143    pub fn with_ttl(mut self, ttl_secs: i64) -> Self {
144        self.ttl_secs = Some(ttl_secs);
145        self
146    }
147    /// Attach a metadata key/value pair.
148    pub fn with_meta(mut self, key: impl Into<String>, value: Value) -> Self {
149        self.metadata.insert(key.into(), value);
150        self
151    }
152
153    /// True if the memory's TTL has elapsed as of `now`.
154    pub fn is_expired(&self, now: i64) -> bool {
155        match self.ttl_secs {
156            Some(ttl) => now - self.created_at >= ttl,
157            None => false,
158        }
159    }
160
161    /// Build the **canonical scaffold manifest** for a freshly-initialised
162    /// database. This is the default "I am a brand-new MNemo file" memory
163    /// inserted by `mnemo init` (and surfaced by `mnemo about`) so every new
164    /// database is self-describing from birth — no opt-in step required.
165    ///
166    /// The scaffold is a placeholder: the vector is all-zeros (it doesn't
167    /// pretend to carry semantic content), and `metadata.scaffold = true`
168    /// marks it as auto-generated so tooling and humans can tell it apart
169    /// from a hand-written manifest. The expected workflow is for the file's
170    /// author to replace this memory with one that records the project's
171    /// actual embedder, agent_id default, and conventions.
172    ///
173    /// See [`crate::Mnemo::about`] for the rest of the convention.
174    pub fn scaffold_manifest(dimensions: usize) -> Self {
175        let content = format!(
176            "MNEMO MANIFEST (scaffold) — Fresh {}-dimensional database created \
177             by `mnemo init`. This is a placeholder. Replace it with a memory \
178             that records your project's embedder (name, dimensions, normalize), \
179             default agent_id, and metadata conventions; keep the metadata keys \
180             `area=\"onboarding\"` and `topic=\"manifest\"` so `mnemo about` \
181             continues to surface it as the headline orientation point. Drop \
182             `metadata.scaffold` once you've replaced this entry so tooling \
183             knows the manifest has been curated.",
184            dimensions
185        );
186        let mut metadata = Map::new();
187        metadata.insert("area".into(), Value::String("onboarding".into()));
188        metadata.insert("topic".into(), Value::String("manifest".into()));
189        metadata.insert("scaffold".into(), Value::Bool(true));
190        metadata.insert(
191            "engine_version".into(),
192            Value::String(env!("CARGO_PKG_VERSION").into()),
193        );
194        metadata.insert(
195            "dimensions".into(),
196            Value::Number(serde_json::Number::from(dimensions as u64)),
197        );
198        // Sentinel vector: a single-axis unit spike `[1, 0, 0, …]`.
199        // A zero vector would now trip the Phase 3 `put` guard
200        // (all-zero refused — see store/records.rs). This spike is non-zero
201        // (so it passes), unit-normalized (so it reads cleanly to any
202        // downstream inspector), and uncorrelated with any real
203        // embedder's output (so it ranks near-last on any user query —
204        // appropriate for a placeholder the user is expected to
205        // replace).
206        let mut vector = vec![0.0_f32; dimensions];
207        if dimensions > 0 {
208            vector[0] = 1.0;
209        }
210        let now = now_secs();
211        Memory {
212            id: Ulid::new(),
213            memory_type: MemoryType::Semantic,
214            vector,
215            content,
216            metadata,
217            agent_id: "mnemo".to_string(),
218            session_id: None,
219            scope: Scope::Shared,
220            created_at: now,
221            accessed_at: now,
222            access_count: 0,
223            importance: 1.0,
224            ttl_secs: None,
225        }
226    }
227}
228
229// ---------------------------------------------------------------------------
230// Phase 12.1: reserved `_mnemo.*` metadata keys for in-place updates + keyed
231// supersession. These live in `Memory.metadata` (which is already
232// `Map<String, Value>` on the record), so nothing in the on-disk record
233// layout changes — v0.7.x readers see them as ordinary user metadata and
234// ignore them. Format bump to v9 (post-12.1) will promote the ones that
235// pay for a typed catalog column.
236// ---------------------------------------------------------------------------
237
238/// Namespace prefix used for every v0.8.0+ reserved metadata key (R-001.10).
239/// Keys outside this namespace are untouched user metadata.
240pub const MNEMO_META_NS: &str = "_mnemo.";
241
242/// Upsert slot name on a `remember(…, key = K)` write (12.1). Combined with
243/// the memory's `scope` (and `agent_id` for `Private` scope) to identify a
244/// single live memory per slot: a newer `remember(key=K)` supersedes the
245/// prior one.
246pub const MNEMO_META_KEY: &str = "_mnemo.key";
247
248/// Set on the newly-inserted record when a `remember(key=K)` supersedes an
249/// earlier record. Value: the superseded record's ULID string.
250pub const MNEMO_META_SUPERSEDES: &str = "_mnemo.supersedes";
251
252/// Set on the earlier record when a newer `remember(key=K)` has replaced
253/// it. Value: the new record's ULID string. Together with `_mnemo.invalid_at`
254/// this marks the record as "superseded, not current" — default `recall`,
255/// `about` and the key index skip it; `history(key)` walks the chain.
256pub const MNEMO_META_SUPERSEDED_BY: &str = "_mnemo.superseded_by";
257
258/// Set on the earlier record when superseded. Value: unix seconds (i64).
259/// Not interpreted by the engine's scorer — purely for audit / `history`.
260pub const MNEMO_META_INVALID_AT: &str = "_mnemo.invalid_at";
261
262/// Set on a record each time `Mnemo::update` succeeds. Value: unix seconds.
263/// Lets callers distinguish an unchanged-since-creation record from one
264/// that has been edited in place. Not interpreted by the scorer.
265pub const MNEMO_META_UPDATED_AT: &str = "_mnemo.updated_at";
266
267// ---------------------------------------------------------------------------
268// Phase 12.7a: thread archive (ingest / export / forget). Reserved
269// `_mnemo.*` keys that identify thread-turn records. All records with
270// `_mnemo.kind = "turn"` are:
271//   * excluded from default recall (opt in with a 12.6
272//     `_mnemo.kind = "turn"` filter or the `--thread` CLI flag),
273//   * written by `Mnemo::ingest_thread` + the `mnemo thread ingest`
274//     CLI from a transcript file in either a generic JSONL shape or
275//     Claude Code's JSONL (`~/.claude/projects/<p>/<s>.jsonl`),
276//   * grouped by `_mnemo.thread = <id>` for `thread export` /
277//     `thread forget` and the 12.7b essence render.
278// ---------------------------------------------------------------------------
279
280/// Record kind for thread-archive turns (Phase 12.7a). Value: `"turn"`.
281pub const MNEMO_META_KIND: &str = "_mnemo.kind";
282
283/// Thread identifier the record belongs to (Phase 12.7a). Value: a
284/// caller-supplied string, typically the Claude Code session uuid or
285/// the planner-chosen thread slug.
286pub const MNEMO_META_THREAD: &str = "_mnemo.thread";
287
288/// Monotonically increasing sequence number within the thread
289/// (Phase 12.7a). Value: unsigned integer, 0-based. Lets
290/// `thread export` reconstruct the transcript in order.
291pub const MNEMO_META_SEQ: &str = "_mnemo.seq";
292
293/// Role of the turn's author (Phase 12.7a). Value: `"user"`,
294/// `"assistant"`, `"system"`, `"tool"`, or any other string the
295/// source transcript used.
296pub const MNEMO_META_ROLE: &str = "_mnemo.role";
297
298/// Opaque per-turn identifier from the source transcript
299/// (Phase 12.7a). Value: typically a uuid4. Used for idempotence —
300/// `ingest_thread` skips any turn whose `turn_id` already exists on a
301/// record in the target thread.
302pub const MNEMO_META_TURN_ID: &str = "_mnemo.turn_id";
303
304/// Zero-based part number for a turn that was chunked at the 8 KB
305/// boundary during ingest (Phase 12.7a). Absent → the turn fits in a
306/// single record.
307pub const MNEMO_META_PART: &str = "_mnemo.part";
308
309/// Hex-encoded SHA-256 of the original tool-result content
310/// (Phase 12.7a). Set when the content exceeded the 16 KB truncation
311/// cap during ingest; absent otherwise.
312pub const MNEMO_META_SHA256: &str = "_mnemo.sha256";
313
314/// Byte length of the original tool-result content (Phase 12.7a). Set
315/// alongside `_mnemo.sha256` when truncation happened; absent
316/// otherwise.
317pub const MNEMO_META_LENGTH: &str = "_mnemo.length";
318
319/// Marker value for `_mnemo.kind` on thread-turn records.
320pub const MNEMO_META_KIND_TURN: &str = "turn";
321
322/// v0.16.1: `true` on a turn whose content is only the markers a
323/// transcript reader makes for blocks it doesn't keep (`[thinking]`,
324/// `[tool_use name=…]`, `[tool_result ok, N bytes]`, `[image]`). Such a
325/// turn is kept in the thread, so `thread export` shows the whole flow,
326/// but it isn't embedded (it carries the sentinel vector) and `recall`
327/// never returns it, since it would match any query weakly. `recall`
328/// leaves out a marker-only turn written before v0.16.1 too, by its
329/// content.
330pub const MNEMO_META_MARKERS_ONLY: &str = "_mnemo.markers_only";
331
332/// Maximum content size for a single turn record before chunking kicks
333/// in (Phase 12.7a). 8 KB per chunk keeps each record small enough
334/// that the per-record page cost dominates — and so that a thread of
335/// mostly short messages ingests as one record each.
336pub const THREAD_TURN_CHUNK_BYTES: usize = 8 * 1024;
337
338/// Maximum content size for a tool-result turn before truncation
339/// (Phase 12.7a). Tool results frequently run tens of kilobytes;
340/// stored truncated with `_mnemo.sha256` + `_mnemo.length` so the
341/// original can be recovered (or verified) out-of-band.
342pub const THREAD_TOOL_RESULT_TRUNCATE_BYTES: usize = 16 * 1024;
343
344// ---------------------------------------------------------------------------
345// Phase 12.7b: status-record core + essence (timeline + sections). The
346// essence layer rides on the same reserved-metadata namespace as the
347// thread archive, so a file keeps the single `_mnemo.*` convention:
348//
349// - `_mnemo.kind = "essence"` identifies an essence record. Section
350//   is in `_mnemo.section`. Scope — thread or project — is in
351//   `_mnemo.thread` (string) or absent (`None` means project scope).
352// - `_mnemo.status` carries the lifecycle for section items
353//   (`"open"` → `"resolved"`). Timeline entries never get a status.
354// - `_mnemo.status_history` records the status transitions. One
355//   element per transition: `{"status": "...", "at": <unix_secs>}`.
356// - `_mnemo.refs` is an optional array of free-form reference
357//   strings (turn ids, memory ids, commits, paths).
358// ---------------------------------------------------------------------------
359
360/// Reserved `_mnemo.section` key — which essence section an item
361/// belongs to (Phase 12.7b). Values: `"timeline"`, `"intent"`,
362/// `"conventions"`, `"decisions"`, `"state"`, `"open"`, `"next"`,
363/// `"lessons"`. Timeline entries are append-only.
364pub const MNEMO_META_SECTION: &str = "_mnemo.section";
365
366/// Reserved `_mnemo.status` key — current status of a status-record.
367/// Values are per-kind (Phase 12.7b: essence uses `"open"` and
368/// `"resolved"`). Timeline entries never carry this.
369pub const MNEMO_META_STATUS: &str = "_mnemo.status";
370
371/// Reserved `_mnemo.status_history` key — array of status transitions,
372/// each `{"status": <str>, "at": <unix_secs>}`. Append-only — the
373/// first entry records creation, each later entry records a
374/// transition.
375pub const MNEMO_META_STATUS_HISTORY: &str = "_mnemo.status_history";
376
377/// Reserved `_mnemo.refs` key — optional array of free-form reference
378/// strings (turn ids, memory ids, commits, paths) attached to an
379/// essence record (Phase 12.7b).
380pub const MNEMO_META_REFS: &str = "_mnemo.refs";
381
382/// Marker value for `_mnemo.kind` on essence records (Phase 12.7b).
383pub const MNEMO_META_KIND_ESSENCE: &str = "essence";
384
385/// Maximum content length for a timeline entry (Phase 12.7b).
386/// Entries over this are rejected, not truncated — the planner's
387/// spec is explicit about this because truncation would lose the
388/// narrative, and splitting across records would lose ordering.
389pub const ESSENCE_TIMELINE_MAX_BYTES: usize = 600;
390
391/// Maximum content length for a section item (Phase 12.7b).
392/// intent / conventions / decisions / state / open / next / lessons
393/// all share the same single-line cap. Items over this are rejected.
394pub const ESSENCE_SECTION_MAX_BYTES: usize = 280;
395
396/// Default byte budget for [`crate::Mnemo::essence`] rendering
397/// (Phase 12.7b). Matches the planner's "max_bytes = 6144" spec,
398/// which sits comfortably below a 4K-token context window.
399pub const ESSENCE_DEFAULT_RENDER_BYTES: usize = 6144;
400
401/// Which essence section an item belongs to.
402///
403/// Rendering order is fixed at this type's declaration order:
404/// intent → conventions → decisions → state → open → next → lessons
405/// → timeline. See [`EssenceSection::render_order`] for the explicit
406/// list and the [`crate::Mnemo::essence`] docs for per-section rules
407/// (timeline is append-only, every other section is item-edited).
408#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
409pub enum EssenceSection {
410    /// What the thread is trying to do.
411    Intent,
412    /// How the user works — conventions that survive across threads.
413    Conventions,
414    /// Decisions made and why (newest first on render).
415    Decisions,
416    /// The current state of the work.
417    State,
418    /// Open problems.
419    Open,
420    /// What to do next.
421    Next,
422    /// Lessons learned — mistakes caught and their fixes.
423    Lessons,
424    /// Append-only milestone timeline. Entries capped at
425    /// [`ESSENCE_TIMELINE_MAX_BYTES`] and never editable.
426    Timeline,
427}
428
429impl EssenceSection {
430    /// Section → stable `_mnemo.section` string.
431    pub fn as_str(&self) -> &'static str {
432        match self {
433            EssenceSection::Intent => "intent",
434            EssenceSection::Conventions => "conventions",
435            EssenceSection::Decisions => "decisions",
436            EssenceSection::State => "state",
437            EssenceSection::Open => "open",
438            EssenceSection::Next => "next",
439            EssenceSection::Lessons => "lessons",
440            EssenceSection::Timeline => "timeline",
441        }
442    }
443
444    /// Parse a string from `_mnemo.section` into the typed enum.
445    /// Case-insensitive; returns `None` on unknown input.
446    pub fn parse(s: &str) -> Option<EssenceSection> {
447        match s.to_ascii_lowercase().as_str() {
448            "intent" => Some(EssenceSection::Intent),
449            "conventions" => Some(EssenceSection::Conventions),
450            "decisions" => Some(EssenceSection::Decisions),
451            "state" => Some(EssenceSection::State),
452            "open" => Some(EssenceSection::Open),
453            "next" => Some(EssenceSection::Next),
454            "lessons" => Some(EssenceSection::Lessons),
455            "timeline" => Some(EssenceSection::Timeline),
456            _ => None,
457        }
458    }
459
460    /// Fixed render order (intent → conventions → decisions → state
461    /// → open → next → lessons → timeline). The [`crate::Mnemo::essence`]
462    /// render walks this list, allocating a per-section byte budget
463    /// proportional to section importance in the user-centric order.
464    pub fn render_order() -> &'static [EssenceSection] {
465        &[
466            EssenceSection::Intent,
467            EssenceSection::Conventions,
468            EssenceSection::Decisions,
469            EssenceSection::State,
470            EssenceSection::Open,
471            EssenceSection::Next,
472            EssenceSection::Lessons,
473            EssenceSection::Timeline,
474        ]
475    }
476
477    /// `true` for sections whose items carry an `open → resolved`
478    /// status lifecycle (every section except [`EssenceSection::Timeline`]).
479    pub fn has_status_lifecycle(&self) -> bool {
480        !matches!(self, EssenceSection::Timeline)
481    }
482
483    /// Per-section byte cap for new items. Timeline: 600 bytes.
484    /// Every other section: 280 bytes.
485    pub fn item_max_bytes(&self) -> usize {
486        match self {
487            EssenceSection::Timeline => ESSENCE_TIMELINE_MAX_BYTES,
488            _ => ESSENCE_SECTION_MAX_BYTES,
489        }
490    }
491}
492
493/// Scope selector for an essence item (Phase 12.7b). Thread-scoped
494/// items belong to one `_mnemo.thread`; project-scoped items are
495/// shared across every thread in the file.
496#[derive(Debug, Clone, PartialEq, Eq, Hash)]
497pub enum EssenceScope {
498    /// Belongs to one thread (the string). Shows up in that
499    /// thread's render only.
500    Thread(String),
501    /// Shared across every thread in the file. Shows up in every
502    /// thread's render, and in the `about` briefing: the CLI and MCP
503    /// `about` append the project render after the manifest, from
504    /// `Mnemo::about_essence()` (12.7d).
505    Project,
506}
507
508/// Status values the essence section supports (Phase 12.7b). More
509/// kinds (tasks: `queued → active → ready → done | blocked`;
510/// findings: `open → accepted | deferred | rejected | needs-user →
511/// verified`) ship with Phase 13 reusing the same status-record
512/// core; the transition tables for those are declared as constants
513/// in this crate but currently unused.
514pub mod status {
515    /// Freshly-added section item.
516    pub const OPEN: &str = "open";
517    /// The user-facing concern has been addressed.
518    pub const RESOLVED: &str = "resolved";
519}
520
521/// Task transition table (declared for Phase 13; currently unused
522/// in the engine). `queued → active → ready → done | blocked`,
523/// with `blocked → active` as the only back-edge.
524pub const TASK_TRANSITIONS: &[(&str, &str)] = &[
525    ("queued", "active"),
526    ("active", "ready"),
527    ("active", "blocked"),
528    ("blocked", "active"),
529    ("ready", "done"),
530];
531
532/// Finding transition table (declared for Phase 13; currently unused
533/// in the engine). `open → {accepted | deferred | rejected |
534/// needs-user} → verified`.
535pub const FINDING_TRANSITIONS: &[(&str, &str)] = &[
536    ("open", "accepted"),
537    ("open", "deferred"),
538    ("open", "rejected"),
539    ("open", "needs-user"),
540    ("accepted", "verified"),
541    ("deferred", "verified"),
542    ("needs-user", "verified"),
543];
544
545/// Essence transition table for Phase 12.7b. Only `open → resolved`
546/// is allowed. Timeline entries don't use this (they're append-only
547/// and have no status).
548pub const ESSENCE_TRANSITIONS: &[(&str, &str)] = &[(status::OPEN, status::RESOLVED)];
549
550// ---------------------------------------------------------------------------
551// Phase 12.7c: continuation + commit_deltas
552// ---------------------------------------------------------------------------
553
554/// Reserved `_mnemo.continues` key (Phase 12.7c). Set on a
555/// thread-start marker record to point at the previous thread whose
556/// context the new thread continues from. Value: the prior thread id
557/// (string). Rendering a continued thread pulls the prior thread's
558/// open items, `next` and last-N timeline entries ahead of the new
559/// thread's own essence.
560pub const MNEMO_META_CONTINUES: &str = "_mnemo.continues";
561
562/// Marker value for `_mnemo.kind` on a thread-start record (one per
563/// `thread_start(new, --from old)` call, carrying the link in
564/// `_mnemo.continues`).
565pub const MNEMO_META_KIND_THREAD_LINK: &str = "thread_link";
566
567/// How many timeline entries from the predecessor thread the
568/// continuation render pulls in (Phase 12.7c). Small enough to keep
569/// the render under the default 6 KB budget, large enough to carry a
570/// handful of milestones.
571pub const CONTINUATION_TIMELINE_ENTRIES: usize = 10;
572
573/// What [`crate::Mnemo::commit_deltas`] does with the `turns` carried
574/// in the batch (Phase 12.7c).
575#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
576pub enum TurnPolicy {
577    /// Archive every turn in the batch via
578    /// [`crate::Mnemo::ingest_thread`]. Default — matches the
579    /// "lossless flow preservation" story of 12.7.
580    #[default]
581    Archive,
582    /// Store turns with a TTL (unix-seconds expiry).
583    ExpireAfter(i64),
584    /// Drop turns on the floor (no archive record written).
585    Drop,
586}
587
588/// Which op a [`EssenceOp`] carries. Mirrors the per-method
589/// `Mnemo::essence_*` surface so one batch can mix section + timeline
590/// edits in one call.
591#[derive(Debug, Clone, PartialEq, Eq)]
592pub enum EssenceOpKind {
593    /// Section item add (any section except timeline).
594    Add,
595    /// Append-only timeline entry.
596    AppendTimeline,
597    /// In-place update of an existing section item.
598    Update,
599    /// Transition an item `open → resolved`.
600    Resolve,
601    /// Soft-delete an item.
602    Remove,
603}
604
605/// One essence op inside a [`CommitBatch`] (Phase 12.7c). Validation
606/// (missing/extra fields per kind) runs up front in
607/// [`crate::Mnemo::commit_deltas`] — a single bad op aborts the
608/// whole batch before any write lands.
609#[derive(Debug, Clone)]
610pub struct EssenceOp {
611    /// Which op to apply.
612    pub kind: EssenceOpKind,
613    /// Scope — required for [`EssenceOpKind::Add`] and
614    /// [`EssenceOpKind::AppendTimeline`].
615    pub scope: Option<EssenceScope>,
616    /// Section — required for [`EssenceOpKind::Add`].
617    pub section: Option<EssenceSection>,
618    /// Target record id — required for [`EssenceOpKind::Update`],
619    /// [`EssenceOpKind::Resolve`], [`EssenceOpKind::Remove`].
620    pub id: Option<Ulid>,
621    /// Content text — required for [`EssenceOpKind::Add`],
622    /// [`EssenceOpKind::AppendTimeline`], [`EssenceOpKind::Update`].
623    pub text: Option<String>,
624    /// Optional refs for ops that carry text.
625    pub refs: Option<Vec<String>>,
626}
627
628/// One keyed fact inside a [`CommitBatch`] (Phase 12.7c).
629#[derive(Debug, Clone)]
630pub struct KeyedMemory {
631    /// The memory to store. An **empty `vector`** means "embed
632    /// `content` with the registered embedder" (12.7d): every such fact
633    /// in a batch is embedded together in one `Embedder::embed` call.
634    pub memory: Memory,
635    /// Optional 12.1 upsert key.
636    pub key: Option<String>,
637}
638
639/// Atomic write batch for [`crate::Mnemo::commit_deltas`]
640/// (Phase 12.7c). The planner's "one call that composes facts +
641/// essence + turns" shape: everything validates up front, then every
642/// write runs under a single `flush()`.
643#[derive(Debug, Clone, Default)]
644pub struct CommitBatch {
645    /// Keyed-or-not facts to remember (12.1).
646    pub facts: Vec<KeyedMemory>,
647    /// Essence ops to apply (12.7b).
648    pub essence_ops: Vec<EssenceOp>,
649    /// Thread archive turns to ingest (12.7a).
650    pub turns: Vec<ThreadTurn>,
651    /// Destination thread id for `turns`. Required when `turns` is
652    /// non-empty.
653    pub thread_id: Option<String>,
654    /// What to do with `turns` — defaults to `Archive`.
655    pub turn_policy: TurnPolicy,
656}
657
658/// Result of [`crate::Mnemo::commit_deltas`] (Phase 12.7c).
659#[derive(Debug, Clone, Default, PartialEq, Eq)]
660pub struct CommitReport {
661    /// Facts added (plain or `WriteOutcome::Added`).
662    pub facts_added: usize,
663    /// Facts whose keyed write superseded a prior record.
664    pub facts_superseded: usize,
665    /// Keyed facts whose write was a no-op (matched live record).
666    pub facts_unchanged: usize,
667    /// Essence ops that produced an Added/Updated result.
668    pub essence_ops_applied: usize,
669    /// Essence ops that were no-ops (e.g. `resolve` on resolved).
670    pub essence_ops_unchanged: usize,
671    /// Turn records written to the archive.
672    pub turns_added: usize,
673    /// Source turns skipped by the archive's idempotence check.
674    pub turns_skipped: usize,
675    /// Source turns whose content was truncated at the 16 KB cap.
676    pub turns_truncated: usize,
677    /// Source turns split into multiple 8 KB chunks.
678    pub turns_chunked: usize,
679}
680
681/// Patch body for [`crate::Mnemo::update`] (Phase 12.1): every field is
682/// optional, and only the `Some(...)` fields overwrite the corresponding
683/// field on the target memory. All fields can be set independently.
684///
685/// `content` paired with `vector` updates both at once — the engine does
686/// not re-embed under `update` (use `update_text` for that). A `content`
687/// change without a new `vector` is rejected to prevent the embedding
688/// drifting silently out of sync with the text.
689///
690/// `metadata` **replaces** the full user-metadata map — the engine's own
691/// `_mnemo.*` reserved keys on the target record are preserved across
692/// the replacement (updated-at timestamp, supersession markers, etc.).
693/// Passing an empty map drops every user-visible metadata key but keeps
694/// the reserved ones.
695///
696/// `ttl_secs` is `Option<Option<i64>>` so a caller can distinguish
697/// "leave it alone" (`None`) from "set it to a value" (`Some(Some(s))`)
698/// and "clear it" (`Some(None)`).
699#[derive(Debug, Clone, Default)]
700pub struct MemoryPatch {
701    /// New text content. If set, a matching `vector` must also be set
702    /// (or call `update_text`, which re-embeds through the registered
703    /// embedder).
704    pub content: Option<String>,
705    /// New embedding. Must match the database's dimensionality.
706    pub vector: Option<Vec<f32>>,
707    /// New importance in `[0, 1]`.
708    pub importance: Option<f32>,
709    /// Replace the memory type.
710    pub memory_type: Option<MemoryType>,
711    /// Replace the user-visible metadata (preserves `_mnemo.*` reserved
712    /// keys).
713    pub metadata: Option<Map<String, Value>>,
714    /// Change the TTL. Outer `None` → leave unchanged; `Some(Some(s))` →
715    /// set TTL to `s`; `Some(None)` → clear any existing TTL.
716    pub ttl_secs: Option<Option<i64>>,
717}
718
719/// One turn fed into [`crate::Mnemo::ingest_thread`] (Phase 12.7a).
720///
721/// The caller supplies `turn_id` (opaque, for idempotence), `role`
722/// (the transcript's author tag; no interpretation), and `content`
723/// (UTF-8 text; chunked at 8 KB, or truncated at 16 KB when `role ==
724/// "tool"`). The ingest path assigns `_mnemo.seq` monotonically within
725/// the destination thread and embeds through the registered embedder.
726///
727/// Tool messages whose content exceeds [`THREAD_TOOL_RESULT_TRUNCATE_BYTES`]
728/// are stored truncated. Other roles over [`THREAD_TURN_CHUNK_BYTES`]
729/// are chunked.
730#[derive(Debug, Clone)]
731pub struct ThreadTurn {
732    /// Opaque per-turn id from the source transcript (e.g. a Claude
733    /// Code message uuid). Used for `ingest_thread`'s idempotence
734    /// check: a turn whose `turn_id` already exists in the target
735    /// thread is skipped.
736    pub turn_id: String,
737    /// Author role verbatim from the transcript (`"user"`,
738    /// `"assistant"`, `"system"`, `"tool"`, …). `"tool"` triggers
739    /// the 16 KB truncation branch; all other roles go through the
740    /// 8 KB chunking branch.
741    pub role: String,
742    /// UTF-8 message content.
743    pub content: String,
744    /// Optional caller-supplied creation timestamp (unix seconds).
745    /// If `None`, the ingest path uses `now_secs()` so the record's
746    /// `created_at` still sorts the thread in order. Transcripts
747    /// that carry a per-turn timestamp should pass it through so a
748    /// future `thread export --by-time` can honour it.
749    pub timestamp: Option<i64>,
750}
751
752/// One turn of a thread's archive in the **ingest shape** (Phase 12.7d),
753/// as returned by [`crate::Mnemo::thread_export_turns`] and by Python
754/// `db.thread_export`, MCP `thread_export` and `mnemo thread export`.
755///
756/// Turns come back in `_mnemo.seq` order, one entry per source turn: the
757/// 8 KB chunks of a long turn are joined back into one `content`, so
758/// feeding the list to `ingest_thread` (same thread: every turn is
759/// skipped; a new thread: the turns are re-chunked identically) round
760/// trips. A tool result that was truncated at 16 KB carries `sha256` and
761/// `original_length` of the original content.
762#[derive(Debug, Clone, PartialEq, Eq)]
763pub struct ExportedTurn {
764    /// Source `turn_id` (`_mnemo.turn_id`).
765    pub turn_id: String,
766    /// Author role (`_mnemo.role`).
767    pub role: String,
768    /// Stored text, with chunks joined in `_mnemo.part` order.
769    pub content: String,
770    /// The turn's timestamp (unix seconds; the record's `created_at`).
771    pub timestamp: i64,
772    /// Hex SHA-256 of the original content, set only for a truncated
773    /// tool result.
774    pub sha256: Option<String>,
775    /// Byte length of the original content, set only for a truncated
776    /// tool result.
777    pub original_length: Option<u64>,
778}
779
780impl ExportedTurn {
781    /// The JSON object shared by the MCP tool and the CLI JSONL export:
782    /// `{turn_id, role, content, timestamp}` plus `sha256` and
783    /// `original_length` when the turn was truncated.
784    pub fn to_json(&self) -> serde_json::Value {
785        let mut obj = serde_json::json!({
786            "turn_id": self.turn_id,
787            "role": self.role,
788            "content": self.content,
789            "timestamp": self.timestamp,
790        });
791        if let Some(sha) = &self.sha256 {
792            obj["sha256"] = serde_json::Value::String(sha.clone());
793        }
794        if let Some(len) = self.original_length {
795            obj["original_length"] = serde_json::Value::Number(len.into());
796        }
797        obj
798    }
799}
800
801/// Result of one [`crate::Mnemo::ingest_thread`] call (Phase 12.7a).
802#[derive(Debug, Clone, Default, PartialEq, Eq)]
803pub struct IngestReport {
804    /// Number of **new** records written (turn chunks after chunking
805    /// / truncation). A long turn counts as however many chunks it
806    /// produced.
807    pub added_records: usize,
808    /// Number of **source turns** that already had a record in the
809    /// target thread and were skipped by the idempotence check.
810    pub skipped_existing_turns: usize,
811    /// Number of turns whose content was truncated at the 16 KB cap.
812    /// Only `role == "tool"` turns can trigger this branch.
813    pub truncated_turns: usize,
814    /// Number of turns that were split into multiple chunks at the
815    /// 8 KB boundary. A truncated turn counts as 0 here even if its
816    /// pre-truncation content would have chunked.
817    pub chunked_turns: usize,
818}
819
820/// Scope selector for a keyed slot (Phase 12.1.1). A keyed
821/// `remember`'s slot is always identified by `(scope_owner, key)`:
822/// `Private(agent_id)` slots are per-agent, `Shared` slots are per-file.
823/// `history_in(key, scope)` uses the same selector so the lookup matches
824/// the write exactly.
825///
826/// The convenience [`crate::Mnemo::history`] is equivalent to
827/// `history_in(key, KeyScope::Private(agent.unwrap_or("default")))` —
828/// i.e. `history(key, None)` resolves to the default agent's private
829/// slot, matching the `remember(…, agent_id=None, scope=Private, key=K)`
830/// write path. Use [`crate::Mnemo::history_in`] with
831/// [`KeyScope::Shared`] when you need the shared slot.
832#[derive(Debug, Clone, PartialEq, Eq, Hash)]
833pub enum KeyScope {
834    /// Per-agent slot. The agent id is the one carried on `Memory.agent_id`
835    /// at write time; `remember` with no explicit agent uses `"default"`.
836    Private(String),
837    /// Per-file slot shared across every agent.
838    Shared,
839}
840
841impl KeyScope {
842    /// Default agent id used when `Memory::new(...)` is called without
843    /// `.with_agent(...)` — same `"default"` the [`Memory::new`]
844    /// constructor seeds into `Memory.agent_id`.
845    pub const DEFAULT_AGENT: &'static str = "default";
846
847    /// Build the private slot for the default agent. Shorthand for
848    /// `KeyScope::Private(KeyScope::DEFAULT_AGENT.to_string())`.
849    pub fn private_default() -> Self {
850        KeyScope::Private(Self::DEFAULT_AGENT.to_string())
851    }
852}
853
854/// Outcome of a 12.1 write operation (`remember` with `key`, or `update`).
855///
856/// Plain `remember` without a key always returns a ULID, not a
857/// `WriteOutcome`, because supersession and NOOP detection are tied to
858/// the key slot.
859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
860pub enum WriteOutcome {
861    /// Keyed write with no prior record for this slot. A brand-new record
862    /// was inserted, no record was superseded.
863    Added,
864    /// Keyed write whose content / type / importance / user metadata
865    /// differs from the live record for this slot. A new record was
866    /// inserted and the prior one was marked
867    /// `_mnemo.superseded_by` / `_mnemo.invalid_at`.
868    Superseded,
869    /// No-op: the incoming keyed write is byte-equal to the live record
870    /// for this slot (content, memory type, importance, user metadata).
871    /// No record was written and no catalog page was dirtied. The
872    /// returned id is the existing record's id.
873    Unchanged,
874    /// In-place `update`: fields changed on the target record. The record
875    /// was rewritten copy-on-write so the previous version remains
876    /// visible through snapshots.
877    Updated,
878}
879
880// ---------------------------------------------------------------------------
881// Phase 12.6: recall filters (session_id + per-metadata-key conditions)
882// ---------------------------------------------------------------------------
883
884/// One AND-ed condition applied to a candidate memory's metadata during
885/// filtered recall (Phase 12.6). Terms are combined conjunctively — a
886/// memory passes the filter only if *every* term evaluates true against
887/// its `metadata` map. See [`Filter`] for the surface API.
888///
889/// Values use `serde_json::Value` so the same term shape serializes
890/// cleanly through the MCP / Python / CLI bridges without a parallel
891/// enum per surface.
892#[derive(Debug, Clone)]
893pub enum FilterTerm {
894    /// The memory's `metadata[key]` must be set to any value.
895    Exists(String),
896    /// `metadata[key]` must equal this JSON value (strict JSON equality:
897    /// strings compare case-sensitively, numbers compare as f64).
898    Eq(String, Value),
899    /// `metadata[key]` must equal one of these JSON values.
900    In(String, Vec<Value>),
901    /// `metadata[key]` must be a number in `[min, max]` (inclusive on
902    /// both ends; `None` on either bound means "no bound on that side").
903    /// A non-numeric metadata value fails the term.
904    Range {
905        /// Metadata key.
906        key: String,
907        /// Lower bound (inclusive) — `None` means unbounded below.
908        min: Option<f64>,
909        /// Upper bound (inclusive) — `None` means unbounded above.
910        max: Option<f64>,
911    },
912}
913
914/// Pre-scoring filter applied by [`crate::Mnemo::recall`] (Phase 12.6).
915///
916/// `session_id` restricts candidates to a single session (when the
917/// memory's `session_id` is set). The `terms` are AND-ed metadata
918/// conditions evaluated against each candidate's `metadata` map; see
919/// [`FilterTerm`] for the shapes.
920///
921/// When an ANN index is present, the filter is applied *after* the ANN
922/// shortlist step, so a selective filter can starve the result below
923/// `top_k`. Recall handles that automatically via the Phase 12.1
924/// short-results-on-indexed-path fix (widen 2×, then exact scan).
925#[derive(Debug, Clone, Default)]
926pub struct Filter {
927    /// Only candidates whose `Memory.session_id` equals this value.
928    /// Candidates without a session_id are excluded when this is set.
929    pub session_id: Option<String>,
930    /// AND-ed metadata conditions. Empty → no metadata constraints.
931    pub terms: Vec<FilterTerm>,
932}
933
934impl Filter {
935    /// Builder helper: a filter that keeps only memories in `session`.
936    pub fn new_session(session: impl Into<String>) -> Self {
937        Self {
938            session_id: Some(session.into()),
939            terms: Vec::new(),
940        }
941    }
942
943    /// Restrict to one session_id (builder form).
944    pub fn with_session(mut self, session: impl Into<String>) -> Self {
945        self.session_id = Some(session.into());
946        self
947    }
948
949    /// Require `metadata[key]` to exist (any value).
950    pub fn metadata_exists(mut self, key: impl Into<String>) -> Self {
951        self.terms.push(FilterTerm::Exists(key.into()));
952        self
953    }
954
955    /// Require `metadata[key]` to equal `value`.
956    pub fn metadata_eq(mut self, key: impl Into<String>, value: Value) -> Self {
957        self.terms.push(FilterTerm::Eq(key.into(), value));
958        self
959    }
960
961    /// Require `metadata[key]` to be one of `values`.
962    pub fn metadata_in(mut self, key: impl Into<String>, values: Vec<Value>) -> Self {
963        self.terms.push(FilterTerm::In(key.into(), values));
964        self
965    }
966
967    /// Require `metadata[key]` to be a number in `[min, max]`.
968    pub fn metadata_range(
969        mut self,
970        key: impl Into<String>,
971        min: Option<f64>,
972        max: Option<f64>,
973    ) -> Self {
974        self.terms.push(FilterTerm::Range {
975            key: key.into(),
976            min,
977            max,
978        });
979        self
980    }
981
982    /// `true` iff the filter has no terms and no `session_id`. The
983    /// recall hot path uses this to skip the per-candidate filter
984    /// check entirely.
985    pub fn is_empty(&self) -> bool {
986        self.session_id.is_none() && self.terms.is_empty()
987    }
988
989    /// Phase 12.7a: `true` iff the filter mentions any reserved
990    /// `_mnemo.*` metadata key. Used by `recall` to decide whether
991    /// to default-exclude thread-archive turns
992    /// (`_mnemo.kind = "turn"`). A caller that wants turns in the
993    /// result opts in by adding any `_mnemo.*` term to the filter
994    /// — equality, `$in`, `$exists`, or range — because those are the
995    /// only queries that can usefully target turn records.
996    pub fn mentions_mnemo_meta(&self) -> bool {
997        self.terms.iter().any(|term| {
998            let key = match term {
999                FilterTerm::Exists(k) => k,
1000                FilterTerm::Eq(k, _) => k,
1001                FilterTerm::In(k, _) => k,
1002                FilterTerm::Range { key, .. } => key,
1003            };
1004            key.starts_with(MNEMO_META_NS)
1005        })
1006    }
1007
1008    /// Evaluate the filter against one memory. Returns `true` if the
1009    /// memory passes every term.
1010    pub fn matches(&self, m: &Memory) -> bool {
1011        if let Some(s) = &self.session_id {
1012            match &m.session_id {
1013                Some(ms) if ms == s => {}
1014                _ => return false,
1015            }
1016        }
1017        for term in &self.terms {
1018            if !term_matches(term, &m.metadata) {
1019                return false;
1020            }
1021        }
1022        true
1023    }
1024}
1025
1026fn term_matches(term: &FilterTerm, metadata: &Map<String, Value>) -> bool {
1027    match term {
1028        FilterTerm::Exists(key) => metadata.contains_key(key),
1029        FilterTerm::Eq(key, v) => metadata.get(key).is_some_and(|got| values_equal(got, v)),
1030        FilterTerm::In(key, options) => metadata
1031            .get(key)
1032            .is_some_and(|got| options.iter().any(|opt| values_equal(got, opt))),
1033        FilterTerm::Range { key, min, max } => metadata
1034            .get(key)
1035            .and_then(|v| v.as_f64())
1036            .is_some_and(|n| min.is_none_or(|m_| n >= m_) && max.is_none_or(|m_| n <= m_)),
1037    }
1038}
1039
1040/// JSON value equality for filter terms. serde_json's `Value: PartialEq`
1041/// compares numbers by exact representation (integer vs float). The
1042/// filter surface should treat `5` and `5.0` as equal, so we compare
1043/// numbers through `as_f64` when both sides are numbers; everything
1044/// else falls back to structural equality.
1045fn values_equal(a: &Value, b: &Value) -> bool {
1046    match (a, b) {
1047        (Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
1048            (Some(xf), Some(yf)) => (xf - yf).abs() < f64::EPSILON,
1049            _ => x == y,
1050        },
1051        (x, y) => x == y,
1052    }
1053}
1054
1055/// Distance/similarity metric for vector comparison.
1056#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1057pub enum Metric {
1058    /// Cosine similarity (orientation only).
1059    Cosine,
1060    /// Negative Euclidean distance, mapped into a `(0,1]` similarity.
1061    L2,
1062    /// Raw dot product.
1063    Dot,
1064}
1065
1066/// Compute a *similarity* (higher = more relevant) under the given metric.
1067pub fn similarity(metric: Metric, a: &[f32], b: &[f32]) -> f32 {
1068    match metric {
1069        Metric::Cosine => cosine(a, b),
1070        Metric::Dot => dot(a, b),
1071        Metric::L2 => {
1072            let d = euclidean(a, b);
1073            1.0 / (1.0 + d)
1074        }
1075    }
1076}
1077
1078fn dot(a: &[f32], b: &[f32]) -> f32 {
1079    a.iter().zip(b).map(|(x, y)| x * y).sum()
1080}
1081
1082/// Cosine similarity in `[-1.0, 1.0]`; returns `0.0` if either vector
1083/// has zero magnitude. `pub(crate)` so [`crate::Mnemo::cache_get_semantic`]
1084/// (Phase 10.2) can reuse the same scoring routine that recall uses,
1085/// keeping the two paths semantically identical.
1086pub(crate) fn cosine(a: &[f32], b: &[f32]) -> f32 {
1087    let na = dot(a, a).sqrt();
1088    let nb = dot(b, b).sqrt();
1089    if na == 0.0 || nb == 0.0 {
1090        0.0
1091    } else {
1092        dot(a, b) / (na * nb)
1093    }
1094}
1095
1096fn euclidean(a: &[f32], b: &[f32]) -> f32 {
1097    a.iter()
1098        .zip(b)
1099        .map(|(x, y)| (x - y) * (x - y))
1100        .sum::<f32>()
1101        .sqrt()
1102}
1103
1104/// Weights for the multi-signal recall score (scoring v2, shipped in
1105/// v0.7.0).
1106///
1107/// ```text
1108/// score = similarity
1109///       + max(similarity, 0)
1110///         · ( β · recency
1111///           + γ · (importance − 0.5)
1112///           + δ · tanh(access_count / 5) )
1113///
1114/// recency = exp( -ln(2) · age_secs / half_life_secs )
1115/// age_secs = now - memory.created_at
1116/// ```
1117///
1118/// Design notes (from the 2026-11-06 scoring-v2 bake-off; see the
1119/// `ranking_v2` harness at `mnemo/examples/ranking_v2.rs`):
1120/// * **Similarity-gated.** The recency / importance / usage terms are
1121///   multiplied by `max(similarity, 0)`, so a stale-but-semantically-off
1122///   memory can't ride recency or importance past a semantically-on-point
1123///   one. Pre-v0.7.0 scoring was purely additive.
1124/// * **Importance is centered at 0.5.** A default-importance memory
1125///   contributes zero importance bonus; importance only pushes a score up
1126///   or down from that reference point.
1127/// * **Usage is saturating.** `tanh(uses/5)` caps the feedback bonus so
1128///   a heavily-returned memory can't keep accumulating weight past a
1129///   plateau. At 5 uses the bonus is ~76% of its asymptote; at 10, ~96%.
1130/// * **Recency is decoupled from the feedback loop.** Age is measured
1131///   from `created_at`, not `accessed_at`, so a `recall()` call does not
1132///   bump its own results' recency scores on later queries.
1133///
1134/// The output of this scorer is on a **different scale** from the
1135/// pre-v0.7.0 formula. Callers that compared raw scores to a fixed
1136/// threshold should re-pick the threshold against the new scale.
1137#[derive(Clone, Copy, Debug)]
1138pub struct ScoreWeights {
1139    /// Weight on semantic similarity. Kept in the struct for calibration
1140    /// hooks and symmetry with the other weights; scoring v2 always uses
1141    /// it as `1.0` because the leading `similarity` term is ungated and
1142    /// the whole score sits on the cosine-similarity scale by design.
1143    pub alpha: f32,
1144    /// Weight on the recency bonus (multiplied by `max(sim, 0)`).
1145    pub beta: f32,
1146    /// Weight on the importance bonus `(importance − 0.5)`, centered at
1147    /// the default-importance 0.5 (multiplied by `max(sim, 0)`).
1148    pub gamma: f32,
1149    /// Weight on the saturating usage bonus `tanh(access_count / 5)`
1150    /// (multiplied by `max(sim, 0)`).
1151    pub delta: f32,
1152    /// Half-life of the recency term, in seconds.
1153    pub half_life_secs: f32,
1154}
1155
1156impl Default for ScoreWeights {
1157    fn default() -> Self {
1158        // Tuned on the Phase 6 corpus + the ranking_v2 age-spread
1159        // fixture; see `ranking_v2.checks` in perf_v0.5.0.json.
1160        Self {
1161            alpha: 1.0,
1162            beta: 0.3,
1163            gamma: 0.2,
1164            delta: 0.1,
1165            half_life_secs: 7.0 * 24.0 * 3600.0,
1166        }
1167    }
1168}
1169
1170/// Saturation constant K for the usage term `tanh(access_count / K)`.
1171/// K = 5 means ~76% of the asymptote at 5 uses and ~96% at 10 — matches
1172/// the "a few repeats is signal; past that it's a habit" intuition.
1173const USAGE_SAT_K: f32 = 5.0;
1174
1175impl ScoreWeights {
1176    /// Combine the four signals into a single score. See the struct docs
1177    /// for the full formula and the scoring-v2 rationale.
1178    pub fn score(&self, similarity: f32, age_secs: f32, importance: f32, access_count: u32) -> f32 {
1179        // Recency is in [0, 1]: 1.0 at age 0, 0.5 at one half-life, etc.
1180        let recency = (-std::f32::consts::LN_2 * age_secs.max(0.0) / self.half_life_secs).exp();
1181        // Saturating usage in [0, 1); tanh caps feedback-loop drift.
1182        let usage = (access_count as f32 / USAGE_SAT_K).tanh();
1183        // Gate the non-similarity bonuses by `max(sim, 0)` so a
1184        // negative-cosine candidate (should be rare after the metric
1185        // layer, but possible with `Metric::Dot` or short-text L2)
1186        // can't collect positive bonuses, and a zero-similarity
1187        // candidate collects no bonus either.
1188        let gate = similarity.max(0.0);
1189        self.alpha * similarity
1190            + gate * (self.beta * recency + self.gamma * (importance - 0.5) + self.delta * usage)
1191    }
1192}