{
 "paper": "total-recall",
 "a": "7.1",
 "b": "7.2",
 "summary": "From v7.1 (1 Apr) to v7.2 (2 Jun): 4,420 words to 6,357 words, 2,711 words in new or rewritten paragraphs and 774 taken out, 124 paragraphs changed.",
 "note": {
  "title": "Adds write reconciliation so working memory stays bounded",
  "kind": "revision",
  "body": "## Summary\n\nThe paper grows by about 1,900 words. The changelog calls it a bounded-memory pass.\n\n- New section on write reconciliation: each new fact is added, updates an old one, deletes one or does nothing. The working memory stays bounded while the audit log stays append-only.\n- New comparison of what a pointer marker costs in tokens per cycle against a narrative summary.\n- New subsection on query formulation, the step before task-conditioned scoring.\n- The implementation section drops line counts and commit hashes in favour of the properties the design guarantees.\n- The limitations add \"retrieval-trigger blindness\": the agent may not know it should look something up.",
  "source": "change note"
 },
 "paragraphs_changed": 124,
 "changes": [
  {
   "section": "",
   "old": "> **Changelog v7.1 (March 2026):** Second precision pass. §4.1 intractability claim sharpened; §5 marker merging elaborated; §9.1 statistical power note added; §9.2 effect size interpretation clarified; §10 retitled \"Limitations and Future Work\" per convention; event-store scalability limitation acknowledged. All prior v7.0 changes preserved.",
   "new": null,
   "marked": "[-> **Changelog v7.1 (March 2026):** Second precision pass. §4.1 intractability claim sharpened; §5 marker merging elaborated; §9.1 statistical power note added; §9.2 effect size interpretation clarified; §10 retitled \"Limitations and Future Work\" per convention; event-store scalability limitation acknowledged. All prior v7.0 changes preserved.-]"
  },
  {
   "section": "",
   "old": null,
   "new": "> **Changelog v7.2 (June 2026):** Bounded-memory pass. New §8 (\"Bounded Total Memory: Write Reconciliation\") closes the monotonic-growth gap — the event store grows forever and the working digest is unbounded; reconciliation (ADD/UPDATE/DELETE/NONE) bounds the *working* memory while keeping the audit log append-only. New §7.3 quantifies pointer-marker vs. narrative-summary token cost per cycle. §2.4 companion-paper handoffs rewritten with inline explanations of *why* pointer markers enable downstream indexing and *what* the nightly reflection loop tunes. §10 adds \"Retrieval-Trigger Blindness.\" §4 references confidence-gated retry as the upstream complement to task-conditioned scoring. Implementation claims (§9) softened to grounded, durable descriptions; per-module line counts and commit hashes removed in favor of architectural invariants. Sections renumbered to accommodate §8.",
   "marked": "{+> **Changelog v7.2 (June 2026):** Bounded-memory pass. New §8 (\"Bounded Total Memory: Write Reconciliation\") closes the monotonic-growth gap — the event store grows forever and the working digest is unbounded; reconciliation (ADD/UPDATE/DELETE/NONE) bounds the *working* memory while keeping the audit log append-only. New §7.3 quantifies pointer-marker vs. narrative-summary token cost per cycle. §2.4 companion-paper handoffs rewritten with inline explanations of *why* pointer markers enable downstream indexing and *what* the nightly reflection loop tunes. §10 adds \"Retrieval-Trigger Blindness.\" §4 references confidence-gated retry as the upstream complement to task-conditioned scoring. Implementation claims (§9) softened to grounded, durable descriptions; per-module line counts and commit hashes removed in favor of architectural invariants. Sections renumbered to accommodate §8.+}"
  },
  {
   "section": "Abstract",
   "old": "Persistent LLM agents must preserve precise strings, causal chains, and decision rationales across sessions that routinely exceed context limits. The industry-standard approach — narrative compaction — replaces this high-resolution state with lossy prose summaries, creating an irrecoverable \"only copy\" failure. We present **Total Recall**, a lossless, event-sourced memory architecture that treats the context window as a managed cache over a durable store. Instead of summarizing, Total Recall evicts history via **pointer-based compaction** — inserting compact time-range markers with topic hints and retrieval directives — while making all evicted content recoverable through a `recall(query)` tool. Retrieval is **task-conditioned**: injection depends on the active task and expected future needs, not just embedding similarity. The **TRACE** production implementation (1,756 LOC TypeScript, 7 modules) validates these claims: 281 tests with 0 failures; **100% needle-in-haystack recall** under forced compaction versus 0% for truncation; **94% exact-match recall at 2-hop** versus 4% for narrative compaction and 36% for MemGPT-style paging; sub-linear compaction latency of 1.46 ms at 200 events; and months of production operation indexing thousands of real emails with zero lossless-invariant violations.",
   "new": "Persistent LLM agents must preserve precise strings, causal chains, and decision rationales across sessions that routinely exceed context limits. The industry-standard approach — narrative compaction — replaces this high-resolution state with lossy prose summaries, creating an irrecoverable \"only copy\" failure. We present **Total Recall**, a lossless, event-sourced memory architecture that treats the context window as a managed cache over a durable store. Instead of summarizing, Total Recall evicts history via **pointer-based compaction** — inserting compact time-range markers with topic hints and retrieval directives — while making all evicted content recoverable through a `recall(query)` tool. Retrieval is **task-conditioned**: injection depends on the active task and expected future needs, not just embedding similarity. To keep total memory bounded along both axes — the in-context cache *and* the long-term store — Total Recall adds a **write-reconciliation** step that classifies each candidate memory as ADD, UPDATE, DELETE, or NONE, so the working set stays bounded while the audit log stays append-only and complete. The **TRACE** production implementation validates these claims: a full automated test suite passes with zero failures; **100% needle-in-haystack recall** under forced compaction versus 0% for truncation; **94% exact-match recall at 2-hop** versus 4% for narrative compaction and 36% for MemGPT-style paging; sub-linear compaction latency on the order of milliseconds; and months of production operation indexing thousands of real emails with zero lossless-invariant violations.",
   "marked": "Persistent LLM agents must preserve precise strings, causal chains, and decision rationales across sessions that routinely exceed context limits. The industry-standard approach — narrative compaction — replaces this high-resolution state with lossy prose summaries, creating an irrecoverable \"only copy\" failure. We present **Total Recall**, a lossless, event-sourced memory architecture that treats the context window as a managed cache over a durable store. Instead of summarizing, Total Recall evicts history via **pointer-based compaction** — inserting compact time-range markers with topic hints and retrieval directives — while making all evicted content recoverable through a `recall(query)` tool. Retrieval is **task-conditioned**: injection depends on the active task and expected future needs, not just embedding similarity. {+To keep total memory bounded along both axes — the in-context cache *and* the long-term store — Total Recall adds a **write-reconciliation** step that classifies each candidate memory as ADD, UPDATE, DELETE, or NONE, so the working set stays bounded while the audit log stays append-only and complete.+} The **TRACE** production implementation [-(1,756 LOC TypeScript, 7 modules)-] validates these claims: [-281 tests-] {+a full automated test suite passes+} with [-0-] {+zero+} failures; **100% needle-in-haystack recall** under forced compaction versus 0% for truncation; **94% exact-match recall at 2-hop** versus 4% for narrative compaction and 36% for MemGPT-style paging; sub-linear compaction latency {+on the order+} of [-1.46 ms at 200 events;-] {+milliseconds;+} and months of production operation indexing thousands of real emails with zero lossless-invariant violations."
  },
  {
   "section": "1. Introduction — The Compaction Failure Mode",
   "old": null,
   "new": "The biology offers a useful frame. In the mammalian brain, an *engram* is the physical trace a memory leaves in neural tissue — the durable change in synaptic connections that makes later recall possible. The hippocampus acts as the brain's librarian, deciding during sleep which fleeting experiences get encoded into long-term storage and which are discarded. Total Recall is an attempt to give an AI agent what biology gives every mammal: a durable, compactable memory trace that survives beyond the current conversation, and a principled rule for what to keep.",
   "marked": "{+The biology offers a useful frame. In the mammalian brain, an *engram* is the physical trace a memory leaves in neural tissue — the durable change in synaptic connections that makes later recall possible. The hippocampus acts as the brain's librarian, deciding during sleep which fleeting experiences get encoded into long-term storage and which are discarded. Total Recall is an attempt to give an AI agent what biology gives every mammal: a durable, compactable memory trace that survives beyond the current conversation, and a principled rule for what to keep.+}"
  },
  {
   "section": "1.3 Thesis and Contributions",
   "old": "**Thesis.** The context window must be treated as a **cache**, not canonical memory. Compaction must be **cache eviction with pointers**, not narrative consolidation.",
   "new": "**Thesis.** The context window must be treated as a **cache**, not canonical memory. Compaction must be **cache eviction with pointers**, not narrative consolidation. A second corollary follows: a memory system that only ever grows is not bounded, so *writes* must be reconciled, not blindly appended.",
   "marked": "**Thesis.** The context window must be treated as a **cache**, not canonical memory. Compaction must be **cache eviction with pointers**, not narrative [-consolidation.-] {+consolidation. A second corollary follows: a memory system that only ever grows is not bounded, so *writes* must be reconciled, not blindly appended.+}"
  },
  {
   "section": "1.3 Thesis and Contributions",
   "old": "- A **lossless append-only event store** as ground truth. - **Pointer-based compaction**: compact time-range markers replace evicted content. - A **hybrid push/pull retrieval model** balancing proactive injection with on-demand recall. - **Task-conditioned retrieval priority** derived from expected-utility optimization.",
   "new": "- A **lossless append-only event store** as ground truth. - **Pointer-based compaction**: compact time-range markers replace evicted content. - A **hybrid push/pull retrieval model** balancing proactive injection with on-demand recall. - **Task-conditioned retrieval priority** derived from expected-utility optimization. - **Write reconciliation** (ADD/UPDATE/DELETE/NONE) that bounds the working set without mutating the audit log.",
   "marked": "- A **lossless append-only event store** as ground truth. - **Pointer-based compaction**: compact time-range markers replace evicted content. - A **hybrid push/pull retrieval model** balancing proactive injection with on-demand recall. - **Task-conditioned retrieval priority** derived from expected-utility [-optimization.-] {+optimization. - **Write reconciliation** (ADD/UPDATE/DELETE/NONE) that bounds the working set without mutating the audit log.+}"
  },
  {
   "section": "1.3 Thesis and Contributions",
   "old": "The **TRACE** production codebase (§8) implements and validates all claims. Code, synthetic generators, and evaluation harness will be released on GitHub (link redacted for anonymity).",
   "new": "The **TRACE** production codebase (§9) implements and validates all claims. Code, synthetic generators, and evaluation harness will be released on GitHub (link redacted for anonymity).",
   "marked": "The **TRACE** production codebase [-(§8)-] {+(§9)+} implements and validates all claims. Code, synthetic generators, and evaluation harness will be released on GitHub (link redacted for anonymity)."
  },
  {
   "section": "2.2 Agent Memory Structures",
   "old": "Park et al. (2023) introduced a memory stream combining append-only logs with reflection. Reflexion (Shinn et al., 2023) and Voyager (Wang et al., 2023) maintain persistent memory via external text/code bases. Structural Memory (Zeng et al., 2024) mixes episodic, semantic, and procedural memories. Total Recall shares the append-only event store but formalizes pointer-based compaction as an eviction protocol with task-conditioned retrieval.",
   "new": "Park et al. (2023) introduced a memory stream combining append-only logs with reflection. Reflexion (Shinn et al., 2023) and Voyager (Wang et al., 2023) maintain persistent memory via external text/code bases. Structural Memory (Zeng et al., 2024) mixes episodic, semantic, and procedural memories. Mem0 (Yu et al., 2024) introduces a reconciliation step that classifies each candidate memory write as add, update, or delete rather than appending unconditionally. Total Recall shares the append-only event store, formalizes pointer-based compaction as an eviction protocol with task-conditioned retrieval, and adapts Mem0-style reconciliation as a *logical* working-set bound layered over an immutable audit log (§8).",
   "marked": "Park et al. (2023) introduced a memory stream combining append-only logs with reflection. Reflexion (Shinn et al., 2023) and Voyager (Wang et al., 2023) maintain persistent memory via external text/code bases. Structural Memory (Zeng et al., 2024) mixes episodic, semantic, and procedural memories. {+Mem0 (Yu et al., 2024) introduces a reconciliation step that classifies each candidate memory write as add, update, or delete rather than appending unconditionally.+} Total Recall shares the append-only event [-store but-] {+store,+} formalizes pointer-based compaction as an eviction protocol with task-conditioned [-retrieval.-] {+retrieval, and adapts Mem0-style reconciliation as a *logical* working-set bound layered over an immutable audit log (§8).+}"
  },
  {
   "section": "2.4 Companion Papers",
   "old": "Total Recall is one layer of a multi-layer memory architecture in the OpenClaw agent framework. Companion papers address session-scoped episodic memory (**Instant Recall**, Serra, 2026a), persona-aware context engineering (**Identity Persistence**, Serra, 2026b), affective tonal consistency (**Humor Embeddings**, Serra, 2026c), multi-model deliberation (**Round Table**, Serra, 2026d), offline episodic consolidation (**Sleep Consolidation**, Serra, 2026e), hierarchical reasoning across context boundaries (**Fractal Reasoning**, Serra, 2026f), and intrinsic knowledge-gap detection (**Curiosity Motivation**, Serra, 2026g). The present paper is self-contained; the companion papers provide the broader stack.",
   "new": null,
   "marked": "[-Total Recall is one layer of a multi-layer memory architecture in the OpenClaw agent framework. Companion papers address session-scoped episodic memory (**Instant Recall**, Serra, 2026a), persona-aware context engineering (**Identity Persistence**, Serra, 2026b), affective tonal consistency (**Humor Embeddings**, Serra, 2026c), multi-model deliberation (**Round Table**, Serra, 2026d), offline episodic consolidation (**Sleep Consolidation**, Serra, 2026e), hierarchical reasoning across context boundaries (**Fractal Reasoning**, Serra, 2026f), and intrinsic knowledge-gap detection (**Curiosity Motivation**, Serra, 2026g). The present paper is self-contained; the companion papers provide the broader stack.-]"
  },
  {
   "section": "2.4 Companion Papers",
   "old": null,
   "new": "Total Recall is one layer of a multi-layer memory architecture. It is self-contained, but composes with companion systems whose interfaces are worth stating concretely, because the composition produces capability none of the layers achieves alone.",
   "marked": "{+Total Recall is one layer of a multi-layer memory architecture. It is self-contained, but composes with companion systems whose interfaces are worth stating concretely, because the composition produces capability none of the layers achieves alone.+}"
  },
  {
   "section": "2.4 Companion Papers",
   "old": null,
   "new": "- **Indexing layer (Instant Recall, Serra 2026a).** Pointer-based compaction is not just space-saving; it is what makes downstream retrieval tractable. Each marker carries topic hints and a time range — structured anchors, not prose. A separate retrieval system builds a navigable index over these compacted pointers: clustering them by topic, scoring them by importance, and enabling sub-second lookup across the full corpus. *Without* the topic-hinted pointers, retrieval degrades to generic full-text search over raw, undifferentiated logs. The pointers are the seams the index grips. - **Consolidation layer (Sleep Consolidation, Serra 2026e).** A nightly reflection process reviews the day's retrieval successes and failures, identifies patterns (for example, \"medical context is consistently under-retrieved\"), and adjusts compaction and importance thresholds — effectively teaching the storage layer which memories deserve preservation. This is also where the deferred reconciliation sweep runs (§8.3): the only safe moment to decide that a fact is now stale is after its downstream outcome is known. - **Identity layer (Identity Persistence, Serra 2026b).** Persona-aware context assembly determines which system-prompt and persona blocks ride alongside the push pack; these blocks are never evicted, anchoring continuity across resets.",
   "marked": "{+- **Indexing layer (Instant Recall, Serra 2026a).** Pointer-based compaction is not just space-saving; it is what makes downstream retrieval tractable. Each marker carries topic hints and a time range — structured anchors, not prose. A separate retrieval system builds a navigable index over these compacted pointers: clustering them by topic, scoring them by importance, and enabling sub-second lookup across the full corpus. *Without* the topic-hinted pointers, retrieval degrades to generic full-text search over raw, undifferentiated logs. The pointers are the seams the index grips. - **Consolidation layer (Sleep Consolidation, Serra 2026e).** A nightly reflection process reviews the day's retrieval successes and failures, identifies patterns (for example, \"medical context is consistently under-retrieved\"), and adjusts compaction and importance thresholds — effectively teaching the storage layer which memories deserve preservation. This is also where the deferred reconciliation sweep runs (§8.3): the only safe moment to decide that a fact is now stale is after its downstream outcome is known. - **Identity layer (Identity Persistence, Serra 2026b).** Persona-aware context assembly determines which system-prompt and persona blocks ride alongside the push pack; these blocks are never evicted, anchoring continuity across resets.+}"
  },
  {
   "section": "2.4 Companion Papers",
   "old": null,
   "new": "The present paper is self-contained; the companion papers provide the broader stack.",
   "marked": "{+The present paper is self-contained; the companion papers provide the broader stack.+}"
  },
  {
   "section": "3.2 Pipeline",
   "old": "- **Layer 1 (Ingest & Index).** Persists events synchronously. Vectors embed asynchronously; the hot tail covers the latency gap. - **Layer 2 (Retrieve & Pack).** Assembles a fixed-budget _Push Pack_ (Task State, markers, hot tail) and handles on-demand _Pull_ via `recall`. - **Layer 3 (Consolidate).** Builds episodic summaries as derived indexes over the lossless store. Managed by the Sleep Consolidation pipeline (`src/memory/engram/sleep-consolidation.ts`, commit `6aea46b1c`).",
   "new": "- **Layer 1 (Ingest & Index).** Persists events synchronously. Vectors embed asynchronously; the hot tail covers the latency gap. - **Layer 2 (Retrieve & Pack).** Assembles a fixed-budget _Push Pack_ (Task State, markers, hot tail) and handles on-demand _Pull_ via `recall`. - **Layer 3 (Consolidate).** Builds episodic summaries as derived indexes over the lossless store, and runs the deferred write-reconciliation sweep (§8.3).",
   "marked": "- **Layer 1 (Ingest & Index).** Persists events synchronously. Vectors embed asynchronously; the hot tail covers the latency gap. - **Layer 2 (Retrieve & Pack).** Assembles a fixed-budget _Push Pack_ (Task State, markers, hot tail) and handles on-demand _Pull_ via `recall`. - **Layer 3 (Consolidate).** Builds episodic summaries as derived indexes over the lossless [-store. Managed by-] {+store, and runs+} the [-Sleep Consolidation pipeline (`src/memory/engram/sleep-consolidation.ts`, commit `6aea46b1c`).-] {+deferred write-reconciliation sweep (§8.3).+}"
  },
  {
   "section": "4.1 Formal Derivation",
   "old": "This objective is combinatorially hard (subset selection under a budget constraint is NP-hard in the general case). We approximate it by assuming marginal contributions are roughly independent — a submodularity assumption. This assumption is violated when events are strongly complementary (e.g., a cryptographic key split across two events, or a bug symptom paired with a configuration change). We acknowledge this limitation: in practice, the greedy approximation works well for the common case where most events contribute independently, but complementary-event retrieval remains an open problem for future work.",
   "new": "This objective is combinatorially hard (subset selection under a budget constraint is NP-hard in the general case). We approximate it by assuming marginal contributions are roughly independent — a submodularity assumption. This assumption is violated when events are strongly complementary (for example, a cryptographic key split across two events, or a bug symptom paired with a configuration change). We acknowledge this limitation: in practice, the greedy approximation works well for the common case where most events contribute independently, but complementary-event retrieval remains an open problem for future work.",
   "marked": "This objective is combinatorially hard (subset selection under a budget constraint is NP-hard in the general case). We approximate it by assuming marginal contributions are roughly independent — a submodularity assumption. This assumption is violated when events are strongly complementary [-(e.g.,-] {+(for example,+} a cryptographic key split across two events, or a bug symptom paired with a configuration change). We acknowledge this limitation: in practice, the greedy approximation works well for the common case where most events contribute independently, but complementary-event retrieval remains an open problem for future work."
  },
  {
   "section": "4.2 Retrieval Completeness",
   "old": "The independence assumption is a simplification; correlated retrieval failures (e.g., events sharing rare vocabulary) would lower the bound. Empirical quantification on LOCA-bench is planned.",
   "new": "The independence assumption is a simplification; correlated retrieval failures (events sharing rare vocabulary) would lower the bound. Empirical quantification on LOCA-bench is planned.",
   "marked": "The independence assumption is a simplification; correlated retrieval failures [-(e.g., events-] {+(events+} sharing rare vocabulary) would lower the bound. Empirical quantification on LOCA-bench is planned."
  },
  {
   "section": "4.3 The Upstream Dependency: Query Formulation",
   "old": null,
   "new": "### 4.3 The Upstream Dependency: Query Formulation",
   "marked": "{+### 4.3 The Upstream Dependency: Query Formulation+}"
  },
  {
   "section": "4.3 The Upstream Dependency: Query Formulation",
   "old": null,
   "new": "The completeness bound assumes the agent issues a query that actually matches how the knowledge was stored. In production this is the binding constraint, not storage. An agent that formulates a low-similarity query, accepts the weak result, and never escalates will miss content that is physically present and perfectly recoverable. Task-conditioned scoring improves *what is injected once a query is issued*; it does not decide *whether* to query or *whether the result is good enough*. The complementary mechanism — a confidence threshold below which the agent reformulates and retries with expanded queries before accepting failure — belongs in the metacognitive layer (Instant Recall, Serra 2026a; escalation in Fractal Reasoning, Serra 2026f). Total Recall defines the interface: `recall(query)` returns scored results with the similarity scores exposed, so a caller can gate on confidence. We return to this as a limitation in §10.",
   "marked": "{+The completeness bound assumes the agent issues a query that actually matches how the knowledge was stored. In production this is the binding constraint, not storage. An agent that formulates a low-similarity query, accepts the weak result, and never escalates will miss content that is physically present and perfectly recoverable. Task-conditioned scoring improves *what is injected once a query is issued*; it does not decide *whether* to query or *whether the result is good enough*. The complementary mechanism — a confidence threshold below which the agent reformulates and retries with expanded queries before accepting failure — belongs in the metacognitive layer (Instant Recall, Serra 2026a; escalation in Fractal Reasoning, Serra 2026f). Total Recall defines the interface: `recall(query)` returns scored results with the similarity scores exposed, so a caller can gate on confidence. We return to this as a limitation in §10.+}"
  },
  {
   "section": "5.1 Eviction Ordering",
   "old": "Total Recall evicts oldest tool results first (large, highly retrievable), then tool calls, then dialogue. System blocks, Task State, and markers are never evicted. Task State serves as a proxy oracle for future access, approximating Belady's MIN. This ordering is encoded in `EVICTION_PRIORITY` in `src/memory/engram/pointer-compaction.ts` (§8.6).",
   "new": "Total Recall evicts oldest tool results first (large, highly retrievable), then tool calls, then dialogue. System blocks, persona state, Task State, and markers are never evicted. Task State serves as a proxy oracle for future access, approximating Belady's MIN. The policy assigns each event kind a numeric eviction weight and selects the oldest contiguous span maximizing total weight; non-evictable kinds carry weight zero and are guarded out entirely.",
   "marked": "Total Recall evicts oldest tool results first (large, highly retrievable), then tool calls, then dialogue. System blocks, {+persona state,+} Task State, and markers are never evicted. Task State serves as a proxy oracle for future access, approximating Belady's MIN. [-This ordering is encoded in `EVICTION_PRIORITY` in `src/memory/engram/pointer-compaction.ts` (§8.6).-] {+The policy assigns each event kind a numeric eviction weight and selects the oldest contiguous span maximizing total weight; non-evictable kinds carry weight zero and are guarded out entirely.+}"
  },
  {
   "section": "5.1 Eviction Ordering",
   "old": null,
   "new": "**Table A.** Eviction weights by event kind (higher = evicted sooner).",
   "marked": "{+**Table A.** Eviction weights by event kind (higher = evicted sooner).+}"
  },
  {
   "section": "5.1 Eviction Ordering",
   "old": null,
   "new": "| Event kind | Weight | Rationale | | ------------------- | ------ | ------------------------------------------------------ | | Tool result | 1.0 | Largest, most retrievable — recovers cleanly via recall | | Tool call | 0.8 | Reconstructable from result + dialogue | | Agent / user message| 0.5 | Carries intent; evict only under pressure | | Artifact reference | 0.3 | Already a pointer; little to gain | | Marker / persona / system | 0.0 | Never evicted (non-evictable guard) |",
   "marked": "{+| Event kind | Weight | Rationale | | ------------------- | ------ | ------------------------------------------------------ | | Tool result | 1.0 | Largest, most retrievable — recovers cleanly via recall | | Tool call | 0.8 | Reconstructable from result + dialogue | | Agent / user message| 0.5 | Carries intent; evict only under pressure | | Artifact reference | 0.3 | Already a pointer; little to gain | | Marker / persona / system | 0.0 | Never evicted (non-evictable guard) |+}"
  },
  {
   "section": "7.1 Linear Memory Growth",
   "old": "The append-only store and pointer-based compaction yield strictly linear storage growth $O(T)$, avoiding the quadratic bloat of recursive summarization. Compaction latency confirms this: 0.20 ms at 100 events, 0.48 ms at 200 events (§9.4, Table 2).",
   "new": "The append-only store and pointer-based compaction yield strictly linear storage growth $O(T)$, avoiding the quadratic bloat of recursive summarization. Compaction latency confirms this: roughly 0.20 ms at 100 events and 0.48 ms at 200 events (§9.4, Table 2).",
   "marked": "The append-only store and pointer-based compaction yield strictly linear storage growth $O(T)$, avoiding the quadratic bloat of recursive summarization. Compaction latency confirms this: {+roughly+} 0.20 ms at 100 [-events,-] {+events and+} 0.48 ms at 200 events (§9.4, Table 2)."
  },
  {
   "section": "7.3 Marker vs. Summary Token Cost",
   "old": null,
   "new": "### 7.3 Marker vs. Summary Token Cost",
   "marked": "{+### 7.3 Marker vs. Summary Token Cost+}"
  },
  {
   "section": "7.3 Marker vs. Summary Token Cost",
   "old": null,
   "new": "The two compaction strategies differ not only in fidelity but in steady-state token cost. A narrative summary of an evicted span is itself prose that must be re-read on every subsequent turn, and as summaries-of-summaries accumulate, this recap text grows with session length. A time-range marker is a fixed-size directive — a time range, a short topic-hint list, and the `recall` instruction — typically tens of tokens, and marker merging (§5.2) bounds the *total* marker footprint to $O(\\log C)$ in the number of compaction cycles.",
   "marked": "{+The two compaction strategies differ not only in fidelity but in steady-state token cost. A narrative summary of an evicted span is itself prose that must be re-read on every subsequent turn, and as summaries-of-summaries accumulate, this recap text grows with session length. A time-range marker is a fixed-size directive — a time range, a short topic-hint list, and the `recall` instruction — typically tens of tokens, and marker merging (§5.2) bounds the *total* marker footprint to $O(\\log C)$ in the number of compaction cycles.+}"
  },
  {
   "section": "7.3 Marker vs. Summary Token Cost",
   "old": null,
   "new": "| Per-cycle artifact | Narrative compaction | Pointer compaction | | ----------------------------- | --------------------------------- | --------------------------- | | Bytes written to context | Full prose recap (hundreds–thousands of tokens) | One marker (tens of tokens) | | Re-read cost per later turn | Entire recap, every turn | One marker, every turn | | Growth across $C$ cycles | Roughly linear in $C$ (recaps stack) | $O(\\log C)$ (markers merge) | | Recovery of evicted detail | Impossible (lossy) | On-demand via `recall` |",
   "marked": "{+| Per-cycle artifact | Narrative compaction | Pointer compaction | | ----------------------------- | --------------------------------- | --------------------------- | | Bytes written to context | Full prose recap (hundreds–thousands of tokens) | One marker (tens of tokens) | | Re-read cost per later turn | Entire recap, every turn | One marker, every turn | | Growth across $C$ cycles | Roughly linear in $C$ (recaps stack) | $O(\\log C)$ (markers merge) | | Recovery of evicted detail | Impossible (lossy) | On-demand via `recall` |+}"
  },
  {
   "section": "7.3 Marker vs. Summary Token Cost",
   "old": null,
   "new": "The marker pays a small, occasional `recall` cost only when evicted detail is actually needed (measured at 22% of turns, §9.3), versus a narrative summary that pays a recurring recap tax on *every* turn whether or not the detail is used. This makes pointer compaction strictly cheaper in steady state for sessions where most evicted content is never re-touched — the common case.",
   "marked": "{+The marker pays a small, occasional `recall` cost only when evicted detail is actually needed (measured at 22% of turns, §9.3), versus a narrative summary that pays a recurring recap tax on *every* turn whether or not the detail is used. This makes pointer compaction strictly cheaper in steady state for sessions where most evicted content is never re-touched — the common case.+}"
  },
  {
   "section": "8. Implementation: TRACE",
   "old": "## 8. Implementation: TRACE",
   "new": null,
   "marked": "[-## 8. Implementation: TRACE-]"
  },
  {
   "section": "8. Implementation: TRACE",
   "old": "**TRACE** (Testing Retrieval And Compaction Engine) is the production TypeScript implementation of Total Recall within the OpenClaw agent framework: **1,756 lines** across 7 core modules, validated by 281 tests. TRACE is not a prototype — it has operated continuously for months in production across persistent multi-session agent deployments.",
   "new": null,
   "marked": "[-**TRACE** (Testing Retrieval And Compaction Engine) is the production TypeScript implementation of Total Recall within the OpenClaw agent framework: **1,756 lines** across 7 core modules, validated by 281 tests. TRACE is not a prototype — it has operated continuously for months in production across persistent multi-session agent deployments.-]"
  },
  {
   "section": "8.1 Module Inventory",
   "old": "### 8.1 Module Inventory",
   "new": null,
   "marked": "[-### 8.1 Module Inventory-]"
  },
  {
   "section": "8.1 Module Inventory",
   "old": "| File | LOC | Commit | Description | | ----------------------------------------------- | --------- | ----------- | -------------------------------------------------------------- | | `src/memory/engram/event-store.ts` | 139 | `e385ccd38` | Append-only JSONL event store with ULID IDs | | `src/memory/engram/ingestion.ts` | 228 | `0bccfced4` | Per-turn event ingestion; artifact externalization | | `src/memory/engram/pointer-compaction.ts` | 202 | `2c22a4510` | Pointer compaction engine; type-weighted eviction | | `src/memory/engram/sleep-consolidation.ts` | 116 | `6aea46b1c` | Offline episode detection and summary generation | | `src/memory/engram/compaction-reflection.ts` | 464 | `7a651d53c` | Post-compaction self-reflection loop and diagnostics | | `src/agents/pi-extensions/compaction-engram.ts` | 222 | `7a651d53c` | Pi agent framework integration; `session_before_compact` hook | | `src/agents/context-anatomy.ts` | 385 | `7523e765c` | Per-turn prompt decomposition and context utilization tracking | | **Total** | **1,756** | | |",
   "new": null,
   "marked": "[-| File | LOC | Commit | Description | | ----------------------------------------------- | --------- | ----------- | -------------------------------------------------------------- | | `src/memory/engram/event-store.ts` | 139 | `e385ccd38` | Append-only JSONL event store with ULID IDs | | `src/memory/engram/ingestion.ts` | 228 | `0bccfced4` | Per-turn event ingestion; artifact externalization | | `src/memory/engram/pointer-compaction.ts` | 202 | `2c22a4510` | Pointer compaction engine; type-weighted eviction | | `src/memory/engram/sleep-consolidation.ts` | 116 | `6aea46b1c` | Offline episode detection and summary generation | | `src/memory/engram/compaction-reflection.ts` | 464 | `7a651d53c` | Post-compaction self-reflection loop and diagnostics | | `src/agents/pi-extensions/compaction-engram.ts` | 222 | `7a651d53c` | Pi agent framework integration; `session_before_compact` hook | | `src/agents/context-anatomy.ts` | 385 | `7523e765c` | Per-turn prompt decomposition and context utilization tracking | | **Total** | **1,756** | | |-]"
  },
  {
   "section": "8.2 Commit History: Key Feature Milestones",
   "old": "### 8.2 Commit History: Key Feature Milestones",
   "new": null,
   "marked": "[-### 8.2 Commit History: Key Feature Milestones-]"
  },
  {
   "section": "8.2 Commit History: Key Feature Milestones",
   "old": "| Commit | Message | Modules affected | | ----------- | ----------------------------------------------------------------------------- | ---------------------------------------- | | `e385ccd38` | feat(engram): Phase 0+1A — metrics, event store, artifact store, test harness | event-store | | `0bccfced4` | trace: wire per-turn event ingestion into attempt.ts | ingestion | | `2c22a4510` | feat(engram): Phase 1B-1D — pointer compaction, push pack, recall tool | pointer-compaction | | `6aea46b1c` | feat(engram): Phase 3 — sleep consolidation, episode detection | sleep-consolidation | | `7a651d53c` | trace: post-compaction self-reflection loop | compaction-reflection, compaction-engram | | `7523e765c` | context-anatomy: topic detection and transition tracking | context-anatomy |",
   "new": null,
   "marked": "[-| Commit | Message | Modules affected | | ----------- | ----------------------------------------------------------------------------- | ---------------------------------------- | | `e385ccd38` | feat(engram): Phase 0+1A — metrics, event store, artifact store, test harness | event-store | | `0bccfced4` | trace: wire per-turn event ingestion into attempt.ts | ingestion | | `2c22a4510` | feat(engram): Phase 1B-1D — pointer compaction, push pack, recall tool | pointer-compaction | | `6aea46b1c` | feat(engram): Phase 3 — sleep consolidation, episode detection | sleep-consolidation | | `7a651d53c` | trace: post-compaction self-reflection loop | compaction-reflection, compaction-engram | | `7523e765c` | context-anatomy: topic detection and transition tracking | context-anatomy |-]"
  },
  {
   "section": "8.3 Architecture Overview",
   "old": "### 8.3 Architecture Overview",
   "new": null,
   "marked": "[-### 8.3 Architecture Overview-]"
  },
  {
   "section": "8.3 Architecture Overview",
   "old": "``` ┌─────────────────────────────────────────────────────────┐ │ Pi Agent Framework │ │ session_before_compact ─────────────────────────────┐ │ └───────────────────────────────────────────────────────┼──┘ │ ┌───────────────────────────────────────────────────────▼──┐ │ compaction-engram.ts (Pi integration) │ │ · Intercepts compact hook · Persists to event store │ │ · Returns pointer markers (pointerMode) or text recap │ └──────────────────────────┬───────────────────────────────┘ │ ┌───────────────▼───────────────┐ │ Total Recall Core Pipeline │ │ ingestion.ts │ │ └─ event-store.ts │ │ └─ artifact-store │ │ pointer-compaction.ts │ │ └─ time-range-marker │ │ sleep-consolidation.ts │ │ compaction-reflection.ts │ └───────────────┬───────────────┘ │ ┌───────────────▼───────────────┐ │ context-anatomy.ts │ │ Per-turn prompt decomposition │ │ Context utilization logging │ └───────────────────────────────┘ ```",
   "new": null,
   "marked": "[-``` ┌─────────────────────────────────────────────────────────┐ │ Pi Agent Framework │ │ session_before_compact ─────────────────────────────┐ │ └───────────────────────────────────────────────────────┼──┘ │ ┌───────────────────────────────────────────────────────▼──┐ │ compaction-engram.ts (Pi integration) │ │ · Intercepts compact hook · Persists to event store │ │ · Returns pointer markers (pointerMode) or text recap │ └──────────────────────────┬───────────────────────────────┘ │ ┌───────────────▼───────────────┐ │ Total Recall Core Pipeline │ │ ingestion.ts │ │ └─ event-store.ts │ │ └─ artifact-store │ │ pointer-compaction.ts │ │ └─ time-range-marker │ │ sleep-consolidation.ts │ │ compaction-reflection.ts │ └───────────────┬───────────────┘ │ ┌───────────────▼───────────────┐ │ context-anatomy.ts │ │ Per-turn prompt decomposition │ │ Context utilization logging │ └───────────────────────────────┘ ```-]"
  },
  {
   "section": "8.4 Event Store (`event-store.ts`, commit `e385ccd38`)",
   "old": "### 8.4 Event Store (`event-store.ts`, commit `e385ccd38`)",
   "new": null,
   "marked": "[-### 8.4 Event Store (`event-store.ts`, commit `e385ccd38`)-]"
  },
  {
   "section": "8.4 Event Store (`event-store.ts`, commit `e385ccd38`)",
   "old": "A 139-line append-only JSONL log with ULID-based time-sortable IDs. Key design choices:",
   "new": null,
   "marked": "[-A 139-line append-only JSONL log with ULID-based time-sortable IDs. Key design choices:-]"
  },
  {
   "section": "8.4 Event Store (`event-store.ts`, commit `e385ccd38`)",
   "old": "- **ULID generation** is inline (no external dependency) with a monotonic counter within the same millisecond. - Events are serialized via `appendFileSync` for durability. - Full-text search uses in-process scan for the test harness; production uses an FTS index.",
   "new": null,
   "marked": "[-- **ULID generation** is inline (no external dependency) with a monotonic counter within the same millisecond. - Events are serialized via `appendFileSync` for durability. - Full-text search uses in-process scan for the test harness; production uses an FTS index.-]"
  },
  {
   "section": "8.5 Ingestion Pipeline (`ingestion.ts`, commit `0bccfced4`)",
   "old": "### 8.5 Ingestion Pipeline (`ingestion.ts`, commit `0bccfced4`)",
   "new": null,
   "marked": "[-### 8.5 Ingestion Pipeline (`ingestion.ts`, commit `0bccfced4`)-]"
  },
  {
   "section": "8.5 Ingestion Pipeline (`ingestion.ts`, commit `0bccfced4`)",
   "old": "The 228-line ingestion module maps conversation messages to Total Recall events. Tool results exceeding 1 KB are externalized to the artifact store with a compact pointer replacing the payload — the primary mechanism preventing context bloat from large API payloads or DOM states.",
   "new": null,
   "marked": "[-The 228-line ingestion module maps conversation messages to Total Recall events. Tool results exceeding 1 KB are externalized to the artifact store with a compact pointer replacing the payload — the primary mechanism preventing context bloat from large API payloads or DOM states.-]"
  },
  {
   "section": "8.6 Pointer Compaction Engine (`pointer-compaction.ts`, commit `2c22a4510`)",
   "old": "### 8.6 Pointer Compaction Engine (`pointer-compaction.ts`, commit `2c22a4510`)",
   "new": null,
   "marked": "[-### 8.6 Pointer Compaction Engine (`pointer-compaction.ts`, commit `2c22a4510`)-]"
  },
  {
   "section": "8.6 Pointer Compaction Engine (`pointer-compaction.ts`, commit `2c22a4510`)",
   "old": "The 202-line compaction engine implements the type-weighted eviction policy from §5.1:",
   "new": null,
   "marked": "[-The 202-line compaction engine implements the type-weighted eviction policy from §5.1:-]"
  },
  {
   "section": "8.6 Pointer Compaction Engine (`pointer-compaction.ts`, commit `2c22a4510`)",
   "old": "```typescript const EVICTION_PRIORITY: Partial<Record<EventKind, number>> = { tool_result: 1.0, tool_call: 0.8, agent_message: 0.5, // NON_EVICTABLE_KINDS: never evicted }; ```",
   "new": null,
   "marked": "[-```typescript const EVICTION_PRIORITY: Partial<Record<EventKind, number>> = { tool_result: 1.0, tool_call: 0.8, agent_message: 0.5, // NON_EVICTABLE_KINDS: never evicted }; ```-]"
  },
  {
   "section": "8.6 Pointer Compaction Engine (`pointer-compaction.ts`, commit `2c22a4510`)",
   "old": "Victims are selected oldest-first within each priority tier. After eviction, `createTimeRangeMarker` inserts a pointer covering the evicted time range with extracted topic hints and a `recall(query)` directive.",
   "new": null,
   "marked": "[-Victims are selected oldest-first within each priority tier. After eviction, `createTimeRangeMarker` inserts a pointer covering the evicted time range with extracted topic hints and a `recall(query)` directive.-]"
  },
  {
   "section": "8.7 Context Anatomy (`context-anatomy.ts`, commit `7523e765c`)",
   "old": "### 8.7 Context Anatomy (`context-anatomy.ts`, commit `7523e765c`)",
   "new": null,
   "marked": "[-### 8.7 Context Anatomy (`context-anatomy.ts`, commit `7523e765c`)-]"
  },
  {
   "section": "8.7 Context Anatomy (`context-anatomy.ts`, commit `7523e765c`)",
   "old": "The 385-line **Context Anatomy** module records the full decomposition of every LLM prompt: system prompt, workspace files, skills, tool schemas, conversation history, tool results, and user message. Each record is tagged with:",
   "new": null,
   "marked": "[-The 385-line **Context Anatomy** module records the full decomposition of every LLM prompt: system prompt, workspace files, skills, tool schemas, conversation history, tool results, and user message. Each record is tagged with:-]"
  },
  {
   "section": "8.7 Context Anatomy (`context-anatomy.ts`, commit `7523e765c`)",
   "old": "- **Compaction cycle counter:** how many compactions have occurred this session. - **Context utilization percentage:** tokens used / total budget. - **Topic detection and transition tracking:** detects task-domain shifts.",
   "new": null,
   "marked": "[-- **Compaction cycle counter:** how many compactions have occurred this session. - **Context utilization percentage:** tokens used / total budget. - **Topic detection and transition tracking:** detects task-domain shifts.-]"
  },
  {
   "section": "8.7 Context Anatomy (`context-anatomy.ts`, commit `7523e765c`)",
   "old": "Records are written to a per-session JSONL file and returned on the attempt result for real-time consumption. Context Anatomy is the primary diagnostic tool for understanding compaction behavior in production: by replaying anatomy logs, engineers reconstruct exactly what was in-context at any turn, which markers were present, and when compaction fired.",
   "new": null,
   "marked": "[-Records are written to a per-session JSONL file and returned on the attempt result for real-time consumption. Context Anatomy is the primary diagnostic tool for understanding compaction behavior in production: by replaying anatomy logs, engineers reconstruct exactly what was in-context at any turn, which markers were present, and when compaction fired.-]"
  },
  {
   "section": "8.7 Context Anatomy (`context-anatomy.ts`, commit `7523e765c`)",
   "old": "**Cross-layer integration.** Context Anatomy sits at the intersection of all three memory layers. Instant Recall feeds the hot tail visible in the anatomy record; Identity Persistence's system prompt assembly appears in the `systemPrompt` field; Total Recall's pointers appear in the `conversationHistory` slice. This makes Context Anatomy the single most useful tool for cross-layer memory debugging.",
   "new": null,
   "marked": "[-**Cross-layer integration.** Context Anatomy sits at the intersection of all three memory layers. Instant Recall feeds the hot tail visible in the anatomy record; Identity Persistence's system prompt assembly appears in the `systemPrompt` field; Total Recall's pointers appear in the `conversationHistory` slice. This makes Context Anatomy the single most useful tool for cross-layer memory debugging.-]"
  },
  {
   "section": "8. Bounded Total Memory: Write Reconciliation",
   "old": null,
   "new": "## 8. Bounded Total Memory: Write Reconciliation",
   "marked": "{+## 8. Bounded Total Memory: Write Reconciliation+}"
  },
  {
   "section": "8. Bounded Total Memory: Write Reconciliation",
   "old": null,
   "new": "Pointer-based compaction bounds the *in-context* cache. It does nothing for the *long-term store*, which grows monotonically: every user message, tool call, and result is appended forever. Append-only is the correct invariant for an *audit* trail, but the wrong invariant for a *working set*. A durable memory whose working digest only ever grows is not bounded, and an unbounded digest defeats the purpose of a digest. Total Recall closes this with a reconciliation step adapted from Mem0 (Yu et al., 2024).",
   "marked": "{+Pointer-based compaction bounds the *in-context* cache. It does nothing for the *long-term store*, which grows monotonically: every user message, tool call, and result is appended forever. Append-only is the correct invariant for an *audit* trail, but the wrong invariant for a *working set*. A durable memory whose working digest only ever grows is not bounded, and an unbounded digest defeats the purpose of a digest. Total Recall closes this with a reconciliation step adapted from Mem0 (Yu et al., 2024).+}"
  },
  {
   "section": "8.1 The Two-Plane Design",
   "old": null,
   "new": "### 8.1 The Two-Plane Design",
   "marked": "{+### 8.1 The Two-Plane Design+}"
  },
  {
   "section": "8.1 The Two-Plane Design",
   "old": null,
   "new": "The central constraint is that the event store is structurally append-only: its interface exposes append and read operations only — no in-place update, no delete. This is deliberate. It preserves the parallelism-safety invariant the whole store relies on: multiple sessions issue fire-and-forget writes, and a raw append never reads or rewrites prior rows. Reconciliation must therefore *not* mutate the log. The design splits into two planes:",
   "marked": "{+The central constraint is that the event store is structurally append-only: its interface exposes append and read operations only — no in-place update, no delete. This is deliberate. It preserves the parallelism-safety invariant the whole store relies on: multiple sessions issue fire-and-forget writes, and a raw append never reads or rewrites prior rows. Reconciliation must therefore *not* mutate the log. The design splits into two planes:+}"
  },
  {
   "section": "8.1 The Two-Plane Design",
   "old": null,
   "new": "1. **Audit plane (the append-only log) stays immutable.** Every event ever ingested remains on disk, recoverable. 2. **Working-memory plane is where reconciliation takes effect.** Decisions are recorded as a separate logical *ledger* of supersede/tombstone rows, and the bounded human-facing digest is *regenerated* from the surviving (non-tombstoned, latest-superseding) facts. A logical DELETE is a ledger tombstone, never a physical row removal.",
   "marked": "{+1. **Audit plane (the append-only log) stays immutable.** Every event ever ingested remains on disk, recoverable. 2. **Working-memory plane is where reconciliation takes effect.** Decisions are recorded as a separate logical *ledger* of supersede/tombstone rows, and the bounded human-facing digest is *regenerated* from the surviving (non-tombstoned, latest-superseding) facts. A logical DELETE is a ledger tombstone, never a physical row removal.+}"
  },
  {
   "section": "8.2 The Four Decisions",
   "old": null,
   "new": "### 8.2 The Four Decisions",
   "marked": "{+### 8.2 The Four Decisions+}"
  },
  {
   "section": "8.2 The Four Decisions",
   "old": null,
   "new": "Each candidate memory write is classified:",
   "marked": "{+Each candidate memory write is classified:+}"
  },
  {
   "section": "8.2 The Four Decisions",
   "old": null,
   "new": "| Action | Meaning | Where it runs | Effect | | ------- | ---------------------------------------- | ------------------------ | --------------------------------------------- | | **ADD** | New fact | Hot path or nightly | Append to the log (the only action that touches disk) | | **NONE**| Not worth storing | Hot path | Skip the append entirely | | **UPDATE** | Supersedes an existing fact | Nightly sweep only | Logical supersede row in the ledger | | **DELETE** | Redundant or stale fact | Nightly sweep only | Logical tombstone row in the ledger |",
   "marked": "{+| Action | Meaning | Where it runs | Effect | | ------- | ---------------------------------------- | ------------------------ | --------------------------------------------- | | **ADD** | New fact | Hot path or nightly | Append to the log (the only action that touches disk) | | **NONE**| Not worth storing | Hot path | Skip the append entirely | | **UPDATE** | Supersedes an existing fact | Nightly sweep only | Logical supersede row in the ledger | | **DELETE** | Redundant or stale fact | Nightly sweep only | Logical tombstone row in the ledger |+}"
  },
  {
   "section": "8.3 Hot-Path Safety and Deferred Reconciliation",
   "old": null,
   "new": "### 8.3 Hot-Path Safety and Deferred Reconciliation",
   "marked": "{+### 8.3 Hot-Path Safety and Deferred Reconciliation+}"
  },
  {
   "section": "8.3 Hot-Path Safety and Deferred Reconciliation",
   "old": null,
   "new": "The load-bearing safety property is a phase split. On the **hot path**, the reconciler is consulted once per turn through the single append chokepoint that all ingestion routes through; it must be cheap and may return **only ADD or NONE**. It must never attempt UPDATE or DELETE, because deciding that a fact supersedes or contradicts another requires comparing against the working set and, in the LLM-backed variant, a model call — too expensive and too risky to run every turn, and unsafe besides: whether a fact is stale often cannot be known until its downstream outcome lands. A NONE simply skips persistence (and the cache push) for that event.",
   "marked": "{+The load-bearing safety property is a phase split. On the **hot path**, the reconciler is consulted once per turn through the single append chokepoint that all ingestion routes through; it must be cheap and may return **only ADD or NONE**. It must never attempt UPDATE or DELETE, because deciding that a fact supersedes or contradicts another requires comparing against the working set and, in the LLM-backed variant, a model call — too expensive and too risky to run every turn, and unsafe besides: whether a fact is stale often cannot be known until its downstream outcome lands. A NONE simply skips persistence (and the cache push) for that event.+}"
  },
  {
   "section": "8.3 Hot-Path Safety and Deferred Reconciliation",
   "old": null,
   "new": "UPDATE and DELETE are **deferred to the nightly consolidation sweep** (Layer 3, §3.2), the same pass that detects episodes and builds summaries. There the reconciler compares each new fact in the consolidation window against the existing working set and emits supersede/tombstone ledger rows. This is also the natural home for the cross-layer feedback loop: the nightly reflection process (Sleep Consolidation, Serra 2026e) reviews which memories were retrieved and which were missed, and tunes both compaction thresholds and reconciliation aggressiveness accordingly.",
   "marked": "{+UPDATE and DELETE are **deferred to the nightly consolidation sweep** (Layer 3, §3.2), the same pass that detects episodes and builds summaries. There the reconciler compares each new fact in the consolidation window against the existing working set and emits supersede/tombstone ledger rows. This is also the natural home for the cross-layer feedback loop: the nightly reflection process (Sleep Consolidation, Serra 2026e) reviews which memories were retrieved and which were missed, and tunes both compaction thresholds and reconciliation aggressiveness accordingly.+}"
  },
  {
   "section": "8.4 Turn Atomicity",
   "old": null,
   "new": "### 8.4 Turn Atomicity",
   "marked": "{+### 8.4 Turn Atomicity+}"
  },
  {
   "section": "8.4 Turn Atomicity",
   "old": null,
   "new": "Hot-path reconciliation operates at event granularity but must respect turn boundaries: a user message and its associated tool calls are kept or dropped together. A NONE on a user message that orphaned its tool calls would corrupt the turn's causal structure. The reconciler therefore evaluates a turn's events as a unit on the hot path.",
   "marked": "{+Hot-path reconciliation operates at event granularity but must respect turn boundaries: a user message and its associated tool calls are kept or dropped together. A NONE on a user message that orphaned its tool calls would corrupt the turn's causal structure. The reconciler therefore evaluates a turn's events as a unit on the hot path.+}"
  },
  {
   "section": "8.5 The Bounded Digest",
   "old": null,
   "new": "### 8.5 The Bounded Digest",
   "marked": "{+### 8.5 The Bounded Digest+}"
  },
  {
   "section": "8.5 The Bounded Digest",
   "old": null,
   "new": "A human-facing digest is regenerated from the ledger's surviving facts plus the per-episode summaries. The writer is a pure function — facts, summaries, and a maximum line count in; serialized content and demotion suggestions out — and never touches disk on its own. It enforces the line bound the same way a well-kept index does: each surviving fact becomes a single one-line entry, and when facts plus summaries would exceed the bound, the lowest-importance entries are demoted to linked detail files rather than dropped. This mirrors the discipline a human curator already applies (\"keep index entries to one line; move detail into topic files\") and preserves hand-authorship: the writer *suggests* prunes rather than silently overwriting a curated file.",
   "marked": "{+A human-facing digest is regenerated from the ledger's surviving facts plus the per-episode summaries. The writer is a pure function — facts, summaries, and a maximum line count in; serialized content and demotion suggestions out — and never touches disk on its own. It enforces the line bound the same way a well-kept index does: each surviving fact becomes a single one-line entry, and when facts plus summaries would exceed the bound, the lowest-importance entries are demoted to linked detail files rather than dropped. This mirrors the discipline a human curator already applies (\"keep index entries to one line; move detail into topic files\") and preserves hand-authorship: the writer *suggests* prunes rather than silently overwriting a curated file.+}"
  },
  {
   "section": "8.6 Compatibility and Rollout",
   "old": null,
   "new": "### 8.6 Compatibility and Rollout",
   "marked": "{+### 8.6 Compatibility and Rollout+}"
  },
  {
   "section": "8.6 Compatibility and Rollout",
   "old": null,
   "new": "Reconciliation is opt-in and ships dark. The default reconciler classifies every event as ADD, so a deployment with no reconciler configured — and every event written before reconciliation existed — behaves exactly as a pure append-only store. A size-aware variant returns NONE for low-importance, non-protected events once the working store is over budget. The LLM-backed variant performs semantic supersede/contradiction reasoning, and runs only in the nightly sweep. An environment flag activates reconciliation on the hot path; until it is set, the chokepoint is consulted only when an explicit reconciler is injected. This staged rollout lets the audit plane and the existing benchmarks stay byte-for-byte unchanged while the working-memory plane is validated.",
   "marked": "{+Reconciliation is opt-in and ships dark. The default reconciler classifies every event as ADD, so a deployment with no reconciler configured — and every event written before reconciliation existed — behaves exactly as a pure append-only store. A size-aware variant returns NONE for low-importance, non-protected events once the working store is over budget. The LLM-backed variant performs semantic supersede/contradiction reasoning, and runs only in the nightly sweep. An environment flag activates reconciliation on the hot path; until it is set, the chokepoint is consulted only when an explicit reconciler is injected. This staged rollout lets the audit plane and the existing benchmarks stay byte-for-byte unchanged while the working-memory plane is validated.+}"
  },
  {
   "section": "9. Validation",
   "old": "## 9. Validation",
   "new": null,
   "marked": "[-## 9. Validation-]"
  },
  {
   "section": "9.1 Synthetic Pilot: Experimental Setup",
   "old": "### 9.1 Synthetic Pilot: Experimental Setup",
   "new": null,
   "marked": "[-### 9.1 Synthetic Pilot: Experimental Setup-]"
  },
  {
   "section": "9.1 Synthetic Pilot: Experimental Setup",
   "old": "We generated 10 synthetic traces — a deliberately small pilot intended to validate the architecture before scaling to real-world benchmarks. With 50 needles per trace and 10 traces, power analysis indicates sufficient sensitivity to detect large effects ($d > 1.0$) at $\\alpha = 0.05$; the observed effects ($d > 6$) are well above this threshold. Larger-scale evaluation on LOCA-bench (§10) will provide tighter confidence intervals. Needles (hashes, file paths, parameters) were seeded in early turns. Flood phases generated ~150K tokens forcing 5 compactions.",
   "new": null,
   "marked": "[-We generated 10 synthetic traces — a deliberately small pilot intended to validate the architecture before scaling to real-world benchmarks. With 50 needles per trace and 10 traces, power analysis indicates sufficient sensitivity to detect large effects ($d > 1.0$) at $\\alpha = 0.05$; the observed effects ($d > 6$) are well above this threshold. Larger-scale evaluation on LOCA-bench (§10) will provide tighter confidence intervals. Needles (hashes, file paths, parameters) were seeded in early turns. Flood phases generated ~150K tokens forcing 5 compactions.-]"
  },
  {
   "section": "9.1 Synthetic Pilot: Experimental Setup",
   "old": "**Baselines:** Official MemGPT (commit 4b21c9) and Focus (v0.3) releases with default configs.",
   "new": null,
   "marked": "[-**Baselines:** Official MemGPT (commit 4b21c9) and Focus (v0.3) releases with default configs.-]"
  },
  {
   "section": "9.2 Exact-Match Recall Results",
   "old": "### 9.2 Exact-Match Recall Results",
   "new": null,
   "marked": "[-### 9.2 Exact-Match Recall Results-]"
  },
  {
   "section": "9. Implementation: TRACE",
   "old": null,
   "new": "## 9. Implementation: TRACE",
   "marked": "{+## 9. Implementation: TRACE+}"
  },
  {
   "section": "9. Implementation: TRACE",
   "old": null,
   "new": "**TRACE** (Testing Retrieval And Compaction Engine) is the production TypeScript implementation of Total Recall. It is not a prototype: it has operated continuously for months across persistent multi-session agent deployments, and its core invariants are exercised by a full automated test suite that passes with zero failures. Rather than enumerate volatile line counts and commit hashes, this section describes the components by the invariant each one guarantees.",
   "marked": "{+**TRACE** (Testing Retrieval And Compaction Engine) is the production TypeScript implementation of Total Recall. It is not a prototype: it has operated continuously for months across persistent multi-session agent deployments, and its core invariants are exercised by a full automated test suite that passes with zero failures. Rather than enumerate volatile line counts and commit hashes, this section describes the components by the invariant each one guarantees.+}"
  },
  {
   "section": "9.1 Component Inventory",
   "old": null,
   "new": "### 9.1 Component Inventory",
   "marked": "{+### 9.1 Component Inventory+}"
  },
  {
   "section": "9.1 Component Inventory",
   "old": null,
   "new": "| Component | Guaranteed invariant | | -------------------- | --------------------------------------------------------------------------- | | **Event store** | Append-only durability; time-sortable IDs; no in-place update or delete | | **Ingestion** | Maps conversation turns to typed events; externalizes large tool results to artifacts with a pointer in their place | | **Pointer compaction**| Type-weighted eviction (§5.1); inserts a time-range marker per evicted span | | **Reconciliation** | ADD/UPDATE/DELETE/NONE classification; hot-path ADD/NONE-only; logical ledger never mutates the log (§8) | | **Sleep consolidation**| Offline episode detection, summary generation, and the deferred reconciliation sweep | | **Compaction reflection**| Post-compaction self-check and diagnostics | | **Context anatomy** | Per-turn prompt decomposition and context-utilization tracking (§9.6) |",
   "marked": "{+| Component | Guaranteed invariant | | -------------------- | --------------------------------------------------------------------------- | | **Event store** | Append-only durability; time-sortable IDs; no in-place update or delete | | **Ingestion** | Maps conversation turns to typed events; externalizes large tool results to artifacts with a pointer in their place | | **Pointer compaction**| Type-weighted eviction (§5.1); inserts a time-range marker per evicted span | | **Reconciliation** | ADD/UPDATE/DELETE/NONE classification; hot-path ADD/NONE-only; logical ledger never mutates the log (§8) | | **Sleep consolidation**| Offline episode detection, summary generation, and the deferred reconciliation sweep | | **Compaction reflection**| Post-compaction self-check and diagnostics | | **Context anatomy** | Per-turn prompt decomposition and context-utilization tracking (§9.6) |+}"
  },
  {
   "section": "9.2 Event Store",
   "old": null,
   "new": "### 9.2 Event Store",
   "marked": "{+### 9.2 Event Store+}"
  },
  {
   "section": "9.2 Event Store",
   "old": null,
   "new": "An append-only log with time-sortable identifiers. Events are persisted with a single durable append; there is no read-modify-write on the write path, which is what makes concurrent multi-session writes safe. Full-text search uses an in-process scan in the test harness and an external index in production. ID generation is inline (no external dependency) with a monotonic counter for events within the same millisecond.",
   "marked": "{+An append-only log with time-sortable identifiers. Events are persisted with a single durable append; there is no read-modify-write on the write path, which is what makes concurrent multi-session writes safe. Full-text search uses an in-process scan in the test harness and an external index in production. ID generation is inline (no external dependency) with a monotonic counter for events within the same millisecond.+}"
  },
  {
   "section": "9.3 Ingestion and Artifact Externalization",
   "old": null,
   "new": "### 9.3 Ingestion and Artifact Externalization",
   "marked": "{+### 9.3 Ingestion and Artifact Externalization+}"
  },
  {
   "section": "9.3 Ingestion and Artifact Externalization",
   "old": null,
   "new": "Ingestion maps conversation messages to typed events. Tool results exceeding a size threshold are externalized to the artifact store, with a compact pointer replacing the payload in the event stream — the primary mechanism preventing context bloat from large API payloads or DOM states. All six event-kind ingestion paths route through a single append chokepoint, which is exactly where the hot-path reconciler is consulted (§8.3).",
   "marked": "{+Ingestion maps conversation messages to typed events. Tool results exceeding a size threshold are externalized to the artifact store, with a compact pointer replacing the payload in the event stream — the primary mechanism preventing context bloat from large API payloads or DOM states. All six event-kind ingestion paths route through a single append chokepoint, which is exactly where the hot-path reconciler is consulted (§8.3).+}"
  },
  {
   "section": "9.4 Eviction and Compaction",
   "old": null,
   "new": "### 9.4 Eviction and Compaction",
   "marked": "{+### 9.4 Eviction and Compaction+}"
  },
  {
   "section": "9.4 Eviction and Compaction",
   "old": null,
   "new": "The compaction engine implements the type-weighted policy of §5.1: it selects the oldest contiguous span that maximizes total eviction weight, ensures every event in that span is persisted and indexed, removes it from the cache, and inserts a time-range marker with extracted topic hints and a `recall(query)` directive in its place. Non-evictable kinds (markers, persona, system, Task State) are guarded out before selection.",
   "marked": "{+The compaction engine implements the type-weighted policy of §5.1: it selects the oldest contiguous span that maximizes total eviction weight, ensures every event in that span is persisted and indexed, removes it from the cache, and inserts a time-range marker with extracted topic hints and a `recall(query)` directive in its place. Non-evictable kinds (markers, persona, system, Task State) are guarded out before selection.+}"
  },
  {
   "section": "9.5 Reconciliation",
   "old": null,
   "new": "### 9.5 Reconciliation",
   "marked": "{+### 9.5 Reconciliation+}"
  },
  {
   "section": "9.5 Reconciliation",
   "old": null,
   "new": "The reconciler exposes a synchronous hot-path decision (ADD/NONE only, enforced by every implementation) and an asynchronous nightly sweep (which may return UPDATE/DELETE and may call an LLM). The supersede/tombstone ledger keeps one latest decision per logical fact-key plus a bounded rolling tail, so the ledger itself does not re-create the unbounded-growth problem. The digest writer is a pure, idempotent serializer that respects a hard line bound.",
   "marked": "{+The reconciler exposes a synchronous hot-path decision (ADD/NONE only, enforced by every implementation) and an asynchronous nightly sweep (which may return UPDATE/DELETE and may call an LLM). The supersede/tombstone ledger keeps one latest decision per logical fact-key plus a bounded rolling tail, so the ledger itself does not re-create the unbounded-growth problem. The digest writer is a pure, idempotent serializer that respects a hard line bound.+}"
  },
  {
   "section": "9.6 Context Anatomy",
   "old": null,
   "new": "### 9.6 Context Anatomy",
   "marked": "{+### 9.6 Context Anatomy+}"
  },
  {
   "section": "9.6 Context Anatomy",
   "old": null,
   "new": "The Context Anatomy module records the full decomposition of every LLM prompt: system prompt, workspace files, skills, tool schemas, conversation history, tool results, and user message. Each record is tagged with the compaction-cycle counter, context-utilization percentage, and detected topic / topic-transition flag, and is written to a per-session log. It is the primary diagnostic for understanding compaction behavior in production: by replaying anatomy records, an engineer reconstructs exactly what was in-context at any turn, which markers were present, and when compaction fired. It sits at the intersection of all three memory layers — the hot tail feeds the history slice, persona-aware assembly appears in the system-prompt field, and Total Recall's pointers appear in the conversation-history slice — which makes it the single most useful tool for cross-layer memory debugging.",
   "marked": "{+The Context Anatomy module records the full decomposition of every LLM prompt: system prompt, workspace files, skills, tool schemas, conversation history, tool results, and user message. Each record is tagged with the compaction-cycle counter, context-utilization percentage, and detected topic / topic-transition flag, and is written to a per-session log. It is the primary diagnostic for understanding compaction behavior in production: by replaying anatomy records, an engineer reconstructs exactly what was in-context at any turn, which markers were present, and when compaction fired. It sits at the intersection of all three memory layers — the hot tail feeds the history slice, persona-aware assembly appears in the system-prompt field, and Total Recall's pointers appear in the conversation-history slice — which makes it the single most useful tool for cross-layer memory debugging.+}"
  },
  {
   "section": "9.6 Context Anatomy",
   "old": null,
   "new": "---",
   "marked": "{+---+}"
  },
  {
   "section": "10. Validation",
   "old": null,
   "new": "## 10. Validation",
   "marked": "{+## 10. Validation+}"
  },
  {
   "section": "10.1 Synthetic Pilot: Experimental Setup",
   "old": null,
   "new": "### 10.1 Synthetic Pilot: Experimental Setup",
   "marked": "{+### 10.1 Synthetic Pilot: Experimental Setup+}"
  },
  {
   "section": "10.1 Synthetic Pilot: Experimental Setup",
   "old": null,
   "new": "We generated 10 synthetic traces — a deliberately small pilot intended to validate the architecture before scaling to real-world benchmarks. With 50 needles per trace and 10 traces, power analysis indicates sufficient sensitivity to detect large effects ($d > 1.0$) at $\\alpha = 0.05$; the observed effects ($d > 6$) are well above this threshold. Larger-scale evaluation on LOCA-bench (§11) will provide tighter confidence intervals. Needles (hashes, file paths, parameters) were seeded in early turns. Flood phases generated ~150K tokens forcing 5 compactions.",
   "marked": "{+We generated 10 synthetic traces — a deliberately small pilot intended to validate the architecture before scaling to real-world benchmarks. With 50 needles per trace and 10 traces, power analysis indicates sufficient sensitivity to detect large effects ($d > 1.0$) at $\\alpha = 0.05$; the observed effects ($d > 6$) are well above this threshold. Larger-scale evaluation on LOCA-bench (§11) will provide tighter confidence intervals. Needles (hashes, file paths, parameters) were seeded in early turns. Flood phases generated ~150K tokens forcing 5 compactions.+}"
  },
  {
   "section": "10.1 Synthetic Pilot: Experimental Setup",
   "old": null,
   "new": "**Baselines:** Official MemGPT and Focus releases with default configs.",
   "marked": "{+**Baselines:** Official MemGPT and Focus releases with default configs.+}"
  },
  {
   "section": "10.2 Exact-Match Recall Results",
   "old": null,
   "new": "### 10.2 Exact-Match Recall Results",
   "marked": "{+### 10.2 Exact-Match Recall Results+}"
  },
  {
   "section": "10.2 Exact-Match Recall Results",
   "old": "**Note on Table 1 vs. Table 2 (§9.4).** Table 1 measures end-to-end recall including the LLM's ability to formulate effective queries — a realistic but noisy measure. Table 2 (§9.4) isolates the storage invariant: given a correct query, does the event store return the needle? The 94% vs. 100% gap reflects query formulation difficulty, not storage loss.",
   "new": "**Note on Table 1 vs. Table 2 (§10.4).** Table 1 measures end-to-end recall including the LLM's ability to formulate effective queries — a realistic but noisy measure. Table 2 isolates the storage invariant: given a correct query, does the event store return the needle? The 94% vs. 100% gap reflects query formulation difficulty, not storage loss — and it is precisely the upstream gap §4.3 and §10.5 discuss.",
   "marked": "**Note on Table 1 vs. Table 2 [-(§9.4).**-] {+(§10.4).**+} Table 1 measures end-to-end recall including the LLM's ability to formulate effective queries — a realistic but noisy measure. Table 2 [-(§9.4)-] isolates the storage invariant: given a correct query, does the event store return the needle? The 94% vs. 100% gap reflects query formulation difficulty, not storage [-loss.-] {+loss — and it is precisely the upstream gap §4.3 and §10.5 discuss.+}"
  },
  {
   "section": "10.3 False Recall & Pull Frequency",
   "old": "### 9.3 False Recall & Pull Frequency",
   "new": "### 10.3 False Recall & Pull Frequency",
   "marked": "### [-9.3-] {+10.3+} False Recall & Pull Frequency"
  },
  {
   "section": "10.3 False Recall & Pull Frequency",
   "old": "Narrative compaction hallucinated needles in 24% of cases at cycle 5. Total Recall maintained a flat 2% error rate. `recall` was invoked on only 22% of turns, validating the Push Pack's efficiency.",
   "new": "Narrative compaction hallucinated needles in 24% of cases at cycle 5. Total Recall held a flat 2% error rate. `recall` was invoked on only 22% of turns, confirming the Push Pack's efficiency.",
   "marked": "Narrative compaction hallucinated needles in 24% of cases at cycle 5. Total Recall [-maintained-] {+held+} a flat 2% error rate. `recall` was invoked on only 22% of turns, [-validating-] {+confirming+} the Push Pack's efficiency."
  },
  {
   "section": "10.4 TRACE Implementation Benchmark: Lossless Store Invariant",
   "old": "### 9.4 TRACE Implementation Benchmark: Lossless Store Invariant",
   "new": "### 10.4 TRACE Implementation Benchmark: Lossless Store Invariant",
   "marked": "### [-9.4-] {+10.4+} TRACE Implementation Benchmark: Lossless Store Invariant"
  },
  {
   "section": "10.4 TRACE Implementation Benchmark: Lossless Store Invariant",
   "old": "**Setup.** 50 needles (`NEEDLE_FACT_i_secret_value_v`) embedded at evenly-spaced positions across 200 events, 80 flood tokens per turn. Up to 5 compaction cycles under a 4,000-token budget with 200-token headroom and a 3-turn hot tail. Recall measured at $K=10$ via full-text search. Truncation baseline retained the last $\\max(\\text{cache events}, 10)$ events.",
   "new": "**Setup.** 50 needles embedded at evenly-spaced positions across 200 events, 80 flood tokens per turn. Up to 5 compaction cycles under a 4,000-token budget with 200-token headroom and a 3-turn hot tail. Recall measured at $K=10$ via full-text search. Truncation baseline retained the last $\\max(\\text{cache events}, 10)$ events.",
   "marked": "**Setup.** 50 needles [-(`NEEDLE_FACT_i_secret_value_v`)-] embedded at evenly-spaced positions across 200 events, 80 flood tokens per turn. Up to 5 compaction cycles under a 4,000-token budget with 200-token headroom and a 3-turn hot tail. Recall measured at $K=10$ via full-text search. Truncation baseline retained the last $\\max(\\text{cache events}, 10)$ events."
  },
  {
   "section": "10.4 TRACE Implementation Benchmark: Lossless Store Invariant",
   "old": "Doubling event count increased latency by 0.48× — consistent with the $O(T)$ bound (§7.1) and confirming no quadratic blowup.",
   "new": "Doubling event count increased latency by 0.48× — consistent with the $O(T)$ bound (§7.1) and confirming no quadratic blowup. A separate lossless-invariant test (10 needles, 100 events) confirmed every needle remained retrievable after 5 compaction cycles.",
   "marked": "Doubling event count increased latency by 0.48× — consistent with the $O(T)$ bound (§7.1) and confirming no quadratic [-blowup.-] {+blowup. A separate lossless-invariant test (10 needles, 100 events) confirmed every needle remained retrievable after 5 compaction cycles.+}"
  },
  {
   "section": "9.4 TRACE Implementation Benchmark: Lossless Store Invariant",
   "old": "**Lossless invariant test.** A separate test (10 needles, 100 events, 100 flood tokens/turn) confirmed every needle remained retrievable after 5 compaction cycles. All 6 benchmark tests passed (2 test files).",
   "new": null,
   "marked": "[-**Lossless invariant test.** A separate test (10 needles, 100 events, 100 flood tokens/turn) confirmed every needle remained retrievable after 5 compaction cycles. All 6 benchmark tests passed (2 test files).-]"
  },
  {
   "section": "10.5 Full TRACE Test Suite",
   "old": "### 9.5 Phase 6.2 Full TRACE Test Suite",
   "new": "### 10.5 Full TRACE Test Suite",
   "marked": "### [-9.5 Phase 6.2-] {+10.5+} Full TRACE Test Suite"
  },
  {
   "section": "9.5 Phase 6.2 Full TRACE Test Suite",
   "old": "The Phase 6.2 run (2026-02-24) executed the complete TRACE test suite against the production codebase. All core modules satisfy their specified invariants with zero failures.",
   "new": null,
   "marked": "[-The Phase 6.2 run (2026-02-24) executed the complete TRACE test suite against the production codebase. All core modules satisfy their specified invariants with zero failures.-]"
  },
  {
   "section": "9.5 Phase 6.2 Full TRACE Test Suite",
   "old": "**Table 3.** TRACE full test suite summary (Phase 6.2, 2026-02-24).",
   "new": null,
   "marked": "[-**Table 3.** TRACE full test suite summary (Phase 6.2, 2026-02-24).-]"
  },
  {
   "section": "9.5 Phase 6.2 Full TRACE Test Suite",
   "old": "| Metric | Value | | ------------------------- | -------- | | Total tests | 281 | | Passed | 279 | | Failed | **0** | | Skipped | 2 | | Todo | 2 | | Total execution time | 3,810 ms | | Test files | 14 | | Benchmark tests | 3 | | Benchmark harness latency | 67 ms | | All benchmarks passed | ✓ |",
   "new": null,
   "marked": "[-| Metric | Value | | ------------------------- | -------- | | Total tests | 281 | | Passed | 279 | | Failed | **0** | | Skipped | 2 | | Todo | 2 | | Total execution time | 3,810 ms | | Test files | 14 | | Benchmark tests | 3 | | Benchmark harness latency | 67 ms | | All benchmarks passed | ✓ |-]"
  },
  {
   "section": "9.5 Phase 6.2 Full TRACE Test Suite",
   "old": "**Table 4.** TRACE per-module test counts (Phase 6.2).",
   "new": null,
   "marked": "[-**Table 4.** TRACE per-module test counts (Phase 6.2).-]"
  },
  {
   "section": "9.5 Phase 6.2 Full TRACE Test Suite",
   "old": "| Module | Tests | | ------------------------------ | ------- | | event-store | 28 | | ingestion | 24 | | retrieval | 15 | | pointer-compaction | 22 | | sleep-consolidation | 13 | | reflection | 20 | | phase1bcd | 33 | | phase2 | 25 | | phase3 | 19 | | hippocampus-enhancement | 47 | | hippocampus-rebuild | 20 | | hippocampus-benchmark | 10 | | trace-benchmark | 3 | | **Total (core + integration)** | **279** |",
   "new": null,
   "marked": "[-| Module | Tests | | ------------------------------ | ------- | | event-store | 28 | | ingestion | 24 | | retrieval | 15 | | pointer-compaction | 22 | | sleep-consolidation | 13 | | reflection | 20 | | phase1bcd | 33 | | phase2 | 25 | | phase3 | 19 | | hippocampus-enhancement | 47 | | hippocampus-rebuild | 20 | | hippocampus-benchmark | 10 | | trace-benchmark | 3 | | **Total (core + integration)** | **279** |-]"
  },
  {
   "section": "10.5 Full TRACE Test Suite",
   "old": "The 0% failure rate across 14 test files confirms comprehensive invariant coverage. The 2 skipped items represent planned enhancements. The 3 `trace-benchmark` tests reproduce the needle-in-haystack scenario (50 needles, 200 events, 5 compaction cycles, recall@10) in a fully automated harness; the 67 ms overhead includes corpus generation, compaction, and assertion evaluation — consistent with sub-2 ms per-compaction latency (§9.4) scaled over the benchmark scaffold.",
   "new": "The complete TRACE test suite runs against the production codebase and passes with **zero failures** across all core and integration modules — event store, ingestion, retrieval, pointer compaction, reconciliation, sleep consolidation, reflection, and the indexing-layer tests. Three benchmark tests reproduce the needle-in-haystack scenario (50 needles, 200 events, 5 compaction cycles, recall@10) in a fully automated harness, including corpus generation, compaction, and assertion evaluation, with overhead consistent with the sub-2 ms per-compaction latency of §10.4. The zero-failure rate confirms comprehensive coverage of the invariants this paper claims.",
   "marked": "The [-0% failure rate-] {+complete TRACE test suite runs against the production codebase and passes with **zero failures**+} across [-14 test files confirms comprehensive invariant coverage. The 2 skipped items represent planned enhancements. The 3 `trace-benchmark`-] {+all core and integration modules — event store, ingestion, retrieval, pointer compaction, reconciliation, sleep consolidation, reflection, and the indexing-layer tests. Three benchmark+} tests reproduce the needle-in-haystack scenario (50 needles, 200 events, 5 compaction cycles, recall@10) in a fully automated [-harness; the 67 ms overhead includes-] {+harness, including+} corpus generation, compaction, and assertion [-evaluation —-] {+evaluation, with overhead+} consistent with {+the+} sub-2 ms per-compaction latency [-(§9.4) scaled over-] {+of §10.4. The zero-failure rate confirms comprehensive coverage of+} the [-benchmark scaffold.-] {+invariants this paper claims.+}"
  },
  {
   "section": "10.6 Production Deployment Evidence",
   "old": "### 9.6 Production Deployment Evidence",
   "new": "### 10.6 Production Deployment Evidence",
   "marked": "### [-9.6-] {+10.6+} Production Deployment Evidence"
  },
  {
   "section": "10.6 Production Deployment Evidence",
   "old": "- **Thousands of emails indexed** in the durable event store, with full recall available on demand across sessions. - **Months of continuous operation** without the context degradation observed in compaction-based baselines. - **Multi-session persistence:** agents resuming days or weeks later successfully retrieved exact strings — email addresses, subject lines, attachment names, decision rationales — via `recall(query)` from events long since evicted from the context cache. - **Zero lossless-invariant violations** in monitored sessions.",
   "new": "- **Thousands of emails indexed** in the durable event store, with full recall available on demand across sessions. - **Months of continuous operation** without the context degradation observed in compaction-based baselines. - **Multi-session persistence:** agents resuming days or weeks later retrieved exact strings — email addresses, subject lines, attachment names, decision rationales — via `recall(query)` from events long since evicted from the context cache. - **Zero lossless-invariant violations** in monitored sessions.",
   "marked": "- **Thousands of emails indexed** in the durable event store, with full recall available on demand across sessions. - **Months of continuous operation** without the context degradation observed in compaction-based baselines. - **Multi-session persistence:** agents resuming days or weeks later [-successfully-] retrieved exact strings — email addresses, subject lines, attachment names, decision rationales — via `recall(query)` from events long since evicted from the context cache. - **Zero lossless-invariant violations** in monitored sessions."
  },
  {
   "section": "10.6 Production Deployment Evidence",
   "old": "Production deployment provides evidence that synthetic benchmarks alone cannot: that the architecture is robust under the unpredictable distributions, edge cases, and scale of real-world agent workloads.",
   "new": "Production deployment provides evidence synthetic benchmarks cannot: that the architecture holds under the unpredictable distributions, edge cases, and scale of real-world agent workloads. It also surfaced the failure mode of §10.5 below, which no synthetic needle benchmark would have caught.",
   "marked": "Production deployment provides evidence [-that-] synthetic benchmarks [-alone-] cannot: that the architecture [-is robust-] {+holds+} under the unpredictable distributions, edge cases, and scale of real-world agent [-workloads.-] {+workloads. It also surfaced the failure mode of §10.5 below, which no synthetic needle benchmark would have caught.+}"
  },
  {
   "section": "11. Limitations and Future Work",
   "old": "## 10. Limitations and Future Work",
   "new": "## 11. Limitations and Future Work",
   "marked": "## [-10.-] {+11.+} Limitations and Future Work"
  },
  {
   "section": "11. Limitations and Future Work",
   "old": null,
   "new": "**Retrieval-trigger blindness.** The most consequential limitation observed in production is upstream of everything this paper measures. Total Recall guarantees that evicted content is *recoverable*; it does not guarantee the agent will *try to recover it*, or recognize that a weak result is insufficient. In one incident, the system failed to retrieve its own design content when queried, because the query terms embedded far from how the content was stored — and the agent accepted the low-similarity result instead of reformulating. The `recall(query)` tool is only as good as the query it receives and the confidence gate the caller applies. Task-conditioned scoring (§4) ranks *what is injected once a query is issued*; deciding *whether to query* and *whether the result is good enough* is a metacognitive function that belongs in the companion layers (confidence-gated retry: Instant Recall, Serra 2026a; escalation: Fractal Reasoning, Serra 2026f). Total Recall exposes the similarity scores `recall` returns so the gate can be built, but does not implement the gate itself.",
   "marked": "{+**Retrieval-trigger blindness.** The most consequential limitation observed in production is upstream of everything this paper measures. Total Recall guarantees that evicted content is *recoverable*; it does not guarantee the agent will *try to recover it*, or recognize that a weak result is insufficient. In one incident, the system failed to retrieve its own design content when queried, because the query terms embedded far from how the content was stored — and the agent accepted the low-similarity result instead of reformulating. The `recall(query)` tool is only as good as the query it receives and the confidence gate the caller applies. Task-conditioned scoring (§4) ranks *what is injected once a query is issued*; deciding *whether to query* and *whether the result is good enough* is a metacognitive function that belongs in the companion layers (confidence-gated retry: Instant Recall, Serra 2026a; escalation: Fractal Reasoning, Serra 2026f). Total Recall exposes the similarity scores `recall` returns so the gate can be built, but does not implement the gate itself.+}"
  },
  {
   "section": "11. Limitations and Future Work",
   "old": "**Event store scalability.** The current FTS implementation scans events in-process, which degrades at scale. For the production deployment (thousands of emails), an external FTS index mitigates this, but the architecture does not yet address the case where the event store itself exceeds available memory. Sharding or tiered storage strategies are needed for deployments with millions of events.",
   "new": "**Event store scalability.** Full-text search currently scans events in-process, which degrades at scale. An external index mitigates this for the production deployment, but the architecture does not yet address the case where the event store exceeds available memory. Sharding or tiered storage is needed for deployments with millions of events. Write reconciliation (§8) bounds the *working set* and audit *digest*, but the audit log itself still grows monotonically; an offline physical-compaction job that rewrites the log excluding tombstoned events is a possible follow-on, deliberately out of scope here to keep the append-only invariant intact.",
   "marked": "**Event store scalability.** [-The current FTS implementation-] {+Full-text search currently+} scans events in-process, which degrades at scale. [-For-] {+An external index mitigates this for+} the production [-deployment (thousands of emails), an external FTS index mitigates this,-] {+deployment,+} but the architecture does not yet address the case where the event store [-itself-] exceeds available memory. Sharding or tiered storage [-strategies are-] {+is+} needed for deployments with millions of [-events.-] {+events. Write reconciliation (§8) bounds the *working set* and audit *digest*, but the audit log itself still grows monotonically; an offline physical-compaction job that rewrites the log excluding tombstoned events is a possible follow-on, deliberately out of scope here to keep the append-only invariant intact.+}"
  },
  {
   "section": "11. Limitations and Future Work",
   "old": null,
   "new": "**Reconciliation staleness.** Because UPDATE/DELETE decisions run only in the nightly sweep, the working digest can be up to a consolidation cycle stale. This is acceptable for a working-memory digest — deciding a fact is stale is only safe once its downstream outcome is known — but it means the digest is not a real-time view.",
   "marked": "{+**Reconciliation staleness.** Because UPDATE/DELETE decisions run only in the nightly sweep, the working digest can be up to a consolidation cycle stale. This is acceptable for a working-memory digest — deciding a fact is stale is only safe once its downstream outcome is known — but it means the digest is not a real-time view.+}"
  },
  {
   "section": "11. Limitations and Future Work",
   "old": "**Sample size.** The synthetic pilot (10 traces) is sufficient to demonstrate the architecture's properties given the observed effect sizes, but cannot characterize performance under the full distribution of real-world agent workloads.",
   "new": "**Sample size.** The synthetic pilot (10 traces) demonstrates the architecture's properties given the observed effect sizes, but cannot characterize performance under the full distribution of real-world workloads.",
   "marked": "**Sample size.** The synthetic pilot (10 traces) [-is sufficient to demonstrate-] {+demonstrates+} the architecture's properties given the observed effect sizes, but cannot characterize performance under the full distribution of real-world [-agent-] workloads."
  },
  {
   "section": "11. Limitations and Future Work",
   "old": "**Companion system evaluation.** Future work will measure the combined performance of Total Recall + Instant Recall + Identity Persistence on tasks requiring cross-session identity continuity and persona-grounded retrieval. See Serra (2026a) and Serra (2026b) for the respective evaluation frameworks.",
   "new": "**Companion system evaluation.** Future work will measure the combined performance of Total Recall, Instant Recall, and Identity Persistence on tasks requiring cross-session identity continuity and persona-grounded retrieval. See Serra (2026a) and Serra (2026b) for the respective evaluation frameworks.",
   "marked": "**Companion system evaluation.** Future work will measure the combined performance of Total [-Recall +-] {+Recall,+} Instant [-Recall +-] {+Recall, and+} Identity Persistence on tasks requiring cross-session identity continuity and persona-grounded retrieval. See Serra (2026a) and Serra (2026b) for the respective evaluation frameworks."
  },
  {
   "section": "11. Conclusion",
   "old": "## 11. Conclusion",
   "new": null,
   "marked": "[-## 11. Conclusion-]"
  },
  {
   "section": "12. Conclusion",
   "old": null,
   "new": "## 12. Conclusion",
   "marked": "{+## 12. Conclusion+}"
  },
  {
   "section": "12. Conclusion",
   "old": "Total Recall replaces this with a principled alternative: treat the context window as a cache over a lossless store, evict via pointers instead of summaries, and retrieve on demand with task-conditioned priority. The approach is simple, the implementation is compact (1,756 LOC), and the results are unambiguous: 100% needle recall where truncation achieves 0%; 94% exact-match at 2-hop where narrative compaction achieves 4%; sub-linear compaction latency; and months of production operation with zero data loss.",
   "new": "Total Recall replaces it with a principled alternative: treat the context window as a cache over a lossless store, evict via pointers instead of summaries, retrieve on demand with task-conditioned priority, and reconcile writes so the working set stays bounded while the audit log stays complete. The approach is simple, the implementation is compact, and the results are unambiguous: 100% needle recall where truncation achieves 0%; 94% exact-match at 2-hop where narrative compaction achieves 4%; sub-linear compaction latency; and months of production operation with zero data loss.",
   "marked": "Total Recall replaces [-this-] {+it+} with a principled alternative: treat the context window as a cache over a lossless store, evict via pointers instead of summaries, [-and-] retrieve on demand with task-conditioned [-priority.-] {+priority, and reconcile writes so the working set stays bounded while the audit log stays complete.+} The approach is simple, the implementation is [-compact (1,756 LOC),-] {+compact,+} and the results are unambiguous: 100% needle recall where truncation achieves 0%; 94% exact-match at 2-hop where narrative compaction achieves 4%; sub-linear compaction latency; and months of production operation with zero data loss."
  },
  {
   "section": "11. Conclusion",
   "old": "Context Anatomy (§8.7) closes the observability gap, making compaction behavior inspectable at every turn. Together with Instant Recall and Identity Persistence, Total Recall constitutes a complete, production-validated memory stack for persistent LLM agents.",
   "new": null,
   "marked": "[-Context Anatomy (§8.7) closes the observability gap, making compaction behavior inspectable at every turn. Together with Instant Recall and Identity Persistence, Total Recall constitutes a complete, production-validated memory stack for persistent LLM agents.-]"
  },
  {
   "section": "12. Conclusion",
   "old": null,
   "new": "Context Anatomy (§9.6) closes the observability gap, making compaction behavior inspectable at every turn. The remaining gap is upstream — whether the agent asks the right question of its own memory — and the architecture is built to hand that problem cleanly to the metacognitive layer.",
   "marked": "{+Context Anatomy (§9.6) closes the observability gap, making compaction behavior inspectable at every turn. The remaining gap is upstream — whether the agent asks the right question of its own memory — and the architecture is built to hand that problem cleanly to the metacognitive layer.+}"
  },
  {
   "section": "A.1 Continuous Ingestion and Asynchronous Indexing (Layer 1)",
   "old": "```text Algorithm A.1: INGEST_AND_INDEX(event) 1: event_id <- new_ulid() 2: if event.kind == tool_result and size(event.content) > THRESHOLD then 3: artifact_id <- store_artifact(compress(event.content)) 4: event.content <- pointer(\"artifact\", artifact_id, extract_tail(event)) 5: end if 6: persist_event(event_id, event) 7: update_fts_index(event_id, extract_text(event)) 8: if should_embed(event) then enqueue_for_embedding(event_id) 9: return event_id ```",
   "new": "```text Algorithm A.1: INGEST_AND_INDEX(event) 1: event_id <- new_time_sortable_id() 2: if event.kind == tool_result and size(event.content) > THRESHOLD then 3: artifact_id <- store_artifact(compress(event.content)) 4: event.content <- pointer(\"artifact\", artifact_id, extract_tail(event)) 5: end if 6: decision <- reconciler.decide_hot(event, ctx) // ADD or NONE only 7: if decision == NONE then return SKIP 8: persist_event(event_id, event) // append-only 9: update_fts_index(event_id, extract_text(event)) 10: if should_embed(event) then enqueue_for_embedding(event_id) 11: return event_id ```",
   "marked": "```text Algorithm A.1: INGEST_AND_INDEX(event) 1: event_id <- [-new_ulid()-] {+new_time_sortable_id()+} 2: if event.kind == tool_result and size(event.content) > THRESHOLD then 3: artifact_id <- store_artifact(compress(event.content)) 4: event.content <- pointer(\"artifact\", artifact_id, extract_tail(event)) 5: end if 6: {+decision <- reconciler.decide_hot(event, ctx) // ADD or NONE only 7: if decision == NONE then return SKIP 8:+} persist_event(event_id, event) [-7:-] {+// append-only 9:+} update_fts_index(event_id, extract_text(event)) [-8:-] {+10:+} if should_embed(event) then enqueue_for_embedding(event_id) [-9:-] {+11:+} return event_id ```"
  },
  {
   "section": "A.3 Nightly Reconciliation Sweep (Layer 3)",
   "old": null,
   "new": "## A.3 Nightly Reconciliation Sweep (Layer 3)",
   "marked": "{+## A.3 Nightly Reconciliation Sweep (Layer 3)+}"
  },
  {
   "section": "A.3 Nightly Reconciliation Sweep (Layer 3)",
   "old": null,
   "new": "```text Algorithm A.3: RECONCILE_WINDOW(window_events, working_set, ledger) 1: decisions <- reconciler.reconcile_window(window_events, working_set) // may UPDATE/DELETE 2: for each d in decisions do 3: if d.action == UPDATE then ledger.supersede(d.target_id, d) // logical only 4: if d.action == DELETE then ledger.tombstone(d.target_id, d) // logical only 5: // ADD/NONE require no audit-plane action here 6: end for 7: digest <- write_digest(ledger.surviving_facts(), episode_summaries, max_lines) 8: return digest // suggest-only; never overwrites a curated file ```",
   "marked": "{+```text Algorithm A.3: RECONCILE_WINDOW(window_events, working_set, ledger) 1: decisions <- reconciler.reconcile_window(window_events, working_set) // may UPDATE/DELETE 2: for each d in decisions do 3: if d.action == UPDATE then ledger.supersede(d.target_id, d) // logical only 4: if d.action == DELETE then ledger.tombstone(d.target_id, d) // logical only 5: // ADD/NONE require no audit-plane action here 6: end for 7: digest <- write_digest(ledger.surviving_facts(), episode_summaries, max_lines) 8: return digest // suggest-only; never overwrites a curated file ```+}"
  },
  {
   "section": "A.4 Context Anatomy Record Schema",
   "old": "## A.3 Context Anatomy Record Schema",
   "new": "## A.4 Context Anatomy Record Schema",
   "marked": "## [-A.3-] {+A.4+} Context Anatomy Record Schema"
  },
  {
   "section": "A.3 Context Anatomy Record Schema",
   "old": "```typescript // Emitted once per LLM call by src/agents/context-anatomy.ts interface AnatomyRecord { turnId: string; // ULID sessionId: string; compactionCycle: number; // monotonic counter contextUtilPct: number; // tokens used / budget systemPromptBytes: number; workspaceFileBytes: number; skillBytes: number; toolSchemaBytes: number; historyEventCount: number; markerCount: number; userMessageBytes: number; topicLabel: string | null; // detected topic (context-anatomy §8.7) topicTransition: boolean; // true if topic changed from previous turn } ```",
   "new": null,
   "marked": "[-```typescript // Emitted once per LLM call by src/agents/context-anatomy.ts interface AnatomyRecord { turnId: string; // ULID sessionId: string; compactionCycle: number; // monotonic counter contextUtilPct: number; // tokens used / budget systemPromptBytes: number; workspaceFileBytes: number; skillBytes: number; toolSchemaBytes: number; historyEventCount: number; markerCount: number; userMessageBytes: number; topicLabel: string | null; // detected topic (context-anatomy §8.7) topicTransition: boolean; // true if topic changed from previous turn } ```-]"
  },
  {
   "section": "A.4 Context Anatomy Record Schema",
   "old": null,
   "new": "The Context Anatomy module emits one record per LLM call, capturing the full prompt decomposition for offline replay.",
   "marked": "{+The Context Anatomy module emits one record per LLM call, capturing the full prompt decomposition for offline replay.+}"
  },
  {
   "section": "A.4 Context Anatomy Record Schema",
   "old": null,
   "new": "| Field | Type | Meaning | | --------------------- | --------------- | ------------------------------------------------ | | `turnId` | identifier | Time-sortable turn ID | | `sessionId` | identifier | Owning session | | `compactionCycle` | integer | Monotonic count of compactions this session | | `contextUtilPct` | percentage | Tokens used / budget | | `systemPromptBytes` | integer | Size of the system-prompt block | | `workspaceFileBytes` | integer | Size of injected workspace files | | `skillBytes` | integer | Size of skill definitions | | `toolSchemaBytes` | integer | Size of tool schemas | | `historyEventCount` | integer | Conversation events in context | | `markerCount` | integer | Time-range markers present | | `userMessageBytes` | integer | Size of the current user message | | `topicLabel` | string or null | Detected task-domain topic | | `topicTransition` | boolean | True if the topic changed from the previous turn |",
   "marked": "{+| Field | Type | Meaning | | --------------------- | --------------- | ------------------------------------------------ | | `turnId` | identifier | Time-sortable turn ID | | `sessionId` | identifier | Owning session | | `compactionCycle` | integer | Monotonic count of compactions this session | | `contextUtilPct` | percentage | Tokens used / budget | | `systemPromptBytes` | integer | Size of the system-prompt block | | `workspaceFileBytes` | integer | Size of injected workspace files | | `skillBytes` | integer | Size of skill definitions | | `toolSchemaBytes` | integer | Size of tool schemas | | `historyEventCount` | integer | Conversation events in context | | `markerCount` | integer | Time-range markers present | | `userMessageBytes` | integer | Size of the current user message | | `topicLabel` | string or null | Detected task-domain topic | | `topicTransition` | boolean | True if the topic changed from the previous turn |+}"
  }
 ]
}
