# INSTANT RECALL: Finding What the Agent Already Owns: v5.0 → v7.0

From v5.0 (9 Mar) to v7.0 (1 Apr): 9,101 words to 4,889 words, 1,965 words in new or rewritten paragraphs and 6,177 taken out, 234 paragraphs changed.

## Change note of v7.0

**Renamed Instant Recall; rebuilt around a clear evaluation**

The paper is renamed from HIPPOCAMPUS to Instant Recall, and the companion papers get their new names too (ENGRAM becomes Total Recall). It is compared here with v5.0, because v6.0 is not in the folder, so the changes of two steps show at once. The text is about half as long.

- The fifth failure mode and its three counter-measures are gone; the paper is back to four failure modes.
- The abstract is cut from 483 to 148 words and drops implementation detail.
- The evaluation is rebuilt as protocol, results, ablations, unit tests and threats to validity.
- Searching every source at question time becomes a named baseline, and the paper says plainly that it finds slightly more than Instant Recall, though much more slowly.
- New section on ethical considerations; several terms in the formulas are now defined.

## Changed paragraphs

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

### Instant Recall: A Pre-Computed Concept Index for O(1) Memory Retrieval in Persistent AI Agents

# [-HIPPOCAMPUS:-] {+Instant Recall:+} A Pre-Computed Concept Index for O(1) Memory Retrieval in Persistent AI Agents

### Instant Recall: A Pre-Computed Concept Index for O(1) Memory Retrieval in Persistent AI Agents

**Oscar Serra¹** ¹Independent Research [-*Version 5.0 - 9-] {+_Version 7.0 —+} March [-2026*-] {+2026_+}

### Abstract

[-Persistent AI agents accumulate long-term memory across sessions, but current retrieval architectures fail to leverage this history at inference time. We identify and formally define **Contextual Ownership Retrieval Failure (CORF)**: the agent cannot retrieve memories it demonstrably owns, because the retrieval mechanism is query-constrained, source-limited, and executed at inference cost. We characterize **five failure modes** and provide empirical frequency estimates from eighteen months of real deployment logs. A newly discovered fifth mode — **Self-Contradiction Failure (SCF)** — is reported here for the first time: the agent has *written* correct information in its own daily logs or memory files but fails to retrieve it before taking an action that contradicts its own notes. SCF is distinct from Modes 1–4 in that the missing memory is not someone else's content but the agent's own recent self-written state.-]

### Abstract

[-We propose **HIPPOCAMPUS** - a pre-computed concept-to-memory-address index mapping anchor terms to pre-ranked chunk lists offline, enabling inference-time retrieval that is **O(1) in corpus size n** (work O(|V| + |A| + K·|A|) including semantic anchor expansion over |V| anchors, plus re-ranking over ≤K·|A| candidates). The architecture is inspired by the neuroscientific role of the biological hippocampus as an indexing structure — not a storage structure — between long-term cortical memory and working memory. HIPPOCAMPUS closes the missing architectural layer between ENGRAM (persistent storage; Serra, 2026a) and CORTEX (agent identity; Serra, 2026b).-]

### Abstract

[-Version 5.0 introduces three architectural components to address SCF: (1) a **Daily Log Hot Cache (Tier 0)** that unconditionally injects today's self-written log into every turn's context, eliminating SCF for current-day notes; (2) **Structured Query Extraction** that replaces generic FTS queries with entity-aware extraction, generating per-entity FTS queries merged with MMR deduplication; and (3) a **Pre-Action Contradiction Gate** that, before any write-class action (calendar, email, task management), performs a targeted memory search for the entities being acted upon and surfaces any state contradictions before execution — analogous to a pre-commit hook in version control.-]

### Abstract

[-Key contributions: (1) a CORF taxonomy (now five modes) plus a source-coverage upper bound that separates *coverage* error from *ranking* error; (2) HIPPOCAMPUS, an offline **anchor→chunk cache** with real-time incremental updates; (3) importance scoring with weighted retrieval, deduplication via similarity check, and an episodic tier for same-day freshness; (4) a design-space comparison against inverted index, all-sources ANN, and knowledge-graph overlays; (5) an annotated CORF benchmark derived from deployment logs and an all-sources ANN baseline that isolates the value of concept anchoring; (6) three new SCF-mitigation components (Tier 0 Hot Cache, Structured Query Extraction, Pre-Action Contradiction Gate) with projected theoretical results. The Phase 6.2 validation suite confirms implementation correctness: 158 tests (154 passed, 4 todo), 0 failures, 968 ms across 6 test files. The production TypeScript implementation spans 6 source files and 2,286 LOC, with three additional planned source files (§8a).-]

### Abstract

{+Persistent AI agents accumulate months of interaction history yet routinely fail to retrieve knowledge they demonstrably own. We formalize this as **Contextual Ownership Retrieval Failure (CORF)**, identify four failure modes from eighteen months of deployment logs, and introduce **Instant Recall** — a pre-computed concept-to-memory index that resolves retrieval _before the model processes the prompt_. By mapping anchor vocabulary terms to pre-ranked memory clusters offline, Instant Recall achieves 0.85 CORF-Recall@20 at 54ms p95 latency — a 5.9× speedup over MemGPT-style sequential retrieval (0.79 at 320ms) — with a false positive rate of 0.18 and zero inference-time search computation. A probabilistic source-coverage analysis establishes that parallel source aggregation, not query quality, is the binding constraint on retrieval completeness. Concept anchoring closes the 9-point recall gap that remains after source coverage is saturated.+}

### Abstract

**Keywords:** AI agent memory, episodic retrieval, cognitive architectures, RAG, hippocampal indexing, context management, [-sleep consolidation, CORF, self-contradiction failure, entity extraction, contradiction detection-] {+Sleep Consolidation, CORF+}

### 1. Introduction

The gap between what a persistent AI agent [-*knows*-] {+_knows_+} and what it [-*retrieves*-] {+_retrieves_+} is one of the least-studied problems in agent architecture. As agents accumulate months of interaction history, project notes, [-emails,-] and [-imported-] documents, the [-stored-] memory base grows [-far-] faster than the retrieval mechanisms designed to access it. The result is not amnesia — the data [-is there-] {+exists+} — but [-*retrieval-] {+_retrieval+} failure under [-load*: the agent holds extensive history but cannot surface it when it matters.-] {+load_.+}

### 1. Introduction

{+Consider a concrete scenario. An agent has collaborated with its user on six technical papers over eighteen months, stored across a local memory directory, an imported ChatGPT archive, and a project index. The user asks: _"Can we talk about peer review for our papers?"_ The agent responds: _"What type of papers are you referring to?"_+}

### 1. Introduction

{+This is not a hallucination or a context-length problem. The agent has the data. The failure is architectural: retrieval was not triggered by the right signals, did not search the right sources, and could not surface the right memories within a single inference step's latency budget.+}

### 1. Introduction

{+We call this **Contextual Ownership Retrieval Failure (CORF)** and argue it is endemic to current agent memory architectures.+}

### 1. Introduction

{+The solution — **Instant Recall** — draws on a structural analogy from neuroscience. The biological hippocampus does not store long-term memories; it indexes them [Teyler & DiScenna, 1986]. Instant Recall implements this separation of indexing from storage computationally: a pre-computed concept index, built offline during a Sleep Consolidation phase, maps anchor vocabulary terms to their nearest memory clusters in embedding space. The mechanism is pre-computed KNN over sentence embeddings — the hippocampal analogy is architectural (index vs. store), not mechanistic. The index lookup completes in ~50ms before the LLM receives its context window, so the model begins reasoning with relevant memories already in place.+}

### 1. Introduction

**Scope note:** This paper addresses deployments up to ~50,000 memory chunks (roughly [-2-3-] {+2–3+} years of [-a-] personal assistant [-accumulating documents, notes, emails, and conversation summaries).-] {+history).+} Large-scale adaptations [-— required at-] {+for+} 100,000+ chunks [-—-] are discussed in Section 8.

### 1. Introduction

[-Consider two concrete scenarios. The first is the canonical CORF scenario: an agent has collaborated with its user on six technical papers over eighteen months. The papers are stored across multiple sources: a local memory directory, an imported ChatGPT conversation archive, and a project index file. The user sends a single message: *"Can we talk about peer review for our papers?"* The agent, despite possessing complete knowledge of every paper, responds: *"What type of papers are you referring to?"* This is not a hallucination. It is not a context-length problem. The agent has the data. The failure is *architectural*: the retrieval layer was not triggered by the right signals, did not search the right sources, and could not surface the right memories within the latency budget of a single inference step.-]

### 1. Introduction

[-The second scenario was discovered in production on 2026-03-09. The HIPPOCAMPUS system was live with a retrieval pack injecting ~16K characters per turn from an 878K-event FTS5 corpus. Despite this substantial retrieval budget, the agent flagged a calendar conflict for a meeting it had **already noted as postponed** in its own daily log earlier that same day. The agent contradicted itself. It wrote the correct state; it failed to retrieve it. The retrieval pack had searched on a generic "recent conversation" query rather than extracting the specific named entities from the user message — the meeting name, the date, the people involved. None of those entities surfaced the daily log entry that contained the postponement note.-]

### 1. Introduction

[-We call this second failure **Self-Contradiction Failure (SCF)**, and designate it CORF Mode 5. It is qualitatively distinct from Modes 1–4: SCF occurs when the agent's own *self-written* recent notes are not retrieved, causing the agent to act against state it explicitly recorded. A retrieval system that saturates source coverage (Mode 3), handles pronouns (Mode 1), traverses associative chains (Mode 2), and covers all anchor terms (Mode 4) can still exhibit SCF if it uses generic rather than entity-specific queries.-]

### 1. Introduction

[-We call this failure mode **Contextual Ownership Retrieval Failure (CORF)**. We argue CORF is endemic to current agent memory architectures and propose a solution that addresses all five of its underlying failure modes.-]

### 1. Introduction

[-The solution — **HIPPOCAMPUS** — takes inspiration from neuroscience. The biological hippocampus does not store long-term memories; it indexes them. HIPPOCAMPUS is that address book. It is a pre-computed index built offline, during a sleep consolidation phase, that maps anchor vocabulary terms to their nearest memory clusters in embedding space.-]

### 1. Introduction

[-HIPPOCAMPUS-] {+Instant Recall+} is the second layer in a three-tier cognitive architecture stack: [-**ENGRAM**-] {+**Total Recall**+} (storage and compaction; Serra, 2026a) → [-**HIPPOCAMPUS**-] {+**Instant Recall**+} (concept index) → [-**CORTEX**-] {+**Identity Persistence**+} (agent identity; Serra, 2026b). [-CORTEX's-] {+Identity Persistence's+} Tier 3 retrieval slots are supplied by [-HIPPOCAMPUS-] {+Instant Recall+} lookups. [-LIMBIC-] {+Humor Embeddings+} (Serra, 2026d) relies on [-HIPPOCAMPUS-] {+Instant Recall+} anchor clusters to load humor-relevant episodic context during bridge discovery. [-SYNAPSE-] {+Round Table+} (Serra, 2026e) coordinates nightly rebuild scheduling across modules.

### 1. Introduction

1. **Formal CORF definition and taxonomy** — [-five-] {+four+} failure modes with empirical frequency estimates and a source-coverage upper bound [-that motivates unified cross-source indexing.-] {+separating _coverage_ error from _ranking_ error.+} 2. [-**HIPPOCAMPUS-] {+**Instant Recall+} architecture** — [-full design-] including real-time incremental index updating [-(promoted from "future work" to-] {+as a+} first-class [-component).-] {+component.+} 3. **Importance scoring** — weighted retrieval prioritizing decisions, entities, and user-engaged content. 4. **Deduplication via similarity check** — prevents index bloat from recurring logs. 5. **Post-retrieval re-ranking** — reduces false positive injection. 6. **Design space analysis** — [-explicit-] comparison against inverted index, all-sources ANN, {+multi-source RAG, knowledge graph,+} and [-knowledge graph-] {+vector database+} alternatives. 7. **Evaluation protocol + artifacts** — metrics, baselines, {+ablations,+} and an annotated CORF dataset from deployment [-logs. 8. **SCF mitigation architecture** — three new components (Tier 0 Hot Cache, Structured Query Extraction, Pre-Action Contradiction Gate) with projected theoretical results targeting SCF elimination on write-class actions.-] {+logs.+}

### 2.1 Persistent Agent Memory Systems

Memory in AI agents has evolved from pure in-context storage toward hierarchical architectures separating short-term working memory from long-term storage. The dominant paradigm is Retrieval-Augmented Generation (RAG): relevant documents are fetched [-from a retriever-] and injected into the context window at inference time [Lewis et al., 2020]. [-HIPPOCAMPUS-] {+Instant Recall+} complements [-these-] {+RAG+} by pre-computing a small anchor→chunk index so retrieval cost is constant in corpus size and [-less dependent on the-] {+independent of+} query [-being well-formed.-] {+quality.+}

### 2.1 Persistent Agent Memory Systems

Recent work has expanded the [-agent memory landscape considerably.-] {+landscape.+} A-MEM [Xu et al., 2025] introduces agentic memory where the agent [-itself-] manages [-memory formation and-] {+its own+} retrieval strategies. Memory-R1 [Yan et al., 2025] applies reinforcement learning to [-train-] memory management policies. LongMemEval [Wu et al., 2024] [-provides a benchmark for-] {+benchmarks+} long-term interactive memory. MemGPT [Packer et al., 2023] introduced virtual context management inspired by [-operating system-] {+OS+} paging. Mem0 [MemoryOS, 2024] builds a multi-level memory [-architecture with short-term, episodic, and long-term stores.-] {+architecture.+} RAPTOR [Sarthi et al., 2024] addresses multi-hop retrieval via recursive tree summarization.

### 2.2 The ENGRAM and CORTEX Architectures

[-### 2.2 The ENGRAM and CORTEX Architectures-]

### 2.2 The Total Recall and Identity Persistence Architectures

{+### 2.2 The Total Recall and Identity Persistence Architectures+}

### 2.2 The Total Recall and Identity Persistence Architectures

[-ENGRAM-] {+Total Recall+} [Serra, 2026a] defines persistent agent memory as a compaction-based cache eviction system. Raw events are stored in an event log; a compaction algorithm promotes high-salience content to long-term storage while evicting low-salience [-content via pointer markers. ENGRAM-] {+content. Total Recall+} provides the storage substrate on which [-HIPPOCAMPUS-] {+Instant Recall+} operates: `runHippocampusRebuild()` (§8a) consumes [-ENGRAM-] {+Total Recall+} event files as its primary input.

### 2.2 The Total Recall and Identity Persistence Architectures

[-CORTEX-] {+Identity Persistence+} [Serra, 2026b] addresses agent identity drift across session [-boundaries. CORTEX maintains-] {+boundaries via+} a PersonaState structure injected into every session's system prompt. [-CORTEX-] {+Identity Persistence+} assumes relevant memories can be retrieved; [-HIPPOCAMPUS provides the mechanism that-] {+Instant Recall+} makes this assumption true [-by-] {+—+} supplying Tier 3 context [-chunks.-] {+chunks at every prompt, before the model begins processing.+}

### 2.3 Neuroscience Basis

The biological hippocampus is a medial temporal lobe structure critical for episodic memory formation and retrieval. Lesion studies establish that it does not store long-term memories — those are distributed across neocortical areas — but encodes [-*indices*-] {+_indices_+} [Teyler & DiScenna, 1986; Squire, 1992].

### 2.3 Neuroscience Basis

During sleep, hippocampal replay consolidates {+these+} indices: recently encoded patterns are reactivated, strengthening links between hippocampal indices and cortical storage sites. This offline consolidation is [-precisely-] what our [-sleep consolidation-] {+Sleep Consolidation+} phase implements.

### 2.4 Self-Contradiction in AI Systems

[-### 2.4 Self-Contradiction in AI Systems-]

### 2.4 Self-Contradiction in AI Systems

[-The SCF failure mode described in this paper has not been formally studied in the agent memory literature to our knowledge. Related phenomena include "instruction following failure" [Wei et al., 2022] and "context window neglect" [Shi et al., 2023], but these involve ignoring information *in* the current context window rather than failing to *retrieve* self-written information before acting. SCF is architecturally distinct: the information was in context at write time (when the agent wrote it), but is not in context at action time (when the agent takes a contradicting action). The gap between these two moments is the retrieval failure.-]

### 2.4 Self-Contradiction in AI Systems

[-Pre-commit hooks in version control systems [Loeliger & McCullough, 2012] provide a useful analogy: a developer may have documented a deprecation decision in a comment file but then introduce a call to the deprecated function in a new commit if no pre-commit hook enforces the constraint. The Pre-Action Contradiction Gate (§4.10) is the agent-memory analogue.-]

### 3.1 Formal Definition

{+**Definition (CORF).** A Contextual Ownership Retrieval Failure occurs when:+}

### 3.1 Formal Definition

[-**Definition (CORF).** A Contextual Ownership Retrieval Failure occurs when:-] 1. There exists $m^* \in M$ such that $m^*$ is ground-truth relevant to $q$. 2. $m^* \notin R(q, M)$ — the retrieval function fails to surface $m^*$. 3. The agent generates a response $a$ that contradicts, ignores, or is incompatible with the content of $m^*$.

### 3.2 Failure Modes

**Mode 1 — Pronoun Blindness.** The query uses pronouns ("our papers", "we wrote") without explicit noun [-anchors. The retrieval signal is present but encoded in referring expressions that do not activate anchor vocabulary.-] {+anchors.+}

### 3.2 Failure Modes

**Mode 2 — Associative Depth Failure.** The relevant memory requires two or more associative hops from query [-terms. The query mentions "deadline" but the relevant chunk discusses a specific project whose deadline is not in the query — the retrieval system cannot traverse the associative chain.-] {+terms.+}

### 3.2 Failure Modes

**Mode 3 — Source Blindness.** The relevant memory exists in a source not queried at inference [-time. The agent searches `memory/` but the relevant chunk is in `archive/chatgpt-import/`.-] {+time.+}

### 3.2 Failure Modes

**Mode 4 — Anchor Silence.** A domain-significant noun is present in the query but does not trigger a comprehensive [-sweep. The anchor "peer review" is in the vocabulary but the relevant chunks are indexed under "review" without the compound term.-] {+sweep.+}

### 3.2 Failure Modes

[-**Mode 5 — Self-Contradiction Failure (SCF).** *(New in v5.0, discovered in production 2026-03-09.)* The agent has *written* correct state information in its own daily log or memory files — earlier in the same session or in a previous session that day — but fails to retrieve this self-authored note before taking an action that directly contradicts the recorded state. Examples: (a) the agent noted a meeting as postponed at 09:14 but flags a calendar conflict for that meeting at 14:37 because the retrieval pack used a generic query that did not extract the meeting entity; (b) the agent marked a task as complete in its daily log but re-adds it to the task list; (c) the agent recorded a user preference change but applies the old preference in a subsequent action.-]

### 3.2 Failure Modes

[-SCF differs categorically from Modes 1–4. In Modes 1–4, the missing memory is *other* content — papers, emails, documents written by external parties or imported from external sources. In Mode 5, the missing memory is the agent's *own recent output*. The content is unambiguously agent-owned, maximally relevant, and typically recent (same day or previous session). The failure is therefore not about source coverage, anchor matching, or query breadth — it is about the retrieval *strategy* not being entity-aware enough to surface the specific state that a pending action is about to contradict.-]

### 3.2 Failure Modes

[-**Key property of SCF:** the agent's own daily log is a guaranteed-relevant source for any action the agent takes that day. Loading it unconditionally (Tier 0 Hot Cache, §4.6c) eliminates SCF for current-day notes. For multi-day contradictions, the Pre-Action Contradiction Gate (§4.10) with entity-targeted retrieval is required.-]

### 3.3 Probabilistic Source-Coverage Analysis

**Observation 1 (Source-coverage upper bound).** {+Let $P(s) = |\{m \in M^* : s_m = s\}| / |M^*|$ be the fraction of ground-truth relevant memories stored in source $s$, where $M^* \subseteq M$ is the set of all relevant memories for the query distribution.+} For any retrieval strategy restricted to sources $\mathcal{Q} \subseteq S$:

### 3.3 Probabilistic Source-Coverage Analysis

**Implication.** Improving query embedding quality within a fixed source set yields bounded recall improvement. Adding sources [-yields unbounded improvement (up to 1.0). HIPPOCAMPUS fixes source coverage-] {+raises the upper bound toward 1.0 but cannot exceed it. Instant Recall saturates this bound+} at build time by aggregating all sources into a single unified [-index, saturating this bound.-] {+index.+}

### 3.3 Probabilistic Source-Coverage Analysis

[-**Observation 2 (SCF as a degenerate source-coverage case).** For Self-Contradiction Failure, the relevant source is the agent's own daily log — a source with $P(s) = 1.0$ for any action the agent takes today. The source-coverage bound for this source is therefore 1.0. SCF is not caused by the daily log being absent from the source set; it is caused by a retrieval query that does not activate the daily log's content. This makes SCF a *query quality* failure, not a *source coverage* failure — and thus not fully addressed by the existing HIPPOCAMPUS anchor mechanism without the enhancements in §4.6c, §4.9, and §4.10.-]

### 3.4 Frequency Analysis

| Failure Mode | Est. Frequency (ownership queries) | Severity | [-|---|---|---|-] {+| ------------------------- | ---------------------------------- | -------- |+} | Pronoun Blindness | ~12% | High | | Associative Depth Failure | ~8% | High | | Source Blindness | ~23% | Critical | | Anchor Silence | ~31% | High [-| | **Self-Contradiction Failure (SCF)** | **~15%*** | **Critical**-] |

### 3.4 Frequency Analysis

[-*\*SCF frequency estimate for write-class actions only (calendar creates/edits, task management, email sends, preference changes). SCF is not applicable to read-only queries. The ~15% estimate is derived from manual review of 340 write-class actions in the deployment log; 51 were found to contradict a same-day or previous-session daily log entry that was not in context at action time. SCF frequency is expected to be near-zero after deploying the Tier 0 Hot Cache (§4.6c) and Pre-Action Contradiction Gate (§4.10). This estimate is preliminary and will be refined in future empirical validation.*-]

### 3.4 Frequency Analysis

{+These frequencies are derived from manual annotation of a stratified sample (n=612) from the full query log. Annotators labeled each query with the applicable failure mode(s) when ground-truth relevant chunks were not retrieved by the baseline system. Percentages do not sum to 100% because a single query can exhibit multiple failure modes simultaneously (e.g., a pronoun-heavy query targeting an unqueried source triggers both Mode 1 and Mode 3).+}

### 4. HIPPOCAMPUS Architecture

[-## 4. HIPPOCAMPUS Architecture-]

### 4. Instant Recall Architecture

{+## 4. Instant Recall Architecture+}

### 4.1 Overview

[-HIPPOCAMPUS is a three-phase system:-]

### 4.1 Overview

{+Instant Recall operates in three phases:+}

### 4.1 Overview

- **Offline [-phase-] (nightly [-sleep consolidation):**-] {+Sleep Consolidation):**+} Full rebuild of the concept index mapping anchor [-vocabulary words-] {+terms+} to pre-ranked memory [-cluster-] {+chunk+} paths. - **Real-time [-phase-] (incremental updates):** O(|V|) per-write update [-that inserts-] {+inserting+} new [-memory-] chunks into relevant anchor clusters [-immediately upon writing.-] {+immediately.+} - **Online [-phase-] (inference):** Detect anchor words in incoming queries; load pre-ranked chunk lists in O(1); re-rank against current query; inject into context.

### 4.1 Overview

[-Version 5.0 adds three new online-phase components: the **Tier 0 Daily Log Hot Cache** (§4.6c), **Structured Query Extraction** (§4.9), and the **Pre-Action Contradiction Gate** (§4.10).-]

### 4.1 Overview

{+The online phase executes before the model's inference pass. By the time the LLM receives the assembled context window, the memory search has already completed programmatically. The model refines and reasons over pre-retrieved chunks — it does not perform the search.+}

### 4.2 Anchor Vocabulary

{+where `engagement(term)` measures the frequency with which the term appears in user-initiated messages (as opposed to system-generated content), weighted by log-scaled conversational turn depth (a term mentioned on turn 8 of a conversation scores higher than one mentioned on turn 1, reflecting sustained topical engagement).+}

### 4.2 Anchor Vocabulary

**User-feedback anchors** — proper nouns introduced by the user — are added to $V_{curated}$ immediately upon detection. The union [-$V = V_{curated} \cup V_{discovered}$-] typically yields [-150-400-] {+150–400+} anchor terms for a mature [-agent-] deployment.

### 4.2 Anchor Vocabulary

**Anchor Vocabulary Lifecycle.** Discovered anchors follow a promotion-and-pruning lifecycle. Anchors whose salience falls below a decay threshold for three consecutive rebuilds are pruned. Anchors [-that maintain-] {+maintaining+} high salience and [-are referenced-] {+appearing+} in user queries are candidates for promotion to $V_{curated}$. Curated anchors are never automatically pruned.

### 4.5 Nightly Sleep Consolidation (Full Rebuild)

The rebuild algorithm: (1) scan all memory sources, chunking long documents into [-256-512-] {+256–512+} token segments; (2) embed all chunks (batch, cached by content hash); (3) build salience-weighted anchor vocabulary; (4) build index using ANN for large corpora, exact KNN for <50k chunks; (5) write atomic JSON artifact. Implementation: `runHippocampusRebuild()` in `src/memory/engram/hippocampus-rebuild.ts` (450 LOC).

### 4.5a Deduplication via Similarity Check

Before storing a new memory chunk into an anchor cluster, [-HIPPOCAMPUS-] {+Instant Recall+} checks cosine similarity against existing chunks to prevent index bloat from daily logs that repeat similar facts. Three thresholds govern the policy:

### 4.5b Real-Time Anchor Discovery

Novel concepts emerging between nightly rebuilds are detected and indexed within [-10-30-] {+10–30+} seconds via a lightweight [-micro-rebuild on-] {+micro-rebuild. A+} new [-anchors exceeding an-] {+anchor is created when its salience score (§4.2) exceeds the+} emergence threshold [-(default: 0.75).-] {+of 0.75 — a normalized value on the [0, 1] salience scale — computed over content ingested since the last nightly build.+}

### 4.6 Two-Tier Memory: Episodic and Semantic

### 4.6 Two-Tier Memory: Episodic and [-Semantic Tiers-] {+Semantic+}

### 4.6 Two-Tier Memory: Episodic and Semantic

**Semantic tier (nightly rebuild).** At 04:15 each night, the full index is rebuilt from [-scratch. The rebuild reflects-] {+scratch, reflecting+} abstracted, consolidated understanding — concepts that have risen to sufficient [-salience,-] {+salience and+} relationships visible across many episodes. Implementation: `EpisodicBuffer` class in `src/memory/engram/hippocampus-enhancement.ts` (468 LOC).

### 4.6 Two-Tier Memory: Episodic and Semantic

[-**The staleness gap is the cost of abstraction.**-] Within a session, retrieval is episodically accurate (same-day freshness). Across sessions, retrieval is semantically rich (nightly consolidation). Both tiers are necessary; neither is sufficient alone.

### 4.6a Importance Scoring

[-HIPPOCAMPUS-] {+Instant Recall+} assigns an **importance score** $\iota(m) \in [1, 10]$ to each memory chunk at write time:

### 4.6a Importance Scoring

Default weights: $w_1 = 3.0$, $w_2 = 3.0$, $w_3 = 2.5$, $w_4 = 1.5$. {+Each component is normalized to [0, 1] before weighting, so the raw weighted sum falls in [0, 10] and is clamped to [1, 10].+} The importance score modulates effective similarity during K-slot ranking:

### 4.6b (Reserved for future use)

[-### 4.6b (Reserved for future use)-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-### 4.6c Daily Log Hot Cache (Tier 0)-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-*(New in v5.0. Addresses CORF Mode 5 — Self-Contradiction Failure.)*-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-**Motivation.** The episodic tier (§4.6) provides <2-minute freshness for memory chunks written via `ON_MEMORY_WRITE()`. However, as demonstrated by the 2026-03-09 production failure, the episodic tier's chunks are still subject to *retrieval query quality* — they are only surfaced if the retrieval query triggers the relevant anchor or FTS match. If the query is generic (e.g., "recent conversation"), a specific daily log entry recording that a meeting was postponed may not be retrieved, even if it was indexed within seconds of being written.-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-The Daily Log Hot Cache resolves this by treating today's daily log not as a *retrievable* resource but as a *guaranteed-loaded* resource — **Tier 0** in the retrieval hierarchy. Tier 0 is unconditional: it is loaded every turn regardless of query content, anchor matches, or retrieval budget allocation.-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-**Definition (Tier 0 — Daily Log Hot Cache).** At the start of each inference turn, the agent loads the current day's daily log file in full and places it at the head of the context window, after the system prompt and persona state but before any HIPPOCAMPUS retrieval results. This placement ensures it is always within the effective attention range.-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-**Formal specification:** $$\text{Tier}_0 = \text{load}(\text{daily\_log}[\text{today}])$$ $$\text{context} = [\text{system\_prompt}, \text{persona\_state}, \text{Tier}_0, \text{HIPPOCAMPUS\_chunks}, \text{user\_message}]$$-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-**Cost analysis.** A typical daily log at the time of a late-afternoon action contains 800–2,000 tokens. At ~$0.003/1K tokens input (Sonnet-class model), this adds $0.0024–$0.006 per turn. For a personal assistant executing 30–50 write-class actions per day, the incremental daily cost is approximately $0.07–$0.30. This is considered negligible relative to the risk cost of SCF (incorrect calendar actions, wrong task states, contradicted user preferences).-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-**SCF coverage.** Tier 0 guarantees that any state change recorded in the current day's daily log is in context for every subsequent action that day. This directly eliminates Mode 5 SCF for same-day contradictions, which constitute approximately 70% of observed SCF instances in the deployment log. The remaining ~30% involve state recorded in previous days' logs; these are addressed by the Pre-Action Contradiction Gate (§4.10).-]

### 4.6c Daily Log Hot Cache (Tier 0)

[-**Implementation note.** The Tier 0 file path follows the convention `memory/YYYY-MM-DD.md`. If no daily log exists for today (e.g., first turn of the day), Tier 0 is empty (zero tokens). The system must not fail if the file is absent. Planned implementation: `loadTier0DailyLog()` in `src/memory/engram/hippocampus-tier0.ts` (estimated 80–120 LOC).-]

### 4.7 Inference-Time Lookup with Post-Retrieval Re-ranking

[-Inference-time retrieval: (1) anchor detection (exact + stemmed + phrase match); (2) semantic anchor expansion over index vocabulary; (3) O(1) index lookup — no search; (4) post-retrieval re-ranking blending anchor relevance (0.6) and query relevance (0.4); (5) chunk content loading.-]

### 4.7 Inference-Time Lookup with Post-Retrieval Re-ranking

{+Inference-time retrieval proceeds in five steps: (1) **anchor detection** — each token in the query is matched against $V$ via exact match, stemmed match, and bigram/trigram phrase match; all matching anchors form the active set $A$; (2) **semantic anchor expansion** — the query embedding is compared against all anchor embeddings in $V$, and any anchor within cosine distance 0.3 of the query is added to $A$; (3) **O(1) index lookup** — for each $a \in A$, retrieve the pre-computed top-K chunk list; (4) **post-retrieval re-ranking** — score each candidate chunk by blending anchor relevance (weight 0.6) and query-specific cosine similarity (weight 0.4); (5) **chunk content loading** — top chunks after re-ranking are loaded from disk.+}

### 4.7 Inference-Time Lookup with Post-Retrieval Re-ranking

The re-ranking step [-(Step 4)-] discards false positives — chunks [-that match-] {+matching+} the anchor word but [-are-] semantically unrelated to the specific query — without [-requiring-] an additional retrieval pass. The candidate set is small (K×|A| ≤ 100 chunks), making [-this-] re-ranking fast (~10ms). Implementation: `registerHippocampusHook()` in `src/plugins/hippocampus-hook.ts` (131 LOC).

### 4.8 Full Inference Pipeline Integration

[-*(Updated in v5.0 to include Tier 0, Structured Query Extraction, and Pre-Action Contradiction Gate.)*-]

### 4.8 Full Inference Pipeline Integration

[-```python-] {+```+} INFERENCE_PIPELINE(user_message, [-agent_config, action_class):-] {+agent_config):+} # Layer 0: Always-loaded context (O(1), ~500 tokens) base_context = load(agent_config.persona_state) # [-CORTEX-] {+Identity Persistence+} project_index = load("memory/projects-master.md")

### Layer 0b: Tier 0 — Daily Log Hot Cache (NEW in v5.0) # Always loaded, unconditional, ~1-2K tokens tier0 = load_tier0_daily_log(today()) # see §4.6c

[-# Layer 0b: Tier 0 — Daily Log Hot Cache (NEW in v5.0) # Always loaded, unconditional, ~1-2K tokens tier0 = load_tier0_daily_log(today()) # see §4.6c-]

### Layer 1a: Structured Query Extraction (NEW in v5.0) # Extract named entities from user message; build per-entity FTS queries entities = EXTRACT_ENTITIES(user_message) # see §4.9 entity_chunks = [] for entity in entities: fts_results = FTS5_SEARCH(entity, corpus) entity_chunks.extend(fts_results) entity_chunks = MMR_DEDUP(entity_chunks)

[-# Layer 1a: Structured Query Extraction (NEW in v5.0) # Extract named entities from user message; build per-entity FTS queries entities = EXTRACT_ENTITIES(user_message) # see §4.9 entity_chunks = [] for entity in entities: fts_results = FTS5_SEARCH(entity, corpus) entity_chunks.extend(fts_results) entity_chunks = MMR_DEDUP(entity_chunks)-]

### Layer 1: Instant Recall lookup + re-rank (O(|A|) + O(K×|A|), ~50ms) instant_recall_index = load_cached("memory/hippocampus-index.json") memory_chunks = INSTANT_RECALL_LOOKUP(user_message, instant_recall_index)

# Layer [-1b: HIPPOCAMPUS-] {+1: Instant Recall+} lookup + re-rank (O(|A|) + O(K×|A|), ~50ms) [-hippocampus_index-] {+instant_recall_index+} = load_cached("memory/hippocampus-index.json") memory_chunks = [-HIPPOCAMPUS_LOOKUP(user_message, hippocampus_index)-] {+INSTANT_RECALL_LOOKUP(user_message, instant_recall_index)+}

### Merge entity-specific chunks with anchor-based chunks (MMR dedup) all_chunks = MMR_DEDUP(entity_chunks + memory_chunks)

[-# Merge entity-specific chunks with anchor-based chunks (MMR dedup) all_chunks = MMR_DEDUP(entity_chunks + memory_chunks)-]

### Layer 1c: Pre-Action Contradiction Gate (NEW in v5.0) # Only fires on write-class actions; zero cost on read-only queries if action_class == WRITE: contradiction = CHECK_CONTRADICTION(entities, all_chunks, tier0) if contradiction: return SURFACE_CONTRADICTION(contradiction) # halt action; ask user

[-# Layer 1c: Pre-Action Contradiction Gate (NEW in v5.0) # Only fires on write-class actions; zero cost on read-only queries if action_class == WRITE: contradiction = CHECK_CONTRADICTION(entities, all_chunks, tier0) if contradiction: return SURFACE_CONTRADICTION(contradiction) # halt action; ask user-]

### Layer 2: Assemble context window context = [base_context, project_index, *memory_chunks, user_message]

# Layer 2: Assemble context window context = [base_context, project_index, [-tier0, *all_chunks,-] {+*memory_chunks,+} user_message]

### Layer 3: Total Recall compaction if budget exceeded if token_count(context) > CONTEXT_BUDGET: context = TOTAL_RECALL_COMPACT(context)

# Layer 3: [-ENGRAM-] {+Total Recall+} compaction if budget exceeded if token_count(context) > CONTEXT_BUDGET: context = [-ENGRAM_COMPACT(context)-] {+TOTAL_RECALL_COMPACT(context)+}

### Layer 3: ENGRAM compaction if budget exceeded if token_count(context) > CONTEXT_BUDGET: context = ENGRAM_COMPACT(context)

[-**Pipeline overhead analysis.** The v5.0 additions add the following overhead relative to v4.0:-]

### Layer 3: ENGRAM compaction if budget exceeded if token_count(context) > CONTEXT_BUDGET: context = ENGRAM_COMPACT(context)

[-| Component | Overhead | Condition | |---|---|---| | Tier 0 load | ~5ms file I/O + 1-2K tokens | Every turn | | Entity extraction (regex) | ~1ms | Every turn | | Entity extraction (LLM, Flash/Haiku) | ~200-500ms, ~300 tokens | Ambiguous cases only (~20% of turns) | | Per-entity FTS queries | ~10ms × E (E=1-5 typical) | Every turn | | MMR deduplication | ~5ms | Every turn | | Contradiction gate search | ~20-50ms | Write-class actions only |-]

### Layer 3: ENGRAM compaction if budget exceeded if token_count(context) > CONTEXT_BUDGET: context = ENGRAM_COMPACT(context)

[-Total expected overhead on a write-class turn with entity extraction: ~80–150ms additional latency. Read-only turns with clear entity signals (regex-only extraction): ~25ms. This is acceptable given the latency budget and the severity of SCF.-]

### 4.9 Structured Query Extraction

[-### 4.9 Structured Query Extraction-]

### 4.9 Structured Query Extraction

[-*(New in v5.0. Addresses CORF Mode 5 — Self-Contradiction Failure, and improves Mode 4 — Anchor Silence.)*-]

### 4.9 Structured Query Extraction

[-**Motivation.** The 2026-03-09 production failure illustrates a fundamental weakness of generic FTS queries: a search for "recent conversation" does not know that the user message is about a specific meeting with a specific name on a specific date. The HIPPOCAMPUS anchor mechanism helps with named entities that appear in the anchor vocabulary, but the anchor vocabulary is built offline and may not contain transient proper nouns (a specific meeting name, a client's name mentioned for the first time). Structured Query Extraction bridges this gap by extracting entities from the *live* user message and issuing per-entity FTS queries in addition to anchor-based lookups.-]

### 4.9 Structured Query Extraction

[-**Definition (Structured Query Extraction).** Let $u$ be the user message and let $E(u) = \{e_1, e_2, \ldots, e_k\}$ be the set of named entities extracted from $u$. For each entity $e_i$, a separate FTS5 query is issued against the memory corpus:-]

### 4.9 Structured Query Extraction

[-$$\text{FTS}_i = \text{FTS5\_SEARCH}(e_i, M)$$-]

### 4.9 Structured Query Extraction

[-Results across all entities are merged and deduplicated using Maximal Marginal Relevance:-]

### 4.9 Structured Query Extraction

[-$$\text{SQE\_results}(u) = \text{MMR\_DEDUP}\left(\bigcup_{i=1}^{k} \text{FTS}_i\right)$$-]

### 4.9 Structured Query Extraction

[-**Entity extraction strategy.** A two-tier extraction approach balances cost and coverage:-]

### 4.9 Structured Query Extraction

[-*Tier A — Regex extraction (O(|u|), ~1ms):* Pattern-matched extraction for high-confidence entity categories: - **Named meetings/events:** Patterns like `/\b(?:meeting|call|session|standup|review)\s+(?:with\s+)?[A-Z][a-z]+/g`, calendar-style date expressions, meeting IDs. - **Person names:** Capitalized bigrams not at sentence start, titles (Dr., Mr., Ms.) followed by name. - **Project names:** Known project vocabulary from `memory/projects-master.md`, code repository names. - **Dates and time expressions:** ISO dates, weekday references, relative expressions ("tomorrow", "next Friday", "this afternoon").-]

### 4.9 Structured Query Extraction

[-*Tier B — LLM extraction (cheap model: Flash/Haiku, ~200–500 tokens, ~200–500ms):* Triggered for messages where Tier A yields zero entities or where the message contains ambiguous referring expressions likely to encode entities. The prompt is minimal:-]

### 4.9 Structured Query Extraction

[-``` Extract named entities (people, meetings, projects, dates) from: "<user_message>" Return JSON: {"entities": ["entity1", "entity2", ...]} ```-]

### 4.9 Structured Query Extraction

[-Tier B fires for approximately 20% of turns in the deployment profile. Its output is merged with Tier A results.-]

### 4.9 Structured Query Extraction

[-**Complexity.** Structured Query Extraction adds $O(E)$ FTS5 queries where $E = |E(u)|$ (typically 1–5 entities per message). Each FTS5 query on the 878K-event corpus takes approximately 8–15ms. Total SQE cost: 10–75ms for the FTS pass, plus 1ms (Tier A) or ~300ms (Tier B, conditional).-]

### 4.9 Structured Query Extraction

[-**MMR deduplication.** The union of per-entity FTS results frequently contains overlapping chunks (the same memory chunk may be retrieved by multiple entity queries). Maximal Marginal Relevance [Carbonell & Goldstein, 1998] selects chunks that are both relevant and mutually diverse:-]

### 4.9 Structured Query Extraction

[-$$\text{MMR}(C_i) = \arg\max_{c_j \in R \setminus S} \left[ \lambda \cdot \text{sim}(c_j, q) - (1-\lambda) \cdot \max_{c_i \in S} \text{sim}(c_j, c_i) \right]$$-]

### 4.9 Structured Query Extraction

[-where $R$ is the set of retrieved chunks, $S$ is the selected set so far, $q$ is the query, and $\lambda = 0.7$ (default). MMR is computed over the merged HIPPOCAMPUS + SQE candidate set.-]

### 4.9 Structured Query Extraction

[-**Interaction with daily log.** When SQE extracts a meeting entity and issues an FTS query, it will naturally retrieve any chunk in the corpus that mentions that meeting — including today's daily log entry recording that the meeting was postponed, if that entry was written before the current turn. This provides a second retrieval path to SCF-relevant content, complementary to the Tier 0 Hot Cache. The Tier 0 approach is unconditional (guaranteed retrieval of the full daily log); SQE is entity-targeted (precise retrieval of the specific entry). Together they provide defense-in-depth against SCF.-]

### 4.9 Structured Query Extraction

[-**Planned implementation:** `extractEntities()`, `structuredQueryExpansion()`, `mmbMerge()` in `src/memory/engram/hippocampus-sqe.ts` (estimated 200–280 LOC).-]

### 4.10 Pre-Action Contradiction Gate

[-### 4.10 Pre-Action Contradiction Gate-]

### 4.10 Pre-Action Contradiction Gate

[-*(New in v5.0. Addresses CORF Mode 5 — Self-Contradiction Failure on write-class actions.)*-]

### 4.10 Pre-Action Contradiction Gate

[-**Motivation.** Even with Tier 0 Hot Cache and SQE in place, there exists a residual SCF risk: the agent may correctly retrieve a prior state record but still proceed to take a contradicting action if the LLM reasoning does not attend to the contradiction. The Pre-Action Contradiction Gate makes contradiction detection explicit and mandatory before any write-class action is executed. It is analogous to a pre-commit hook in version control — it does not prevent the action, but it forces explicit acknowledgement of any contradiction before proceeding.-]

### 4.10 Pre-Action Contradiction Gate

[-**Definition (Pre-Action Contradiction Gate).** A write-class action $a$ targeting entities $E_a$ is subject to a contradiction check before execution:-]

### 4.10 Pre-Action Contradiction Gate

[-$$\text{GATE}(a) = \exists m \in \text{SEARCH}(E_a, M \cup \text{Tier}_0) : \text{CONTRADICTS}(m, a)$$-]

### 4.10 Pre-Action Contradiction Gate

[-where $\text{SEARCH}(E_a, \cdot)$ retrieves chunks mentioning any entity in $E_a$, and $\text{CONTRADICTS}(m, a)$ evaluates whether the state described in $m$ is inconsistent with the state implied by $a$.-]

### 4.10 Pre-Action Contradiction Gate

[-**Write-class actions.** The gate fires on actions that change external or internal state: - Calendar operations: `create_event`, `update_event`, `delete_event`, `decline_invite` - Task management: `create_task`, `complete_task`, `reopen_task`, `assign_task` - Email: `send_email`, `schedule_send` - Memory writes: `write_memory`, `append_daily_log` - Preference changes: `set_preference`, `update_config`-]

### 4.10 Pre-Action Contradiction Gate

[-Read-only operations (search, read, list, summarize) are excluded. In the deployment profile, write-class actions constitute approximately 18% of all turns. The gate overhead (~20–50ms) is acceptable for this subset.-]

### 4.10 Pre-Action Contradiction Gate

[-**Contradiction detection.** State contradiction is defined via a lightweight classifier operating on the action's target state and retrieved memory chunks. Contradiction patterns include:-]

### 4.10 Pre-Action Contradiction Gate

[-| Pattern | Example | |---|---| | Scheduled vs. postponed | Creating calendar event for a meeting recorded as "postponed" | | Done vs. active | Re-adding a task recorded as "completed" | | Accepted vs. declined | Sending acceptance for an event recorded as "I declined" | | Old preference vs. new | Applying font size "medium" after log entry "user changed font size to large" |-]

### 4.10 Pre-Action Contradiction Gate

[-The classifier is implemented as a structured prompt to a cheap model (Flash/Haiku, ~300 tokens), or as a rule-based state machine for high-confidence patterns (e.g., the word "postponed" appearing in the same sentence as the meeting entity in a daily log chunk, combined with a `create_event` action for that meeting).-]

### 4.10 Pre-Action Contradiction Gate

[-**Gate output.** When `GATE(a) = True`, the action is suspended and the contradiction is surfaced to the agent for explicit resolution before proceeding:-]

### 4.10 Pre-Action Contradiction Gate

[-``` [CONTRADICTION GATE] Before creating this calendar event: Action: Create "Q2 planning meeting" on March 12 Memory (09:14 today): "Q2 planning meeting postponed — a key participant unavailable, rescheduling to week of March 18" Resolve: Proceed anyway? Cancel? Reschedule to March 18? ```-]

### 4.10 Pre-Action Contradiction Gate

[-The agent then resolves the contradiction — either abandoning the action, modifying it, or confirming an override — before the tool call is executed.-]

### 4.10 Pre-Action Contradiction Gate

[-**SCF reduction estimate.** The combination of Tier 0 Hot Cache + Structured Query Extraction + Pre-Action Contradiction Gate is projected to reduce SCF from ~15% of write-class actions to near-zero. Quantitatively: Tier 0 addresses same-day contradictions (~70% of SCF); SQE retrieves entity-specific prior-day notes reducing the residual (~20% of SCF); the Contradiction Gate provides a final safety net for any remaining cases (~10% of SCF) that reach the write-action stage. These projections are theoretical; empirical validation is planned for Q2 2026.-]

### 4.10 Pre-Action Contradiction Gate

[-**Planned implementation:** `contradictionGate()`, `detectContradiction()`, `surfaceContradiction()` in `src/memory/engram/hippocampus-gate.ts` (estimated 180–240 LOC).-]

### 5. Theoretical Analysis

## 5. Theoretical [-Analysis and Empirical Validation-] {+Analysis+}

### 5.0 Empirical Validation of Core Claims

[-### 5.0 Empirical Validation of Core Claims-]

### 5.0 Empirical Validation of Core Claims

[-| System | CORF-Recall@20 | Latency (p95, ms) | FPR | Index Build | |---|---|---|---|---| | No Retrieval (NR) | 0.12 | <1 | - | - | | Single-Source RAG (SS-RAG) | 0.51 | 178 | 0.28 | - | | All-Sources ANN (AS-ANN) | 0.76 | 94 | 0.31 | 45s | | MemGPT-style Sequential (MG-REC) | 0.79 | 320 | 0.19 | - | | **HIPPOCAMPUS** | **0.85** | **54** | **0.18** | **12s** | | **HIPPOCAMPUS + SCF Mitigations** *(projected)* | **~0.93** | **~130*** | **~0.16** | **12s** |-]

### 5.0 Empirical Validation of Core Claims

[-*\*Latency projection for write-class actions with entity LLM extraction (Tier B, 20% of turns) + contradiction gate. Read-only turns: ~80ms projected. All HIPPOCAMPUS+SCF figures are theoretical projections, not yet empirically validated. Empirical validation planned Q2 2026.*-]

### 5.0 Empirical Validation of Core Claims

[-**Key Findings:** - **vs. MemGPT:** 6-point recall advantage (0.85 vs 0.79) with 5.9× latency speedup (54ms vs 320ms). - **vs. All-Sources ANN:** 9-point recall advantage validates concept anchoring beyond multi-source coverage. - **vs. Single-Source RAG:** 34-point improvement validates the source-coverage observation. - **Build Cost:** 12s for HIPPOCAMPUS vs 45s for AS-ANN. - **SCF mitigations (projected):** Additional ~8 recall points from Mode 5 coverage; modest FPR improvement from MMR deduplication of SQE results; latency increase acceptable within write-action latency budget.-]

### 5.1 Amortized Complexity Analysis

| Method | Per-query inference cost | Build cost | [-|---|---|---|-] {+| -------------------------------------------- | ------------------------ | ---------- | --- | --- | ---- | --- | --- | --- | --- | ----------- |+} | Single-source exact KNN | O(n) | [---] {+—+} | | Single-source ANN (FAISS) | O(log n) | O(n log n) | | [-HIPPOCAMPUS-] {+Instant Recall+} (+ semantic anchor expansion) | [-O(|V|-] {+O( | V |+} + [-|A|-] {+| A |+} + [-K·|A|)-] {+K·+} | [-O(|V|·n) offline-] {+A+} | {+)+} | [-HIPPOCAMPUS + SQE-] {+O(+} | [-O(|V| + |A| + K·|A| + E·|FTS|)-] {+V+} | [-O(|V|·n)-] {+·n)+} offline |

### 5.1 Amortized Complexity Analysis

[-For $n=50{,}000$, $|V|=300$, $|A|=3$, $K=20$, $E=3$, $|FTS|=10$: HIPPOCAMPUS+SQE inference cost = O(63 + 30) = O(93) operations, vs. O(50,000) for exact KNN. The FTS pass scales with corpus size but FTS5 is empirically O(log n) for typical query selectivity. The nightly build cost O(15M) is paid once offline.-]

### 5.1 Amortized Complexity Analysis

{+For $n=50{,}000$, $|V|=300$, $|A|=3$, $K=20$: Instant Recall inference evaluates ~363 operations (300 anchor comparisons + 3 lookups + 60 re-rank comparisons), independent of corpus size $n$. By contrast, exact KNN scales as O(n) = 50,000 comparisons per query. The nightly build cost O(|V|·n) ≈ 15M operations is amortized across all queries until the next rebuild.+}

### 5.2 Recognition vs. Recall

Current RAG systems implement recall: given a query, the system generates the retrieval path. [-HIPPOCAMPUS-] {+Instant Recall+} implements recognition: given an anchor word, the system activates the pre-existing index entry. The re-ranking step adds a lightweight query-specific discriminator within the already-small candidate set — analogous to the "familiarity signal" in dual-process recognition theory [Yonelinas, 2002].

### 5.2 Recognition vs. Recall

[-SQE adds a third mode: **targeted recall**. Per-entity FTS queries are not anchor-based (recognition) nor free-form (recall) — they are entity-pinned: the system knows *exactly* what it is looking for (the specific meeting name, the specific person) and retrieves all mentions of that entity across the corpus. This targeted recall mode is particularly effective for SCF because the entity in the pending action is precisely the entity whose prior state must be verified.-]

### 6.1 Alternative 1: Inverted Index (Classical IR) Fails to capture synonymy and paraphrase. Preferred on edge devices where compute is constrained.

[-### 6.1 Alternative 1: Inverted Index (Classical IR) Fails to capture synonymy and paraphrase. Preferred on edge devices where compute is constrained.-]

### 6.1 Alternative 1: Inverted Index (Classical IR)

{+### 6.1 Alternative 1: Inverted Index (Classical IR)+}

### 6.1 Alternative 1: Inverted Index (Classical IR)

{+Captures exact term matches but fails on synonymy and paraphrase. Preferred on edge devices where embedding compute is too expensive.+}

### 6.2 Alternative 2: All-Sources ANN

{+### 6.2 Alternative 2: All-Sources ANN+}

### 6.2 Alternative 2: All-Sources ANN

[-### 6.2 Alternative 2: All-Sources ANN-] Fixes Source Blindness {+by searching across all memory sources,+} but still requires a [-good-] {+well-formed+} query — Pronoun Blindness and Anchor Silence [-are not addressed. This is the **key discriminating baseline** in our evaluation: the-] {+remain unaddressed. The+} 9-point gap between AS-ANN (0.76) and [-HIPPOCAMPUS-] {+Instant Recall+} (0.85) {+in §7+} isolates the benefit of concept-anchored clustering. [-ANN-] {+AS-ANN+} also [-does not address SCF, as the generic query embedding is not entity-targeted.-] {+runs at inference time, adding latency.+}

### 6.3 Alternative 3: Knowledge Graph Overlay Preferred when relationship type between concepts matters. A natural HIPPOCAMPUS extension for structured domains (future work, §8.6). A knowledge graph over agent state transitions (e.g., meeting-status edges: scheduled → postponed → rescheduled) could provide a structured complement to the Contradiction Gate's pattern matching.

[-### 6.3 Alternative 3: Knowledge Graph Overlay Preferred when relationship type between concepts matters. A natural HIPPOCAMPUS extension for structured domains (future work, §8.6). A knowledge graph over agent state transitions (e.g., meeting-status edges: scheduled → postponed → rescheduled) could provide a structured complement to the Contradiction Gate's pattern matching.-]

### 6.3 Alternative 3: Multi-Source RAG (MS-RAG)

{+### 6.3 Alternative 3: Multi-Source RAG (MS-RAG)+}

### 6.3 Alternative 3: Multi-Source RAG (MS-RAG)

{+MS-RAG queries all memory sources at inference time with full embedding search, achieving high recall (0.87 in our evaluation). However, it incurs 418ms p95 latency — 7.7× slower than Instant Recall — because it performs exhaustive embedding comparison across all sources at every query. Instant Recall trades 2 percentage points of recall for an order-of-magnitude latency reduction, and the gap narrows further with anchor vocabulary tuning.+}

### 6.4 Alternative 4: Knowledge Graph Overlay

{+### 6.4 Alternative 4: Knowledge Graph Overlay+}

### 6.4 Alternative 4: Knowledge Graph Overlay

{+Preferred when relationship types between concepts matter (e.g., causal chains, temporal ordering). A natural Instant Recall extension for structured domains (future work, §8.6).+}

### 6.5 Alternative 5: Hosted Vector Databases (Pinecone, Weaviate)

### [-6.4-] {+6.5+} Alternative [-4:-] {+5: Hosted+} Vector Databases (Pinecone, Weaviate)

### 6.5 Alternative 5: Hosted Vector Databases (Pinecone, Weaviate)

| Dimension | [-GravityClaw / Pinecone-] {+Hosted Vector DB+} | [-HIPPOCAMPUS-] {+Instant Recall+} | [-|---|---|---|-] {+| ------------------- | ------------------------------------------ | -------------------------------------- |+} | **Retrieval model** | Flat similarity search (O(log n) via HNSW) | Pre-computed anchor→chunk cache (O(1)) | | **Cost** | $8+/month [-(starter)-] {+(starter tier)+} | Zero ongoing cost (local compute) | | **Privacy** | Embeddings sent to cloud | All data remains local | | **Latency** | ~50–200ms (network round-trip) | [-~54ms-] {+~50ms+} (local, no network) |

### 6.5 Alternative 5: Hosted Vector Databases (Pinecone, Weaviate)

Vector databases are preferred for large-scale deployments (n > 100k chunks) or when query-time semantic flexibility is [-critical. Neither vector databases nor standard ANN approaches include a Tier 0 Hot Cache or a Pre-Action Contradiction Gate; these are HIPPOCAMPUS-specific SCF mitigations.-] {+critical.+}

### 7.4 Empirical Results (Deployment Validation)

[-### 7.4 Empirical Results (Deployment Validation)-]

### 7.1 Evaluation Protocol

{+### 7.1 Evaluation Protocol+}

### 7.1 Evaluation Protocol

**Test Setup:** Evaluated on a real personal assistant deployment with 47,392 memory chunks across memory/ (52%), archive/chatgpt-import/ (28%), emails/ (15%), other (5%). Test set: 612 queries annotated with ground-truth target [-chunks.-] {+chunks by two independent annotators (Cohen's κ = 0.87).+}

### 7.1 Evaluation Protocol

{+**Baselines:**+}

### 7.1 Evaluation Protocol

{+- **NR (No Retrieval):** No memory retrieval; model sees only base context. - **SS-RAG (Single-Source RAG):** Standard RAG over the primary memory directory only. - **AS-ANN (All-Sources ANN):** ANN search across all memory sources at inference time. - **MS-RAG (Multi-Source RAG):** Full embedding search across all sources at inference time — the highest-recall but highest-latency baseline. - **MG-REC (MemGPT-style Sequential):** Sequential multi-step retrieval with virtual context paging [Packer et al., 2023].+}

### 7.2 Results

{+### 7.2 Results+}

### 7.2 Results

| Metric | NR | SS-RAG | AS-ANN | {+MG-REC |+} MS-RAG | [-HIPPOCAMPUS-] {+Instant Recall+} | [-HIPP+SCF *(proj.)*-] | [-|---|---|---|---|---|---|---|-] {+--------------------------- | ---- | ------ | ------ | ------ | -------- | -------------- |+} | CORF-Recall@20 | 0.12 | 0.51 | 0.76 | [-0.87-] {+0.79 | **0.87**+} | 0.85 [-| ~0.93-] | | Source Coverage Rate | 0.25 | 0.33 | 1.00 | 1.00 | 1.00 | 1.00 | | [-SCF Rate (write-class) | ~15%* | ~15%* | ~15%* | ~12%* | ~15%* | **~0%** *(proj.)* | |-] Inference Latency (p95, ms) | <1 | 178 | 94 | {+320 |+} 418 | [-54 | ~130 (write)-] {+**54**+} | | FPR (post-rerank) | [---] {+—+} | 0.28 | 0.31 | {+0.19 |+} 0.22 | [-0.18 | ~0.16 *(proj.)*-] {+**0.18**+} | | Index Build Time | [---] {+—+} | [---] {+—+} | 45s | [---] {+—+} | [-12s-] {+—+} | 12s | | Same-Day Index Freshness | [---] {+—+} | [---] {+—+} | 24h | [---] {+—+} | [-<2min-] {+—+} | <2min |

### 7.4 Empirical Results (Deployment Validation)

[-*\*SCF Rate for NR/SS-RAG/AS-ANN/HIPPOCAMPUS estimated from the same deployment log analysis; these systems have no SCF-specific mitigation. HIPPOCAMPUS+SCF projected figures are theoretical; empirical validation planned Q2 2026.*-]

### 7.4 Empirical Results (Deployment Validation)

[-**Ablations:**-]

### 7.2 Results

{+**Key findings:**+}

### 7.2 Results

{+- **Recall–latency tradeoff.** MS-RAG achieves the highest recall (0.87) but at 418ms — 7.7× slower than Instant Recall. For personal assistant workloads where sub-100ms retrieval is required for responsive interaction, Instant Recall's 0.85 recall at 54ms represents a favorable operating point on the Pareto frontier. - **Concept anchoring value.** The 9-point gap between AS-ANN (0.76) and Instant Recall (0.85) isolates the benefit of pre-computed concept clustering beyond source coverage. - **False positive control.** Post-retrieval re-ranking gives Instant Recall the lowest FPR (0.18) of any method achieving >0.75 recall. - **MS-RAG ceiling.** MS-RAG's 2-point recall advantage over Instant Recall comes entirely from queries where no anchor term matches the relevant concept — a limitation addressable through vocabulary expansion rather than architectural change.+}

### 7.3 Ablations

{+### 7.3 Ablations+}

### 7.3 Ablations

| Variant | CORF-Recall@20 | Latency (p95, ms) | FPR | [-|---|---:|---:|---:|-] {+| ----------------------------------------- | -------------: | ----------------: | ---: | | Full Instant Recall | 0.85 | 54 | 0.18 |+} | A1 [-- HIPPOCAMPUS-] {+—+} w/o pronoun expansion | 0.79 | 52 | 0.19 | | A2 [-- HIPPOCAMPUS-] {+—+} w/o post-retrieval re-ranking | 0.85 | 41 | 0.35 | | A3 [-- HIPPOCAMPUS-] {+—+} nightly-only [-(disable-] {+(no+} real-time [-episodic updates)-] {+episodic)+} | 0.82 | 54 | 0.18 [-| | A4 - HIPPOCAMPUS+SCF w/o Tier 0 (projected) | ~0.89 | ~120 | ~0.16 | | A5 - HIPPOCAMPUS+SCF w/o Contradiction Gate (projected) | ~0.91 | ~90 | ~0.16-] |

### 7.4 Empirical Results (Deployment Validation)

[-**Statistical Significance:** Inter-annotator agreement (Cohen's κ): 0.87. Confidence intervals at 95%: CORF-Recall [0.81, 0.89], Latency [52, 56ms]. Projected HIPPOCAMPUS+SCF figures do not have confidence intervals pending empirical validation.-]

### 7.3 Ablations

{+Pronoun expansion contributes 6 points of recall (Mode 1 mitigation). Re-ranking does not affect recall but nearly halves FPR (0.35 → 0.18). The episodic tier contributes 3 points of recall for within-day queries.+}

### 7.4 Unit Benchmark Validation

### [-7.4a-] {+7.4+} Unit Benchmark [-Validation (Implementation-Level)-] {+Validation+}

### 7.4 Unit Benchmark Validation

**Phase 6.2 [-HIPPOCAMPUS-] {+Instant Recall+} full test suite summary [-(2026-02-24T07:50:00+01:00,-] {+(2026-02-24,+} Vitest v4.0.18):**

### 7.4 Unit Benchmark Validation

| Metric | Value | [-|---|---|-] {+| -------------------------- | -------- |+} | Total tests (src + mirror) | 158 | | Passed | 154 | | Failed | **0** | | Skipped / Todo | 0 / 4 | | Pass rate | **100%** | | Total execution time | 968 ms [-| | Test files | 6 (3 source + 3 mirror)-] |

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-**Per source-file breakdown:**-]

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-| Test file | Tests | Passed | Skipped | Duration (ms) | |---|---|---|---|---| | hippocampus-enhancement.test.ts | 47 | 47 | 0 | 112 | | hippocampus-benchmark.test.ts | 12 | 10 | 2 | 29 | | hippocampus-rebuild.test.ts | 20 | 20 | 0 | 56 | | **Total (source-only)** | **79** | **77** | **2** | **197** |-]

### 7.4 Unit Benchmark Validation

The 4 todo items [-(2 skipped in source × 2 copies)-] correspond to [-the `A1`-] pronoun expansion unit [-tests, which remain-] {+tests (A1),+} pending implementation in the `hippocampus-enhancement` API. All other [-test-] assertions — including A2 importance re-ranking, A3 episodic tier freshness, and [-the-] combined-query deduplication [-check-] — pass at 100%.

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-The three new v5.0 components (Tier 0, SQE, Contradiction Gate) are not yet implemented; their test files are planned as part of Phase 7.0 (see §8a.1 planned files).-]

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-**A2 - Importance Re-ranking Ablation:**-]

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-| Condition | Recall@20 | FPR | Avg Latency (ms) | Queries | |---|---:|---:|---:|---:| | Without re-ranking (flat score) | 1.0000 | 0.75 | 0.130 | 6 | | With importance re-ranking | 1.0000 | 0.75 | 0.088 | 6 |-]

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-Re-ranking preserves recall at 1.0 on the synthetic corpus and reduces latency by 32%. The structural FPR parity between conditions in the synthetic test is expected (small corpus geometry); the deployment evaluation (612 queries, ~47k chunks) is the authoritative FPR benchmark, where re-ranking reduces FPR from 0.35 to 0.18.-]

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-**A3 - Episodic Tier vs. Nightly Rebuild:**-]

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-| Condition | Recall@20 | FPR | Avg Latency (ms) | |---|---:|---:|---:| | Episodic real-time tier | 1.0000 | 0.0000 | 0.097 | | Nightly rebuild (6 small files) | — | — | 13.9 |-]

### 7.4a Unit Benchmark Validation (Implementation-Level)

[-The `A3-freshness` test confirms that a chunk written with timestamp `new Date().toISOString()` is immediately retrievable from the episodic buffer without any rebuild step. The `A3-combined` test confirms correct deduplication of results appearing in both tiers.-]

### 7.5 Threats to Validity

{+### 7.5 Threats to Validity+}

### 7.5 Threats to Validity

{+**Single-deployment evaluation.** All results come from one personal assistant deployment with one user. Interaction patterns, source distributions, and vocabulary characteristics may not generalize to other domains (e.g., enterprise knowledge management, multi-user systems). We mitigate this partially through ablation analysis, which demonstrates that each architectural component contributes independently, but cross-deployment validation remains necessary future work.+}

### 7.5 Threats to Validity

{+**Annotator bias.** Both annotators had familiarity with the system, potentially inflating relevance judgments. The high inter-annotator agreement (κ = 0.87) suggests consistency but does not rule out shared bias.+}

### 7.5 Threats to Validity

{+**Synthetic ablation corpus.** Unit benchmark ablations (§7.4) run on a synthetic corpus that is geometrically simpler than the deployment corpus. Deployment-scale ablation numbers (§7.3) are the authoritative benchmarks.+}

### 8.1 Limitations and Mitigation Strategies

**Semantic ambiguity.** The anchor "paper" could refer to research papers, [-paper-] manuscripts, [-paper material,-] or paper-based workflows. Mitigation: sense-specific sub-clustering via contextual embeddings. Deployment results: FPR drops from 0.18 to 0.14 with sub-clustering.

### 8.1 Limitations and Mitigation Strategies

**K selection.** Fixed K=20 may be too small or too [-large.-] {+large depending on anchor specificity.+} Adaptive K based on score distribution within a cluster reduces context overhead by 15% with no recall loss.

### 8.1 Limitations and Mitigation Strategies

[-**SCF mitigation coverage.** The Tier 0 Hot Cache guarantees retrieval of today's daily log, but does not guarantee the agent will *attend* to a contradiction buried among 2,000 tokens of log content. LLM attention is not uniform across long contexts [Liu et al., 2023]. The Contradiction Gate mitigates this by making contradiction detection explicit and structured rather than relying on the LLM to notice it independently. For very long daily logs (>3,000 tokens), a targeted summary of today's state changes may be preferable to injecting the full log as Tier 0.-]

### 8.1 Limitations and Mitigation Strategies

[-**Entity extraction errors.** Regex-based Tier A extraction may miss entities in informal phrasing or unusual name formats. The LLM Tier B extraction is more robust but adds latency and cost. A calibration study on the deployment corpus is needed to establish the optimal Tier A/B threshold; this is planned for Q2 2026.-]

### 8.1 Limitations and Mitigation Strategies

[-**Contradiction gate false positives.** The gate may surface spurious contradictions — e.g., a chunk mentioning "postponed" in an unrelated context triggering a gate for a different meeting. The entity-pinned retrieval (SQE) mitigates this by only retrieving chunks that mention the *specific* entity being acted upon, but co-occurrence of entity names in unrelated contexts remains a source of false gates. A precision/recall tradeoff study of the gate classifier is planned alongside empirical validation.-]

### 8.2 Large-Scale Deployment (n > 100,000 chunks)

{+### 8.2 Large-Scale Deployment (n > 100,000 chunks)+}

### 8.2 Large-Scale Deployment (n > 100,000 chunks)

{+For n > 100k chunks: (1) replace exact KNN with FAISS IVF at build time; (2) use differential builds (track chunk hashes changed since last build); (3) use disk-backed embedding store (DiskANN/ScaNN); (4) shard by source for parallel builds.+}

### 8.2 Large-Scale Deployment (n > 100,000 chunks)

{+| Corpus Size | Build Time (full) | Index Size | p95 Latency | | --------------------------- | ----------------- | ---------- | ----------- | | 50k (deployed) | 12s | 150KB | 54ms | | 100k (projected, FAISS IVF) | 8min | 500KB | 58ms | | 1M (projected, DiskANN) | 90min | 6.2GB | 62ms† |+}

### 8.2 Large-Scale Deployment (n > 100,000 chunks)

{+†Projected from extrapolation; not empirically validated at this scale.+}

### 8.3 Ethical Considerations

{+### 8.3 Ethical Considerations+}

### 8.3 Ethical Considerations

{+Instant Recall indexes personal interaction history, including potentially sensitive content. The local-first architecture (no cloud embedding storage, no external API calls for retrieval) mitigates data exfiltration risks. However, the index itself — a JSON file mapping anchor terms to memory paths — constitutes a condensed summary of what the agent knows about its user. Deployments should encrypt the index at rest and restrict file-system access. The importance scoring system (§4.6a) introduces implicit content prioritization that could surface sensitive memories preferentially; operators should review weight configurations for their context.+}

### 8a.1 Source Files and Line Counts

The [-HIPPOCAMPUS-] {+Instant Recall+} module is implemented in TypeScript (ESM, Node [-22+). The production implementation comprises the following source files:-] {+22+):+}

### 8a.1 Source Files and Line Counts

| File | LOC | Role | [-Status-] | [-|---|---|---|---|-] {+---------------------------- | ------- | ------------------------------------------------------------------------------------------------- |+} | `hippocampus-enhancement.ts` | 468 | `EpisodicBuffer`, `computeImportance()`, `weightedScore()`, `enhanceIndex()`, deduplication logic | [-✅ Deployed |-] | `hippocampus-rebuild.ts` | 450 | `runHippocampusRebuild()`, `scheduleNightlyRebuild()`, `buildAnchorFromFile()`, mtime-diff state | [-✅ Deployed | | `hippocampus-tier0.ts` | ~100 | `loadTier0DailyLog()` — unconditional daily log loading | 🔲 Planned (v5.0) | | `hippocampus-sqe.ts` | ~240 | `extractEntities()`, `structuredQueryExpansion()`, `mmbMerge()` | 🔲 Planned (v5.0) | | `hippocampus-gate.ts` | ~210 | `contradictionGate()`, `detectContradiction()`, `surfaceContradiction()` | 🔲 Planned (v5.0) |-] | **Subtotal (core)** | [-**~1,468** |-] {+**918**+} | |

### 8a.1 Source Files and Line Counts

| File | LOC | Role | [-Status-] | [-|---|---|---|---|-] {+--------------------- | ------- | --------------------------------------------------------------------------- |+} | `hippocampus-hook.ts` | 131 | `registerHippocampusHook()` — wires [-HIPPOCAMPUS-] {+Instant Recall+} into the [-OpenClaw-] plugin registry [-| ✅ Deployed-] | | **Subtotal (plugin)** | **131** | [-|-] |

### 8a.1 Source Files and Line Counts

| File | LOC | Role | [-Status-] | [-|---|---|---|---|-] {+--------------------------------- | --------- | ---------------------------------------------------------------- |+} | `hippocampus-enhancement.test.ts` | 608 | Unit tests for EpisodicBuffer, importance scoring, deduplication [-| ✅ Deployed-] | | `hippocampus-benchmark.test.ts` | 269 | A2/A3 ablation benchmarks; A1 pronoun expansion (4 todo) | [-✅ Deployed |-] | `hippocampus-rebuild.test.ts` | 360 | Nightly rebuild, mtime-diff, anchor extraction | [-✅ Deployed | | `hippocampus-tier0.test.ts` | ~80 | Tier 0 load, empty-log handling, token count | 🔲 Planned (v5.0) | | `hippocampus-sqe.test.ts` | ~150 | Entity extraction (regex + LLM), FTS5 query generation, MMR dedup | 🔲 Planned (v5.0) | | `hippocampus-gate.test.ts` | ~200 | Contradiction detection, write-class classification, gate output formatting | 🔲 Planned (v5.0) |-] | **Subtotal (tests)** | [-**~1,667** |-] {+**1,237**+} | |

### 8a.1 Source Files and Line Counts

[-**Grand total (deployed): 2,286 LOC across 6 files** **Grand total (planned additions): ~980 LOC across 6 files** **Grand total (all HIPPOCAMPUS files, v5.0 complete): ~3,266 LOC across 12 files**-]

### 8a.2 Key Commits

[-### 8a.2 Key Commits-]

### 8a.2 Key Commits

[-| Commit | Message | |---|---| | `74f9146` | `hippocampus: importance scoring and deduplication` | | `0a27429` | `hippocampus: episodic tier and nightly rebuild` | | `d3e1604` | `feat(hippocampus): add importance scoring, dedup, episodic tier, nightly rebuild` | | `0bdbf9d` | `bench(hippocampus): ablation study and retrieval quality benchmark` | | `bc978c9` | `fix(fork): hippocampus-hook TS2339 — cast registry, dynamic import` | | `c4e1c93` | `fix(hippocampus): use typedHooks.push() instead of non-existent registerHook()` |-]

### 8a.1 Source Files and Line Counts

{+**Grand total: 2,286 LOC** (918 core + 131 plugin + 1,237 tests).+}

### 8a.2 Architecture and Data Flow

### [-8a.3-] {+8a.2+} Architecture and Data Flow

### 8a.2 Architecture and Data Flow

``` [-ENGRAM-] {+Total Recall+} event files (memory/, archive/, emails/) │ ▼ hippocampus-rebuild.ts ├─ collectFiles() ← scans all source directories ├─ buildAnchorFromFile() ← extracts anchor terms per file ├─ reindexPhase() ← builds anchor→chunk KNN index ├─ scheduleNightlyRebuild() ← cron at 04:15; mtime-diff incremental └─ runHippocampusRebuild() ← main entry point

### 8a.2 Architecture and Data Flow

hippocampus-enhancement.ts ├─ EpisodicBuffer ← real-time episodic tier [-(EPISODIC_TTL_MS-] {+(TTL+} = 24h) ├─ computeImportance() ← entity_density + decision_signal + {+│+} engagement + recency ├─ weightedScore() ← [-effective_score =-] cosine × (1 + α·log(ι)) ├─ enhanceIndex() ← applies importance scores to [-serialized-] index └─ deduplicateCluster() ← sim > 0.9: merge; 0.7–0.9: flag; < 0.7: keep

### 8a.3 Architecture and Data Flow

[-[NEW v5.0] hippocampus-tier0.ts └─ loadTier0DailyLog() ← unconditional load of memory/YYYY-MM-DD.md (Tier 0)-]

### 8a.3 Architecture and Data Flow

[-[NEW v5.0] hippocampus-sqe.ts ├─ extractEntities() ← Tier A (regex) + Tier B (LLM) entity extraction ├─ structuredQueryExpansion() ← per-entity FTS5 queries against corpus └─ mmbMerge() ← MMR deduplication across entity + anchor results-]

### 8a.3 Architecture and Data Flow

[-[NEW v5.0] hippocampus-gate.ts ├─ contradictionGate() ← entry point; fires on WRITE-class actions only ├─ detectContradiction() ← entity-state vs. retrieved-memory contradiction check └─ surfaceContradiction() ← structured output to agent for resolution-]

### 8a.2 Architecture and Data Flow

hippocampus-hook.ts └─ registerHippocampusHook() ← [-hippocampusSearch() →-] {+wires into+} plugin registry

### 8a.3 Architecture and Data Flow

[-At inference time (via CORTEX Tier 3): loadTier0DailyLog() → unconditional daily log injection (Tier 0) extractEntities() → per-entity FTS5 queries (SQE) HIPPOCAMPUS_LOOKUP() → anchor detection → O(1) index lookup mmbMerge() → MMR dedup of Tier 0 + SQE + anchor results contradictionGate() → pre-action contradiction check (WRITE only) → post-retrieval re-rank → load chunk content → inject into CORTEX context window ```-]

### 8a.2 Architecture and Data Flow

{+At inference time: INSTANT_RECALL_LOOKUP() → anchor detection → O(1) index lookup → post-retrieval re-rank → load chunks → inject into context window ```+}

### 8a.3 Cross-Module Dependencies

### [-8a.4-] {+8a.3+} Cross-Module Dependencies

### 8a.3 Cross-Module Dependencies

| Dependency | Direction | Interface | [-|---|---|---|-] | [-**ENGRAM**-] {+--------------------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------- | | **Total Recall**+} (Serra, 2026a) | [-HIPPOCAMPUS-] {+Instant Recall+} reads [-ENGRAM-] {+Total Recall+} output | `loadEventsFromFile()` consumes [-ENGRAM-] event files; `eventToChunk()` converts [-events-] to index chunks | | [-**CORTEX**-] {+**Identity Persistence**+} (Serra, 2026b) | [-CORTEX-] {+Identity Persistence+} consumes [-HIPPOCAMPUS-] {+Instant Recall+} | Tier 3 context slots filled by `hippocampusSearch()` [-results; Tier 0 loaded before Tier 3-] {+results+} | | [-**LIMBIC**-] {+**Humor Embeddings**+} (Serra, 2026d) | [-LIMBIC-] {+Humor Embeddings+} reads [-HIPPOCAMPUS-] {+Instant Recall+} | Humor-relevant anchor clusters loaded during bridge discovery | | [-**SYNAPSE**-] {+**Round Table**+} (Serra, 2026e) | Orchestration | Coordinates `scheduleNightlyRebuild()` timing across modules |

### 8.3 Large-Scale Deployment (n > 100,000 chunks)

[-### 8.3 Large-Scale Deployment (n > 100,000 chunks)-]

### 8.3 Large-Scale Deployment (n > 100,000 chunks)

[-For n > 100k chunks: (1) replace exact KNN with FAISS IVF at build time; (2) use differential builds (track chunk hashes changed since last build); (3) use disk-backed embedding store (DiskANN/ScaNN); (4) shard by source for parallel builds.-]

### 8.3 Large-Scale Deployment (n > 100,000 chunks)

[-| Corpus Size | Build Time (full) | Index Size | p95 Latency | |---|---|---|---| | 50k (deployed) | 12s | 150KB | 54ms | | 100k (FAISS IVF) | 8min | 500KB | 58ms | | 1M (DiskANN) | 90min | 6.2GB | 62ms* |-]

### 8.3 Large-Scale Deployment (n > 100,000 chunks)

[-The SQE FTS5 pass scales with corpus size. At 878K events (current production corpus), each FTS5 query takes approximately 10–15ms. At 1M events, FTS5 with a selective entity query is expected to remain under 25ms per query. Tier 0 load time is independent of corpus size (single file, O(1) I/O).-]

### 9. Conclusion

[-We have presented HIPPOCAMPUS, a pre-computed concept index that addresses Contextual Ownership Retrieval Failure in persistent AI agents by moving the computational cost of memory retrieval from inference time to build time. The architecture draws on the neuroscientific insight that the biological hippocampus is an *indexing* structure — and that this separation between storage and indexing is the key to fast, reliable episodic recall.-]

### 9. Conclusion

[-Version 5.0 extends HIPPOCAMPUS with three architectural components motivated by a real production failure discovered on 2026-03-09. The failure — an agent contradicting its own same-day daily log entry despite operating with a 16K-character retrieval pack — defined a fifth CORF mode: **Self-Contradiction Failure (SCF)**. SCF is not a source-coverage problem or a query-quality problem in the conventional sense; it is a *retrieval strategy* problem. A retrieval system that issues generic queries will miss entity-specific self-authored notes even when those notes are indexed and recent.-]

### 9. Conclusion

[-The three new components address SCF at three levels of the inference pipeline: **Tier 0 Hot Cache** (unconditional inclusion of today's daily log in every turn's context), **Structured Query Extraction** (entity-aware FTS queries that precisely target the entities relevant to the current turn), and the **Pre-Action Contradiction Gate** (explicit contradiction detection before write-class actions execute, analogous to a pre-commit hook). Together, these components are projected to reduce SCF from ~15% of write-class actions to near-zero.-]

### 9. Conclusion

[-HIPPOCAMPUS addresses all five CORF failure modes. The source-coverage observation establishes that parallel source coverage is the binding constraint on retrieval completeness — not query quality — for Modes 1–4. Real-time incremental updating ensures same-day freshness. Post-retrieval re-ranking approximates pattern separation and reduces false positive injection. The SCF mitigation architecture adds entity-awareness and action-time safety checks that transform the retrieval pipeline from passive to active.-]

### 9. Conclusion

[-The production TypeScript implementation (§8a) — 6 source files deployed (2,286 LOC, 100% test pass rate across 158 tests) plus 6 planned source files (~980 LOC) for the v5.0 components — confirms that the theoretical architecture translates cleanly to deployable code. HIPPOCAMPUS is the indexing layer in the ENGRAM → HIPPOCAMPUS → CORTEX cognitive stack, ensuring that CORTEX's identity invariants are supported by fast, reliable, cross-source memory access with explicit self-consistency guarantees.-]

### 9. Conclusion

[-HIPPOCAMPUS transforms agent memory from a search problem into a recognition problem. The SCF mitigations transform write-class actions from contradiction-prone operations into explicitly verified state transitions. The agent stops asking "what papers are you referring to?" — because the answer was already in context before the question was asked. And it stops flagging meetings as conflicted — because it checked its own notes before touching the calendar.-]

### 9. Conclusion

{+This paper introduced CORF as a formal framework for diagnosing retrieval failures in persistent agents and demonstrated that the dominant failure mode is architectural — rooted in source fragmentation and anchor vocabulary gaps — rather than embedding quality. The source-coverage upper bound (§3.3) makes this precise: no amount of query refinement compensates for unsearched sources.+}

### 9. Conclusion

{+Instant Recall resolves these failures by shifting retrieval from inference time to build time. A pre-computed concept index, rebuilt nightly and kept fresh by real-time episodic updates, maps anchor vocabulary terms to pre-ranked memory clusters. At inference time, a ~50ms lookup surfaces relevant memories before the model processes the prompt — achieving 0.85 CORF-Recall@20 at the lowest latency of any evaluated system. Concept anchoring accounts for 9 points of recall beyond what source aggregation alone provides. Post-retrieval re-ranking halves the false positive rate.+}

### 9. Conclusion

{+The deeper insight is architectural: Instant Recall transforms agent memory from a _search problem_ into a _recognition problem_. The agent stops asking "what papers are you referring to?" — because the answer was already in context before the question was asked.+}

### References

1. Lewis, P., et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. [-*NeurIPS 2020*.-] {+_NeurIPS 2020_.+} 2. Packer, C., et al. (2023). MemGPT: Towards LLMs as Operating Systems. [-*arXiv:2310.08560*.-] {+_arXiv:2310.08560_.+} 3. Sarthi, P., et al. (2024). RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval. [-*ICLR 2024*.-] {+_ICLR 2024_.+} 4. Collins, A. M., & Loftus, E. F. (1975). A spreading-activation theory of semantic processing. [-*Psychological Review*,-] {+_Psychological Review_,+} 82(6), [-407-428.-] {+407–428.+} 5. Teyler, T. J., & DiScenna, P. (1986). The hippocampal memory indexing theory. [-*Behavioral Neuroscience*,-] {+_Behavioral Neuroscience_,+} 100(2), [-147-154.-] {+147–154.+} 6. Squire, L. R. (1992). Memory and the hippocampus: A synthesis from findings with rats, monkeys, and humans. [-*Psychological Review*,-] {+_Psychological Review_,+} 99(2), [-195-231.-] {+195–231.+} 7. Wilson, M. A., & McNaughton, B. L. (1994). Reactivation of hippocampal ensemble memories during sleep. [-*Science*,-] {+_Science_,+} 265(5172), [-676-679.-] {+676–679.+} 8. Tulving, E. (1976). Ecphoric processes in recall and recognition. [-*Recall-] {+_Recall+} and [-Recognition*, 37-73.-] {+Recognition_, 37–73.+} 9. Mandler, G. (1980). Recognizing: The judgment of previous occurrence. [-*Psychological Review*,-] {+_Psychological Review_,+} 87(3), [-252-271.-] {+252–271.+} 10. Yonelinas, A. P. (2002). The nature of recollection and familiarity: A review of 30 years of research. [-*Journal-] {+_Journal+} of Memory and [-Language*,-] {+Language_,+} 46(3), [-441-517.-] {+441–517.+} 11. MemoryOS. (2024). Mem0: The Memory Layer for Personalized AI. [-*arXiv:2504.19413*.-] {+_arXiv:2504.19413_.+} 12. Serra, O. (2026a). [-ENGRAM:-] {+Total Recall:+} Compaction as Cache Eviction in Persistent AI Agent Memory. [-*Independent Research*.-] {+_Independent Research_.+} 13. Serra, O. (2026b). [-CORTEX:-] {+Identity Persistence:+} Persistent Agent Identity Through Structured Persona Maintenance. [-*Independent Research*.-] {+_Independent Research_.+} 14. Serra, O. (2026d). [-LIMBIC:-] {+Humor Embeddings:+} Bisociation in Embedding Space for Humor Generation. [-*Independent Research*.-] {+_Independent Research_.+} 15. Serra, O. (2026e). [-SYNAPSE:-] {+Round Table:+} Cross-Session Signal Routing for Persistent AI Agents. [-*Independent Research*.-] {+_Independent Research_.+} 16. Park, J. S., et al. (2023). Generative Agents: Interactive Simulacra of Human Behavior. [-*UIST 2023*.-] {+_UIST 2023_.+} 17. Zhong, W., et al. (2023). MemoryBank: Enhancing Large Language Models with Long-Term Memory. [-*arXiv:2305.10250*.-] {+_arXiv:2305.10250_.+} 18. Manning, C. D., Raghavan, P., & Schütze, H. (2008). [-*Introduction-] {+_Introduction+} to Information [-Retrieval*.-] {+Retrieval_.+} Cambridge University Press. 19. Guu, K., et al. (2020). REALM: Retrieval-Augmented Language Model Pre-Training. [-*ICML 2020*.-] {+_ICML 2020_.+} 20. Borgeaud, S., et al. (2022). Improving language models by retrieving from trillions of tokens. [-*ICML 2022*.-] {+_ICML 2022_.+} 21. Xu, X., et al. (2025). A-MEM: Agentic Memory for LLM Agents. [-*arXiv:2502.12345*.-] {+_arXiv:2502.12345_.+} 22. Wu, D., et al. (2024). LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory. [-*arXiv:2407.xxxxx*.-] {+_arXiv:2410.10813_.+} 23. Yan, Z., et al. (2025). Memory-R1: RL-Trained Memory Management for LLM Agents. [-*arXiv:2505.xxxxx*.-] {+_arXiv:2505.14075_.+} 24. Gama, J., et al. (2014). A survey on concept drift adaptation. [-*ACM-] {+_ACM+} Computing [-Surveys*,-] {+Surveys_,+} 46(4), [-1-37. 25. Carbonell, J., & Goldstein, J. (1998). The use of MMR, diversity-based reranking for reordering documents and producing summaries. *SIGIR 1998*, 335-336. 26. Liu, N. F., et al. (2023). Lost in the Middle: How Language Models Use Long Contexts. *arXiv:2307.03172*. 27. Wei, J., et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. *NeurIPS 2022*. 28. Shi, F., et al. (2023). Large Language Models Can Be Easily Distracted by Irrelevant Context. *ICML 2023*. 29. Loeliger, J., & McCullough, M. (2012). *Version Control with Git* (2nd ed.). O'Reilly Media.-] {+1–37.+}

### References

[-*Word count: ~9,700 words* *Version 5.0 — 9 March 2026* *Changes from v4.0: Introduced CORF Mode 5 — Self-Contradiction Failure (SCF) — motivated by a real production failure observed 2026-03-09 in which a 16K-char/turn retrieval pack failed to surface a same-day daily log entry recording a meeting postponement. Added §2.4 (SCF literature context), updated §3.2 (Mode 5 definition), §3.3 (Observation 2 on SCF as query-quality failure), §3.4 (SCF frequency estimate ~15% of write-class actions). Added three new architectural components: §4.6c Daily Log Hot Cache (Tier 0), §4.9 Structured Query Extraction (entity-aware FTS with MMR dedup), §4.10 Pre-Action Contradiction Gate (pre-commit-hook analogy). Updated §4.8 inference pipeline pseudocode to include all three new components plus overhead analysis table. Updated §5.0 results table with projected HIPPOCAMPUS+SCF variant (~0.93 recall, marked as theoretical). Added A4 and A5 ablation rows in §7.4. Updated §7.4 main results table with SCF Rate column. Updated §8a.1 with 6 planned source files (~980 LOC) for v5.0 components (hippocampus-tier0.ts, hippocampus-sqe.ts, hippocampus-gate.ts + their test files). Updated §8a.3 architecture diagram. Updated Abstract, §1 Introduction, §8.1 limitations, and §9 conclusion. Added references [25]–[29] (MMR, Lost in the Middle, CoT, context distraction, Git). All projected/theoretical results clearly marked. No existing content removed or shortened.*-]

### References

[-*Version 4.0 — 24 February 2026* *Changes from v2.1: Added §8a (Implementation) documenting the production TypeScript implementation: 6 source files, 2,286 total LOC, key commit references (`74f9146`, `0a27429`, `d3e1604`, `0bdbf9d`), and the full module dependency graph. Added explicit cross-references to ENGRAM (Serra, 2026a), CORTEX (Serra, 2026b), LIMBIC (Serra, 2026d), and SYNAPSE (Serra, 2026e) throughout §1, §4, §8a.4. Clarified that `runHippocampusRebuild()` consumes ENGRAM event files as its primary input. No changes to theory, algorithms, or benchmark results.*-]

### References

[-*Version 2.1 — 24 February 2026* *Changes from v2.0: Section 7.4a updated with Phase 6.2 validation run results (2026-02-24T07:50:00+01:00, Vitest v4.0.18): full HIPPOCAMPUS suite summary table added (158 tests, 154 passed, 100% pass rate, 968 ms); per-file breakdown table added for all 3 source test files; run timestamp updated to Phase 6.2; minor wording clarifications consistent with Phase 6.2 scope.*-]

### References

[-----]

### Implementation Note (added 2026-04-16)

[-## Implementation Note (added 2026-04-16)-]

### Implementation Note (added 2026-04-16)

[-The O(1) concept index described in this paper is now implemented as **Feature 1** of the **MNEMOSYNE plugin** (J14, `tinkerclaw-memory-enhancements`). The implementation targets upstream's `memory-core` as the retrieval chassis — the plugin registers a retrieval pre-hook that short-circuits hybrid search when the query contains a known concept with importance above a configurable threshold.-]

### Implementation Note (added 2026-04-16)

[-The core data structure is a `Map<string, {chunkIds: Set<string>, importance: number, lastSeenAtMs: number}>`, persisted to `<agent state dir>/memory-enhancements/hippocampus/anchors.json`. Ingestion extracts concept anchors from each memory chunk, scores them by frequency × recency × distinctiveness, and prunes below-threshold entries on a nightly sweep. The lookup path is O(1) per concept token — consistent with the complexity analysis in §4.5 of this paper.-]

### Implementation Note (added 2026-04-16)

[-The original `extensions/hippocampus/` plugin remains as a thin compatibility wrapper. The substantive retrieval logic now lives in MNEMOSYNE (J14 §4).-]

### Implementation Note (added 2026-04-16)

[-Additionally, the **task-conditioned retrieval scoring** enhancement described in J14 §5 extends the HIPPOCAMPUS retrieval model by biasing scores according to the current task context — a contribution not covered in this paper. See J14 for the full treatment.-]

### Implementation Note (added 2026-04-16)

[-**Plugin mapping:** J2 HIPPOCAMPUS → `hippocampus` (thin wrapper, running) + `tinkerclaw-memory-enhancements` (MNEMOSYNE, running v0.1, Feature 1).-]

### References

{+_Version 7.0 — March 2026_ _Changes from v6.0: Structural and argumentative overhaul. Rewrote abstract (removed implementation trivia, clarified "zero inference-time search computation"). Fixed section numbering (§5→Theoretical Analysis, §7→full Evaluation with §7.1–7.5). Introduced MS-RAG as a named baseline with explicit definition (§6.3) and honest discussion of its recall advantage (§7.2). Added §7.5 Threats to Validity (single-deployment limitation, annotator bias, synthetic ablation corpus). Added §8.3 Ethical Considerations. Defined P(s) in source-coverage bound (§3.3). Defined engagement(term) precisely in §4.2 with log-scaled turn depth. Normalized importance scoring inputs in §4.6a. Clarified emergence threshold units in §4.5b. Fixed arXiv placeholders in references [22, 23]. Expanded §4.7 anchor detection to describe multi-word query handling and anchor collision. Corrected O-notation misuse in §5.1 (replaced "O(63)" with concrete operation count). Tempered neuroscience analogy in §1 (architectural not mechanistic). Rewrote conclusion to avoid restating abstract. Removed undefined "GravityClaw" reference. Consolidated §5.0 preview table into §7.2 to eliminate data duplication. Noted non-summation of failure mode frequencies in §3.4._+}
