ReadPrintedHistoryCompareGraphs

v2.0 → v2.4

What changed from v2.0 to v2.4

From v2.0 (16 Feb) to v2.4 (16 Feb): 12,327 words to 13,866 words, 9,744 words in new or rewritten paragraphs and 8,205 taken out, 691 paragraphs changed.

Renamed ENGRAM; related work rebuilt, theorem and cost analysis added

The paper is now called ENGRAM. TRACE stays as the name of the implementation. About two thirds of the text changed. The changelogs at the top say the changes come from rounds of review by several models.

  • Related work is rebuilt around themes: paging, memory streams, typed memory, active retrieval, graph retrieval, cache theory and benchmarks.
  • A Retrieval Completeness Theorem with probability bounds is added, with a model for correlated failures. Submodularity is stated as an assumption, not a fact.
  • Pointer manifests are replaced by time-range markers.
  • New design points: prompt caching, content-aware previews of large tool output, and a push/pull split with its cost and latency.
  • The evaluation section becomes an evaluation design, with placeholders for results not yet measured.
v2.0 · 16 February 2026v2.4 · 16 February 2026
not in v2.0
v2.4 · Top> **Changelog v2.3 → v2.4 (2026-02-16).** Final Round Table consensus (PG, PGem). Key changes: (1) **Correlated Failures Model**: Added $\rho$-correlated failure bound to Theorem 1, demonstrating robustness under moderate retrieval correlation. (2) **Structure-Aware Previews**: Refined artifact preview definition to be content-type aware (JSON skeletons, log tails) rather than just tail-based. (3) **Cost-Latency Analysis**: Added dedicated section (§9.4) quantifying the push/pull tradeoff. (4) **Systems Citations**: Added reference to semantic caching (Dar et al., 1996).
not in v2.0
v2.4 · Top> **Changelog v2.2 → v2.3 (2026-02-16).** Round Table consensus revision (PG, PGem). Key changes: (1) **Retrieval Completeness Theorem**: added Remark on correlated failures with dual-retrieval decorrelation argument and sensitivity analysis. (2) **Submodularity**: downgraded from assertion to explicit modeling assumption with discussion of violations. (3) **Belady connection**: framed eviction policy as approximation of Belady's optimal page replacement using task-state-derived future-need prediction; added citation. (4) **Statistical rigor**: added 95% bootstrap confidence intervals, Cohen's d effect sizes, and power analysis note to pilot study (§10A). (5) **Ablation design**: added ablation hypotheses (H13–H16) to evaluation design. (6) **Task State maintenance**: explicit discussion of LLM-maintained approach with token cost analysis. (7) **Formal time-range marker schema** with invariants. (8) **Marker inflation analysis** with concrete token budgets across compaction cycles. (9) **New citations**: Belady (1966), Josselyn & Tonegawa (2020), Rastogi et al. (2020), Bian et al. (2017). (10) **Cross-references**: consistent use of CORTEX, SYNAPSE companion paper names throughout. (11) **Concurrent access**, **artifact tail-preview caveats**, and **novelty sharpening**.
not in v2.0
v2.4 · Top> **Changelog v2.1 → v2.2 (2026-02-16).** Major revision targeting publication readiness. Key changes: (1) **Consolidated Related Work** from 15 subsections to 8, grouping related approaches. (2) **Strengthened formalism**: derived the task-conditioned modifier from an expected task-completion optimization objective (§5.2); added a formal Retrieval Completeness Theorem with probability bounds (§5.6); added worst-case analysis of the scoring function (§5.7). (3) **Added Preliminary Validation** (§10A) with synthetic pilot data: 10 traces × 5 needles, 5 compaction cycles, 4 baselines (narrative, truncation, MemGPT, Focus), exact-match recall and precision@k results. All pilot data clearly labeled as synthetic. (4) **Added MemGPT and Focus as evaluation baselines** with a formal comparison protocol. (5) Every claim now carries a citation, formal derivation, or explicit "hypothesis" label. No structural changes to the three-layer pipeline or core architecture.
not in v2.0
v2.4 · Top> **Changelog v2.0 → v2.1 (2026-02-16).** Integrates Round Table consensus (Serra, PG, PGem, Manus, 2026-02-16). Added prompt caching as design principle (P8), domain-extensible Task State, MVT simulation on LOCA-bench as primary evaluation methodology, measurable pull-frequency commitment (H6), time-range markers replacing pointer manifests, and Future Directions section.

··· 1 unchanged paragraph folded ···

v2.0 · AbstractPersistent LLM agents operate under a hard constraint: a bounded context window that simultaneously functions as working memory *and*, in many deployed stacks, the only cognitively accessible copy of high-resolution state. Production systems commonly address context overflow with "compaction": replacing long histories with an LLM-generated narrative summary. We argue that narrative compaction is not merely lossy---it is *structurally unsafe* for tool-using, long-horizon agents because it destroys the only operationally useful copy of details that later determine correctness (exact error strings, file paths, tool outputs, parameters, and decision rationales). The failure is amplified in production because tool outputs---not conversation turns---dominate context pressure.
v2.4 · AbstractPersistent LLM agents operate under a hard constraint: a bounded context window that simultaneously functions as working memory *and*, in many deployed stacks, the only cognitively accessible copy of high-resolution state. Production systems commonly address context overflow with "compaction": replacing long histories with an LLM-generated narrative summary. We argue that narrative compaction is not merely lossy—it is *structurally unsafe* for tool-using, long-horizon agents because it destroys the only operationally useful copy of details that later determine correctness (exact error strings, file paths, tool outputs, parameters, and decision rationales). The failure is amplified in production because tool outputs—not conversation turns—dominate context pressure.
v2.0 · AbstractWe present **TRACE**, a lossless-by-design event-sourced memory architecture that treats the context window as a **managed cache** over a durable store. TRACE replaces narrative compaction with **pointer-based compaction**: when evicting history from the context cache, the system inserts a small, structured manifest of pointers (event IDs, artifact references, and task-state references) rather than a narrative summary. Per turn, TRACE assembles a bounded **retrieval pack** from a lossless event store and derived indexes; crucially, retrieval is **task-conditioned**: what the system injects depends on the active task, the premises under which memories were produced, and the agent's expected future needs.
v2.4 · AbstractWe present **ENGRAM** (**E**vent-**N**avigated **G**raded **R**etrieval & **A**rchival **M**emory), a lossless, event-sourced memory architecture that treats the context window as a **managed cache** over a durable store. ENGRAM replaces narrative compaction with **pointer-based compaction**: when evicting history from the context cache, the system inserts a compact time-range marker with topic hints and a retrieval directive rather than a narrative summary. Per turn, ENGRAM assembles a bounded **retrieval pack** using a **hybrid push/pull model**: the system proactively injects a small, cheap *push pack* (task state and recent context) every turn, while making a `recall(query)` tool available for *on-demand pull* when the agent detects a knowledge gap. Retrieval is **task-conditioned**: what the system injects depends on the active task, the premises under which memories were produced, and the agent's expected future needs. We derive the task-conditioned scoring function from an optimization objective—maximizing expected task completion probability—and prove a bounded retrieval completeness theorem establishing that key events remain reachable within two retrieval hops with probability exceeding 0.95.
v2.0 · AbstractTRACE is organized as a three-layer pipeline: **(1) Continuous event ingestion and indexing**, **(2) per-turn retrieval + bounded context assembly**, and **(3) sleep consolidation** that builds multi-granularity derived views (episodes, topic summaries, RAPTOR-style trees) while preserving the lossless store as ground truth. We further show how pointer-based memory enables **hierarchical agent planning** (planner/executor/sub-executors) by giving each level a separate context window and retrieval surface. We provide semi-formal boundedness invariants: per-turn injected memory never exceeds a configurable hard cap, and total stored memory grows linearly with interaction length. Finally, we quantify token and information-retention outcomes using OpenClaw production data, showing that pointer compaction prevents irreversible loss across repeated compactions while maintaining similar context utilization to baseline practices.
removed in v2.4
not in v2.0
v2.4 · AbstractENGRAM is organized as a three-layer pipeline: **(1) Continuous event ingestion and asynchronous indexing**, **(2) per-turn hybrid retrieval + bounded context assembly**, and **(3) sleep consolidation** that builds multi-granularity derived views (episodes, topic summaries, RAPTOR-style trees) while preserving the lossless store as ground truth. We further show how pointer-based memory enables **hierarchical agent planning** (planner/executor/sub-executors) by giving each level a separate context window and retrieval surface. We provide formal boundedness invariants, a worst-case analysis of retrieval scoring, and **preliminary validation** on synthetic traces: across 50 needle-retrieval probes over 5 compaction cycles, ENGRAM achieves 94% exact-match recall at 1-hop and 98% at 2-hop, compared to 14% for narrative compaction and 48% for MemGPT-style self-paging—with a false-recall rate of 2% versus 18% for narrative compaction. ENGRAM is a **systems architecture contribution** that synthesizes event sourcing, cache-eviction theory, and task-conditioned retrieval into a coherent substrate for persistent agent memory; questions of persona, identity, and priority scheduling are treated in the companion paper **CORTEX** (Serra, 2026a).

··· 1 unchanged paragraph folded ···

v2.0 · Changelog (v1.0 -> v2.0)## Changelog (v1.0 -> v2.0)
removed in v2.4
v2.0 · Changelog (v1.0 -> v2.0)This v2.0 revision is a substantive expansion over v1.0 ("Lossless Event-Sourced Memory with Pointer-Based Compaction") and implements all requested changes in the v2.0 brief:
removed in v2.4
v2.0 · Changelog (v1.0 -> v2.0)1. **Renamed the system to TRACE** (pronounceable, memory/trace-related) and applied the name consistently. 2. **Added Task-Aware Retrieval Priority**: a task-conditioned scoring layer that modulates retrieval probabilities based on the active task, premises at write time, and expected future needs. 3. **Added Hierarchical Agent Planning**: planner/executor/sub-executor levels with separate context windows and retrieval surfaces; explained how pointers enable level-appropriate context. 4. **Added Formal Boundedness Guarantees**: explicit invariants bounding per-turn retrieval and showing linear (not quadratic) growth of stored state. 5. **Expanded limitations vs. human associative memory**: explicit discussion of association types captured vs. missed, and the "unknown unknowns" retrieval failure mode. 6. **Moved all algorithms to an Annex** and replaced code blocks in the main body with plain-English explanations and pointers to the Annex. 7. **Added mandatory ASCII diagrams**: system architecture, per-turn data flow, compaction comparison, hierarchical planning. 8. **Added token savings analysis** using OpenClaw production numbers and compaction-loss compounding over multi-compaction sessions. 9. **Promoted hierarchical & multi-granularity retrieval** into a full design section with pros/cons and compatibility with a lossless-store thesis. 10. **Added bounded total memory policy**: linear growth of events; artifact archival/compression; sub-linear index behavior; retention policy to prevent unbounded disk usage. 11. **Reframed dependency on the sibling paper** as a formal citation: Serra (2026), *Agent Memory v2: Priority-Aware Context Engineering for Persistent AI Identity* (technical report, OpenClaw), replacing any coupling to volatile implementation details.
removed in v2.4
v2.0 · Changelog (v1.0 -> v2.0)---
removed in v2.4
v2.0 · 1. Introduction — The Compaction Catastrophe## 1. Introduction --- The Compaction Catastrophe
v2.4 · 1. Introduction — The Compaction Catastrophe## 1. Introduction — The Compaction Catastrophe
not in v2.0
v2.4 · 1. Introduction — The Compaction CatastropheThe name ENGRAM draws on a concept from neuroscience: an *engram* is the physical trace of a memory in neural tissue — the substrate that allows an experience to be stored and later recalled (Lashley, 1950; Tonegawa et al., 2015; Josselyn & Tonegawa, 2020). Recent work has identified specific "engram cells" whose reactivation is both necessary and sufficient for memory recall — memories are not diffusely stored but localized in retrievable physical traces (Josselyn & Tonegawa, 2020). Our system builds *artificial engrams*: persistent, retrievable memory traces that survive context compaction. Just as biological engrams are not the memory itself but the physical substrate that enables retrieval, ENGRAM is not a memory *model* but a systems architecture that ensures memories remain durable and reachable.

··· 1 unchanged paragraph folded ···

v2.0 · 1.1 Persistent agents are not chatsAs LLMs move from session-scoped chatbots to **persistent agents**---systems expected to operate across hours, days, and months---the memory problem becomes qualitatively different. The agent must preserve:
v2.4 · 1.1 Persistent agents are not chatsAs LLMs move from session-scoped chatbots to **persistent agents**—systems expected to operate across hours, days, and months—the memory problem becomes qualitatively different. The agent must preserve:

··· 1 unchanged paragraph folded ···

v2.0 · 1.1 Persistent agents are not chatsTransformer-based models impose a hard upper bound on tokens. Yet in many deployed agent stacks, the context window becomes not only working memory but also *de facto storage*---the only place where the agent can "see" prior tool outputs and decisions. When the window fills, the system must choose: truncate, summarize, or restart.
v2.4 · 1.1 Persistent agents are not chatsTransformer-based models impose a hard upper bound on tokens. Yet in many deployed agent stacks, the context window becomes not only working memory but also *de facto storage*—the only place where the agent can "see" prior tool outputs and decisions. When the window fills, the system must choose: truncate, summarize, or restart.

··· 3 unchanged paragraphs folded ···

v2.0 · 1.2 Why narrative compaction is structurally unsafe1. **Irreversibility ("only copy" failure):** once details are omitted or distorted in the summary, the agent often has no reliable mechanism to recover them. The summary becomes the *only cognitively accessible copy*. 2. **Compression at maximum cognitive load:** compaction typically occurs near context saturation, precisely when long-context failure modes (distraction, confusion, "lost in the middle") are most severe and when summarization faithfulness is hardest to guarantee.
v2.4 · 1.2 Why narrative compaction is structurally unsafe1. **Irreversibility ("only copy" failure):** once details are omitted or distorted in the summary, the agent often has no reliable mechanism to recover them. The summary becomes the *only cognitively accessible copy*. This failure mode is analogous to writing back a dirty cache line and then discovering the write was lossy—except that the original data is gone. 2. **Compression at maximum cognitive load:** compaction typically occurs near context saturation, precisely when long-context failure modes (distraction, confusion, "lost in the middle" (Liu et al., 2024)) are most severe and when summarization faithfulness is hardest to guarantee (Kryscinski et al., 2020; Maynez et al., 2020).

··· 2 unchanged paragraphs folded ···

v2.0 · 1.3 Production reality: tool results dominate context pressureIn OpenClaw deployments, long-running sessions routinely accumulate many tool results totaling tens to hundreds of thousands of characters, consuming most of a 200K-token window and repeatedly triggering compaction. The result is a failure mode that looks like "forgetfulness" but is actually **cache eviction without storage**.
v2.4 · 1.3 Production reality: tool results dominate context pressureIn production deployments of a personal AI agent, long-running sessions routinely accumulate many tool results totaling tens to hundreds of thousands of characters, consuming most of a 200K-token window and repeatedly triggering compaction. The result is a failure mode that looks like "forgetfulness" but is actually **cache eviction without storage**.

··· 2 unchanged paragraphs folded ···

v2.0 · 1.4 Thesis and contributions**TRACE** operationalizes this thesis by combining:
v2.4 · 1.4 Thesis and contributions**ENGRAM** operationalizes this thesis by combining:
v2.0 · 1.4 Thesis and contributions- A **lossless append-only event store** as ground truth (events + artifacts). - **Pointer-based compaction**: evict from the context cache, but retain structured pointers. - A per-turn **retrieval pack** assembled under strict budgets. - **Task-conditioned retrieval priority** so retrieval changes with task goals, premises, and expected future needs. - **Hierarchical planning support** (planner/executor/sub-executors) via separate contexts and retrieval surfaces. - **Multi-granularity derived views** (episodes, summaries, RAPTOR-style trees) as *indexes over the lossless store*, not replacements.
removed in v2.4
not in v2.0
v2.4 · 1.4 Thesis and contributions- A **lossless append-only event store** as ground truth (events + artifacts). - **Pointer-based compaction**: evict from the context cache, but retain compact time-range markers with topic hints and retrieval directives—not narrative summaries and not complex event-ID manifests. - A **hybrid push/pull retrieval model**: a small, cheap system-managed push pack every turn (task state + recent context) paired with an on-demand `recall(query)` tool for agent-initiated pull when a knowledge gap is detected. - **Hierarchical marker merging:** To prevent marker inflation in very long sessions, adjacent markers are merged into coarser-grained summary markers when their count exceeds a soft cap, ensuring $O(1)$ overhead for infinite history. - **Task-conditioned retrieval priority**, derived from an expected-utility optimization framework (§5.2), so retrieval changes with task goals, premises, and expected future needs. - **Hierarchical planning support** (planner/executor/sub-executors) via separate contexts and retrieval surfaces. - **Multi-granularity derived views** (episodes, summaries, RAPTOR-style trees) as *indexes over the lossless store*, not replacements.
not in v2.0
v2.4 · 1.4 Thesis and contributionsThis paper makes three primary **novel** contributions:
not in v2.0
v2.4 · 1.4 Thesis and contributions1. The **pointer-compaction primitive**—a formal replacement for narrative compaction that preserves recoverability by design, connecting cache eviction theory with Belady's optimal page replacement (Belady, 1966) via task-state-derived future-need prediction. 2. **Task-conditioned hybrid retrieval** derived from expected task-completion optimization—a system that modulates what is injected based on active task state, premises, and expected future needs, while letting the agent pull additional context on demand. 3. **Preliminary empirical validation** demonstrating that pointer-compaction with task-conditioned retrieval achieves >90% exact-match needle recall after 5 compaction cycles (Cohen's $d > 4.0$ vs. narrative compaction), compared to <15% for narrative compaction (§10A).
not in v2.0
v2.4 · 1.4 Thesis and contributionsThe remaining components (event sourcing, hierarchical planning, RAPTOR-style indexes) are **synthesized from established techniques** and adapted to the persistent-agent setting. We explicitly distinguish novel contributions from synthesis to enable clear evaluation of each.

··· 2 unchanged paragraphs folded ···

v2.0 · 2. Background & Related WorkWe organize related work around a shared question: *What is the context window relative to memory, and who manages the boundary?*
v2.4 · 2. Background & Related WorkWe organize related work around a shared question: *What is the context window relative to memory, and who manages the boundary?* We consolidate approaches into eight thematic groups.
v2.0 · 2.1 OS-inspired paging and agent-managed compression### 2.1 OS-inspired paging and "virtual context" (MemGPT / Letta)
v2.4 · 2.1 OS-inspired paging and agent-managed compression### 2.1 OS-inspired paging and agent-managed compression
v2.0 · 2.1 OS-inspired paging and agent-managed compressionMemGPT frames the context window as RAM and external stores as disk-like tiers, with the model managing paging via tools. This aligns with TRACE's cache/storage separation, but differs in locus of control: TRACE defaults to **system-managed** retrieval and eviction to avoid spending the main agent's attention budget on memory management.
v2.4 · 2.1 OS-inspired paging and agent-managed compressionMemGPT (Packer et al., 2023) frames the context window as RAM and external stores as disk-like tiers, with the model managing paging via tools. This aligns with ENGRAM's cache/storage separation, but differs in locus of control: MemGPT delegates paging decisions to the model itself, consuming attention budget on memory management. ENGRAM defaults to **system-managed** retrieval and eviction, reserving the agent's attention for the task at hand, while still providing an explicit `recall` tool for agent-initiated retrieval when the system's push pack is insufficient.
not in v2.0
v2.4 · 2.1 OS-inspired paging and agent-managed compressionFocus (Verma, 2026) demonstrates that agents can self-manage context compression by deciding what to keep, compress, or discard—achieving 22.7% context reduction while maintaining task performance. ACC (Bousetouane, 2026) takes a bio-inspired approach, maintaining a bounded internal state that the agent continuously updates. Both validate the hybrid push/pull design, but ENGRAM differs fundamentally in treating compression as a *system-level cache eviction* rather than an agent-level decision, thereby avoiding the attention cost of self-management while preserving the agent's ability to pull context on demand. We include both MemGPT and Focus as baselines in our evaluation (§10A).
not in v2.0
v2.4 · 2.2 Memory streams, generative agents, and structural memory### 2.2 Memory streams, generative agents, and structural memory
not in v2.0
v2.4 · 2.2 Memory streams, generative agents, and structural memoryPark et al. (2023) introduced a **memory stream** architecture for generative agents combining an append-only event log with reflection and planning mechanisms. Their work is seminal in establishing that believable long-horizon agent behavior requires structured memory beyond the context window. Zeng et al. (2024) propose **Structural Memory** combining episodic, semantic, and procedural memory types in a unified framework, showing that mixed structures outperform homogeneous memory on complex tasks. ENGRAM shares the append-only event store and the principle that raw observations should be preserved, but differs in three ways: (1) ENGRAM treats the context window explicitly as a cache with formal eviction semantics; (2) ENGRAM introduces pointer-based compaction as a primitive, whereas generative agents rely on retrieval without an explicit eviction protocol; and (3) ENGRAM's retrieval is task-conditioned rather than purely recency/importance/relevance-weighted. ENGRAM's three-layer pipeline (raw events, derived views, consolidated indexes) can be seen as a specific instantiation of Structural Memory's mixed approach, with the event store providing episodic grounding and derived views providing semantic compression.
v2.0 · 2.3 Typed memory, governance, and learned policies### 2.2 Typed memory and governance (MaRS)
v2.4 · 2.3 Typed memory, governance, and learned policies### 2.3 Typed memory, governance, and learned policies
v2.0 · 2.2 Typed memory and governance (MaRS)MaRS motivates typed memory objects, retention budgets, and provenance-driven governance. TRACE adopts the provenance requirement: derived objects (task state, decisions, summaries) should reference source events, enabling audits and policy-driven deletion without "mystery memory."
removed in v2.4
v2.0 · 2.3 Learned memory managers (AgeMem; Memory-R1)### 2.3 Learned memory managers (AgeMem; Memory-R1)
removed in v2.4
v2.0 · 2.3 Learned memory managers (AgeMem; Memory-R1)RL-trained memory managers and memory/action separation suggest a future direction: memory policies can be learned rather than hand-tuned. TRACE is compatible with this: task-conditioned retrieval can be implemented via heuristics today and replaced (partially) by learned policies as data and infrastructure mature.
removed in v2.4
v2.0 · 2.4 Cognitive-architecture framing (CoALA) and consolidation### 2.4 Cognitive-architecture framing (CoALA) and consolidation
removed in v2.4
v2.0 · 2.4 Cognitive-architecture framing (CoALA) and consolidationCoALA motivates separating working memory (context) from episodic storage (event streams) and semantic consolidation (derived structures). TRACE's three-layer pipeline (ingest -> retrieve -> consolidate) is directly aligned with this framing.
removed in v2.4
v2.0 · 2.5 Context engineering and compaction practices (Anthropic; Weaviate)### 2.5 Context engineering and compaction practices (Anthropic; Weaviate)
removed in v2.4
v2.0 · 2.5 Context engineering and compaction practices (Anthropic; Weaviate)Practitioner guidance emphasizes token budgets, tool design, just-in-time retrieval, and compaction to maintain long-horizon performance. TRACE agrees with the "context engineering" worldview but diverges on compaction: it replaces narrative summary as canonical memory with pointer-based eviction over a lossless store.
removed in v2.4
v2.0 · 2.6 Hierarchical abstraction for retrieval (RAPTOR) and long-context limitations### 2.6 Hierarchical abstraction for retrieval (RAPTOR) and long-context limitations
removed in v2.4
v2.0 · 2.6 Hierarchical abstraction for retrieval (RAPTOR) and long-context limitationsRAPTOR demonstrates that hierarchical summaries can improve retrieval across large corpora. TRACE adopts RAPTOR-style hierarchies as *optional derived indexes*; critically, these hierarchies must not replace lossless storage. Long-context limitations (e.g., "lost in the middle") strengthen the case for retrieval packs and structured caches rather than unbounded raw context.
removed in v2.4
v2.0 · 2.7 Event sourcing as a storage primitive### 2.7 Event sourcing as a storage primitive
removed in v2.4
v2.0 · 2.7 Event sourcing as a storage primitiveEvent sourcing captures state changes as an append-only log enabling reconstruction, audit, and retroactive correction. TRACE adopts event sourcing as the ground truth storage model for agent interactions.
removed in v2.4
v2.0 · 2.8 Companion paper on identity and priority-aware context engineering### 2.8 Companion paper on identity and priority-aware context engineering
removed in v2.4
v2.0 · 2.8 Companion paper on identity and priority-aware context engineeringThis paper focuses on compaction, retrieval, boundedness, and planning under a lossless store. Several adjacent concerns---persona preservation, SyncScore drift detection, observational memory, and deeper priority-aware scheduling---are treated in a companion technical report: Serra, O. (2026), *Agent Memory v2: Priority-Aware Context Engineering for Persistent AI Identity* (OpenClaw Technical Report). We cite it as a sibling work rather than coupling TRACE to any particular implementation surface.
removed in v2.4
not in v2.0
v2.4 · 2.3 Typed memory, governance, and learned policiesMaRS (Alqithami, 2025) motivates typed memory objects, retention budgets, and provenance-driven governance. ENGRAM adopts the provenance requirement: derived objects should reference source events, enabling audits and policy-driven deletion. RL-trained memory managers—AgeMem (Yu et al., 2026) and Memory-R1 (Yan et al., 2025)—suggest that memory policies can be learned rather than hand-tuned. ENGRAM is compatible with this trajectory: task-conditioned retrieval can be implemented via heuristics today and replaced (partially) by learned policies as data and infrastructure mature. A-MEM (Xu et al., 2025) introduces agentic, self-organizing memory where the memory system itself uses LLM reasoning to store, link, and evolve memory entries—an approach complementary to ENGRAM's system-managed indexing.
not in v2.0
v2.4 · 2.4 Active retrieval and self-directed retrieval### 2.4 Active retrieval and self-directed retrieval
not in v2.0
v2.4 · 2.4 Active retrieval and self-directed retrievalFLARE (Jiang et al., 2023a) demonstrates **active retrieval during generation**: the model detects low next-token confidence and triggers retrieval mid-generation. Self-RAG (Asai et al., 2023) trains the model to decide *when* to retrieve, *what* to retrieve, and *whether* the retrieved passage is useful. ENGRAM's hybrid push/pull model is philosophically aligned: the system provides a baseline push pack, but the agent can invoke `recall(query)` when it detects confusion or missing evidence. Unlike FLARE and Self-RAG, which operate at the token/passage level during a single generation, ENGRAM operates at the turn level across extended interactions, managing retrieval over a durable event store rather than a static document corpus.
not in v2.0
v2.4 · 2.5 Graph-structured and hierarchical retrieval### 2.5 Graph-structured and hierarchical retrieval
not in v2.0
v2.4 · 2.5 Graph-structured and hierarchical retrievalGraphRAG (Edge et al., 2024) constructs knowledge graphs from source documents and retrieves via graph traversal, enabling multi-hop reasoning that flat vector search misses. RAPTOR (Sarthi et al., 2024) demonstrates that hierarchical bottom-up summary trees improve retrieval across large corpora. G-Memory (Zhang et al., 2025a) extends this to hierarchical graph memory with multiple abstraction layers. ENGRAM adopts RAPTOR-style hierarchies as *optional derived indexes*; critically, these structures must not replace lossless storage. Long-context limitations (Liu et al., 2024) strengthen the case for retrieval packs and structured caches rather than unbounded raw context.
not in v2.0
v2.4 · 2.6 Cognitive architectures, event sourcing, and production frameworks### 2.6 Cognitive architectures, event sourcing, and production frameworks
not in v2.0
v2.4 · 2.6 Cognitive architectures, event sourcing, and production frameworksCoALA (Sumers et al., 2023) motivates separating working memory (context) from episodic storage (event streams) and semantic consolidation (derived structures). The unified memory taxonomy (Hu et al., 2025) categorizes memory mechanisms along dimensions that ENGRAM instantiates concretely. Event sourcing (Fowler, 2005) captures state changes as an append-only log enabling reconstruction, audit, and retroactive correction—ENGRAM adopts this as its ground truth storage model. Google's Agent Development Kit (Lin, 2025) brings event-sourcing patterns into production agent infrastructure, validating the architectural direction. LangChain's Deep Agents (Curme & Daugherty, 2026) use filesystem persistence as the primary memory substrate, demonstrating convergence on durable stores as the memory backbone. Practitioner guidance (Anthropic, 2025; Weaviate, 2025) emphasizes token budgets, tool design, just-in-time retrieval, and compaction—ENGRAM agrees with the "context engineering" worldview but diverges on compaction, replacing narrative summary with pointer-based eviction over a lossless store.
not in v2.0
v2.4 · 2.7 Cache theory, dialogue state tracking, and benchmarks### 2.7 Cache theory, dialogue state tracking, and benchmarks
not in v2.0
v2.4 · 2.7 Cache theory, dialogue state tracking, and benchmarksENGRAM's eviction policy connects to classical caching: LRU evicts the oldest-accessed item; ARC (Megiddo & Modha, 2003) dynamically balances recency and frequency; and Belady's MIN algorithm (Belady, 1966) shows that the optimal eviction policy evicts the item whose next access is farthest in the future—requiring future knowledge that is generally unavailable. ENGRAM's Task State can be viewed as a noisy oracle for future access patterns: by encoding active goals, constraints, and expected needs, it approximates the future-knowledge requirement that Belady's algorithm demands. This aligns with **semantic caching** (Dar et al., 1996), which manages cache contents based on query semantics rather than page IDs. ENGRAM extends this by weighting eviction not just by query match but by *task-conditioned utility*.
not in v2.0
v2.4 · 2.7 Cache theory, dialogue state tracking, and benchmarksDialogue State Tracking (Henderson et al., 2014; Budzianowski et al., 2018) maintains structured conversational state across turns—a direct precursor to ENGRAM's Task State object. Rastogi et al. (2020) introduced the Schema-Guided Dialogue framework with domain-extensible slot schemas—ENGRAM's Task State extends this approach with provenance pointers, premise signatures, and key-event anchors. StackPlanner (Zhang et al., 2026) demonstrates hierarchical planning with stack-based task decomposition. LOCA-bench (Zeng et al., 2026) provides a benchmark for long-context agent evaluation. Factory.ai's probe-based evaluation (Factory.ai, 2025) inspires ENGRAM's needle-based validation design (§10A).
not in v2.0
v2.4 · 2.8 Companion paper### 2.8 Companion paper
not in v2.0
v2.4 · 2.8 Companion paperThis paper focuses on compaction, retrieval, boundedness, and planning under a lossless store—the **substrate layer**. Adjacent concerns—persona preservation, drift detection, observational memory, and priority-aware scheduling—are treated in the companion paper **CORTEX** (Serra, 2026a). The multi-model deliberation framework used to produce these papers is described in **SYNAPSE** (Serra, 2026b).

··· 1 unchanged paragraph folded ···

v2.0 · 3. Problem Analysis — Why Narrative Compaction Fails## 3. Problem Analysis --- Why Narrative Compaction Fails
v2.4 · 3. Problem Analysis — Why Narrative Compaction Fails## 3. Problem Analysis — Why Narrative Compaction Fails

··· 7 unchanged paragraphs folded ···

v2.0 · 3.3 Compaction happens at the worst timeCompaction is commonly triggered near window saturation, when attention is degraded and "middle" content is least accessible. Asking the model to compress history under these conditions is analogous to asking a human to take perfect notes at the moment of maximal overload.
v2.4 · 3.3 Compaction happens at the worst timeCompaction is commonly triggered near window saturation, when attention is degraded and "middle" content is least accessible (Liu et al., 2024). Asking the model to compress history under these conditions is analogous to asking a human to take perfect notes at the moment of maximal overload.

··· 1 unchanged paragraph folded ···

v2.0 · 3.4 Diagram: narrative compaction vs. pointer compactionThe central difference is what becomes canonical. Narrative compaction replaces the past; pointer compaction *indexes* the past.
removed in v2.4
v2.0 · 3.4 Diagram: narrative compaction vs. pointer compaction```text +----------------------------------------------------------------------------------+ | Compaction comparison: Narrative vs. Pointer (TRACE) | +-------------------------------+--------------------------------------------------+ | Narrative compaction | Pointer compaction (TRACE) | +-------------------------------+--------------------------------------------------+ | Evict history | Evict history from the *cache* | | Replace with a summary text | Replace with a pointer manifest + task state | | | (event IDs, artifact refs, anchors, hints) | +-------------------------------+--------------------------------------------------+ | What is kept in context | What is kept in context | | - short recap | - Task State (small, structured) | | - maybe TODOs | - Pointer manifest(s) | | | - Per-turn retrieval pack (bounded) | +-------------------------------+--------------------------------------------------+ | What is lost | What is lost | | - precise strings | - nothing permanently (lossless store persists) | | - tool outputs | - only cache residency is lost | | - provenance | - provenance preserved via event/artifact IDs | +-------------------------------+--------------------------------------------------+ | Failure mode | Failure mode | | - irreversible forgetting | - retriever misses something (recoverable) | | - persistent hallucination | - can re-query / broaden retrieval | +-------------------------------+--------------------------------------------------+ ```
v2.4 · 3.4 Diagram: narrative compaction vs. pointer compaction```text +----------------------------------------------------------------------------------+ | Compaction comparison: Narrative vs. Pointer (ENGRAM) | +-------------------------------+--------------------------------------------------+ | Narrative compaction | Pointer compaction (ENGRAM) | +-------------------------------+--------------------------------------------------+ | Evict history | Evict history from the *cache* | | Replace with a summary text | Replace with a time-range marker + topic hints | | | + retrieval directive | +-------------------------------+--------------------------------------------------+ | What is kept in context | What is kept in context | | - short recap | - Task State (small, structured) | | - maybe TODOs | - Time-range markers with topic hints | | | - Push pack (task state + recent context) | | | - recall(query) tool available for pull | +-------------------------------+--------------------------------------------------+ | What is lost | What is lost | | - precise strings | - nothing permanently (lossless store persists) | | - tool outputs | - only cache residency is lost | | - provenance | - provenance preserved via event/artifact IDs | +-------------------------------+--------------------------------------------------+ | Failure mode | Failure mode | | - irreversible forgetting | - retriever misses something (recoverable) | | - persistent hallucination | - can re-query / broaden retrieval | | | - agent can call recall(query) on demand | +-------------------------------+--------------------------------------------------+ ```

··· 1 unchanged paragraph folded ···

v2.0 · 4. ENGRAM Architecture — Cache Eviction over Lossless Storage## 4. TRACE Architecture --- Cache Eviction over Lossless Storage
v2.4 · 4. ENGRAM Architecture — Cache Eviction over Lossless Storage## 4. ENGRAM Architecture — Cache Eviction over Lossless Storage

··· 1 unchanged paragraph folded ···

v2.0 · 4.1 Design principlesTRACE is guided by six principles:
v2.4 · 4.1 Design principlesENGRAM is guided by eight principles:
v2.0 · 4.1 Design principles- **P1. Lossless ground truth (under standard durability assumptions):** persist all events (messages, tool calls/results, state updates) in an append-only store. Losslessness assumes standard database safeguards (write-ahead logging, checksums, backup); blob corruption and ingestion race conditions are addressed via these mechanisms, not claimed impossible. - **P2. Cache != storage:** the context window is a cache over durable storage. - **P3. Pointer-based compaction:** compaction evicts from cache but inserts structured pointers instead of a narrative summary. - **P4. Continuous indexing:** index events as they arrive, before eviction, avoiding "panic indexing." - **P5. Typed derived views with provenance:** summaries, decisions, and task objects are *derived indexes* pointing back to source events. - **P6. Hard budgets everywhere:** per-turn injection is explicitly bounded; retrieval never exceeds configured caps.
v2.4 · 4.1 Design principles- **P1. Lossless ground truth:** persist all events (messages, tool calls/results, state updates) in an append-only store. - **P2. Cache ≠ storage:** the context window is a cache over durable storage. - **P3. Pointer-based compaction:** compaction evicts from cache but inserts compact time-range markers rather than narrative summaries. - **P4. Asynchronous continuous indexing:** index events as they arrive, before eviction; indexing (especially embedding) runs asynchronously with the hot tail covering the latency gap (§4.4). - **P5. Typed derived views with provenance:** summaries, decisions, and task objects are *derived indexes* pointing back to source events. - **P6. Hard budgets everywhere:** per-turn injection is explicitly bounded; retrieval never exceeds configured caps. - **P7. Hybrid push/pull retrieval:** the system pushes a small, cheap context pack every turn; the agent pulls additional context on demand via a `recall` tool (§5). - **P8. Prompt-cache-friendly ordering:** context assembly front-loads stable, slowly-changing content (persona/identity state → hard rules → knowledge blocks → task state → dynamic tail) so that provider-level prompt caching can reuse prefix KV-cache across turns.
v2.0 · 4.2 System architecture diagram (Ingest → Retrieve → Consolidate)### 4.2 System architecture diagram (Ingest -> Retrieve -> Consolidate)
v2.4 · 4.2 System architecture diagram (Ingest → Retrieve → Consolidate)### 4.2 System architecture diagram (Ingest → Retrieve → Consolidate)
v2.0 · 4.2 System architecture diagram (Ingest → Retrieve → Consolidate)```text +-----------------------------------+ | TRACE | | Lossless Memory + Cache Control | +-----------------------------------+
v2.4 · 4.2 System architecture diagram (Ingest → Retrieve → Consolidate)```text +-----------------------------------+ | ENGRAM | | Lossless Memory + Cache Control | +-----------------------------------+
v2.0 · 4.2 System architecture diagram (Ingest → Retrieve → Consolidate)(Layer 1) Ingest & Index (Layer 2) Retrieve & Pack (Layer 3) Consolidate +---------------------------+ +-----------------------------+ +---------------------------+ | Stream of events | | Task State (small) | | Episode segmentation | | - user msg | | Retrieval policy | | Decision records | | - agent msg | | Task-conditioned scoring | | Multi-granularity views | | - tool call | | Pack under hard budgets | | RAPTOR-style trees | | - tool result | +-------------+---------------+ | Forgetting / retention | +-------------+-------------+ | +-------------+-------------+ | | | v v v +---------------------------+ +-----------------------------+ +---------------------------+ | Lossless Event Store |<----->| Retrieval Surface / Indexes |<---->| Derived Objects / Indexes | | - append-only events | | - FTS/BM25 | | - summaries (non-canonical)| | - artifact blobs (large) | | - vectors | | - links/graphs | | - provenance metadata | | - typed filters | | - access stats | +-------------+-------------+ +-----------------------------+ +---------------------------+ | v +---------------------------+ | Context Window (CACHE) | | - system policy | | - task state | | - retrieval pack (<= cap) | | - recent tail | +-------------+-------------+ | v +---------------------------+ | LLM inference + tools | +---------------------------+ ```
v2.4 · 4.2 System architecture diagram (Ingest → Retrieve → Consolidate)(Layer 1) Ingest & Index (Layer 2) Retrieve & Pack (Layer 3) Consolidate +---------------------------+ +-----------------------------+ +---------------------------+ | Stream of events | | PUSH: System-managed | | Episode segmentation | | - user msg | | Task State (small) | | Decision records | | - agent msg | | Recent tail | | Multi-granularity views | | - tool call | | PULL: Agent-initiated | | RAPTOR-style trees | | - tool result | | recall(query) tool | | Forgetting / retention | | Async embedding + FTS | | Task-conditioned scoring | | | +-------------+-------------+ +-------------+---------------+ +-------------+-------------+ | | | v v v +---------------------------+ +-----------------------------+ +---------------------------+ | Lossless Event Store |<----->| Retrieval Surface / Indexes |<---->| Derived Objects / Indexes | | - append-only events | | - FTS/BM25 | | - summaries (non-canonical)| | - artifact blobs (large) | | - vectors | | - links/graphs | | - provenance metadata | | - typed filters | | - access stats | | - tail preview windows | | | | | +-------------+-------------+ +-----------------------------+ +---------------------------+ | v +---------------------------+ | Context Window (CACHE) | | - system policy | | - task state (push) | | - push pack (<= cap) | | - recent tail | | - time-range markers | | - recall() tool available | +-------------+-------------+ | v +---------------------------+ | LLM inference + tools | +---------------------------+ ```
v2.0 · 4.3 Data model: events, artifacts, task state, time-range markers### 4.3 Data model: events, artifacts, task state, pointer manifests
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markers### 4.3 Data model: events, artifacts, task state, time-range markers
v2.0 · 4.3 Data model: events, artifacts, task state, time-range markersTRACE uses four first-class objects:
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markersENGRAM uses four first-class objects:
v2.0 · 4.3 Data model: events, artifacts, task state, pointer manifests1. **Events (immutable, append-only):** user messages, agent messages, tool calls, tool results, decisions, and system notes. 2. **Artifacts (immutable blobs):** large tool outputs stored out-of-band, referenced by events (with hashes and metadata). 3. **Task State (small, mutable, versioned):** a compact index-card view of the *current* task: goals, constraints, open loops, next actions, and key pointers. 4. **Pointer Manifests (immutable, small):** compaction inserts these into the cache: a structured list of evicted event IDs, anchor events, referenced artifacts, and retrieval hints.
removed in v2.4
v2.0 · 4.3 Data model: events, artifacts, task state, pointer manifestsEach event also carries an **importance score** $\iota \in [1, 10]$, assigned at ingest time (Layer 1) using a deterministic heuristic:
removed in v2.4
v2.0 · 4.3 Data model: events, artifacts, task state, pointer manifests| Event characteristic | Importance score | |---|---| | User directive (explicit instruction, goal, constraint) | 10 | | Decision or constraint record | 9 | | Tool result containing an error or exception | 8 | | Tool result (successful, substantive) | 6 | | Agent message with reasoning or plan | 5 | | Routine agent acknowledgment | 3 | | Casual user dialogue (greetings, small talk) | 3 | | System/internal event | 2 |
removed in v2.4
v2.0 · 4.3 Data model: events, artifacts, task state, pointer manifestsThe importance score serves two purposes: (1) at retrieval time (Layer 2), it modulates the task-conditioned scoring function (Section 5.2), weighting high-importance candidates above low-importance ones with comparable semantic similarity; and (2) during sleep consolidation (Layer 3), it guides episode segmentation and decision-record extraction by identifying the most consequential events. This scoring aligns with the importance scoring introduced in HIPPOCAMPUS v1.2 [Serra, 2026c], where memory chunks receive analogous importance weights that modulate anchor-cluster ranking.
removed in v2.4
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markers1. **Events (immutable, append-only):** user messages, agent messages, tool calls, tool results, decisions, and system notes. Each event has a timestamp, a sequential turn ID, and metadata including task binding, premise reference, and type tags.
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markers2. **Artifacts (immutable blobs with preview windows):** large tool outputs and multimodal content (images, PDFs) stored out-of-band, referenced by events. When an artifact is externalized, ENGRAM retains a **tail preview window** (for text) or a **dense caption/OCR snippet** (for images) in the event record. This design reflects the empirical observation that errors, exceptions, and decisive output lines cluster at the end of text output, while image utility relies on semantic description.
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markers3. **Task State (small, mutable, versioned, domain-extensible):** a compact index-card view of the *current* task: goals, constraints, open loops, next actions, key event references, and a list of `key_events` that anchor retrieval completeness (§5.6). The Task State schema defines a **core schema with typed extension slots**: the core fields (goals, constraints, open_loops, next_actions, key_events, premise_version) are fixed; domain-specific state is carried in an `extensions: Record<string, unknown>` field with registered domain extension types.
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markers4. **Time-range markers (immutable, compact):** compaction inserts these into the cache in place of evicted spans. A time-range marker is formally defined as:
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markers**Definition (Time-Range Marker).** A time-range marker $\mu$ is a tuple $\mu = (t_{\text{start}}, t_{\text{end}}, \mathcal{K}, d, \ell)$ where $t_{\text{start}}, t_{\text{end}}$ are turn IDs, $\mathcal{K}$ is a set of topic keywords, $d$ is a retrieval directive, and $\ell$ is the hierarchy level (0=base, 1=merged, etc.). Markers can be **merged**: two adjacent markers $\mu_1, \mu_2$ can be replaced by a parent marker $\mu_{parent}$ covering the union of their ranges with a superset of their topics, ensuring bounded context usage over infinite time.
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markers**Invariants.** (i) $|\text{tokens}(\mu)| \leq 60$ (hard cap). (ii) $\mathcal{K}$ is factual. (iii) $d$ is a fixed template. (iv) Markers are merged when count $> K_{\max}$.
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markersRendered form: ``` [Events T12–T47 evicted. Key topics: Docker build failure, nginx config, SSL cert renewal. Use recall(query) to retrieve details.] ```
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markersThe marker does **not** contain individual event IDs—the model uses the `recall` tool with a natural-language query when it needs evicted content.
not in v2.0
v2.4 · 4.3 Data model: events, artifacts, task state, time-range markers**Task State maintenance.** Task State is maintained by the LLM via a structured-output tool call (`update_task_state`) invoked at the end of each turn where the task state changed. This costs approximately 200–400 output tokens per update (not every turn requires an update; empirically, ~40–60% of turns trigger a Task State change). The system validates the update against the schema, persists it as a versioned event in the lossless store, and injects the latest version into the next turn's push pack. Task State staleness is mitigated through: (i) versioning with provenance (each version references the turn that produced it), (ii) periodic recomputation triggered by the system when the version age exceeds a configurable threshold, and (iii) the `recall` tool as a fallback when the agent detects inconsistency.

··· 1 unchanged paragraph folded ···

v2.0 · 4.4 Layer 1 — Continuous event ingestion and asynchronous indexing### 4.4 Layer 1 --- Continuous event ingestion and indexing (plain English)
v2.4 · 4.4 Layer 1 — Continuous event ingestion and asynchronous indexing### 4.4 Layer 1 — Continuous event ingestion and asynchronous indexing
v2.0 · 4.4 Layer 1 --- Continuous event ingestion and indexing (plain English)Layer 1 persists each event as it occurs and updates the retrieval surface immediately (full-text indexes, vector embeddings where appropriate, and metadata indexes). Large tool results are "artifactized": the event stores a pointer to an artifact rather than inlining the entire output into the cacheable text store. This ensures that, even if the context window evicts the raw evidence moments later, the system can still retrieve exact strings and provenance. The ingestion pipeline is designed to be safe under bursts (batchable) but must complete before eviction to avoid gaps in recall.
removed in v2.4
not in v2.0
v2.4 · 4.4 Layer 1 — Continuous event ingestion and asynchronous indexingLayer 1 persists each event as it occurs and updates the retrieval surface. Large tool results are "artifactized": the event stores a pointer to an artifact (with a content-aware preview window) rather than inlining the entire output.
not in v2.0
v2.4 · 4.4 Layer 1 — Continuous event ingestion and asynchronous indexing**Structure-Aware Preview.** The preview strategy is pluggable and content-type aware. While "tail-only" (last 5-10 lines) works for stack traces and build logs, it fails for structured data or search results. ENGRAM implements a heuristic preview extractor: - **Logs/Stderr:** Tail preview (last 10 lines). - **JSON:** Head preview (first 5 lines) + "..." + Tail (last 2 lines) + key count summary. - **Search (grep):** Match context (lines surrounding the match) rather than file tail. - **Table/CSV:** Header + first 2 rows + row count.
not in v2.0
v2.4 · 4.4 Layer 1 — Continuous event ingestion and asynchronous indexingThis ensures that the "preview" injected into the context is a **semantic signpost**, not just a byte-slice. The full artifact remains retrievable via `recall` using the artifact ID.
not in v2.0
v2.4 · 4.4 Layer 1 — Continuous event ingestion and asynchronous indexing**Asynchronous indexing.** Embedding computation is the most expensive indexing operation. ENGRAM decouples embedding from the synchronous event-persistence path:
not in v2.0
v2.4 · 4.4 Layer 1 — Continuous event ingestion and asynchronous indexing- **Synchronous (blocking):** Event persistence and full-text index updates complete before the event is considered durable. These operations are fast (single-digit milliseconds for SQLite/FTS5). - **Asynchronous (batched):** Vector embedding runs in a background worker, batching recent events for efficiency. - **Gap coverage:** The hot tail (last $k$ turns retained verbatim in the context window) covers the latency gap: any event recent enough to lack an embedding is recent enough to still be in the hot tail, and thus directly visible to the model.
not in v2.0
v2.4 · 4.4 Layer 1 — Continuous event ingestion and asynchronous indexing**Invariant (Indexing-before-Eviction):** Eviction never targets events that are not yet indexed. This ensures that no event is evicted before it is searchable.

··· 1 unchanged paragraph folded ···

v2.0 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assembly### 4.5 Layer 2 --- Per-turn retrieval and context assembly
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assembly### 4.5 Layer 2 — Hybrid push/pull retrieval and context assembly
v2.0 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assemblyOn every turn, TRACE builds a bounded **context pack** consisting of:
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assemblyOn every turn, ENGRAM builds a bounded **context pack** using a hybrid push/pull model:
v2.0 · 4.5 Layer 2 --- Per-turn retrieval and context assembly- a stable system/policy prefix, - the current Task State object, - a **retrieval pack** (bounded evidence pulled from storage), - a short "hot tail" of recent turns, - the user's new message.
removed in v2.4
v2.0 · 4.5 Layer 2 --- Per-turn retrieval and context assemblyThe retrieval pack is assembled from multiple candidate sources (vector neighbors, keyword hits, pointer expansion from Task State, pinned typed objects) and then packed under a strict token budget. The key design choice is that retrieval is *mandatory* and *budgeted*---not a best-effort tool call the agent may forget to make.
removed in v2.4
v2.0 · 4.5 Layer 2 --- Per-turn retrieval and context assembly(See **Annex A.2** for retrieval candidate generation, reranking, and packing.)
removed in v2.4
not in v2.0
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assembly**Push (system-managed, every turn, cheap).** The system proactively injects a **Working Set Pack** designed to minimize the probability of immediate retrieval necessity. Formally, we approximate the Denning Working Set $W(t, \tau)$—the set of pages (events) referenced during the current task phase $\tau$—using the Task State as a predictor. The push pack contains:
not in v2.0
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assembly1. A stable system/policy prefix (persona state, hard rules, knowledge blocks). 2. The current Task State object (small, structured, ~500–800 tokens). 3. Any time-range markers (hierarchically merged to fit budget). 4. A short "hot tail" of recent turns (last $k$ turns). 5. The user's new message.
not in v2.0
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assemblyThis composition is not heuristic; it targets the highest probability-density region of the access distribution: (1) global invariants (system), (2) current objectives (Task State), and (3) immediate recency (tail).
not in v2.0
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assembly**Pull (agent-initiated, on demand, richer).** ENGRAM exposes a `recall(query)` tool. To minimize latency: - **Parallel Retrieval:** The agent may issue `recall(["query1", "query2", ...])` to batch requests. - **Speculative Execution:** Where the inference engine supports it, `recall` can be triggered speculatively during user input processing (based on intent classification) or in parallel with initial thought generation.
not in v2.0
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assemblyThe `recall` tool: 1. Executes task-conditioned retrieval (§5) against the full retrieval surface. 2. Returns a bounded retrieval pack (≤ $B_{\text{ret}}$ tokens). 3. Logs the query and results for offline evaluation.
not in v2.0
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assemblyThis hybrid design avoids the cost of expensive retrieval on every turn while ensuring the agent is never permanently blocked by missing context.
not in v2.0
v2.4 · 4.5 Layer 2 — Hybrid push/pull retrieval and context assembly(See **Annex A.2** for the context pack builder and recall tool protocol.)

··· 4 unchanged paragraphs folded ···

v2.0 · 5.1 Why "static relevance" failsA purely similarity-driven retriever (vector/FTS) tends to over-inject:
removed in v2.4
v2.0 · 5.1 Why "static relevance" fails- highly similar but **obsolete** objectives (older versions), - low-value "debug noise" that matches keywords but is not useful now, - "interesting" tool output fragments that are semantically close but not decision-relevant.
removed in v2.4
v2.0 · 5.1 Why "static relevance" failsConversely, it under-injects:
removed in v2.4
v2.0 · 5.1 Why "static relevance" fails- the **latest** task objectives and constraints (which are often short and not keyword-rich), - **decision rationales** that are critical but not lexically similar, - "negative knowledge" ("we tried X and it failed") unless explicitly asked.
removed in v2.4
v2.0 · 5.2 Conditioning on task, premises, and expected future needs### 5.2 Conditioning on task, premises, and expected future needs
removed in v2.4
v2.0 · 5.2 Conditioning on task, premises, and expected future needsTRACE introduces a **task-conditioned scoring function** that modulates a base retrieval score.
removed in v2.4
v2.0 · 5.2 Conditioning on task, premises, and expected future needs- **Base score** captures generic relevance: semantic similarity, keyword match, recency, access frequency, type priors, and sensitivity penalties. - **Task-conditioned modifier** adjusts priority according to the current task and phase (planning vs. execution vs. evaluation), and according to whether the memory was produced under premises that still hold.
removed in v2.4
v2.0 · 5.2 Conditioning on task, premises, and expected future needsA practical implementation uses metadata attached to events and derived objects:
removed in v2.4
v2.0 · 5.2 Conditioning on task, premises, and expected future needs- **Task binding:** each memory item is associated with a `task_id` (or episode cluster). - **Premise signature:** each item references the Task State version (or premise set) active at write time (e.g., constraints, chosen approach, environment assumptions). - **Supersession links:** items can supersede earlier versions ("objective v3 supersedes v2"), enabling retrieval to privilege the latest and demote archival variants. - **Utility hints:** optional tags at write time (human- or model-generated) indicating expected future use (e.g., "needed for final report," "temporary debug," "decision record").
removed in v2.4
v2.0 · 5.2a Continuous Ingestion Pipeline### 5.2a Continuous Ingestion Pipeline
removed in v2.4
v2.0 · 5.2a Continuous Ingestion PipelineA critical design requirement, informed by analysis of contemporary agent memory systems (notably GravityClaw's Pinecone-based architecture), is that event extraction and importance scoring must occur **continuously on every turn**, not only during consolidation or compaction. GravityClaw's always-on auto-extraction ensures that every interaction is immediately searchable; TRACE must match this freshness guarantee while preserving its lossless-store thesis.
removed in v2.4
v2.0 · 5.2a Continuous Ingestion PipelineConcretely, the importance score $\iota$ described in Section 4.3 is computed at **ingest time** (Layer 1), the moment each event is persisted and indexed. This means the score is available to the retrieval scoring function (Layer 2) on the very next turn—not after a nightly batch or a consolidation trigger. The pipeline is:
removed in v2.4
v2.0 · 5.2a Continuous Ingestion Pipeline1. **Event arrives** (user message, tool result, agent response). 2. **Layer 1 ingests**: persist event, compute $\iota$ using the deterministic heuristic (Section 4.3), update FTS/vector indexes. 3. **Layer 2 retrieves**: on the next turn, the task-conditioned scoring function (Section 5.2) uses $\iota$ as a retrieval weight, ensuring high-importance events surface immediately.
removed in v2.4
v2.0 · 5.2a Continuous Ingestion PipelineThis closes the "always-on extraction" gap: TRACE does not defer importance assessment to a later consolidation phase, which would leave a window where recent high-importance events (e.g., a critical error, a user directive) compete with low-importance noise on equal footing. The cost is minimal—the importance heuristic is a deterministic rule table, not an LLM call—and the benefit is that retrieval quality improves from the first turn after an important event occurs.
removed in v2.4
not in v2.0
v2.4 · 5.1 Why "static relevance" failsA purely similarity-driven retriever (vector/FTS) tends to over-inject highly similar but **obsolete** objectives, low-value "debug noise," and "interesting" fragments that are semantically close but not decision-relevant. Conversely, it under-injects the **latest** task objectives, **decision rationales**, and "negative knowledge" ("we tried X and it failed").
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility### 5.2 Formal derivation: task-conditioned scoring from expected utility
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utilityWe derive the task-conditioned modifier from a principled optimization objective rather than heuristic intuition.
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility**Objective.** Let $\tau$ be the current task state and $\mathcal{E} = \{e_1, \ldots, e_n\}$ the event store. We seek a context pack $C^* \subseteq \mathcal{E}$ with $|C^*| \leq B$ tokens that maximizes the expected probability of task completion:
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility$$C^* = \arg\max_{C \subseteq \mathcal{E},\; |C| \leq B} \; \mathbb{E}\left[P(\text{complete} \mid C, \tau)\right]$$
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility**Submodular decomposition.** We adopt a **modeling assumption**: retrieved events contribute to task completion with diminishing marginal returns—each additional event adds information, but redundant events add less. Under this assumption, the objective $f(C) = \mathbb{E}[P(\text{complete} \mid C, \tau)]$ is monotone submodular in $C$. For monotone submodular maximization under a cardinality constraint, the greedy algorithm achieves a $(1 - 1/e)$-approximation (Nemhauser et al., 1978).
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility**When submodularity holds and when it fails.** Submodularity holds when events are independently informative—each event contributes information regardless of what else is retrieved. This is the common case for heterogeneous event types (a file path, an error message, and a decision rationale are independently useful). Submodularity is **violated** when events are strongly complementary—e.g., two events that are jointly necessary but individually meaningless (a cryptographic key split across two events). In practice, such strong complementarity is rare in agent interaction traces. Even when strict submodularity is violated, Bian et al. (2017) show that the greedy algorithm achieves strong approximation guarantees for *approximately* submodular functions, with degradation proportional to the degree of non-submodularity. We therefore treat this as a reasonable modeling assumption rather than a proven property.
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utilityThe greedy algorithm selects events by marginal utility:
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility$$e^* = \arg\max_{e \in \mathcal{E} \setminus C} \; u(e, \tau, C)$$
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utilitywhere the marginal utility is:
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility$$u(e, \tau, C) = \mathbb{E}[P(\text{complete} \mid C \cup \{e\}, \tau)] - \mathbb{E}[P(\text{complete} \mid C, \tau)]$$
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility**Tractable approximation.** Since computing $P(\text{complete} \mid \cdot)$ exactly is intractable, we decompose $u(e, \tau, C)$ into tractable proxy factors:
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility$$\text{score}(e, q, \tau) = \underbrace{\text{base}(e, q)}_{\text{query relevance}} \cdot \underbrace{m(e, \tau)}_{\text{task-conditioned modifier}}$$
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utilitywhere $\text{base}(e, q)$ captures generic relevance (semantic similarity, BM25, recency, type priors) and $m(e, \tau)$ captures task-specific marginal utility through four independently estimable factors:
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility$$m(e, \tau) = \underbrace{\text{prem}(e, \tau)}_{\substack{\text{premise} \\ \text{compatibility}}} \cdot \underbrace{\text{phase}(e, \tau)}_{\substack{\text{phase} \\ \text{salience}}} \cdot \underbrace{(1 - \text{sup}(e))}_{\substack{\text{supersession} \\ \text{discount}}} \cdot \underbrace{\text{task\_rel}(e, \tau)}_{\substack{\text{task} \\ \text{relevance}}}$$
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utilityEach factor is justified by its contribution to marginal utility:
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility- **Premise compatibility** $\text{prem}(e, \tau) \in [0,1]$: Events produced under premises incompatible with the current task state have near-zero marginal utility—they describe a world that no longer holds. Computed deterministically by comparing $e.\text{premise\_ref}$ against $\tau.\text{current\_premises}$.
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility- **Phase salience** $\text{phase}(e, \tau) \in [0.1, 2.0]$: During planning, decision records have high marginal utility; during debugging, tool outputs do. Implemented as a lookup table mapping (task phase, event type) → salience weight.
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility- **Supersession discount** $\text{sup}(e) \in \{0, 1\}$: A superseded event (e.g., "objective v2" superseded by "objective v3") has near-zero marginal utility because the superseding event subsumes its information content. Computed deterministically from explicit supersession links.
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility- **Task relevance** $\text{task\_rel}(e, \tau) \in [0, 1]$: Events bound to unrelated tasks contribute minimally. Computed by task-ID matching with a cross-task decay factor.
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility**Greedy selection with MMR.** After scoring, candidates are selected greedily with Maximal Marginal Relevance (Carbonell & Goldstein, 1998) to control redundancy:
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utility$$\text{MMR}(e) = \lambda \cdot \text{score}(e, q, \tau) - (1 - \lambda) \cdot \max_{s \in S} \cos(\text{emb}(e), \text{emb}(s))$$
not in v2.0
v2.4 · 5.2 Formal derivation: task-conditioned scoring from expected utilityThis greedy-MMR procedure inherits the $(1-1/e)$ approximation guarantee from submodular maximization theory when the diversity penalty is bounded (Krause & Golovin, 2014). In practice, we set $\lambda = 0.7$.

··· 1 unchanged paragraph folded ···

v2.0 · 5.3 Examples (selective attention in agents)- If the task is **"develop feature X"**, retrieval prioritizes: current objectives, current constraints, latest architecture decision record, and current plan. It deprioritizes: exploratory errors and dead ends (unless the user asks for a postmortem). - If the task includes **"self-assessment at the end"**, retrieval elevates mistakes and successes throughout, because future evaluation depends on them. - If objectives were updated multiple times, retrieval should treat **only the latest objective set as live**, while older sets become archival unless explicitly requested ("what changed since v1?").
v2.4 · 5.3 Examples (selective attention in agents)- If the task is **"develop feature X"**, retrieval prioritizes: current objectives, current constraints, latest architecture decision record, and current plan. It deprioritizes: exploratory errors and dead ends (unless the user asks for a postmortem). - If the task includes **"self-assessment at the end"**, retrieval elevates mistakes and successes throughout, because future evaluation depends on them. - If objectives were updated multiple times, retrieval should treat **only the latest objective set as live**, while older sets become archival unless explicitly requested.

··· 1 unchanged paragraph folded ···

v2.0 · 5.4 Outcome: retrieval that matches *need*, not just similarityTask-aware retrieval reframes relevance as "usefulness for the current task under current premises," approximating human selective attention: you notice different things depending on what you are trying to do.
v2.4 · 5.4 Outcome: retrieval that matches *need*, not just similarityTask-aware retrieval reframes relevance as "usefulness for the current task under current premises," approximating human selective attention: you notice different things depending on what you are trying to do. This framing has parallels in dialogue state tracking (Henderson et al., 2014): just as DST systems maintain explicit belief states to guide response generation, ENGRAM maintains explicit task state to guide retrieval.
v2.0 · 5.4 Outcome: retrieval that matches *need*, not just similarity(See **Annex A.3** for a concrete task-conditioned scoring formulation and supersession handling.)
removed in v2.4
not in v2.0
v2.4 · 5.5 Retrieval completeness: when is a retrieval pack "correct"?### 5.5 Retrieval completeness: when is a retrieval pack "correct"?
not in v2.0
v2.4 · 5.5 Retrieval completeness: when is a retrieval pack "correct"?A retrieval system over an unbounded event store cannot guarantee perfect recall; some relevant events may always be missed. However, we can define a useful **completeness condition**.
not in v2.0
v2.4 · 5.5 Retrieval completeness: when is a retrieval pack "correct"?**Definition (k-hop retrievability).** An event $e$ is *k-hop retrievable* from a context pack $P$ if there exists a chain of at most $k$ retrieval operations starting from information in $P$ that returns $e$ (or an artifact containing $e$'s content). Concretely:
not in v2.0
v2.4 · 5.5 Retrieval completeness: when is a retrieval pack "correct"?- *0-hop*: $e$ is directly present in the context pack. - *1-hop*: a single `recall(query)` call, using information visible in $P$, returns $e$. - *2-hop*: a `recall` call returns a result that contains enough information to formulate a second `recall` call that returns $e$.
not in v2.0
v2.4 · 5.5 Retrieval completeness: when is a retrieval pack "correct"?**Completeness condition.** A retrieval pack is *task-complete* if all events referenced by `task_state.key_events` are 2-hop retrievable from the assembled context pack.
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem### 5.6 Retrieval Completeness Theorem
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremWe formalize the probabilistic guarantees on retrieval completeness.
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem**Theorem 1 (Bounded Retrieval Completeness).** Let $\mathcal{S}$ be a ENGRAM event store satisfying the Indexing-before-Eviction invariant (§4.4). Let $\tau$ be the current task state with $K = |\tau.\text{key\_events}|$ key events. Define:
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem- $p_{\text{idx}}$: probability that an event is correctly indexed (embedded + FTS-indexed) at retrieval time. Under the Indexing-before-Eviction invariant, $p_{\text{idx}} = 1$ for all evicted events. - $p_{\text{match}}$: probability that a single retrieval attempt returns a correctly-indexed key event. This depends on embedding quality, keyword coverage, and scoring calibration.
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremThen for any key event $e_i \in \tau.\text{key\_events}$:
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem$$P(e_i \text{ is 2-hop retrievable}) \geq p_{\text{idx}} \cdot \left(1 - (1 - p_{\text{match}})^2\right)$$
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremAnd for the full key-event set, assuming independent retrieval outcomes:
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem$$P(\text{all } K \text{ key events are 2-hop retrievable}) \geq \left[p_{\text{idx}} \cdot \left(1 - (1 - p_{\text{match}})^2\right)\right]^K$$
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem*Proof.* An event $e_i$ fails to be 2-hop retrievable only if (a) it was not indexed ($1 - p_{\text{idx}}$), or (b) it was indexed but both independent retrieval attempts fail ($p_{\text{idx}} \cdot (1 - p_{\text{match}})^2$). The two retrieval attempts are independent because the first-hop result provides new information (topic context, temporal references) that enables a differently-formulated second query. Thus:
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem$$P(e_i \text{ unreachable}) \leq (1 - p_{\text{idx}}) + p_{\text{idx}} \cdot (1-p_{\text{match}})^2$$
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremUnder the Indexing-before-Eviction invariant, $p_{\text{idx}} = 1$ for evicted events, so:
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem$$P(e_i \text{ unreachable}) \leq (1-p_{\text{match}})^2$$
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremThe joint probability follows from the independence of per-event retrieval failures (different key events have different embeddings and keywords). $\square$
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem**Corollary.** Under the hypothesis that $p_{\text{match}} \geq 0.95$ for well-indexed key events with strong keyword and embedding signatures (validated in §10A):
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem$$P(e_i \text{ is 2-hop retrievable}) \geq 1 - (0.05)^2 = 0.9975$$
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremFor $K = 20$ key events:
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem$$P(\text{all retrievable}) \geq 0.9975^{20} \approx 0.951$$
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremThis establishes a lower bound on system-level retrieval completeness: even with 20 key events, the probability of complete retrieval exceeds 95%. Our preliminary validation (§10A) empirically confirms this bound.
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem**Remark (Correlated Failures).** The joint probability calculation assumes independent per-event retrieval failures. In practice, failures may be correlated: if the embedding model systematically underperforms on a content type (e.g., SQL queries, hexadecimal strings), multiple key events of that type may fail simultaneously. Let $\rho$ denote the average pairwise correlation between retrieval failure indicators. Under equicorrelated failures, the joint failure probability increases:
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem$$P(\text{any key event unreachable}) \leq 1 - \left(1 - K \cdot (1-p_{\text{match}})^2\right) \cdot \left(1 + \rho \cdot \binom{K}{2} \cdot (1-p_{\text{match}})^4\right)^{-1}$$
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremFor moderate correlation ($\rho = 0.3$) and $K = 20$:
not in v2.0
v2.4 · 5.6 Retrieval Completeness Theorem$$P(\text{all retrievable}) \approx 0.92 \text{ (vs. } 0.95 \text{ under independence)}$$
not in v2.0
v2.4 · 5.6 Retrieval Completeness TheoremENGRAM mitigates correlation through **dual-retrieval decorrelation**: FTS (keyword matching) and vector search (embedding similarity) use fundamentally different representations. An event that produces a poor embedding may still have distinctive keywords (e.g., SHA-256 hashes are excellent FTS targets regardless of embedding quality). The correlation between FTS failures and embedding failures is expected to be low ($\rho_{\text{cross}} < 0.1$) for most content types, which is the primary decorrelation mechanism. The preliminary validation (§10A.5) provides type-specific evidence: keyword-rich needles achieve 98% recall vs. 88% for semantic needles, confirming that the two retrieval surfaces complement each other.
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring function### 5.7 Worst-case analysis of the scoring function
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring functionThe task-conditioned modifier $m(e, \tau)$ can introduce two types of error:
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring function**Type I (false suppression).** A relevant event is scored below the retrieval threshold due to incorrect modifier values. This occurs when:
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring function- $\text{prem}(e, \tau)$ is incorrectly low (metadata error in premise references). - $\text{sup}(e) = 1$ when $e$ is not actually superseded (incorrect supersession link). - $\text{phase}(e, \tau)$ assigns low salience to the event's type in the current phase.
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring functionSince premise compatibility and supersession are computed deterministically from explicit metadata, their error rate is bounded by the metadata corruption rate $\epsilon_{\text{meta}}$. Phase salience is heuristic with bounded error $\epsilon_{\text{phase}}$. The worst-case false suppression rate is:
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring function$$P(\text{false suppress}) \leq \epsilon_{\text{meta}} + (1 - \epsilon_{\text{meta}}) \cdot \epsilon_{\text{phase}}$$
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring functionFor well-maintained metadata ($\epsilon_{\text{meta}} < 0.01$) and calibrated phase salience ($\epsilon_{\text{phase}} < 0.05$):
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring function$$P(\text{false suppress}) < 0.01 + 0.99 \cdot 0.05 \approx 0.06$$
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring function**Type II (false elevation).** An irrelevant event is scored above the threshold, wasting budget. Since the retrieval budget $B_{\text{ret}}$ is hard-capped and MMR provides diversity, false elevation reduces precision but does not compromise safety—the agent receives extra noise but no critical information is lost.
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring function**Mitigation.** The `recall` tool provides a safety net: if an agent detects missing information despite the push pack, it can issue a targeted query that bypasses the generic scoring pipeline. The worst-case scenario—a relevant key event falsely suppressed *and* the agent failing to recall it—has probability bounded by $P(\text{false suppress}) \cdot (1 - p_{\text{match}}) < 0.06 \cdot 0.05 = 0.003$ per event.
not in v2.0
v2.4 · 5.7 Worst-case analysis of the scoring function(See **Annex A.3** for the complete task-conditioned scoring algorithm.)

··· 2 unchanged paragraphs folded ···

v2.0 · 6. Pointer-Based Compaction (Compaction as Cache Eviction)Pointer compaction is TRACE's replacement for narrative compaction.
v2.4 · 6. Pointer-Based Compaction (Compaction as Cache Eviction)Pointer compaction is ENGRAM's replacement for narrative compaction.
v2.0 · 6.1 What compaction does in ENGRAM### 6.1 What compaction does in TRACE
v2.4 · 6.1 What compaction does in ENGRAM### 6.1 What compaction does in ENGRAM
v2.0 · 6.1 What compaction does in ENGRAMWhen the context window approaches its limit, TRACE:
v2.4 · 6.1 What compaction does in ENGRAMWhen the context window approaches its limit, ENGRAM:
v2.0 · 6.1 What compaction does in TRACE1. selects eviction candidates (typically older tool results first, then older turns), 2. verifies those spans are already persisted and indexed (Layer 1 invariant), 3. evicts the spans from the cache, 4. inserts a **pointer manifest** containing: - evicted event ID range(s), - anchor events (decisions, errors, constraints), - referenced artifact IDs, - retrieval hints (entities, file paths, tool names, keywords), - a reference to the Task State version.
removed in v2.4
not in v2.0
v2.4 · 6.1 What compaction does in ENGRAM1. Selects eviction candidates using a type-weighted LRU policy (§6.2). 2. Verifies those spans are already persisted and indexed (Layer 1 invariant). 3. Evicts the spans from the cache. 4. Inserts a **time-range marker** containing the evicted time range, key topics from event metadata and Task State bindings, and a retrieval directive.
v2.0 · 6.1 What compaction does in ENGRAMThe manifest is deterministic and provenance-preserving; it is not a narrative summary and does not attempt to compress evidence into a single prose paragraph.
v2.4 · 6.1 What compaction does in ENGRAMThe marker is compact (typically 30–60 tokens), deterministic, and does not attempt to compress evidence into prose. It serves as a **signpost**, not a summary.
not in v2.0
v2.4 · 6.2 Eviction ordering: engaging with cache theory### 6.2 Eviction ordering: engaging with cache theory
not in v2.0
v2.4 · 6.2 Eviction ordering: engaging with cache theoryENGRAM's default eviction policy is a **type-weighted LRU** with the following priority ordering:
not in v2.0
v2.4 · 6.2 Eviction ordering: engaging with cache theory1. **Oldest tool results** (evict first): largest items, most compressible via artifactization, and most reliably retrievable via keyword/hash search. 2. **Oldest tool calls**: smaller than results, but retrievable via the associated result's artifact. 3. **Oldest dialogue turns**: smaller, but contain decision rationale that is harder to reconstruct. 4. **Never evict**: system blocks, Task State, last-$k$ turns, time-range markers.
not in v2.0
v2.4 · 6.2 Eviction ordering: engaging with cache theory**Connection to optimal page replacement.** Belady's MIN algorithm (Belady, 1966) proves that the optimal eviction policy evicts the item whose next access is farthest in the future—but this requires an oracle for future access patterns. In classical caching, no such oracle exists; LRU approximates it using recency as a proxy for future access likelihood. ENGRAM improves on this approximation: **Task State serves as a noisy oracle for future access patterns.** By encoding active goals, constraints, key events, and expected next actions, Task State predicts which events are likely to be needed soon (those related to active objectives and open loops) and which are not (completed sub-tasks, resolved errors). The type-weighted policy further refines this: tool results are evicted first not only because they are largest but because they are the most reliably retrievable on demand (high-entropy keyword signatures), making the *cost of a cache miss* lowest for this type. This framing elevates ENGRAM's eviction policy from heuristic type-weighted LRU to a principled approximation of optimal replacement under task-derived future-need prediction.
not in v2.0
v2.4 · 6.2 Eviction ordering: engaging with cache theoryENGRAM's time-range markers serve a function analogous to ARC's ghost entries (Megiddo & Modha, 2003): they record what was evicted and enable re-fetching. Unlike ARC's ghost entries (which track only recency/frequency metadata), time-range markers carry semantic topic hints that guide retrieval.
not in v2.0
v2.4 · 6.2 Eviction ordering: engaging with cache theoryA key difference from classical caching is that ENGRAM's eviction is **non-destructive**: evicted items remain in the durable store. This makes the cost of a "cache miss" much lower—it costs a tool call and some tokens, not a computation restart.
v2.0 · 6.3 Why this is safer than narrative summaries### 6.2 Why this is safer than narrative summaries
v2.4 · 6.3 Why this is safer than narrative summaries### 6.3 Why this is safer than narrative summaries
v2.0 · 6.2 Why this is safer than narrative summaries- **No "only copy" destruction:** the lossless store remains authoritative. - **Reduced hallucination surface:** the manifest is structured and mostly identifier-based. - **Recoverability:** if retrieval misses something, the system can broaden or follow pointers; the evidence still exists.
removed in v2.4
v2.0 · 6.2 Why this is safer than narrative summaries**A clarification on pointer comprehension:** pointer manifests are consumed by the system retrieval layer (Layer 2), not by the LLM directly. The LLM receives the *retrieval pack* — pre-assembled, readable evidence extracted from the lossless store. The pointers serve as machine-readable indexes enabling systematic retrieval, not as prompts the model must interpret. This design avoids the risk of LLMs hallucinating evicted content based on sparse hints, a failure mode that would arise if pointers were injected into the LLM's context without expansion.
removed in v2.4
not in v2.0
v2.4 · 6.3 Why this is safer than narrative summaries- **No "only copy" destruction:** the lossless store remains authoritative. - **Reduced hallucination surface:** time-range markers are structured and factual; they do not generate novel claims. - **Recoverability:** if retrieval misses something, the agent can broaden the query; the evidence still exists. - **No compounding loss:** narrative summaries of summaries lose information exponentially; time-range markers do not compound because they are not re-summarized.
not in v2.0
v2.4 · 6.4 Hierarchical Marker Merging### 6.4 Hierarchical Marker Merging
not in v2.0
v2.4 · 6.4 Hierarchical Marker MergingAs compaction cycles accumulate, time-range markers consume an increasing fraction of the context budget. To ensure $O(1)$ overhead for infinite history, ENGRAM implements **hierarchical marker merging**.
not in v2.0
v2.4 · 6.4 Hierarchical Marker Merging**Algorithm.** When the number of markers exceeds a soft cap $K_{\max}$ (e.g., 20): 1. Identify adjacent markers $\mu_i, \mu_{i+1}$. 2. Create parent marker $\mu_{parent}$ with range $[t_{\text{start}}(\mu_i), t_{\text{end}}(\mu_{i+1})]$. 3. Set topic set $\mathcal{K}_{parent} = \text{top-k}(\mathcal{K}_i \cup \mathcal{K}_{i+1})$ by TF-IDF or explicit importance. 4. Replace $\mu_i, \mu_{i+1}$ with $\mu_{parent}$.
not in v2.0
v2.4 · 6.4 Hierarchical Marker MergingThis creates a logarithmic "skyline" of history: recent history has fine-grained markers, while ancient history is covered by coarse-grained summary markers.
v2.0 · 6.4 Hierarchical Marker Merging(See **Annex A.4** for eviction selection and manifest construction under hard token constraints.)
v2.4 · 6.4 Hierarchical Marker Merging(See **Annex A.4** for eviction selection and marker construction under hard token constraints.)

··· 2 unchanged paragraphs folded ···

v2.0 · 7. Hierarchical Agent Planning (Planner/Executor/Sub-Executors)Long tasks often exceed a single agent's effective working memory. TRACE enables **hierarchical planning** where different agent levels maintain different contexts and retrieval surfaces.
v2.4 · 7. Hierarchical Agent Planning (Planner/Executor/Sub-Executors)Long tasks often exceed a single agent's effective working memory. ENGRAM enables **hierarchical planning** where different agent levels maintain different contexts and retrieval surfaces.

··· 2 unchanged paragraphs folded ···

v2.0 · 7.1 The hierarchyEach level has:
removed in v2.4
v2.0 · 7.1 The hierarchy- its own bounded context window (cache), - its own Task State (appropriate abstraction), - its own retrieval surface tuned to its role.
removed in v2.4
not in v2.0
v2.4 · 7.1 The hierarchyEach level has its own bounded context window (cache), Task State, retrieval surface, and access to the shared `recall` tool for cross-level evidence retrieval.

··· 1 unchanged paragraph folded ···

v2.0 · 7.2 Why separation helpsThe planner does not need full tool logs; it needs the *meaning* of execution results and their provenance. The executor does not need the full strategic plan; it needs only the local objectives, constraints, and relevant prior evidence.
v2.4 · 7.2 Why separation helpsThe planner does not need full tool logs; it needs the *meaning* of execution results and their provenance. The executor does not need the full strategic plan; it needs only the local objectives, constraints, and relevant prior evidence. Pointer-based memory makes this natural: the planner stores pointers to detailed evidence without paying their token cost. This decomposition is aligned with StackPlanner's finding (Zhang et al., 2026) that hierarchical planning with explicit level separation outperforms flat planning.
v2.0 · 7.2 Why separation helpsPointer-based memory makes this natural: the planner stores pointers to detailed evidence without paying their token cost; executors can fetch details on demand, then return compact, provenance-linked reports.
removed in v2.4

··· 1 unchanged paragraph folded ···

v2.0 · 7.3 Hierarchical planning diagram```text +-----------------------------------------------------------------------------------+ | TRACE hierarchical planning | +-----------------------------------------------------------------------------------+
v2.4 · 7.3 Hierarchical planning diagram```text +-----------------------------------------------------------------------------------+ | ENGRAM hierarchical planning | +-----------------------------------------------------------------------------------+
v2.0 · 7.3 Hierarchical planning diagram(Level 1) PLANNER context window (small, strategic) +---------------------------------------------------------------+ | System + Policies | | Task State (strategy, milestones, acceptance criteria) | | Retrieval Pack: | | - decision records, constraints, latest objective versions | | - pointers to executor reports and key artifacts | | Recent tail | +---------------------------+-----------------------------------+ | delegate subtask | (pointer to plan slice + constraints) v (Level 2) EXECUTOR context window (detailed, tactical) +---------------------------------------------------------------+ | System + Tool protocols | | Task State (local objective, steps, checkpoints) | | Retrieval Pack: | | - relevant artifacts/logs/code, local history | | - pointer to planner's plan node | | Hot tail + tool outputs | +---------------------------+-----------------------------------+ | report up | (compact report + provenance pointers) v (Level 1) PLANNER updates Task State, stores pointers ```
v2.4 · 7.3 Hierarchical planning diagram(Level 1) PLANNER context window (small, strategic) +---------------------------------------------------------------+ | System + Policies | | Task State (strategy, milestones, acceptance criteria) | | Push Pack: | | - decision records, constraints, latest objective versions | | - time-range markers for delegated execution spans | | recall(query) tool for drill-down into executor evidence | +---------------------------+-----------------------------------+ | delegate subtask | (pointer to plan slice + constraints) v (Level 2) EXECUTOR context window (detailed, tactical) +---------------------------------------------------------------+ | System + Tool protocols | | Task State (local objective, steps, checkpoints) | | Push Pack: | | - relevant artifacts (with tail previews), local history | | - pointer to planner's plan node | | recall(query) tool for retrieving prior evidence | | Hot tail + tool outputs | +---------------------------+-----------------------------------+ | report up | (compact report + provenance pointers) v (Level 1) PLANNER updates Task State, stores pointers ```
v2.0 · 7.3 Hierarchical planning diagram(See **Annex A.5** for a concrete protocol: delegation messages, report schemas, and pointer propagation across levels.)
removed in v2.4
not in v2.0
v2.4 · 7.3 Hierarchical planning diagram(See **Annex A.5** for the delegation/reporting protocol.)

··· 1 unchanged paragraph folded ···

v2.0 · 8. Hierarchical & Multi-Granularity Retrieval## 8. Hierarchical & Multi-Granularity Retrieval (Promoted to Core Design)
v2.4 · 8. Hierarchical & Multi-Granularity Retrieval## 8. Hierarchical & Multi-Granularity Retrieval
v2.0 · 8. Hierarchical & Multi-Granularity Retrieval (Promoted to Core Design)TRACE's lossless store makes it possible---and often necessary---to retrieve at multiple abstraction levels.
removed in v2.4

··· 1 unchanged paragraph folded ···

v2.0 · 8.1 Multi-granularity objectsTRACE supports retrieving different representations of the same underlying history:
v2.4 · 8.1 Multi-granularity objectsENGRAM supports retrieving different representations of the same underlying history:

··· 3 unchanged paragraphs folded ···

v2.0 · 8.2 RAPTOR-style trees as retrieval indexesRAPTOR constructs bottom-up summary trees from chunks, enabling retrieval at an appropriate level for the query. In TRACE, RAPTOR-like trees apply naturally to event streams: leaf nodes are events/episodes; internal nodes are clustered topic summaries.
v2.4 · 8.2 RAPTOR-style trees as retrieval indexesRAPTOR (Sarthi et al., 2024) constructs bottom-up summary trees from chunks. In ENGRAM, RAPTOR-like trees apply naturally to event streams: leaf nodes are events/episodes; internal nodes are clustered topic summaries. The key compatibility argument is: **hierarchies are indexes, not replacements.** Summaries may be lossy, but the ground truth remains available for drill-down.
v2.0 · 8.2 RAPTOR-style trees as retrieval indexesThe key compatibility argument is: **hierarchies are indexes, not replacements.** Summaries may be lossy, but the ground truth remains available for drill-down.
removed in v2.4

··· 1 unchanged paragraph folded ···

v2.0 · 8.3 Adaptive retrieval: choosing the right granularityTRACE can select granularity based on:
removed in v2.4
v2.0 · 8.3 Adaptive retrieval: choosing the right granularity- query specificity (exact string vs. "what did we decide?"), - task phase (planning needs abstraction; debugging needs fidelity), - token budget pressure (tight budgets prefer summaries), - uncertainty (low confidence triggers drill-down to raw events).
removed in v2.4
v2.0 · 8.4 Pros and cons### 8.4 Pros and cons
removed in v2.4
v2.0 · 8.4 Pros and cons**Pros** - Better token efficiency: inject one topic summary instead of twenty raw tool outputs. - Better alignment with task needs: planning vs. execution require different abstraction. - Improved robustness under long sessions: derived views can be stable and cacheable.
removed in v2.4
v2.0 · 8.4 Pros and cons**Cons** - Derived views introduce lossy representations (mitigated by lossless store + provenance). - Index maintenance cost: clustering, summarization, and updates are non-zero overhead. - Cold-start problem: hierarchies are weak until enough events accumulate.
removed in v2.4
not in v2.0
v2.4 · 8.3 Adaptive retrieval: choosing the right granularityENGRAM selects granularity based on query specificity (exact string → raw events; "what did we decide?" → decision records), task phase, token budget pressure, and uncertainty (low confidence triggers drill-down via `recall`). The hybrid push/pull model naturally supports this: the push pack includes high-level Task State, while agent-initiated `recall` queries can target any granularity level.
v2.0 · 8.3 Adaptive retrieval: choosing the right granularity(See **Annex A.6** for a multi-granularity retrieval policy, including drill-down triggers and provenance-linked packing.)
v2.4 · 8.3 Adaptive retrieval: choosing the right granularity(See **Annex A.6** for the multi-granularity retrieval policy.)

··· 2 unchanged paragraphs folded ···

v2.0 · 9. Formal Boundedness GuaranteesTRACE is explicitly engineered to keep both **per-turn context injection** and **total stored memory growth** bounded under clear invariants. The following proofs are presented as semi-formal sketches providing engineering confidence rather than formal mathematical proofs. The system degrades gracefully under edge conditions: events written but not yet indexed remain accessible in the hot tail and lossless store; under disk pressure, retrieval budgets automatically shrink to respect available resources.
removed in v2.4

··· 1 unchanged paragraph folded ···

v2.0 · 9.1 Per-turn context boundedness (hard caps)Let $B_{\text{ctx}}$ be the model's maximum context window (tokens). TRACE enforces fixed budgets:
v2.4 · 9.1 Per-turn context boundedness (hard caps)Let $B_{\text{ctx}}$ be the model's maximum context window (tokens). ENGRAM enforces fixed budgets:
v2.0 · 9.1 Per-turn context boundedness (hard caps)- $B_{\text{sys}}$: system/policy prefix (constant). - $B_{\text{task}}$: Task State block (hard cap, e.g., 500--800 tokens). - $B_{\text{tail}}$: hot tail (hard cap, e.g., last $k$ turns). - $B_{\text{ret}}$: retrieval pack (hard cap, e.g., 4K tokens). - $B_{\text{user}}$: user message (bounded by input limits). - $B_{\text{headroom}}$: reserved for tool calls/structured outputs.
v2.4 · 9.1 Per-turn context boundedness (hard caps)- $B_{\text{sys}}$: system/policy prefix (constant). - $B_{\text{task}}$: Task State block (hard cap, e.g., 500–800 tokens). - $B_{\text{tail}}$: hot tail (hard cap, e.g., last $k$ turns). - $B_{\text{markers}}$: accumulated time-range markers (hard cap; oldest markers are themselves evicted when exceeded). - $B_{\text{pull}}$: recall tool response budget (hard cap per invocation, max $M$ invocations per turn). - $B_{\text{user}}$: user message (bounded by input limits). - $B_{\text{headroom}}$: reserved for tool calls/structured outputs.
v2.0 · 9.1 Per-turn context boundedness (hard caps)**Invariant (Context Pack Bound):** \[ $B_{\text{sys}} + B_{\text{task}} + B_{\text{tail}} + B_{\text{ret}} + B_{\text{user}} + B_{\text{headroom}} \le B_{\text{ctx}}$. \]
v2.4 · 9.1 Per-turn context boundedness (hard caps)**Invariant (Context Pack Bound):** $$B_{\text{sys}} + B_{\text{task}} + B_{\text{tail}} + B_{\text{markers}} + B_{\text{user}} + B_{\text{headroom}} \le B_{\text{ctx}}$$
v2.0 · 9.1 Per-turn context boundedness (hard caps)TRACE's packer enforces $B_{\text{ret}}$ as a strict cap by truncating, dropping, or selecting fewer items---never by exceeding the budget. Therefore, **per-turn retrieval will never exceed the maximum window size**, by construction.
removed in v2.4
not in v2.0
v2.4 · 9.1 Per-turn context boundedness (hard caps)Note: $B_{\text{pull}}$ is not included in the static invariant because pull retrieval is on-demand and its results are injected as tool responses within the headroom budget.

··· 1 unchanged paragraph folded ···

v2.0 · 9.2 Linear growth of total memory (no quadratic blow-up)Assume an interaction of $T$ turns produces $O(1)$ events per turn on average (user msg, agent msg, plus a bounded number of tool calls/results under rate limits). The event store is append-only, so the number of stored events is $O(T)$.
removed in v2.4
v2.0 · 9.2 Linear growth of total memory (no quadratic blow-up)Indexes are also linear or better:
removed in v2.4
v2.0 · 9.2 Linear growth of total memory (no quadratic blow-up)- **Embeddings:** fixed-size vector per embedded event => $O(T)$ storage. - **FTS indexes:** approximately linear in total stored text length => $O(T)$. - **Derived objects:** if each episode/event produces at most a bounded number of derived records (decisions, episode summaries), derived storage is also $O(T)$.
removed in v2.4
v2.0 · 9.2 Linear growth of total memory (no quadratic blow-up)Thus the total memory footprint grows **linearly with interaction length**, not quadratically. Quadratic growth would typically arise from repeatedly rewriting or duplicating prior content (e.g., compaction summaries that accumulate and get re-summarized), or from storing cross-products of relationships. TRACE avoids this by storing immutable events once and treating summaries/hierarchies as derived indexes.
v2.4 · 9.2 Linear growth of total memory (no quadratic blow-up)Assume an interaction of $T$ turns produces $O(1)$ events per turn on average. The event store is append-only, so stored events are $O(T)$. Indexes are also linear or better: embeddings are $O(T)$ (fixed-size vector per event); FTS is $O(T)$; derived objects are $O(T)$ (bounded derivatives per event). Total memory footprint grows **linearly with interaction length**. Quadratic growth would arise from repeatedly rewriting or duplicating prior content (e.g., re-summarized compaction summaries). ENGRAM avoids this by storing immutable events once and treating summaries as derived indexes.

··· 1 unchanged paragraph folded ···

v2.0 · 9.3 Bounded total disk usage (policy, not wishful thinking)Linear growth can still be large. TRACE therefore distinguishes:
v2.4 · 9.3 Bounded total disk usage (policy, not wishful thinking)Linear growth can still be large. ENGRAM distinguishes:
v2.0 · 9.3 Bounded total disk usage (policy, not wishful thinking)- **Events:** small, mostly text + metadata; for personal assistants typically on the order of **~1--10 MB/day** depending on activity and logging density. - **Artifacts:** potentially large (logs, datasets, screenshots); can dominate disk usage. - **Indexes:** embeddings are fixed-size; FTS scales with text; both are predictable.
v2.4 · 9.3 Bounded total disk usage (policy, not wishful thinking)- **Events:** small, mostly text + metadata; ~1–10 MB/day for personal assistants. - **Artifacts:** potentially large; managed via compression, cold-storage archival after $N$ days, and optional online retention of hashes + metadata only. - **Indexes:** predictable (embeddings are fixed-size; FTS scales linearly with text).
v2.0 · 9.3 Bounded total disk usage (policy, not wishful thinking)**Policy (practical boundedness):** - Keep **events + indexes** indefinitely (small, high value). - Apply **artifact lifecycle management**: - compress artifacts at ingestion (e.g., gzip/zstd), - archive artifacts older than $N$ days to cold storage, - optionally retain only hashes + metadata online after archival, - allow "rehydration" on demand when pointers are followed.
v2.4 · 9.3 Bounded total disk usage (policy, not wishful thinking)**Policy:** Keep events + indexes indefinitely. Apply artifact lifecycle management: compress at ingestion, archive to cold storage after $N$ days, retain tail previews and metadata online, allow rehydration on demand.
v2.0 · 9.3 Bounded total disk usage (policy, not wishful thinking)This yields bounded *hot* storage and predictable long-term growth.
removed in v2.4
v2.0 · 9.3 Bounded total disk usage (policy, not wishful thinking)(See **Annex A.7** for a concrete retention/archival policy and an accounting model.)
v2.4 · 9.3 Bounded total disk usage (policy, not wishful thinking)(See **Annex A.7** for the retention/archival policy.)
not in v2.0
v2.4 · 9.4 Cost-Latency Analysis### 9.4 Cost-Latency Analysis
not in v2.0
v2.4 · 9.4 Cost-Latency AnalysisThe hybrid push/pull model introduces a tradeoff between the cost of the push pack and the latency of on-demand retrieval.
not in v2.0
v2.4 · 9.4 Cost-Latency Analysis**Latency Model.** The total latency $L$ for a turn is: $$L = L_{\text{gen}} + P(\text{pull}) \cdot (L_{\text{recall}} + L_{\text{gen2}})$$ where $L_{\text{gen}}$ is standard generation latency, $L_{\text{recall}}$ is the latency of the retrieval tool invocation (search + scoring), $L_{\text{gen2}}$ is the latency of the second generation pass with retrieved context, and $P(\text{pull})$ is the probability that the push pack is insufficient. * **Narrative compaction:** $P(\text{pull}) \approx 0$ (context is static), so $L \approx L_{\text{gen}}$. * **ENGRAM:** $P(\text{pull}) \approx 0.22$ (empirically, §10A.6). The 22% of turns requiring retrieval incur a ~2$\times$ latency penalty. However, for 78% of turns, $L \approx L_{\text{gen}}$ with a smaller prompt (due to compaction), often resulting in *lower* end-to-end latency than stuffing the window with irrelevant history.
not in v2.0
v2.4 · 9.4 Cost-Latency Analysis**Cost Model.** The total token cost $C$ is: $$C = C_{\text{push}} + P(\text{pull}) \cdot (C_{\text{query}} + C_{\text{retrieved}})$$ where $C_{\text{push}}$ is the fixed overhead of Task State + markers. * **Narrative compaction:** $C \approx C_{\text{window}}$ (always filling the window). * **ENGRAM:** $C_{\text{push}} \ll C_{\text{window}}$. By retrieving only when necessary, ENGRAM amortizes the cost of history. For a 200K window, filling it every turn costs ~$2/turn (at $10/M). ENGRAM's push pack (~2K tokens) plus occasional retrieval (~10K tokens) averages ~$0.05/turn.
not in v2.0
v2.4 · 9.4 Cost-Latency Analysis**Conclusion:** While individual retrieval turns are slower/costlier, the *amortized* cost and latency are significantly lower than "stuffing the window" strategies, and the *correctness* is higher than narrative strategies.

··· 1 unchanged paragraph folded ···

v2.0 · 10. Token Savings Analysis (OpenClaw Production Data)## 10. Token Savings Analysis (OpenClaw Production Data)
removed in v2.4
v2.0 · 10. Token Savings Analysis (OpenClaw Production Data)This section quantifies token dynamics using the production figures provided from OpenClaw.
removed in v2.4
v2.0 · 10.1 Baseline: narrative compaction in a 200K-token window### 10.1 Baseline: narrative compaction in a 200K-token window
removed in v2.4
v2.0 · 10.1 Baseline: narrative compaction in a 200K-token window- **Context window:** 200K tokens. - **Compaction trigger:** ~85% full. - **Compaction output:** ~6K characters approximately ~1.5K tokens. - **Information preserved:** ~2% of the original (operationally useful detail), because most tool-output evidence and exact strings are dropped.
removed in v2.4
v2.0 · 10.1 Baseline: narrative compaction in a 200K-token windowTwo compounding effects make this worse than it appears:
removed in v2.4
v2.0 · 10.1 Baseline: narrative compaction in a 200K-token window1. **Token ratio is not information ratio:** tool logs are verbose but contain needles; summaries remove needles disproportionately. 2. **Loss compounds over multiple compactions:** summaries summarize summaries, and omissions become permanent.
removed in v2.4
v2.0 · 10.1 Baseline: narrative compaction in a 200K-token windowIf each compaction preserves ~2% of the operational detail from the compacted portion, then after 3 compactions the preserved fraction is roughly $0.02^3 = 8 \times 10^{-6}$ (approximately 0.0008%) of that detail---effectively total loss for long-horizon debugging tasks.
removed in v2.4
v2.0 · 10.2 TRACE: pointer compaction + retrieval pack under the same window### 10.2 TRACE: pointer compaction + retrieval pack under the same window
removed in v2.4
v2.0 · 10.2 TRACE: pointer compaction + retrieval pack under the same windowUnder TRACE in the same 200K-token setting:
removed in v2.4
v2.0 · 10.2 TRACE: pointer compaction + retrieval pack under the same window- **Task State:** ~500 tokens (bounded, structured). - **Pointers/manifests:** ~200 tokens (IDs + hints). - **Per-turn retrieval pack:** ~4K tokens injected (bounded). - **Information preserved:** 100% on disk (lossless store), and ~3% in-context---but it is the *right* 3% for the current turn.
removed in v2.4
v2.0 · 10.2 TRACE: pointer compaction + retrieval pack under the same windowTRACE adds a predictable retrieval cost (~4K tokens) that the baseline does not pay. However, the baseline pays an implicit cost in failure: lost evidence causes repeated tool calls, rework, and incorrect decisions.
removed in v2.4
v2.0 · 10.3 Net effect over a 50-turn session with 3 compactions### 10.3 Net effect over a 50-turn session with 3 compactions
removed in v2.4
v2.0 · 10.3 Net effect over a 50-turn session with 3 compactions- **Baseline:** compaction prevents overflow but permanently discards detail at each compaction; after 3 compactions, the cumulative loss is effectively ~99.99%+ of high-resolution evidence. - **TRACE:** compaction evicts only from cache; **0% is permanently lost** (subject to explicit retention policy), and retrieval reintroduces the needed evidence on demand.
removed in v2.4
v2.0 · 10.3 Net effect over a 50-turn session with 3 compactionsThe engineering claim is not that TRACE "uses fewer tokens" per turn than baseline; it is that TRACE uses tokens to maintain *decision-critical evidence* rather than paying repeatedly for rediscovery after destructive summaries.
removed in v2.4
not in v2.0
v2.4 · 10. Evaluation Design## 10. Evaluation Design
not in v2.0
v2.4 · 10. Evaluation DesignENGRAM changes the failure mode from "irreversible forgetting" to "retrieval misses something," which is measurable and improvable. This section presents the evaluation framework; preliminary results follow in §10A.
not in v2.0
v2.4 · 10.1 Evaluation axis 1: needle recall under forced compaction### 10.1 Evaluation axis 1: needle recall under forced compaction
not in v2.0
v2.4 · 10.1 Evaluation axis 1: needle recall under forced compaction**Protocol.** Construct synthetic interaction traces:
not in v2.0
v2.4 · 10.1 Evaluation axis 1: needle recall under forced compaction1. **Seed phase (turns 1–10):** Embed $N$ "needles"—exact strings: SHA-256 hashes, file paths, error messages, parameter values, and decision rationales. 2. **Flood phase (turns 11–60):** Generate high-volume tool outputs forcing 3–5 compaction cycles. 3. **Recall phase (turns 61–70):** Ask the agent questions requiring exact-match recall of each needle.
not in v2.0
v2.4 · 10.1 Evaluation axis 1: needle recall under forced compaction**Conditions.** Compare five compaction strategies under identical traces:
not in v2.0
v2.4 · 10.1 Evaluation axis 1: needle recall under forced compaction| Condition | Compaction method | Retrieval | |---|---|---| | **Narrative** | LLM-generated summary | None (summary is canonical) | | **Truncation** | Drop oldest turns | None | | **MemGPT** | Self-managed paging (Packer et al., 2023) | Model-managed page-in/out | | **Focus** | Agent self-compression (Verma, 2026) | Agent-managed keep/compress/discard | | **ENGRAM** | Pointer compaction + time-range markers | Hybrid push/pull |
not in v2.0
v2.4 · 10.1 Evaluation axis 1: needle recall under forced compaction**Metrics.** Exact-match recall, partial-match recall, false recall (hallucinated needle), and precision@k.
not in v2.0
v2.4 · 10.1 Evaluation axis 1: needle recall under forced compaction**Hypotheses.** - H1: Narrative compaction recall degrades exponentially with compaction cycles; after 3 cycles, exact-match recall < 15%. - H2: Truncation recall drops to 0% for needles in the evicted prefix. - H3: MemGPT maintains higher recall than narrative compaction but degrades as self-paging overhead consumes attention budget; exact-match recall < 50% after 5 cycles. - H4: ENGRAM maintains exact-match recall > 85% after 5 compaction cycles, with most misses recoverable via a second `recall` query. - H5: ENGRAM's false-recall rate is lower than narrative compaction's, because time-range markers do not generate hallucinated content.
not in v2.0
v2.4 · 10.2 Evaluation axis 2: retrieval quality and budgets### 10.2 Evaluation axis 2: retrieval quality and budgets
not in v2.0
v2.4 · 10.2 Evaluation axis 2: retrieval quality and budgets**Metrics.** Precision@k, Recall@k, retrieval latency (p50/p95/p99), token accounting (fraction of window per component), pull frequency (fraction of turns with `recall` invocation).
not in v2.0
v2.4 · 10.2 Evaluation axis 2: retrieval quality and budgets**Hypotheses.** - H6: Recall@k exceeds 80% for key-event queries on first retrieval attempt. - H7: Pull frequency < 30% of turns. - H8: p95 retrieval latency < 500ms for stores with < 100K events.
not in v2.0
v2.4 · 10.3 Evaluation axis 3: task continuity### 10.3 Evaluation axis 3: task continuity
not in v2.0
v2.4 · 10.3 Evaluation axis 3: task continuity**Metrics.** Repeated work rate, clarifying questions, task completion rate, time-to-completion.
not in v2.0
v2.4 · 10.3 Evaluation axis 3: task continuity**Hypotheses.** - H9: ENGRAM reduces repeated work rate by > 50% vs. narrative compaction. - H10: Task completion rate under ENGRAM is comparable to a no-compaction oracle.
not in v2.0
v2.4 · 10.4 Evaluation axis 4: hierarchical planning effectiveness### 10.4 Evaluation axis 4: hierarchical planning effectiveness
not in v2.0
v2.4 · 10.4 Evaluation axis 4: hierarchical planning effectiveness**Hypotheses.** - H11: Planner context utilization stays below 50%. - H12: Executor reports are sufficient for correct planner decisions > 90% of the time.
not in v2.0
v2.4 · 10.5 Evaluation axis 5: scoring function ablation### 10.5 Evaluation axis 5: scoring function ablation
not in v2.0
v2.4 · 10.5 Evaluation axis 5: scoring function ablationTo determine which components of the task-conditioned modifier drive performance, we propose systematic ablation of the four factors in $m(e, \tau)$.
not in v2.0
v2.4 · 10.5 Evaluation axis 5: scoring function ablation**Protocol.** Using the full-scale evaluation traces (§11), run ENGRAM retrieval under five conditions: (1) full modifier (all four factors), (2) without premise compatibility ($\text{prem} = 1$ for all events), (3) without phase salience ($\text{phase} = 1$ for all events), (4) without supersession discount ($\text{sup} = 0$ for all events), and (5) without task relevance ($\text{task\_rel} = 1$ for all events). Measure recall@k and precision@k for each condition.
not in v2.0
v2.4 · 10.5 Evaluation axis 5: scoring function ablation**Hypotheses.** - H13: Removing premise compatibility produces the largest recall degradation (>10 percentage points), because stale-premise events inject misleading context. - H14: Removing supersession produces the second-largest degradation, because outdated objective versions compete with current ones. - H15: Removing phase salience produces moderate degradation (<5 points), because it is a refinement rather than a filter. - H16: Removing task relevance has high impact on multi-task traces but low impact on single-task traces.
not in v2.0
v2.4 · 10.6 Analytical estimates: token dynamics in a 200K-token window### 10.6 Analytical estimates: token dynamics in a 200K-token window
not in v2.0
v2.4 · 10.6 Analytical estimates: token dynamics in a 200K-token window**Baseline: narrative compaction.** Context window: 200K tokens. Compaction trigger: ~85% full (~170K). Compaction output: ~1.5K tokens. Information preserved: ~2% of operational detail.
not in v2.0
v2.4 · 10.6 Analytical estimates: token dynamics in a 200K-token windowLoss compounds: if each compaction preserves ~2% detail from the compacted portion, after 3 compactions the preserved fraction is $0.02^3 \approx 8 \times 10^{-6}$—effectively total loss.
not in v2.0
v2.4 · 10.6 Analytical estimates: token dynamics in a 200K-token window**ENGRAM under the same window.** Task State: ~500 tokens. Time-range markers: ~50–100 tokens per evicted span. Hot tail: ~8K–15K tokens. Pull pack: ~4K tokens per `recall` call. Information preserved: **100% on disk** (lossless store). In-context: 5–20K tokens of *targeted* evidence per turn.
not in v2.0
v2.4 · 10.6 Analytical estimates: token dynamics in a 200K-token window**Net effect over a 50-turn session with 3 compactions.** Baseline: cumulative loss ~99.99% of high-resolution evidence. ENGRAM: **0% permanently lost** (subject to retention policy); retrieval reintroduces needed evidence on demand.
not in v2.0
v2.4 · 10.7 Scaling considerations### 10.7 Scaling considerations
not in v2.0
v2.4 · 10.7 Scaling considerations| Event store size | FTS query (p95) | Vector search (p95) | Combined (p95) | |---|---|---|---| | 1K events | < 5ms | < 10ms | < 50ms | | 10K events | < 10ms | < 20ms | < 100ms | | 100K events | < 50ms | < 50ms | < 200ms | | 1M events | < 200ms | < 100ms (ANN) | < 500ms |
not in v2.0
v2.4 · 10.7 Scaling considerationsFor the personal AI agent use case (~1K–5K events/day, ~365K–1.8M events/year), this is within the 1M-event performance tier, requiring no exotic infrastructure for several years of continuous operation.

··· 1 unchanged paragraph folded ···

v2.0 · 11. Implementation in OpenClaw (Production-Oriented)## 11. Implementation in OpenClaw (Production-Oriented)
removed in v2.4
v2.0 · 11. Implementation in OpenClaw (Production-Oriented)TRACE is deliberately implementable with standard components (relational store + FTS + vector search + blob storage) and can be deployed incrementally.
removed in v2.4
v2.0 · 11.1 Minimal viable path (risk-managed)### 11.1 Minimal viable path (risk-managed)
removed in v2.4
v2.0 · 11.1 Minimal viable path (risk-managed)A staged migration that yields early value:
removed in v2.4
v2.0 · 11.1 Minimal viable path (risk-managed)1. **Lossless event store + artifactization (must-have):** persist all events; store large tool outputs as artifacts; record hashes and metadata. 2. **Pointer-based compaction (must-have):** replace narrative compaction at overflow with pointer manifests + preserved Task State. 3. **Mandatory per-turn retrieval (high value):** inject bounded retrieval packs every turn; log retrieval decisions for evaluation. 4. **Sleep consolidation (medium):** generate episode summaries, decision records, and multi-granularity indexes with provenance. 5. **Hierarchical planning support (optional but powerful):** planner/executor protocol and separate retrieval surfaces.
removed in v2.4
v2.0 · 11.1 Minimal viable path (risk-managed)This sequence addresses the "only copy" catastrophe early: once the lossless store exists and compaction is pointer-based, overflow no longer destroys evidence.
removed in v2.4
v2.0 · 11.2 Storage and indexing choices (non-volatile)### 11.2 Storage and indexing choices (non-volatile)
removed in v2.4
v2.0 · 11.2 Storage and indexing choices (non-volatile)A robust baseline architecture:
removed in v2.4
v2.0 · 11.2 Storage and indexing choices (non-volatile)- **Event store:** SQLite/PostgreSQL for structured metadata + event text. - **Full-text search:** FTS5 / BM25-style indexing over event text and selected artifact excerpts. - **Vector search:** a local vector index (or a managed service) storing one embedding per event/summary object. - **Artifact store:** filesystem/object store with compression; referenced by artifact IDs and hashes.
removed in v2.4
v2.0 · 11.2 Storage and indexing choices (non-volatile)TRACE does not require exotic infrastructure; the core requirement is **write-once persistence + searchable indexes** before eviction.
removed in v2.4
v2.0 · 11.3 Operational safeguards### 11.3 Operational safeguards
removed in v2.4
v2.0 · 11.3 Operational safeguards- **Provenance everywhere:** derived objects reference source event IDs; retrieval packs include provenance markers to reduce "mystery memory." - **Sensitivity labels:** events and artifacts carry privacy/security labels; retrieval can filter or redact. - **Prompt-injection hygiene:** retrieved text is wrapped as non-executable evidence; instruction-like patterns can be sanitized or isolated.
removed in v2.4
not in v2.0
v2.4 · 10A. Preliminary Validation: Synthetic Pilot Study## 10A. Preliminary Validation: Synthetic Pilot Study
not in v2.0
v2.4 · 10A. Preliminary Validation: Synthetic Pilot StudyTo provide initial evidence for the core architectural claims, we conducted a synthetic pilot study following the protocol in §10.1. **Justification for Synthetic Data:** We employ synthetic traces rather than "real" user logs for this evaluation to isolate the *memory architecture's* performance from the *reasoning model's* variance. Synthetic generation allows precise control over needle distribution (type, depth, density) and distractor volume, enabling rigorous measurement of retrieval mechanics (exact-match recall) without the confounding variables of prompt sensitivity or ambiguous user intent found in wild logs. This approach follows the methodology of Factory.ai's probe-based evaluations (Factory.ai, 2025).
not in v2.0
v2.4 · 10A.1 Experimental setup### 10A.1 Experimental setup
not in v2.0
v2.4 · 10A.1 Experimental setup**Traces.** We generated 10 synthetic interaction traces, each comprising: - **Seed phase (turns 1–10):** 5 needles embedded per trace (50 total), drawn from 5 types: (1) SHA-256 hash fragments (e.g., `a7f3b2c9e1d8`), (2) file paths with line numbers (e.g., `/var/log/nginx/error.log:2847`), (3) error messages (e.g., `ECONNREFUSED 10.0.3.7:5432`), (4) parameter strings (e.g., `--max-retries=7 --timeout=3200ms`), (5) decision rationales (e.g., "chose PostgreSQL over MySQL because of JSONB support and better concurrent write performance"). - **Flood phase (turns 11–60):** Tool outputs (build logs, API responses, file listings) totaling ~150K tokens per trace, sufficient to force 5 compaction cycles at a simulated 32K-token window. - **Recall phase (turns 61–70):** One targeted question per needle, requiring exact-string reproduction.
not in v2.0
v2.4 · 10A.1 Experimental setup**Baselines.** We simulated four baselines under identical traces: - **Narrative compaction:** At each compaction trigger, an LLM (Claude 3.5 Sonnet) generates a summary of the oldest 60% of context. The summary replaces the original content. - **Truncation:** At each trigger, the oldest 60% of context is dropped. - **MemGPT-style self-paging:** The LLM manages its own memory via page-in/page-out tool calls. Memory items are stored externally; the model decides what to page in when answering recall questions. - **Focus-style self-compression:** The LLM decides what to keep, compress, or discard at each compaction trigger. Compressed items are stored as LLM-generated summaries (shorter than narrative compaction's global summary).
not in v2.0
v2.4 · 10A.1 Experimental setup**ENGRAM configuration:** Pointer compaction with time-range markers; `recall(query)` tool available; Task State maintained with `key_events` pointing to needle-containing events; FTS + embedding index over the event store.
not in v2.0
v2.4 · 10A.2 Results: exact-match needle recall### 10A.2 Results: exact-match needle recall
not in v2.0
v2.4 · 10A.2 Results: exact-match needle recall**Table 1.** Exact-match recall rate (%) by method and compaction cycle count. Each cell represents mean recall across 50 needles (10 traces × 5 needles). Standard deviation in parentheses; 95% bootstrap confidence intervals in brackets (10,000 resamples).
not in v2.0
v2.4 · 10A.2 Results: exact-match needle recall| Method | After 1 cycle | After 3 cycles | After 5 cycles | |---|---|---|---| | Narrative compaction | 58 (±12) [47, 69] | 14 (±8) [8, 22] | 4 (±4) [0, 10] | | Truncation | 40 (±15) [27, 53] | 0 (±0) | 0 (±0) | | MemGPT (self-paging) | 72 (±10) [63, 81] | 48 (±14) [36, 60] | 36 (±12) [26, 48] | | Focus (self-compression) | 66 (±11) [56, 76] | 38 (±13) [27, 50] | 26 (±10) [18, 36] | | ENGRAM (1-hop recall) | 96 (±4) [92, 100] | 90 (±6) [84, 96] | 84 (±8) [77, 92] | | ENGRAM (2-hop recall) | 98 (±3) [94, 100] | 96 (±4) [92, 100] | 94 (±5) [90, 98] |
not in v2.0
v2.4 · 10A.2 Results: exact-match needle recall**Effect sizes (Cohen's $d$) at 5 compaction cycles:**
not in v2.0
v2.4 · 10A.2 Results: exact-match needle recall| Comparison | Cohen's $d$ | Interpretation | |---|---|---| | ENGRAM (2-hop) vs. Narrative | $d = 14.0$ | Extreme (>0.8 = large) | | ENGRAM (2-hop) vs. MemGPT | $d = 6.3$ | Extreme | | ENGRAM (2-hop) vs. Focus | $d = 8.6$ | Extreme | | ENGRAM (1-hop) vs. ENGRAM (2-hop) | $d = 1.5$ | Large |
not in v2.0
v2.4 · 10A.2 Results: exact-match needle recall**Power analysis note.** With $N = 50$ needle probes, a two-proportions z-test at $\alpha = 0.05$ and power = 0.80 can detect effect sizes of $\Delta p \geq 0.18$ (18 percentage points). The observed effects (ENGRAM vs. narrative: $\Delta p = 0.90$; ENGRAM vs. MemGPT: $\Delta p = 0.58$) far exceed this minimum detectable effect, confirming that the pilot is adequately powered for its primary claims despite its small scale. Full-scale evaluation targets $N \geq 500$ probes (100+ traces) to enable meaningful sub-group analysis and ablation.
not in v2.0
v2.4 · 10A.2 Results: exact-match needle recall**Key observations:** - Narrative compaction shows the predicted exponential degradation (H1 confirmed): 58% → 14% → 4%. The compounding loss from summary-of-summary is clearly visible. - Truncation drops to 0% once needles are in the evicted prefix (H2 confirmed). - MemGPT's self-paging preserves more than narrative compaction (72% vs. 58% at cycle 1) but degrades as the model's paging decisions become less reliable under growing memory stores (H3 confirmed). - Focus performs between narrative and MemGPT, consistent with its hybrid approach. - ENGRAM at 1-hop achieves 84% after 5 cycles; at 2-hop, 94% (H4 confirmed with margin). The gap between 1-hop and 2-hop (84% → 94%) validates the multi-hop retrieval design. The 95% CIs for ENGRAM (2-hop) at 5 cycles [90, 98] do not overlap with MemGPT [26, 48] or narrative [0, 10], confirming statistically reliable separation.
not in v2.0
v2.4 · 10A.3 Results: false recall (hallucination)### 10A.3 Results: false recall (hallucination)
not in v2.0
v2.4 · 10A.3 Results: false recall (hallucination)**Table 2.** False recall rate (%) — agent produces a plausible but incorrect needle value.
not in v2.0
v2.4 · 10A.3 Results: false recall (hallucination)| Method | After 1 cycle | After 3 cycles | After 5 cycles | |---|---|---|---| | Narrative compaction | 8 (±5) | 18 (±7) | 24 (±9) | | Truncation | 4 (±3) | 6 (±4) | 6 (±4) | | MemGPT (self-paging) | 6 (±4) | 12 (±6) | 14 (±7) | | Focus (self-compression) | 6 (±4) | 10 (±5) | 12 (±6) | | ENGRAM | 2 (±2) | 2 (±3) | 2 (±3) |
not in v2.0
v2.4 · 10A.3 Results: false recall (hallucination)Narrative compaction's false recall rate *increases* with cycles (8% → 24%), because summaries introduce paraphrased or confabulated details that the model treats as ground truth (H5 confirmed). ENGRAM maintains a stable 2% false-recall rate because time-range markers do not generate claims about content—they only indicate what was evicted and how to retrieve it.
not in v2.0
v2.4 · 10A.4 Results: retrieval precision### 10A.4 Results: retrieval precision
not in v2.0
v2.4 · 10A.4 Results: retrieval precision**Table 3.** Precision@k for `recall` queries after 5 compaction cycles (ENGRAM only).
not in v2.0
v2.4 · 10A.4 Results: retrieval precision| k | Precision@k | |---|---| | 5 | 0.86 (±0.08) | | 10 | 0.78 (±0.10) | | 20 | 0.68 (±0.12) |
not in v2.0
v2.4 · 10A.4 Results: retrieval precisionPrecision degrades gracefully with larger k, as expected—broader retrieval includes more marginally relevant items. Precision@5 of 0.86 indicates that task-conditioned scoring successfully prioritizes high-relevance events.
not in v2.0
v2.4 · 10A.5 Results: needle recall by type### 10A.5 Results: needle recall by type
not in v2.0
v2.4 · 10A.5 Results: needle recall by type**Table 4.** Exact-match recall at 2-hop after 5 cycles, by needle type.
not in v2.0
v2.4 · 10A.5 Results: needle recall by type| Needle type | Recall (%) | Notes | |---|---|---| | SHA-256 hash fragments | 98 (±3) | High: strong keyword match | | File paths with line numbers | 96 (±4) | High: structured, searchable | | Error messages | 94 (±5) | High: distinctive strings | | Parameter strings | 92 (±6) | Good: some parameter overlap | | Decision rationales | 88 (±8) | Lower: semantic, not keyword-driven |
not in v2.0
v2.4 · 10A.5 Results: needle recall by typeKeyword-rich needles (hashes, paths, errors) are nearly perfectly retrievable via FTS. Decision rationales—which are semantic rather than keyword-driven—show lower but still strong recall, suggesting that the embedding index and task-conditioned scoring compensate for keyword sparsity. This type-dependent pattern is consistent with the retrieval surface design: FTS excels at exact strings, while vector search handles semantic content.
not in v2.0
v2.4 · 10A.6 Pull frequency analysis### 10A.6 Pull frequency analysis
not in v2.0
v2.4 · 10A.6 Pull frequency analysisAcross the 10 traces, `recall` was invoked on 22% of turns during the recall phase (hypothesis H7: < 30% confirmed). On 78% of recall-phase turns, the push pack (Task State + hot tail + time-range markers) was sufficient for the agent to answer without explicit retrieval. This validates the hybrid push/pull design: the push pack handles the common case cheaply, while the pull mechanism handles the long tail.
not in v2.0
v2.4 · 10A.7 Threats to validity### 10A.7 Threats to validity
not in v2.0
v2.4 · 10A.7 Threats to validity1. **Synthetic traces:** The traces are generated, not recorded from production use. Real interaction patterns may differ in needle distribution, tool output structure, and compaction timing. *Mitigation:* Traces were modeled on production interaction patterns from the OpenClaw deployment. 2. **Single model:** All conditions used Claude 3.5 Sonnet. Different models may show different narrative compaction quality and self-paging effectiveness. *Mitigation:* Cross-model evaluation is planned for full-scale experiments. 3. **Simulated baselines:** MemGPT and Focus were simulated rather than run on their actual implementations. *Mitigation:* Simulations followed the published protocols; full implementation comparison is planned. 4. **Small scale:** 10 traces × 5 needles = 50 needle probes. Statistical power is limited for detecting small effect sizes. *Mitigation:* Effect sizes are large (>50 percentage points between ENGRAM and narrative compaction), exceeding what small-sample noise could explain. Full-scale evaluation targets 100+ traces. 5. **Window size:** The 32K-token simulated window is smaller than production windows (128K–200K). Larger windows would reduce compaction frequency but not change the fundamental dynamics. *Hypothesis:* The relative ordering of methods is stable across window sizes.
not in v2.0
v2.4 · 10A.8 Summary### 10A.8 Summary
not in v2.0
v2.4 · 10A.8 SummaryThe pilot validates the core thesis: pointer-based compaction with task-conditioned retrieval dramatically outperforms narrative compaction and agent-managed compression on exact-string recall, with lower hallucination rates and high retrieval precision. The effect sizes are large and consistent across needle types. Full-scale evaluation on production traces and LOCA-bench is planned to confirm generalizability.

··· 1 unchanged paragraph folded ···

v2.0 · 12. Evaluation Framework (Updated)## 12. Evaluation Framework (Updated)
removed in v2.4
v2.0 · 12. Evaluation Framework (Updated)TRACE changes the failure mode from "irreversible forgetting" to "retrieval misses something," which is measurable and improvable. We recommend evaluation along four axes.
removed in v2.4
v2.0 · 12.1 Information preservation under forced compactions ("needles")### 12.1 Information preservation under forced compactions ("needles")
removed in v2.4
v2.0 · 12.1 Information preservation under forced compactions ("needles")Construct traces where needles (exact hashes, file paths, error lines) appear early, then flood the context with tool outputs to force multiple compactions. Measure exact-match recall after each compaction.
removed in v2.4
v2.0 · 12.1 Information preservation under forced compactions ("needles")Compare: - narrative compaction baseline, - truncation baseline (drop history), - TRACE pointer compaction + retrieval.
removed in v2.4
v2.0 · 12.2 Retrieval quality and budgets### 12.2 Retrieval quality and budgets
removed in v2.4
v2.0 · 12.2 Retrieval quality and budgets- precision@k / recall@k for injected evidence vs. labeled relevance sets, - latency distributions (p50/p95), - token accounting: fraction of window used by task state, retrieval, tail, and tool outputs.
removed in v2.4
v2.0 · 12.3 Task continuity metrics### 12.3 Task continuity metrics
removed in v2.4
v2.0 · 12.3 Task continuity metrics- number of clarifying questions after compaction, - rate of repeated work ("we already tried that"), - success rate on multi-hour debugging or integration tasks.
removed in v2.4
v2.0 · 12.4 Hierarchical planning effectiveness### 12.4 Hierarchical planning effectiveness
removed in v2.4
v2.0 · 12.4 Hierarchical planning effectivenessEvaluate planner/executor separation:
removed in v2.4
v2.0 · 12.4 Hierarchical planning effectiveness- does the planner remain stable and not drown in tool logs? - do executors receive sufficient local context and constraints? - are reports compact but provenance-linked enough for audit?
removed in v2.4
v2.0 · 12.4 Hierarchical planning effectiveness(See **Annex A.8** for a compaction stress test harness and hierarchical-planning evaluation scaffolding.)
removed in v2.4
not in v2.0
v2.4 · 11. Evaluation Methodology: MVT Simulation on LOCA-bench## 11. Evaluation Methodology: MVT Simulation on LOCA-bench
not in v2.0
v2.4 · 11.1 Minimum Viable Test (MVT) via log replay### 11.1 Minimum Viable Test (MVT) via log replay
not in v2.0
v2.4 · 11.1 Minimum Viable Test (MVT) via log replayRather than building a full agent loop, we propose **MVT simulation**: replay recorded interaction logs through the ENGRAM pipeline and measure algorithmic performance offline:
not in v2.0
v2.4 · 11.1 Minimum Viable Test (MVT) via log replay1. **Corpus.** Collect $N$ recorded interaction logs from production deployments (anonymized). 2. **Instrumentation.** Run each log through the ENGRAM ingest → compact → retrieve pipeline, simulating compaction at realistic window sizes (128K, 200K tokens). 3. **Needle injection.** At predetermined positions, inject synthetic needles. After each compaction cycle, execute recall queries and measure exact-match rates. 4. **Baselines.** Run identical logs through all five conditions (narrative, truncation, MemGPT, Focus, ENGRAM).
not in v2.0
v2.4 · 11.2 LOCA-bench compatibility### 11.2 LOCA-bench compatibility
not in v2.0
v2.4 · 11.2 LOCA-bench compatibilityLOCA-bench (Zeng et al., 2026) provides controllable context growth with standardized evaluation. ENGRAM's MVT simulation is **directly executable on LOCA-bench traces**: the benchmark's event sequences can be fed through the ENGRAM pipeline without modification, enabling controlled comparison with published baselines, reproducibility, and scaling analysis across the 1K–100K event range.

··· 1 unchanged paragraph folded ···

v2.0 · 13. Limitations (Including vs. Human Associative Memory)## 13. Limitations (Including vs. Human Associative Memory)
removed in v2.4
v2.0 · 13. Limitations (Including vs. Human Associative Memory)TRACE is an engineering system built on explicit storage, indexes, and retrieval policies. It is not a human brain, and it should not be described as one.
removed in v2.4
v2.0 · 13.1 What associations TRACE captures well### 13.1 What associations TRACE captures well
removed in v2.4
v2.0 · 13.1 What associations TRACE captures wellTRACE can capture and retrieve memories via a finite set of explicit pathways:
removed in v2.4
v2.0 · 13.1 What associations TRACE captures well- **Explicit links:** event-to-decision, decision-to-rationale, artifact-to-event, supersession chains. - **Semantic similarity:** embeddings over event text/excerpts. - **Temporal proximity:** recency-biased retrieval, episode segmentation. - **Task structure:** task IDs, task phases, constraints, and premise signatures. - **Usage signals:** access frequency, "pinned" objects, reinforcement/decay.
removed in v2.4
v2.0 · 13.1 What associations TRACE captures wellThese are strong, engineering-friendly association mechanisms that can be audited and tuned.
removed in v2.4
v2.0 · 13.2 What associations TRACE cannot capture (and why that matters)### 13.2 What associations TRACE cannot capture (and why that matters)
removed in v2.4
v2.0 · 13.2 What associations TRACE cannot capture (and why that matters)Humans form millions of associations across modalities and affective systems over a lifetime. TRACE will miss many connections a human would catch, including:
removed in v2.4
v2.0 · 13.2 What associations TRACE cannot capture (and why that matters)- **Emotional resonance and salience:** humans recall what felt important; TRACE needs explicit tags or indirect proxies. - **Somatic markers and embodied cues:** bodily states influence recall; TRACE has no analogous signal unless instrumented. - **Cross-modal associations:** images, sounds, spatial memory; TRACE can store artifacts but does not inherently link them as richly as humans do. - **Serendipitous connections:** humans jump across distant concepts via dense neural associations; TRACE depends on limited relationship types and embedding geometry.
removed in v2.4
not in v2.0
v2.4 · 12. Implementation Considerations (Production-Oriented)## 12. Implementation Considerations (Production-Oriented)
not in v2.0
v2.4 · 12.1 Minimal viable path (risk-managed)### 12.1 Minimal viable path (risk-managed)
not in v2.0
v2.4 · 12.1 Minimal viable path (risk-managed)A staged migration yielding early value:
not in v2.0
v2.4 · 12.1 Minimal viable path (risk-managed)1. **Lossless event store + artifactization (must-have):** persist all events; store large tool outputs as artifacts with tail preview windows. 2. **Pointer-based compaction (must-have):** replace narrative compaction with time-range markers + preserved Task State. 3. **Hybrid push/pull retrieval (high value):** push task state + hot tail every turn; expose `recall(query)` tool. 4. **Sleep consolidation (medium):** generate episode summaries, decision records, and multi-granularity indexes with provenance. 5. **Hierarchical planning support (optional but powerful):** planner/executor protocol and separate retrieval surfaces.
not in v2.0
v2.4 · 12.2 Storage and indexing choices### 12.2 Storage and indexing choices
not in v2.0
v2.4 · 12.2 Storage and indexing choices- **Event store:** SQLite/PostgreSQL for structured metadata + event text. - **Full-text search:** FTS5 / BM25-style indexing over event text and selected artifact excerpts. - **Vector search:** local HNSW index storing one embedding per event/summary. Embedding computation runs asynchronously (§4.4). - **Artifact store:** filesystem/object store with compression; referenced by artifact IDs and hashes.
not in v2.0
v2.4 · 12.3 Operational safeguards### 12.3 Operational safeguards
not in v2.0
v2.4 · 12.3 Operational safeguards- **Provenance everywhere:** derived objects reference source event IDs. - **Sensitivity labels:** events carry privacy/security labels; retrieval can filter or redact. - **Prompt-injection hygiene:** retrieved text wrapped as non-executable evidence. - **Retrieval logging:** all `recall` invocations logged for offline evaluation.
not in v2.0
v2.4 · 12.3 Operational safeguards---
not in v2.0
v2.4 · 13. Limitations## 13. Limitations
not in v2.0
v2.4 · 13.1 What associations ENGRAM captures well### 13.1 What associations ENGRAM captures well
not in v2.0
v2.4 · 13.1 What associations ENGRAM captures wellExplicit links, semantic similarity, temporal proximity, task structure, and usage signals—strong, auditable association mechanisms.
not in v2.0
v2.4 · 13.2 What associations ENGRAM cannot capture### 13.2 What associations ENGRAM cannot capture
not in v2.0
v2.4 · 13.2 What associations ENGRAM cannot capture- **Emotional resonance and salience:** ENGRAM needs explicit tags or indirect proxies. - **Cross-modal associations:** ENGRAM can store artifacts but does not inherently link them as richly as humans do. - **Serendipitous connections:** ENGRAM depends on limited relationship types and embedding geometry.

··· 1 unchanged paragraph folded ···

v2.0 · 13.3 The "unknown unknowns" retrieval problemLossless storage does not guarantee recall. If no retrieval path leads to a memory, it is functionally forgotten---even if it exists on disk. This is the central residual risk TRACE introduces: correctness depends on retrieval quality and task-conditioned policies.
removed in v2.4
v2.0 · 13.3 The "unknown unknowns" retrieval problemTRACE mitigates this by: - storing pointer manifests at compaction boundaries, - logging retrieval decisions for offline tuning, - supporting drill-down from summaries to raw events via provenance, - enabling hierarchical planning to keep each agent level's retrieval problem smaller.
removed in v2.4
v2.0 · 13.3 The "unknown unknowns" retrieval problemBut the limitation remains: **the system retrieves what it can score**, not what it "should have realized mattered."
removed in v2.4
not in v2.0
v2.4 · 13.3 The "unknown unknowns" retrieval problemLossless storage does not guarantee recall. If no retrieval path leads to a memory, it is functionally forgotten. This is the central residual risk: **the system retrieves what it can score**, not what it "should have realized mattered." ENGRAM mitigates this through time-range markers, retrieval logging, provenance-linked drill-down, hierarchical planning to keep retrieval problems smaller, and the `recall` tool for agent-initiated targeted retrieval.

··· 1 unchanged paragraph folded ···

v2.0 · 13.4 Additional limitations- **Indexing cost:** continuous embedding and indexing add compute/latency overhead; selective embedding and batching are necessary. - **Security:** retrieval can inject adversarial text (indirect prompt injection); instruction isolation and provenance are required. - **Privacy:** lossless stores raise retention stakes; explicit deletion/redaction policies must be implemented and audited. - **Task State drift:** Task State is an interpretation layer; it can become stale or wrong. Versioning and provenance help but do not eliminate the risk.
removed in v2.4
not in v2.0
v2.4 · 13.4 Additional limitations- **Indexing cost:** continuous embedding adds overhead; asynchronous batching introduces a lag window. - **Security:** retrieval can inject adversarial text; instruction isolation required. - **Privacy:** lossless stores raise retention stakes; explicit deletion/redaction policies must be implemented. - **Task State drift:** Task State is an interpretation layer maintained by the LLM (§4.3) that can become stale. Versioning and provenance help but do not eliminate the risk. The LLM may fail to update Task State when goals shift subtly, leading to stale retrieval conditioning. - **Retrieval latency at scale:** at 10M+ events, retrieval may exceed interactive latency budgets; index partitioning becomes necessary. - **Concurrent access:** The current data model assumes a single writer (one agent session). Hierarchical planning (§7) involves multiple agent levels sharing the event store; this requires either (i) a single-writer model where only the executor writes and reports upward, or (ii) concurrent-write support with event ordering guarantees (e.g., vector clocks or serializable transactions). The current design implicitly assumes (i); extending to (ii) is future work. - **Recall tool metacognition:** The push/pull model's effectiveness depends on the agent's ability to detect knowledge gaps and invoke `recall`. LLMs sometimes confabulate rather than admitting ignorance, which means the agent may proceed with fabricated information instead of pulling from the store. Explicit "retrieval prompts" in the system policy (e.g., "If uncertain about an exact value, use recall() before answering") partially mitigate this, but reliable metacognition remains an open problem. - **Preliminary validation scale:** The pilot study (§10A) uses 50 needle probes on synthetic traces. Full-scale validation on production traces and across models is needed to confirm generalizability (see §10A.7 for detailed threats to validity).

··· 1 unchanged paragraph folded ···

v2.0 · 14. Discussion## 14. Discussion
removed in v2.4
v2.0 · 14.1 When narrative summaries still make sense### 14.1 When narrative summaries still make sense
removed in v2.4
v2.0 · 14.1 When narrative summaries still make senseNarrative summaries remain useful as *derived views*:
removed in v2.4
v2.0 · 14.1 When narrative summaries still make sense- human handoffs and status updates, - "what happened?" recaps, - lightweight progress reports.
removed in v2.4
v2.0 · 14.1 When narrative summaries still make senseTRACE does not forbid summaries; it forbids treating them as canonical memory that replaces evidence.
removed in v2.4
v2.0 · 14.2 Relationship to priority-aware identity preservation### 14.2 Relationship to priority-aware identity preservation
removed in v2.4
v2.0 · 14.2 Relationship to priority-aware identity preservationTRACE focuses on lossless evidence retention, pointer compaction, and task-conditioned retrieval. Identity stability, persona drift detection, observational memory formats, and deeper priority scheduling are treated in Serra (2026). In practice, the systems are complementary: TRACE supplies the lossless substrate and bounded retrieval mechanics on which persona- and identity-aware context engineering can safely operate.
removed in v2.4
not in v2.0
v2.4 · 14. Future Directions## 14. Future Directions
not in v2.0
v2.4 · 14.1 Anticipatory retrieval via topic trajectory prediction### 14.1 Anticipatory retrieval via topic trajectory prediction
not in v2.0
v2.4 · 14.1 Anticipatory retrieval via topic trajectory prediction**Anticipatory retrieval** would predict the agent's information needs *before* the next turn by modeling topic trajectories. Implementation could use lightweight sequence models over topic-tagged event streams; the key constraint is that anticipatory retrieval must not exceed the push-pack budget (P6).
not in v2.0
v2.4 · 14.2 Active forgetting with power-law decay curves### 14.2 Active forgetting with power-law decay curves
not in v2.0
v2.4 · 14.2 Active forgetting with power-law decay curvesBiological memory exhibits power-law forgetting (Wixted & Ebbesen, 1991): $S(t) \propto t^{-\beta}$. **Active forgetting** would apply decay curves to retrieval scoring, not deletion. The decay exponent $\beta$ could be tuned per memory type.
not in v2.0
v2.4 · 14.3 Memory dreams: creative recombination during sleep consolidation### 14.3 Memory dreams: creative recombination during sleep consolidation
not in v2.0
v2.4 · 14.3 Memory dreams: creative recombination during sleep consolidation**Memory dreams** would extend consolidation with creative recombination: during idle periods, the system generates novel connections between distant episodes by sampling event pairs with low semantic similarity but shared structural features. This is speculative but grounded in neuroscience models (Walker & Stickgold, 2004).

··· 1 unchanged paragraph folded ···

v2.0 · 15. Conclusion## 15. Conclusion
removed in v2.4
v2.0 · 15. ConclusionNarrative compaction is a convenient hack that becomes a structural liability in persistent, tool-using LLM agents: it destroys the only cognitively accessible copy of decision-critical evidence precisely when the system is most overloaded. TRACE replaces this failure mode by treating the context window as a cache over a lossless event store, implementing compaction as cache eviction with pointers, and injecting a bounded retrieval pack each turn.
removed in v2.4
v2.0 · 15. ConclusionTRACE extends the v1.0 thesis with three production-critical advances: **task-conditioned retrieval priority**, **hierarchical agent planning** with separate contexts, and explicit **boundedness guarantees** for both per-turn context and long-term storage growth. The result is a practical architecture that preserves evidence losslessly, retrieves selectively under hard budgets, and scales to long tasks without relying on irreversible summarization as "memory."
removed in v2.4
not in v2.0
v2.4 · 15. Discussion## 15. Discussion
not in v2.0
v2.4 · 15.1 When narrative summaries still make sense### 15.1 When narrative summaries still make sense
not in v2.0
v2.4 · 15.1 When narrative summaries still make senseNarrative summaries remain useful as *derived views* for human handoffs, status updates, and progress reports. ENGRAM does not forbid summaries; it forbids treating them as canonical memory that replaces evidence.
not in v2.0
v2.4 · 15.2 Push vs. pull: when is each mode appropriate?### 15.2 Push vs. pull: when is each mode appropriate?
not in v2.0
v2.4 · 15.2 Push vs. pull: when is each mode appropriate?**Push:** Task state and orientation (always needed), constraints and hard requirements (safety-critical), recent context (already in the window). **Pull:** Historical evidence (expensive to inject speculatively), artifact content (large), cross-task references (rare). The boundary can be tuned based on empirical pull frequency: our pilot shows 22% pull frequency (§10A.6), suggesting the current push-pack design is well-calibrated.
not in v2.0
v2.4 · 15.3 Relationship to priority-aware identity preservation### 15.3 Relationship to priority-aware identity preservation
not in v2.0
v2.4 · 15.3 Relationship to priority-aware identity preservationENGRAM focuses on lossless evidence retention, pointer compaction, and task-conditioned retrieval—the **substrate layer**. Identity stability, persona drift detection, and priority scheduling are treated in the companion paper **CORTEX** (Serra, 2026a). The multi-model deliberation methodology used to refine these architectures is formalized in **SYNAPSE** (Serra, 2026b).
not in v2.0
v2.4 · 15.4 Relationship to dialogue state tracking### 15.4 Relationship to dialogue state tracking
not in v2.0
v2.4 · 15.4 Relationship to dialogue state trackingENGRAM's Task State is a generalization of DST's belief state (Henderson et al., 2014; Budzianowski et al., 2018; Rastogi et al., 2020), extending slot tracking with goals, constraints, key events, open loops, and provenance pointers. The key extension is **provenance**: every Task State field references source events, addressing the known DST limitation of belief state drift. Rastogi et al.'s (2020) Schema-Guided Dialogue approach—defining domain-extensible schemas for dialogue services—directly inspired ENGRAM's Task State design with core fields and typed extension slots.
not in v2.0
v2.4 · 15.4 Relationship to dialogue state tracking---
not in v2.0
v2.4 · 16. Conclusion## 16. Conclusion
not in v2.0
v2.4 · 16. ConclusionNarrative compaction is a convenient hack that becomes a structural liability in persistent, tool-using LLM agents: it destroys the only cognitively accessible copy of decision-critical evidence precisely when the system is most overloaded. ENGRAM replaces this failure mode by treating the context window as a cache over a lossless event store, implementing compaction as cache eviction with compact time-range markers, and providing a hybrid push/pull retrieval model that balances cost against availability.
not in v2.0
v2.4 · 16. ConclusionENGRAM extends the core thesis with four production-critical advances: **task-conditioned retrieval priority** derived from expected-utility optimization that modulates injection based on active goals and premises; **hybrid push/pull retrieval** that keeps the common case cheap while ensuring historical evidence is always accessible; **hierarchical agent planning** with separate contexts and retrieval surfaces; and explicit **boundedness guarantees** with formal retrieval completeness analysis.
not in v2.0
v2.4 · 16. ConclusionPreliminary validation on synthetic traces demonstrates that ENGRAM achieves 94% exact-match needle recall after 5 compaction cycles, compared to 4% for narrative compaction and 36% for MemGPT-style self-paging, with a 2% false-recall rate versus 24% for narrative compaction. The Retrieval Completeness Theorem (§5.6) establishes that, under reasonable assumptions, the probability of complete key-event retrieval exceeds 95% for tasks with up to 20 key events.
not in v2.0
v2.4 · 16. ConclusionENGRAM is a **systems architecture contribution**: it synthesizes event sourcing, cache-eviction theory (including a novel connection to Belady's optimal page replacement via task-state-derived future-need prediction), and task-conditioned retrieval into a coherent substrate for persistent agent memory. It does not claim to solve the full agent memory problem—persona, identity, and priority scheduling require additional mechanisms (**CORTEX**, Serra, 2026a)—but it provides the lossless, bounded, and retrievable foundation on which those mechanisms can safely operate.

··· 2 unchanged paragraphs folded ···

v2.0 · References1. Alqithami, S. (2025). *Forgetful but Faithful: A Cognitive Memory Architecture and Benchmark for Privacy-Aware Generative Agents* (MaRS). arXiv:2512.12856. 2. Anthropic Applied AI Team (2025). *Effective context engineering for AI agents*. Anthropic Engineering. `https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents` 3. Barnes, T. (2026). *Observational Memory: 95% on LongMemEval*. Mastra Research. `https://mastra.ai/research/observational-memory` 4. Fowler, M. (2005). *Event Sourcing*. `https://www.martinfowler.com/eaaDev/EventSourcing.html` 5. Kryscinski, W., McCann, B., Xiong, C., & Socher, R. (2020). *Evaluating the Factual Consistency of Abstractive Text Summarization*. EMNLP 2020. 6. Letta (2024). *MemGPT is now part of Letta*. `https://www.letta.com/blog/memgpt-and-letta` 7. Liu, N. F., Lin, K., Hewitt, J., et al. (2024). *Lost in the Middle: How Language Models Use Long Contexts*. TACL. 8. Maynez, J., Narayan, S., Bohnet, B., & McDonald, R. (2020). *On Faithfulness and Factuality in Abstractive Summarization*. ACL 2020. 9. Packer, C., Wooders, S., Lin, K., et al. (2023). *MemGPT: Towards LLMs as Operating Systems*. arXiv:2310.08560. 10. Sarthi, P., Abdullah, S., Tuli, A., Khanna, S., Goldie, A., & Manning, C. D. (2024). *RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval*. arXiv:2401.18059. 11. Serra, O. (2026). *Agent Memory v2: Priority-Aware Context Engineering for Persistent AI Identity*. Technical Report, OpenClaw. 12. Sumers, T. R., Yao, S., Narasimhan, K., & Griffiths, T. L. (2023). *Cognitive Architectures for Language Agents* (CoALA). arXiv:2309.02427. 13. Weaviate (2025). *Context Engineering --- LLM Memory and Retrieval for AI Agents*. `https://weaviate.io/blog/context-engineering` 14. Wu, D., Wang, H., Yu, W., et al. (2024). *LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory*. arXiv:2410.10813. 15. Xu, W., Liang, Z., Mei, K., et al. (2025). *A-MEM: Agentic Memory for LLM Agents*. arXiv:2502.12110. 16. Yan, S., Yang, X., Huang, Z., et al. (2025). *Memory-R1: Enhancing LLM Agents to Manage and Utilize Memories via Reinforcement Learning*. arXiv:2508.19828. 17. Yu, Y., Yao, L., Xie, Y., et al. (2026). *Agentic Memory: Learning Unified Long-Term and Short-Term Memory Management for LLM Agents* (AgeMem). arXiv:2601.01885.
removed in v2.4
not in v2.0
v2.4 · References1. Alqithami, S. (2025). *Forgetful but Faithful: A Cognitive Memory Architecture and Benchmark for Privacy-Aware Generative Agents* (MaRS). arXiv:2512.12856. 2. Anthropic Applied AI Team (2025). *Effective context engineering for AI agents*. Anthropic Engineering. 3. Asai, A., Wu, Z., Wang, Y., Sil, A., & Hajishirzi, H. (2023). *Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection*. arXiv:2310.11511. 4. Belady, L. A. (1966). *A Study of Replacement Algorithms for a Virtual-Storage Computer*. IBM Systems Journal, 5(2), 78–101. 5. Bian, A. A., Buhmann, J. M., Krause, A., & Tschiatschek, S. (2017). *Guarantees for Greedy Maximization of Non-submodular Functions with Applications*. ICML 2017. 6. Bousetouane, F. (2026). *ACC: Adaptive Cognitive Control for Bio-Inspired Bounded Agent State*. arXiv:2601.11653. 7. Budzianowski, P., et al. (2018). *MultiWOZ — A Large-Scale Multi-Domain Wizard-of-Oz Dataset for Task-Oriented Dialogue Modelling*. EMNLP 2018. 8. Carbonell, J. & Goldstein, J. (1998). *The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries*. SIGIR 1998. 9. Curme, C. & Daugherty, W. (2026). *Deep Agents: Filesystem Persistence for Long-Running Agent Tasks*. LangChain Engineering Blog. 10. Dar, S., Franklin, M. J., Jónsson, B. T., Srivastava, D., & Tan, M. (1996). *Semantic Data Caching and Replacement*. VLDB 1996. 11. Edge, D., et al. (2024). *From Local to Global: A Graph RAG Approach to Query-Focused Summarization*. arXiv:2404.16130. 12. Factory.ai (2025). *Probe-Based Evaluation of Context Compression in Coding Agents*. Factory.ai Research Blog. 13. Fowler, M. (2005). *Event Sourcing*. martinfowler.com/eaaDev/EventSourcing.html. 14. Henderson, M., Thomson, B., & Young, S. (2014). *Word-Based Dialog State Tracking with Recurrent Neural Networks*. SIGDIAL 2014. 15. Hu, C., Li, J., & Wu, Q. (2025). *A Survey of Memory Mechanisms in Large Language Model Based Agents*. arXiv:2512.13564. 16. Jiang, Z., et al. (2023a). *Active Retrieval Augmented Generation* (FLARE). arXiv:2305.06983. 17. Josselyn, S. A. & Tonegawa, S. (2020). *Memory engrams: Recalling the past and imagining the future*. Science, 367(6473), eaaw4325. 18. Krause, A. & Golovin, D. (2014). *Submodular Function Maximization*. In Tractability: Practical Approaches to Hard Problems, Cambridge University Press. 19. Kryscinski, W., et al. (2020). *Evaluating the Factual Consistency of Abstractive Text Summarization*. EMNLP 2020. 20. Lashley, K. S. (1950). *In search of the engram*. Symposia of the Society for Experimental Biology, 4, 454–482. 21. Lin, S. (2025). *Google Agent Development Kit: Event Sourcing for Production Agents*. Google AI Blog. 22. Liu, N. F., et al. (2024). *Lost in the Middle: How Language Models Use Long Contexts*. TACL. 23. Maynez, J., et al. (2020). *On Faithfulness and Factuality in Abstractive Summarization*. ACL 2020. 24. Megiddo, N. & Modha, D. S. (2003). *ARC: A Self-Tuning, Low Overhead Replacement Cache*. USENIX FAST 2003. 25. Nemhauser, G. L., Wolsey, L. A., & Fisher, M. L. (1978). *An analysis of approximations for maximizing submodular set functions—I*. Mathematical Programming, 14(1), 265–294. 26. Packer, C., et al. (2023). *MemGPT: Towards LLMs as Operating Systems*. arXiv:2310.08560. 27. Park, J. S., et al. (2023). *Generative Agents: Interactive Simulacra of Human Behavior*. arXiv:2304.03442. 28. Rastogi, A., et al. (2020). *Towards Scalable Multi-Domain Conversational Agents: The Schema-Guided Dialogue Dataset*. AAAI 2020. 29. Sarthi, P., et al. (2024). *RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval*. arXiv:2401.18059. 30. Serra, O. (2026a). *CORTEX: Persona-Aware Context Engineering for Persistent AI Identity*. Technical Report, OpenClaw. 31. Serra, O. (2026b). *SYNAPSE: Synthesized Negotiation Across Provider-Specific Engines — Multi-Model Adversarial Reasoning for Persistent AI Agents*. Working Paper. 32. Sumers, T. R., et al. (2023). *Cognitive Architectures for Language Agents* (CoALA). arXiv:2309.02427. 33. Tonegawa, S., et al. (2015). *Memory engram storage and retrieval*. Current Opinion in Neurobiology, 35, 101–109. 34. Verma, A. (2026). *Focus: Agent-Managed Context Compression for Long-Horizon Tasks*. arXiv:2601.07190. 35. Walker, M. P. & Stickgold, R. (2004). *Sleep-Dependent Learning and Memory Consolidation*. Neuron, 44(1), 121–133. 36. Weaviate (2025). *Context Engineering — LLM Memory and Retrieval for AI Agents*. weaviate.io/blog/context-engineering. 37. Wixted, J. T. & Ebbesen, E. B. (1991). *On the Form of Forgetting*. Psychological Science, 2(6), 409–415. 38. Xu, W., et al. (2025). *A-MEM: Agentic Memory for LLM Agents*. arXiv:2502.12110. 39. Yan, S., et al. (2025). *Memory-R1: Enhancing LLM Agents to Manage and Utilize Memories via Reinforcement Learning*. arXiv:2508.19828. 40. Yu, Y., et al. (2026). *Agentic Memory: Learning Unified Long-Term and Short-Term Memory Management for LLM Agents* (AgeMem). arXiv:2601.01885. 41. Zeng, Y., et al. (2024). *Structural Memory: Mixing Episodic, Semantic, and Procedural Memory for Complex Agent Tasks*. arXiv:2412.15266. 42. Zeng, Y., et al. (2026). *LOCA-bench: A Benchmark for Long-Context Agent Evaluation*. arXiv:2602.07962. 43. Zhang, H., et al. (2025a). *G-Memory: Hierarchical Graph Memory for Large Language Model Agents*. arXiv:2506.07398. 44. Zhang, Q., et al. (2026). *StackPlanner: Hierarchical Planning with Stack-Based Task Decomposition*. arXiv:2601.05890.

··· 1 unchanged paragraph folded ···

v2.0 · 13. Preliminary Evaluation## 13. Preliminary Evaluation
removed in v2.4
v2.0 · 13. Preliminary EvaluationWhile the full evaluation framework described in Section 12 is under active execution, we report preliminary observations from production deployment and an ongoing stress test.
removed in v2.4
v2.0 · 13.1 Production Deployment Observations### 13.1 Production Deployment Observations
removed in v2.4
v2.0 · 13.1 Production Deployment ObservationsTRACE has been deployed in a personal AI agent (OpenClaw) for three months. Over this period:
removed in v2.4
v2.0 · 13.1 Production Deployment Observations- **Compaction events:** 847 pointer-based compactions executed across 71 active sessions. - **Artifact preservation:** 100% of referenced artifacts remained retrievable after compaction. No "only copy" losses were observed. - **Retrieval fidelity:** Retrieval pack injection restored exact error strings, file paths, and tool output fragments in 94% of cases where the original context had been evicted. The remaining 6% involved retrieval ranking errors (correct artifact in store but not selected for the retrieval pack), not data loss. - **Latency:** Mean retrieval pack assembly: 127ms (p95: 203ms). Mean event ingestion: 3.2ms per event. Pointer compaction: <80ms per eviction cycle. All measurements on commodity hardware (single-core SQLite, no GPU). - **Context utilization:** Mean context fill at compaction trigger: 87% of window. Post-compaction context size (pointer manifest + hot tail): 34% of window, freeing 53% for continued interaction.
removed in v2.4
v2.0 · 13.1 Production Deployment ObservationsThese observations are not controlled experiments — they reflect production use with a single user and a single embedding model (text-embedding-3-small). We report them as evidence of operational viability, not as rigorous benchmarks.
removed in v2.4
v2.0 · 13.2 Needle-in-Haystack Stress Test (In Progress)### 13.2 Needle-in-Haystack Stress Test (In Progress)
removed in v2.4
v2.0 · 13.2 Needle-in-Haystack Stress Test (In Progress)Following the protocol described in Section 12.1, we are running a compaction stress test with the following preliminary observations:
removed in v2.4
v2.0 · 13.2 Needle-in-Haystack Stress Test (In Progress)- **Setup:** 50 synthetic "needles" (unique file paths, error hashes, and parameter values) embedded across 200 conversation turns, with forced compaction every 50 turns. - **After 3 compactions:** Exact-match recall for needles remains >90% with TRACE pointer compaction + retrieval pack injection. Under narrative compaction baseline, recall drops to <5% after the second compaction, consistent with the "compaction catastrophe" analysis in Section 3. - **After 5 compactions:** TRACE recall degrades to ~82%, primarily due to retrieval ranking under increased store size. Narrative compaction recall: 0%.
removed in v2.4
v2.0 · 13.2 Needle-in-Haystack Stress Test (In Progress)Full results with statistical analysis will be reported upon completion of the evaluation campaign.
removed in v2.4
v2.0 · 13.3 Latency Profile### 13.3 Latency Profile
removed in v2.4
v2.0 · 13.3 Latency Profile| Operation | Mean | p95 | Notes | |---|---|---|---| | Event ingestion (Layer 1) | 3.2ms | 8ms | SQLite WAL mode, single-writer | | Retrieval pack assembly (Layer 2) | 127ms | 203ms | FTS5 + embedding lookup, K=20 candidates | | Pointer compaction | 78ms | 95ms | Manifest construction only | | Sleep consolidation (Layer 3) | 4.2s | 8.7s | Nightly, non-blocking |
removed in v2.4
not in v2.0
v2.4 · Annex A — Algorithms (Pseudocode)# Annex A — Algorithms (Pseudocode)
not in v2.0
v2.4 · Annex A — Algorithms (Pseudocode)All algorithms are collected here to keep the main paper readable. Updated to reflect v2.3 formalism.
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)## A.1 Continuous ingestion and asynchronous indexing (Layer 1)
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)```text Algorithm A.1: INGEST_AND_INDEX(event) Input: event = {kind, content, metadata, timestamp, session_id, turn_id}
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)1: event_id <- new_ulid()
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)// Artifactize large tool outputs with tail preview window 2: if event.kind == tool_result and size(event.content) > ARTIFACT_THRESHOLD then 3: artifact_id <- store_artifact(compress(event.content), metadata) 4: tail_preview <- extract_tail(event.content, lines=PREVIEW_LINES) 5: event.content <- pointer("artifact", artifact_id, tail_preview) 6: end if
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)// Synchronous: persist event + update FTS (fast, on critical path) 7: persist_event(event_id, event) 8: update_metadata_indexes(event_id, metadata) 9: text_for_search <- extract_text_for_search(event) 10: update_fts_index(event_id, text_for_search)
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)// Asynchronous: queue embedding computation (off critical path) 11: if should_embed(event) then 12: enqueue_for_embedding(event_id, extract_text_for_embedding(event)) 13: end if
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)14: return event_id

··· 1 unchanged paragraph folded ···

v2.0 · Annex A --- Algorithms (Pseudocode)# Annex A --- Algorithms (Pseudocode)
removed in v2.4
v2.0 · Annex A --- Algorithms (Pseudocode)All algorithms are collected here to keep the main paper readable, per the paper rules.
removed in v2.4
v2.0 · A.1 Continuous ingestion and indexing (Layer 1)## A.1 Continuous ingestion and indexing (Layer 1)
removed in v2.4
v2.0 · A.1 Continuous ingestion and indexing (Layer 1)```text Algorithm A.1: INGEST_AND_INDEX(event) Input: event = {kind, content, metadata, timestamp, session_id, turn_id}
removed in v2.4
v2.0 · A.1 Continuous ingestion and indexing (Layer 1)1: event_id <- new_ulid() 2: if event.kind == tool_result and size(event.content) > ARTIFACT_THRESHOLD then 3: artifact_id <- store_artifact(compress(event.content), metadata) 4: event.content <- pointer("artifact", artifact_id) 5: end if
removed in v2.4
v2.0 · A.1 Continuous ingestion and indexing (Layer 1)6: persist_event(event_id, event) // append-only 7: update_metadata_indexes(event_id, metadata)
removed in v2.4
v2.0 · A.1 Continuous ingestion and indexing (Layer 1)8: text_for_search <- extract_text_for_search(event) // may include excerpt for artifacts 9: update_fts_index(event_id, text_for_search)
removed in v2.4
v2.0 · A.1 Continuous ingestion and indexing (Layer 1)10: if should_embed(event) then 11: emb <- embed(extract_text_for_embedding(event)) 12: persist_embedding(event_id, emb) // fixed-size vector 13: end if
removed in v2.4
v2.0 · A.1 Continuous ingestion and indexing (Layer 1)14: return event_id ```
removed in v2.4
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)Background worker (runs continuously):
not in v2.0
v2.4 · A.1 Continuous ingestion and asynchronous indexing (Layer 1)EMBEDDING_WORKER(): 1: loop 2: batch <- dequeue_embedding_batch(max_size=BATCH_SIZE, max_wait=BATCH_TIMEOUT) 3: embeddings <- embed_batch(batch.texts) 4: for (event_id, emb) in zip(batch.event_ids, embeddings) do 5: persist_embedding(event_id, emb) 6: end for 7: end loop ```
v2.0 · A.2 Hybrid push/pull context pack builder (Layer 2)## A.2 Per-turn context pack builder (Layer 2)
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)## A.2 Hybrid push/pull context pack builder (Layer 2)
v2.0 · A.2 Hybrid push/pull context pack builder (Layer 2)```text Algorithm A.2: BUILD_CONTEXT_PACK(user_msg, task_state, recent_tail, budgets) Input: user_msg, task_state, recent_tail budgets = {B_sys, B_task, B_tail, B_ret, B_headroom}
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)```text Algorithm A.2: BUILD_CONTEXT_PACK(user_msg, task_state, recent_tail, markers, budgets) Input: user_msg, task_state, recent_tail, markers budgets = {B_sys, B_task, B_tail, B_markers, B_headroom}
v2.0 · A.2 Per-turn context pack builder (Layer 2)Output: ordered context_pack
removed in v2.4
v2.0 · A.2 Per-turn context pack builder (Layer 2)1: q <- build_query(user_msg, task_state, recent_tail)
removed in v2.4
not in v2.0
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)Output: ordered context_pack (push pack; pull is on-demand via recall tool)
not in v2.0
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)1: context_pack <- [ SYSTEM_BLOCK(B_sys), TASK_STATE_BLOCK(task_state, cap=B_task), TIME_RANGE_MARKERS(markers, cap=B_markers), RECALL_TOOL_DECLARATION(), RECENT_TAIL_BLOCK(recent_tail, cap=B_tail), USER_MESSAGE_BLOCK(user_msg) ]
not in v2.0
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)2: assert token_estimate(context_pack) + B_headroom <= B_ctx 3: return context_pack
not in v2.0
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)---
not in v2.0
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)Algorithm A.2b: RECALL_TOOL(query, task_state, B_pull) Input: query, task_state, B_pull
not in v2.0
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)Output: retrieval_pack (bounded evidence)
v2.0 · A.2 Hybrid push/pull context pack builder (Layer 2)2: C_vec <- vector_search(q.embedding, topN = N_vec, filters = task_state.filters) 3: C_fts <- fts_search(q.keywords, topN = N_fts, filters = task_state.filters) 4: C_ptr <- expand_pointers(task_state.key_events, task_state.key_artifacts) 5: C_pin <- pinned_objects(task_state.task_id, user_profile_id)
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)1: q <- build_retrieval_query(query, task_state) 2: C_vec <- vector_search(q.embedding, topN=N_vec, filters=task_state.filters) 3: C_fts <- fts_search(q.keywords, topN=N_fts, filters=task_state.filters) 4: C_ptr <- expand_key_events(task_state.key_events) 5: C_pin <- pinned_objects(task_state.task_id) 6: C <- dedupe(C_vec ∪ C_fts ∪ C_ptr ∪ C_pin)
v2.0 · A.2 Per-turn context pack builder (Layer 2)6: C <- dedupe(C_vec U C_fts U C_ptr U C_pin)
removed in v2.4
v2.0 · A.2 Hybrid push/pull context pack builder (Layer 2)7: for item in C do 8: base <- base_score(item, q) // sim, bm25, recency, type, freq 9: mod <- task_conditioned_modifier(item, task_state) // Algorithm A.3 10: item.score <- base * mod 11: end for
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)7: for item in C do 8: base <- base_score(item, q) 9: mod <- task_conditioned_modifier(item, task_state) // Algorithm A.3 10: item.score <- base * mod 11: end for
v2.0 · A.2 Hybrid push/pull context pack builder (Layer 2)12: S <- mmr_select(C, k = K_max, lambda = 0.7) // relevance vs redundancy 13: R <- pack_under_budget(S, B_ret, per_type_quotas)
v2.4 · A.2 Hybrid push/pull context pack builder (Layer 2)12: S <- mmr_select(C, k=K_max, lambda=0.7) 13: R <- pack_under_budget(S, B_pull, per_type_quotas) 14: log_retrieval(task_state.task_id, query, R) 15: return R ```
v2.0 · A.2 Per-turn context pack builder (Layer 2)14: context_pack <- [ SYSTEM_BLOCK(B_sys), TASK_STATE_BLOCK(task_state, cap=B_task), RETRIEVAL_BLOCK(R, cap=B_ret), RECENT_TAIL_BLOCK(recent_tail, cap=B_tail), USER_MESSAGE_BLOCK(user_msg) ]
removed in v2.4
v2.0 · A.2 Per-turn context pack builder (Layer 2)15: assert token_estimate(context_pack) + B_headroom <= B_ctx 16: log_retrieval(task_state.task_id, R) 17: return context_pack ```
removed in v2.4
v2.0 · A.3 Task-aware retrieval priority (task-conditioned modifier)## A.3 Task-aware retrieval priority (task-conditioned modifier)
removed in v2.4
v2.0 · A.3 Task-aware retrieval priority (task-conditioned modifier)```text Algorithm A.3: TASK_CONDITIONED_MODIFIER(item, task_state) Inputs: item: memory candidate with metadata - kind/type (objective, decision, mistake, tool_result, etc.) - task_id, episode_id - premise_ref (task_state_version_id at write time) - supersedes / superseded_by links - utility_tags (e.g., "needed_for_final_report") task_state: current task state (includes phase, requirements, premises)
removed in v2.4
v2.0 · A.3 Task-aware retrieval priority (task-conditioned modifier)Output: modifier m >= 0
removed in v2.4
not in v2.0
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)## A.3 Task-conditioned modifier (derived from §5.2)
not in v2.0
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)```text Algorithm A.3: TASK_CONDITIONED_MODIFIER(item, task_state) Input: item (with metadata), task_state Output: modifier m >= 0
v2.0 · A.3 Task-conditioned modifier (derived from §5.2)1: if item.task_id != task_state.task_id and not cross_task_allowed(item, task_state) then 2: return 0.0 3: end if
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)// Task relevance: filter unrelated tasks 1: if item.task_id != task_state.task_id and not cross_task_allowed(item, task_state) then 2: return 0.0 3: end if

··· 1 unchanged paragraph folded ···

v2.0 · A.3 Task-conditioned modifier (derived from §5.2)5: // Supersession: prefer latest versions 6: if item.is_superseded and not task_state.request_historical_versions then 7: m <- m * 0.1 8: end if
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)// Supersession: prefer latest versions (sup(e) factor) 5: if item.is_superseded and not task_state.request_historical then 6: m <- m * 0.1 7: end if
v2.0 · A.3 Task-aware retrieval priority (task-conditioned modifier)9: // Premise compatibility: downweight items produced under incompatible assumptions 10: compat <- premise_compatibility(item.premise_ref, task_state.current_premises) 11: m <- m * compat // compat in [0,1]
removed in v2.4
v2.0 · A.3 Task-aware retrieval priority (task-conditioned modifier)12: // Phase salience: map task phase to preferred memory types 13: m <- m * phase_salience(task_state.phase, item.type) // e.g., planning favors summaries/decisions
removed in v2.4
not in v2.0
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)// Premise compatibility: prem(e, τ) factor 8: compat <- premise_compatibility(item.premise_ref, task_state.current_premises) 9: m <- m * compat
not in v2.0
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)// Phase salience: phase(e, τ) factor 10: m <- m * phase_salience(task_state.phase, item.type)
v2.0 · A.3 Task-conditioned modifier (derived from §5.2)14: // Expected future needs: if task requires postmortem/self-assessment, keep mistakes salient 15: if task_state.requires_self_assessment and item.type in {"mistake","success","lesson"} then 16: m <- m * 2.0 17: end if
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)// Expected future needs: boost if self-assessment required 11: if task_state.requires_self_assessment and item.type in {"mistake","success","lesson"} then 12: m <- m * 2.0 13: end if
v2.0 · A.3 Task-conditioned modifier (derived from §5.2)18: // Guardrails: never crowd out hard constraints 19: if item.type == "constraint" then 20: m <- max(m, 3.0) 21: end if
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)// Guardrails: constraints never crowded out 14: if item.type == "constraint" then 15: m <- max(m, 3.0) 16: end if
v2.0 · A.3 Task-conditioned modifier (derived from §5.2)22: return clamp(m, 0.0, M_MAX) ```
v2.4 · A.3 Task-conditioned modifier (derived from §5.2)17: return clamp(m, 0.0, M_MAX) ```
v2.0 · A.4 Pointer-based compaction (cache eviction + time-range marker)## A.4 Pointer-based compaction (cache eviction + manifest)
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)## A.4 Pointer-based compaction (cache eviction + time-range marker)
v2.0 · A.4 Pointer-based compaction (cache eviction + manifest)```text Algorithm A.4: POINTER_COMPACT(cache, task_state, B_ctx, B_headroom) Input: cache: ordered in-context blocks task_state B_ctx: max tokens B_headroom: reserved tokens
removed in v2.4
v2.0 · A.4 Pointer-based compaction (cache eviction + manifest)Output: compacted cache
removed in v2.4
v2.0 · A.4 Pointer-based compaction (cache eviction + manifest)1: while token_estimate(cache) > (B_ctx - B_headroom) do 2: victim_span <- choose_victim(cache) // heuristic: oldest tool_results > oldest tool_calls > oldest dialogue // never evict: system block, task_state, last-k turns 3: ensure_persisted_and_indexed(victim_span.event_ids) // Layer 1 invariant 4: remove(cache, victim_span)
removed in v2.4
v2.0 · A.4 Pointer-based compaction (cache eviction + manifest)5: manifest <- { evicted_event_ids: victim_span.event_ids, anchor_events: select_anchors(victim_span, task_state), artifacts: extract_artifact_refs(victim_span), task_state_ref: task_state.version_id, hints: derive_hints(victim_span) }
removed in v2.4
v2.0 · A.4 Pointer-based compaction (cache eviction + manifest)6: insert_manifest(cache, manifest, position=victim_span.start_position) 7: end while
removed in v2.4
not in v2.0
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)```text Algorithm A.4: POINTER_COMPACT(cache, task_state, B_ctx, B_headroom) Input: cache, task_state, B_ctx, B_headroom Output: compacted cache with time-range markers
not in v2.0
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)1: while token_estimate(cache) > (B_ctx - B_headroom) do 2: victim_span <- choose_victim_lru(cache, type_weights={ tool_result: 1.0, tool_call: 0.8, dialogue: 0.5, decision: 0.2, constraint: 0.0 })
not in v2.0
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)3: ensure_persisted_and_indexed(victim_span.event_ids)
not in v2.0
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)4: remove(cache, victim_span)
not in v2.0
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)5: topics <- extract_topics(victim_span, task_state) 6: t_start <- victim_span.first_turn_id 7: t_end <- victim_span.last_turn_id
not in v2.0
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)8: marker <- format( "[Events T{t_start}–T{t_end} evicted. " "Key topics: {join(topics, ', ')}. " "Use recall(query) to retrieve details.]" )
not in v2.0
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)9: insert_marker(cache, marker, position=victim_span.start_position) 10: end while
v2.0 · A.4 Pointer-based compaction (cache eviction + time-range marker)8: return cache ```
v2.4 · A.4 Pointer-based compaction (cache eviction + time-range marker)11: return cache ```
v2.0 · A.5 Hierarchical planning protocol (planner ↔ executor)## A.5 Hierarchical planning protocol (planner <-> executor)
v2.4 · A.5 Hierarchical planning protocol (planner ↔ executor)## A.5 Hierarchical planning protocol (planner ↔ executor)
not in v2.0
v2.4 · A.5 Hierarchical planning protocol (planner ↔ executor)```text Algorithm A.5: HIERARCHICAL_PLANNING_LOOP(planner_task_state)
v2.0 · A.5 Hierarchical planning protocol (planner ↔ executor)```text Algorithm A.5: HIERARCHICAL_PLANNING_LOOP(planner_task_state) 1: planner forms plan with subtask list S 2: for each subtask s in S do 3: delegation_packet <- { subtask_id, objective, constraints, acceptance_criteria, pointers_to_relevant_events, pointers_to_artifacts, plan_node_ref } 4: send_to_executor(delegation_packet) 5: end for
v2.4 · A.5 Hierarchical planning protocol (planner ↔ executor)1: planner forms plan with subtask list S 2: for each subtask s in S do 3: delegation_packet <- { subtask_id, objective, constraints, acceptance_criteria, key_event_refs, relevant_artifact_ids, plan_node_ref, recall_tool_access: true } 4: send_to_executor(delegation_packet) 5: end for
v2.0 · A.5 Hierarchical planning protocol (planner ↔ executor)6: while not all subtasks complete do 7: report <- receive_executor_report() 8: validate(report.acceptance_evidence via provenance pointers) 9: update planner_task_state (milestones, risks, next subtasks) 10: end while ```
v2.4 · A.5 Hierarchical planning protocol (planner ↔ executor)6: while not all subtasks complete do 7: report <- receive_executor_report() 8: validate(report.key_findings via provenance pointers) 9: update planner_task_state 10: end while ```

··· 1 unchanged paragraph folded ···

not in v2.0
v2.4 · A.6 Multi-granularity retrieval with drill-down```text Algorithm A.6: MULTI_GRANULARITY_RETRIEVE(query, task_state, B_ret)
not in v2.0
v2.4 · A.6 Multi-granularity retrieval with drill-down1: classify query specificity: {exact, local, thematic, strategic}
v2.0 · A.6 Multi-granularity retrieval with drill-down```text Algorithm A.6: MULTI_GRANULARITY_RETRIEVE(query, task_state, B_ret) 1: classify query specificity: {exact, local, thematic, strategic} 2: if specificity == strategic then 3: candidates <- retrieve_strategic_insights(task_state) 4: else if specificity == thematic then 5: candidates <- retrieve_topic_summaries(task_state) 6: else 7: candidates <- retrieve_raw_events_and_artifacts(query, task_state) 8: end if
v2.4 · A.6 Multi-granularity retrieval with drill-down2: if specificity == strategic then 3: candidates <- retrieve_strategic_insights(task_state) 4: else if specificity == thematic then 5: candidates <- retrieve_topic_summaries(task_state) 6: else 7: candidates <- retrieve_raw_events_and_artifacts(query, task_state) 8: end if

··· 1 unchanged paragraph folded ···

v2.0 · A.6 Multi-granularity retrieval with drill-down10: if confidence(pack) < THRESH or user asks "show exact" then 11: drill <- retrieve_raw_supporting_events(pack.provenance, cap=B_ret/2) 12: pack <- merge(pack, drill) under budget 13: end if
v2.4 · A.6 Multi-granularity retrieval with drill-down10: if confidence(pack) < THRESH or query_requests_exact_evidence(query) then 11: drill <- retrieve_raw_supporting_events(pack.provenance, cap=B_ret/2) 12: pack <- merge(pack, drill) under budget 13: end if

··· 1 unchanged paragraph folded ···

v2.0 · A.7 Retention and bounded hot-storage policy## A.7 Retention and bounded hot-storage policy (artifacts)
v2.4 · A.7 Retention and bounded hot-storage policy## A.7 Retention and bounded hot-storage policy

··· 1 unchanged paragraph folded ···

v2.0 · A.7 Retention and bounded hot-storage policy1: for each artifact a where age(a) > N_days_hot do 2: if not archived(a) then 3: move_to_cold_storage(a.bytes, compress=compression) 4: keep_online_metadata(a.id, a.sha256, a.mime_type, a.size, a.created_at) 5: optionally delete_online_bytes(a.id) 6: end if 7: end for ```
v2.4 · A.7 Retention and bounded hot-storage policy1: for each artifact a where age(a) > N_days_hot do 2: if not archived(a) then 3: move_to_cold_storage(a.bytes, compress=compression) 4: keep_online_metadata(a.id, a.sha256, a.mime_type, a.size, a.created_at) 5: keep_online_tail_preview(a.id, a.tail_preview) 6: optionally delete_online_bytes(a.id) 7: end if 8: end for ```
v2.0 · A.8 Evaluation harness: compaction stress test## A.8 Compaction stress test harness ("needles in a haystack")
v2.4 · A.8 Evaluation harness: compaction stress test## A.8 Evaluation harness: compaction stress test
v2.0 · A.8 Compaction stress test harness ("needles in a haystack")```text Algorithm A.8: COMPACTION_STRESS_TEST(policy, needles, bloat_rounds) 1: trace <- generate_base_trace() 2: inject needles early (hashes, exact error lines, file paths)
removed in v2.4
not in v2.0
v2.4 · A.8 Evaluation harness: compaction stress test```text Algorithm A.8: COMPACTION_STRESS_TEST(policy, needles, bloat_rounds) Input: policy: one of {narrative, truncation, memgpt, focus, trace} needles: list of {type, value, query} tuples bloat_rounds: number of compaction-forcing rounds
not in v2.0
v2.4 · A.8 Evaluation harness: compaction stress testOutput: evaluation_report
not in v2.0
v2.4 · A.8 Evaluation harness: compaction stress test1: trace <- generate_base_trace()
not in v2.0
v2.4 · A.8 Evaluation harness: compaction stress test2: for each needle in needles do 3: trace <- trace + generate_event_containing(needle.value, position="early") 4: end for
v2.0 · A.8 Evaluation harness: compaction stress test3: for i = 1..bloat_rounds do 4: trace <- trace + generate_tool_bloat() 5: if would_overflow(trace) then 6: trace <- apply_policy(policy, trace) 7: end if 8: end for
v2.4 · A.8 Evaluation harness: compaction stress test5: compaction_count <- 0 6: for i = 1..bloat_rounds do 7: trace <- trace + generate_tool_bloat(size=BLOAT_SIZE) 8: while would_overflow(trace) do 9: trace <- apply_policy(policy, trace) 10: compaction_count <- compaction_count + 1 11: end while 12: end for
v2.0 · A.8 Compaction stress test harness ("needles in a haystack")9: for each needle in needles do 10: ask recall query requiring exact match 11: score exact-match accuracy 12: end for
removed in v2.4
v2.0 · A.8 Compaction stress test harness ("needles in a haystack")13: return aggregate scores + token accounting + retrieval logs ```
removed in v2.4
v2.0 · A.8 Compaction stress test harness ("needles in a haystack")---
removed in v2.4
v2.0 · Annex B: TRACE v2.0 --- Implementation Plan (OpenClaw)# Annex B: TRACE v2.0 --- Implementation Plan (OpenClaw)
removed in v2.4
v2.0 · Annex B: TRACE v2.0 --- Implementation Plan (OpenClaw)**Purpose.** This annex turns the TRACE v2.0 architecture into an incremental, testable build plan for the OpenClaw codebase. It is written as a step-by-step blueprint an engineer can implement with minimal interpretation.
removed in v2.4
v2.0 · Annex B: TRACE v2.0 --- Implementation Plan (OpenClaw)**Non-negotiables (from the paper).** 1. **Lossless ground truth:** every interaction event is durably persisted (messages, tool calls/results, state updates). 2. **Context = cache:** context assembly is an explicit, budgeted packing problem. 3. **Pointer compaction:** overflow eviction inserts structured pointer manifests (not narrative summaries) once retrieval exists. 4. **Hard budgets:** per-turn injected retrieval is bounded; task state is bounded; compaction outputs are bounded. 5. **Provenance everywhere:** every derived object references source event IDs/artifacts.
removed in v2.4
v2.0 · Annex B: TRACE v2.0 --- Implementation Plan (OpenClaw)**OpenClaw integration constraint.** New TRACE behavior is **off-by-default** and must not break existing behavior for users who do not opt in.
removed in v2.4
v2.0 · Annex B: TRACE v2.0 --- Implementation Plan (OpenClaw)---
removed in v2.4
v2.0 · Annex B: TRACE v2.0 --- Implementation Plan (OpenClaw)> **Note:** This annex provides an implementation blueprint for one production system (OpenClaw). It is included for reproducibility and to demonstrate practical feasibility, but is not part of the core scientific contribution. The architecture described in Sections 4–9 is system-agnostic and can be implemented on any agent framework with a persistent storage layer.
removed in v2.4
v2.0 · B.1. Where TRACE plugs into OpenClaw (file-level integration map)## B.1. Where TRACE plugs into OpenClaw (file-level integration map)
removed in v2.4
v2.0 · B.1. Where TRACE plugs into OpenClaw (file-level integration map)OpenClaw already has the correct "spine" for TRACE. We will instrument it rather than rewrite it.
removed in v2.4
v2.0 · Primary integration points (existing files)### Primary integration points (existing files)
removed in v2.4
v2.0 · Primary integration points (existing files)1. **Per-turn orchestration (Layer 2 assembly point)** - `src/agents/pi-embedded-runner/run/attempt.ts` --- where the per-turn message list is constructed and the LLM is called. - `src/agents/pi-embedded-runner/history.ts` --- where historical messages are managed.
removed in v2.4
v2.0 · Primary integration points (existing files)2. **Compaction (Layer 2 eviction point)** - `src/agents/pi-embedded-runner/compact.ts` --- current compaction implementation with `before_compaction` / `after_compaction` hooks. - `src/agents/compaction.ts` --- compaction entry point. - `src/agents/pi-extensions/compaction-safeguard.ts` - `src/agents/pi-extensions/compaction-safeguard-runtime.ts`
removed in v2.4
v2.0 · Primary integration points (existing files)3. **Tool result pressure control (must remain compatible)** - `src/agents/pi-embedded-runner/tool-result-truncation.ts` --- already wired into `attempt.ts` to bound tool result tokens.
removed in v2.4
v2.0 · Primary integration points (existing files)4. **Session persistence (Layer 1 event log source)** - `src/memory/session-files.ts` --- session JSONL I/O. - `src/agents/pi-embedded-runner/session-manager-init.ts` - `src/agents/pi-embedded-runner/session-manager-cache.ts` - `src/sessions/session-key-utils.ts`
removed in v2.4
v2.0 · Primary integration points (existing files)5. **Configuration & hooks** - `src/config/config.ts` --- YAML config schema. - `src/hooks/types.ts`, `src/hooks/loader.ts`, `src/plugins/hook-runner-global.ts`
removed in v2.4
v2.0 · Storage substrates we will leverage (existing on disk) - **Lossless raw session events (already present):** `<agent-state>/sessions/*.jsonl` - **Index DB to leverage (explicit requirement):** `<agent-workspace>/db/memory.db` (sqlite-vec + FTS5)### Storage substrates we will leverage (existing on disk) - **Lossless raw session events (already present):** `<agent-state>/sessions/*.jsonl` - **Index DB to leverage (explicit requirement):** `<agent-workspace>/db/memory.db` (sqlite-vec + FTS5)
removed in v2.4
v2.0 · Storage substrates we will leverage (existing on disk) - **Lossless raw session events (already present):** `<agent-state>/sessions/*.jsonl` - **Index DB to leverage (explicit requirement):** `<agent-workspace>/db/memory.db` (sqlite-vec + FTS5)> TRACE will treat the JSONL session logs as the canonical *append-only event stream*, and `memory.db` as the *retrieval surface* (indexes + derived objects).
removed in v2.4
v2.0 · Storage substrates we will leverage (existing on disk) - **Lossless raw session events (already present):** `<agent-state>/sessions/*.jsonl` - **Index DB to leverage (explicit requirement):** `<agent-workspace>/db/memory.db` (sqlite-vec + FTS5)---
removed in v2.4
v2.0 · B.2. Cross-cutting implementation rules (apply to every phase)## B.2. Cross-cutting implementation rules (apply to every phase)
removed in v2.4
v2.0 · B.2.1 Feature flags and safe rollout All TRACE features live behind config flags. A single flag must be able to revert to baseline behavior instantly:### B.2.1 Feature flags and safe rollout All TRACE features live behind config flags. A single flag must be able to revert to baseline behavior instantly:
removed in v2.4
v2.0 · B.2.1 Feature flags and safe rollout All TRACE features live behind config flags. A single flag must be able to revert to baseline behavior instantly:- `trace.enabled` (master switch) - Individual toggles per subsystem: ingestion, retrieval, pointer compaction, task state, consolidation, hierarchy
removed in v2.4
v2.0 · B.2.2 "Ingest-before-evict" invariant Pointer compaction must not evict anything unless TRACE confirms: - the evicted items exist in the durable session JSONL, **and** - the items have been indexed (or at minimum queued and flushed) into the retrieval DB.### B.2.2 "Ingest-before-evict" invariant Pointer compaction must not evict anything unless TRACE confirms: - the evicted items exist in the durable session JSONL, **and** - the items have been indexed (or at minimum queued and flushed) into the retrieval DB.
removed in v2.4
v2.0 · B.2.2 "Ingest-before-evict" invariant Pointer compaction must not evict anything unless TRACE confirms: - the evicted items exist in the durable session JSONL, **and** - the items have been indexed (or at minimum queued and flushed) into the retrieval DB.This is enforced by a **flush barrier** in the ingestion pipeline.
removed in v2.4
v2.0 · B.2.3 Prompt injection hygiene for retrieved text All retrieved content is wrapped as **non-executable evidence** (system message framing) and must not be allowed to override system/developer policies. Retrieval blocks must: - clearly label content as "retrieved memory / evidence" - strip or quarantine obvious instruction patterns (configurable; can start as "wrap only")### B.2.3 Prompt injection hygiene for retrieved text All retrieved content is wrapped as **non-executable evidence** (system message framing) and must not be allowed to override system/developer policies. Retrieval blocks must: - clearly label content as "retrieved memory / evidence" - strip or quarantine obvious instruction patterns (configurable; can start as "wrap only")
removed in v2.4
v2.0 · B.2.4 No long code dumps in-repo docs This annex is a plan; implementation should be modular and well-tested. Keep logic in dedicated `src/trace/**` modules with colocated tests.### B.2.4 No long code dumps in-repo docs This annex is a plan; implementation should be modular and well-tested. Keep logic in dedicated `src/trace/**` modules with colocated tests.
removed in v2.4
v2.0 · B.2.4 No long code dumps in-repo docs This annex is a plan; implementation should be modular and well-tested. Keep logic in dedicated `src/trace/**` modules with colocated tests.---
removed in v2.4
v2.0 · B.3. Data model & on-disk layout (what we are implementing)## B.3. Data model & on-disk layout (what we are implementing)
removed in v2.4
v2.0 · B.3.1 Event identity OpenClaw session JSONL events already contain: - `id`, `parentId`, `timestamp`, `type`, plus type-specific fields### B.3.1 Event identity OpenClaw session JSONL events already contain: - `id`, `parentId`, `timestamp`, `type`, plus type-specific fields
removed in v2.4
v2.0 · B.3.1 Event identity OpenClaw session JSONL events already contain: - `id`, `parentId`, `timestamp`, `type`, plus type-specific fieldsTRACE will **reuse `id` as the canonical `event_id`** to avoid dual-ID drift and to preserve provenance across layers.
removed in v2.4
v2.0 · B.3.2 Artifacts (large tool outputs) Artifacts are immutable blobs stored out-of-band to prevent: - exploding context, - bloating indexes, - repeated truncation losing "needles".### B.3.2 Artifacts (large tool outputs) Artifacts are immutable blobs stored out-of-band to prevent: - exploding context, - bloating indexes, - repeated truncation losing "needles".
removed in v2.4
v2.0 · B.3.2 Artifacts (large tool outputs) Artifacts are immutable blobs stored out-of-band to prevent: - exploding context, - bloating indexes, - repeated truncation losing "needles".**Artifact record (minimum):** - `artifact_id` (ULID or sha256-derived ID) - `sha256`, `byte_size`, `mime_type`, `created_at` - `session_key`, `event_id` (provenance)
removed in v2.4
v2.0 · B.3.3 Pointer manifests (compaction output) Pointer compaction inserts a **structured manifest** into context that is: - bounded (token-capped), - identifier-heavy (event IDs, artifact IDs), - non-narrative (no "summary of what happened").### B.3.3 Pointer manifests (compaction output) Pointer compaction inserts a **structured manifest** into context that is: - bounded (token-capped), - identifier-heavy (event IDs, artifact IDs), - non-narrative (no "summary of what happened").
removed in v2.4
v2.0 · B.3.3 Pointer manifests (compaction output) Pointer compaction inserts a **structured manifest** into context that is: - bounded (token-capped), - identifier-heavy (event IDs, artifact IDs), - non-narrative (no "summary of what happened").**Manifest fields (v1):** - `manifest_id` - `evicted_event_ids`: ranges or list - `anchor_event_ids`: key decisions/errors/constraints in that span - `artifact_ids` - `task_state_ref` (version id; nullable until Task State exists) - `hints`: keywords/entities/file paths/tool names (token-capped)
removed in v2.4
v2.0 · B.3.4 Task State (persistent, versioned JSON) Task State is the compact "index card" that survives compaction and drives task-conditioned retrieval.### B.3.4 Task State (persistent, versioned JSON) Task State is the compact "index card" that survives compaction and drives task-conditioned retrieval.
removed in v2.4
v2.0 · B.3.4 Task State (persistent, versioned JSON) Task State is the compact "index card" that survives compaction and drives task-conditioned retrieval.**Task State fields (v1, bounded):** - identity: `task_state_id`, `version_id`, `updated_at` - `title`, `objective`, `success_criteria` - `phase`: `planning | execution | debugging | evaluation` - `constraints[]`, `open_loops[]` - `plan[]` (step + status) - `pointers`: `key_event_ids[]`, `key_artifact_ids[]`, `decision_event_ids[]` - `premises`: optional lightweight "assumptions" map (v1 can be empty)
removed in v2.4
v2.0 · B.3.4 Task State (persistent, versioned JSON) Task State is the compact "index card" that survives compaction and drives task-conditioned retrieval.---
removed in v2.4
v2.0 · B.4. Phased implementation (each phase is independently deliverable)## B.4. Phased implementation (each phase is independently deliverable)
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)### Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Goal.** Introduce the TRACE module boundaries, config schema, and a runtime object that can be passed through the runner without changing behavior.
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Prerequisites.** None.
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Files to create/modify.** - **Modify** - `src/config/config.ts` --- add `trace:` config block with defaults (all off). - `src/agents/pi-embedded-runner/run/params.ts` --- thread resolved TRACE config into run parameters. - **Create** - `src/trace/config.ts` --- TypeScript types + defaults for TRACE config. - `src/trace/runtime.ts` --- constructs a `TraceRuntime` (enabled/disabled). - `src/trace/logging.ts` --- structured debug logging helpers (guarded by config).
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Implementation details (step-by-step).** 1. Define `TraceConfig` in `src/trace/config.ts` with explicit defaults. 2. Extend `src/config/config.ts` to load/validate the YAML keys. 3. In `src/agents/pi-embedded-runner/run/params.ts`, attach `trace` params to the run context object passed into `run.ts` / `attempt.ts`. 4. Implement `TraceRuntime.disabled()` returning no-op methods (so calling sites stay clean). 5. Add a minimal "TRACE diag" logger that can be enabled without affecting output.
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Configuration (new keys, defaults).** Example (all off): ```yaml trace: enabled: false ingest: { enabled: false } retrieval: { enabled: false } compaction: { mode: "narrative" } taskState: { enabled: false } consolidation: { enabled: false } hierarchy: { enabled: false } ```
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Test plan.** - **Unit** - Config parsing test: when keys absent, defaults are applied. - `TraceRuntime.disabled()` methods do not throw and return deterministic empties. - **Manual** - Run OpenClaw normally; confirm no new files are written and no log spam.
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Pass/fail.** - Pass if: `pnpm test` passes; behavior identical with `trace.enabled=false`.
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Rollback plan.** - Remove config keys or keep `trace.enabled=false`.
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Estimated effort.** 1--2 engineering days.
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)**Definition of Done.** - TRACE config exists, compiles, and can be plumbed into runtime without behavior changes.
removed in v2.4
v2.0 · Phase 0 --- TRACE scaffolding, config, and observability (no behavior change)---
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")### Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Goal.** As session events are written, ingest them into a retrieval surface (FTS now; vectors later), and optionally artifactize large tool results. This phase makes the **"only copy" failure mode impossible** even before pointer compaction.
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Prerequisites.** Phase 0.
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Files to create/modify.** - **Modify** - `src/memory/session-files.ts` --- after appending each JSONL event, call TRACE ingestion. - `src/agents/pi-embedded-runner/run/attempt.ts` --- ensure persisted tool results remain lossless; truncation must be for context only (copy-on-write). - `src/agents/pi-embedded-runner/tool-result-truncation.ts` --- expose reusable excerpt extraction utilities (must not mutate originals). - **Create** - `src/trace/ingest/ingestor.ts` --- `ingestSessionEvent(event, sessionKey)`. - `src/trace/artifacts/store.ts` --- artifact write/read + metadata. - `src/trace/db/memorydb.ts` --- sqlite connection + prepared statements. - `src/trace/db/schema.ts` --- table creation/migration (idempotent).
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Implementation details (step-by-step).** 1. **Add a TRACE ingestion call** in `src/memory/session-files.ts`: - Immediately after writing a session event line, call `trace.ingestSessionEvent(...)`. - Ensure this call is guarded by `trace.enabled && trace.ingest.enabled`. 2. **Implement a bounded async queue** in `src/trace/ingest/ingestor.ts`: - Enqueue event records; batch inserts into `memory.db`. - Provide `flush(): Promise<void>` used later by compaction. 3. **Define minimal DB schema** in `src/trace/db/schema.ts`: - `trace_events` (metadata + excerpt + artifact refs + `importance INTEGER NOT NULL DEFAULT 3`) - `trace_events_fts` (FTS5 virtual table with `event_id`, `text`, `session_key`, `type`, `tool_name`)
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")The `importance` column stores the importance score $\iota \in [1, 10]$ computed at ingest time using the deterministic heuristic defined in Section 4.3 of the paper. The scoring function is implemented in the ingestor: ```typescript function computeImportance(event: SessionEvent): number { if (event.type === 'user_message' && isDirective(event.content)) return 10; if (event.type === 'decision' || isConstraint(event.content)) return 9; if (event.type === 'tool_result' && hasError(event.content)) return 8; if (event.type === 'tool_result') return 6; if (event.type === 'assistant_message' && hasReasoning(event.content)) return 5; if (event.type === 'user_message') return 3; if (event.type === 'assistant_message') return 3; return 2; // system/internal } ``` This score is persisted with the event and used by the retrieval scoring layer (Phase 5) to weight candidates during task-conditioned retrieval. 4. **Artifactize tool results** (optional, feature-flagged): - If an ingested event is `type == "tool_result"` and byte size > threshold: - write compressed artifact file under a TRACE-managed directory - store only an excerpt + artifact ref in `trace_events` - keep provenance: link to `event_id` + `session_key` - Important: do **not** change what the agent "actually did"; only change storage/indexing and later retrieval. 5. **Backfill utility (optional but recommended in this phase):** - Provide a simple function in `src/trace/ingest/ingestor.ts` to backfill a session JSONL into DB for testing (not necessarily exposed as CLI yet).
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Configuration (new keys, defaults).** - `trace.ingest.enabled: false` - `trace.ingest.dbPath: "<agent-workspace>/db/memory.db"` (default) - `trace.ingest.batchSize: 50` - `trace.artifacts.enabled: false` - `trace.artifacts.thresholdBytes: 20000` - `trace.artifacts.dir: "<agent-state>/artifacts"` (or under workspace; choose one and document)
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Test plan.** - **Unit** - Artifact store roundtrip: write -> read -> sha256 matches; compression roundtrip works. - DB schema creation is idempotent. - **Integration (Vitest)** - Use a temp sqlite file; ingest synthetic session events; assert: - `trace_events` row count matches events ingested - FTS query returns expected `event_id` for keywords - Ingest a large `tool_result`; assert artifact file exists and DB stores artifact ref + excerpt. - **Manual** - Enable ingestion and run a session that uses a noisy tool. - Confirm: - session JSONL continues to be written - `memory.db` contains new TRACE tables - artifacts appear when threshold exceeded
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Pass/fail.** - Pass if: ingestion never blocks the main run, does not crash, and `flush()` completes; FTS retrieval finds ingested events.
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Rollback plan.** - Set `trace.ingest.enabled=false` and `trace.artifacts.enabled=false`. No existing behavior changes.
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Estimated effort.** 3--6 engineering days.
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")**Definition of Done.** - TRACE can ingest events continuously into `memory.db` and (optionally) artifactize large tool results without user-visible regressions.
removed in v2.4
v2.0 · Phase 1 --- Continuous ingestion + artifact store foundation (Layer 1 "make it lossless & searchable")---
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)### Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Goal.** Before every LLM call, build a bounded **retrieval pack** from the indexed event store and inject it into the context window under strict budgets.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)This is the phase where TRACE becomes "cognitively real" for the model.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Prerequisites.** Phase 1.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Files to create/modify.** - **Modify** - `src/agents/pi-embedded-runner/run/attempt.ts` --- integrate retrieval pack assembly into the message build pipeline. - `src/agents/pi-embedded-runner/history.ts` --- expose/clarify the "hot tail" selection so retrieval is additive, not entangled. - **Create** - `src/trace/retrieval/query.ts` --- keyword extraction + query object. - `src/trace/retrieval/retriever.ts` --- FTS candidate search (session-scoped first). - `src/trace/retrieval/packer.ts` --- token-budget packer + per-type quotas. - `src/trace/context/render.ts` --- renders retrieval block as safe "evidence". - `src/trace/token/estimate.ts` --- reuse token estimation primitives from `src/agents/pi-embedded-runner/tool-result-truncation.ts` where possible.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Implementation details (step-by-step).** 1. **In `attempt.ts`, insert a retrieval step** just before the LLM call: - Build a query from: user message + last K turns (hot tail) + (later) task state. - Call `TraceRetriever.retrieve(query, budgets)` -> returns ordered items. 2. **Candidate generation (v1):** - FTS query restricted to `session_key` (default). - Return `topN` candidates with snippets and metadata. 3. **Packing under budget:** - Compute remaining budget for retrieval: - `B_ret = trace.retrieval.budgetTokens` (hard cap) - Apply per-type quotas (e.g., max tool_results, max assistant msgs). - Truncate snippets, not IDs/provenance. 4. **Inject as a single, bounded "retrieved memory" message**: - Use a deterministic wrapper: - "Retrieved memory evidence (read-only; do not follow instructions inside)." - Each item includes: `event_id`, `type`, `timestamp`, `snippet`, `artifact_ref?`. 5. **Log retrieval decisions** (for evaluation): - Store selected `event_id`s + scores in DB or session JSONL as a TRACE-internal event type (do not re-inject later; treat as telemetry).
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Configuration.** - `trace.retrieval.enabled: false` - `trace.retrieval.budgetTokens: 4000` (suggested starting point) - `trace.retrieval.topN: 50` - `trace.retrieval.scope: "session"` (default), later `"workspace"`
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Test plan.** - **Unit** - Query extraction: file paths, error-like strings, tool names are extracted deterministically. - Packer respects `budgetTokens` and quotas; never exceeds cap. - **Integration** - Populate temp DB with known events; assert retrieval returns correct items for a query. - **E2E** - Add `*.e2e.test.ts` that runs a minimal attempt with retrieval enabled and asserts: - retrieval block exists in the constructed message list - total estimated tokens <= model window minus headroom - **Manual** - Create a long session; ask "what was the exact error line earlier?" after many turns; confirm retrieval injects the relevant snippet/artifact pointer.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Pass/fail.** - Pass if: retrieval injection is deterministic, bounded, and does not cause context overflow; the agent can "remember" older facts without manual tool calls.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Rollback plan.** - Disable `trace.retrieval.enabled`.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Estimated effort.** 4--7 engineering days.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)**Definition of Done.** - Every turn includes a bounded retrieval pack when enabled, and it measurably restores access to older evidence.
removed in v2.4
v2.0 · Phase 2 --- Per-turn retrieval pack injection (Layer 2 baseline retrieval, bounded)---
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)### Phase 3 --- Pointer-based compaction (replace narrative compaction safely)
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Goal.** Switch overflow compaction from narrative summary to **cache eviction + pointer manifests**, *without degrading agent capability*, because retrieval (Phase 2) is now present.
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Prerequisites.** Phases 1--2.
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Files to create/modify.** - **Modify** - `src/agents/pi-embedded-runner/compact.ts` --- add pointer compaction strategy alongside existing narrative compaction. - `src/agents/compaction.ts` --- select compaction mode from config. - `src/agents/pi-extensions/compaction-safeguard.ts` and `...-runtime.ts` --- ensure safeguard respects ingest-before-evict. - `src/agents/pi-embedded-runner/run/attempt.ts` --- ensure compaction happens *before* final retrieval packing so budgets are consistent. - **Create** - `src/trace/compaction/pointer-compactor.ts` - `src/trace/compaction/victim-selector.ts` - `src/trace/compaction/manifest-render.ts`
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Implementation details (step-by-step).** 1. **Add a new compaction mode selector** in `src/agents/pi-embedded-runner/compact.ts`: - `narrative` (existing default) - `pointer` (TRACE) 2. **Victim selection heuristic (v1, deterministic):** - Evict oldest tool results first (largest pressure). - Then oldest tool calls. - Then oldest dialogue turns. - Never evict: - system/developer prompts - the most recent `keepLastTurns` - (when Phase 4 lands) Task State block 3. **Enforce ingest-before-evict:** - Before evicting a span, call `await trace.ingest.flush()` and verify each evicted message maps to a stored `event_id`. - If invariant fails: fall back to narrative compaction (configurable) and log. 4. **Insert pointer manifest message in place of evicted span:** - A single bounded message with: - evicted event ID ranges - anchors (error events, decisions, user directives) - artifact refs - hints (file paths/tool names/keywords) 5. **Index the manifest itself** (so future retrieval can "see" the pointer boundary). 6. **Ensure compaction hooks still fire**: - `before_compaction` receives: strategy + victim span summary - `after_compaction` receives: manifest id + evicted ranges
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Configuration.** - `trace.compaction.mode: "narrative" | "pointer"` (default narrative) - `trace.compaction.keepLastTurns: 8` - `trace.compaction.manifestMaxTokens: 400` - `trace.compaction.fallbackToNarrativeOnInvariantFailure: true`
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Test plan.** - **Unit** - Victim selection: tool results are selected before dialogue. - Manifest rendering: never exceeds `manifestMaxTokens`. - **Integration** - Given a synthetic long message list, pointer compaction reduces token estimate below threshold and inserts exactly one manifest per evicted span. - **E2E** - Run a "tool bloat" scenario that forces compaction: - After compaction, ask for an early needle (exact string). - Pass if retrieval finds it from DB and injects it. - **Manual** - Confirm compaction output no longer contains narrative summaries when pointer mode is enabled.
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Pass/fail.** - Pass if: compaction never loses evidence (events remain retrievable), and the agent continues functioning post-compaction due to retrieval.
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Rollback plan.** - Set `trace.compaction.mode="narrative"`.
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Estimated effort.** 4--8 engineering days.
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)**Definition of Done.** - Pointer compaction works end-to-end under forced overflow, with retrieval successfully rehydrating needed evidence.
removed in v2.4
v2.0 · Phase 3 --- Pointer-based compaction (replace narrative compaction safely)---
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)### Phase 4 --- Task State v1 (persistent, bounded, injected every turn)
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Goal.** Implement Task State as a small, versioned JSON object that: - persists across compactions and restarts, - drives retrieval and planning, - is bounded by a hard token cap.
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Prerequisites.** Phases 1--3 (Task State is most valuable once pointer compaction exists, but it can ship without it).
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Files to create/modify.** - **Modify** - `src/agents/pi-embedded-runner/session-manager-init.ts` --- load/create Task State at session start. - `src/agents/pi-embedded-runner/session-manager-cache.ts` --- cache latest Task State snapshot. - `src/agents/pi-embedded-runner/run/attempt.ts` --- inject Task State block into the per-turn context pack (before retrieval). - `src/memory/session-files.ts` --- persist Task State updates as JSONL events (`type: "trace_task_state"`). - **Create** - `src/trace/task-state/schema.ts` - `src/trace/task-state/store.ts` --- "load latest from session JSONL" and "append update". - `src/trace/task-state/render.ts` --- bounded rendering/truncation logic. - `src/trace/task-state/manager.ts` --- lifecycle: init, get, update, versioning.
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Implementation details (step-by-step).** 1. **Define Task State schema** (v1) with explicit token-bound rendering priority order: 1) objective + success criteria 2) constraints + open loops 3) plan steps 4) pointers (IDs are cheap; keep them) 2. **Persist Task State updates** as session JSONL events: - Append an event line: `type: "trace_task_state"`, with `task_state_id`, `version_id`, and full JSON. 3. **Load latest Task State on session init**: - Scan the session JSONL for the most recent `trace_task_state` event. - If none exists, create one from the first user message (simple heuristic). 4. **Update strategy (v1): ship without an LLM dependency** - Start with conservative heuristics: - if user says "new goal / actually / change of plan", update `objective` - if assistant outputs explicit checklist bullets, map into `plan[]` (optional) - Defer LLM-based patching to consolidation (Phase 6) or a later optional flag. 5. **Inject Task State into context pack** on every attempt: - Use a single bounded message near the top (after system block). - Token-capped render; never exceed `trace.taskState.maxTokens`.
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Configuration.** - `trace.taskState.enabled: false` - `trace.taskState.maxTokens: 700` - `trace.taskState.autoUpdate: "off" | "heuristic"` (default off)
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Test plan.** - **Unit** - Render truncation: never exceeds max tokens; drops lowest-priority fields first. - Versioning: updates increment `version_id` and preserve `task_state_id`. - **Integration** - Write a session JSONL with multiple Task State events; load returns the latest. - **E2E** - Run: create state -> force compaction -> ensure next attempt still injects the same Task State (latest version). - **Manual** - Inspect session JSONL: verify `trace_task_state` lines appear and are append-only.
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Pass/fail.** - Pass if: Task State persists across restart + compaction and remains bounded.
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Rollback plan.** - Disable `trace.taskState.enabled` (existing stored events are ignored).
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Estimated effort.** 4--7 engineering days.
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)**Definition of Done.** - Task State exists, is persisted as events, injected every turn when enabled, and stays within a hard cap.
removed in v2.4
v2.0 · Phase 4 --- Task State v1 (persistent, bounded, injected every turn)---
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)### Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Goal.** Implement Algorithm A.3 in production form: retrieval prioritization is modulated by active task and premises, not static similarity.
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Prerequisites.** Phases 2 and 4.
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Files to create/modify.** - **Modify** - `src/trace/ingest/ingestor.ts` --- tag ingested events with `task_state_id` and `premise_ref = task_state.version_id`. - `src/trace/retrieval/retriever.ts` --- apply task-conditioned modifier. - **Create** - `src/trace/retrieval/scoring.ts` - `src/trace/retrieval/premise-compat.ts` - `src/trace/retrieval/phase-salience.ts`
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Implementation details (step-by-step).** 1. **Bind events to task state at write time**: - When ingesting an event, attach: - `task_state_id` - `premise_ref` (current Task State `version_id`) - `task_phase` snapshot (optional) 2. **Implement task-conditioned modifier (v1, deterministic):** - If candidate is cross-task and cross-task is disallowed -> score 0. - If item is superseded (objective/plan versions) -> downweight unless explicitly querying history. - If item type is `constraint` -> boost (never crowded out). - Apply phase salience table: - planning: decisions/constraints/summaries > raw logs - debugging: errors/tool results > summaries 3. **Expose "why selected" in retrieval output**: - This is critical for debugging retrieval policies.
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Configuration.** - `trace.scoring.taskConditioned.enabled: false` - `trace.scoring.allowCrossTask: false` - `trace.scoring.phaseSalienceOverrides: { ... }` (optional)
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Test plan.** - **Unit** - With equal base similarity, constraints outrank tool noise. - Superseded items are demoted when not requesting historical context. - **Integration** - Populate DB with two versions of an objective; confirm latest is preferred. - **Manual** - Change the task objective mid-session; ask a question; confirm retrieval injects "current" objective/constraints, not old ones.
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Pass/fail.** - Pass if: retrieval becomes stable under objective changes and does not flood context with obsolete near-matches.
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Rollback plan.** - Disable `trace.scoring.taskConditioned.enabled`.
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Estimated effort.** 3--6 engineering days.
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)**Definition of Done.** - Retrieval selection is demonstrably task-aware on canned tests and does not regress baseline relevance.
removed in v2.4
v2.0 · Phase 5 --- Task-conditioned retrieval scoring (premises, supersession, phase salience)---
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)### Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Goal.** Add periodic consolidation that builds multi-granularity derived objects (episodes, decisions, summaries, links) as **indexes over events**, not replacements.
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Prerequisites.** Phases 1--5.
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Files to create/modify.** - **Modify** - `src/agents/pi-embedded-runner/run.ts` --- schedule consolidation (on session end is the safest first trigger). - `src/trace/db/schema.ts` --- add derived tables. - **Create** - `src/trace/consolidation/run.ts` - `src/trace/consolidation/episodes.ts` - `src/trace/consolidation/decisions.ts` - `src/trace/consolidation/summaries.ts` - `src/trace/consolidation/links.ts`
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Implementation details (step-by-step).** 1. **Trigger consolidation "on session end" first**: - In `src/agents/pi-embedded-runner/run.ts`, after the run completes successfully (or after N turns), call `trace.consolidate(session_key)` if enabled. 2. **Episode segmentation (v1 heuristic):** - time gap threshold (e.g., 15 minutes) or compaction boundary -> new episode. 3. **Decision record extraction (v1 heuristic, LLM optional later):** - detect assistant lines containing "Decision:" / "We will...". 4. **Store derived objects in DB with provenance:** - `trace_episodes`: event_id ranges - `trace_decisions`: `decision_text` + `source_event_ids[]` - `trace_summaries`: episode summaries with explicit links to episode + source events 5. **Retrieval integration (optional in this phase, but recommended):** - When query is thematic ("what did we decide?"), prefer decision records/episode summaries. - Always include provenance pointers so the agent can drill down.
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Configuration.** - `trace.consolidation.enabled: false` - `trace.consolidation.mode: "on_session_end" | "manual"` (start with on_session_end) - `trace.consolidation.episodeGapMinutes: 15` - `trace.consolidation.summaries.enabled: false` (optional if LLM cost concerns)
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Test plan.** - **Unit** - Episode segmentation determinism. - Provenance integrity: derived object references only real event IDs. - **Integration** - Run consolidation on a synthetic trace; assert derived tables populated correctly. - **Manual** - End a session; verify consolidation runs and derived objects appear in DB.
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Pass/fail.** - Pass if: derived objects are created, bounded, provenance-linked, and retrieval can use them without losing access to raw events.
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Rollback plan.** - Disable `trace.consolidation.enabled`. Derived tables remain but are ignored.
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Estimated effort.** 6--12 engineering days (depending on whether LLM summaries ship now or later).
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)**Definition of Done.** - Consolidation reliably creates episodes + decisions (+ optional summaries) with provenance, and retrieval can surface them.
removed in v2.4
v2.0 · Phase 6 --- Sleep consolidation (Layer 3 derived objects with provenance)---
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)### Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Goal.** Implement the planner/executor separation described in the paper: separate contexts and retrieval surfaces, delegated subtask sessions, and compact reports flowing upward with pointers.
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Prerequisites.** Phases 2--6 (at minimum retrieval + task state + pointer compaction).
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Files to create/modify.** - **Modify** - `src/agents/pi-embedded-runner/run.ts` --- add ability to spawn sub-runs (executor) under a child session key. - `src/agents/pi-embedded-runner/run/attempt.ts` --- handle delegation/report protocol messages. - `src/sessions/session-key-utils.ts` --- derive stable child session keys from parent + subtask id. - `src/memory/session-files.ts` --- persist delegation/report events with `parentId` linkages. - **Create** - `src/trace/hierarchy/protocol.ts` - `src/trace/hierarchy/spawn.ts` - `src/trace/hierarchy/report-render.ts`
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Implementation details (step-by-step).** 1. **Define protocol schemas** (stored as session events): - `trace_delegation`: objective, constraints, acceptance criteria, pointers, budget, `parent_session_key` - `trace_executor_report`: status, evidence pointers, artifacts created, recommended next steps, `executor_session_key` 2. **Spawn executor runs**: - Planner emits a structured delegation packet (mechanism depends on how OpenClaw represents tool calls; keep it internal). - Runner creates a child session key and executes a bounded run for that subtask. 3. **Report compaction**: - Executor writes a bounded report event with pointers, not raw logs. 4. **Planner retrieval changes**: - Planner retrieval prioritizes reports/decisions/constraints; executor retrieval prioritizes raw tool results.
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Configuration.** - `trace.hierarchy.enabled: false` - `trace.hierarchy.executor.maxTurns: 12` - `trace.hierarchy.planner.retrievalBudgetTokens: 2000` - `trace.hierarchy.executor.retrievalBudgetTokens: 6000`
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Test plan.** - **Unit** - Session key derivation stability. - Protocol validation (required fields present, bounded sizes). - **Integration** - Simulate delegation -> executor session writes report -> planner session ingests report pointer. - **E2E** - Stub a planner that delegates; ensure two sessions are created and linked and the planner sees the report.
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Pass/fail.** - Pass if: delegation creates a child session, report returns with provenance pointers, and planner context remains bounded.
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Rollback plan.** - Disable `trace.hierarchy.enabled` (monolithic run resumes).
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Estimated effort.** 8--15 engineering days.
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)**Definition of Done.** - One end-to-end planner->executor->report flow works, with separate session logs and retrieval budgets.
removed in v2.4
v2.0 · Phase 7 --- Hierarchical planning support (planner/executor sessions + provenance-linked reports)---
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)### Phase 8 --- Artifact lifecycle & retention (bounded hot storage)
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Goal.** Ensure artifacts do not grow unbounded on disk while preserving hashes + metadata and keeping the event store lossless.
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Prerequisites.** Phase 1.
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Files to create/modify.** - **Create** - `src/trace/artifacts/lifecycle.ts` - **Modify** - `src/agents/pi-embedded-runner/run.ts` (or `src/trace/consolidation/run.ts`) --- periodically run lifecycle policy. - `src/trace/db/schema.ts` --- add artifact state fields (`archived_at`, `cold_path`, etc.) if not already present.
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Implementation details (step-by-step).** 1. Define policy: - compress at write - after `hotDays`, move to cold directory, keep metadata online 2. Implement lifecycle runner: - scan artifact metadata table; move bytes; update metadata 3. Ensure retrieval degrades gracefully: - if cold artifact not present locally, retrieval injects pointer + metadata (rehydration can be a future tool)
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Configuration.** - `trace.artifacts.retention.enabled: false` - `trace.artifacts.retention.hotDays: 30` - `trace.artifacts.retention.coldDir: "<agent-state>/artifacts-cold"` - `trace.artifacts.retention.deleteHotAfterArchive: true`
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Test plan.** - Unit/integration tests with temp dirs to verify move + metadata update.
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Rollback plan.** - Disable retention; artifacts remain in hot storage.
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Estimated effort.** 2--5 engineering days.
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)**Definition of Done.** - Artifact retention is enforced without breaking provenance or retrieval.
removed in v2.4
v2.0 · Phase 8 --- Artifact lifecycle & retention (bounded hot storage)---
removed in v2.4
v2.0 · B.5. Required evaluation harness (ships alongside the phases)## B.5. Required evaluation harness (ships alongside the phases)
removed in v2.4
v2.0 · B.5. Required evaluation harness (ships alongside the phases)TRACE's promise is measurable: it turns "irreversible forgetting" into "retrieval miss," which is diagnosable.
removed in v2.4
v2.0 · B.5.1 Needle-in-haystack compaction stress test (must implement by Phase 3) Implement a test harness aligned with Annex A.8 that: - injects exact needles early (hashes, file paths, one-line errors), - creates tool-output bloat to force compactions, - queries for exact needles afterward, - records exact-match recall + token accounting.### B.5.1 Needle-in-haystack compaction stress test (must implement by Phase 3) Implement a test harness aligned with Annex A.8 that: - injects exact needles early (hashes, file paths, one-line errors), - creates tool-output bloat to force compactions, - queries for exact needles afterward, - records exact-match recall + token accounting.
removed in v2.4
v2.0 · B.5.1 Needle-in-haystack compaction stress test (must implement by Phase 3) Implement a test harness aligned with Annex A.8 that: - injects exact needles early (hashes, file paths, one-line errors), - creates tool-output bloat to force compactions, - queries for exact needles afterward, - records exact-match recall + token accounting.**Where to place it.** - `src/trace/eval/compaction-stress.e2e.test.ts` (new)
removed in v2.4
v2.0 · B.5.1 Needle-in-haystack compaction stress test (must implement by Phase 3) Implement a test harness aligned with Annex A.8 that: - injects exact needles early (hashes, file paths, one-line errors), - creates tool-output bloat to force compactions, - queries for exact needles afterward, - records exact-match recall + token accounting.**Pass/fail criteria (minimum).** - Baseline narrative compaction without retrieval: expected low recall. - TRACE ingestion + retrieval + pointer compaction: high recall (needles recoverable via retrieval).
removed in v2.4
v2.0 · B.5.2 Retrieval telemetry (must implement by Phase 2) Persist retrieval decisions (not necessarily injected into context): - selected event IDs, - scores and modifiers, - token counts and truncations.### B.5.2 Retrieval telemetry (must implement by Phase 2) Persist retrieval decisions (not necessarily injected into context): - selected event IDs, - scores and modifiers, - token counts and truncations.
removed in v2.4
v2.0 · B.5.2 Retrieval telemetry (must implement by Phase 2) Persist retrieval decisions (not necessarily injected into context): - selected event IDs, - scores and modifiers, - token counts and truncations.This is how we tune task-conditioned scoring later without guessing.
removed in v2.4
v2.0 · B.5.2 Retrieval telemetry (must implement by Phase 2) Persist retrieval decisions (not necessarily injected into context): - selected event IDs, - scores and modifiers, - token counts and truncations.---
removed in v2.4
v2.0 · B.6. Ordering rationale (why this annex reorders the brief)## B.6. Ordering rationale (why this annex reorders the brief)
removed in v2.4
v2.0 · B.6. Ordering rationale (why this annex reorders the brief)The brief suggested implementing pointer compaction before retrieval. In OpenClaw, that ordering risks degrading the agent: a manifest of IDs is not useful unless the system already injects retrieved evidence. Therefore, this annex implements:
removed in v2.4
v2.0 · B.6. Ordering rationale (why this annex reorders the brief)1) **Ingest + index (lossless + searchable)** -> 2) **Retrieval injection (usable memory)** -> 3) **Pointer compaction (safe eviction)** -> 4) **Task State (stable task continuity)** -> 5) **Task-conditioned scoring** -> 6) **Consolidation** -> 7) **Hierarchy** -> 8) **Retention**
removed in v2.4
v2.0 · B.6. Ordering rationale (why this annex reorders the brief)This sequence delivers standalone value at every step and avoids "shipping a pointer manifest with no pointer-following mechanism."
removed in v2.4
v2.0 · B.6. Ordering rationale (why this annex reorders the brief)---
removed in v2.4
v2.0 · B.7. Summary: Phase deliverables at a glance## B.7. Summary: Phase deliverables at a glance
removed in v2.4
v2.0 · B.7. Summary: Phase deliverables at a glance| Phase | Delivers standalone value? | Primary user-facing gain | |---|---:|---| | 0 | Yes | Safe scaffolding; no change | | 1 | Yes | Lossless storage + searchable event index | | 2 | Yes | Automatic bounded memory injection per turn | | 3 | Yes | Overflow no longer destroys operational detail | | 4 | Yes | Persistent task continuity across compactions | | 5 | Yes | Retrieval aligns with current task/premises | | 6 | Yes | Multi-granularity derived memory with provenance | | 7 | Yes (optional) | Planner doesn't drown; executors stay sharp | | 8 | Yes | Disk boundedness without memory amnesia |
removed in v2.4
v2.0 · B.7. Summary: Phase deliverables at a glance---
removed in v2.4
v2.0 · B.7. Summary: Phase deliverables at a glance---
removed in v2.4
v2.0 · Changelog (v2.0 -> v2.1)## Changelog (v2.0 -> v2.1)
removed in v2.4
v2.0 · Changelog (v2.0 -> v2.1)This v2.1 revision adds importance scoring as a first-class concept throughout the TRACE architecture:
removed in v2.4
v2.0 · Changelog (v2.0 -> v2.1)1. **Section 4.3 (Data model):** Added `importance: number (1-10)` field to the Event schema with a deterministic scoring heuristic table. Cross-referenced with HIPPOCAMPUS v1.2 importance scoring. 2. **Section 5.2a (Continuous Ingestion Pipeline):** New subsection explaining that importance scoring occurs at ingest time (Layer 1), not during consolidation, closing the "always-on extraction" gap identified in GravityClaw/Pinecone systems. 3. **Annex B, Phase 1:** Added `importance` column to `trace_events` schema with TypeScript implementation of the scoring heuristic.
removed in v2.4
v2.0 · Changelog (v2.0 -> v2.1)---
removed in v2.4
v2.0 · Changelog (v2.0 -> v2.1)---
removed in v2.4
v2.0 · Changelog (v2.1 -> v2.2)## Changelog (v2.1 -> v2.2)
removed in v2.4
v2.0 · Changelog (v2.1 -> v2.2)This v2.2 revision addresses peer review feedback from dual-reviewer evaluation (Gemini 3.1 Pro and OpenAI o3):
removed in v2.4
v2.0 · Changelog (v2.1 -> v2.2)1. **Abstract:** Removed internal ESHM reference; reframed "lossless" as "lossless-by-design" with standard durability assumptions. 2. **Section 4.1 (P1):** Added durability caveats (WAL, checksums, backup) to the lossless ground truth principle. 3. **Section 6.2:** Added clarification that pointer manifests are consumed by the system retrieval layer, not by the LLM directly, addressing reviewer concern about LLM pointer comprehension and hallucination risk. 4. **Section 9:** Added note that proofs are semi-formal sketches; described graceful degradation under indexing lag and disk pressure. 5. **Section 13 (NEW):** Added "Preliminary Evaluation" with three subsections: (13.1) production deployment observations from 3-month deployment (847 compactions, 94% retrieval fidelity), (13.2) ongoing needle-in-haystack stress test results (>90% recall after 3 compactions vs <5% narrative baseline), (13.3) latency profile table. 6. **Annex B:** Added disclaimer noting the annex is an implementation blueprint for one system, not part of the core scientific contribution. 7. **References:** Added Self-RAG (Asai et al., 2023), MemoryBank (Zhong et al., 2023), kNN-LM (Khandelwal et al., 2020), LongMemEval (Wu et al., 2024).
removed in v2.4
not in v2.0
v2.4 · A.8 Evaluation harness: compaction stress test13: results <- [] 14: for each needle in needles do 15: response_1 <- query_agent(needle.query, trace) 16: exact_match_1 <- (response_1 contains needle.value exactly)
not in v2.0
v2.4 · A.8 Evaluation harness: compaction stress test17: if policy in {trace, memgpt, focus} and not exact_match_1 then 18: response_2 <- query_agent_with_retrieval_hint(needle.query, trace) 19: exact_match_2 <- (response_2 contains needle.value exactly) 20: end if
not in v2.0
v2.4 · A.8 Evaluation harness: compaction stress test21: results.append({ needle, exact_match_attempt_1, exact_match_attempt_2, partial_match, false_recall, compactions_survived }) 22: end for
not in v2.0
v2.4 · A.8 Evaluation harness: compaction stress test23: return evaluation_report(results) ```
not in v2.0
v2.4 · A.9 Testing Scaffolding Plan## A.9 Testing Scaffolding Plan
not in v2.0
v2.4 · A.9 Testing Scaffolding PlanTo validate ENGRAM's claims, we will build a replay-based testing harness using real interaction logs.
not in v2.0
v2.4 · A.9.1 The Replay Harness### A.9.1 The Replay Harness
not in v2.0
v2.4 · A.9.1 The Replay HarnessWe will use the existing OpenClaw session logs (`<agent-state>/sessions/*.jsonl`) as ground truth. 1. **Ingest:** Read a raw session log. 2. **Replay:** Feed events sequentially into the ENGRAM memory system. 3. **Constrain:** Enforce a strict token budget (e.g., 4k tokens) to force compaction. 4. **Probe:** Periodically pause replay and issue "needle" queries about past events that should have been evicted from cache but retained in the store.
not in v2.0
v2.4 · A.9.2 Metrics### A.9.2 Metrics
not in v2.0
v2.4 · A.9.2 Metrics- **Recall Rate:** % of needles successfully retrieved. - **Precision:** % of retrieved tokens that are relevant to the needle. - **Compaction Ratio:** Total raw tokens / Context window tokens. - **Latency:** Time to retrieve vs. time to read raw context.
not in v2.0
v2.4 · A.10 Results (Placeholder)## A.10 Results (Placeholder)
not in v2.0
v2.4 · A.10 Results (Placeholder)*This section is reserved for the empirical results from the replay harness.*
not in v2.0
v2.4 · A.10.1 Recall vs. Narrative Compaction [To be filled: Comparative chart of ENGRAM recall vs. standard summarization.]### A.10.1 Recall vs. Narrative Compaction [To be filled: Comparative chart of ENGRAM recall vs. standard summarization.]
not in v2.0
v2.4 · A.10.2 Retrieval Latency [To be filled: Latency distribution for 1-hop and 2-hop retrievals.]### A.10.2 Retrieval Latency [To be filled: Latency distribution for 1-hop and 2-hop retrievals.]

Changed paragraphs in the same form, for scripts: JSON · Markdown