# MNEMOSYNE: One Check on Every Memory Write: v1.6 → v2.0

From v1.6 (29 Jul) to v2.0 (12 Oct): 8,886 words to 9,244 words, 8,966 words in new or rewritten paragraphs and 8,608 taken out, 392 paragraphs changed.

## Change note of v2.0

**Rewritten as a new paper: one check on every memory write**

Almost the whole text is new (97 per cent changed), and so is the title: "MNEMOSYNE: One Check on Every Memory Write". The four-feature plugin is gone. The paper now argues one thing: every write to an agent's long-term memory should pass a single check inside the write tool, so no writer can skip it. The check compares the new text with facts on the same topic, with the rules the agent loads on every turn, and with what the current turn observed. A small model names the relation, only that judgement may retire an old fact, and the old line is struck through and kept with two dates.

- Opens with a plain picture: a good assistant's notebook, where a changed meeting is struck out and rewritten, never torn out.
- Four failures from practice motivate the design, among them a negative written as a fact and a retire rule that hides facts that never changed.
- New parts on what to write at all, where each fact came from, the shape of memory files, and what the check costs against what it saves.
- It is stated as a design with no results; section 12 names the tests that would decide it.

## Changed paragraphs

Marks: [-removed-] {+added+}.

### Abstract

[-Personal AI assistants that accumulate months of memory face four gaps that general-purpose retrieval systems do not close: concept lookup can become more expensive as the corpus grows, retrieval scoring ignores the agent's current task, memory writes can silently introduce contradictions, and context compaction can destroy information that was used once but never queried again. We present **MNEMOSYNE**, a plugin-layered enhancement suite that addresses these gaps without modifying the underlying memory-core codebase. MNEMOSYNE registers four hooks — `retrieval_pre`, `before_message_write`, `before_compaction`, and `after_compaction` — on top of OpenClaw's markdown-first memory system. The concept index has a production implementation; compaction-aware capture has a confirmed write and indexing path but lacks trustworthy liveness evidence because the upstream compaction trigger was mis-measured and some triggered compactions were later discarded. Task-conditioned retrieval scoring and the contradiction gate remain scaffolded. We also describe how the contradiction gate becomes a bi-temporal validity layer (§9.5): a contradicting write supersedes the prior fact by closing its validity interval, retaining full history for "true now" and "true then" queries. The validity substrate is not paper-only — memory-core already ships the validity columns, temporal search predicate, and supersede writer — but MNEMOSYNE still has to route the gate's decision into it. We position compaction capture against reversible Compress-Cache-Retrieve as implemented in chopratejas/headroom and report first-party operational measurements of trigger error and capture-filter yield. The central retrieval, validity-overhead, and answer-quality claims remain architectural rather than benchmarked. This paper is therefore an integration and deployment analysis, not evidence that the composed system outperforms current retrieval baselines.-]

### Abstract

{+Think of a good assistant's notebook. When your weekly call moves to Thursday, she does not tear out the page that said Wednesday. She strikes the line, writes Thursday beneath it with the date and who told her, and if the new note clashes with something pinned to the first page, she asks you before she writes. Years later the notebook is still worth trusting, because every line says where it came from and nothing was overwritten behind your back.+}

### Abstract

{+AI agents now keep notebooks of their own: memory files they write with ordinary file tools, in the middle of a conversation, during a nightly pass, or because another agent told them to. But most memory systems check a new memory only against the few stored memories that look most like it, delete what it contradicts, and keep no note of where a fact came from. So an old line in a file the agent reads on every turn can override a rule kept in another file, a guess comes back weeks later as if it had been observed, and a rule that retires old facts by their position in a file can hide facts that never changed.+}

### Abstract

{+We propose MNEMOSYNE, one check on every write to an agent's long-term memory, placed inside the tool that performs the write so that no writer can skip it. The check compares the new text with the facts on the same topic, with the rules the agent loads on every turn, and with what the current turn observed. A small model names the relation, and only that judgement can retire an old fact: the old line is struck through and kept, with two dates, one for when the change became true and one for when the agent learned it. Every fact carries its source (observed, told by the owner, inferred, assumed, or taken from untrusted content) and never an author. Before the check comes the choice of what to write: a live turn writes at once what the owner states and what contradicts the store, and a nightly pass picks the rest out of the day's session record.+}

### Abstract

{+In your own assistant, a correction made once stays made, a rule pinned to the first page beats an old note, a sentence lifted from a web page cannot become a standing instruction, and you can still ask what was true last month. The check costs one call to a small model; at published prices it pays for itself in money alone once about one write in sixty would have misled a single turn. This is a design, and §12 names the tests that would prove it.+}

### Abstract

{+If it holds, an agent's memory becomes something you can audit like a notebook and trust like one.+}

### 1.1 The Personal-Assistant vs Enterprise-Wiki Divergence

[-### 1.1 The Personal-Assistant vs Enterprise-Wiki Divergence-]

### 1.1 The Personal-Assistant vs Enterprise-Wiki Divergence

[-The memory-core library that MNEMOSYNE builds on was designed as a general-purpose memory system — part personal assistant, part enterprise wiki. It provides hybrid FTS5 full-text search, vector embeddings with cosine similarity, Maximal Marginal Relevance (MMR) deduplication, and temporal decay scoring. For an enterprise wiki where queries are well-formed and contexts are stable, this suite is sufficient.-]

### 1.1 The Personal-Assistant vs Enterprise-Wiki Divergence

[-A personal assistant diverges in three structural ways. First, queries are ambiguous: "what was that thing about the cron job?" contains no entity that FTS5 can match. Second, the agent context-switches constantly — from debugging cron tasks to drafting emails to reviewing code — and retrieval scoring should reflect this. Third, the agent writes its own memories autonomously through nightly consolidation cycles, and those writes can contradict earlier facts without any human review gate.-]

### 1.1 The Personal-Assistant vs Enterprise-Wiki Divergence

[-These divergences motivate a layered enhancement approach rather than a fork of memory-core.-]

### 1.2 Why a Plugin, Not a Fork

[-### 1.2 Why a Plugin, Not a Fork-]

### 1.2 Why a Plugin, Not a Fork

[-OpenClaw's plugin system provides four properties that make it the correct integration point:-]

### 1.2 Why a Plugin, Not a Fork

[-1. **Failure isolation.** A crash in MNEMOSYNE does not take down memory-core. The hook runner catches exceptions and logs them; the underlying retrieval continues unimpaired. 2. **Upgrade independence.** The memory-core library ships frequent updates. A plugin does not create merge conflicts. 3. **Distribution.** A single `tinkerclaw-memory-enhancements` package can be installed via ClawHub, OpenClaw's plugin marketplace, without users maintaining a fork. 4. **Composability.** Each of the four features can be independently enabled or disabled via plugin configuration.-]

### 1.3 Contributions

[-### 1.3 Contributions-]

### 1.3 Contributions

[-1. An O(1) concept index that short-circuits hybrid retrieval for known concepts (Feature 1). 2. A task-conditioned score modifier that biases retrieval toward the agent's current work (Feature 2). 3. A contradiction gate that intercepts memory writes before promotion to durable storage (Feature 3), and its bi-temporal evolution into a supersession layer (§9.5). 4. A compaction-aware capture pass that snapshots context before intended eviction, together with an operational analysis of trigger validity and filter yield (Feature 4). 5. A unified plugin architecture and a documented set of integration failure modes for delivering the four mechanisms as one unit.-]

### 2. Background and Related Work

[-## 2. Background and Related Work-]

### 2.1 Underlying Memory-Core Architecture

[-### 2.1 Underlying Memory-Core Architecture-]

### 2.1 Underlying Memory-Core Architecture

[-OpenClaw's memory-core implements a markdown-first memory system with five retrieval stages:-]

### 2.1 Underlying Memory-Core Architecture

[-1. **FTS5 full-text search** over a SQLite corpus. 2. **Vector embedding similarity** using cosine distance against pre-computed chunk embeddings. 3. **MMR deduplication** to prevent redundant chunks from consuming retrieval budget. 4. **Temporal decay** that exponentially down-weights older memories (half-life configurable, default 30 days). 5. **Relevance threshold** that filters chunks below a minimum combined score.-]

### 2.1 Underlying Memory-Core Architecture

[-The retrieval pipeline is extensible via hooks registered at plugin load time. Memory-core exposes `retrieval_pre` (modify query or inject candidates before search), `before_message_write` (intercept writes to durable storage), `before_compaction` (observe context about to be evicted), and `after_compaction` (react to completed evictions). MNEMOSYNE uses all four.-]

### 2.2 Prior Components This Work Composes

[-### 2.2 Prior Components This Work Composes-]

### 2.2 Prior Components This Work Composes

[-MNEMOSYNE assembles four mechanisms that have been described and built separately, and which we summarize here so this paper stands on its own.-]

### 2.2 Prior Components This Work Composes

[-**An event-sourced memory store with pointer-based compaction.** In this model the context window is treated as a cache over a durable event log; when context is evicted, the system inserts time-range pointer markers (e.g., "cron debugging happened between 14:00 and 15:30") rather than discarding the slot silently. MNEMOSYNE's compaction capture (Feature 4) operates on this substrate: it intercepts the eviction to preserve the content that a pointer alone cannot recover.-]

### 2.2 Prior Components This Work Composes

[-**A pre-computed concept-to-address index for constant-time retrieval.** The idea is to map a finite vocabulary of recurring concepts — project names, people, tools, error classes — to their associated memory chunks offline, so that a query containing a known concept can be answered without a full hybrid scan. MNEMOSYNE's Feature 1 is the production plugin implementation of this index, and it also owns the bi-temporal *schema* — the `validity_start / validity_end / ingestion_time` columns and the temporal search predicate — that MNEMOSYNE's validity layer (§9.5) sits on top of.-]

### 2.2 Prior Components This Work Composes

[-**An identity-and-consistency layer that keeps a persona coherent across sessions.** A long-running agent maintains a structured record of what it "believes" to be true about itself; that record must not drift or contradict itself across restarts. MNEMOSYNE's contradiction gate (Feature 3) protects this kind of structure from silent corruption.-]

### 2.2 Prior Components This Work Composes

[-**Nightly reflection and consolidation ("dreaming").** Between sessions, the agent summarizes the day's events and promotes durable memories autonomously. These autonomous writes — not human edits — are precisely what Feature 3 gates and Feature 4 captures.-]

### 2.3 Related Systems

[-### 2.3 Related Systems-]

### 2.3 Related Systems

[-**Mem0** [MemoryOS, 2024] builds multi-level memory (short-term, episodic, long-term) but does not address task-conditioned retrieval or write-time contradiction checking. **MemGPT** [Packer et al., 2023] introduces virtual context paging but operates at the context-window level rather than the retrieval-scoring level. **A-MEM** [Xu et al., 2025] gives agents control over memory formation strategies; MNEMOSYNE complements this by adding retrieval-time and write-time gates that A-MEM does not address. None of these three attacks the eviction-loss problem that Feature 4 targets: they manage what is stored and how it is layered, not what is destroyed when the context window overflows.-]

### 2.3 Related Systems

[-**Reversible Compress-Cache-Retrieve (headroom).** The most directly comparable external system to Feature 4 is chopratejas/headroom (Apache-2.0), an open-source context-compression layer for agents built on *reversible CCR — Compress-Cache-Retrieve*. Rather than dropping evicted content, headroom compresses it, caches the originals, and lets the LLM retrieve the full original on demand. It ships per-content-type compressors — statistical crushing of JSON arrays ("SmartCrusher"), AST-aware code compression via tree-sitter, and dedicated log/diff/text handlers — reports 60–95% token savings at near-zero accuracy delta on public benchmarks (GSM8K, TruthfulQA, SQuAD, BFCL), and, distinctively, ships a *reproducible* evaluation suite (`python -m headroom.evals`) alongside a trained compression model (Kompress-v2-base).-]

### 2.3 Related Systems

[-headroom and MNEMOSYNE solve overlapping problems from opposite ends, and the differentiation is worth stating precisely because it is not a matter of one being a subset of the other. headroom is *content-agnostic, reversible, and lossless-by-caching*: every byte survives eviction in compressed form and is recoverable, with type-specific compressors doing the work. It has no concept of task-conditioned retrieval, no write-time contradiction or validity semantics, and no bi-temporal "what was true then" axis. MNEMOSYNE is *selective and semantic*: the `isTrivial`/redundancy filtering of §7.3 deliberately discards greetings and acknowledgments and keeps only the "by the way" details, and its capture feeds the concept index and — via §9.5 — a validity-aware corpus. The slogans are complementary: headroom maximizes recall-of-everything-per-token; MNEMOSYNE maximizes signal-per-stored-chunk and supplies the retrieval, write-gating, and temporal machinery that headroom does not attempt. The two are composable rather than competing — headroom could compress MNEMOSYNE's `captured/` corpus, and conversely MNEMOSYNE's nearest CCR analogue, the pointer marker, is *lossy* exactly where headroom's cache is reversible. §7.5 returns to this as a concrete design gap.-]

### 2.3 Related Systems

[-**Ecosystem eval discipline.** A broader signal frames the empirical posture of this revision. Both headroom and coreyhaines31/marketingskills — a large, widely adopted skills collection — independently converge on shipping per-system reproducible assertion suites (headroom's `headroom.evals`, marketingskills' per-skill `evals.json`-style checks). When competing and adjacent systems all ship runnable evidence, an unmeasured systems paper reads as under-evidenced. §10.4 confronts this directly.-]

### 2.3 Related Systems

[-No existing system combines O(1) concept lookup, task-conditioned scoring, write-time contradiction gating, and compaction-time capture in a single plugin-layered architecture. The novelty is the *composition* and the validity layer, not any single mechanism; headroom in particular is the stronger system on the narrow axis of eviction-loss recovery, and we say so.-]

### 3. Architecture

[-## 3. Architecture-]

### 3.1 Plugin-Layered Design

[-### 3.1 Plugin-Layered Design-]

### 3.1 Plugin-Layered Design

[-MNEMOSYNE is a single OpenClaw plugin with ID `tinkerclaw-memory-enhancements`. It registers four hooks at load time:-]

### 3.1 Plugin-Layered Design

[-``` /** * MNEMOSYNE plugin entry point. * Registers four hooks on memory-core's retrieval and write * pipelines. No modification of the underlying source required. */ export function activate(api: PluginAPI): void { api.hooks.register('retrieval_pre', conceptIndexLookup); api.hooks.register('retrieval_pre', taskConditionedScoring); api.hooks.register('before_message_write', contradictionGate); api.hooks.register('before_compaction', compactionCapture); } ```-]

### 3.1 Plugin-Layered Design

[-Hook execution order is deterministic: hooks registered first run first. The concept index runs before task-conditioned scoring so that O(1) lookups can short-circuit the pipeline entirely — if the concept index returns a high-confidence result, the full hybrid search is skipped.-]

### 3.1 Plugin-Layered Design

[-Figure 1 shows the full data flow: how a query enters through the two `retrieval_pre` hooks, how a write passes the contradiction gate before promotion, and where the supersede path routes the gate's decision into memory-core's bi-temporal writer (§9.5).-]

### 3.1 Plugin-Layered Design

[-![Figure 1: MNEMOSYNE's four hooks layered over memory-core's retrieval and write pipelines, with the supersede path routing a contradicting write into the bi-temporal validity writer.](images/mnemosyne-architecture.png)-]

### 3.2 Hook Surface

[-### 3.2 Hook Surface-]

### 3.2 Hook Surface

[-| Hook | Timing | Receives | Returns | |------|--------|----------|---------| | `retrieval_pre` | Before hybrid FTS+vector search | Query string, task descriptor, retrieval config | Modified query, injected candidates, or `skip_search` signal | | `before_message_write` | Before promotion to MEMORY.md | Candidate chunk, existing facts | `allow`, `warn`, `block`, or (§9.5) `supersede` | | `before_compaction` | Before context eviction | Messages about to be dropped | Captured chunks (written to corpus) | | `after_compaction` | After eviction completes | Eviction metadata | Void (used for bookkeeping) |-]

### 3.3 Failure Isolation

[-### 3.3 Failure Isolation-]

### 3.3 Failure Isolation

[-Each hook is wrapped in a try-catch at the memory-core level. If MNEMOSYNE throws, the exception is logged to the plugin's own log file (`<agent-logs>/tinkerclaw-memory-enhancements.log`) and the pipeline continues as if the hook were not registered. This means:-]

### 3.3 Failure Isolation

[-- A bug in the concept index does not prevent hybrid search from running. - A crash in the contradiction gate does not block memory writes. - A failure in compaction capture does not prevent compaction.-]

### 3.4 Storage Isolation

[-### 3.4 Storage Isolation-]

### 3.4 Storage Isolation

[-MNEMOSYNE stores its data separately from memory-core:-]

### 3.4 Storage Isolation

[-- **Concept index:** `<agent-data>/mnemosyne/anchors.json` - **Capture corpus:** `<agent-data>/mnemosyne/captured/` (one `.md` file per capture event) - **Contradiction log:** `<agent-data>/mnemosyne/contradictions.jsonl` - **Task descriptor cache:** In-memory only (ephemeral per session)-]

### 3.4 Storage Isolation

[-This separation ensures that uninstalling the plugin leaves memory-core's data untouched. The one exception is the bi-temporal validity layer (§9.5), which writes through memory-core's own `chunks` table rather than a separate store — because superseding a fact must close *that fact's* validity interval, not a shadow copy.-]

### 4. Feature 1: Concept Index for O(1) Retrieval

[-## 4. Feature 1: Concept Index for O(1) Retrieval-]

### 4.1 Design

[-### 4.1 Design-]

### 4.1 Design

[-A personal assistant's memory corpus contains a finite vocabulary of recurring concepts — project names, people, tools, error classes. Mapping these concepts to their chunks offline turns query-time retrieval into a constant-time lookup: when a query contains a recognized concept token (e.g., "cron", "invoice-export", "WhatsApp"), the index returns the pre-ranked chunk list directly, bypassing the full FTS5 + vector + MMR pipeline.-]

### 4.2 Data Structure

[-### 4.2 Data Structure-]

### 4.2 Data Structure

[-``` /** * Concept index. Maps concept tokens to their associated memory * chunk IDs with importance scoring for retrieval ranking. * Persisted to anchors.json, loaded lazily on first query. */ type ConceptEntry = { chunkIds: Set<string>; importance: number; lastSeenAtMs: number; };-]

### 4.2 Data Structure

[-const conceptIndex: Map<string, ConceptEntry> = new Map(); ```-]

### 4.2 Data Structure

[-Each entry stores: - **chunkIds**: The set of memory chunk identifiers associated with this concept. Chunk IDs are opaque strings assigned by memory-core. - **importance**: A scalar combining frequency, recency, and distinctiveness (§4.5). - **lastSeenAtMs**: Unix timestamp of the most recent ingestion event that referenced this concept, used for staleness pruning.-]

### 4.3 Ingestion

[-### 4.3 Ingestion-]

### 4.3 Ingestion

[-The index is built during nightly consolidation. For each memory chunk processed during consolidation:-]

### 4.3 Ingestion

[-1. **Tokenize** the chunk into candidate concept tokens using whitespace splitting and stop-word removal. 2. **Filter** to tokens that appear in the anchor vocabulary — a curated set of entity names, project identifiers, tool names, and error classes extracted from the agent's operational history. 3. **Update** the concept index: for each surviving token, add the chunk ID to the token's `chunkIds` set and recompute importance.-]

### 4.3 Ingestion

[-Incremental updates occur during the session when new memories are written: the `after_compaction` hook triggers a lightweight re-index of newly captured chunks.-]

### 4.4 Lookup

[-### 4.4 Lookup-]

### 4.4 Lookup

[-At query time, the `retrieval_pre` hook tokenizes the incoming query and checks each token against the concept index:-]

### 4.4 Lookup

[-``` function conceptIndexLookup(ctx: RetrievalContext): RetrievalResult | null { const tokens = tokenize(ctx.query); const matches: ConceptEntry[] = [];-]

### 4.4 Lookup

[-for (const token of tokens) { const entry = conceptIndex.get(token); if (entry && entry.importance >= CONFIDENCE_THRESHOLD) { matches.push(entry); } }-]

### 4.4 Lookup

[-if (matches.length === 0) return null; // fall through to hybrid search-]

### 4.4 Lookup

[-const chunkIds = unionChunkIds(matches); const ranked = rankByImportance(chunkIds, matches); return { candidates: ranked.slice(0, ctx.config.maxResults), skipSearch: true }; } ```-]

### 4.4 Lookup

[-When the index returns a result with `skipSearch: true`, memory-core skips the full hybrid pipeline. If no concept matches above the confidence threshold, the hook returns `null` and hybrid search proceeds normally.-]

### 4.5 Importance Scoring

[-### 4.5 Importance Scoring-]

### 4.5 Importance Scoring

[-Importance is computed as a weighted sum of three factors:-]

### 4.5 Importance Scoring

[-``` importance(token) = w_f * frequency(token) + w_r * recency(token) + w_d * distinctiveness(token) ```-]

### 4.5 Importance Scoring

[-Where: - **frequency** = log(1 + count of chunks containing this token), normalized to [0, 1]. - **recency** = exponential decay from `lastSeenAtMs` with a half-life of 14 days. - **distinctiveness** = inverse document frequency: tokens that appear in fewer chunks score higher. A token appearing in every chunk (e.g., "the") has distinctiveness near zero.-]

### 4.5 Importance Scoring

[-Default weights: `w_f = 0.3`, `w_r = 0.4`, `w_d = 0.3`. Recency is weighted highest because a personal assistant's interests shift over weeks — a project abandoned two months ago should not dominate retrieval.-]

### 4.6 Pruning

[-### 4.6 Pruning-]

### 4.6 Pruning

[-Concepts whose `lastSeenAtMs` is older than 90 days and whose importance has decayed below `PRUNE_THRESHOLD` (default 0.05) are removed during nightly consolidation. This prevents the index from growing unboundedly as the agent's operational vocabulary evolves.-]

### 4.6 Pruning

[-Pruning is conservative: a concept is removed only if both conditions hold. A rarely-seen but highly distinctive concept (e.g., a unique project name) may persist indefinitely because its distinctiveness score keeps importance above the threshold.-]

### 4.7 Complexity Analysis

[-### 4.7 Complexity Analysis-]

### 4.7 Complexity Analysis

[-| Operation | Hybrid search (memory-core) | Concept index (MNEMOSYNE) | |-----------|-------------------------|---------------------------| | Query-time retrieval | O(n log n) — FTS5 scan + vector cosine + MMR | O(\|Q\|) — token lookup in Map, where \|Q\| is query token count | | Index build | N/A | O(n \* \|V\|) — one-time, during nightly consolidation | | Incremental update | N/A | O(\|V\|) per new chunk | | Storage | FTS5 index + vector store | anchors.json (~50KB for 2,000 concepts) |-]

### 4.7 Complexity Analysis

[-The critical property is that query-time retrieval is **O(1) in corpus size n**. As the memory corpus grows from thousands to hundreds of thousands of chunks, hybrid search degrades (FTS5 scan time grows, vector search requires more comparisons); the concept index remains constant. This is a theoretical property of the data structure, not a measured result; §10.4 is explicit that wall-clock confirmation on the production corpus is still pending, and treats the absence of that measurement as a substantive limitation rather than a footnote.-]

### 4.8 Persistence

[-### 4.8 Persistence-]

### 4.8 Persistence

[-The index is serialized to `anchors.json` using JSON, with `Set` values converted to arrays:-]

### 4.8 Persistence

[-``` { "cron": { "chunkIds": ["c_4a2f", "c_891b", "c_3e7d"], "importance": 0.72, "lastSeenAtMs": 1744675200000 }, "whatsapp": { "chunkIds": ["c_12ab", "c_56cd"], "importance": 0.61, "lastSeenAtMs": 1744588800000 } } ```-]

### 4.8 Persistence

[-Loading is lazy: the file is read and parsed on the first retrieval query of each session. Subsequent queries use the in-memory Map.-]

### 5. Feature 2: Task-Conditioned Retrieval Scoring

[-## 5. Feature 2: Task-Conditioned Retrieval Scoring-]

### 5.1 Motivation

[-### 5.1 Motivation-]

### 5.1 Motivation

[-Standard retrieval scoring is **query-only**: the score of a memory chunk depends solely on its textual similarity to the query. For a personal assistant that context-switches between tasks throughout the day, this is insufficient.-]

### 5.1 Motivation

[-Consider: the agent is debugging a cron failure. The user asks "what did we change last week?" Without task conditioning, the retrieval system returns all changes from last week — code commits, email drafts, configuration edits — ranked by textual similarity to "change" and "last week." With task conditioning, chunks tagged with cron-related metadata are boosted, surfacing the specific cron script modifications that the user implicitly meant.-]

### 5.1 Motivation

[-The phenomenon is well-studied in information retrieval as **query context bias** [Croft et al., 2010], but has not been applied to agent memory systems where the "context" is the agent's current task rather than a user profile.-]

### 5.2 Task Descriptor

[-### 5.2 Task Descriptor-]

### 5.2 Task Descriptor

[-The task descriptor is a lightweight structure extracted from the agent's current session state:-]

### 5.2 Task Descriptor

[-``` type TaskDescriptor = { keywords: string[]; // e.g., ["cron", "merge", "guardian"] projectId: string | null; // e.g., "tinkerclaw" taskType: string | null; // e.g., "debugging", "writing", "review" }; ```-]

### 5.2 Task Descriptor

[-The descriptor is populated from two sources: 1. **Explicit task markers** — if the agent's session includes a task header (e.g., `## Task: Debug safe-cron-merge.sh`), the keywords and project are extracted directly. 2. **Implicit inference** — if no explicit marker exists, the descriptor is inferred from the last N messages using keyword extraction (TF-IDF over the session window).-]

### 5.3 Score Modifier

[-### 5.3 Score Modifier-]

### 5.3 Score Modifier

[-The task-conditioned score modifier is registered as a second `retrieval_pre` hook that runs after the concept index lookup (and only if the concept index did not short-circuit):-]

### 5.3 Score Modifier

[-``` function taskConditionedScoring(ctx: RetrievalContext): void { const task = ctx.taskDescriptor; if (!task || task.keywords.length === 0) return; // no task context available-]

### 5.3 Score Modifier

[-for (const candidate of ctx.candidates) { const taskRelevance = computeTaskRelevance(candidate.metadata, task); candidate.score += TASK_WEIGHT * taskRelevance; } } ```-]

### 5.3 Score Modifier

[-The modifier does not replace existing scores — it adds a weighted bonus. Chunks already highly relevant to the query stay highly ranked; the task bias adjusts marginal rankings.-]

### 5.4 Weight Calibration

[-### 5.4 Weight Calibration-]

### 5.4 Weight Calibration

[-The `TASK_WEIGHT` parameter (default 0.3) controls how aggressively task context biases retrieval. At 0.0, the modifier has no effect. At 1.0, task relevance dominates textual similarity.-]

### 5.4 Weight Calibration

[-The default of 0.3 was chosen empirically: high enough to promote task-relevant chunks from page 2 to page 1 of results, low enough that a query about an unrelated topic still returns correct results. Formal calibration against an annotated retrieval-failure benchmark is planned for the next release.-]

### 5.5 Interaction with Concept Index

[-### 5.5 Interaction with Concept Index-]

### 5.5 Interaction with Concept Index

[-The two `retrieval_pre` hooks interact as follows:-]

### 5.5 Interaction with Concept Index

[-1. If the concept index fires and returns `skipSearch: true`, the task-conditioned modifier never runs. This is correct: O(1) concept lookup already returns the right chunks for well-known concepts, and adding task bias would only degrade a precise result. 2. If the concept index does not fire (no recognized concepts in the query), the task-conditioned modifier runs on the hybrid search candidates. This is where it adds the most value — ambiguous queries where hybrid search returns too many marginally relevant results.-]

### 6. Feature 3: Contradiction-Gate on Writes

[-## 6. Feature 3: Contradiction-Gate on Writes-]

### 6.1 Threat Model: Agent Self-Corruption

[-### 6.1 Threat Model: Agent Self-Corruption-]

### 6.1 Threat Model: Agent Self-Corruption

[-Autonomous agents that write their own memories face a risk that human-curated knowledge bases do not: **self-corruption through hallucinated or outdated facts**. The threat manifests in three scenarios:-]

### 6.1 Threat Model: Agent Self-Corruption

[-1. **Hallucinated consolidation.** During nightly dreaming, the LLM summarizes the day's events. If the summary includes a hallucinated detail — a wrong date, an incorrect attribution, a confused sequence of events — that hallucination is promoted to durable storage and becomes a "fact" the agent retrieves in future sessions.-]

### 6.1 Threat Model: Agent Self-Corruption

[-2. **Stale override.** The agent learns a new fact ("the meeting was moved to Thursday") but a later consolidation cycle processes an older memory that still says "the meeting is on Wednesday." If the older memory is promoted after the newer one, the durable store now holds a contradiction, and temporal ordering may not resolve it.-]

### 6.1 Threat Model: Agent Self-Corruption

[-3. **Semantic drift.** Over months, repeated summarization introduces gradual semantic shifts. A project described as "experimental" becomes "production" through successive paraphrases, not through any actual status change.-]

### 6.1 Threat Model: Agent Self-Corruption

[-These threats are not hypothetical. A self-contradiction failure was observed in production when the agent flagged a calendar conflict for a meeting it had already noted as postponed.-]

### 6.2 Gate Mechanism

[-### 6.2 Gate Mechanism-]

### 6.2 Gate Mechanism

[-The contradiction gate registers on the `before_message_write` hook. When memory-core's dreaming phase prepares to promote a short-term recall to MEMORY.md, the gate intercepts the candidate chunk and performs a targeted contradiction check:-]

### 6.2 Gate Mechanism

[-``` async function contradictionGate(ctx: WriteContext): Promise<WriteDecision> { const candidate = ctx.chunk; const existingFacts = await queryRelatedFacts(candidate);-]

### 6.2 Gate Mechanism

[-if (existingFacts.length === 0) { return { action: 'allow' }; // no existing facts to contradict }-]

### 6.2 Gate Mechanism

[-const contradictions = detectContradictions(candidate, existingFacts);-]

### 6.2 Gate Mechanism

[-if (contradictions.length === 0) { return { action: 'allow' }; }-]

### 6.2 Gate Mechanism

[-logContradiction(candidate, contradictions);-]

### 6.2 Gate Mechanism

[-return { action: config.contradictionMode, // 'warn', 'block', or 'supersede' (§9.5) reason: formatContradictionReport(contradictions), }; } ```-]

### 6.2 Gate Mechanism

[-The `detectContradictions` function uses entity-level comparison: it extracts named entities (dates, names, project identifiers, status labels) from both the candidate and existing facts, then checks for direct conflicts (same entity, different value). This is a conservative approach — it catches explicit contradictions ("meeting on Wednesday" vs "meeting on Thursday") but not subtle semantic drift. Semantic drift detection remains future work.-]

### 6.3 Modes: Warn, Block, Supersede

[-### 6.3 Modes: Warn, Block, Supersede-]

### 6.3 Modes: Warn, Block, Supersede

[-The gate operates in one of three modes, configured per-plugin:-]

### 6.3 Modes: Warn, Block, Supersede

[-**Warn mode**: The contradiction is logged to `contradictions.jsonl` with the candidate chunk, the conflicting existing facts, and a timestamp. The write proceeds. The agent (or its operator) can review the log to identify patterns of self-corruption.-]

### 6.3 Modes: Warn, Block, Supersede

[-**Block mode**: The write is refused. The candidate chunk is not promoted to MEMORY.md. The blocked write is logged with the same detail as warn mode, plus a `blocked: true` flag. This is safer than warn but risks losing legitimate updates when the detector produces false positives.-]

### 6.3 Modes: Warn, Block, Supersede

[-**Supersede mode** (§9.5): The contradiction is resolved rather than logged or blocked. The prior fact's validity interval is closed and the new fact opens its own — both rows are retained, so nothing is lost. This is a non-lossy resolution; §9.5 describes the mechanism and its grounding in memory-core's bi-temporal substrate.-]

### 6.3 Modes: Warn, Block, Supersede

[-Warn is the conservative default because block is lossy and supersede changes live behavior; §9.5.4 examines when the default should change.-]

### 6.4 Relationship to the Write Model and Identity Layer

[-### 6.4 Relationship to the Write Model and Identity Layer-]

### 6.4 Relationship to the Write Model and Identity Layer

[-The contradiction gate sits at the intersection of two architectural concerns.-]

### 6.4 Relationship to the Write Model and Identity Layer

[-The event-sourced **write model** treats memory writes as cache promotions — content moves from the ephemeral context window to durable storage. The contradiction gate adds a validation step to this promotion, analogous to a database constraint check before an INSERT.-]

### 6.4 Relationship to the Write Model and Identity Layer

[-The **identity-and-consistency layer** maintains agent identity across sessions by keeping its persona record coherent. The contradiction gate protects not just the persona but the entire fact base from inconsistency. Where the identity layer guards the "who am I?" question, the contradiction gate guards the "what do I know?" question.-]

### 7. Feature 4: Compaction-Aware Capture

[-## 7. Feature 4: Compaction-Aware Capture-]

### 7.1 The Gap: Messages Used Once and Never Queried Can Be Lost

[-### 7.1 The Gap: Messages Used Once and Never Queried Can Be Lost-]

### 7.1 The Gap: Messages Used Once and Never Queried Can Be Lost

[-Pointer-based compaction replaces evicted messages with time-range markers containing topic hints. The pointers are enough for the agent to know that "something about cron debugging happened between 14:00 and 15:30" — but the actual content (the exact error message, the specific fix attempted, the user's aside about a related problem) is gone from the context window.-]

### 7.1 The Gap: Messages Used Once and Never Queried Can Be Lost

[-Nightly dreaming can recover some of this content by promoting memories that were recently searched for. But dreaming promotes only what has been queried. Content used once — read, acted upon, and never referenced again — can be lost after a completed compaction. Operational measurements also show that not every capture trigger corresponds to legitimate window pressure or a completed eviction (§7.6), so trigger activation cannot itself establish that content would otherwise have been lost.-]

### 7.1 The Gap: Messages Used Once and Never Queried Can Be Lost

[-This creates a specific class of information loss:-]

### 7.1 The Gap: Messages Used Once and Never Queried Can Be Lost

[-1. User mentions a detail in passing ("by the way, the SSL cert expires next month"). 2. The agent acknowledges but does not create a task or note. 3. Compaction evicts the message. 4. The detail was never queried, so dreaming never promotes it. 5. The agent has no record of the SSL certificate expiry.-]

### 7.1 The Gap: Messages Used Once and Never Queried Can Be Lost

[-For a personal assistant, these "by the way" details are often the most valuable — precisely because no one explicitly searched for them later.-]

### 7.2 Capture Protocol

[-### 7.2 Capture Protocol-]

### 7.2 Capture Protocol

[-The compaction-aware capture pass runs on the `before_compaction` hook, which fires immediately before memory-core evicts messages from the context window:-]

### 7.2 Capture Protocol

[-``` async function compactionCapture(ctx: CompactionContext): Promise<void> { const messagesToEvict = ctx.messages; const captured: CapturedChunk[] = [];-]

### 7.2 Capture Protocol

[-for (const msg of messagesToEvict) { if (isAlreadyInCorpus(msg)) continue; // already persisted if (isTrivial(msg)) continue; // greetings, acks, etc.-]

### 7.2 Capture Protocol

[-const chunk = extractChunk(msg); chunk.metadata.capturedAt = Date.now(); chunk.metadata.captureReason = 'compaction'; captured.push(chunk); }-]

### 7.2 Capture Protocol

[-if (captured.length > 0) { await writeToCapturePath(captured); updateConceptIndex(captured); // incremental index update } } ```-]

### 7.3 Triviality Filter

[-### 7.3 Triviality Filter-]

### 7.3 Triviality Filter

[-Not every evicted message deserves preservation. The `isTrivial` function applies three heuristics:-]

### 7.3 Triviality Filter

[-1. **Length threshold**: Messages under 20 tokens are likely greetings or acknowledgments. 2. **Template match**: Messages matching common conversational patterns ("ok", "got it", "thanks") are skipped. 3. **Redundancy check**: If the message content is already present in a previously captured chunk (checked via a lightweight hash), it is skipped.-]

### 7.3 Triviality Filter

[-The filter is deliberately permissive — it is better to capture a marginally useful message than to lose a detail that matters. It is nonetheless *lossy by construction*: anything it drops is gone, with no recovery path. More importantly, first-party traffic measurements show that the exact-hash test addresses the wrong scale of redundancy. Across 23,376,348 bytes in 4,402 Read-tool calls from 890 sessions, identical repeats accounted for 25,042 bytes in seven calls (about 0.1%). Stale reads accounted for 3,374,879 bytes in 680 calls, line-number scaffolding for 1,512,097 bytes, and subset containment for 94,971 bytes in 35 calls: about 5.0 MB, or 21% of Read traffic, was addressable by known compression strategies. An exact hash remains worth keeping because it is cheap, not because it has high yield.-]

### 7.3 Triviality Filter

[-The same audit found 20,916,377 bytes of Bash-tool traffic, nearly as much as Read traffic, outside the file-oriented filter's scope. Read content also split materially by type: 11,960,293 bytes of documentation/text, 9,245,180 bytes of source code, and 1,461,551 bytes of data/configuration. These distributions argue for similarity- and validity-aware filtering plus content-specific handling; a uniform exact-match filter cannot address superseded content or command output. Context residency also varied widely (median 48, mean 139.6, p90 364; maximum re-reads of one file: 34), replacing the earlier unmeasured "used once" generalization with an observed distribution.-]

### 7.4 Integration with the before_compaction Hook

[-### 7.4 Integration with the before_compaction Hook-]

### 7.4 Integration with the before_compaction Hook

[-The `before_compaction` hook receives the full list of messages that memory-core is about to evict. MNEMOSYNE's capture pass processes them synchronously before returning control to memory-core, which then proceeds with eviction. The captured chunks are written to `<agent-data>/mnemosyne/captured/` as individual markdown files, one per capture event.-]

### 7.4 Integration with the before_compaction Hook

[-These captured files are indexed by memory-core's FTS5 crawler on its next pass, making them available for future hybrid search and concept index ingestion. The capture thus feeds back into the retrieval pipeline: content captured during compaction becomes searchable in subsequent sessions.-]

### 7.5 Relationship to Pointer-Based Compaction and Reversible Caching

[-### 7.5 Relationship to Pointer-Based Compaction and Reversible Caching-]

### 7.5 Relationship to Pointer-Based Compaction and Reversible Caching

[-Pointer-based compaction and MNEMOSYNE's capture are complementary, not competing:-]

### 7.5 Relationship to Pointer-Based Compaction and Reversible Caching

[-- **Pointers** tell the agent *what happened* (time range, topic hints) so it can decide whether to search for details. - **MNEMOSYNE capture** ensures the *details exist to be found* when the agent does search.-]

### 7.5 Relationship to Pointer-Based Compaction and Reversible Caching

[-Without capture, the pointers point to content that may no longer exist in any searchable form. Without pointers, capture would be insufficient because the agent would not know to search for captured content. The two mechanisms close each other's gaps — but only for content that survives the triviality filter.-]

### 7.5 Relationship to Pointer-Based Compaction and Reversible Caching

[-There is an honest gap here, and the comparison to chopratejas/headroom (§2.3) names it cleanly. MNEMOSYNE's pointer-plus-capture pair is, in CCR terms, a *lossy* compress step: a pointer marker is an extreme compression of an eviction window, and any message the §7.3 filter classifies as trivial is discarded with no cache holding the original. headroom's reversible CCR makes the opposite tradeoff — it never decides a byte is unworthy; it compresses everything and keeps the originals recoverable. The cost of MNEMOSYNE's selectivity is precisely the case where a "by the way" detail of §7.1 is shorter than the length threshold, or is paraphrased closely enough to trip the redundancy check, and is therefore filtered out and lost. A reversible-cache tier for sub-threshold content — compressing rather than discarding what the triviality filter rejects, so it remains recoverable on demand even though it is not promoted to the searchable corpus — is a candidate mechanism that would let MNEMOSYNE keep its signal-per-chunk selectivity for retrieval while closing the residual loss path. §10.5 treats it as future work alongside the capture-volume retention policy, since the two interact: a reversible tier changes what "stored" volume means.-]

### 7.6 The Trigger Is Not Ground Truth

[-### 7.6 The Trigger Is Not Ground Truth-]

### 7.6 The Trigger Is Not Ground Truth

[-The `before_compaction` hook is a notification from an upstream component, not proof that the context is near capacity or that eviction will complete. First-party instrumentation from 25–28 July 2026 found that compaction triggered at a median of about 5.5% of the actual context window. In one observed session, a per-message `usage` field containing the aggregate for an entire turn was treated as a context snapshot: 1,029,656 reported tokens for 52,116 decoded per-call context tokens, a 19.8× over-read. A separate estimator path assigned zero tokens to a 55,632–61,336-character system prompt because its synthetic message role was unsupported. The pressure estimate therefore failed in both directions.-]

### 7.6 The Trigger Is Not Ground Truth

[-The hook contract has a second consequence: 29 events reached a 540-second cap and were discarded after MNEMOSYNE had already written and indexed their captures; the measured compaction work itself took 19 ms. The capture corpus can therefore accumulate content that was never evicted. A correct capture integration must validate pressure independently or persist the observed `contextUtilPct` and final compaction disposition with every captured chunk. Captures associated with discarded compactions must be identifiable for retention or rollback. Hook signature stability (§10.1) is insufficient when trigger semantics are wrong.-]

### 8. Implementation

[-## 8. Implementation-]

### 8.1 Plugin Manifest

[-### 8.1 Plugin Manifest-]

### 8.1 Plugin Manifest

[-``` { "id": "tinkerclaw-memory-enhancements", "name": "MNEMOSYNE — Memory Enhancement Suite", "version": "0.1.0", "description": "Concept index, task-conditioned scoring, contradiction gate, and compaction capture for personal-agent memory systems.", "entryPoint": "dist/index.js", "configSchema": { "conceptIndex": { "enabled": { "type": "boolean", "default": true }, "confidenceThreshold": { "type": "number", "default": 0.4 }, "pruneThresholdDays": { "type": "number", "default": 90 } }, "taskScoring": { "enabled": { "type": "boolean", "default": false }, "weight": { "type": "number", "default": 0.3 } }, "contradictionGate": { "enabled": { "type": "boolean", "default": false }, "mode": { "type": "string", "enum": ["warn", "block", "supersede"], "default": "warn" } }, "compactionCapture": { "enabled": { "type": "boolean", "default": true }, "trivialityThresholdTokens": { "type": "number", "default": 20 } } } } ```-]

### 8.1 Plugin Manifest

[-The `configSchema` field is mandatory in current memory-core: a plugin that omits it fails to load entirely. This is a load-time contract, not a runtime check, so a missing schema blocks the plugin before any hook can register.-]

### 8.2 Hook Registrations

[-### 8.2 Hook Registrations-]

### 8.2 Hook Registrations

[-All four hooks are registered in `activate()` and individually gated by their `enabled` config flag. Hook registration order:-]

### 8.2 Hook Registrations

[-1. `conceptIndexLookup` on `retrieval_pre` — runs first, may short-circuit. 2. `taskConditionedScoring` on `retrieval_pre` — runs second, only if concept index did not fire. 3. `contradictionGate` on `before_message_write` — synchronous, returns allow/warn/block/supersede. 4. `compactionCapture` on `before_compaction` — synchronous, must complete before eviction proceeds.-]

### 8.3 Deployment Status

[-### 8.3 Deployment Status-]

### 8.3 Deployment Status

[-| Feature | Status | Notes | |---------|--------|-------| | Concept index | Implemented; traffic unquantified | anchors.json persisted, lazy loading, nightly rebuild; no stated-window request counter | | Compaction-aware capture | Path confirmed; liveness unverified | Write and FTS5 indexing paths confirmed, but no non-zero completed-eviction counter; upstream trigger was mis-measured (§7.6) | | Task-conditioned scoring | Scaffolded | Hook registered but returns early (no task descriptor extraction yet) | | Contradiction gate | Scaffolded | Hook registered; today it injects passive contradiction warnings into the retrieval pack rather than blocking, and entity-level conflict detection is not yet wired | | Bi-temporal supersede (§9.5) | Core-ready, plugin-pending | memory-core ships the validity columns, search predicate, and supersede writer; MNEMOSYNE must route the gate's decision into them | | Reproducible eval harness (§10.4) | Not built | No latency or accuracy benchmark exists; the gap is now a first-class limitation, not a footnote |-]

### 8.3 Deployment Status

[-A component is called **live** here only when a traffic or volume counter shows non-zero use on the intended path during a stated window. Installation, enablement, hook registration, and a successful synthetic write are necessary but insufficient. This stricter standard follows an observed counterexample: a context-compression proxy was installed, enabled, running, and referenced by the gateway environment, yet served six requests over its lifetime and saved zero tokens because production traffic ran in a subprocess that stripped the proxy environment variable.-]

### 8.4 Lines of Code

[-### 8.4 Lines of Code-]

### 8.4 Lines of Code

[-| File | LOC | Purpose | |------|-----|---------| | `index.ts` | 85 | Plugin entry, hook registration, config loading | | `concept-index.ts` | 210 | Map data structure, ingestion, lookup, pruning | | `task-scoring.ts` | 65 | Score modifier, task descriptor interface | | `contradiction-gate.ts` | 120 | Write interception, contradiction detection stub | | `compaction-capture.ts` | 145 | Before-compaction capture, triviality filter | | `utils.ts` | 55 | Tokenizer, hash, file I/O helpers | | **Total** | **680** | |-]

### 8.5 Deployment

[-### 8.5 Deployment-]

### 8.5 Deployment

[-``` # Build the plugin cd <agent-workspace>/extensions/tinkerclaw-memory-enhancements pnpm build-]

### Enable in openclaw.json # plugins.allow: ["tinkerclaw-memory-enhancements"] # plugins.entries: [{ "id": "tinkerclaw-memory-enhancements", "enabled": true }]

[-# Enable in openclaw.json # plugins.allow: ["tinkerclaw-memory-enhancements"] # plugins.entries: [{ "id": "tinkerclaw-memory-enhancements", "enabled": true }]-]

### Restart gateway (SIGUSR1 does not reload ES modules) openclaw-restart --full ```

[-# Restart gateway (SIGUSR1 does not reload ES modules) openclaw-restart --full ```-]

### 9. Discussion

[-## 9. Discussion-]

### 9.1 Why a Unified Plugin

[-### 9.1 Why a Unified Plugin-]

### 9.1 Why a Unified Plugin

[-The four features could have been implemented as four separate plugins. A unified plugin was chosen for three reasons:-]

### 9.1 Why a Unified Plugin

[-1. **Shared data structures.** The concept index is updated by both the ingestion pipeline (Feature 1) and the compaction capture pass (Feature 4). Splitting them into separate plugins would require inter-plugin communication or duplicated state. 2. **Consistent configuration.** A single `configSchema` with four feature flags is simpler to manage than four separate plugin configurations. 3. **Marketplace distribution.** ClawHub distributes plugins as atomic units. A user searching for "memory enhancements" finds one package with four toggles rather than four packages that must be installed in the right combination.-]

### 9.2 Relationship to Upstream Memory-Wiki

[-### 9.2 Relationship to Upstream Memory-Wiki-]

### 9.2 Relationship to Upstream Memory-Wiki

[-OpenClaw's upstream is developing a "Memory-Wiki" feature that combines memory-core with a wiki-style editor for structured knowledge management. Memory-Wiki targets enterprise teams managing shared knowledge bases.-]

### 9.2 Relationship to Upstream Memory-Wiki

[-MNEMOSYNE targets a different use case: a single personal assistant whose memory grows organically through conversation, nightly consolidation, and imported archives. The two systems are complementary:-]

### 9.2 Relationship to Upstream Memory-Wiki

[-- Memory-Wiki assumes well-structured, human-curated content. MNEMOSYNE handles messy, auto-generated content. - Memory-Wiki optimizes for collaborative editing and version history. MNEMOSYNE optimizes for single-agent consistency and retrieval speed. - Memory-Wiki provides a UI for manual fact management. MNEMOSYNE provides automated gates that reduce the need for manual review.-]

### 9.3 The Complementarity Argument

[-### 9.3 The Complementarity Argument-]

### 9.3 The Complementarity Argument

[-Enterprise-wiki and personal-assistant are not just different products — they produce different *failure modes*. An enterprise wiki fails when it returns outdated information (solved by version history and review processes). A personal assistant fails when it contradicts itself (solved by contradiction gating and supersession) or loses context (solved by compaction capture). Designing for one set of failures does not address the other.-]

### 9.3 The Complementarity Argument

[-This divergence justifies maintaining MNEMOSYNE as a separate enhancement layer rather than lobbying for its features to be merged into the memory-core mainline. The mainline maintainers optimize for the general case; MNEMOSYNE optimizes for the personal-assistant edge.-]

### 9.4 Potential ClawHub Distribution

[-### 9.4 Potential ClawHub Distribution-]

### 9.4 Potential ClawHub Distribution

[-The plugin architecture and configSchema compliance make MNEMOSYNE a candidate for ClawHub distribution once the next release reaches stability. Distribution requirements:-]

### 9.4 Potential ClawHub Distribution

[-- All four features must be individually toggleable (already implemented via config flags). - The plugin must not crash when memory-core hooks are unavailable (already handled by failure isolation). - Documentation must include configuration examples for common scenarios.-]

### 9.4 Potential ClawHub Distribution

[-The wider ClawHub-adjacent ecosystem now sets an evidence bar as well as an interface bar: distributed agent systems such as chopratejas/headroom and coreyhaines31/marketingskills ship per-system reproducible assertion suites alongside their code, and a plugin that claims a constant-time retrieval property without a runnable benchmark will read as weaker than its measured neighbors. §10.4 treats closing that gap as a distribution prerequisite, not a nicety.-]

### 9.5 Bi-Temporal Validity: From Contradiction-Logger to Contradiction-Resolver

[-### 9.5 Bi-Temporal Validity: From Contradiction-Logger to Contradiction-Resolver-]

### 9.5 Bi-Temporal Validity: From Contradiction-Logger to Contradiction-Resolver

[-The contradiction gate (§6) is a *single-valued-present* operation: it decides allow / warn / block over a corpus implicitly assumed to be a flat snapshot of "what is true now." That assumption is exactly what the §6.1 *stale-override* and *semantic-drift* threats violate. Bi-temporal validity replaces *overwrite/block* with *supersede*: a contradicting write neither destroys the prior fact (lossy — the reason warn is the conservative default) nor silently keeps both (the calendar-conflict failure of §6.1). Instead it **closes the prior fact's validity interval and opens the new one**, so the corpus carries the full history and every retrieval can ask "valid-at-now" versus "valid-at-time-T." This upgrades the gate from a *logger of conflicts* into a *resolver of conflicts*, and it makes task-conditioned scoring (§5) honest: a debugging query asking "what's the cron schedule" gets the currently-valid value, not the superseded one written three weeks ago.-]

### 9.5 Bi-Temporal Validity: From Contradiction-Logger to Contradiction-Resolver

[-Figure 2 illustrates a single fact's life across a supersede event: fact A is written with an open interval, a contradicting fact B closes A's interval and opens its own, and a `current` query returns only B while a `valid-at` query before B's write still returns A.-]

### 9.5 Bi-Temporal Validity: From Contradiction-Logger to Contradiction-Resolver

[-![Figure 2: A fact's validity timeline across a supersede event. Fact A's interval is closed at B's ingestion; both rows persist, so 'current' returns B and 'valid-at-T' returns A.](images/bitemporal-timeline.png)-]

### 9.5.1 Division of Labor: The Index Owns the Schema, MNEMOSYNE Owns the Behavior

[-#### 9.5.1 Division of Labor: The Index Owns the Schema, MNEMOSYNE Owns the Behavior-]

### 9.5.1 Division of Labor: The Index Owns the Schema, MNEMOSYNE Owns the Behavior

[-The schema work belongs to the concept-index subsystem; the write/retrieve *semantics* belong to MNEMOSYNE. The substrate has landed in memory-core and can be verified directly in the codebase:-]

### 9.5.1 Division of Labor: The Index Owns the Schema, MNEMOSYNE Owns the Behavior

[-- The `chunks` table carries `validity_start`, `validity_end`, `ingestion_time`, and `superseded_by` columns, added idempotently via `ensureColumn()` in `memory-schema.ts`, with a covering index `idx_chunks_validity` on `validity_end` so the hot-path "current" filter does not table-scan. (`validity_end IS NULL` means currently-valid / unbounded; back-filled legacy rows are NULL and so remain retrievable in the default mode.) - `StoredChunk` (`storage/types.ts`) carries the matching optional fields `validityStart`, `validityEnd`, `ingestionTime`, and `supersededBy`, and `SearchParams` gains `temporalMode: "current" | "valid-at" | "all"` plus `asOfTime`. - The read path is already temporal-aware: `manager-search.ts` exports `temporalPredicate()`, threaded into the vector, FTS, and hybrid SELECTs — `current` appends `validity_end IS NULL OR validity_end > now`, `valid-at` binds `validity_start <= asOf AND (validity_end IS NULL OR validity_end > asOf)`, and `all` drops the predicate entirely.-]

### 9.5.1 Division of Labor: The Index Owns the Schema, MNEMOSYNE Owns the Behavior

[-So MNEMOSYNE's claim is not gated on a future migration. The substrate exists. What MNEMOSYNE owns is routing the contradiction gate's decision into it and keeping task scoring validity-aware. The unmeasured part is the *cost* of the always-on `validity_end` filter under production load; §10.4 lists it.-]

### 9.5.2 The Supersede Write Decision

[-#### 9.5.2 The Supersede Write Decision-]

### 9.5.2 The Supersede Write Decision

[-MNEMOSYNE extends the gate's `WriteDecision` with a `supersede` variant alongside `warn`/`block`. memory-core already ships the executor: `engram/supersede-writer.ts` exposes `decideSupersede(db, candidate, mode = "supersede")`, which finds the currently-valid (`validity_end IS NULL`) prior chunk(s) at the candidate's identity and returns `{ action, supersedes: ChunkId[], reason }`; and `applySupersede(db, decision, candidate)`, which — only in `supersede` mode — calls `invalidate()` once per superseded chunk. `invalidate()` (in `temporal-invalidation.ts`) stamps `validity_end` and `superseded_by` on rows that are *still open* (`WHERE … AND validity_end IS NULL`), never deleting and never resurrecting a closed row. The behavior is non-lossy: the prior row stays queryable in `all` / `valid-at` mode.-]

### 9.5.2 The Supersede Write Decision

[-``` type WriteDecision = | { action: "allow" } | { action: "warn", supersedes, reason } | { action: "block", supersedes, reason } | { action: "supersede", supersedes: ChunkId[], reason } // resolves the conflict-]

### 9.5.2 The Supersede Write Decision

[-function contradictionGate(ctx): candidate = ctx.chunk decision = decideSupersede(db, candidate, config.contradictionMode) // memory-core if decision.action == "allow": return decision logContradiction(candidate, decision) // still append to contradictions.jsonl return decision // 'warn' | 'block' | 'supersede'-]

### On apply (supersede mode only): close each prior interval as of the candidate's validity_start applySupersede(db, decision, { id: candidate.id, validityStart: now }) ```

[-# On apply (supersede mode only): close each prior interval as of the candidate's validity_start applySupersede(db, decision, { id: candidate.id, validityStart: now }) ```-]

### On apply (supersede mode only): close each prior interval as of the candidate's validity_start applySupersede(db, decision, { id: candidate.id, validityStart: now }) ```

[-`decideSupersede` defaults its `mode` argument to `"supersede"`. `applySupersede` exposes an `onClosed(closedIds, reason)` callback that fires only when an interval is actually closed; the production caller (`manager-embedding-ops.ts`) uses that seam to emit a `fork.prefrontal.trailEvent` of kind `recipe-supersede`, so the UI renders a supersede icon. The MNEMOSYNE side is the configuration default it advertises — see §9.5.4.-]

### 9.5.3 Validity-Aware Task Scoring

[-#### 9.5.3 Validity-Aware Task Scoring-]

### 9.5.3 Validity-Aware Task Scoring

[-Because the read-path predicate (§9.5.1) already excludes superseded chunks in `current` mode, the scoring change is small. In `valid-at` / `all` modes, where historical chunks *are* returned, `taskConditionedScoring` (§5.3) must not let a stale-but-textually-similar fact out-rank the current one on task bias alone. The guard down-weights — not zeros — a candidate whose validity interval does not contain the query's `asOf`:-]

### 9.5.3 Validity-Aware Task Scoring

[-``` function taskConditionedScoring(ctx): if not ctx.taskDescriptor: return asOf = ctx.asOfTime ?? now for cand in ctx.candidates: rel = computeTaskRelevance(cand.metadata, ctx.taskDescriptor) if cand.validityEnd != null and cand.validityEnd <= asOf: rel = rel * HISTORICAL_TASK_DAMP # down-weight, don't zero cand.score += TASK_WEIGHT * rel ```-]

### 9.5.3 Validity-Aware Task Scoring

[-The scorer already carries the right primitive: its event-level scoring applies a fixed `SUPERSESSION_DISCOUNT` (0.1) to any event a newer version has replaced, so a superseded fact is multiplicatively penalized rather than dropped. The validity-aware guard generalizes that constant into a mode-sensitive damp keyed on the query's `asOf`, so the penalty applies only in `valid-at` / `all` retrieval, not unconditionally.-]

### 9.5.3 Validity-Aware Task Scoring

[-A related correctness note: recency-based importance should derive its recency tier from `validity_start`, not the row's last-updated timestamp — a fact reinstated after being superseded became *true again* at its new `validity_start`, and that is the date a recency bonus should reflect. `ingestion_time` is stamped once at first insert and never on re-touch, so it stays the honest "when did the system first learn this" clock.-]

### 9.5.4 The One Genuine Product Decision

[-#### 9.5.4 The One Genuine Product Decision-]

### 9.5.4 The One Genuine Product Decision

[-memory-core defaults `decideSupersede` to `supersede` mode, but MNEMOSYNE's published plugin defaults `contradictionGate.mode` to `warn` for backward compatibility (§8.1). Whether the *plugin* default should flip to `supersede` is a product call, not a code-derivable one. The argument for flipping is that supersede is strictly safer than block — nothing is destroyed — and resolves rather than merely logs the §6.1 failure. The argument against is that it changes live behavior for every existing installation, and a false-positive contradiction would close the interval of a fact that was actually still valid (recoverable via `all`-mode query, but no longer surfaced by default). The conservative path — ship `supersede` opt-in, observe the `contradictions.jsonl` false-positive rate, then consider flipping the default later — is the one this paper recommends. Note that "observe the false-positive rate" is itself a measurement the paper does not yet report, which is the same evidence gap §10.4 names for the retrieval claims.-]

### 9.5.5 What Is Not Yet Built

[-#### 9.5.5 What Is Not Yet Built-]

### 9.5.5 What Is Not Yet Built

[-Two pieces of the design remain unimplemented and are stated honestly as future work:-]

### 9.5.5 What Is Not Yet Built

[-1. **Cascade retraction.** `temporal-invalidation.ts` is explicit that there is *no cascade in the current build*: invalidating a fact does not invalidate facts that depended on it. A `depends_on` edge plus a topological, visited-set-guarded cascade (to terminate on cyclic dependencies) is a future item, and it overlaps the link-graph work — the `backlinks` table is already in the schema. 2. **Fact-level (triple) validity.** The landed schema is *chunk-level*: one validity interval per chunk row. A true fact-level bi-temporal graph — `(subject, predicate, object, valid_from, valid_to)` — is richer but a larger build, and is left as an open granularity question rather than claimed.-]

### 9.5.5 What Is Not Yet Built

[-A third design question — whether the supersede boundary uses *ingestion time* (simple, what the current executor assumes via the candidate's `validity_start`) or an *extracted event time* from the content (correct for "the meeting moved to Thursday," but requires reliable temporal entity extraction) — is unresolved. Using ingestion time can mis-order the §6.1 stale-override scenario when an old memory is consolidated after a newer one; event-time extraction is the principled fix and a candidate for a later release.-]

### 9.5.6 Test Plan for the Validity Layer

[-#### 9.5.6 Test Plan for the Validity Layer-]

### 9.5.6 Test Plan for the Validity Layer

[-The substrate ships with tests; the plugin-side behavior needs its own, matching the subsystem's vitest convention (`pnpm vitest src/memory/...`). The cases that pin the supersede semantics:-]

### 9.5.6 Test Plan for the Validity Layer

[-- **Supersede closes the prior interval.** Insert fact A (`validity_end = NULL`); write a contradicting fact B in `supersede` mode. Assert A's `validity_end` equals B's `ingestion_time` and B's `validity_end` is NULL, and that both rows are still present — no `DELETE`. - **Current-mode filter.** `search(temporalMode: 'current')` returns B, not A. - **Valid-at query.** `search(temporalMode: 'valid-at', asOfTime: T)` with `A.validity_start < T < B.validity_start` returns A — the "what was true then" path. - **All-mode.** `search(temporalMode: 'all')` returns both A and B. - **Scoring honesty.** In `valid-at` mode a superseded chunk that matches the task descriptor scores below the current chunk despite higher textual similarity (`HISTORICAL_TASK_DAMP` applied). - **Index guard.** `PRAGMA index_list(chunks)` includes `idx_chunks_validity`, since every `current`-mode search filters on `validity_end`.-]

### 9.5.6 Test Plan for the Validity Layer

[-The end-to-end target is the §6.1 calendar-conflict reproduction: a recipe-conditioned query at `asOf = now` never surfaces the superseded "Wednesday" fact once the "Thursday" write has passed through the gate in `supersede` mode. These are correctness tests; they pin behavior but do not measure latency, which §10.4 calls out separately.-]

### 10. Limitations and Future Work

[-## 10. Limitations and Future Work-]

### 10.1 Hook Dependency on Memory-Core

[-### 10.1 Hook Dependency on Memory-Core-]

### 10.1 Hook Dependency on Memory-Core

[-MNEMOSYNE's four hooks (`retrieval_pre`, `before_message_write`, `before_compaction`, `after_compaction`) are not part of memory-core's public API. They exist as extension points but are not contractually stable. A refactor could rename, remove, or change the signature of any hook.-]

### 10.1 Hook Dependency on Memory-Core

[-**Mitigation:** A merge-guardian automation checks for hook availability after every memory-core merge. If a hook disappears, the guardian logs a warning and MNEMOSYNE degrades gracefully — the missing feature is disabled, the others continue.-]

### 10.2 Ingestion Wiring

[-### 10.2 Ingestion Wiring-]

### 10.2 Ingestion Wiring

[-The concept index is populated during nightly consolidation. Real-time ingestion — indexing new memories as they arrive during the session — is implemented as an incremental update in `compactionCapture` but is not yet triggered from all memory write paths. Full real-time ingestion is planned for the next release.-]

### 10.3 Contradiction Detection Depth

[-### 10.3 Contradiction Detection Depth-]

### 10.3 Contradiction Detection Depth

[-The current contradiction detector uses entity-level comparison: same entity, different value. This catches explicit contradictions but misses:-]

### 10.3 Contradiction Detection Depth

[-- **Semantic contradictions**: "The project is going well" vs "The project has critical blockers." - **Implication contradictions**: "All tests pass" followed by "Feature X is broken" (the second implies at least one test should fail).-]

### 10.3 Contradiction Detection Depth

[-Temporal contradictions — facts that were true at time T but not at T+1 — are no longer a detection gap so much as a *resolution* one: the bi-temporal validity layer (§9.5) is the mechanism that resolves them once the gate routes through `supersede`. Deeper semantic and implication detection using LLM-assisted comparison is planned for a later release.-]

### 10.4 Benchmarks: The Central Evidence Gap

[-### 10.4 Benchmarks: The Central Evidence Gap-]

### 10.4 Benchmarks: The Central Evidence Gap

[-This is the paper's most consequential limitation, and the surrounding ecosystem makes it sharper than it was at v1.0. MNEMOSYNE's headline claim — O(1) concept-index retrieval that beats degrading hybrid search at scale (§4.7) — has never been benchmarked. The complexity analysis predicts constant-time retrieval, but no wall-clock measurement on the production corpus (thousands of concepts) exists to quantify the actual speedup, and the same is true of the bi-temporal read path: §9.5.1 notes a covering index that should keep the always-on `validity_end` filter off the table-scan path, but the per-query overhead has not been measured under production load. The supersede false-positive rate (§9.5.4) and the capture's effect on answer accuracy are likewise unmeasured.-]

### 10.4 Benchmarks: The Central Evidence Gap

[-The comparison to chopratejas/headroom (§2.3) is what makes this gap a liability rather than a routine "future work" line. headroom ships a runnable benchmark suite (`python -m headroom.evals`) that reports token savings and an accuracy delta against named public datasets (GSM8K, TruthfulQA, SQuAD, BFCL). coreyhaines31/marketingskills similarly ships per-skill reproducible assertion checks. When competing and adjacent systems ship runnable evidence, an unmeasured systems paper reads as under-evidenced regardless of how sound its architecture is.-]

### 10.4 Benchmarks: The Central Evidence Gap

[-Benchmark performance and deployed effect are different measurements. In the observed deployment, an installed and enabled headroom proxy served six lifetime requests and saved zero tokens because it was not on the actual traffic path. This does not dispute headroom's stateless benchmark results; it shows that benchmark results cannot establish integration liveness. MNEMOSYNE needs both a reproducible evaluation harness and per-component request/volume counters on the production path.-]

### 10.4 Benchmarks: The Central Evidence Gap

[-The next revision has two honest paths and should commit to one:-]

### 10.4 Benchmarks: The Central Evidence Gap

[-1. **Adopt a comparable reproducible eval harness.** A fixed query set with relevance labels, measuring concept-index versus hybrid-search latency at growing corpus sizes (thousands → hundreds of thousands of chunks), the bi-temporal filter's per-query overhead, and capture's effect on end-to-end answer accuracy — the analogue of headroom's eval module for a retrieval-and-validity system. This is the path that lets the O(1) and supersede claims be stated as results. 2. **Scope the paper as architecture-only.** If the harness is out of scope for now, the speedup and overhead claims should be reframed explicitly as design predictions, not empirical findings, and the abstract and §4.7 should say so without hedging. The current text leans on "O(1)" language that reads as a measured property.-]

### 10.4 Benchmarks: The Central Evidence Gap

[-Path (1) is preferred, because a personal-agent corpus that already exists in production is exactly the realistic workload a benchmark wants, and because eval reproducibility is becoming a distribution prerequisite (§9.4), not a nicety.-]

### 10.5 Capture Volume and a Reversible Sub-Threshold Tier

[-### 10.5 Capture Volume and a Reversible Sub-Threshold Tier-]

### 10.5 Capture Volume and a Reversible Sub-Threshold Tier

[-Compaction-aware capture increases the total volume of stored content. Over time, the captured corpus may grow to rival the original memory corpus. A retention policy (e.g., captured chunks older than 180 days with zero retrieval hits are pruned) is planned for the next release.-]

### 10.5 Capture Volume and a Reversible Sub-Threshold Tier

[-Discarded compactions create a distinct source of growth: the current hook can write and index a capture before the upstream operation is abandoned (§7.6). Retention accounting must separate completed-eviction captures from trigger misfires. The observed redundancy distribution also changes the priority of future filtering: identical hashes addressed about 0.1% of measured Read bytes, while stale, scaffolded, and subset content accounted for about 21%. Similarity and temporal-validity tests deserve evaluation before more exact-match machinery, and Bash/command output must either receive content-specific handling or remain an explicit scope boundary.-]

### 10.5 Capture Volume and a Reversible Sub-Threshold Tier

[-A second, orthogonal direction comes directly from the headroom comparison (§7.5). MNEMOSYNE's triviality filter is lossy: sub-threshold content is discarded with no recovery path, which is precisely the "by the way" loss case Feature 4 set out to fix when the detail happens to be short or near-redundant. A *reversible sub-threshold tier* — compressing what the triviality filter rejects (in the spirit of headroom's reversible CCR) and caching it as recoverable-on-demand rather than promoting it to the searchable corpus — would close that residual loss path while preserving MNEMOSYNE's signal-per-chunk selectivity for normal retrieval. This interacts with the retention policy above: a reversible tier changes what "stored volume" means, since compressed-and-cached content costs far less than promoted-and-indexed content. Evaluating whether the recovery rate of that tier justifies its storage cost is a benchmark question, and folds into the §10.4 harness.-]

### 10.6 Instrumented Does Not Mean On the Path

[-### 10.6 Instrumented Does Not Mean On the Path-]

### 10.6 Instrumented Does Not Mean On the Path

[-Configuration and registration prove that code *can* run, not that production traffic reaches it. The proxy counterexample in §8.3 and the compaction-trigger defects in §7.6 failed at different layers but share the same shape: structural checks passed while the measured data source or traffic path was wrong. Every deployed-status claim therefore needs a stated observation window and at least one request, byte, or event counter at the component boundary. For capture, the minimum evidence is counts of hook invocations, completed compactions, discarded compactions, captured chunks, and indexed bytes. For retrieval and validity, it is query counts by path and temporal mode. Without those counters, the correct status is "path confirmed; liveness unverified."-]

### 11. Conclusion

[-## 11. Conclusion-]

### 11. Conclusion

[-MNEMOSYNE shows how concept indexing, task-conditioned scoring, write-time contradiction handling, and compaction-aware capture can be assembled as a plugin over an unmodified memory core. Its defensible contribution is the integration design and the operational failure modes it exposes, not evidence of superior retrieval performance. The concept index is implemented, the capture write and indexing path is confirmed, and the other two features remain scaffolded; none has enough traffic evidence to justify an unqualified "live" label. The contradiction gate's bi-temporal evolution (§9.5) rests on an existing validity schema, temporal predicate, and supersede writer, but plugin routing remains unfinished. First-party measurements further show that capture correctness depends on upstream trigger validity, final compaction disposition, and content-aware redundancy handling: exact duplicates were only about 0.1% of measured Read bytes, while broader stale and near-duplicate classes were about 21%. The next step is therefore empirical: public retrieval benchmarks and ablations, production-path counters, and a reversible sub-threshold tier evaluated against simpler retention and similarity baselines. Until those exist, MNEMOSYNE is best treated as an implemented integration contribution that can feed a broader persistent-memory systems evaluation.-]

### 1. Introduction

{+An agent that serves one person for months learns things the way an assistant does: the person says something once and expects it to stick. The meeting moved. The supplier prefers calls before noon. Replies go out in the language the owner wrote in. The agent writes these down, and on a later day it reads them back and acts on them. Every serious agent harness now has some version of this. Anthropic's memory tool gives the model a directory of files it can create and edit (Anthropic, 2025); Letta gives it blocks of always-present text it rewrites itself (Packer et al., 2023); Mem0 and Zep extract facts from the conversation and store them in a database or a graph (Chhikara et al., 2025; Rasmussen et al., 2025).+}

### 1. Introduction

{+And the hard part of memory, it turns out, is not storing. Disks are cheap and a full session record can be kept word for word. The hard part is that the memory store is written by many hands at many moments, and a single careless write can poison every turn that follows. Four failures recur in practice, and each one shaped a choice in this paper.+}

### 1. Introduction

{+*A write that contradicts a rule in another file.* A line in the index file, written months ago, restates one of the owner's preferences in shorthand. Later the owner refines the preference, and the agent records the new version in the rules file it loads on every turn. The old line in the index file is never touched, and the index file is loaded on every turn too. Now two always-present texts disagree, and the agent follows whichever one it weighs more on that turn. A check that compares a new write with the nearest stored memories does not catch this, because the two lines sit in different files, were written months apart, and use different words.+}

### 1. Introduction

{+*A fact that has forgotten where it came from.* The agent runs one query, gets nothing back, and concludes that a certain kind of item does not exist. It writes that conclusion down as a fact. Weeks later it reads the fact back and repeats the negative to the owner several times in one session, each time with the confidence of something it had seen. The stored line never said "inferred from one empty query", so nothing told the reader to look again. Zhan et al. (2026) measured the same failure across seven memory systems and named it authority collapse: consolidation keeps the claim and drops the conditions under which it may be used.+}

### 1. Introduction

{+*A retire rule with no judge.* A system that keeps history marks old facts as superseded when a new one replaces them. If it decides "replaced" by position (same file, same line range, new text), then two fragments of one long note that inherit the same position will retire each other in a single pass, although neither fact changed. Nothing counts these closures, so the store hides text that is still true, for weeks, and nobody is told.+}

### 1. Introduction

{+*A correction written beside the error.* When a stored fact turns out wrong, the easy edit is to append a note below it: "this is wrong, see below". The wrong line is still there, still reads as a plain statement, and an agent that reads only the first match picks it up again.+}

### 1. Introduction

{+But none of these is exotic, and none is fixed by a better retriever. They happen at the moment of writing. They are hard for four reasons. The writers are many: a live turn, a nightly pass, the owner editing a file by hand, other agents. The contradictions that hurt are between files and against standing rules, not between near neighbours in an embedding space. Deleting the old version destroys the history that would explain what happened. And judging whether two sentences conflict takes language understanding, which costs money and time on every write.+}

### 1. Introduction

{+Therefore we propose to put one check on every write. *The claim of this paper, in one sentence: an agent's long-term memory stays trustworthy if every write passes a single check inside the write tool that compares it with the same-topic facts, the always-loaded rules and the current turn's observations, stamps it with its source and two dates, and lets only a judge retire an old fact, which is struck through and kept.*+}

### 1. Introduction

{+The contributions, each pointing to the section that argues it:+}

### 1. Introduction

{+1. *A selection step* that says what a live turn writes at once and what the nightly pass picks out of the day's session record, each candidate tied to the record entries it rests on (§4). 2. *A gate in the write path* that every writer passes, with a receipt for every check, so the gate's health is read from counts and never from a switch that says "on" (§5). 3. *A comparison set built from the always-loaded files, the same-topic facts and the turn's own observations*, judged by a small model into a closed set of relations and outcomes (§6). 4. *Supersede by judgement only*, at the level of a fact line, with event time separated from ingestion time, an alarm on suspicious closures, and history kept in the file so that no re-index can lose it (§7). 5. *Source and date on every fact, never an author*, with the source class deciding what a fact may become (§8). 6. *A file shape* that makes the check cheap and the store easy to read: one fact per line, one topic per file, an index file that holds pointers only, use keys written with the fact, and edits as deltas (§9). 7. *A cost model* in the series' notation, showing the check pays for itself at a low error rate if, and only if, the judge is a small model (§10).+}

### 1. Introduction

{+This paper is a design for the next build; it reports no results, and §12 names the tests that would decide each claim. The name MNEMOSYNE, the Greek personification of memory and mother of the Muses, is a handle and not an anchor: what matters is what the mechanism lets an agent do.+}

### 2. Where this sits

{+## 2. Where this sits+}

### 2. Where this sits

{+This is one of four designs for an agent's memory: keeping (J1), writing (J14), finding (J2), learning (J5). J1 decides what survives the context window and keeps the full session record as ground truth. J2 decides how the right fact is found fast. J5 turns repeated experience into rules and promotes them up a ladder from text to code. This paper owns the moment in between: what enters long-term memory, starting with the choice to write at all, in what shape, and under which checks. It checks what the other stages hand it, records what it did, and points to them wherever their ground begins.+}

### 2. Where this sits

{+Several systems already act at write time. We keep what works in each and say what we change.+}

### 2. Where this sits

{+*Mem0* (Chhikara et al., 2025) extracts candidate facts from each exchange, retrieves the most similar stored memories by embedding, and asks a model to choose one of four operations: add, update, delete or do nothing. Its graph variant marks contradicted relationships invalid instead of removing them. We keep the core move, a model that compares a candidate with what is stored and picks from a closed set. We change two things. The comparison set adds the always-loaded rules and the turn's observations to the nearest neighbours, because the contradictions that hurt most are not near neighbours (§6). And delete becomes supersede, struck and kept, for the plain-text store as well as the graph (§7). We also do not extract from every exchange; §4 says what is worth a line.+}

### 2. Where this sits

{+*Zep and Graphiti* (Rasmussen et al., 2025) store facts as edges in a temporal knowledge graph. A new edge is compared with related edges by a model; a contradicted edge is invalidated, not deleted; and each edge carries both the time the fact held in the world and the time the system ingested it. This is the closest prior work to our supersede step, and we adopt its two clocks outright. We differ in the unit and the store: our fact is a line in a human-readable file, the file is the ground truth, and any database is a cache rebuilt from it (§7.3). We add an alarm on closures and a hold for writes that clash with a standing rule.+}

### 2. Where this sits

{+*A-MEM* (Xu et al., 2025) builds each new memory as a note with keywords, tags and a context description, links it to related notes, and lets new notes update the descriptions of old ones. We keep the idea that the moment of writing is the moment to add what will help later; our use keys come from the same instinct (§9.4). We decline the automatic rewrite of old notes: a model that rewrites stored text every time something new arrives is a slow way to lose details, and in our design an old fact changes only by being superseded, visibly.+}

### 2. Where this sits

{+*ROAM* (Zheng et al., 2026) classifies each pair of a new and a stored fact as independent, equivalent, subsuming or conflicting, keeps one primary view and treats the rest as evidence, and reports large accuracy gains over managers that add and rewrite in one step. Its four relations map almost one-to-one onto our judge's outcomes (§6.2). We add two relations ROAM does not need, because its store has no standing rules and no untrusted sources: "clashes with an always-loaded rule" and "comes from untrusted content".+}

### 2. Where this sits

{+*Authority collapse* (Zhan et al., 2026) is the failure measured by the AuthMem benchmark: consolidation keeps a claim but drops the authority under which it may be reused, so a casual remark becomes a standing instruction. Collapse appeared in 48 of 49 configurations they tested, and persisted authority labels removed the unauthorised actions in their end-to-end test. Our source classes are such labels, and §8 makes them decide what a fact may become.+}

### 2. Where this sits

{+*Context collapse*, the loss of detail under repeated wholesale rewriting, is covered with its source in J1 §1.3; the gate's answer to it is the delta rule (§9.5).+}

### 2. Where this sits

{+*File and block tools.* Anthropic's memory tool runs on the client: the model asks for a file operation and the application executes it, which means the application sees every write and can check it (Anthropic, 2025). MemGPT and its successor Letta let the agent edit its own in-context memory blocks, and Letta's sleep-time agents move that editing to a background agent (Packer et al., 2023; sleep-time compute is covered in J5 §2). Both show where writes happen in practice: through tools, in the foreground and in the background. Our gate sits in exactly that tool layer, so it covers both (§5).+}

### 2. Where this sits

{+*Memory poisoning.* MINJA (Dong et al., 2025) injects malicious records into an agent's memory through ordinary queries and reports high success rates. Our untrusted source class and its ceiling (untrusted content never becomes a rule, §8.1) are the write-side defence.+}

### 2. Where this sits

{+Each piece of this design has precedent. What we did not find in the systems above is the placement: a check that sits in the file tool and therefore sees every writer, a comparison set that includes the rules the agent reads on every turn, and a retire step that only a judge may take and that is counted and alarmed. The contribution is that combination, aimed at a store people can read.+}

### 3. The design in one picture

{+## 3. The design in one picture+}

### 3. The design in one picture

{+Figure 1 shows the whole path of a write. Four kinds of writer can change memory: a live turn of conversation, the nightly pass that consolidates the day, the owner editing a file by hand, and another agent. Every write goes through one gate. The gate gathers what the write must be compared with, a small model judges the relation, the fact is stamped with its source and dates, and then it is written, with a receipt for the check.+}

### 3. The design in one picture

{+![The life of a memory write. Every writer goes through one gate inside the write tool. The gate compares the write with the facts on the same topic, the always-loaded files and what the current turn observed; a small model names the relation; the fact is stamped with its source and two dates and written to its file, with a pointer in the index file and a receipt for every check. A write that clashes with a rule is held for the owner and written only after the owner answers.](images/fig1-write-gate.png){width=64%}+}

### 3. The design in one picture

{+A few words carry the rest of the paper. A *fact* is one claim about the world, one line in a file. A *rule* is an instruction about behaviour; where it lives is J5's ladder (J5 §5). An *always-loaded file* is one the harness puts in front of the model on every turn. The *memory store* is the set of fact files, read only when something asks for them; it is a separate place from the always-loaded files, as in J5, and the gate guards writes to both. The *index file* is the always-loaded head of the store: one line per topic, naming the file that holds it. The *owner* is the person the agent serves. A *receipt* is the record the gate leaves for each check.+}

### 3. The design in one picture

{+Walk the example from the abstract through it. On 9 March the owner says, in passing, that the weekly call moved to Thursday the day before. The live turn asks the write tool to add a line to the meetings file. The gate finds the meetings file through the index file, reads its lines, reads the rules, and sees that this turn's calendar lookup also shows Thursday. The judge answers: this replaces the line that says Wednesday. The old line is struck through and kept, marked superseded as of 8 March with a pointer to the new line. The new line carries "told by the owner", true since 8 March, learned 9 March. A receipt records the supersede. Nothing was deleted, and a question about last week still has its answer.+}

### 4. Choosing what to write

{+## 4. Choosing what to write+}

### 4. Choosing what to write

{+The write stage starts before the gate, with the choice to write at all. J1 keeps every session word for word, so a detail left unwritten stays in the record, a search and a read away. A line in the memory store earns its place when it saves a later session that search. In J2's notation, a detail that a later task needs with probability $q$ is worth a line when $q$ times the cost of digging it out of the record (a search and a read, two turns at least, J2 §7.1) exceeds the cost of keeping one line and checking it once (§10). Two kinds of detail pass easily: what the owner states about his world and his preferences, which is needed again almost by definition and cannot be derived from anything else, and observations that took real work to get (where a machine lives, how a problem was solved, what a supplier answered). Two kinds fail: the passing state of the task in hand, and content still on disk, which gets a pointer and never a copy.+}

### 4.1 What a live turn writes, and when

{+### 4.1 What a live turn writes, and when+}

### 4.1 What a live turn writes, and when

{+A live turn writes at once in three cases, because waiting for the night would leave the store wrong for the rest of the day: the owner states a fact or a preference about his world; a tool result disagrees with a stored fact (§8.5); or the turn makes a decision, which is written with its reason. Everything else waits for the nightly pass. A live turn does not extract facts from every exchange, as Mem0 does: each write costs a check, and most exchanges hold nothing a later session needs.+}

### 4.1 What a live turn writes, and when

{+When the owner corrects the agent, J5's cause table sorts the correction first (J5 §3.3). A correction about behaviour becomes a rule in J5's ledger. A correction of a wrong fact has a class of its own there, and it comes here as a supersede of the wrong line (§7.5).+}

### 4.2 What the nightly pass picks out

{+### 4.2 What the nightly pass picks out+}

### 4.2 What the nightly pass picks out

{+The nightly pass reads the day's session records, never the compaction markers, since a summary of a summary has already lost detail (J1 §5.4). A model reads each session and returns candidate fact lines, each with the address of the record entries it rests on (J1 §4.2). A candidate with no address is dropped: a fact the record does not show is a guess. The address stays on the fact as its evidence, and the source class follows the author of those entries (J1 §4.1): an entry the owner wrote gives "told by the owner", a tool result "observed", the agent's own text "inferred", and a web page, a document or another agent's text "untrusted".+}

### 4.2 What the nightly pass picks out

{+The pass looks for four kinds of candidate:+}

### 4.2 What the nightly pass picks out

{+1. facts the owner stated or the agent observed that no live turn wrote down; 2. lines written in a hurry during the day that bundle several claims or sit in the wrong topic file (§9.1, §9.2); 3. lines marked "unchecked" when the judge was down (§5.3), and supersedes left as proposals (§7.2); 4. changes to the layout of the store proposed by J2 (§9.2).+}

### 4.2 What the nightly pass picks out

{+Every candidate is an ordinary write through the gate, so the nightly pass can do nothing the gate does not see. The pass hands its candidates to the gate in event-time order (§7.4) and caps the lines it adds to one topic in a night; candidates past the cap go to the owner as proposals in J5's morning report (J5 §7.4).+}

### 5. Where the check sits

{+## 5. Where the check sits+}

### 5.1 In the write path, as code

{+### 5.1 In the write path, as code+}

### 5.1 In the write path, as code

{+The gate is code, and it sits where every write already passes: the tool that changes a file. Why this is code and not a prompt: J5 §1.2.+}

### 5.1 In the write path, as code

{+Concretely, the gate wraps every tool that can change a file under the memory store or an always-loaded file: create, edit, insert, rename, delete. A shell command can also write a file, and a path guard catches the common forms (redirection, copy, move, in-place edit) aimed at memory paths. Those are refused with a pointer to the file tool, so every write arrives through a tool the gate can read. The same gate serves a client-side memory tool such as Anthropic's, where the application executes each operation itself.+}

### 5.2 Every writer, one gate

{+### 5.2 Every writer, one gate+}

### 5.2 Every writer, one gate

{+The gate does not care who writes, only what is written. The cases differ in what happens when the check objects.+}

### 5.2 Every writer, one gate

{+- *A live turn.* The common case. The check runs before the write lands, and its verdict comes back to the agent as the tool result, so the agent sees "superseded line 4" or "held: clashes with the reply-language rule" and can tell the owner. - *The nightly pass.* Same check. The pass often handles notes in an order that is not the order in which things happened, which is why the gate orders facts by event time and not by arrival (§7.4). - *The owner by hand.* The owner is never blocked. A change he makes is checked after it lands, by watching the files, and a clash is reported to him in J5's morning report (J5 §7.4). He may have forgotten the rule he wrote three months ago; he may also mean to change it, and that is his call. - *Another agent.* A sub-agent or a sibling session writes through the same tools and passes the same check. A write into another agent's memory is also a privacy boundary, so facts of the owner-sensitive classes are scrubbed or refused at that gate.+}

### 5.3 Fast, and never silent when it fails

{+### 5.3 Fast, and never silent when it fails+}

### 5.3 Fast, and never silent when it fails

{+The check is synchronous: the write waits for the verdict. The budget is one small-model call, well under a second in normal operation, and a turn makes many tool calls for each memory write, so the delay is a small share of a turn. When the judge cannot answer (a timeout, a provider error, a quota limit), the write goes through with an "unchecked" mark on the line and an "unchecked" receipt, and a sweep checks those lines later. The gate never fails open in silence, and never blocks the agent because a provider is down.+}

### 5.4 Receipts, and why a zero must mean zero

{+### 5.4 Receipts, and why a zero must mean zero+}

### 5.4 Receipts, and why a zero must mean zero

{+Every check writes a receipt: which file, which relation the judge named, which outcome was applied, which lines were touched, the judge's confidence and the time it took. Receipts are what the rest of the system reads. The health of the gate is computed from them: writes checked per day, outcomes by kind, holds waiting for the owner, unchecked lines waiting for a sweep, closures split by same-file and cross-file.+}

### 5.4 Receipts, and why a zero must mean zero

{+An empty table of contradictions must never read as "no contradictions" when it means "nothing was checked": the series-wide zero-means-zero rule (J5 §9.1) applies, so a count of zero checks on a day when the agent wrote memory is an alarm.+}

### 6. What a write is compared with

{+## 6. What a write is compared with+}

### 6.1 Three sources, not the nearest neighbours alone

{+### 6.1 Three sources, not the nearest neighbours alone+}

### 6.1 Three sources, not the nearest neighbours alone

{+A candidate fact is compared with three things.+}

### 6.1 Three sources, not the nearest neighbours alone

{+*The facts on the same topic.* The write names its target file, and the index file links that file to its topic. The gate reads the target file and the files the index file lists under the same topic. An embedding search over the whole store adds a few near neighbours as a backstop for a fact written in the wrong place. Topic links come first because they are cheap, exact, and already maintained for reading.+}

### 6.1 Three sources, not the nearest neighbours alone

{+*The always-loaded files.* All of them. Always-loaded files are small by design, since they cost context on every turn, and they are exactly where a contradiction does the most harm: a wrong line there is read on every turn, by every task. This is the source that nearest-neighbour checks miss. A line in the index file and a rule that disagree rarely look alike to an embedding, because one is a terse pointer and the other a sentence of instruction, yet they are about the same behaviour.+}

### 6.1 Three sources, not the nearest neighbours alone

{+*What the current turn observed.* Tool results from the turn that mention the subject of the write. If the agent writes "the store has no items of kind X" in the same turn in which a query returned items of kind X, the gate sees both.+}

### 6.2 Relations and outcomes

{+### 6.2 Relations and outcomes+}

### 6.2 Relations and outcomes

{+The judge answers with one relation from a closed set, and each relation has one outcome. Table 1 is the whole decision.+}

### 6.2 Relations and outcomes

{+| Relation the judge names | Outcome | |---|---| | New: nothing stored says this | Add the line, stamped | | Same: already stored, same meaning | Skip the write; refresh the stored line's "last confirmed" date | | Adds detail: compatible, more specific | Merge into the existing line; keep one line per fact | | Replaces: same subject, newer state of the world | Supersede: strike the old line, keep it, point to the new one (§7) | | Conflicts, unclear which is right | Write the new line beside the old, both marked "in conflict"; ask the owner (J5 §7.4) | | Clashes with an always-loaded rule | Hold the write; tell the agent and ask the owner (J5 §7.4) | | Comes from untrusted content and would act as a rule | Store it as a quoted claim with its source; never in an always-loaded file |+}

### 6.2 Relations and outcomes

{+: The judge's relations and the gate's outcomes.+}

### 6.2 Relations and outcomes

{+Two outcomes stop short of writing. A clash with a rule is held because rules are the owner's: either the new fact is wrong, or the rule is out of date, and only the owner can say which. A conflict with no clear winner is written in both versions because dropping either one loses information; the conflict mark makes the reader see both and look again. Both questions reach the owner through J5's morning report (J5 §7.4), the same approval path as every other change to what every turn loads.+}

### 6.3 The judge

{+### 6.3 The judge+}

### 6.3 The judge

{+The judge is a small, fast model that answers only in typed choices: the relation from Table 1, the line it refers to, and a confidence. It writes no free text that the gate must parse. Jev, a small model built to answer in typed choices, is one such judge (TypeSafe AI, 2026); any model that can return a closed choice will do. The instructions it receives describe the relations above, give a few contrasting examples of each, and say what counts as the same subject. The exact wording is kept with the code and changes as the judge improves; the paper does not print it.+}

### 6.3 The judge

{+Two habits keep the judge honest. First, its thresholds are set on a labelled sample, not on defaults: a confidence cut-off that was never tuned learns nothing from being used, and §12 names the sample. Second, people facts sent to a third-party judge carry opaque identifiers ("P17: good at sourcing specific hardware") and never names or contact details.+}

### 6.4 The brain does something similar

{+### 6.4 The brain does something similar+}

### 6.4 The brain does something similar

{+In the brain, recalling a memory can open it for change, and research on fear memory found that it opens only when the recall brings a surprise: a prediction error, a mismatch between what was expected and what happened (Sevenster et al., 2013). With no mismatch, the memory is read and left alone. The gate makes the same distinction explicit. A write that matches what is stored changes nothing but a date; a write that mismatches is the only kind that can change a stored fact, and the mismatch is named and recorded.+}

### 7. Retiring a fact without losing it

{+## 7. Retiring a fact without losing it+}

### 7.1 The unit is the fact line

{+### 7.1 The unit is the fact line+}

### 7.1 The unit is the fact line

{+A fact is retired, never a chunk, a file region or a database row. The reason is the third failure in §1. Any identity based on position (this file, these line numbers) will match pieces that have nothing to do with each other as soon as a long note is split, re-flowed or re-indexed. Facts change because the world changed, and only something that reads the meaning of two lines can tell that the second is a newer state of the first. So the supersede step is an outcome of the judge (§6.2) and nothing else can trigger it.+}

### 7.1 The unit is the fact line

{+![Retiring a fact without losing it. Fact A, written on 2 March, holds until the change it describes; fact B, learned on 9 March, has been true since 8 March. A is struck through and kept, superseded as of 8 March, with a pointer to B. A question about now answers B; a question about 5 March still answers A. The triangles mark when each fact was written down, which is a different clock from when its claim became true.](images/fig2-supersede-timeline.png){width=86%}+}

### 7.2 Only a judge closes, and only when it has earned it

{+### 7.2 Only a judge closes, and only when it has earned it+}

### 7.2 Only a judge closes, and only when it has earned it

{+Automatic closing is a privilege the judge earns. Until a hand-audited sample shows that the judge's "replaces" verdicts are right at least nine times in ten, a supersede is written as a proposal: the new line is added, the old line gets a "possibly superseded by" mark, and the owner or the nightly pass confirms it. Once the judge clears that bar, it closes on its own for fact files. A closure that would retire a line in an always-loaded file is held for the owner in every case and put to him in J5's morning report (J5 §7.4).+}

### 7.3 The mark lives in the file

{+### 7.3 The mark lives in the file+}

### 7.3 The mark lives in the file

{+A retired line stays in place, struck through, followed by one machine-readable tag: superseded, the event date, a pointer to the line that replaced it. One format everywhere, so a person reading the file and a program parsing it see the same thing. Ad hoc markers ("WRONG", "see below", a strike-through with no date) are what a store collects when every writer improvises, and they cannot be counted or queried.+}

### 7.3 The mark lives in the file

{+This puts history where it cannot be lost. J2's text index, or any database built over the files, is a cache: it may mirror the validity of each line in two columns for fast filtering, but it can be dropped and rebuilt from the files at any time. A re-index that deletes a file's rows before writing them again loses nothing, because the history was never in the rows. The reverse arrangement, history kept only in the rows of a search index, means that the most ordinary maintenance step erases it.+}

### 7.4 Two clocks

{+### 7.4 Two clocks+}

### 7.4 Two clocks

{+Every fact carries two dates. *Event time* is when the claim became true in the world: the call moved on 8 March. *Ingestion time* is when the agent learned it: 9 March. The supersede boundary uses event time when the text carries one and ingestion time when it does not.+}

### 7.4 Two clocks

{+The two clocks fix an ordering bug that one clock cannot. Suppose the nightly pass processes an old note ("the call is on Wednesday", event time 2 March) after the live turn has already stored the new one (event time 8 March). With ingestion time alone, the old note looks newest and would retire the new fact. With event time, the gate sees that the incoming claim is older than the current one and files it as history, below the current line, already marked superseded. Zep separates the same two timelines for the same reason (Rasmussen et al., 2025).+}

### 7.5 A correction replaces the line it corrects

{+### 7.5 A correction replaces the line it corrects+}

### 7.5 A correction replaces the line it corrects

{+When a stored fact proves wrong, the correction is a supersede of that line: struck, kept, pointed to the correct one, with the source of the correction ("observed in a tool result", "told by the owner"). A note appended below an untouched wrong line is refused by the gate as a write, because the judge sees that the new line contradicts the one above it and the outcome for that relation is a supersede, not an append. The agent that reads only the first match then reads a struck line and a pointer, and follows the pointer.+}

### 7.6 Count every closure, and alarm on the suspicious ones

{+### 7.6 Count every closure, and alarm on the suspicious ones+}

### 7.6 Count every closure, and alarm on the suspicious ones

{+Every closure writes a receipt (§5.4), and two patterns raise an alarm at their first occurrence. The first is a closure in which the old and new lines come from the same file in the same pass and the judge found no change of meaning: that is the signature of a position-based retire rule, and it should never happen in this design, so any instance means something outside the gate is closing facts. The second is a burst: more closures in a day than a threshold set from the store's normal rate. A burst pauses automatic closing until someone looks. The point of both is that a false closure hides a true fact from every reader, and the only defence that works is to notice it the day it happens.+}

### 7.7 When deleting is right

{+### 7.7 When deleting is right+}

### 7.7 When deleting is right

{+Two cases justify removing content: a privacy request (the owner asks to forget something about a person) and poisoned content (a line proved to have been injected). Even then the gate leaves a short tombstone in place of the line, saying that a line was removed, when and why, without the content. The tombstone keeps the file's history honest. It also stays in the comparison set for its topic, so a later write on the same subject is held for the owner instead of slipping back in unnoticed.+}

### 7.7 When deleting is right

{+A fact file is rarely the only copy. A privacy deletion therefore covers every place the content lives:+}

### 7.7 When deleting is right

{+- *Fact files and the index file.* The line becomes a tombstone, and a line in the index file that pointed only at the removed content goes too. - *The session record.* The entries that carry the content are replaced by tombstones at the same addresses, so a pointer into the record resolves to "removed" and never to a neighbour. How a tombstone sits in a record that is otherwise never edited is J1's to state (J1 §4.3). - *Compaction markers* that quote the content are rebuilt from the record (J1 §5.4), which now holds only the tombstone. - *J2's text and asset indexes.* They are caches over the files and the record (§7.3), so their rows are dropped and rebuilt from the cleaned sources.+}

### 7.7 When deleting is right

{+The deletion writes one receipt that lists every place it touched, and it counts as done only when a search of all of them for the removed content comes back empty. Poisoned content is handled differently in one place: the session record keeps the entries, flagged as untrusted, because they are what happened and the evidence of the attack. The fact lines and index rows built from them go.+}

### 8. Source and date on every fact

{+## 8. Source and date on every fact+}

### 8.1 Source classes, and what each may become

{+### 8.1 Source classes, and what each may become+}

### 8.1 Source classes, and what each may become

{+Every fact carries one of five source classes:+}

### 8.1 Source classes, and what each may become

{+- observed: read from a tool result in the turn that wrote it; - told by the owner: read only from the owner-words field of the session record (J1 §4.1), so a wrapper or an injected instruction never gets this stamp; - inferred: concluded by the agent from other facts or observations; - assumed: taken as true to move on, not checked; - untrusted: taken from content the owner did not write and the agent did not observe directly: a web page, an email, a document, another agent's text.+}

### 8.1 Source classes, and what each may become

{+The class decides what a fact may become. Only facts told by the owner, or observed and then confirmed by the owner, may enter an always-loaded file as rules. Inferred and assumed facts live in fact files and are labelled as such. Untrusted content can be stored as a quoted claim ("the vendor's page says the part ships in May") but never as a rule, and never in a form that drops the quote marks. This is the write-side defence against both authority collapse (Zhan et al., 2026) and memory injection (Dong et al., 2025): a sentence crafted to look like an instruction can get into memory as a quotation, but it cannot get into the place where the agent looks for instructions.+}

### 8.2 No author

{+### 8.2 No author+}

### 8.2 No author

{+A fact says where it came from, never who wrote the line. Which agent, session or model typed a fact into a file tells the reader nothing about whether to trust it; the source class does. Memories, like skills, are knowledge shared by every agent that reads them, and knowledge needs no author: an author field only invites the reader to weigh a fact by its writer. The session record does keep authors (J1 §4.1), and that is where the source class comes from; the fact line keeps the class and drops the writer.+}

### 8.3 A rule carries its purpose and its exception

{+### 8.3 A rule carries its purpose and its exception+}

### 8.3 A rule carries its purpose and its exception

{+What a rule must carry is J5's to say (J5 §3.4): its purpose, and when it applies and when it does not. The gate enforces those fields on the write. A rule written to an always-loaded file (rungs 2–3 in J5) must arrive with a purpose and an exception, and the gate holds one that lacks either. A fact needs neither.+}

### 8.4 Dates, confirmation, and negatives

{+### 8.4 Dates, confirmation, and negatives+}

### 8.4 Dates, confirmation, and negatives

{+Each fact line carries its event date and its ingestion date, plus a "last confirmed" date that a "same" verdict refreshes (§6.2). A fact that keeps being confirmed is worth more than one written once and never seen again, and the confirmation date tells a reader which is which without any learned score.+}

### 8.4 Dates, confirmation, and negatives

{+Negative facts get a mark of their own. "There are no items of kind X" is the kind of claim that is most often wrong, because an empty answer has many causes, and the most expensive to believe, because it stops the search. The gate stamps a negative with its source (almost always "inferred") and the query that produced it, so that a later reader knows to run the query again before repeating it.+}

### 8.5 What happens when a stored fact meets an observation

{+### 8.5 What happens when a stored fact meets an observation+}

### 8.5 What happens when a stored fact meets an observation

{+How a found fact is presented to the model belongs to J2; the write side needs one rule. When a turn reads a stored fact and a tool result in the same turn disagrees with it, the observation wins, and the turn writes the correction then and there. The correction passes through the gate as "observed", the judge names it "replaces", and the old line is superseded (§7.5). The error is fixed in the store at the moment it is discovered, instead of being remembered as a lesson and fixed later, or never.+}

### 8.6 Importance is written, not guessed later

{+### 8.6 Importance is written, not guessed later+}

### 8.6 Importance is written, not guessed later

{+Corrections and decisions are marked important at the moment they are written, as a field on the fact. The gate knows when a write is a correction (the relation is "replaces" and the source is the owner or an observation) and when it records a decision, and it is cheaper to write that down than to infer it months later. How the mark and the last-confirmed date weigh in ranking, and whether unmarked facts fade, is J2's (J2 §5, "Combining keys").+}

### 9. The shape of what is written

{+## 9. The shape of what is written+}

### 9. The shape of what is written

{+The check is only as good as what it reads. Five rules for the shape of the store make the comparison cheap, the supersede exact and the result readable by a person. Figure 3 shows them together.+}

### 9. The shape of what is written

{+![The shape of the store. The index file holds one line per topic: a pointer and a hook saying when to read, never the fact itself. A fact file holds one topic, the facts read together, one fact per line, each with its source and its two dates; a retired line is struck through and kept, with a pointer to its replacement and a use key on the live line. The rules file is always loaded, and every rule carries its purpose and when it does not apply. Content from a web page, an email or another agent can be stored as a quoted claim, but never becomes a rule.](images/fig3-fact-shape.png){width=88%}+}

### 9.1 One fact per line

{+### 9.1 One fact per line+}

### 9.1 One fact per line

{+Each line holds one claim. A line that bundles three claims cannot have one of them retired without rewriting the other two, and a rewrite is exactly the kind of write that loses detail. One fact per line also makes the judge's job smaller: it compares a claim with claims, not paragraphs with paragraphs.+}

### 9.2 One topic per file, and files hold what is read together

{+### 9.2 One topic per file, and files hold what is read together+}

### 9.2 One topic per file, and files hold what is read together

{+A fact file holds one topic, and the facts that tend to be needed together live in the same file. The reason is cost. For an agent working through tools, reading a file costs a turn and the context it fills, so a topic spread over five files costs five reads and a file that mixes five topics fills the context with four that are not needed. J2 develops the cost model; here it decides the layout. J2 also sends this stage evidence about the layout: paths agents keep reaching for that do not exist (J2 §6.7, §8), and co-access pairs that suggest merging or splitting files (J2 §5). Each becomes a proposed write through the gate, and a merge or split waits for the owner's review in J5's morning report (J5 §7.4).+}

### 9.3 The index file holds pointers only

{+### 9.3 The index file holds pointers only+}

### 9.3 The index file holds pointers only

{+A line in the index file holds a pointer and a short hook saying when to read the file. It never restates the fact. This rule exists because of the first failure in §1: a fact restated in the index file is a second copy, and the second copy does not change when the fact does. Every such line that carries a claim is a contradiction waiting for the next update. With pointers only, the index file cannot disagree with the files it points to, and the gate refuses a write to it that contains a claim instead of a pointer. J14 owns the shape of a line in the index file; which entries the head holds and in what order is J2's (J2 §4.3), and the gate checks every line written there, whoever generated it. What leaves an always-loaded file when it outgrows its budget is J5's decision (J5 §7.1–§7.2).+}

### 9.4 Write the use key with the fact

{+### 9.4 Write the use key with the fact+}

### 9.4 Write the use key with the fact

{+How use keys are indexed and matched: J2 §5. The rule here is that the gate asks for a use key, such as "when a hardware part is hard to source", on facts about people and capabilities, where the gap between what a fact is about and when it is needed is widest.+}

### 9.5 Edit by delta, never by wholesale rewrite

{+### 9.5 Edit by delta, never by wholesale rewrite+}

### 9.5 Edit by delta, never by wholesale rewrite

{+The gate accepts small edits: add a line, merge into a line, supersede a line. It holds a write that replaces a whole memory file unless every line the old version had is accounted for: kept, merged, superseded or deleted with a tombstone. A model asked to rewrite a file "more concisely" drops details it judges minor, and repeated rewrites compound the loss (§2). The delta rule makes that loss impossible to commit by accident.+}

### 10. What the check costs, and when it pays

{+## 10. What the check costs, and when it pays+}

### 10. What the check costs, and when it pays

{+Every check costs one model call, and the design must say when that is money well spent. We derive the break-even point from published prices, in the series' notation (J2 §7.1): a cached token is read at $r$ times a model's base input price, and an output token costs $g$ times it. Write $\pi_s$ and $\pi_\ell$ for the base input price, in dollars per token, of a small and a large model.+}

### 10. What the check costs, and when it pays

{+*The cost of a check.* The judge reads the write plus its comparison set, $T_c$ tokens, and returns a typed verdict of about $o_j = 150$ tokens. A small model at $\pi_s$ = \$0.10 per million tokens with $g = 5$ (Anthropic, 2026) checks a write that reads 4,000 tokens for+}

### 10. What the check costs, and when it pays

{+$$C_{\text{check}} = (T_c + g\,o_j)\,\pi_s = \frac{(4000 + 5 \times 150) \times 0.10}{10^6} \approx \$0.00048.$$+}

### 10. What the check costs, and when it pays

{+*The cost of a bad write.* A wrong fact that reaches the store costs at least one wrong turn of the main model before anyone notices. Take a large model at $\pi_\ell$ = \$4 per million tokens, with $r = 0.05$ and $g = 5$ (\$0.20 per million cached tokens and \$20 per million output tokens on the same page), re-reading a cached context of $L$ = 150,000 tokens and writing $o$ = 1,500 tokens:+}

### 10. What the check costs, and when it pays

{+$$C_{\text{turn}} = (rL + g\,o)\,\pi_\ell = \frac{(7500 + 7500) \times 4}{10^6} = \$0.06.$$+}

### 10. What the check costs, and when it pays

{+That cache-read price lies inside the range J5 §5.2 quotes from the same page.+}

### 10. What the check costs, and when it pays

{+*Break-even.* Let $p$ be the share of writes that would mislead, $c$ the judge's catch rate (the share of those it catches), and $n$ the wrong turns each miss causes. The check pays when $p\,c\,n\,C_{\text{turn}} > C_{\text{check}}$, so the break-even share is+}

### 10. What the check costs, and when it pays

{+$$p^{*} = \frac{C_{\text{check}}}{c\,n\,C_{\text{turn}}}.$$+}

### 10. What the check costs, and when it pays

{+With a judge that catches half the bad writes ($c = 0.5$) and one wrong turn per miss, $p^{*} \approx 1.6\%$: the check pays once about one write in sixty would have misled a single turn. If a bad write costs three wrong turns, the bar drops to about one in two hundred. Figure 4 plots $p^{*}$ against the size of the comparison set.+}

### 10. What the check costs, and when it pays

{+![When the check pays for itself, in money alone. The vertical axis is the share of memory writes that would mislead at least one turn; above each curve the check saves more than it costs. A small-model judge breaks even at one to a few percent of writes across comparison sets of up to 20,000 tokens. The same check run on the large model breaks even only when a large share of writes would mislead, and past about 7,000 tokens it can never pay in money. Computed from Anthropic's published prices (October 2026) with a judge that catches half the bad writes; the owner's time is not counted.](images/fig4-check-breakeven.png){width=86%}+}

### 10. What the check costs, and when it pays

{+Three design choices follow. The judge is a small model: the same check on the large model costs forty times more and only pays when most writes are bad. The comparison set is kept tight (same-topic facts and the rules, not the whole store), because its cost grows with every token it reads. And the estimate is a floor: it counts no minute of the owner's time, and the failures in §1 cost the owner corrections, repeated explanations and lost trust, which are worth far more than a few cents of model time.+}

### 10. What the check costs, and when it pays

{+Latency follows the same logic: one small-model call per write is a small share of a turn, and §5.3 says what happens when it is not.+}

### 11. Conclusions

{+## 11. Conclusions+}

### 11. Conclusions

{+An agent's memory goes wrong at the moment of writing, and the fix belongs there. MNEMOSYNE first says what is worth writing: a live turn writes what the owner states and what contradicts the store, and the nightly pass picks the rest out of the session record, each candidate tied to the entries it rests on. It then puts one check inside the write tool, so that a live turn, the nightly pass, the owner's own edits and other agents all pass it. The check compares a write with the facts on the same topic, the always-loaded files and the turn's own observations; a small model names one of seven relations, and each relation has one outcome. Only that judgement can retire a fact, which is struck through and kept in the file with its event and ingestion dates. Every fact carries a source class that decides what it may become, and no author. The store is shaped so the check is cheap and exact: one fact per line, one topic per file, an index file of pointers only, use keys written with the fact, and edits as deltas. A deletion for privacy reaches every copy, from the fact file to the session record and J2's indexes. Every check leaves a receipt, so the gate's health is read from counts. At published prices the check pays for itself once roughly one write in sixty would mislead a single turn, provided the judge is a small model.+}

### 11. Conclusions

{+The design has limits. The judge's precision is unknown until it is measured, and a judge that holds too often will annoy the owner as surely as one that misses will mislead him. Topic links are only as good as the index file, so a fact filed under the wrong topic is compared with the wrong neighbours, and the embedding backstop narrows this gap without closing it. Checks on the owner's own edits only report, so a clash he does not read stays in place. The path guard on shell writes covers the common forms, and an indirect write (a script that writes a memory file) can still go around it. And the gate does nothing for a fact that is stored correctly and never found; that is J2's problem, just as making a rule bind is J5's.+}

### 11. Conclusions

{+If the tests below hold, the notebook from the first paragraph becomes something an agent can keep: every line dated, every source named, every correction made once and kept, and nothing true ever erased without a trace.+}

### 12. Next steps

{+## 12. Next steps+}

### 12. Next steps

{+The gate will be built and tested on our own agent, and an updated version of this paper will report the results. These tests decide the design:+}

### 12. Next steps

{+1. *Catching the clashes that matter.* Build a labelled set from the dated corrections already written by hand in a long-lived memory store, plus every known case of an always-loaded line that contradicted a rule. Replay each original write through the gate with the store as it stood that day. Pass: the gate flags every rule clash and at least half of the later-corrected facts, at a precision of at least 0.9 on a hand audit of its flags. 2. *The judge's bar for closing on its own.* On a hand-audited sample of 200 "replaces" verdicts, automatic closing turns on only if at least nine in ten are right (§7.2). The same sample sets the confidence threshold. 3. *No closure by position.* Index the same file twice, split a long note into fragments, and re-flow a file. Pass: zero closures. Then write one fact in one file that contradicts a fact in another. Pass: exactly one closure, made by the judge, with a pointer. 4. *The alarm fires on day one.* Replay a burst of same-file, same-pass closures. Pass: the alarm fires on the first one, and automatic closing pauses. 5. *Authority survives the write.* In the style of AuthMem (Zhan et al., 2026), pair facts that differ only in their source, one told by the owner and one quoted from a web page or another agent. Pass: the untrusted twin never reaches an always-loaded file, and an action that depends on it is never taken without the owner. 6. *Errors fixed when found.* Over a month of session records, count turns in which a stored fact met a disagreeing tool result. Pass: the store was corrected in the same turn in at least nine of ten such cases. 7. *Cost and delay.* Measure tokens and time per check on real writes. Pass: median under one second, and a cost per check consistent with §10. 8. *The outcome that counts.* The share of the owner's prompts that repeat a correction about a stored fact, before and after the gate. Pass: it falls, and a fact corrected once is not corrected again. 9. *What the nightly pass misses.* Over a month of session records, take every fact the owner had to state twice. Pass: the nightly pass had proposed at least nine in ten of them after the first time, each with a record address, and the owner rejected fewer than one proposal in five. 10. *A deletion leaves no copy.* Plant a fact about a made-up person in a session, let it reach a fact file, a compaction marker and both of J2's indexes, then ask for it to be forgotten. Pass: a search of every store returns only tombstones, every pointer into the record still resolves, and a later write about the same person is held.+}

### 12. Next steps

{+Two further ideas are worth trying once the gate runs. A judge could also propose use keys for facts written without one, and its proposals could be scored by whether J2's replay finds the fact sooner. And the conflict outcome (both versions kept, owner asked) could feed J5's rule ledger, since a fact that keeps flipping is often a rule that was never written down.+}

### References

[-- Lewis, P., et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. *NeurIPS 2020.* - Packer, C., et al. (2023). MemGPT: Towards LLMs as Operating Systems. *arXiv:2310.08560.* - Xu, Z., et al. (2025). A-MEM: Agentic Memory for LLM Agents. *arXiv preprint.* - Croft, W.B., Metzler, D., & Strohman, T. (2010). *Search Engines: Information Retrieval in Practice.* Addison-Wesley. - MemoryOS. (2024). Mem0: Multi-Level Memory Architecture. *mem0.ai.* - Carbonell, J. & Goldstein, J. (1998). The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries. *SIGIR 1998.* - Robertson, S. & Zaragoza, H. (2009). The Probabilistic Relevance Framework: BM25 and Beyond. *Foundations and Trends in IR.* - Chopra, T. (2025). headroom: Reversible Compress-Cache-Retrieve for Agent Context. Open-source project (chopratejas/headroom), Apache-2.0; reproducible eval suite and Kompress-v2-base compression model. - Haines, C. (2025). marketingskills: A Reproducible Skills Collection for Marketing Agents. Open-source project (coreyhaines31/marketingskills).-]

### References

{+Anthropic (2025). *Memory tool.* Claude Developer Platform documentation. <https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool>+}

### References

{+Anthropic (2026). *Pricing.* Claude Developer Platform documentation, read 12 October 2026. <https://platform.claude.com/docs/en/about-claude/pricing>+}

### References

{+Chhikara, P., Khant, D., Aryan, S., Singh, T., and Yadav, D. (2025). *Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory.* arXiv:2504.19413. <https://arxiv.org/abs/2504.19413>+}

### References

{+Dong, S., Xu, S., He, P., Li, Y., Tang, J., Liu, T., Liu, H., and Xiang, Z. (2025). *Memory Injection Attacks on LLM Agents via Query-Only Interaction.* arXiv:2503.03704. <https://arxiv.org/abs/2503.03704>+}

### References

{+Packer, C., Wooders, S., Lin, K., Fang, V., Patil, S. G., Stoica, I., and Gonzalez, J. E. (2023). *MemGPT: Towards LLMs as Operating Systems.* arXiv:2310.08560. <https://arxiv.org/abs/2310.08560>+}

### References

{+Rasmussen, P., Paliychuk, P., Beauvais, T., Ryan, J., and Chalef, D. (2025). *Zep: A Temporal Knowledge Graph Architecture for Agent Memory.* arXiv:2501.13956. <https://arxiv.org/abs/2501.13956>+}

### References

{+Sevenster, D., Beckers, T., and Kindt, M. (2013). Prediction error governs pharmacologically induced amnesia for learned fear. *Science* 339(6121), 830–833. <https://doi.org/10.1126/science.1231357>+}

### References

{+TypeSafe AI (2026). *Introducing System One models and Jev.* <https://typesafe.ai/blog/introducing-system-one-models-and-jev>+}

### References

{+Xu, W., Liang, Z., Mei, K., Gao, H., Tan, J., and Zhang, Y. (2025). *A-MEM: Agentic Memory for LLM Agents.* arXiv:2502.12110. <https://arxiv.org/abs/2502.12110>+}

### References

{+Zhan, Q., Zhang, R., Guo, S., Zhao, L., and Liu, Z. (2026). *When Memory Becomes Authority: Benchmarking Authority Collapse at the Memory Consolidation Boundary.* arXiv:2608.01679. <https://arxiv.org/abs/2608.01679>+}

### References

{+Zheng, J., Lai, P., Cheng, S., Zhao, J., Yang, L., and Chen, G. (2026). *ROAM: Robust Organization of Atomic Memories for Agents through Semantic Relations.* arXiv:2609.09778. <https://arxiv.org/abs/2609.09778>+}

### References

{+---+}

### References

{+_J-series paper J14 | Version 2.0 | 2026-10-12_+}
