Machine Learning
en-US

Agent Memory: Separating Online Notes, Offline Dreaming, and Context Injection — With a Real Run of a Memory Loop

Anthropic's 2026-11-06 post 'The components of agent memory' splits long-term memory into online note-taking, offline dreaming verification, wiki representations, and a session injection layer. Walking through the CL-Bench, Pokémon, Stainless, and Harvey case studies, this post explains what each layer solves—and what it does not prove—then runs a deterministic synthetic memory loop in Python: full raw notes score 5/10, raw notes under the same head-truncation rule score 3/10, and an index paired with on-demand reads scores 10/10. That 269-byte figure covers only the startup-injected index, with an additional 872 bytes read on demand across 10 questions. Consolidation fixes all 4 planted errors without losing any of the 5 originally correct note facts. This is a rule-driven synthetic fixture, not a reproduction of official dreaming or real-model performance, and bytes are not tokens.

·33 min read·Lios09
#agent-memory#context-engineering#dreaming#retrieval#python#evaluation

1. The One-Sentence Version: Memory Is Not an Ever-Growing Summary

An agent's memory system does not just have to answer "what should be stored?" It also has to answer: who verifies it, how staleness is handled, what deserves to live permanently in context, and what should stay out of context until a question actually calls for it.

Anthropic's original post defines agent memory as knowledge acquired from user interactions and task experience, persisted across sessions in a form that can later be read back into context. It explicitly excludes model weight updates, in-context learning within a single conversation, and compaction that replaces earlier turns just to keep current work going.

The "dreaming" discussed here means using out-of-session compute to organize external memory—not putting a model to sleep for retraining, and not fabricating imagined facts out of thin air. The original post was written by Lance Martin under Engineering; all official evaluations cited below are summarized from that article—I did not run those models or access any private corpora.

Online session
  observations / actions / user feedback
       |                         |
       v                         v
  append-only transcript    provisional notes
       |                         |
       +------------+------------+
                    v
          offline dreaming / consolidation
           verify -> correct -> merge -> link
                    |
          +---------+----------+
          v                    v
       topic wiki       small MEMORY.md index
          ^                    |
          |                    v
          +-- on-demand -- next session context

Closing the loop here does not mean "the write succeeded." It means: next time, the agent can find the relevant knowledge, know why it holds, and revise it when the evidence changes.


2. Online Notes vs. Offline Dreaming: Two Different Jobs

2.1 Online Recording Captures the Scene; Offline Consolidation Reviews the Whole Picture

An in-session agent knows best what is happening in the current task, but it also has to finish that task. It does not know what future sessions will ask, and it can easily record a mid-task hunch as fact. Offline consolidation can compare records across sessions, trace claims back to raw evidence, and merge duplicate pages—at the cost of extra compute and update latency.

LayerWhat It Should OwnAssumption You Should Not Take for Granted
Raw transcriptPreserving observations, actions, feedback, and provenanceEvery line in the log is ground truth
Online notesCapturing important in-the-moment findings, open questions, and next stepsJudgments written at the time have already been verified
Offline dreamingChecking evidence, correcting errors, rewriting representations, repairing linksOffline rewrites are inherently more reliable than raw notes
Wiki / indexProviding navigation and abstractions for future tasksMore pages automatically mean more complete and useful memory
Injection layerSupplying necessary background and retrieval entry points upfrontAnything placed in context will reliably be followed

This is an engineering trade-off: pushing all memory creation to the background means freshly learned knowledge cannot immediately help the next turn; doing all organization in the foreground burns task-execution time maintaining directories. The original post leaves this timing question open and does not prescribe a universal dreaming cadence.

2.2 CL-Bench: What Actually Pays Off Is Verified Rules

The original post uses a database Q&A task from CL-Bench 1.0: each question starts in a fresh session, the agent receives the correct answer after responding, and only the memory directory persists across sessions. It does not replay the full history back into context.

The memories written by different models reflect very different degrees of closing the loop:

ModelObservation from the Original Post
Sonnet 4.6Writes theories about why it got questions wrong, leaving untested guesses in the files
Opus 4.7Consolidates notes into reference docs, distinguishing verified facts from unconfirmed claims
Sonnet 5Confirms answers against the grader and adds corrections when it misses
Opus 5Builds rules, the rationale behind them, past answers, and gotcha warnings
Opus 5.5 / Sonnet 5.5Also produces verified rules; scores with memory are roughly on par with Opus 5, with a slightly higher no-memory baseline

"It happened before" and "it is reusable" are not the same thing. Saving a failure case only warns you that something might go wrong next time; verifying an explanation and distilling it into a rule is what actually changes future decisions.

The original post also tested a prompting intervention: telling Sonnet 4.6 to read memory before answering and explicitly test its theories nearly doubled its score. Without that extra prompt, Sonnet 5 already reads memory first nine times out of ten, while Sonnet 4.6 does so less than half the time. "Nearly doubled" is the original post's wording—I did not eyeball absolute scores off the chart.

Conversely, instructing stronger models to "only record failures" cost Opus 5 and Opus 4.7 a large share of their memory gains. The post recommends explaining the purpose of memory rather than locking down every write rule in advance.

My takeaway is that judging salience is a capability, not just a database schema problem. A rigid template can guarantee every audit field is populated, yet still fail to ensure the contents are useful later. The rule-based script later in this post only demonstrates the pipeline; it does not test that capability.


3. Pokémon: Why Remembering More Can Slow You Down

3.1 Copying Observable State Is Not Always Accumulating Knowledge

The original post compares a single Pokémon Red run each for Sonnet 3.7 and Fable 5, measured around step 10,000:

ModelMemory OrganizationGame Progress
Sonnet 3.7413 memory files across 225 folders1 badge
Fable 59 files across 2 folders, plus a top-level global.md4 badges

Sonnet 3.7 obsessively logged every battle, item, NPC, and constantly changing state. Around step 10,000, it started creating a fourth "master" directory, spending the next 17 steps creating 6 files and deleting 9 without taking a single in-game action.

Fable 5's global.md worked more like a dashboard: current objectives, gym battle plans, and its own rules for using memory, while other files were organized by location and mechanics. It prioritized strategy and knowledge earned through exploration rather than money totals or coordinates it could read straight off the screen every turn. The post also notes that Opus 5.5 used a similarly small, continuously updated memory structure and eventually beat the game.

This is not causal proof that "fewer files make a stronger model": the comparison involves different models, and only one run is shown for each of the first two. What it supports is a concrete failure mode: memory maintenance competes with task progress, and stale state keeps compounding the maintenance overhead.

3.2 A Wrong Landmark: The More Reliable Retrieval Gets, the More Reliably Errors Propagate

Mt. Moon's entrance is on the west side and its exit is on the east, with a one-way jumpable ledge near the entrance. Claude misrecorded the PokéCenter by the entrance as being on the east side, and therefore treated walking out of the PokéCenter as already having crossed the cave.

Subsequent actions did not self-correct the mistake: the navigation tool did not show the drop down the ledge, so Claude explained away landing back on the old route as having walked too far west—preserving its belief that it had already passed the mountain.

The original post tested dreaming on that memory: reviewing the transcript exposed the wrong landmark orientation and rewrote the note. With the corrected memory, Claude returned to the cave entrance and eventually reached Cerulean City. The run with uncorrected memory fell back onto the old route three times in a row and never reached the goal before the run ended; the no-memory control also failed to clear the cave.

The decisive difference was not plugging in a better retriever at query time—it was fixing the persistent fact being retrieved.

The original post notes that the transcript provided ground truth for verifying memory in this case. In your own systems, be more cautious: transcripts can also contain missed tool outputs, agent misunderstandings, or untrusted third-party text. My recommendation is to separate observations, inferences, and feedback, keeping provenance, scope, and verification status intact—never treat an agent's own narrative as higher-grade truth than raw evidence.


4. Wiki: Not Just Summaries, but a Knowledge Map for Future Questions

4.1 Stainless: Structured Representations and Raw Search Complement Each Other

The original post evaluates a wiki built over Stainless's internal documentation: roughly 350,000 files and ~420M tokens, benchmarked on 25 questions. Opus 5 agents ran successive dreaming sessions to explore files, write or correct linked pages, merge duplicates, and check sources, coordinating through a shared log.

ApproachResult in Original PostHow to Read It
Wiki only, scaling dreaming from 2 to 128 sessionsGraded criteria rose from 13% to 48%Not "percentage of 25 questions answered correctly"
Wiki + search, as the wiki growsAggregate score rose from 54% to 61%Combines map-level navigation with drilling into raw files
Search only53%Raw search is already a competitive baseline
Wiki + searchSaves roughly 20,000 tokens per questionApproximate figure from the original post, not measured here

The 2-to-128 progression is successive sessions, not model training steps; likewise, 13% to 48% should not be generalized as an expected lift for every enterprise Q&A workload.

What a wiki actually provides is precomputed linkage: which systems a concept touches, which pages belong together, and which sources back a conclusion. Search then lets the agent drop back to primary evidence whenever the map lacks detail. A representation is not a replacement for the source text—it is a route to it.

4.2 Not Every Task Needs That Map

On a set of 24 questions over M&A materials, the original post notes that more than half required cross-document synthesis, and many also required judgment or calculation. On the items requiring synthesis, the wiki scored 87% compared to 73% for search alone. Those two numbers should not be overstated as overall results across all legal tasks.

In another Harvey LAB task where most brief criteria could be satisfied by searching a single document, the wiki showed no clear benefit. In yet another task, the wiki ended up larger than the source corpus—failing to abstract anything and merely producing a bulkier duplicate.

Whether to build a wiki should therefore be task-driven:

  • Cross-document synthesis, multi-hop relationships, and repeatedly needed explanations are strong candidates for topic pages.
  • One-off lookups inside a single document are often served just fine by direct search.
  • Precision-sensitive material—contract clauses, config constants, API fields—should never sacrifice exact source wording just to read more like a summary.

4.3 Harvey: Going from 72% to 100% Changed Both Task Instructions and Write Topology

One LAB acquisition task in the original post was highly sensitive to exact contract terms. The initial wiki instructions did not emphasize that use case, and multiple agents wrote concurrently into a shared clause table: summaries dropped details, and concurrent writes overwrote one another.

The main text states that the brief generated from that wiki captured only 41 of 57 facts, or 72%. The Figure 14 caption similarly reports 41/57 vs. 57/57 facts retained before and after the change. After analyzing the failures, revising the wiki-building instructions, and rebuilding the wiki, the improved architecture looked like this:

Original approach
  agent A ----+
  agent B ----+--> shared contract summary table
  agent C ----+         |
                        +--> omission / overwritten updates

Improved approach
  agent A --> contract A page --+
  agent B --> contract B page --+--> links / downstream brief
  agent C --> contract C page --+
              verbatim terms

Each contract got its own page owned by a single agent, quoting clauses verbatim instead of cramming everything into a shared summary table. The original post's wording for the improved brief is that 100% of criteria could be satisfied, up from 72%; that is not a blanket promise of 100% accuracy across all of Harvey LAB.

This case shows two distinct problems that must not be conflated: whether summarization preserves the facts a task requires, and whether concurrent writes drop updates. Swapping models is no substitute for clean file ownership and commit protocols.

The original post also shows a second dreaming pass repairing graph structure: in one task, it found 9 broken links pointing to missing pages, repointed them to existing pages covering the same documents, and added 3 new pages including an index. Link maintenance itself is part of memory consolidation.


5. The Injection Layer: The Expensive Part Is Not Storing Memory, It Is Paying for It Every Turn

5.1 MEMORY.md Is an Entry Point, Not a Warehouse

Both the original post and the Claude Code memory docs reviewed for this article state the same rule: at the start of every session, only the first 200 lines or first 25KB of MEMORY.md, whichever comes first, are loaded. Topic files are not bulk-loaded at startup; they are read on demand with standard file tools.

File or LayerStartup Loading BehaviorCommon Misconception
Auto memory's MEMORY.mdHead-truncated at 200 lines / 25KBWriting to the file successfully means the tail enters the next session's context
Auto memory's topic filesRead on demandStaying intact on disk means the model already knows it
CLAUDE.mdHas its own loading rules; docs advise keeping it conciseAuto memory's hard truncation cap directly applies to it

The docs also make clear that these files are context, not enforced configuration; when you need hard blocks on actions, use hooks or permission controls. Nor should the docs' warning that long instructions degrade adherence be read as "stay under the cap and compliance is guaranteed."

Head truncation turns ordering into a semantic concern: if retrieval pointers get pushed to the bottom of the file by repetitive log entries, the topic pages may still sit intact on disk while the next session has no idea where to look.

5.2 Filling the Budget Is Not the Goal

I recommend reserving the always-loaded layer for three things: current goals, essential verified constraints, and topic navigation. Push long justifications, historical logs, and verbatim reference material down into topic pages, and have topic pages link back to their sources.

A real budget needs to account for all three costs:

  • Startup injection: the fixed context cost paid on every session.
  • On-demand reads: the extra document cost paid when answering specific questions.
  • Offline maintenance: the compute and storage cost of consolidating, verifying, and rebuilding indexes.

Reporting only that the index is short while ignoring the cost of reading topic pages turns "lazy loading" into an illusion of "free knowledge."

5.3 Do Not Conflate Three Different Product Surfaces

The documentation reviewed for this post also distinguishes three separate surfaces:

  • Memory tool: the model requests file operations that your application executes client-side; persistence and path safety are your application's responsibility.
  • Managed Agents memory stores: persistent storage mounted as a directory for sessions; the docs describe version auditing and optimistic concurrency control via content-hash preconditions.
  • Claude Code auto memory: the MEMORY.md index plus on-demand topic files described above.

The 200-line / 25KB limit verified here is Claude Code auto memory's injection cap, not a universal protocol shared by every memory tool or store.


6. Hands-On Experiment: A Deterministic Minimal Memory Loop

This is a custom illustrative experiment, not an official implementation. I ran the full Python script below locally without calling any paid APIs and without using real user sessions or private data.

The experiment does not test whether a model can judge salience. It tests three narrower questions:

  1. After verifying against sources, deduplicating, and building topic pages, are any originally correct facts lost?
  2. Under the same head-truncation budget, what do raw notes vs. an index actually make visible to the next session?
  3. When the index holds only paths and keys without answers, are on-demand reads strictly required, or can the index answer on its own?

6.1 Data and Rules: Deliberately Planting Errors and Head Congestion

Synthetic logs simulate a small project spanning a Go service, a frontend, and AI features. Three sessions append records to transcript and note JSONL files. Every piece of evidence uses structured fields—no natural-language understanding is involved.

ItemExperiment Setup
Backed facts9 distinct keys
Planted errors4 total: request timeout, retry scope, shutdown wait, log retention
Originally correct note facts5
Unsourced assertion1 claim about PII; correct evaluation behavior is to abstain
Duplicate noise210 extra identical health-check entries appended
Total raw notes220 entries
Topicsgo, frontend, ops, ai

For example, the synthetic tool record states go.timeout=30s, while the note records 300s. These values are test fixtures only—not Go defaults or production configuration recommendations. The repeated health-check entries are an artificial stress condition designed to push later facts past the head limit; the magnitude of the gain here should not be treated as a realistic distribution of real-world sessions.

The offline rules are:

  • Deduplicate exact (topic, key, value, source) tuples.
  • Trust only tool/user records pre-marked verified in this fixture, matching on source ID, topic, and key.
  • If the note value disagrees with that evidence, correct it and record an old/new/source audit entry.
  • If no backing source exists, quarantine the note rather than promoting a guess to fact.
  • Build one wiki page per topic, and generate an index that lists only topics, paths, and keys—no values.
  • Inject only the head of the index into the next session, and look up topic pages on demand by key.

This does not implement general temporal conflict resolution: if a configuration legitimately changes over time, you cannot decide which value is newer merely by checking an older source pointer stored on an older note. Here, each key has a single trusted fact, explicitly sidestepping that harder problem.

6.2 Evaluation Criteria: Same Questions, Separating Retrieval from Correctness

The test set has 10 questions: 9 with sourced answers and 1 that should abstain. The question-to-key mapping is hardcoded, and answers are extracted from retrieved FACT lines—semantic retrieval, natural-language reasoning, and LLM answering are not being tested here.

MetricDefinition
AccuracyExact match across all 10 questions, including returning None for the unsourced question
Evidence hitFraction of the 9 answerable questions that retrieve the right fact; in this deterministic pipeline, it coincides with correctness on those 9 items
FixesOut of the 4 planted errors, how many are corrected in the final retrieved output
True facts lostOut of the 5 originally correct note facts, how many are missing or wrong under the current strategy's readable output
Transcript facts lostOut of the 9 sourced facts, how many fail to survive into the final wiki
Injected bytes / tokensCounts only text loaded at session startup; topic-page reads are counted separately

So "evidence hit" here is a narrow "correct-evidence hit rate," not a general retriever's Recall@K ranking benchmark. The fact loss shown on the index-only row reflects loss of currently visible information, not deletion of wiki files from disk.

head_only() enforces both a 200-line cap and a 25,000-byte cap. I explicitly use decimal KB here and avoid splitting multi-byte UTF-8 characters. The official docs state 25KB; this post does not verify whether Claude Code internally counts decimal or binary kilobytes, nor does it claim byte-for-byte parity with its loader. In this dataset, the line limit triggers first anyway, so that distinction does not affect the result.

Token counts are computed locally with tiktoken's cl100k_base encoding—strictly a consistent proxy metric, not Claude's tokenizer or API billing count. The script also includes boundary assertions for line count, byte count, and multi-byte UTF-8 character truncation.

6.3 Full Code

Save the script below as memory_loop.py. Its temporary directory is cleaned up automatically when the run finishes; no external data preparation is required—data generation, session appends, offline consolidation, retrieval, and evaluation are all self-contained.

python3 -m venv .venv
.venv/bin/pip install tiktoken==0.14.0
.venv/bin/python memory_loop.py

Fetching the public BPE vocabulary on first run may require network access, but no API key is needed. The rule-based pipeline itself makes no model API calls.

# Custom illustrative experiment, not an official implementation; handles only the structured evidence schema defined in this script.
import json
import re
import tempfile
from pathlib import Path
from importlib.metadata import version
import tiktoken

ENC = tiktoken.get_encoding('cl100k_base')  # proxy count, not Claude's tokenizer
LINE_LIMIT, BYTE_LIMIT = 200, 25_000  # this experiment explicitly uses decimal KB


def head_only(text, lines=LINE_LIMIT, byte_limit=BYTE_LIMIT):
    data = ''.join(text.splitlines(keepends=True)[:lines]).encode('utf-8')
    return data[:byte_limit].decode('utf-8', errors='ignore')


def measure(text):
    return len(text.encode('utf-8')), len(ENC.encode(text))


def append_json(path, rows):
    with path.open('a', encoding='utf-8') as f:
        for row in rows:
            f.write(json.dumps(row, ensure_ascii=False) + '\n')


def load_json(path):
    return [json.loads(line) for line in path.read_text().splitlines()]


def session(root, name, facts, notes):
    # facts: (topic, key, verified tool/user value, raw note value)
    transcript, raw = [], []
    for i, (topic, key, value, note) in enumerate(facts):
        src = f'{name}:{i}'
        transcript.append(dict(id=src, role='tool', topic=topic,
                               key=key, value=value, verified=True))
        raw.append(dict(topic=topic, key=key, value=note, source=src))
    raw.extend(notes)
    append_json(root / 'transcripts.jsonl', transcript)
    append_json(root / 'notes.jsonl', raw)


def render_raw(rows):
    return ''.join(f"FACT\t{r['key']}\t{r['value']}\t{r['source']}\n" for r in rows)


def parse_facts(text):
    result = {}
    for line in text.splitlines():
        fields = line.split('\t')
        if len(fields) == 4 and fields[0] == 'FACT':
            result[fields[1]] = fields[2]  # simple last-write-wins baseline
    return result


def dream(root):
    rows = load_json(root / 'notes.jsonl')
    events = load_json(root / 'transcripts.jsonl')
    # This experiment trusts only tool/user records marked verified; real systems cannot trust arbitrary labels.
    evidence = {e['id']: e for e in events
                if e['verified'] and e['role'] in ('tool', 'user')}
    unique, seen = [], set()
    for row in rows:
        identity = tuple(row[k] for k in ('topic', 'key', 'value', 'source'))
        if identity not in seen:
            seen.add(identity)
            unique.append(row)
    pages, corrected, quarantine, audit = {}, 0, [], []
    for row in unique:
        event = evidence.get(row['source'])
        if not event or (event['topic'], event['key']) != (row['topic'], row['key']):
            quarantine.append(row)
            continue
        if row['value'] != event['value']:
            corrected += 1
            audit.append(dict(key=row['key'], old=row['value'],
                              new=event['value'], source=event['id']))
        pages.setdefault(row['topic'], {})[row['key']] = event
    wiki = root / 'wiki'
    wiki.mkdir()
    index = '# Memory index\nVerified topics; read linked pages on demand.\n'
    for topic, facts in sorted(pages.items()):
        page = f'# {topic}\n[Back](../MEMORY.md)\n'
        for key, event in sorted(facts.items()):
            page += f"FACT\t{key}\t{event['value']}\t{event['id']}\n"
        (wiki / f'{topic}.md').write_text(page, encoding='utf-8')
        index += f"- [{topic}](wiki/{topic}.md): {', '.join(sorted(facts))}\n"
    (root / 'MEMORY.md').write_text(index, encoding='utf-8')
    (root / 'audit.json').write_text(json.dumps(audit, indent=2), encoding='utf-8')
    (root / 'quarantine.json').write_text(json.dumps(quarantine), encoding='utf-8')
    return index, corrected, len(rows) - len(unique), len(quarantine)


def retrieve(root, index, key):
    for line in index.splitlines():
        match = re.fullmatch(r'- \[([a-z]+)\]\(wiki/([a-z]+)\.md\): (.+)', line)
        if match and key in match[3].split(', '):
            text = (root / 'wiki' / f'{match[2]}.md').read_text()
            return parse_facts(text).get(key), text
    return None, ''


def main():
    with tempfile.TemporaryDirectory(prefix='memory-loop-') as tmp:
        root = Path(tmp)
        repeat = dict(topic='ops', key='ops.health', value='/healthz', source='s1:3')
        session(root, 's1', [
            ('go', 'go.timeout', '30s', '300s'),
            ('frontend', 'frontend.test', 'pnpm test', 'pnpm test'),
            ('go', 'go.retry', 'idempotent-only', 'all-posts'),
            ('ops', 'ops.health', '/healthz', '/healthz'),
        ], [dict(repeat) for _ in range(210)])
        session(root, 's2', [
            ('go', 'go.shutdown', '10s', '60s'),
            ('frontend', 'frontend.build', 'pnpm build', 'pnpm build'),
            ('ai', 'ai.retention', '7d', '30d'),
        ], [])
        session(root, 's3', [
            ('ops', 'ops.deploy', 'canary', 'canary'),
            ('ai', 'ai.embedding', 'local', 'local'),
        ], [dict(topic='ai', key='ai.pii', value='allowed', source='missing')])
        # Independent question set used only for evaluation, not passed to dream(); None means abstaining is the right behavior.
        questions = [
            ('Go request timeout?', 'go.timeout', '30s'),
            ('Frontend test command?', 'frontend.test', 'pnpm test'),
            ('Which requests are allowed to retry?', 'go.retry', 'idempotent-only'),
            ('Health check path?', 'ops.health', '/healthz'),
            ('Graceful shutdown wait?', 'go.shutdown', '10s'),
            ('Frontend build command?', 'frontend.build', 'pnpm build'),
            ('How long are AI logs retained?', 'ai.retention', '7d'),
            ('Deployment strategy?', 'ops.deploy', 'canary'),
            ('Where are embeddings computed?', 'ai.embedding', 'local'),
            ('Is logging PII allowed?', 'ai.pii', None),
        ]
        notes = load_json(root / 'notes.jsonl')
        raw = render_raw(notes)
        index, corrected, duplicates, quarantined = dream(root)
        injected = head_only(index)
        all_wiki = '\n'.join(p.read_text() for p in sorted((root / 'wiki').glob('*.md')))
        truth = {key: expected for _, key, expected in questions if expected is not None}
        original_true = {k for k, v in parse_facts(raw).items() if truth.get(k) == v}
        final = parse_facts(all_wiki)
        assert all(final.get(k) == v for k, v in truth.items())
        assert corrected == 4 and len(original_true) == 5
        # Truncation boundary tests; does not claim byte-for-byte parity with Claude Code's internal loader.
        assert head_only('x\n' * 201).count('\n') == 200
        assert len(head_only('x' * 26000).encode()) == BYTE_LIMIT
        assert head_only('\u6c49' * 10, byte_limit=4) == '\u6c49'
        print(f'Python local; tiktoken={version("tiktoken")}; encoding=cl100k_base')
        print(f'sessions=3 notes={len(notes)} duplicates_removed={duplicates}')
        print(f'corrected={corrected}/4 quarantined={quarantined}')
        print(f'true_note_facts_lost={sum(final.get(k) != truth[k] for k in original_true)}/{len(original_true)}')
        print(f'transcript_true_facts_lost={sum(final.get(k) != v for k, v in truth.items())}/{len(truth)}')
        print('mode | injected_bytes | proxy_tokens | lines | accuracy | evidence_hit | fixes | true_lost | read_bytes | read_proxy_tokens')
        for mode, text in [('raw-full', raw), ('raw-head', head_only(raw)),
                           ('index-only', injected), ('index+wiki', injected)]:
            correct = hits = fixes = read_bytes = read_tokens = 0
            answers = {}
            available = parse_facts(text)
            for _, key, expected in questions:
                if mode == 'index+wiki':
                    answer, page = retrieve(root, text, key)
                    read_bytes += len(page.encode())
                    read_tokens += len(ENC.encode(page))
                else:
                    answer = available.get(key)
                answers[key] = answer
                fixes += key in {'go.timeout', 'go.retry', 'go.shutdown', 'ai.retention'} and answer == expected
                correct += answer == expected
                hits += expected is not None and answer == expected
            nbytes, ntokens = measure(text)
            print(f'{mode} | {nbytes} | {ntokens} | {len(text.splitlines())} | '
                  f'{correct}/10 | {hits}/9 | {fixes}/4 | '
                  f'{sum(answers.get(k) != truth[k] for k in original_true)}/5 | '
                  f'{read_bytes} | {read_tokens}')
        wiki_bytes = sum(p.stat().st_size for p in (root / 'wiki').glob('*.md'))
        print(f'wiki_storage_bytes={wiki_bytes}; boundary_tests=PASS')
        print('question | raw-full | raw-head | index+wiki')
        for question, key, _ in questions:
            a = parse_facts(raw).get(key)
            b = parse_facts(head_only(raw)).get(key)
            c, _ = retrieve(root, injected, key)
            print(f'{question} | {a} | {b} | {c}')
        # Temporary directory is used only for reproducibility; no real user memory is read.


if __name__ == '__main__':
    main()

6.4 Actual Output

Below is the output from running the script; read_bytes and read_proxy_tokens reflect cumulative on-demand page reads across the entire question set, excluding startup injection and without page caching.

Python local; tiktoken=0.14.0; encoding=cl100k_base
sessions=3 notes=220 duplicates_removed=210
corrected=4/4 quarantined=1
true_note_facts_lost=0/5
transcript_true_facts_lost=0/9
mode | injected_bytes | proxy_tokens | lines | accuracy | evidence_hit | fixes | true_lost | read_bytes | read_proxy_tokens
raw-full | 6593 | 2845 | 220 | 5/10 | 5/9 | 0/4 | 0/5 | 0 | 0
raw-head | 5999 | 2595 | 200 | 3/10 | 2/9 | 0/4 | 3/5 | 0 | 0
index-only | 269 | 75 | 6 | 1/10 | 0/9 | 0/4 | 5/5 | 0 | 0
index+wiki | 269 | 75 | 6 | 10/10 | 9/9 | 4/4 | 0/5 | 872 | 338
wiki_storage_bytes=380; boundary_tests=PASS
question | raw-full | raw-head | index+wiki
Go request timeout? | 300s | 300s | 30s
Frontend test command? | pnpm test | pnpm test | pnpm test
Which requests are allowed to retry? | all-posts | all-posts | idempotent-only
Health check path? | /healthz | /healthz | /healthz
Graceful shutdown wait? | 60s | None | 10s
Frontend build command? | pnpm build | None | pnpm build
How long are AI logs retained? | 30d | None | 7d
Deployment strategy? | canary | None | canary
Where are embeddings computed? | local | None | local
Is logging PII allowed? | allowed | None | None

6.5 Breaking Down the Results Without Moving the Goalposts

StrategyStartup BytesProxy TokensAccuracyEvidence HitFixesReadable Correct Note Facts Lost
Full raw notes raw-full659328455/105/90/40/5
Head-truncated raw notes raw-head599925953/102/90/43/5
Index only, no reads index-only269751/100/90/45/5
Index + on-demand reads index+wiki2697510/109/94/40/5

Start with the untruncated baseline. raw-full already receives every raw note, yet it still carries 4 errors and 1 unsourced assertion, scoring 5/10. Offline consolidation brings that to 10/10, showing that the error-correction gain here does not merely come from "reading further down the file."

Next, compare under the same head-truncation rule. Both raw-head and the index pass through the exact same head_only() function (200 lines / 25,000 bytes), yet their actual footprints differ sharply: raw-head is capped at the first 200 lines, where repeated health-check entries crowd out the build, deployment, and embedding facts recorded later. The index costs only 269 bytes and 75 proxy tokens at startup—much smaller than the raw head's 5,999 bytes and 2,595 proxy tokens—while routing queries to the right topic page. Note that those 269 bytes cover only the startup-injected index itself, with zero topic-page content; 10/10 is the result of index+wiki, not the index alone.

An index is not an answer. When topic-page reads are disabled, only abstention on the unsourced question succeeds, yielding 1/10. Including this control keeps us from mistaking file pointers for knowledge the model already holds.

You still pay for reads. Across the 10 questions, index+wiki reads a cumulative 872 bytes and 338 proxy tokens on demand; the same topic page can be read multiple times by different questions without caching. Under a "fresh session per question" accounting model, total context is 269 startup bytes per question plus that question's reads—not a single startup injection amortized over all 10 questions. Doing the arithmetic from the measured run above: index+wiki totals 10 × 269 + 872 = 3,562 bytes (10 × 75 + 338 = 1,088 proxy tokens), compared to 10 × 6,593 = 65,930 bytes (28,450 proxy tokens) for raw-full and 10 × 5,999 = 59,990 bytes (25,950 proxy tokens) for raw-head. Those totals are derived arithmetically from the same run rather than measured separately, and neither bytes nor cl100k_base proxy tokens equal Claude's tokenizer or billing. Furthermore, because the index lists every key per topic and the question-to-key mapping is hardcoded, routing here is exact match—heavily favoring index+wiki. A real agent has to decide which page to open and may open the wrong page or read extra pages. No real LLM invocation cost or end-to-end latency was measured here.

Error correction did not come at the expense of good facts. The full wiki retains all 5/5 originally correct note facts, and against the full transcript it retains all 9/9 trusted facts—losses of 0/5 and 0/9 respectively. Quarantining the unsourced PII claim is refusing an unverified promotion, not losing a verified fact. The topic pages occupy 380 bytes on disk, and the raw JSONL files are never overwritten by consolidation.

Finally, why do these numbers look so clean? Because we engineered complete provenance, alignable fields, and decidable errors, and hardcoded the question-to-key mapping. The script never faces a real agent's salience choices or semantic ambiguity. 100% is strictly a property of this fixture and cannot be compared to official CL-Bench, Stainless, or Harvey scores.

6.6 What Breaks When You Swap in an LLM Dreamer

A real LLM dreamer can hunt for evidence inside free-form natural-language transcripts, infer when multiple notes refer to the same entity, build conceptual links, and reorganize memory structure—none of which string equality can do.

The trade-off is that it can also merge similar-but-distinct facts, flatten away uncertainty, cite nonexistent sources, or produce cleaner-reading yet less accurate summaries. Because my script has none of those capabilities, it does not measure those risks. The moment you replace deterministic functions with model calls, you need to re-evaluate at least:

  • Retention of originally correct facts, not just how many errors were fixed.
  • Abstention when evidence is absent, plus false "corrections" triggered by bad sources.
  • Fact freshness and scope, rather than naive last-write-wins.
  • Whether the agent actually uses the right evidence after retrieving it.
  • Offline consolidation cost in tokens, wall-clock time, and regression rate.

In this experiment, verified=True was minted by our own harness—a model cannot earn trust by stamping a label on itself. In production systems, source identity and authorization boundaries must be enforced by the harness or storage layer.


7. Design Recommendations: Treat Memory as Auditable Derived Data

The engineering recommendations below are my own synthesis from the original post's case studies and docs—not an official reference implementation from Anthropic.

7.1 Separate Raw Records, Staging Notes, and Published Views

Treat transcripts as traceable event logs, notes as potentially fallible staging data, and the wiki/index as rebuildable derived views. Have offline jobs write a new candidate version, run integrity checks and regression questions against it, and only then promote that version for subsequent sessions.

That way, even if dreaming itself introduces an error, you can rebuild from primary sources rather than letting the latest summary become the sole source of truth. The Managed Agents docs likewise support writing consolidation outputs to a new output store; having version auditing does not let you skip regression verification.

7.2 Make Fact Status and Scope Explicit

A memory entry should ideally answer: is this an observation or an inference, who verified it, which tool result produced it, which project or environment does it apply to, and when was it last confirmed?

Error correction should also distinguish four cases:

  • Wrong from the start: e.g., misreading a landmark.
  • Right at the time, now stale: e.g., a config or contract changed later.
  • Insufficient evidence: merely an agent's guess.
  • Different scope: a staging-environment fact must not overwrite production.

The experiment above covers only the first case plus unsourced quarantine, not the remaining conflict types.

7.3 Write Protocols Must Prevent Overwrites; Summary Protocols Must Protect Exactness

Harvey's failure was not just "sloppy summarization"—it also involved concurrent writes colliding on a shared page. Partition ownership by entity with a single writer per page, let dedicated topic pages carry the detail, and aggregate indexes in a separate pass.

If concurrent edits are allowed, the storage interface needs version or content-hash preconditions; on conflict, re-read and merge instead of blindly retrying and clobbering prior writes. For high-fidelity material like contract clauses, store locatable verbatim excerpts first and keep interpretations separate from quotes.

7.4 Automate Injection Budget Checks Instead of Relying on Author Discipline

Check index byte size, line count, and link reachability automatically; put critical navigation at the top; reorganize when you approach the budget instead of endlessly appending. Regression suites should test the raw baseline, the index-plus-retrieval combo, and a no-drill-down control side by side.

At a minimum, your checks should catch two distinct regressions: wrong answers, and answers that stay right while startup or retrieval costs quietly blow up. Because this post did not measure real tokenizers, latency, or dollar costs, do not extrapolate production ROI from these numbers.

7.5 Memory Is Not a Privilege-Escalation Channel

The Managed Agents docs explicitly warn that if an agent processing untrusted input has write access, a successful prompt injection can plant malicious content in the store, which later sessions then read back as trusted memory. Put shared reference material in read-only stores and grant write permissions only where needed.

Similarly, the Memory tool docs require applications to validate file paths so operations stay strictly within the permitted memory root, and to manage sensitive data, file sizes, and expiration.

By the same token, dreaming must preserve source trust levels rather than laundering instructions from a random web page into global rules via "summarization," and user data must stay isolated from project data. Remembering something does not turn it into authorization.

7.6 Prioritize What to Consolidate by Risk Before Choosing a Cadence

The original post acknowledges that continuously re-checking all memory may be impractical, suggesting a focus on volatile information or tuning dreaming cadence by access frequency. I would additionally prioritize recently contradicted notes, heavily injected rules, write conflicts, broken links, and topics that frequently force the agent to drill back into raw sources.

That makes cost bounds much easier to enforce than "periodically rewrite every file," though any concrete scheduling policy still needs validation against your own access logs—this post did not run cadence or scale experiments.


8. My Take

  1. The real lesson is separation of concerns, not the "dreaming" metaphor. Capture what matters in the moment online, verify with a wider view offline, and inject only the necessary entry points at session start. Those three stages have different goals and should not be crammed into one ever-growing MEMORY.md.

  2. Memory quality is verified future utility, not write volume. Moving from guesses to verified rules in CL-Bench and from state logs to strategy dashboards in Pokémon both cut wasted work on the next decision. Trimming noise matters, and preserving precision matters just as much—Harvey's contract facts are a clear reminder that shorter abstractions are not always better.

  3. Pitting wiki against search misreads Stainless. The strongest setup in the original post is wiki plus search, not wiki alone. The knowledge map tells the agent where to look; search takes it back to primary evidence where the map stops. Being able to check sources and fix mistakes is far more reliable than pretending "everything lives in memory."

  4. My experiment tests the pipeline, not intelligence. It did produce 4/4 error fixes, 0/5 loss of originally correct note facts, and a 269-byte startup index, and it showed that injecting an index without reading pages cannot answer questions. It does not prove a rule engine can replace LLM dreaming, nor does it reproduce any official benchmark.

  5. The next thing to test is messy evidence and time, not prettier directories. Introduce conflicting tool outputs, real configuration changes, similar-but-distinct entities, missing provenance, and adversarial text—then measure whether consolidation ends up corrupting good memories. Only after those regressions hold is it worth porting the loop to a real agent.


References

  • Anthropic: The components of agent memory (2026-11-06) — Source for all official case studies, model observations, and benchmark numbers in this post; read in full.
  • Claude Code: How Claude remembers your project — Verified auto memory's head-truncation cap, on-demand loading of topic pages, and instruction-adherence caveats; product documentation may evolve over time.
  • Claude API: Memory tool — Client-side persistence, path validation, and security considerations.
  • Claude Managed Agents: Memory stores — Directory mounting, version auditing, concurrency preconditions, read/write isolation, and memory-poisoning warnings.
  • CL-Bench 1.0 release announcement — Reviewed release page; task details and model results in this post come from Anthropic's article, with no claim of independent benchmark reproduction.
  • Harvey LAB repository — Reviewed project page; this post did not run the tasks or inspect the full dataset, and relies on Anthropic's article for reported results.
  • Google Research: The sleep framework — Linked from the original post and reviewed; it deals with parametric memory updates, which should not be conflated with offline consolidation of external text memory discussed here, and none of its benchmark numbers are cited in this post.

Related Posts