Lab: Compaction for a Fifty-Step Task
Keep a long agent run inside a fixed token budget with three levers, cheapest first: clear stale tool results behind a stub, keep notes in a file outside the context window, and summarise the history into a structured checkpoint only when the first two are not enough.
Contentsand lesson path
On this page
- Why Long Runs Outgrow the Window, and Three Levers to Fix It
- Mechanics: Triggers, Turn Groups and the Compactor
- Lab: A 50-Step Audit with All Three Levers
- Practice
- Apply it
- Review prompt
Lessons of Memory & Context Engineering
- Context as a Scarce Resource Concept · 15 min
- Building a Per-Step Context Assembler Worked example · 20 min
- Lab: Compaction for a Fifty-Step Task Lab · 25 min
- Loading Tools and Skills on Demand Worked example · 15 min
- A Long-Term Memory Store with Write and Expiry Policies Lab · 25 min
- Check: Context and Memory Design Review Knowledge check · 8 questions
What you will learn
- Keep long runs within budget with compaction: summarizing history, clearing stale tool results and keeping notes outside the context window.
Prerequisites: Tokens & Context
01. Why Long Runs Outgrow the Window, and Three Levers to Fix It
Agents that audit ledgers or migrate a repository often need fifty or more tool calls. Every call adds its result to the history, so by step 15 or 20 the file reads and logs fill the context window. Quality often drops before the hard limit: the agent repeats work or forgets a decision made ten steps earlier. Cost grows too: each call re-sends the whole history, so total tokens grow roughly with the square of the step count.
Compaction means keeping a long run inside a budget by shrinking what the context holds. There are three levers. They differ in cost and in what they lose, so use the cheapest first:
- Clear stale tool results. Once the agent has acted on a raw result, such as a file it read or a log it scanned, replace that result with a short stub:
[cleared: result of read_file(a.py), 4,200 tokens; call again to re-read]. Keep the tool call itself, so every call still has a result and the record of what the agent did stays complete. It needs no model call, and the data can be fetched again. The Claude API offers this as context editing (strategyclear_tool_uses_20250919); you can do the same in your own loop. - Keep notes outside the context window. The agent writes what it must not forget (decisions, IDs, findings, and a to-do list of what is done and what is left) to a file such as
notes.mdor a memory store, and reads it back when it needs it, for example after each compaction. The notes live on disk, so clearing and summarising cannot change them. - Summarise the history. When the first two levers are not enough, a model condenses older turns into a structured checkpoint, and those turns are removed from the context. This is lossy: each summary can drop a detail whose importance only shows later, and errors compound across repeated compactions. Keep the full raw transcript in storage so a fact can be looked up again.
Clearing has a limit: every stub still costs a few tokens, so on a very long run the stubs themselves fill the window. That is when summarising earns its cost. The lab runs all three levers on the same task.
02. Mechanics: Triggers, Turn Groups and the Compactor
The simplest reduction, a sliding window, drops the oldest turns when space runs low. It often drops the original goal or an early discovery, and the agent repeats work or breaks a constraint. The compactor in this lab works in four steps instead:
- Trigger. After each tool call, count the tokens of the assembled context. When they reach the threshold (6,000 tokens in an 8,192-token window here), act. The gap leaves room for the next observation and the model's answer.
- Partition. Split the history into old turn groups and the newest three. A turn group is an assistant tool call plus its tool result. Never split one: a tool result without its call is rejected by the API.
- Clear, then summarise if needed. First replace the results of the old groups with stubs. Only if the context is still above half the threshold, merge the old groups into the checkpoint with a summary prompt.
- Rebuild. The next context is the system prompt, the checkpoint, the notes and the remaining groups.
"""Three levers for long runs: clear old tool results, then summarise."""
import math
def count_tokens(messages):
return sum(math.ceil(len(m["content"]) / 4) + 4 for m in messages)
class RecursiveCompactor:
def __init__(self, goal, threshold=6000):
self.threshold = threshold
self.checkpoint = f"GOAL: {goal}"
self.groups = [] # each group: assistant call + its tool result
def context(self, system, notes=""):
head = "Checkpoint:\n" + self.checkpoint
if notes:
head += "\nNotes (re-read from notes.md):\n" + notes
return ([{"role": "system", "content": system},
{"role": "user", "content": head}]
+ [m for g in self.groups for m in g])
def should_compact(self, system, notes=""):
return count_tokens(self.context(system, notes)) >= self.threshold
def clear_tool_results(self, keep_recent=3):
"""Lever 1: swap old results for a stub; keep the call, so pairs stay valid."""
cleared = 0
for call, result in self.groups[:-keep_recent]:
if not result["content"].startswith("[cleared"):
size = count_tokens([result])
result["content"] = (f"[cleared: result of {call['content']}, "
f"{size} tokens; call again to re-read]")
cleared += 1
return cleared
def compact(self, summarize, keep_recent=3):
"""Lever 3: fold old groups into the checkpoint. Lossy: test what survives."""
if len(self.groups) <= keep_recent:
return False
old, self.groups = self.groups[:-keep_recent], self.groups[-keep_recent:]
self.checkpoint = summarize(self.checkpoint, [m for g in old for m in g])
return True03. Lab: A 50-Step Audit with All Three Levers
You run a ledger audit in an 8,192-token window with a 6,000-token trigger. Each step returns about 270 tokens of ledger rows, and six steps hide one line that matters later: a failed endpoint, an account ID, a decision, two findings and an open question. You will compare a summary-only run, a bare summary, and the three levers together.
You need: Python 3.12 or later, standard library only, no API key. Tested with Python 3.12.13. Create a folder compaction-lab, save compactor.py from above into it, add the four files below and run every command from inside the folder. The summariser and note-taker are offline stand-ins that pick tagged lines, so every run prints the same result. In a real agent the model writes the summary from SUMMARY_PROMPT and calls a write_note tool.
compaction-lab/
├── compactor.py turn groups, clear_tool_results(), compact()
├── audit_tools.py step 1: noisy observations with six key lines
├── notes.py step 2: notes.md, written and re-read by the agent
├── summarizer.py step 3: the rubric prompt and an offline stand-in
└── run_compaction.py step 4: the loop, in three modesStep 1: the fixture tool. audit_step(n) returns 22 seeded ledger rows. KEY_LINES are the facts the agent must still know at the end.
"""Fixture tool: each audit step returns a long, noisy observation."""
import random
KEY_LINES = { # the few lines a good summary must keep
3: "DO-NOT-RETRY: GET /v1/ledger/export returned 403 (no scope)",
7: "ID: subsidiary NL-04 posts to ledger L-7781",
12: "DECISION: convert with ECB FY2025 rates from fx_2025.csv",
21: "FINDING: vendor V-19 billed invoice INV-3302 twice",
33: "FINDING: NL-04 transfer of EUR 48,000 has no approval record",
44: "OPEN: confirm whether INV-3302 was refunded",
}
def audit_step(step):
rng = random.Random(f"audit|{step}")
rows = [f"row {i}: acct {rng.randrange(10**6):06d} amount "
f"{rng.uniform(10, 9999):9.2f} status ok" for i in range(22)]
tagged = [KEY_LINES[step]] if step in KEY_LINES else []
return "\n".join([f"[audit step {step}] scanned 22 ledger rows", *rows, *tagged])Step 2: the notes file. notes.md holds a progress line (the to-do: what is done, what is left) and every tagged line the agent has seen. It is a real file, so it outlives the context and even the process.
"""Lever 2: a notes file outside the context window, re-read when needed."""
from pathlib import Path
TAGS = ("DECISION", "ID", "FINDING", "DO-NOT-RETRY", "OPEN")
class NotesFile:
def __init__(self, path="notes.md"):
self.path = Path(path)
self.path.write_text("PROGRESS: not started\n") # a fresh run starts clean
def read(self):
return self.path.read_text().strip()
def record(self, step, total, observation):
"""Stand-in for the model calling a write_note tool on lines that matter."""
lines = self.read().splitlines()
lines[0] = f"PROGRESS: audit_step 1-{step} done, {total - step} to go"
for line in observation.splitlines():
if line.split(":", 1)[0] in TAGS and line not in lines:
lines.append(line)
self.path.write_text("\n".join(lines) + "\n")Step 3: the summariser. The prompt names fixed sections: goal, decisions, IDs, findings, failed actions not to retry, and open questions. Anything outside a section is dropped. naive_summarize imitates what a bare "summarise what happened" prompt often returns.
"""The compaction prompt, plus an offline stand-in that follows the same rubric."""
SECTIONS = ("GOAL", "DECISION", "ID", "FINDING", "DO-NOT-RETRY", "OPEN")
SUMMARY_PROMPT = """Update the checkpoint for a long-running audit agent.
Merge the previous checkpoint with the new turns. Output exactly these sections:
GOAL, DECISION (choices made and why), ID (names, accounts, file paths),
FINDING (verified facts), DO-NOT-RETRY (failed actions and why), OPEN (questions).
Keep every item of the previous checkpoint unless a new turn resolves it.
Copy IDs and numbers exactly. Drop raw rows, logs and anything not in a section.
Previous checkpoint:
{checkpoint}
New turns:
{turns}"""
def fake_summarize(checkpoint, turns):
"""Stand-in for model(SUMMARY_PROMPT.format(...)): keeps only tagged lines."""
text = checkpoint + "\n" + "\n".join(m["content"] for m in turns)
kept = {s: [] for s in SECTIONS}
for line in text.splitlines():
head = line.split(":", 1)[0]
if head in kept and line not in kept[head]:
kept[head].append(line)
return "\n".join(line for s in SECTIONS for line in kept[s])
def naive_summarize(checkpoint, turns):
"""What a bare "summarise what happened" prompt often returns."""
goal = checkpoint.splitlines()[0]
return f"{goal}\nRan {len(turns) // 2} more audit steps; scanned rows were ok."Step 4: the loop. Each step appends one turn group and measures the context. At the threshold, summary and naive summarise at once; levers clears old results first and summarises only if clearing left more than half the threshold. The assert fails the run if the window would overflow.
"""A long audit in an 8,192-token window with a 6,000-token trigger.
python3 run_compaction.py summary lever 3 only, rubric summary
python3 run_compaction.py naive lever 3 only, bare summary
python3 run_compaction.py levers clear results first, keep notes, summarise last
"""
import sys
from audit_tools import KEY_LINES, audit_step
from compactor import RecursiveCompactor, count_tokens
from notes import NotesFile
from summarizer import fake_summarize, naive_summarize
SYSTEM = "You are an audit agent. Call audit_step(n) for n = 1..N, then report."
WINDOW, THRESHOLD = 8192, 6000
mode = sys.argv[1] if len(sys.argv) > 1 else "summary"
steps = int(sys.argv[2]) if len(sys.argv) > 2 else 50
summarize = naive_summarize if mode == "naive" else fake_summarize
notes = NotesFile() if mode == "levers" else None
agent = RecursiveCompactor(f"audit FY2025 ledgers for {steps} steps", THRESHOLD)
peak = clears = summaries = 0
def size():
return count_tokens(agent.context(SYSTEM, notes.read() if notes else ""))
for step in range(1, steps + 1):
observation = audit_step(step)
call = {"role": "assistant", "content": f"audit_step({step})"}
agent.groups.append([call, {"role": "tool", "content": observation}])
if notes:
notes.record(step, steps, observation)
before = size()
peak = max(peak, before)
assert before <= WINDOW, f"overflow at step {step}"
if before < THRESHOLD:
continue
if mode == "levers":
n = agent.clear_tool_results()
clears += 1
print(f"step {step:3}: {before:,} tokens; cleared {n} results -> {size():,}")
if size() > THRESHOLD // 2: # clearing freed too little (or was not used)
agent.compact(summarize)
summaries += 1
print(f"step {step:3}: {before:,} tokens; summarised -> {size():,}")
print(f"\nsteps={steps} peak={peak:,} final={size():,} of {WINDOW:,} tokens"
+ (f"; clearings={clears} summaries={summaries}" if mode == "levers" else ""))
print("checkpoint:\n " + agent.checkpoint.replace("\n", "\n "))
kept = agent.checkpoint + str(agent.groups) + (notes.read() if notes else "")
lost = [line for line in KEY_LINES.values() if line not in kept]
print(f"key lines lost: {len(lost)}")
for line in lost:
print(" -", line)
if notes:
print("oldest group:", agent.groups[0][1]["content"])
in_notes = sum(line in notes.read() for line in KEY_LINES.values())
print(f"key lines in notes.md: {in_notes} of {len(KEY_LINES)}")python3 run_compaction.py summarystep 22: 6,208 tokens; summarised -> 926
step 41: 6,223 tokens; summarised -> 941
steps=50 peak=6,223 final=3,454 of 8,192 tokens
checkpoint:
GOAL: audit FY2025 ledgers for 50 steps
DECISION: convert with ECB FY2025 rates from fx_2025.csv
ID: subsidiary NL-04 posts to ledger L-7781
FINDING: vendor V-19 billed invoice INV-3302 twice
FINDING: NL-04 transfer of EUR 48,000 has no approval record
DO-NOT-RETRY: GET /v1/ledger/export returned 403 (no scope)
key lines lost: 0Summarising ran twice and each time the context fell from about 6,200 tokens to about 930. All six key lines survived: five in the checkpoint and the step-44 open question in the recent turns. Now try the bare summary:
python3 run_compaction.py naivestep 22: 6,208 tokens; summarised -> 898
step 41: 6,195 tokens; summarised -> 885
steps=50 peak=6,208 final=3,398 of 8,192 tokens
checkpoint:
GOAL: audit FY2025 ledgers for 50 steps
Ran 19 more audit steps; scanned rows were ok.
key lines lost: 5
- DO-NOT-RETRY: GET /v1/ledger/export returned 403 (no scope)
- ID: subsidiary NL-04 posts to ledger L-7781
- DECISION: convert with ECB FY2025 rates from fx_2025.csv
- FINDING: vendor V-19 billed invoice INV-3302 twice
- FINDING: NL-04 transfer of EUR 48,000 has no approval recordThe token numbers barely change, but five key lines are gone. Token counts alone would call this run a success, so test summaries against facts you know must survive.
Step 5: clear first, keep notes. Run the same audit with the three levers, then look at the notes file the run left on disk:
python3 run_compaction.py levers
cat notes.mdstep 21: 6,001 tokens; cleared 18 results -> 1,497
step 38: 6,253 tokens; cleared 17 results -> 2,009
steps=50 peak=6,253 final=5,367 of 8,192 tokens; clearings=2 summaries=0
checkpoint:
GOAL: audit FY2025 ledgers for 50 steps
key lines lost: 0
oldest group: [cleared: result of audit_step(1), 270 tokens; call again to re-read]
key lines in notes.md: 6 of 6
PROGRESS: audit_step 1-50 done, 0 to go
DO-NOT-RETRY: GET /v1/ledger/export returned 403 (no scope)
ID: subsidiary NL-04 posts to ledger L-7781
DECISION: convert with ECB FY2025 rates from fx_2025.csv
FINDING: vendor V-19 billed invoice INV-3302 twice
FINDING: NL-04 transfer of EUR 48,000 has no approval record
OPEN: confirm whether INV-3302 was refundedClearing alone kept 50 steps inside the budget: no summary call was made, and each tool call is still in the history with a stub that says how to get its data back. The checkpoint holds only the goal, because the key lines were in results that are now cleared. They are not lost: the agent copied each one to notes.md when it saw it, and the progress line tells a resumed agent where to continue.
Step 6: a longer run. Each clearing frees less than the one before, because the stubs stay. Run 120 steps to see where summarising takes over:
python3 run_compaction.py levers 120step 21: 6,001 tokens; cleared 18 results -> 1,497
step 38: 6,254 tokens; cleared 17 results -> 2,010
step 53: 6,202 tokens; cleared 15 results -> 2,471
step 66: 6,085 tokens; cleared 13 results -> 2,861
step 78: 6,197 tokens; cleared 12 results -> 3,221
step 78: 6,197 tokens; summarised -> 971
step 97: 6,253 tokens; cleared 19 results -> 1,541
step 114: 6,267 tokens; cleared 17 results -> 2,051
steps=120 peak=6,267 final=3,719 of 8,192 tokens; clearings=7 summaries=1
checkpoint:
GOAL: audit FY2025 ledgers for 120 steps
key lines lost: 0
oldest group: [cleared: result of audit_step(76), 270 tokens; call again to re-read]
key lines in notes.md: 6 of 6At step 78 clearing left more than 3,000 tokens, so the loop summarised the old groups and stubs, and the cycle started again. The summary kept no key lines (their results were already cleared), but the notes file kept all six. Clear first, write down what matters, and summarise only when the cheaper levers stop freeing enough.
04. Practice
05. Apply it
For the skill practice, run your own agent on a task of more than 40 steps and add the levers in this order:
- Clear first. Replace tool results the agent has acted on with a stub naming the call and its size; keep the call. If your provider offers context editing, compare it with your own clearing.
- Give the agent a notes file. Add
write_noteandread_notestools (or a memory tool), ask the agent to record decisions, IDs, failures and a to-do list, and re-read the notes after every compaction. - Summarise last, with a rubric. Use named sections, keep IDs verbatim, and keep the raw transcript in storage.
- Log every compaction. Record tokens before and after, and which lever ran, so a runaway checkpoint or stubs that free too little show up.
Keep a small test set like the lab's key lines and check after every prompt or model change that they still survive.
06. Review prompt
Without looking back, name the three compaction levers in the order you would use them, and say what each one costs and what it can lose. Why does the stub keep the tool call? Why did the 120-step run summarise at step 78 but the 50-step run never did?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.