# Total Recall: The Context Window as a Cache Over the Session Record: v1.0 → v1.5

From v1.0 (15 Feb) to v1.5 (16 Feb): 7,625 words to 6,361 words, 5,474 words in new or rewritten paragraphs and 6,738 taken out, 513 paragraphs changed.

## Change note of v1.5

**System named TRACE; text tightened and algorithms moved to an annex**

The same argument, rewritten and shortened by about 1,300 words. Most paragraphs were redrafted.

- The system gets a name, TRACE, and a new title: task-conditioned retrieval and pointer-based compaction.
- Related work is regrouped by theme instead of one subsection per system.
- New: retrieval conditioned on the active task, explained with examples.
- New diagrams comparing narrative compaction with pointer compaction, and of the overall architecture.
- The algorithms move out of the body into an annex as pseudocode.
- Adds a pointer to a companion paper on agent identity.

## Changed paragraphs

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

### Abstract

[-Persistent large-language-model (LLM) agents must operate under a hard constraint: a bounded context window that simultaneously serves as (i) the model’s working memory and (ii) the system’s *de facto* storage of high-resolution state. Production systems commonly respond to context overflow by "compaction": replacing long interaction histories with an LLM-generated narrative summary. We argue that this practice is not merely lossy---it is *catastrophically* lossy for persistent agents because it destroys the only cognitively accessible copy of the very details that later determine correctness (e.g., commit hashes, error messages, tool outputs, parameter values, and decisions). The catastrophe is amplified by a production reality that the literature underemphasizes: in tool-using agents, **tool results---not conversational turns---are the dominant driver of context pressure**. In our OpenClaw deployment, a single long-running session accumulated 89 tool results totaling 368K characters (approximately 92K tokens), consuming 79% of a 200K-token window and repeatedly triggering compaction.-]

### Abstract

[-We propose a refactoring of the memory problem: **Cache != Storage**. The context window should be treated as a cache over a lossless, append-only event store, and "compaction" should be implemented as cache eviction rather than narrative consolidation. Building on OS-inspired memory hierarchies (MemGPT/Letta), typed memory governance (MaRS), agentic and RL-trained memory managers (A-MEM, AgeMem, Memory-R1), cognitive-architecture framing (CoALA), and production context-engineering guidance (Anthropic, Weaviate), we introduce a **three-layer architecture** for persistent agents: *(1) Continuous Event Ingestion & Indexing*, *(2) Per-Turn Context-Primed Retrieval with an explicit Task State object*, and *(3) Sleep Consolidation with principled forgetting and hierarchical abstraction*. The key mechanism is **pointer-based compaction**: when evicting history from the context cache, we replace it with structured pointers (event IDs, artifact references, and task-state references) that preserve provenance and enable on-demand retrieval---eliminating the hallucination and irreversibility risks of LLM-generated summaries.-]

### Abstract

[-We present an implementation plan in OpenClaw using SQLite + FTS + vector indexing, describe an already-deployed band-aid (aggregate tool-result truncation), and propose an evaluation framework emphasizing information preservation across forced compactions ("needles in the haystack") and production metrics such as task continuity, retrieval precision@k, and context utilization. Our contribution is primarily architectural: a practical, lossless, production-oriented replacement for narrative compaction that reframes the context window as a managed cache over durable state.-]

### Abstract

{+Persistent 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.+}

### Abstract

{+We present **TRACE**, a lossless, 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.+}

### Abstract

{+TRACE 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 production data from a personal AI agent deployment, showing that pointer compaction prevents irreversible loss across repeated compactions while maintaining similar context utilization to baseline practices.+}

### 1.1 Persistent agents are not chats

As LLMs [-transition-] {+move+} from [-single-session assistants-] {+session-scoped chatbots+} to [-persistent agents---systems that-] {+**persistent agents**---systems expected to+} operate [-continuously-] across hours, days, and months---the memory problem [-changes qualitatively. A persistent-] {+becomes qualitatively different. The+} agent must [-maintain:-] {+preserve:+}

### 1.1 Persistent agents are not chats

[-1.-] {+-+} **High-resolution task state**: what [-has been tried,-] {+was attempted,+} what failed, what [-remains,-] {+succeeded,+} and why. [-2.-] {+-+} **Long-horizon commitments**: decisions, constraints, {+follow-ups,+} and [-follow-ups. 3.-] {+external dependencies. -+} **Tool-grounded evidence**: tool outputs, [-error-] {+logs, stack+} traces, [-file-] {+code+} diffs, [-search results, and logs that anchor reasoning in reality. 4.-] {+API responses. -+} **Continuity [-across-] {+under+} context resets**: the ability to resume without [-re-asking for already-provided details.-] {+re-deriving or re-asking.+}

### 1.1 Persistent agents are not chats

[-In transformer-based systems, the context window is the model’s only working memory. But in many deployed agent stacks, the context window also becomes the *only operational storage* of crucial intermediate state---because the system does not automatically persist, index, and retrieve that state. When the window fills, the system must choose between truncation, summarization, or restart. "Compaction" via narrative summarization is the prevailing compromise, endorsed as a practical technique for long-horizon tasks in production guidance. Anthropic explicitly describes compaction as summarizing a near-limit conversation and restarting with a compressed summary, discarding redundant tool outputs while preserving important decisions and unresolved issues. ([anthropic.com](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents))-]

### 1.1 Persistent agents are not chats

[-We argue this compromise is structurally wrong for persistent agents.-]

### 1.2 The catastrophe: narrative compaction destroys the only accessible copy

[-### 1.2 The catastrophe: narrative compaction destroys the only accessible copy-]

### 1.2 The catastrophe: narrative compaction destroys the only accessible copy

[-Narrative compaction takes a long trace---messages, tool calls, tool results, intermediate reasoning---and replaces it with a short summary. The summary is then re-injected into a new context window and becomes the system’s "memory" of the evicted interaction.-]

### 1.2 The catastrophe: narrative compaction destroys the only accessible copy

[-This is a catastrophe for two reasons:-]

### 1.2 The catastrophe: narrative compaction destroys the only accessible copy

[-1. **Irreversibility (the "only copy" problem).** Once details are omitted or distorted in the summary, the agent has no built-in path to recover them. The summary becomes the only copy the model can see; unless the system also stores and retrieves the original evidence, loss is permanent.-]

### 1.2 The catastrophe: narrative compaction destroys the only accessible copy

[-2. **Unreliable compression at maximum cognitive load.** Compaction is usually triggered *when the context is already saturated*---precisely when long-context performance is degraded ("context rot") and when the model is least reliable at selecting what matters. Both Anthropic and Weaviate emphasize that context is finite and exhibits diminishing returns; as it grows, failure modes emerge (poisoning, distraction, confusion, clash) and attention is stretched by the transformer’s quadratic interaction structure. ([anthropic.com](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents))-]

### 1.2 The catastrophe: narrative compaction destroys the only accessible copy

[-The "lost-in-the-middle" phenomenon compounds the problem: models often retrieve information less reliably when it appears in the middle of long contexts, even in explicitly long-context settings. ([aclanthology.org](https://aclanthology.org/2024.tacl-1.9/)) When compaction asks the model to summarize a long interaction, it is effectively asking it to recover and compress information from a regime where retrieval is already fragile.-]

### 1.1 Persistent agents are not chats

{+Transformer-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.+}

### 1.2 Why narrative compaction is structurally unsafe

{+### 1.2 Why narrative compaction is structurally unsafe+}

### 1.2 Why narrative compaction is structurally unsafe

{+A prevailing production technique is **narrative compaction**: summarize a large prefix of the conversation/tool trace into a short textual recap, then restart with the recap. This is attractive because it is simple and model-native.+}

### 1.2 Why narrative compaction is structurally unsafe

{+For persistent tool-using agents, it is structurally unsafe for two reasons:+}

### 1.2 Why narrative compaction is structurally unsafe

{+1. **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.+}

### 1.3 Production reality: tool results dominate context pressure

### 1.3 Production reality: tool [-result bloat dominates-] {+results dominate+} context pressure

### 1.3 Production reality: tool result bloat dominates context pressure

[-In production, persistent agents do not merely converse---they act. They call tools: code execution, file reads, grep, API queries, web search, database queries, telemetry retrieval, and more. Tool outputs can be large, repetitive, and high-entropy (logs, stack traces, JSON blobs). These outputs rapidly consume context capacity while often being useful only in small parts.-]

### 1.3 Production reality: tool result bloat dominates context pressure

[-In OpenClaw, we observed a representative failure: **89 tool results totaling 368K characters (~92K tokens) consumed ~79% of a 200K-token context window**. This bloat frequently triggers compaction. Importantly, the conversational history itself is often not the bottleneck; the tool outputs are.-]

### 1.3 Production reality: tool result bloat dominates context pressure

[-This production pattern is under-discussed in much of the academic agent-memory literature, which often assumes that the main scaling challenge is *dialogue length* rather than *tool evidence volume*. By contrast, practitioner context-engineering guidance increasingly highlights tool design, tool-result management, and just-in-time retrieval to avoid context saturation. ([anthropic.com](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents))-]

### 1.3 Production reality: tool results dominate context pressure

{+In production agents, context pressure is frequently driven not by dialogue length but by **tool output volume**. Tool outputs are large, high-entropy, repetitive, and often contain one critical line embedded in thousands. This matters because those outputs are exactly the evidence the agent must later cite, re-check, or operationalize.+}

### 1.3 Production reality: tool results dominate context pressure

{+In 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**.+}

### 1.4 Thesis and contributions

[-**Thesis:** *Lossless event-sourced memory with pointer-based compaction can replace lossy narrative summarization as the persistence mechanism for long-running LLM agents.*-]

### 1.4 Thesis and contributions

[-We make five central claims:-]

### 1.4 Thesis and contributions

[-1. **The Compaction Catastrophe:** Narrative compaction is catastrophically lossy because it destroys the only cognitively accessible copy of high-resolution state and evidence. 2. **Cache != Storage:** The context window should be treated as a cache over a durable memory store, not as primary storage. 3. **Pointer Compaction:** Replace narrative summaries with structured pointers (Task State + event/artifact references) enabling on-demand retrieval and provenance. 4. **Continuous Indexing:** Index events in real time---*before* they leave context---so retrieval is available without panic flushes at overflow. 5. **Tool Result Bloat:** In production, tool results are a primary driver of overflow; memory systems must handle tool evidence as first-class artifacts.-]

### 1.4 Thesis and contributions

[-Our practical contributions are:-]

### 1.4 Thesis and contributions

[-- A production-grounded **three-layer architecture** (Continuous Indexing -> Per-Turn Retrieval -> Sleep Consolidation) for persistent agents. - A concrete design for **pointer-based compaction** as cache eviction over a lossless event store. - An OpenClaw-oriented **implementation plan** (SQLite + FTS + vector search + artifacts) and a migration path from narrative compaction. - A proposed **evaluation framework** for information preservation across forced compactions.-]

### 1.4 Thesis and contributions

{+**Thesis:** The context window must be treated as a **cache**, not canonical memory. "Compaction" should be implemented as **cache eviction with pointers**, not narrative consolidation.+}

### 1.4 Thesis and contributions

{+**TRACE** operationalizes this thesis by combining:+}

### 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.+}

### 2. Background & Related Work

[-This section surveys memory architectures and context-management approaches most relevant to persistent agents, organizing them around a shared question: *What is the context window, and what is "memory" relative to it?*-]

### 2. Background & Related Work

{+We organize related work around a shared question: *What is the context window relative to memory, and who manages the boundary?*+}

### 2.1 OS-inspired paging and "virtual context" (MemGPT / Letta)

### 2.1 [-MemGPT-] {+OS-inspired paging and "virtual context" (MemGPT+} / [-Letta: virtual context and OS-inspired paging-] {+Letta)+}

### 2.1 MemGPT / Letta: virtual context and OS-inspired paging

[-MemGPT proposes "virtual context management" inspired by operating systems: the context window is analogous to RAM, while external stores provide disk-like tiers. The agent (an LLM) manages paging between tiers using tool calls, enabling operation beyond the base context limit. ([arxiv.org](https://arxiv.org/abs/2310.08560))-]

### 2.1 MemGPT / Letta: virtual context and OS-inspired paging

[-A key pragmatic evolution is the consolidation of the MemGPT framework under the Letta project; Letta clarifies that "MemGPT" should refer to the design pattern (LLM-managed self-editing memory tools), while Letta refers to the production framework. ([letta.com](https://www.letta.com/blog/memgpt-and-letta))-]

### 2.1 MemGPT / Letta: virtual context and OS-inspired paging

[-**Relevance:** MemGPT’s cache/storage framing is aligned with our thesis. However, its default mode places memory management *inside* the reasoning loop: the same LLM must decide what to page, what to store, and how to compress, competing for cognitive bandwidth with task reasoning. We treat this as an important trade-off rather than a universal optimum.-]

### 2.2 A-MEM: Zettelkasten-inspired agentic memory networks

[-### 2.2 A-MEM: Zettelkasten-inspired agentic memory networks-]

### 2.2 A-MEM: Zettelkasten-inspired agentic memory networks

[-A-MEM introduces a Zettelkasten-inspired memory system where each memory becomes a "note" with structured attributes (context description, keywords, tags), and the system builds an evolving network through linking and memory evolution (new memories can trigger updates to old representations). ([arxiv.org](https://arxiv.org/abs/2502.12110))-]

### 2.2 A-MEM: Zettelkasten-inspired agentic memory networks

[-**Relevance:** A-MEM supplies mechanisms for Layer 3 ("sleep consolidation"): link generation, evolving representations, and multi-path retrieval. It also highlights that memory organization is not static and that structure matters for retrieval quality.-]

### 2.3 AgeMem: unified STM/LTM via reinforcement learning over memory tools

[-### 2.3 AgeMem: unified STM/LTM via reinforcement learning over memory tools-]

### 2.3 AgeMem: unified STM/LTM via reinforcement learning over memory tools

[-AgeMem (Agentic Memory) proposes unifying short-term and long-term memory management as tool-based actions within the agent policy, trained via reinforcement learning. The agent chooses actions such as store, retrieve, update, summarize, discard, and coordinates STM/LTM under task pressure. ([arxiv.org](https://arxiv.org/abs/2601.01885))-]

### 2.3 AgeMem: unified STM/LTM via reinforcement learning over memory tools

[-**Relevance:** AgeMem supports the view that memory management can be learned rather than hand-tuned. In our architecture, we treat learned policies as a natural future extension---particularly for deciding what becomes part of Task State, what gets promoted to semantic memory, and what to retrieve under tight budgets.-]

### 2.1 OS-inspired paging and "virtual context" (MemGPT / Letta)

{+MemGPT 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.+}

### 2.2 Typed memory and governance (MaRS)

### [-2.4 MaRS: typed memory, budgets, provenance,-] {+2.2 Typed memory+} and [-principled forgetting-] {+governance (MaRS)+}

### 2.4 MaRS: typed memory, budgets, provenance, and principled forgetting

[-MaRS (Memory-Aware Retention Schema) introduces a privacy-aware cognitive memory architecture and benchmark, with typed memory nodes and multiple forgetting policies, including hybrids that balance coherence, task completion, social recall, privacy, and cost. ([arxiv.org](https://arxiv.org/abs/2512.12856))-]

### 2.4 MaRS: typed memory, budgets, provenance, and principled forgetting

[-**Relevance:** MaRS motivates two key design requirements we adopt: - **Typed memory objects** (episodic, semantic, social, task) with different retention/decay behaviors. - **Provenance and governance** as first-class metadata, enabling audits and privacy control.-]

### 2.4 MaRS: typed memory, budgets, provenance, and principled forgetting

[-Our "lossless event store" does not imply "keep everything forever." It implies: do not destroy the only high-resolution copy *as a side effect of compaction*. Governance remains necessary.-]

### 2.5 Memory-R1: RL-trained memory manager + answer agent separation

[-### 2.5 Memory-R1: RL-trained memory manager + answer agent separation-]

### 2.5 Memory-R1: RL-trained memory manager + answer agent separation

[-Memory-R1 proposes splitting responsibilities: a Memory Manager agent performs structured memory edits (ADD/UPDATE/DELETE/NOOP), and an Answer Agent distills retrieved memories before reasoning. Both are RL-trained with outcome-based rewards. ([arxiv.org](https://arxiv.org/abs/2508.19828))-]

### 2.5 Memory-R1: RL-trained memory manager + answer agent separation

[-**Relevance:** The separation-of-concerns point is critical. It suggests a middle path between MemGPT’s self-managed approach and purely heuristic system-managed retrieval: memory can be curated by a specialized manager (possibly learned), reducing cognitive bandwidth competition in the main reasoning agent.-]

### 2.6 CoALA: cognitive architectures for language agents

[-### 2.6 CoALA: cognitive architectures for language agents-]

### 2.6 CoALA: cognitive architectures for language agents

[-CoALA proposes a cognitive-architecture framework for language agents, mapping components like working memory, episodic memory, semantic memory, and decision processes into a modular architecture. ([arxiv.org](https://arxiv.org/abs/2309.02427))-]

### 2.6 CoALA: cognitive architectures for language agents

[-**Relevance:** CoALA provides a conceptual justification for our three-layer design: - **Working memory** <-> context window (cache). - **Episodic memory** <-> event store (lossless log). - **Semantic memory** <-> consolidated facts, graphs, hierarchies. - **Procedural memory** <-> tool schemas, code, skills.-]

### 2.6 CoALA: cognitive architectures for language agents

[-Layer 3 ("sleep consolidation") aligns with the cognitive idea of transforming episodic traces into semantic structures.-]

### 2.7 Context engineering: from prompt text to end-to-end context selection

[-### 2.7 Context engineering: from prompt text to end-to-end context selection-]

### 2.7 Context engineering: from prompt text to end-to-end context selection

[-Anthropic’s "Effective context engineering for AI agents" reframes the engineering task as selecting the smallest set of high-signal tokens to maximize desired behavior, emphasizing tool design, just-in-time retrieval, and compaction for long-horizon tasks. ([anthropic.com](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents))-]

### 2.7 Context engineering: from prompt text to end-to-end context selection

[-Weaviate’s "Context Engineering" article similarly emphasizes that production reliability depends on how information is selected, structured, and delivered, and enumerates failure modes as context grows: poisoning, distraction, confusion, and clash. ([weaviate.io](https://weaviate.io/blog/context-engineering))-]

### 2.7 Context engineering: from prompt text to end-to-end context selection

[-**Relevance:** Our work adopts context engineering’s systems view but diverges on compaction: we replace narrative compaction with pointer-based eviction plus retrieval over a lossless store.-]

### 2.8 Observational Memory (Mastra): stable, cacheable compressed observation logs

[-### 2.8 Observational Memory (Mastra): stable, cacheable compressed observation logs-]

### 2.8 Observational Memory (Mastra): stable, cacheable compressed observation logs

[-Mastra’s Observational Memory (OM) achieves state-of-the-art reported results on LongMemEval while maintaining a stable context window: background Observer and Reflector processes convert raw messages into dense, dated observations, replacing raw history as it grows. OM emphasizes token-triggered observation/reflection and temporal anchoring (multiple date fields). ([mastra.ai](https://mastra.ai/research/observational-memory))-]

### 2.8 Observational Memory (Mastra): stable, cacheable compressed observation logs

[-**Relevance:** OM demonstrates a key practical principle: **structured compression can outperform raw retrieval** and stable prefixes can yield large cost reductions via prompt caching. However, OM’s observations are still a *compressed representation* that may omit details. Our thesis targets the "only copy" failure by insisting on a lossless event store beneath any compressed cache representation. OM can be interpreted as a *cache format*, not a storage layer.-]

### 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."+}

### 2.3 Learned memory managers (AgeMem; Memory-R1)

{+### 2.3 Learned memory managers (AgeMem; Memory-R1)+}

### 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.+}

### 2.4 Cognitive-architecture framing (CoALA) and consolidation

{+### 2.4 Cognitive-architecture framing (CoALA) and consolidation+}

### 2.4 Cognitive-architecture framing (CoALA) and consolidation

{+CoALA 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.+}

### 2.5 Context engineering and compaction practices (Anthropic; Weaviate)

{+### 2.5 Context engineering and compaction practices (Anthropic; Weaviate)+}

### 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.+}

### 2.6 Hierarchical abstraction for retrieval (RAPTOR) and long-context limitations

### [-2.9-] {+2.6+} Hierarchical abstraction {+for retrieval+} (RAPTOR) and long-context limitations

### 2.9 Hierarchical abstraction (RAPTOR) and long-context limitations

[-RAPTOR builds a tree of recursive summaries (chunk -> embed -> cluster -> summarize), enabling retrieval across multiple abstraction levels, improving performance on long-document QA. ([arxiv.org](https://arxiv.org/abs/2401.18059))-]

### 2.9 Hierarchical abstraction (RAPTOR) and long-context limitations

[-LongMemEval formalizes long-term interactive memory evaluation across multi-session histories and multiple question types. ([arxiv.org](https://arxiv.org/abs/2410.10813))-]

### 2.9 Hierarchical abstraction (RAPTOR) and long-context limitations

[-Lost in the Middle demonstrates that long-context models often show a U-shaped performance curve over token position---beginning and end are privileged, middle is weak---motivating systems that do not assume uniform access to all context tokens. ([aclanthology.org](https://aclanthology.org/2024.tacl-1.9/))-]

### 2.9 Hierarchical abstraction (RAPTOR) and long-context limitations

[-**Relevance:** Layer 3 can use RAPTOR-style hierarchies to provide multiple granularity levels; Layer 2 must be attention-aware and budgeted; Layer 1 must ensure that the evidence is still available even if it was "lost in the middle" of a previous window.-]

### 2.10 Event sourcing and log-based state

[-### 2.10 Event sourcing and log-based state-]

### 2.10 Event sourcing and log-based state

[-Event sourcing captures all state changes as an append-only sequence of events, enabling reconstruction of past states and supporting audit and retroactive correction. ([martinfowler.com](https://www.martinfowler.com/eaaDev/EventSourcing.html))-]

### 2.10 Event sourcing and log-based state

[-**Relevance:** Event sourcing provides the storage primitive we need: a lossless, append-only event log as ground truth. Our pointer compaction is effectively "cache eviction over an event-sourced store."-]

### 2.11 Why summarization is a dangerous memory primitive

[-### 2.11 Why summarization is a dangerous memory primitive-]

### 2.11 Why summarization is a dangerous memory primitive

[-Abstractive summarization is known to produce hallucinated or unfaithful content, and factual consistency is a core research challenge. ([aclanthology.org](https://aclanthology.org/2020.acl-main.173/)) In long-context summarization, faithfulness remains difficult to evaluate and can degrade systematically. ([arxiv.org](https://arxiv.org/abs/2404.01261))-]

### 2.11 Why summarization is a dangerous memory primitive

[-**Relevance:** If we use LLM-generated text as *the* representation of past evidence, then any unfaithful claim becomes a persistent, compounding error. This is the "context poisoning" path in memory form. Pointer-based compaction reduces reliance on model-generated narratives as canonical memory.-]

### 2.6 Hierarchical abstraction for retrieval (RAPTOR) and long-context limitations

{+RAPTOR 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.+}

### 2.7 Event sourcing as a storage primitive

{+### 2.7 Event sourcing as a storage primitive+}

### 2.7 Event sourcing as a storage primitive

{+Event 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.+}

### 2.8 Companion paper on identity and priority-aware context engineering

{+### 2.8 Companion paper on identity and priority-aware context engineering+}

### 2.8 Companion paper on identity and priority-aware context engineering

{+This paper focuses on compaction, retrieval, boundedness, and planning under a lossless store. Several adjacent concerns---persona preservation, drift detection, observational memory, and deeper priority-aware scheduling---are treated in a companion technical report: Serra, O. (2026), *Agent Memory: 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.+}

### 3. Problem Analysis --- Why Narrative Compaction Fails

[-We now analyze narrative compaction as it appears in production agent systems and characterize the failure modes that motivate our replacement.-]

### 3.1 Compaction as a non-invertible transformation

### 3.1 [-Formalizing compaction-] {+Compaction+} as a {+non-invertible+} transformation

### 3.1 Formalizing compaction as a transformation

[-Let an agent interaction be an ordered sequence of events:-]

### 3.1 Formalizing compaction as a transformation

[-\[ $E = (e_1, e_2, \dots, e_T)$, \]-]

### 3.1 Formalizing compaction as a transformation

[-where events include user messages, agent responses, tool calls, tool results, and derived state updates. The context window can only hold a bounded subset of these events (plus system prompts and retrieved context). When the window approaches its limit, a system triggers **compaction**, producing a compressed representation $c$ that replaces some prefix of $E$ in the next window.-]

### 3.1 Formalizing compaction as a transformation

[-Narrative compaction implements an approximate map:-]

### 3.1 Formalizing compaction as a transformation

[-\[ $f: (e_1, \dots, e_k) \mapsto s$, \]-]

### 3.1 Formalizing compaction as a transformation

[-where $s$ is a short textual summary, and then continues with $(s, e_{k+1}, \dots, e_T)$ as the new "history."-]

### 3.1 Formalizing compaction as a transformation

[-The problem is that $f$ is not invertible. Even if $s$ is excellent, the mapping discards information that may later be required. Worse, the system typically discards the original $e_1, \dots, e_k$ from the model’s accessible working set and often does not guarantee they are available for retrieval.-]

### 3.2 The "only copy" problem

[-### 3.2 The "only copy" problem-]

### 3.2 The "only copy" problem

[-In many deployments, the only representation of high-resolution evidence is the raw transcript in the context window. After compaction, the raw transcript is gone; only the summary remains.-]

### 3.2 The "only copy" problem

[-This is a distinct failure mode from traditional summarization tasks. In document summarization, the source document remains available to humans (and often to downstream systems). In agent compaction, the summary often becomes the only cognitively accessible version of the source for future reasoning. If the summary omitted a stack trace line, a file path, a parameter value, or a "why," the agent cannot recover it without an explicit retrieval mechanism.-]

### 3.2 The "only copy" problem

[-This is why we call the failure **catastrophic**: a single omission can irreparably sever the causal chain needed to finish the task.-]

### 3.3 Tool result bloat as the primary trigger

[-### 3.3 Tool result bloat as the primary trigger-]

### 3.3 Tool result bloat as the primary trigger

[-The compaction literature often frames the pressure as "long conversations." In production tool-using agents, the pressure is frequently **evidence volume**.-]

### 3.3 Tool result bloat as the primary trigger

[-Tool results exhibit characteristics that are uniquely hostile to context windows:-]

### 3.3 Tool result bloat as the primary trigger

[-- **High entropy**: logs, JSON, traces. - **Redundancy**: repeated file listings, repeated queries. - **Long tails**: one relevant line embedded in thousands. - **Position volatility**: key lines appear early in the session and become "lost in the middle" as more evidence arrives. ([aclanthology.org](https://aclanthology.org/2024.tacl-1.9/))-]

### 3.3 Tool result bloat as the primary trigger

[-Compaction is therefore commonly triggered not by user-agent dialogue but by tool outputs---exactly the content where fidelity matters most.-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-### 3.4 Information loss taxonomy (what gets lost and why it matters)-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-Narrative compaction fails in predictable, recurring ways. We categorize the losses that matter operationally:-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-1. **Identifiers and precise strings** - commit hashes, branch names, ticket IDs - exact error messages, stack-trace lines - command invocations, flags, env vars-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-2. **Causal chains** - what was tried, in what order, and what happened - why a choice was made (rationale), not merely what was chosen-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-3. **Negative knowledge** - "we already tried X; it did not work" - critical in debugging and planning-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-4. **Tool-grounded evidence** - the single line in a log that proves a hypothesis - the exact row in a query result that triggers a constraint-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-5. **Temporal anchors** - "yesterday we deployed," "after the restart," "before the migration" - needed for reasoning over state changes-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-6. **Open loops** - unresolved questions, pending experiments, TODOs - compaction often preserves goals but drops the "next concrete step"-]

### 3.4 Information loss taxonomy (what gets lost and why it matters)

[-Narrative summaries tend to preserve the *shape* of the task but not the *substance* of the evidence.-]

### 3.5 Hallucination and poisoning risk in LLM-generated memory

[-### 3.5 Hallucination and poisoning risk in LLM-generated memory-]

### 3.5 Hallucination and poisoning risk in LLM-generated memory

[-Even if a summary is intended to be faithful, abstractive summarization is prone to hallucinations and factual inconsistency. ([aclanthology.org](https://aclanthology.org/2020.acl-main.173/)) When summaries become persistent memory, unfaithful claims are not merely incorrect---they become self-reinforcing. Future turns treat the summary as ground truth; retrieved "memories" can be written back; contradictions accumulate ("context clash"). ([weaviate.io](https://weaviate.io/blog/context-engineering))-]

### 3.5 Hallucination and poisoning risk in LLM-generated memory

[-This is a qualitatively different risk from occasional generation hallucination: it is **persistent hallucination**, embedded into the agent’s long-term working state.-]

### 3.6 Compaction under degraded conditions: the worst time to compress

[-### 3.6 Compaction under degraded conditions: the worst time to compress-]

### 3.6 Compaction under degraded conditions: the worst time to compress

[-Compaction typically occurs when:-]

### 3.6 Compaction under degraded conditions: the worst time to compress

[-- the context window is saturated, - the agent is already experiencing context distraction/confusion, ([weaviate.io](https://weaviate.io/blog/context-engineering)) - the relevant information may be in the middle of the window, ([aclanthology.org](https://aclanthology.org/2024.tacl-1.9/)) - tool outputs are large and noisy.-]

### 3.6 Compaction under degraded conditions: the worst time to compress

[-Thus compaction is a "panic flush" at the worst possible time, asking the model to perform a delicate selection/compression task under maximum attention scarcity. ([anthropic.com](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents))-]

### 3.6 Compaction under degraded conditions: the worst time to compress

[-**Conclusion:** Narrative compaction is an unreliable, irreversible transformation that destroys the only accessible copy of the evidence needed for long-horizon correctness. The correct engineering move is to decouple storage from cache.-]

### 3.1 Compaction as a non-invertible transformation

{+Let an interaction produce an event sequence $E = (e_1,\dots,e_T)$. Compaction typically computes a summary $s = f(e_1,\dots,e_k)$ and continues with $(s,e_{k+1},\dots)$. This map $f$ is not invertible. In document summarization, the source text remains available; in agent compaction, the summary often becomes the only accessible representation for future reasoning.+}

### 3.2 The loss taxonomy that matters in production

{+### 3.2 The loss taxonomy that matters in production+}

### 3.2 The loss taxonomy that matters in production

{+Narrative compaction predictably loses the kinds of information that determine whether agents can actually complete tasks:+}

### 3.2 The loss taxonomy that matters in production

{+- **Precise strings** (hashes, IDs, file paths, exact error lines). - **Causal chains** (what was tried, in what order, why). - **Negative knowledge** ("we tried X; it failed"). - **Tool evidence** (the one decisive line in a long log). - **Temporal anchors** (before/after deployments or migrations). - **Open loops** (unresolved questions and next concrete steps).+}

### 3.2 The loss taxonomy that matters in production

{+A summary may preserve the *shape* of the task while destroying the operational substance.+}

### 3.3 Compaction happens at the worst time

{+### 3.3 Compaction happens at the worst time+}

### 3.3 Compaction happens at the worst time

{+Compaction 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.+}

### 3.4 Diagram: narrative compaction vs. pointer compaction

{+### 3.4 Diagram: narrative compaction vs. pointer compaction+}

### 3.4 Diagram: narrative compaction vs. pointer compaction

{+The central difference is what becomes canonical. Narrative compaction replaces the past; pointer compaction *indexes* the past.+}

### 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 | +-------------------------------+--------------------------------------------------+ ```+}

### 4. Proposed Architecture --- Event-Sourced Hierarchical Memory

[-## 4. Proposed Architecture --- Event-Sourced Hierarchical Memory-]

### 4. TRACE Architecture --- Cache Eviction over Lossless Storage

{+## 4. TRACE Architecture --- Cache Eviction over Lossless Storage+}

### 4.1 Design principles

[-We propose **Event-Sourced Hierarchical Memory (ESHM)**, a production-oriented architecture grounded in five principles:-]

### 4.1 Design principles

[-**P1. Event sourcing as ground truth.** All interaction events (including tool inputs/outputs) are persisted in an append-only event log. ([martinfowler.com](https://www.martinfowler.com/eaaDev/EventSourcing.html))-]

### 4.1 Design principles

[-**P2. Cache != storage.** The context window is a cache over the event store, not the canonical record.-]

### 4.1 Design principles

[-**P3. Pointer compaction replaces narrative compaction.** Compaction becomes cache eviction: remove evicted events from the cache, but keep structured pointers that allow on-demand retrieval.-]

### 4.1 Design principles

[-**P4. Continuous indexing, not panic indexing.** Events are indexed (FTS + embeddings + metadata) as they arrive, so retrieval works even if eviction happens suddenly.-]

### 4.1 Design principles

[-**P5. Typed memory and provenance.** Derived memory objects (task, semantic facts, decisions, social relations) are typed and reference the source events that justify them, consistent with provenance-driven governance. ([arxiv.org](https://arxiv.org/abs/2512.12856))-]

### 4.2 Three-layer architecture overview

[-### 4.2 Three-layer architecture overview-]

### 4.2 Three-layer architecture overview

[-We decompose memory across three time scales:-]

### 4.2 Three-layer architecture overview

[-1. **Layer 1 --- Continuous Event Ingestion & Indexing (seconds):** Persist every event and index it immediately.-]

### 4.2 Three-layer architecture overview

[-2. **Layer 2 --- Per-Turn Context-Primed Retrieval with Task State (milliseconds):** Before each agent response, retrieve a compact set of relevant evidence and state from storage into the context cache.-]

### 4.2 Three-layer architecture overview

[-3. **Layer 3 --- Sleep Consolidation & Principled Forgetting (minutes--hours):** Periodically derive higher-level structures (typed memories, links, hierarchies) and update retention/forgetting policies.-]

### 4.2 Three-layer architecture overview

[-This decomposition is consistent with cognitive-architecture perspectives that separate working memory, episodic memory, and semantic memory, and emphasize consolidation. ([arxiv.org](https://arxiv.org/abs/2309.02427))-]

### 4.1 Design principles

{+TRACE is guided by six principles:+}

### 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 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.+}

### 4.2 System architecture diagram (Ingest -> Retrieve -> Consolidate)

{+### 4.2 System architecture diagram (Ingest -> Retrieve -> Consolidate)+}

### 4.2 System architecture diagram (Ingest -> Retrieve -> Consolidate)

{+```text +-----------------------------------+ | TRACE | | Lossless Memory + Cache Control | +-----------------------------------++}

### 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 | +---------------------------+ ```+}

### 4.3 Data model: events, artifacts, task state, pointer manifests

### 4.3 Data model: events, artifacts, [-and derived memory-] {+task state, pointer manifests+}

### 4.3.1 Event log

[-#### 4.3.1 Event log-]

### 4.3.1 Event log

[-Each event is immutable and append-only:-]

### 4.3.1 Event log

[-- `event_id`: UUID / ULID - `timestamp` - `session_id`, `turn_id` - `kind`: `{user_message, agent_message, tool_call, tool_result, system_note, decision, task_update, ...}` - `content`: text payload (or pointer to artifact) - `metadata`: tool name, args hash, token estimate, sensitivity label, provenance - `embedding`: vector for semantic search (optional for some kinds)-]

### 4.3.2 Artifacts for large tool results

[-#### 4.3.2 Artifacts for large tool results-]

### 4.3.2 Artifacts for large tool results

[-Large tool results should be stored as **artifacts** and referenced by events:-]

### 4.3.2 Artifacts for large tool results

[-- `artifact_id` - `content_bytes` (compressed if needed) - `content_text` (optional) - `sha256` - `mime_type` - `source_tool` - `created_at`-]

### 4.3.2 Artifacts for large tool results

[-This isolates large payloads from the context cache while preserving lossless storage.-]

### 4.3.3 Derived, typed memory objects

[-#### 4.3.3 Derived, typed memory objects-]

### 4.3.3 Derived, typed memory objects

[-Derived objects represent *views* over the event log:-]

### 4.3.3 Derived, typed memory objects

[-- **Task Memory:** goals, plans, open loops, next actions - **Decision Records:** decision + rationale + alternatives + supporting events - **Semantic Facts:** stable facts extracted from episodes - **Social/Preference Memory:** user preferences, relationships - **Procedural Memory:** tool schemas, workflows, scripts-]

### 4.3.3 Derived, typed memory objects

[-Critically, each derived object stores **provenance pointers** to the event IDs that justify it, enabling audits and reducing hallucination risk.-]

### 4.4 The Task State object (the minimal persistent "working set")

[-### 4.4 The Task State object (the minimal persistent "working set")-]

### 4.4 The Task State object (the minimal persistent "working set")

[-At the center of Layer 2 is an explicit **Task State** object: a structured representation of what the agent is doing *now*, designed to be small enough to remain in the context cache across turns and compactions.-]

### 4.4 The Task State object (the minimal persistent "working set")

[-A representative schema:-]

### 4.4 The Task State object (the minimal persistent "working set")

[-```json { "task_id": "ulid", "title": "Fix webhook retry silent failure", "status": "active", "goals": [ {"id": "g1", "text": "Identify why retries fail silently", "priority": "high"} ], "constraints": [ {"id": "c1", "text": "Do not change public API", "source_event": "evt_..."} ], "open_questions": [ {"id": "q1", "text": "Is the retry handler swallowing exceptions?", "last_touched": "2026-02-14T...Z"} ], "next_actions": [ {"id": "a1", "text": "Add instrumentation around retry wrapper", "blocking": false} ], "key_artifacts": [ {"artifact_id": "art_...", "label": "Latest stack trace", "event_id": "evt_..."} ], "key_events": [ {"event_id": "evt_...", "label": "Decision: use exponential backoff", "weight": 0.9} ], "context_hints": { "entities": ["webhook", "retry", "silence", "exception"], "paths": ["src/webhooks/retry.ts"], "queries": ["grep -R \"catch\" src/webhooks"] }, "updated_at": "2026-02-15T...Z" } ```-]

### 4.4 The Task State object (the minimal persistent "working set")

[-**Key property:** Task State is **not** the only copy of details. It is an index-card view into the lossless store. If it omits a detail, the detail still exists in the event log and can be retrieved by pointer.-]

### 4.3 Data model: events, artifacts, task state, pointer manifests

{+TRACE uses four first-class objects:+}

### 4.3 Data model: events, artifacts, task state, pointer manifests

{+1. **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.+}

### 4.3 Data model: events, artifacts, task state, pointer manifests

{+A critical rule: **Task State and derived summaries are never the only copy.** They are indexes over the lossless event store.+}

### 4.4 Layer 1 --- Continuous event ingestion and indexing

### [-4.5-] {+4.4+} Layer 1 --- Continuous [-Event Ingestion & Indexing-] {+event ingestion and indexing+}

### 4.5 Layer 1 --- Continuous Event Ingestion & Indexing

[-Layer 1 ensures that every cognitively relevant event is persisted and searchable *before* it can be evicted from context.-]

### 4.5 Layer 1 --- Continuous Event Ingestion & Indexing

[-**Algorithmic goal:** turn the agent’s live trace into a lossless, queryable event stream with minimal latency.-]

### Algorithm 1: Continuous ingestion and indexing

[-#### Algorithm 1: Continuous ingestion and indexing-]

### Algorithm 1: Continuous ingestion and indexing

[-```text Algorithm 1: INGEST_AND_INDEX(event) Input: event = {kind, content, metadata, timestamp, session_id, turn_id}-]

### Algorithm 1: Continuous ingestion and indexing

[-1: event_id <- new_ulid() 2: if event.kind == tool_result and size(event.content) > ARTIFACT_THRESHOLD then 3: artifact_id <- store_artifact(event.content, metadata) 4: event.content <- pointer("artifact", artifact_id) 5: end if 6: persist_event(event_id, event) 7: if should_embed(event.kind) then 8: emb <- embed(event.content or artifact_excerpt(event.content)) 9: persist_embedding(event_id, emb) 10: end if 11: update_fts_index(event_id, extract_text(event)) 12: update_metadata_indexes(event_id, metadata) 13: return event_id ```-]

### Algorithm 1: Continuous ingestion and indexing

[-**Notes:** - Embedding tool results can be expensive and noisy. We often embed an excerpt plus structured fields (tool name, file paths, error lines). - Indexing must be robust to bursts. Batching is acceptable as long as indexing completes before eviction.-]

### Algorithm 1: Continuous ingestion and indexing

[-This continuous approach avoids "panic flush" behavior: compaction no longer needs to summarize because the system already stored and indexed the raw evidence.-]

### 4.4 Layer 1 --- Continuous event ingestion and indexing

{+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.+}

### 4.4 Layer 1 --- Continuous event ingestion and indexing

{+(See **Annex A.1** for the ingestion/indexing algorithm.)+}

### 4.5 Layer 2 --- Per-turn retrieval and context assembly

### [-4.6-] {+4.5+} Layer 2 --- Per-turn [-context-primed-] retrieval [-with task state-] {+and context assembly+}

### 4.6 Layer 2 --- Per-turn context-primed retrieval with task state

[-Layer 2 constructs the context cache for each turn:-]

### 4.6 Layer 2 --- Per-turn context-primed retrieval with task state

[-- stable system prompt / policies - current Task State object - last $k$ conversational turns (hot tail) - retrieved evidence (memory pack) selected to maximize relevance under a strict token budget-]

### 4.6 Layer 2 --- Per-turn context-primed retrieval with task state

[-This aligns with the broader "context engineering" view that reliability is primarily a function of what enters the model at each step. ([anthropic.com](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents))-]

### Retrieval candidate sources

[-#### Retrieval candidate sources-]

### Retrieval candidate sources

[-We recommend combining:-]

### Retrieval candidate sources

[-1. **Vector similarity over events and derived objects** 2. **FTS/BM25 keyword search** 3. **Pointer expansion from Task State** - key events, artifacts, entities, paths 4. **Typed-memory "pinned" objects** - active task records, recent decisions, user preferences-]

### Algorithm 2: Per-turn retrieval and packing

[-#### Algorithm 2: Per-turn retrieval and packing-]

### Algorithm 2: Per-turn retrieval and packing

[-```text Algorithm 2: BUILD_CONTEXT_PACK(user_msg, task_state, recent_tail, budgets) Input: user_msg: latest user message task_state: current TaskState object recent_tail: last k turns kept in cache budgets: {tokens_system, tokens_taskstate, tokens_tail, tokens_retrieval}-]

### Algorithm 2: Per-turn retrieval and packing

[-Output: context_pack: ordered list of context blocks-]

### Algorithm 2: Per-turn retrieval and packing

[-1: q <- build_query(user_msg, task_state, recent_tail) 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_typed_memories(task_state.task_id, user_profile_id)-]

### Algorithm 2: Per-turn retrieval and packing

[-6: C <- dedupe(C_vec U C_fts U C_ptr U C_pin)-]

### Algorithm 2: Per-turn retrieval and packing

[-7: for each item in C do 8: item.score <- score_item(item, q, task_state, recency_weight, type_weight, access_frequency_weight, sensitivity_penalty) 9: end for-]

### Algorithm 2: Per-turn retrieval and packing

[-10: S <- mmr_select(C, k = K_max, lambda = 0.7) // diversity against near-duplicates 11: R <- pack_under_budget(S, budgets.tokens_retrieval, per_type_quotas, prefer_low_sensitivity = true)-]

### Algorithm 2: Per-turn retrieval and packing

[-12: context_pack <- [ SYSTEM_BLOCK, TASK_STATE_BLOCK(task_state), RETRIEVED_MEMORY_BLOCK(R), RECENT_TAIL_BLOCK(recent_tail), USER_MESSAGE_BLOCK(user_msg) ] 13: log_retrieval(task_state.task_id, R) 14: return context_pack ```-]

### Algorithm 2: Per-turn retrieval and packing

[-This differs from MemGPT in an important way: the *system* constructs the retrieval pack by default, rather than requiring the agent to spend turns calling search tools and managing paging. MemGPT’s pattern is powerful, but it creates cognitive bandwidth competition: memory management tokens are not task reasoning tokens. ([arxiv.org](https://arxiv.org/abs/2310.08560))-]

### Algorithm 2: Per-turn retrieval and packing

[-Our recommended compromise (for a single persistent production agent) is:-]

### Algorithm 2: Per-turn retrieval and packing

[-- **System-managed default retrieval** (cheap, deterministic, always-on) - **Agent-initiated deepening tools** (optional; only when needed) - **Layer 3 curation** (can be learned or heuristic)-]

### 4.7 Layer 3 --- Sleep consolidation: hierarchical abstraction, linking, and forgetting

[-### 4.7 Layer 3 --- Sleep consolidation: hierarchical abstraction, linking, and forgetting-]

### 4.7 Layer 3 --- Sleep consolidation: hierarchical abstraction, linking, and forgetting

[-Layer 3 is periodic, offline(ish) processing that transforms raw events into more useful memory structures:-]

### 4.7 Layer 3 --- Sleep consolidation: hierarchical abstraction, linking, and forgetting

[-1. **Episode segmentation:** group events into tasks/threads. 2. **Typed extraction:** create decision records, task updates, semantic facts. 3. **Linking:** connect related memories, A-MEM-style. ([arxiv.org](https://arxiv.org/abs/2502.12110)) 4. **Hierarchical abstraction:** build RAPTOR-like trees and summaries. ([arxiv.org](https://arxiv.org/abs/2401.18059)) 5. **Principled forgetting:** update retention and retrieval priority using MaRS-style policies and budgets. ([arxiv.org](https://arxiv.org/abs/2512.12856))-]

### 4.7 Layer 3 --- Sleep consolidation: hierarchical abstraction, linking, and forgetting

[-Importantly, "forgetting" does **not** mean deleting the only copy. It means demoting items in the retrieval surface, pruning derived summaries, and (only when policy requires) deleting or redacting sensitive content.-]

### Algorithm 3: Sleep consolidation pipeline

[-#### Algorithm 3: Sleep consolidation pipeline-]

### Algorithm 3: Sleep consolidation pipeline

[-```text Algorithm 3: SLEEP_CONSOLIDATE(time_range) Input: time_range = [t_start, t_end]-]

### Algorithm 3: Sleep consolidation pipeline

[-1: E <- load_events(time_range) 2: episodes <- segment_into_episodes(E) // by task_id, topic shift, inactivity gaps 3: for each ep in episodes do 4: decisions <- extract_decisions(ep) // structured, with provenance pointers 5: facts <- extract_semantic_facts(ep) // typed, with confidence & provenance 6: tasks <- update_task_records(ep) // open/closed loops, milestones 7: links <- generate_links(decisions, facts, tasks, memory_graph) // A-MEM style 8: update_memory_graph(links) 9: end for-]

### Algorithm 3: Sleep consolidation pipeline

[-10: raptor_tree <- update_hierarchical_summaries(episodes, existing_tree) 11: apply_forgetting_policy(memory_items, budgets_by_type, sensitivity_rules, access_stats)-]

### Algorithm 3: Sleep consolidation pipeline

[-12: persist_consolidation_outputs(decisions, facts, tasks, raptor_tree, access_stats) ```-]

### Algorithm 3: Sleep consolidation pipeline

[-**Where LLMs belong:** LLM calls can be used in Layer 3 for extraction and summarization because (i) they are offline, (ii) they can be bounded and audited, and (iii) their outputs can be traced back to provenance events. This is safer than using LLMs to produce the *only* representation of history during emergency compaction.-]

### 4.8 Pointer-based compaction: compaction as cache eviction

[-### 4.8 Pointer-based compaction: compaction as cache eviction-]

### 4.8 Pointer-based compaction: compaction as cache eviction

[-We now define the core mechanism: **pointer compaction**.-]

### 4.8 Pointer-based compaction: compaction as cache eviction

[-**Goal:** reduce in-context token load while preserving the ability to retrieve any evicted detail.-]

### 4.8 Pointer-based compaction: compaction as cache eviction

[-**Mechanism:** remove evictable blocks (typically older tail turns and bulky tool results) from the context cache, while inserting a compact, structured record that points to: - the evicted event span(s), - key anchor events (decisions, errors, constraints) by ID, - referenced artifacts, - the current Task State (or its store reference).-]

### Algorithm 4: Pointer-based compaction

[-#### Algorithm 4: Pointer-based compaction-]

### Algorithm 4: Pointer-based compaction

[-```text Algorithm 4: POINTER_COMPACT(context_cache, task_state, token_limit, headroom) Input: context_cache: ordered messages currently in the context window task_state: current TaskState object token_limit: maximum tokens allowed headroom: tokens reserved for next turns + tool calls-]

### Algorithm 4: Pointer-based compaction

[-Output: new_context_cache: cache after eviction + pointer manifest insertion-]

### Algorithm 4: Pointer-based compaction

[-1: while estimated_tokens(context_cache) > token_limit - headroom do 2: victim <- select_eviction_candidate(context_cache) // Prefer: oldest tool_results > oldest tool_calls > oldest dialogue turns // Avoid: system blocks, task_state block, last k turns 3: span <- victim.event_span 4: ensure_persisted_and_indexed(span) // Layer 1 guarantee; otherwise flush 5: remove_span_from_cache(context_cache, span)-]

### Algorithm 4: Pointer-based compaction

[-6: manifest <- build_pointer_manifest( evicted_span = span.event_ids, key_events = select_anchor_events(span, task_state), artifacts = extract_artifact_refs(span), task_state_ref = task_state.task_id, retrieval_hints = derive_hints(span, task_state) )-]

### Algorithm 4: Pointer-based compaction

[-7: insert_manifest_marker(context_cache, manifest, position = earliest_removed_position) 8: end while 9: return context_cache ```-]

### Algorithm 4: Pointer-based compaction

[-The pointer manifest is deterministic, provenance-preserving, and does **not** require a narrative summary. It is therefore resistant to hallucination and omission in the way narrative compaction is not.-]

### 4.9 Relationship to existing approaches

[-### 4.9 Relationship to existing approaches-]

### 4.9 Relationship to existing approaches

[-- **Versus MemGPT/Letta:** We adopt the cache/storage framing but default to system-managed paging; we do not require the agent to spend turns managing memory. ([arxiv.org](https://arxiv.org/abs/2310.08560)) - **Versus Observational Memory:** OM compresses history into dense observations for a stable prompt; we treat such representations as cache formats derived from the lossless store. ([mastra.ai](https://mastra.ai/research/observational-memory)) - **Versus narrative compaction:** We do not replace evicted state with a lossy textual summary; we replace it with pointers and a minimal Task State index-card.-]

### 4.5 Layer 2 --- Per-turn retrieval and context assembly

{+On every turn, TRACE builds a bounded **context pack** consisting of:+}

### 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.+}

### 4.5 Layer 2 --- Per-turn retrieval and context assembly

{+The 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.+}

### 4.5 Layer 2 --- Per-turn retrieval and context assembly

{+(See **Annex A.2** for retrieval candidate generation, reranking, and packing.)+}

### 5. Implementation in OpenClaw

[-## 5. Implementation in OpenClaw-]

### 5. Implementation in OpenClaw

[-This section grounds the proposal in a production agent platform and specifies a minimal viable path.-]

### 5.1 System context: OpenClaw’s current compaction and memory

[-### 5.1 System context: OpenClaw’s current compaction and memory-]

### 5.1 System context: OpenClaw’s current compaction and memory

[-OpenClaw is a persistent agent platform with:-]

### 5.1 System context: OpenClaw’s current compaction and memory

[-- a ~200K-token context window - multi-channel messaging interfaces (e.g., WhatsApp, Telegram, webchat) - heavy tool usage (code, file system, web, APIs) - a current compaction mechanism that summarizes a full conversation into ~6K characters and restarts with the summary-]

### 5.1 System context: OpenClaw’s current compaction and memory

[-Long-term memory exists on disk (notes, logs, project files), but the agent typically accesses it only if it *remembers to*. There is no mandatory per-turn retrieval layer, so compaction tends to erase the cues that would trigger the agent to look up the missing information later.-]

### 5.2 The band-aid: aggregate tool-result truncation

[-### 5.2 The band-aid: aggregate tool-result truncation-]

### 5.2 The band-aid: aggregate tool-result truncation

[-A practical immediate mitigation is to cap tool-result bloat directly. OpenClaw has implemented an "aggregate truncation" policy: cap the total number of tool-result characters included in the context to a fixed fraction (e.g., 50%), truncating oldest tool results first. This reduces overflow events but remains lossy and does not solve the "only copy" problem unless tool results are persisted elsewhere.-]

### 5.2 The band-aid: aggregate tool-result truncation

[-We formalize this mechanism as a baseline:-]

### Algorithm 5: Aggregate tool-result truncation (band-aid)

[-#### Algorithm 5: Aggregate tool-result truncation (band-aid)-]

### Algorithm 5: Aggregate tool-result truncation (band-aid)

[-```text Algorithm 5: TRUNCATE_TOOL_RESULTS(messages, max_tool_chars) Input: messages: ordered context messages including tool results max_tool_chars: global budget for tool-result characters-]

### Algorithm 5: Aggregate tool-result truncation (band-aid)

[-1: tool_msgs <- [m in messages where m.role == "tool" or m.kind == tool_result] 2: total <- sum(char_len(m.content) for m in tool_msgs)-]

### Algorithm 5: Aggregate tool-result truncation (band-aid)

[-3: if total <= max_tool_chars then 4: return messages 5: end if-]

### Algorithm 5: Aggregate tool-result truncation (band-aid)

[-6: // truncate oldest-first 7: for m in tool_msgs ordered by m.timestamp ascending do 8: if total <= max_tool_chars then break end if 9: removable <- min(char_len(m.content), total - max_tool_chars) 10: m.content <- truncate_tail(m.content, char_len(m.content) - removable) 11: total <- total - removable 12: end for-]

### Algorithm 5: Aggregate tool-result truncation (band-aid)

[-13: return messages ```-]

### Algorithm 5: Aggregate tool-result truncation (band-aid)

[-**Limitation:** Without a lossless artifact store, truncation is still destructive. In ESHM, truncation is replaced by artifactization + pointers (lossless store, cache eviction).-]

### 5.3 Migration path: narrative compaction -> pointer compaction

[-### 5.3 Migration path: narrative compaction -> pointer compaction-]

### 5.3 Migration path: narrative compaction -> pointer compaction

[-We recommend a staged migration that yields value quickly:-]

### 5.3 Migration path: narrative compaction -> pointer compaction

[-**Phase 0 (already):** aggregate truncation to reduce catastrophic blow-ups.-]

### 5.3 Migration path: narrative compaction -> pointer compaction

[-**Phase 1 (Layer 1 minimal):** implement event log + artifact store + immediate indexing. - Every message and tool result is persisted. - Tool results above a size threshold are stored as artifacts and referenced.-]

### 5.3 Migration path: narrative compaction -> pointer compaction

[-**Phase 2 (pointer compaction):** replace narrative compaction with pointer manifests + Task State. - Context overflow triggers eviction + pointer insertion, not summarization. - Task State is always preserved across windows.-]

### 5.3 Migration path: narrative compaction -> pointer compaction

[-**Phase 3 (Layer 2 retrieval):** add mandatory per-turn retrieval. - Before responding, retrieve relevant events/objects and inject a memory pack.-]

### 5.3 Migration path: narrative compaction -> pointer compaction

[-**Phase 4 (Layer 3 consolidation):** build derived typed memory and hierarchies. - Add A-MEM style linking and RAPTOR summarization. - Add MaRS-style forgetting and privacy governance.-]

### 5.3 Migration path: narrative compaction -> pointer compaction

[-This path avoids a risky "big bang" and solves the catastrophe early: once events are losslessly stored and pointer compaction is used, the system no longer destroys the only copy during compaction.-]

### 5.4 SQLite schema sketch (event store + pointers)

[-### 5.4 SQLite schema sketch (event store + pointers)-]

### 5.4 SQLite schema sketch (event store + pointers)

[-A minimal schema (illustrative, not exhaustive):-]

### 5.4 SQLite schema sketch (event store + pointers)

[-```sql -- Immutable event log CREATE TABLE events ( event_id TEXT PRIMARY KEY, ts INTEGER NOT NULL, session_id TEXT NOT NULL, turn_id INTEGER, kind TEXT NOT NULL, role TEXT, content_text TEXT, artifact_id TEXT, tool_name TEXT, tool_args_json TEXT, sensitivity INTEGER DEFAULT 0, provenance TEXT );-]

### 5.4 SQLite schema sketch (event store + pointers)

[--- Artifact store for large tool outputs CREATE TABLE artifacts ( artifact_id TEXT PRIMARY KEY, ts INTEGER NOT NULL, sha256 TEXT NOT NULL, mime_type TEXT, bytes BLOB );-]

### 5.4 SQLite schema sketch (event store + pointers)

[--- Full-text search CREATE VIRTUAL TABLE events_fts USING fts5( event_id, content, tokenize='unicode61' );-]

### 5.4 SQLite schema sketch (event store + pointers)

[--- Embeddings (sqlite-vec or equivalent) CREATE TABLE event_embeddings ( event_id TEXT PRIMARY KEY, embedding BLOB );-]

### 5.4 SQLite schema sketch (event store + pointers)

[--- Pointer manifests inserted during compaction CREATE TABLE compaction_manifests ( manifest_id TEXT PRIMARY KEY, ts INTEGER NOT NULL, session_id TEXT NOT NULL, evicted_from TEXT NOT NULL, -- first event_id evicted_to TEXT NOT NULL, -- last event_id task_id TEXT NOT NULL, anchors_json TEXT NOT NULL, -- key events + labels artifacts_json TEXT NOT NULL, -- artifact refs hints_json TEXT NOT NULL );-]

### 5.4 SQLite schema sketch (event store + pointers)

[--- Task state (small, mutable, versioned) CREATE TABLE task_state_versions ( task_id TEXT NOT NULL, version_id TEXT PRIMARY KEY, ts INTEGER NOT NULL, state_json TEXT NOT NULL ); ```-]

### 5.4 SQLite schema sketch (event store + pointers)

[-This schema supports: - lossless storage, - retrieval by keywords and embeddings, - pointer compaction manifests for rehydration, - versioned Task State.-]

### 5.5 Vector indexing and continuous ingestion

[-### 5.5 Vector indexing and continuous ingestion-]

### 5.5 Vector indexing and continuous ingestion

[-OpenClaw already has components ("agent-memory-ultimate") that can support vector search and knowledge graphs. The key is wiring them into the turn loop such that indexing happens continuously (Layer 1) and retrieval happens automatically (Layer 2). With local SQLite vector indexing, per-turn retrieval latencies can remain in the tens of milliseconds, typically dominated by embedding computation if performed online.-]

### 5.6 Minimal viable implementation priorities (definitive recommendation)

[-### 5.6 Minimal viable implementation priorities (definitive recommendation)-]

### 5.6 Minimal viable implementation priorities (definitive recommendation)

[-For OpenClaw specifically (single persistent agent, production constraints), the highest ROI sequence is:-]

### 5.6 Minimal viable implementation priorities (definitive recommendation)

[-1. **Lossless event store + artifactization (must-have):** eliminate "only copy" loss. 2. **Pointer compaction (must-have):** replace narrative summaries at overflow with deterministic manifests. 3. **Per-turn retrieval with Task State (high):** restore continuity and relevance automatically. 4. **Typed derived memory (medium):** decisions/tasks/preferences become structured objects with provenance. 5. **Sleep consolidation (medium):** A-MEM links + RAPTOR hierarchies + forgetting policies. 6. **Learned memory policies (future):** AgeMem/Memory-R1 style RL for memory actions when data/infra permit. ([arxiv.org](https://arxiv.org/abs/2601.01885))-]

### 5.6 Minimal viable implementation priorities (definitive recommendation)

[-On the self-managed vs system-managed question: adopt a **hybrid**: - system-managed retrieval by default (low cognitive overhead), - optional agent-driven deep retrieval tools (for exploration), - eventually a specialized memory manager (learned or heuristic) if needed.-]

### 5. Task-Aware Retrieval Priority (Task-Conditioned Scoring)

{+## 5. Task-Aware Retrieval Priority (Task-Conditioned Scoring)+}

### 5. Task-Aware Retrieval Priority (Task-Conditioned Scoring)

{+Not all cached context is equally important; more importantly, **importance is not static**. Retrieval should be conditioned on (i) the active task, (ii) the premises under which a memory was created, and (iii) what the agent expects to need later.+}

### 5.1 Why "static relevance" fails

{+### 5.1 Why "static relevance" fails+}

### 5.1 Why "static relevance" fails

{+A purely similarity-driven retriever (vector/FTS) tends to over-inject:+}

### 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.+}

### 5.1 Why "static relevance" fails

{+Conversely, it under-injects:+}

### 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.+}

### 5.2 Conditioning on task, premises, and expected future needs

{+### 5.2 Conditioning on task, premises, and expected future needs+}

### 5.2 Conditioning on task, premises, and expected future needs

{+TRACE introduces a **task-conditioned scoring function** that modulates a base retrieval score.+}

### 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.+}

### 5.2 Conditioning on task, premises, and expected future needs

{+A practical implementation uses metadata attached to events and derived objects:+}

### 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").+}

### 5.3 Examples (selective attention in agents)

{+### 5.3 Examples (selective attention in agents)+}

### 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 the earlier version?").+}

### 5.4 Outcome: retrieval that matches *need*, not just similarity

{+### 5.4 Outcome: retrieval that matches *need*, not just similarity+}

### 5.4 Outcome: retrieval that matches *need*, not just similarity

{+Task-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.+}

### 5.4 Outcome: retrieval that matches *need*, not just similarity

{+(See **Annex A.3** for a concrete task-conditioned scoring formulation and supersession handling.)+}

### 6. Evaluation Framework (Proposed)

[-## 6. Evaluation Framework (Proposed)-]

### 6. Evaluation Framework (Proposed)

[-We do not report experimental results here. Instead, we specify an evaluation plan designed to measure what narrative compaction breaks and what pointer compaction restores.-]

### 6.1 Core metrics

[-### 6.1 Core metrics-]

### 6.1 Core metrics

[-1. **Information preservation (losslessness at the system level)** - Can the system recover exact strings (hashes, error lines) after multiple compactions? - Metric: exact-match accuracy on recall queries.-]

### 6.1 Core metrics

[-2. **Retrieval accuracy** - Precision@k / Recall@k for injected evidence given a labeled relevant set. - Retrieval latency distribution (p50/p95).-]

### 6.1 Core metrics

[-3. **Context utilization** - Fraction of context occupied by (i) tool results, (ii) retrieval packs, (iii) tail dialogue, (iv) Task State. - Compaction frequency per hour.-]

### 6.1 Core metrics

[-4. **Task continuity** - Number of user clarifications needed after compaction. - Rate of repeated work ("we already tried this") in debugging tasks.-]

### 6.1 Core metrics

[-5. **Hallucination/poisoning incidence** - Rate at which the agent states false "memories." - Especially important when summaries are used; pointer compaction should reduce persistent hallucination risk.-]

### 6.2 Needle-in-a-haystack across forced compactions

[-### 6.2 Needle-in-a-haystack across forced compactions-]

### 6.2 Needle-in-a-haystack across forced compactions

[-We propose tests that explicitly target the catastrophe:-]

### 6.2 Needle-in-a-haystack across forced compactions

[-- Plant "needles" early: commit hashes, stack-trace lines, precise config values. - Flood the context with tool outputs (the production trigger). - Force compaction multiple times. - Ask questions requiring those needles.-]

### 6.2 Needle-in-a-haystack across forced compactions

[-Compare: - **Baseline A:** narrative compaction summaries. - **Baseline B:** truncation-only (drop history). - **Proposed:** pointer compaction + retrieval.-]

### 6.2 Needle-in-a-haystack across forced compactions

[-LongMemEval provides a general benchmark for long-term interactive memory, but we need tests that specifically model tool-result bloat and forced eviction. ([arxiv.org](https://arxiv.org/abs/2410.10813))-]

### Algorithm 6: Compaction stress test harness

[-#### Algorithm 6: Compaction stress test harness-]

### Algorithm 6: Compaction stress test harness

[-```text Algorithm 6: COMPACTION_STRESS_TEST(trace, needles, bloat_generator, policy) Input: trace: base interaction trace (messages + tool calls) needles: list of (event, query) pairs requiring exact recall bloat_generator: produces large tool results to saturate context policy: {narrative_compact, truncate, pointer_compact}-]

### Algorithm 6: Compaction stress test harness

[-1: inject_needles(trace, needles, positions = early) 2: for i = 1..N_bloat_rounds do 3: trace <- trace + bloat_generator() 4: if context_overflow(trace) then 5: trace <- apply_policy(policy, trace) 6: end if 7: end for-]

### Algorithm 6: Compaction stress test harness

[-8: score <- 0 9: for each (needle_event, query) in needles do 10: answer <- run_agent_with_policy(policy, trace, query) 11: score <- score + exact_match(answer, needle_event.ground_truth) 12: end for-]

### Algorithm 6: Compaction stress test harness

[-13: return score / |needles| ```-]

### 6.3 Ablations

[-### 6.3 Ablations-]

### 6.3 Ablations

[-To validate the decomposition, we propose ablations:-]

### 6.3 Ablations

[-- Remove Layer 1 continuous indexing (only store at compaction time). - Remove Task State (retrieval based only on last user message). - Remove typed memory (all items treated as homogeneous). - Replace pointer compaction with narrative summary (keep retrieval). - Disable artifactization (store tool outputs inline only).-]

### 6.3 Ablations

[-This will measure whether the proposed thesis components are individually necessary.-]

### 6. Pointer-Based Compaction (Compaction as Cache Eviction)

{+## 6. Pointer-Based Compaction (Compaction as Cache Eviction)+}

### 6. Pointer-Based Compaction (Compaction as Cache Eviction)

{+Pointer compaction is TRACE's replacement for narrative compaction.+}

### 6.1 What compaction does in TRACE

{+### 6.1 What compaction does in TRACE+}

### 6.1 What compaction does in TRACE

{+When the context window approaches its limit, TRACE:+}

### 6.1 What compaction does in TRACE

{+1. 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.+}

### 6.1 What compaction does in TRACE

{+The manifest is deterministic and provenance-preserving; it is not a narrative summary and does not attempt to compress evidence into a single prose paragraph.+}

### 6.2 Why this is safer than narrative summaries

{+### 6.2 Why this is safer than narrative summaries+}

### 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.+}

### 6.2 Why this is safer than narrative summaries

{+(See **Annex A.4** for eviction selection and manifest construction under hard token constraints.)+}

### 7. Discussion

[-## 7. Discussion-]

### 7.1 When is narrative compaction still appropriate?

[-### 7.1 When is narrative compaction still appropriate?-]

### 7.1 When is narrative compaction still appropriate?

[-Narrative compaction is not useless. It remains appropriate when:-]

### 7.1 When is narrative compaction still appropriate?

[-- The target audience is **human** (recaps, handoffs, summaries). - The system can tolerate loss and does not require exact recall (creative writing, brainstorming). - The narrative is treated as a **non-canonical view** derived from a lossless store, with provenance and ability to drill down.-]

### 7.1 When is narrative compaction still appropriate?

[-In other words: narrative summaries can exist, but they should be *derived caches*, not the canonical memory that replaces the only copy.-]

### 7.2 Cognitive bandwidth: self-managed vs system-managed memory

[-### 7.2 Cognitive bandwidth: self-managed vs system-managed memory-]

### 7.2 Cognitive bandwidth: self-managed vs system-managed memory

[-MemGPT-style self-management is elegant: the agent decides what to page and store. ([arxiv.org](https://arxiv.org/abs/2310.08560)) But in production, this can be expensive: every memory-management turn is a reasoning turn not spent on user goals. Weaviate’s context-engineering framing reinforces that reliability is often an architecture problem, not a "smarter model" problem. ([weaviate.io](https://weaviate.io/blog/context-engineering))-]

### 7.2 Cognitive bandwidth: self-managed vs system-managed memory

[-Our position is pragmatic: - use **system-managed retrieval** as the default for reliability and cost control, - allow **agent-directed deep retrieval** when the agent detects uncertainty, - explore **learned managers** (AgeMem, Memory-R1) as a future optimization. ([arxiv.org](https://arxiv.org/abs/2601.01885))-]

### 7.3 Privacy and governance in lossless event stores

[-### 7.3 Privacy and governance in lossless event stores-]

### 7.3 Privacy and governance in lossless event stores

[-A lossless event store increases privacy stakes:-]

### 7.3 Privacy and governance in lossless event stores

[-- tool results may contain secrets (tokens, credentials), - chats may contain sensitive personal data, - retention may violate user expectations or regulations.-]

### 7.3 Privacy and governance in lossless event stores

[-MaRS explicitly integrates privacy-aware retention and budgets, motivating: - sensitivity labels on events, - encryption at rest, - access control per agent/user/project, - deletion/editing capabilities ("forget this") that propagate through derived views. ([arxiv.org](https://arxiv.org/abs/2512.12856))-]

### 7.3 Privacy and governance in lossless event stores

[-Lossless storage does not mean indefinite retention. It means that compaction should not *accidentally* delete the only accessible copy; deletion should be explicit, policy-driven, and auditable.-]

### 7.4 Limitations

[-### 7.4 Limitations-]

### 7.4 Limitations

[-1. **Retrieval quality is now a correctness bottleneck.** Pointer compaction shifts the problem from summarization fidelity to retrieval fidelity. Poor retrieval can still cause failures---though failures become *recoverable* (try a different query) rather than permanently destructive.-]

### 7.4 Limitations

[-2. **Indexing overhead.** Continuous embedding can be expensive; batching and selective embedding are necessary.-]

### 7.4 Limitations

[-3. **Security risks: prompt injection via stored content.** Any retrieval system can inject adversarial text. Provenance, sanitization, and instruction-isolation are required.-]

### 7.4 Limitations

[-4. **Task State drift.** Task State is an interpretation layer; it can become stale or wrong. Provenance pointers and versioning mitigate this, but do not eliminate it.-]

### 7.5 Future work

[-### 7.5 Future work-]

### 7.5 Future work

[-- **Learned memory policies:** integrate AgeMem/Memory-R1 style RL to optimize retrieval and forgetting policies end-to-end. ([arxiv.org](https://arxiv.org/abs/2601.01885)) - **Observation logs as cache formats:** adopt OM-like dense observations as a stable prefix derived from the event store, combining stable caching benefits with lossless ground truth. ([mastra.ai](https://mastra.ai/research/observational-memory)) - **Hierarchical and multi-granularity retrieval:** expand RAPTOR-like hierarchies and typed retrieval surfaces for better budget control. ([arxiv.org](https://arxiv.org/abs/2401.18059)) - **Robust evaluation suites for tool-bloat workloads:** extend LongMemEval-style evaluation with tool-result-heavy traces that reflect production pressures. ([arxiv.org](https://arxiv.org/abs/2410.10813))-]

### 7. Hierarchical Agent Planning (Planner/Executor/Sub-Executors)

{+## 7. Hierarchical Agent Planning (Planner/Executor/Sub-Executors)+}

### 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.+}

### 7.1 The hierarchy

{+### 7.1 The hierarchy+}

### 7.1 The hierarchy

{+- **Level 1 (Planner):** maintains strategy, milestones, acceptance criteria, risk register, and pointers to evidence; delegates sub-tasks. - **Level 2 (Executor):** performs a delegated sub-task; maintains detailed tool outputs and execution traces; reports results upward. - **Level 3+ (Sub-executors):** for very large tasks, executors can delegate further.+}

### 7.1 The hierarchy

{+Each level has:+}

### 7.1 The hierarchy

{+- its own bounded context window (cache), - its own Task State (appropriate abstraction), - its own retrieval surface tuned to its role.+}

### 7.2 Why separation helps

{+### 7.2 Why separation helps+}

### 7.2 Why separation helps

{+The 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.+}

### 7.2 Why separation helps

{+Pointer-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.+}

### 7.3 Hierarchical planning diagram

{+### 7.3 Hierarchical planning diagram+}

### 7.3 Hierarchical planning diagram

{+```text +-----------------------------------------------------------------------------------+ | TRACE hierarchical planning | +-----------------------------------------------------------------------------------++}

### 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 ```+}

### 7.3 Hierarchical planning diagram

{+(See **Annex A.5** for a concrete protocol: delegation messages, report schemas, and pointer propagation across levels.)+}

### 8. Conclusion

[-## 8. Conclusion-]

### 8. Conclusion

[-Narrative compaction is a convenient hack that becomes a structural liability in persistent, tool-using LLM agents. It is catastrophically lossy because it destroys the only cognitively accessible copy of high-resolution evidence, and it is executed under the worst possible conditions---near context saturation, where long-context failures and summarization unfaithfulness are most likely. ([aclanthology.org](https://aclanthology.org/2024.tacl-1.9/))-]

### 8. Conclusion

[-We presented **Event-Sourced Hierarchical Memory (ESHM)** as a replacement: treat the context window as a cache over a lossless event store, implement compaction as cache eviction, and replace narrative summaries with **pointer-based compaction** plus an explicit **Task State** object. A three-layer architecture---Continuous Indexing, Per-Turn Retrieval, and Sleep Consolidation---provides a practical decomposition aligned with both cognitive-architecture framing and modern context-engineering guidance. ([arxiv.org](https://arxiv.org/abs/2309.02427))-]

### 8. Conclusion

[-For OpenClaw and similar production agents, the immediate priority is clear: stop destroying the only copy. Persist and index events continuously, evict from cache with pointers, and retrieve on demand. Once the catastrophe is removed, higher-level memory organization---typed objects, linking, hierarchies, and principled forgetting---can be built safely atop a lossless foundation.-]

### 8. Hierarchical & Multi-Granularity Retrieval

{+## 8. Hierarchical & Multi-Granularity Retrieval+}

### 8. Hierarchical & Multi-Granularity Retrieval

{+TRACE's lossless store makes it possible---and often necessary---to retrieve at multiple abstraction levels.+}

### 8.1 Multi-granularity objects

{+### 8.1 Multi-granularity objects+}

### 8.1 Multi-granularity objects

{+TRACE supports retrieving different representations of the same underlying history:+}

### 8.1 Multi-granularity objects

{+- **Raw events:** exact messages, tool calls/results, error strings (highest fidelity; token-expensive). - **Episode summaries:** summaries of contiguous work episodes (task/incident-level). - **Topic summaries:** aggregated summaries across episodes (theme-level). - **Strategic insights:** distilled patterns, policies, and stable decisions (highest abstraction).+}

### 8.1 Multi-granularity objects

{+These are all **derived views** with provenance pointers; none replace the lossless store.+}

### 8.2 RAPTOR-style trees as retrieval indexes

{+### 8.2 RAPTOR-style trees as retrieval indexes+}

### 8.2 RAPTOR-style trees as retrieval indexes

{+RAPTOR 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.+}

### 8.2 RAPTOR-style trees as retrieval indexes

{+The key compatibility argument is: **hierarchies are indexes, not replacements.** Summaries may be lossy, but the ground truth remains available for drill-down.+}

### 8.3 Adaptive retrieval: choosing the right granularity

{+### 8.3 Adaptive retrieval: choosing the right granularity+}

### 8.3 Adaptive retrieval: choosing the right granularity

{+TRACE can select granularity based on:+}

### 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).+}

### 8.4 Pros and cons

{+### 8.4 Pros and cons+}

### 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.+}

### 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.+}

### 8.4 Pros and cons

{+(See **Annex A.6** for a multi-granularity retrieval policy, including drill-down triggers and provenance-linked packing.)+}

### 8.4 Pros and cons

{+---+}

### 9. Formal Boundedness Guarantees

{+## 9. Formal Boundedness Guarantees+}

### 9. Formal Boundedness Guarantees

{+TRACE is explicitly engineered to keep both **per-turn context injection** and **total stored memory growth** bounded under clear invariants.+}

### 9.1 Per-turn context boundedness (hard caps)

{+### 9.1 Per-turn context boundedness (hard caps)+}

### 9.1 Per-turn context boundedness (hard caps)

{+Let $B_{\text{ctx}}$ be the model's maximum context window (tokens). TRACE enforces fixed budgets:+}

### 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.+}

### 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}}$. \]+}

### 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.+}

### 9.2 Linear growth of total memory (no quadratic blow-up)

{+### 9.2 Linear growth of total memory (no quadratic blow-up)+}

### 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)$.+}

### 9.2 Linear growth of total memory (no quadratic blow-up)

{+Indexes are also linear or better:+}

### 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)$.+}

### 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.+}

### 9.3 Bounded total disk usage (policy, not wishful thinking)

{+### 9.3 Bounded total disk usage (policy, not wishful thinking)+}

### 9.3 Bounded total disk usage (policy, not wishful thinking)

{+Linear growth can still be large. TRACE therefore distinguishes:+}

### 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.+}

### 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.+}

### 9.3 Bounded total disk usage (policy, not wishful thinking)

{+This yields bounded *hot* storage and predictable long-term growth.+}

### 9.3 Bounded total disk usage (policy, not wishful thinking)

{+(See **Annex A.7** for a concrete retention/archival policy and an accounting model.)+}

### 9.3 Bounded total disk usage (policy, not wishful thinking)

{+---+}

### 10. Token Savings Analysis (Production Data)

{+## 10. Token Savings Analysis (Production Data)+}

### 10. Token Savings Analysis (Production Data)

{+This section quantifies token dynamics using production figures from a personal AI agent deployment.+}

### 10.1 Baseline: narrative compaction in a 200K-token window

{+### 10.1 Baseline: narrative compaction in a 200K-token window+}

### 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.+}

### 10.1 Baseline: narrative compaction in a 200K-token window

{+Two compounding effects make this worse than it appears:+}

### 10.1 Baseline: narrative compaction in a 200K-token window

{+1. **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.+}

### 10.1 Baseline: narrative compaction in a 200K-token window

{+If 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.+}

### 10.2 TRACE: pointer compaction + retrieval pack under the same window

{+### 10.2 TRACE: pointer compaction + retrieval pack under the same window+}

### 10.2 TRACE: pointer compaction + retrieval pack under the same window

{+Under TRACE in the same 200K-token setting:+}

### 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.+}

### 10.2 TRACE: pointer compaction + retrieval pack under the same window

{+TRACE 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.+}

### 10.3 Net effect over a 50-turn session with 3 compactions

{+### 10.3 Net effect over a 50-turn session with 3 compactions+}

### 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.+}

### 10.3 Net effect over a 50-turn session with 3 compactions

{+The 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.+}

### 10.3 Net effect over a 50-turn session with 3 compactions

{+---+}

### 11. Implementation Considerations (Production-Oriented)

{+## 11. Implementation Considerations (Production-Oriented)+}

### 11. Implementation Considerations (Production-Oriented)

{+TRACE is deliberately implementable with standard components (relational store + FTS + vector search + blob storage) and can be deployed incrementally.+}

### 11.1 Minimal viable path (risk-managed)

{+### 11.1 Minimal viable path (risk-managed)+}

### 11.1 Minimal viable path (risk-managed)

{+A staged migration that yields early value:+}

### 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.+}

### 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.+}

### 11.2 Storage and indexing choices

{+### 11.2 Storage and indexing choices+}

### 11.2 Storage and indexing choices

{+A robust baseline architecture:+}

### 11.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:** 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.+}

### 11.2 Storage and indexing choices

{+TRACE does not require exotic infrastructure; the core requirement is **write-once persistence + searchable indexes** before eviction.+}

### 11.3 Operational safeguards

{+### 11.3 Operational safeguards+}

### 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.+}

### 11.3 Operational safeguards

{+---+}

### 12. Evaluation Framework

{+## 12. Evaluation Framework+}

### 12. Evaluation Framework

{+TRACE changes the failure mode from "irreversible forgetting" to "retrieval misses something," which is measurable and improvable. We recommend evaluation along four axes.+}

### 12.1 Information preservation under forced compactions ("needles")

{+### 12.1 Information preservation under forced compactions ("needles")+}

### 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.+}

### 12.1 Information preservation under forced compactions ("needles")

{+Compare: - narrative compaction baseline, - truncation baseline (drop history), - TRACE pointer compaction + retrieval.+}

### 12.2 Retrieval quality and budgets

{+### 12.2 Retrieval quality and budgets+}

### 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.+}

### 12.3 Task continuity metrics

{+### 12.3 Task continuity metrics+}

### 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.+}

### 12.4 Hierarchical planning effectiveness

{+### 12.4 Hierarchical planning effectiveness+}

### 12.4 Hierarchical planning effectiveness

{+Evaluate planner/executor separation:+}

### 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?+}

### 12.4 Hierarchical planning effectiveness

{+(See **Annex A.8** for a compaction stress test harness and hierarchical-planning evaluation scaffolding.)+}

### 12.4 Hierarchical planning effectiveness

{+---+}

### 13. Limitations (Including vs. Human Associative Memory)

{+## 13. Limitations (Including vs. Human Associative Memory)+}

### 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.+}

### 13.1 What associations TRACE captures well

{+### 13.1 What associations TRACE captures well+}

### 13.1 What associations TRACE captures well

{+TRACE can capture and retrieve memories via a finite set of explicit pathways:+}

### 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.+}

### 13.1 What associations TRACE captures well

{+These are strong, engineering-friendly association mechanisms that can be audited and tuned.+}

### 13.2 What associations TRACE cannot capture (and why that matters)

{+### 13.2 What associations TRACE cannot capture (and why that matters)+}

### 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:+}

### 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.+}

### 13.3 The "unknown unknowns" retrieval problem

{+### 13.3 The "unknown unknowns" retrieval problem+}

### 13.3 The "unknown unknowns" retrieval problem

{+Lossless 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.+}

### 13.3 The "unknown unknowns" retrieval problem

{+TRACE 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.+}

### 13.3 The "unknown unknowns" retrieval problem

{+But the limitation remains: **the system retrieves what it can score**, not what it "should have realized mattered."+}

### 13.4 Additional limitations

{+### 13.4 Additional limitations+}

### 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.+}

### 13.4 Additional limitations

{+---+}

### 14. Discussion

{+## 14. Discussion+}

### 14.1 When narrative summaries still make sense

{+### 14.1 When narrative summaries still make sense+}

### 14.1 When narrative summaries still make sense

{+Narrative summaries remain useful as *derived views*:+}

### 14.1 When narrative summaries still make sense

{+- human handoffs and status updates, - "what happened?" recaps, - lightweight progress reports.+}

### 14.1 When narrative summaries still make sense

{+TRACE does not forbid summaries; it forbids treating them as canonical memory that replaces evidence.+}

### 14.2 Relationship to priority-aware identity preservation

{+### 14.2 Relationship to priority-aware identity preservation+}

### 14.2 Relationship to priority-aware identity preservation

{+TRACE 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 the companion technical report (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.+}

### 14.2 Relationship to priority-aware identity preservation

{+---+}

### 15. Conclusion

{+## 15. Conclusion+}

### 15. Conclusion

{+Narrative 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.+}

### 15. Conclusion

{+TRACE extends the core 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."+}

### References

[-*(Production-ready reference list; identifiers and venues as available.)*-]

### References

1. Alqithami, S. (2025). [-**Forgetful-] {+*Forgetful+} but Faithful: A Cognitive Memory Architecture and Benchmark for Privacy-Aware Generative [-Agents** (introduces MaRS and FiFA benchmark).-] {+Agents* (MaRS).+} arXiv:2512.12856. [-([arxiv.org](https://arxiv.org/abs/2512.12856))-] 2. Anthropic Applied AI Team (2025). [-**Effective-] {+*Effective+} context engineering for AI [-agents**.-] {+agents*.+} Anthropic [-Engineering (Sep 29, 2025). ([anthropic.com](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents))-] {+Engineering. `https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents`+} 3. Barnes, T. (2026). [-**Observational-] {+*Observational+} Memory: 95% on [-LongMemEval**.-] {+LongMemEval*.+} Mastra [-Research (Feb 9, 2026). ([mastra.ai](https://mastra.ai/research/observational-memory))-] {+Research. `https://mastra.ai/research/observational-memory`+} 4. [-Cao, S., & Wang, L. (2021). **CLIFF: Contrastive Learning for Improving Faithfulness and Factuality in Abstractive Summarization**. arXiv:2109.09209. ([arxiv.org](https://arxiv.org/abs/2109.09209)) 5. Durmus, E., He, H., & Diab, M. (2020). **FEQA: A Question Answering Evaluation Framework for Faithfulness Assessment in Abstractive Summarization**. arXiv:2005.03754. ([arxiv.org](https://arxiv.org/abs/2005.03754)) 6.-] Fowler, M. (2005). [-**Event Sourcing**. martinfowler.com (Dec 12, 2005). ([martinfowler.com](https://www.martinfowler.com/eaaDev/EventSourcing.html)) 7. Kim, Y., Chang, Y., Karpinska, M., et al. (2024). **FABLES: Evaluating faithfulness and content selection in book-length summarization**. arXiv:2404.01261. ([arxiv.org](https://arxiv.org/abs/2404.01261)) 8.-] {+*Event Sourcing*. `https://www.martinfowler.com/eaaDev/EventSourcing.html` 5.+} Kryscinski, W., McCann, B., Xiong, C., & Socher, R. (2020). [-**Evaluating-] {+*Evaluating+} the Factual Consistency of Abstractive Text [-Summarization**.-] {+Summarization*.+} EMNLP 2020. [-ACL Anthology: 2020.emnlp-main.750. ([aclanthology.org](https://aclanthology.org/2020.emnlp-main.750/)) 9.-] {+6.+} Letta (2024). [-**MemGPT-] {+*MemGPT+} is now part of [-Letta** (project clarification). Letta Blog (Sep 23, 2024). ([letta.com](https://www.letta.com/blog/memgpt-and-letta)) 10. Letta Docs (2024--2025). **MemGPT (concepts)**. ([docs.letta.com](https://docs.letta.com/concepts/memgpt)) 11. Li, Z., Song, S., Xi, C., et al. (2025). **MemOS: A Memory OS for AI System**. arXiv:2507.03724. ([arxiv.org](https://arxiv.org/abs/2507.03724)) 12.-] {+Letta*. `https://www.letta.com/blog/memgpt-and-letta` 7.+} Liu, N. F., Lin, K., Hewitt, J., et al. (2024). [-**Lost-] {+*Lost+} in the Middle: How Language Models Use Long [-Contexts**. Transactions of the ACL (TACL), 12:157--173. DOI: 10.1162/tacl_a_00638. ([aclanthology.org](https://aclanthology.org/2024.tacl-1.9/)) 13.-] {+Contexts*. TACL. 8.+} Maynez, J., Narayan, S., Bohnet, B., & McDonald, R. (2020). [-**On-] {+*On+} Faithfulness and Factuality in Abstractive [-Summarization**.-] {+Summarization*.+} ACL 2020. [-ACL Anthology: 2020.acl-main.173. ([aclanthology.org](https://aclanthology.org/2020.acl-main.173/)) 14. Mastra (2026). **Research index** (entry point for Observational Memory and LongMemEval work). ([mastra.ai](https://mastra.ai/research)) 15.-] {+9.+} Packer, C., Wooders, S., Lin, K., [-Fang, V., Patil, S. G., Stoica, I., & Gonzalez, J. E.-] {+et al.+} (2023). [-**MemGPT:-] {+*MemGPT:+} Towards LLMs as Operating [-Systems**.-] {+Systems*.+} arXiv:2310.08560. [-([arxiv.org](https://arxiv.org/abs/2310.08560)) 16.-] {+10.+} Sarthi, P., Abdullah, S., Tuli, A., Khanna, S., Goldie, A., & Manning, C. D. (2024). [-**RAPTOR:-] {+*RAPTOR:+} Recursive Abstractive Processing for Tree-Organized [-Retrieval**.-] {+Retrieval*.+} arXiv:2401.18059. [-([arxiv.org](https://arxiv.org/abs/2401.18059)) 17.-] {+11. Serra, O. (2026). *Agent Memory: Priority-Aware Context Engineering for Persistent AI Identity*. Technical Report, OpenClaw. 12.+} Sumers, T. R., Yao, S., Narasimhan, K., & Griffiths, T. L. (2023). [-**Cognitive-] {+*Cognitive+} Architectures for Language [-Agents**-] {+Agents*+} (CoALA). arXiv:2309.02427. [-([arxiv.org](https://arxiv.org/abs/2309.02427)) 18.-] {+13.+} Weaviate [-(Plantinga, F.; Yadav, P.; Slocum, V.)-] (2025). [-**Context-] {+*Context+} Engineering [----] {+---+} LLM Memory and Retrieval for AI [-Agents**. Weaviate Blog (Dec 9, 2025). ([weaviate.io](https://weaviate.io/blog/context-engineering)) 19.-] {+Agents*. `https://weaviate.io/blog/context-engineering` 14.+} Wu, D., Wang, H., Yu, W., [-Zhang, Y., Chang, K.-W., & Yu, D.-] {+et al.+} (2024). [-**LongMemEval:-] {+*LongMemEval:+} Benchmarking Chat Assistants on Long-Term Interactive [-Memory**.-] {+Memory*.+} arXiv:2410.10813. [-([arxiv.org](https://arxiv.org/abs/2410.10813)) 20.-] {+15.+} Xu, W., Liang, Z., Mei, K., [-Gao, H., Tan, J., & Zhang, Y.-] {+et al.+} (2025). [-**A-MEM:-] {+*A-MEM:+} Agentic Memory for LLM [-Agents**.-] {+Agents*.+} arXiv:2502.12110. [-([arxiv.org](https://arxiv.org/abs/2502.12110)) 21.-] {+16.+} Yan, S., Yang, X., Huang, Z., et al. (2025). [-**Memory-R1:-] {+*Memory-R1:+} Enhancing [-Large Language Model-] {+LLM+} Agents to Manage and Utilize Memories via Reinforcement [-Learning**.-] {+Learning*.+} arXiv:2508.19828. [-([arxiv.org](https://arxiv.org/abs/2508.19828)) 22.-] {+17.+} Yu, Y., Yao, L., Xie, Y., [-Tan, Q., Feng, J., Li, Y., & Wu, L.-] {+et al.+} (2026). [-**Agentic-] {+*Agentic+} Memory: Learning Unified Long-Term and Short-Term Memory Management for [-Large Language Model Agents**-] {+LLM Agents*+} (AgeMem). [-arXiv:2601.01885. ([arxiv.org](https://arxiv.org/abs/2601.01885)) 23. Zhang, Y., Li, Y., Cui, L., et al. (2023). **Siren’s Song in the AI Ocean: A Survey on Hallucination in Large Language Models**. arXiv:2309.01219. ([arxiv.org](https://arxiv.org/abs/2309.01219))-] {+arXiv:2601.01885.+}

### References

{+---+}

### Annex A --- Algorithms (Pseudocode)

{+# Annex A --- Algorithms (Pseudocode)+}

### Annex A --- Algorithms (Pseudocode)

{+All algorithms are collected here to keep the main paper readable.+}

### A.1 Continuous ingestion and indexing (Layer 1)

{+## A.1 Continuous ingestion and indexing (Layer 1)+}

### 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}+}

### 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+}

### A.1 Continuous ingestion and indexing (Layer 1)

{+6: persist_event(event_id, event) // append-only 7: update_metadata_indexes(event_id, metadata)+}

### 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)+}

### 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+}

### A.1 Continuous ingestion and indexing (Layer 1)

{+14: return event_id ```+}

### A.2 Per-turn context pack builder (Layer 2)

{+## A.2 Per-turn context pack builder (Layer 2)+}

### A.2 Per-turn 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}+}

### A.2 Per-turn context pack builder (Layer 2)

{+Output: ordered context_pack+}

### A.2 Per-turn context pack builder (Layer 2)

{+1: q <- build_query(user_msg, task_state, recent_tail)+}

### A.2 Per-turn 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)+}

### A.2 Per-turn context pack builder (Layer 2)

{+6: C <- dedupe(C_vec U C_fts U C_ptr U C_pin)+}

### A.2 Per-turn 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+}

### A.2 Per-turn 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)+}

### 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) ]+}

### 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 ```+}

### A.3 Task-aware retrieval priority (task-conditioned modifier)

{+## A.3 Task-aware retrieval priority (task-conditioned modifier)+}

### 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)+}

### A.3 Task-aware retrieval priority (task-conditioned modifier)

{+Output: modifier m >= 0+}

### A.3 Task-aware retrieval priority (task-conditioned modifier)

{+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+}

### A.3 Task-aware retrieval priority (task-conditioned modifier)

{+4: m <- 1.0+}

### A.3 Task-aware retrieval priority (task-conditioned modifier)

{+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+}

### 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]+}

### 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+}

### A.3 Task-aware retrieval priority (task-conditioned modifier)

{+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+}

### A.3 Task-aware retrieval priority (task-conditioned modifier)

{+18: // Guardrails: never crowd out hard constraints 19: if item.type == "constraint" then 20: m <- max(m, 3.0) 21: end if+}

### A.3 Task-aware retrieval priority (task-conditioned modifier)

{+22: return clamp(m, 0.0, M_MAX) ```+}

### A.4 Pointer-based compaction (cache eviction + manifest)

{+## A.4 Pointer-based compaction (cache eviction + manifest)+}

### 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+}

### A.4 Pointer-based compaction (cache eviction + manifest)

{+Output: compacted cache+}

### 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)+}

### 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) }+}

### A.4 Pointer-based compaction (cache eviction + manifest)

{+6: insert_manifest(cache, manifest, position=victim_span.start_position) 7: end while+}

### A.4 Pointer-based compaction (cache eviction + manifest)

{+8: return cache ```+}

### A.5 Hierarchical planning protocol (planner <-> executor)

{+## A.5 Hierarchical planning protocol (planner <-> executor)+}

### 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+}

### 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 ```+}

### A.6 Multi-granularity retrieval with drill-down

{+## A.6 Multi-granularity retrieval with drill-down+}

### 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+}

### A.6 Multi-granularity retrieval with drill-down

{+9: pack <- pack_under_budget(candidates, B_ret)+}

### A.6 Multi-granularity retrieval with drill-down

{+10: 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+}

### A.6 Multi-granularity retrieval with drill-down

{+14: return pack ```+}

### A.7 Retention and bounded hot-storage policy (artifacts)

{+## A.7 Retention and bounded hot-storage policy (artifacts)+}

### A.7 Retention and bounded hot-storage policy (artifacts)

{+```text Algorithm A.7: ARTIFACT_LIFECYCLE_POLICY(now) Parameters: N_days_hot, compression, cold_storage_backend+}

### A.7 Retention and bounded hot-storage policy (artifacts)

{+1: 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 ```+}

### A.8 Compaction stress test harness ("needles in a haystack")

{+## A.8 Compaction stress test harness ("needles in a haystack")+}

### 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)+}

### A.8 Compaction stress test harness ("needles in a haystack")

{+3: 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+}

### 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+}

### A.8 Compaction stress test harness ("needles in a haystack")

{+13: return aggregate scores + token accounting + retrieval logs ```+}
