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