---
title: "Lossless Event-Sourced Memory with Pointer-Based Compaction"
date: "2026-02-15"
---



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

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.

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.

---

## 1. Introduction --- The Compaction Catastrophe

### 1.1 Persistent agents are not chats

As LLMs transition from single-session assistants to persistent agents---systems that operate continuously across hours, days, and months---the memory problem changes qualitatively. A persistent agent must maintain:

1. **High-resolution task state**: what has been tried, what failed, what remains, and why.
2. **Long-horizon commitments**: decisions, constraints, and follow-ups.
3. **Tool-grounded evidence**: tool outputs, error traces, file diffs, search results, and logs that anchor reasoning in reality.
4. **Continuity across context resets**: the ability to resume without re-asking for already-provided details.

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))

We argue this compromise is structurally wrong for persistent agents.

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

This is a catastrophe for two reasons:

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.

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))

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.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.

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.

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.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.*

We make five central claims:

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.

Our practical contributions are:

- 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.

---

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

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))

**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

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))

**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

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))

**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.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))

**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.

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

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))

**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

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))

**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.

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

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))

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))

**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

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))

**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.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))

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

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/))

**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

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))

**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

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))

**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.

---

## 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 Formalizing compaction as a transformation

Let an agent interaction be an ordered sequence of events:

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

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.

Narrative compaction implements an approximate map:

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

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

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

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.

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.

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

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

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

- **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/))

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)

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

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

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

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

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

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

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

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

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))

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

Compaction typically occurs when:

- 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.

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))

**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.

---

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

### 4.1 Design principles

We propose **Event-Sourced Hierarchical Memory (ESHM)**, a production-oriented architecture grounded in five 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))

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

**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.

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

**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

We decompose memory across three time scales:

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

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.

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

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.3 Data model: events, artifacts, and derived memory

#### 4.3.1 Event log

Each event is immutable and append-only:

- `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

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

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

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

#### 4.3.3 Derived, typed memory objects

Derived objects represent *views* over the event log:

- **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

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")

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.

A representative schema:

```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"
}
```

**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.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.

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

#### Algorithm 1: Continuous ingestion and indexing

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

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
```

**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.

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

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

Layer 2 constructs the context cache for each turn:

- 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

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

We recommend combining:

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

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

Output: context_pack: ordered list of context blocks

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)

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

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

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)

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
```

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))

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

- **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

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

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))

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

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

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

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

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

**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

We now define the core mechanism: **pointer compaction**.

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

**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

```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

Output:
  new_context_cache: cache after eviction + pointer manifest insertion

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)

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)
        )

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

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

- **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.

---

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

OpenClaw is a persistent agent platform with:

- 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

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

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.

We formalize this mechanism as a baseline:

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

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)

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

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

13: return messages
```

**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

We recommend a staged migration that yields value quickly:

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

**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.

**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.

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

**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.

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)

A minimal schema (illustrative, not exhaustive):

```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
);

-- 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
);

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

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

-- 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
);

-- 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
);
```

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

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)

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

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))

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.

---

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

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.

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

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

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

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

We propose tests that explicitly target the catastrophe:

- 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.

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

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

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

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

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

13: return score / |needles|
```

### 6.3 Ablations

To validate the decomposition, we propose 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).

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

---

## 7. Discussion

### 7.1 When is narrative compaction still appropriate?

Narrative compaction is not useless. It remains appropriate when:

- 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.

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

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))

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

A lossless event store increases privacy stakes:

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

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))

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

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.

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

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

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

- **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))

---

## 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/))

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))

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.

---

## References

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

1. Alqithami, S. (2025). **Forgetful but Faithful: A Cognitive Memory Architecture and Benchmark for Privacy-Aware Generative Agents** (introduces MaRS and FiFA benchmark). arXiv:2512.12856. ([arxiv.org](https://arxiv.org/abs/2512.12856))  
2. Anthropic Applied AI Team (2025). **Effective context engineering for AI agents**. Anthropic Engineering (Sep 29, 2025). ([anthropic.com](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents))  
3. Barnes, T. (2026). **Observational Memory: 95% on LongMemEval**. Mastra Research (Feb 9, 2026). ([mastra.ai](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. Kryscinski, W., McCann, B., Xiong, C., & Socher, R. (2020). **Evaluating the Factual Consistency of Abstractive Text Summarization**. EMNLP 2020. ACL Anthology: 2020.emnlp-main.750. ([aclanthology.org](https://aclanthology.org/2020.emnlp-main.750/))  
9. Letta (2024). **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. Liu, N. F., Lin, K., Hewitt, J., et al. (2024). **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. Maynez, J., Narayan, S., Bohnet, B., & McDonald, R. (2020). **On Faithfulness and Factuality in Abstractive 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. Packer, C., Wooders, S., Lin, K., Fang, V., Patil, S. G., Stoica, I., & Gonzalez, J. E. (2023). **MemGPT: Towards LLMs as Operating Systems**. arXiv:2310.08560. ([arxiv.org](https://arxiv.org/abs/2310.08560))  
16. Sarthi, P., Abdullah, S., Tuli, A., Khanna, S., Goldie, A., & Manning, C. D. (2024). **RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval**. arXiv:2401.18059. ([arxiv.org](https://arxiv.org/abs/2401.18059))  
17. Sumers, T. R., Yao, S., Narasimhan, K., & Griffiths, T. L. (2023). **Cognitive Architectures for Language Agents** (CoALA). arXiv:2309.02427. ([arxiv.org](https://arxiv.org/abs/2309.02427))  
18. Weaviate (Plantinga, F.; Yadav, P.; Slocum, V.) (2025). **Context Engineering -- LLM Memory and Retrieval for AI Agents**. Weaviate Blog (Dec 9, 2025). ([weaviate.io](https://weaviate.io/blog/context-engineering))  
19. Wu, D., Wang, H., Yu, W., Zhang, Y., Chang, K.-W., & Yu, D. (2024). **LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory**. arXiv:2410.10813. ([arxiv.org](https://arxiv.org/abs/2410.10813))  
20. Xu, W., Liang, Z., Mei, K., Gao, H., Tan, J., & Zhang, Y. (2025). **A-MEM: Agentic Memory for LLM Agents**. arXiv:2502.12110. ([arxiv.org](https://arxiv.org/abs/2502.12110))  
21. Yan, S., Yang, X., Huang, Z., et al. (2025). **Memory-R1: Enhancing Large Language Model Agents to Manage and Utilize Memories via Reinforcement Learning**. arXiv:2508.19828. ([arxiv.org](https://arxiv.org/abs/2508.19828))  
22. Yu, Y., Yao, L., Xie, Y., Tan, Q., Feng, J., Li, Y., & Wu, L. (2026). **Agentic Memory: Learning Unified Long-Term and Short-Term Memory Management for Large Language Model 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))


