08B.3 Short-Term Memory: Truncation, Summarization and Compaction

Agents & multimodalLesson 3 of 510,178 words9 parts
Module 08B · 0 of 5 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

A conversation grows with every turn, and the model's window does not. Short-term memory is everything you do to keep the part of the conversation that matters inside the window. This lesson builds the basic tools in plain Python (sliding window, token-aware truncation, rolling summary and tool-result management), shows with a probe test which of them forget a rule you gave early on, and then covers the agent-level material that goes with them: a result policy for bulky tool outputs, the provider features that do part of the work for you (OpenAI's server-side compaction, Anthropic's compaction and context editing, and what Gemini and OpenRouter offer instead), files and git as the memory for tasks that outlive one window, and delegating noisy work to a fresh sub-context. It follows 08B.1 (what a session holds) and comes before 08B.4 (what survives the session). The prompt-level side of the same problem (summarization prompts, keeping instructions alive, cache-aware layout, graceful limits and a full ConversationManager) stays in lesson 04.7.

What you'll learn

  • What short-term memory means for an LLM app, the simple rule for what to keep word for word and what to shrink, and where short-term ends and long-term begins
  • Sliding window (by turns), token-aware truncation and why they must never split a tool call from its result
  • Rolling summarization with a fake summarizer you can test offline, folding in batches, and why summaries drift
  • Tool-result management: clearing, truncating with a marker, digest plus handle, pagination, just-in-time retrieval and what to do with images and files in history
  • How to test any strategy with probes: a list of facts that must still be visible after trimming
  • The provider-side features as of 1 December 2026: OpenAI context_management compaction and /responses/compact, Anthropic compaction (on demand and at a threshold), Anthropic context editing and the memory tool, what Gemini and OpenRouter offer, and what each costs you in transparency and cache hits
  • Long tasks across many context windows: a task list, a progress file and git as the memory, a prescriptive start-up prompt, and when a fresh window beats compaction
  • Sub-context isolation: handing a noisy sub-task to a fresh context and taking back only a distilled result

What you don't need

  • API keys. Every strategy and every test runs offline in standard-library Python. The provider samples are labelled illustrative.
  • Docker or any service.
  • The prompt-level material. Lesson 04.7 teaches the summarization prompts, instruction re-injection, cache-aware history, graceful limits and a complete ConversationManager. This lesson is the beginner-first, agent-level version and links to 04.7 where that depth lives instead of repeating it.

Setup

Python 3.11 or newer. Nothing to install for the offline code. Illustrative provider samples only (package names, as of 1 December 2026):

bash
mkdir short-term-memory && cd short-term-memory
# offline code: nothing to install
# illustrative provider samples only: pip install openai anthropic

The files sit next to each other: short_term.py (the library), demo_short_term.py (one long chat through every strategy), eval_compaction.py (a probe test), tool_results.py and demo_tool_results.py (the result policy), progress_files.py (files as memory) and sub_context.py (delegation). Run each with python3 <file>.


What you must be able to do after this lesson#

  • Write a keep-list that names what trimming must never shorten, and apply it as pinned messages
  • Build sliding-window, token-aware truncation, rolling-summary and tool-result clearing code that never splits a tool call from its result
  • Apply a result policy that keeps, truncates or replaces a tool output with an annotated stub and a handle the model can re-fetch
  • Test a trimming strategy with probes and read the retention matrix
  • Choose between provider compaction and your own policy, and state what each costs in visibility and cache hits
  • Set up a task list, a progress file and a start-up prompt so a fresh window can continue a long task
  • Decide when to delegate a noisy sub-task to a fresh context and specify what it must return

Why this matters for an AI engineer#

Every long-running assistant hits the same wall: the history no longer fits, costs rise with each turn, or quality drops long before the window is full (04.7, 1.2). Trimming is easy to write and easy to get wrong in silent ways: the rule the user stated in turn one vanishes, a tool result is dropped but its call stays, a summary invents a fact.

You'll hear... You'll understand it after...
"Just keep the last 10 messages." Part 2, 2.3 what it forgets
"Summarise the old turns." Part 3: Rolling summarization
"Tool outputs are eating the window." Part 4: Tool-result clearing, 4.5 a result policy
"Which messages must never be dropped?" 1.3 What to keep word for word
"How do we know trimming did not break anything?" Part 5: Probes
"Should we use the provider's compaction?" Part 6: Provider-side compaction
"The agent has to remember a task for days, across many windows." Part 7: Long tasks across many windows
"Spawn a sub-agent for the research part." Part 8: Sub-context isolation
"Is this short-term or long-term memory?" 1.4 Where short-term ends and long-term begins

Part 1: What short-term memory is#

1.1 The idea#

Short-term memory is the working set of a session: the messages, tool results and notes the model can see on this call. It is the conversation state of 08B.1, and it is limited by the model's context window (the maximum number of tokens it can read in one request; see 02.7). Long-term memory (08B.4) is what survives after the session ends.

1.2 Four tools, one table#

Tool What it does Cost What it risks
Sliding window Keep the last N turns, drop the rest Free, instant Forgets early rules and facts without warning
Token-aware truncation Drop the oldest messages until the total fits a token budget Free, instant Same, plus splitting a tool call from its result if careless
Rolling summary Replace old messages with a short summary that you update as the chat grows One model call per fold The summary can drop or invent facts; repeated summaries drift
Tool-result clearing Replace old tool outputs with a short placeholder Free The model cannot re-read a cleared result, only its placeholder

They stack. A common order is: clear old tool results first (cheapest, biggest saving), summarise next, truncate only as the last resort. Lesson 04.7, 2.1 has the wider strategy table (selective retention, hierarchical summaries, structured state); this lesson builds the four that every app needs first.

1.3 What to keep word for word#

Before writing any trimming code, decide what must never be shortened. This is the part most beginners skip.

Keep verbatim Why
The system prompt and standing rules They define behaviour. Re-sent every call, never trimmed
Constraints the user stated ("never email me, phone only") A summary may soften "never" into "prefers"
Exact identifiers, amounts, dates, file paths, error messages A summary that rounds "A17" or "$40" makes the next tool call wrong
User corrections ("no, I meant Munich") The newest instruction wins and must not be averaged away
The last few turns The model needs the immediate context of what was just said
Open tool calls and their results A call without its result (or the reverse) is rejected by providers (03.2, Part 4)
The current plan or todo list Without it a long task loses its thread (08B.2, Part 2)

Things that are safe to shrink: greetings, small talk, finished sub-tasks, verbose tool output that has already been used, repeated explanations.

04.7, 3.1 turns this list into a summarization prompt. Here we implement the policy in code.

1.4 Where short-term ends and long-term begins#

Everything in this lesson manages memory inside one session. Memory across sessions is a different job with a different store and different risks, and the line between them is about time, not topic.

Short-term (inside a session) Long-term (across sessions)
Lifetime One session; it dies with the session Survives sessions
Lives in The history you re-send each call, plus session files A database or file store you own
Managed by Pin, summarise, clear, trim (this lesson) Extract, validate, store, retrieve (08B.4)
Typical content Goal, decisions, open tasks, recent detail Stable preferences, identity, durable decisions
Typical failure Drift and loss when compacting Stale, wrong or poisoned memories (08B.5, Part 1)

"My refund case is open" is short-term, because it ends when the case closes. "Prefers metric units and German replies" is long-term. A well-built system moves a fact down into long-term memory only once it proves durable, and lets the rest decay with the session. The write-back loop (extract, validate, store, retrieve, inject) and user control and deletion are taught once, in 08B.4, Part 3 and 08B.4, Part 6. What to store and what never to store (secrets, PII you do not need, instructions smuggled into data) is the write policy of 08B.2, 4.1 and the validation step of 08B.2, 6.2. Two rules carry over from there: memories are untrusted text that will be re-read later (08B.2, 6.1), and a stale memory is worse than none.


Part 2: Sliding window and token-aware truncation#

This part extends 04.7, 2.2 (windows by turns and by tokens) with a runnable library that keeps tool calls paired with their results, and with a test that shows what a window forgets. The production-sized version of the same stack is the ConversationManager in 04.7, Part 11.

2.1 The library#

This is the whole file. Read the four sections in order. Messages are plain dicts. A message can carry "pinned": True (never drop it) and a call_id (links a tool call to its result).

python
# short_term.py: four ways to keep a conversation inside a budget, in plain Python
from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Callable

Message = dict   # {"role": "user"|"assistant"|"tool", "content": str, optional "call_id", "pinned": bool}


def count_tokens(m: Message) -> int:
    """Rough stand-in: about 4 characters per token. Swap in a real tokenizer for production (04.7)."""
    return max(1, len(m["content"]) // 4) + 4          # +4 for per-message overhead


def total(msgs: list[Message]) -> int:
    return sum(count_tokens(m) for m in msgs)


# 1. Sliding window by turns -------------------------------------------------------------
def sliding_window(msgs: list[Message], keep_turns: int) -> list[Message]:
    """Keep the last N user turns (and everything after them). Pinned messages always stay."""
    user_idx = [i for i, m in enumerate(msgs) if m["role"] == "user"]
    cut = user_idx[-keep_turns] if len(user_idx) > keep_turns else 0
    return [m for i, m in enumerate(msgs) if i >= cut or m.get("pinned")]


# 2. Token-aware truncation --------------------------------------------------------------
def truncate_to_budget(msgs: list[Message], budget: int) -> list[Message]:
    """Drop the oldest unpinned messages until the total fits. Never split a tool call from its result."""
    kept = list(msgs)
    while total(kept) > budget:
        victim = next((i for i, m in enumerate(kept) if not m.get("pinned")), None)
        if victim is None:
            break                                          # only pinned messages left: caller must decide
        drop = {victim}
        call_id = kept[victim].get("call_id")
        if call_id:                                        # drop the partner message too
            drop |= {i for i, m in enumerate(kept) if m.get("call_id") == call_id}
        kept = [m for i, m in enumerate(kept) if i not in drop]
    return kept


# 3. Rolling summary ----------------------------------------------------------------------
Summarizer = Callable[[str, list[Message]], str]           # (old_summary, messages_to_fold) -> new_summary


@dataclass
class FakeSummarizer:
    """Deterministic stand-in for an LLM call: keeps sentences with rules, ids or amounts."""
    calls: int = 0
    keep_pattern: str = r"\b(never|always|must|only)\b|\b[A-Z]\d{2,}\b|\$\d+"

    def __call__(self, old_summary: str, msgs: list[Message]) -> str:
        self.calls += 1
        facts = [s.strip() for m in msgs for s in re.split(r"(?<=[.!?])\s+", m["content"])
                 if re.search(self.keep_pattern, s)]
        merged = [old_summary] if old_summary else []
        merged += [f for f in facts if f not in old_summary]
        return " ".join(merged)


@dataclass
class RollingSummary:
    summarizer: Summarizer
    keep_recent: int = 6                                    # messages kept word for word
    summary: str = ""
    history: list[Message] = field(default_factory=list)

    def add(self, msg: Message) -> None:
        self.history.append(msg)
        if len(self.history) > self.keep_recent * 2:        # fold in batches, not on every turn
            old, self.history = self.history[:-self.keep_recent], self.history[-self.keep_recent:]
            self.summary = self.summarizer(self.summary, old)

    def window(self) -> list[Message]:
        head = [{"role": "user", "content": f"[Summary of earlier conversation] {self.summary}",
                 "pinned": True}] if self.summary else []
        return head + self.history


# 4. Tool-result clearing -------------------------------------------------------------------
def clear_tool_results(msgs: list[Message], keep_last: int = 2,
                       placeholder: str = "[tool result cleared to save space]") -> list[Message]:
    """Replace old tool outputs with a short placeholder. The call stays; only the bulky output goes."""
    tool_idx = [i for i, m in enumerate(msgs) if m["role"] == "tool"]
    stale = set(tool_idx[:-keep_last]) if keep_last else set(tool_idx)
    return [{**m, "content": placeholder} if i in stale else m for i, m in enumerate(msgs)]

2.2 Why pairs matter#

truncate_to_budget removes a message's partner whenever it removes a message with a call_id. Both OpenAI and Anthropic reject a conversation where a tool result has no matching call, or a call has no result. Dropping "the oldest message" without checking is a common cause of 400 errors in long agent sessions. The safe unit to drop is the pair, not the message.

2.3 What the sliding window forgets#

A window by turns is the simplest strategy and the one most likely to hurt. Suppose the user's very first message contains a rule ("never email the customer") and a fact (an order id and amount). After a few more turns the window slides past it. Nothing errors. The bot just starts emailing the customer. Part 5 shows this with real output.

Two small fixes cover most of the damage:

  • Pin the messages in the keep-list of 1.3 so trimming skips them.
  • Window by tokens, not turns. Ten short turns and ten pasted documents are not the same size. Truncation by budget respects the real limit (04.7, 2.2).

Part 3: Rolling summarization#

This part extends 04.7, 2.4 (rolling and hierarchical summaries) with a folding loop and a fake summarizer you can test offline. The summarization prompts themselves are in 04.7, Part 3.

3.1 The idea#

A rolling summary keeps a short text that stands for everything older than the last few messages. When the live history grows past a limit, you fold the oldest messages into the summary and delete them from the live list. The model then sees: summary, then recent messages word for word.

RollingSummary in the library folds in batches (when history exceeds twice keep_recent, it folds the oldest half) rather than on every turn. Folding every turn pays for a model call per message and rewrites the summary so often that errors compound.

3.2 A fake summarizer you can test#

A real summarizer is a model call. For tests you want something deterministic that needs no key. FakeSummarizer plays the role of the model: it keeps sentences that contain a rule word (never, always, must, only), an id like A17, or an amount like $40, and drops the rest. It is not smart, but it lets you test the plumbing (when folding happens, what the model would see, what survives) with real, repeatable output. The same function signature accepts a real model call:

python
# real_summarizer_illustrative.py  (needs a key; illustrative)
from anthropic import Anthropic

claude = Anthropic()
SUMMARY_PROMPT = (
    "Update the running summary with the new messages. Keep every rule the user stated, every id, "
    "amount, date and file name exactly as written, every correction, and any open question. "
    "Drop greetings and finished side topics. Reply with the summary text only."
)

def claude_summarizer(old_summary: str, msgs: list[dict]) -> str:
    transcript = "\n".join(f"{m['role']}: {m['content']}" for m in msgs)
    reply = claude.messages.create(
        model="claude-haiku-5-5", max_tokens=600, system=SUMMARY_PROMPT,
        messages=[{"role": "user", "content": f"Summary so far:\n{old_summary}\n\nNew messages:\n{transcript}"}],
    )
    return reply.content[0].text

Output (illustrative): a short paragraph such as "User wants a refund for order A17 ($40). Rule: never email the customer; phone only." The OpenAI version is the same shape with client.responses.create(model=..., instructions=SUMMARY_PROMPT, input=...) and response.output_text. Use a small, cheap model for summaries; the work is simple and it runs often. Summarization prompts that survive real use are in 04.7, Part 3.

3.3 How summaries fail#

04.7, 2.6 is the full catalogue with defences. The short version for this lesson:

  • Loss and distortion. A fact gets dropped, or "never email" becomes "prefers phone". Pin the keep-list and ask for rules to be copied verbatim.
  • Invention. The summary states something the chat never said, and later turns treat it as truth. Test for it (08B.5, Part 1).
  • Drift. A summary of a summary of a summary slowly loses detail. After a set number of folds, start a fresh window from structured notes instead (08B.5, Part 3).
  • Wrong role. Put the summary in a message the model treats as background information, not as a new user instruction. The library marks it pinned and labels it "Summary of earlier conversation".

Part 4: Tool-result clearing#

In any agent loop, tool outputs are the biggest context consumers, often 10 to 100 times the size of the user's messages. One read_file on a source file, a web_search result set, a query that returns 200 rows or a test log can outweigh the rest of the conversation, and a few such calls can fill a very large window. This part starts with the simplest fix (clearing) and builds up to a full result policy. Where a tool result sits in the agent loop is 08A.2, 6.1; the agent view of compressing observations is 08B.2, 2.4.

4.1 Why tool outputs are different from chat#

Chat turns are small and mostly irreplaceable: you cannot re-derive what the user said. Tool outputs are the opposite. They are large, re-fetchable and usually needed only once. The model reads a search result, extracts the answer and never needs the raw 4,000-token page again, unless it does. That is why "just delete it" is wrong and "manage it" is right.

4.2 Clearing: the simplest policy#

In agent loops, tool outputs are usually the biggest items: a database record, a web page, a file. Once the agent has used a result, the full text rarely matters again. clear_tool_results (in short_term.py) keeps the call, so the model remembers what it did, and replaces old outputs with a one-line placeholder, keeping the newest keep_last results intact.

Two cautions. First, only clear results the agent has already acted on, and never clear a result the next step still needs. Second, tell the model a result was cleared (the placeholder does), so it knows to call the tool again instead of guessing.

Clearing is lossy but honest and cheap: no model call, and the placeholder tells the model exactly what happened. It is also the building block behind the provider features in Part 6.

4.3 The result-lifecycle toolkit#

Clearing is one row of a larger menu. Pick per tool, because a log, a list of rows and a web page need different treatment.

Technique How it works When to use Cost or risk
Keep verbatim (recent) The last few results stay whole The model is actively reasoning over them Window space
Clear to a stub Replace an old result with [cleared: kb_search, 3,912 tokens, ...] Result consumed; the model may re-call if needed The model must know it can re-fetch
Truncate with markers Keep head and tail, elide the middle: [... 1,240 characters elided ...] The result has structure (logs, files) and the ends matter Loses middle detail silently
Summarize plus handle Store the full result outside; keep a short digest and a handle Large outputs consulted repeatedly The digest may lose the needed detail
Paginate Return the first page plus has_more; the model fetches more through a tool List-shaped results (search hits, rows) Extra tool calls and latency
Store outside, pass a reference Write the result to a file, database or blob; the context holds a path or id only Very large or sensitive outputs The model must call a fetch tool

The pattern that scales mirrors how you treat chat turns: recent results verbatim, older results as digest plus handle, the oldest as stubs or dropped. Anthropic's clear_tool_uses_20250919 context-editing strategy automates the "clear to a stub" row on the server (6.2); your own code does the rest.

4.4 Handles and just-in-time retrieval#

The powerful version of "store outside, pass a reference" is just-in-time retrieval: keep lightweight identifiers (file paths, query ids, URLs, record keys) in the context and let the model fetch content through tools only when it needs it. Anthropic's context-engineering post describes agents that "maintain lightweight identifiers (file paths, stored queries, web links, etc.) and use these references to dynamically load data into context at runtime". It is the same as using a bookmark instead of memorising a web page. (The retrieval side of "load only what earns its tokens" is 04.6, 3.4.)

For this to work, two things must be true:

  1. The model knows what is available. The handle must be meaningful. search_id=8821 is opaque; kb_search(query="battery drain warranty", result_id=kb_2026_118) tells the model what it can re-fetch and why.
  2. Re-fetching is cheap and safe. The tool that resolves a handle should be idempotent, fast and return the same content (or a fresh equivalent). If re-fetching costs a web search or a slow query, the model will avoid it and guess instead.

4.5 A result policy you can run#

A practical default, tunable per tool: at write-back time, keep a small result whole; keep a result that is still in use; otherwise store the full text outside the window and leave a digest plus a handle. When the window is tight, stub the oldest results first, whatever their turn age. Two rules prevent subtle bugs:

  • Never orphan a tool call from its result. A result whose call was trimmed is a protocol error on every provider, and a result without its call is meaningless. The policy below only ever rewrites the content of a tool message, so pairs stay paired.
  • Annotate stubs so the model knows. [cleared: web_fetch example.com/page, 4,102 tokens, re-fetch with web_fetch if needed] invites a re-fetch. A bare [...] invites a hallucination.

tool_results.py builds on short_term.py. It has a ResultStore (the storage outside the window, with a paged fetch), apply_result_policy (keep, or stub with digest and handle), truncate_middle (head, tail and a marker), age_out_media (Part 4.6) and an orphans checker. The token numbers are small on purpose, so you can read the output.

python
# tool_results.py: a result policy for tool outputs (keep, truncate with a marker, or spill to a store with a handle)
from __future__ import annotations

from dataclasses import dataclass, field

from short_term import count_tokens, total

KEEP_WHOLE = 150          # tokens a result may use and still stay verbatim (tiny, so the demo is readable)


@dataclass
class ResultStore:
    """Storage outside the window. The handle is all the model keeps, so fetch must be cheap and repeatable."""
    _data: dict[str, str] = field(default_factory=dict)

    def put(self, tool: str, text: str) -> str:
        handle = f"{tool}#{len(self._data) + 1}"
        self._data[handle] = text
        return handle

    def fetch(self, handle: str, page: int = 0, page_size: int = 400) -> dict:
        """The tool the model calls to re-read a result, one page at a time."""
        text = self._data.get(handle)
        if text is None:
            return {"error": f"unknown handle {handle}"}
        start = page * page_size
        return {"handle": handle, "page": page, "text": text[start:start + page_size],
                "has_more": start + page_size < len(text)}


def truncate_middle(text: str, head: int = 60, tail: int = 40) -> str:
    """Keep the start and the end, say how much was removed. Good for logs and files."""
    if len(text) <= head + tail:
        return text
    return f"{text[:head]} [... {len(text) - head - tail} characters elided ...] {text[-tail:]}"


def make_stub(m: dict, handle: str) -> str:
    """An annotated stub: says what was cleared, how big it was and how to get it back."""
    digest = m["content"].split("\n", 1)[0][:60]
    return (f"[cleared: {m.get('tool', 'tool')} result, {count_tokens(m)} tokens. Digest: {digest}. "
            f"Stored as {handle}; call fetch_result('{handle}') to re-read]")


def apply_result_policy(msgs: list[dict], store: ResultStore, keep_recent: int = 2,
                        keep_whole: int = KEEP_WHOLE, in_use: frozenset[str] = frozenset()) -> list[dict]:
    """Recent results stay whole, small results stay whole, results still in use stay whole,
    everything else becomes a digest plus a handle. Calls are never touched, so pairs stay paired."""
    tool_idx = [i for i, m in enumerate(msgs) if m["role"] == "tool"]
    recent = set(tool_idx[-keep_recent:]) if keep_recent else set()
    out = []
    for i, m in enumerate(msgs):
        keep = (m["role"] != "tool" or m.get("cleared") or i in recent
                or count_tokens(m) <= keep_whole or m.get("call_id") in in_use)
        if keep:
            out.append(m)
        else:
            out.append({**m, "content": make_stub(m, store.put(m.get("tool", "tool"), m["content"])),
                        "cleared": True})
    return out


def age_out_media(msgs: list[dict], keep_recent: int = 1) -> list[dict]:
    """Old images and files become a description plus a file reference. Describe BEFORE you drop."""
    media_idx = [i for i, m in enumerate(msgs) if m.get("media")]
    old = set(media_idx[:-keep_recent]) if keep_recent else set(media_idx)
    out = []
    for i, m in enumerate(msgs):
        if i in old:
            md = m["media"]
            if not md.get("description"):
                raise ValueError(f"describe {md['ref']} before dropping it: the description is all that survives")
            m = {**{k: v for k, v in m.items() if k != "media"},
                 "content": f"[{md['kind']} removed: {md['description']}. File kept at {md['ref']}; re-open with read_file]"}
        out.append(m)
    return out


def orphans(msgs: list[dict]) -> set[str]:
    """Call ids that have a call without a result, or a result without a call."""
    calls = {m["call_id"] for m in msgs if m["role"] == "assistant" and "call_id" in m}
    results = {m["call_id"] for m in msgs if m["role"] == "tool"}
    return calls ^ results

demo_tool_results.py runs a 12-lookup agent run through the policy, re-reads one result through its handle, and checks that no call lost its result.

python
# demo_tool_results.py: the result policy on a 12-lookup agent run, plus handles, pages and media
from short_term import clear_tool_results, total
from tool_results import (ResultStore, age_out_media, apply_result_policy, orphans,
                          truncate_middle)

chat = [{"role": "user", "content": "Check orders A1 to A12. Never email the customer; phone only."}]
for i in range(1, 13):
    rows = "\n".join(f"line {n}: item sku-{i}{n:02d} qty {n} price {n * 3}.00" for n in range(1, 25))
    chat += [{"role": "assistant", "content": "lookup_order", "call_id": f"c{i}"},
             {"role": "tool", "tool": "lookup_order", "call_id": f"c{i}",
              "content": f"order A{i}: status shipped, 24 lines\n{rows}"}]

store = ResultStore()
print(f"full history              tokens~{total(chat):>5}")
print(f"simple clearing (Part 4)  tokens~{total(clear_tool_results(chat, keep_last=2)):>5}")
managed = apply_result_policy(chat, store, keep_recent=2)
print(f"result policy             tokens~{total(managed):>5}   stored outside: {len(store._data)} results")
print("orphaned calls/results:", orphans(managed) or "none")

print("\nOne stub, as the model sees it:")
print(" ", managed[2]["content"])
print("\nThe model re-reads A1 through the handle, one page at a time:")
page0 = store.fetch("lookup_order#1", page=0)
print(f"  page 0: {len(page0['text'])} chars, has_more={page0['has_more']}")
page1 = store.fetch("lookup_order#1", page=1)
print(f"  page 1: {len(page1['text'])} chars, has_more={page1['has_more']}")
print("  bad handle ->", store.fetch("lookup_order#99"))

print("\nA result still in use is kept whole:")
kept = apply_result_policy(chat, ResultStore(), keep_recent=1, in_use=frozenset({"c1"}))
print("  c1 cleared?", kept[2].get("cleared", False), "| c2 cleared?", kept[4].get("cleared", False))

print("\nTruncate with a marker (good for a log):")
log = "START build " + "compiling module ... ok. " * 20 + "FAILED: test_login expected 200 got 500"
print(" ", truncate_middle(log))

print("\nNon-text parts:")
media = [{"role": "user", "content": "[image] first photo", "media": {"kind": "image", "ref": "uploads/img_1.png",
                                                                    "description": "photo of a swollen battery pack"}},
         {"role": "user", "content": "[image] second photo", "media": {"kind": "image", "ref": "uploads/img_2.png",
                                                                      "description": None}}]
print(" ", age_out_media(media, keep_recent=1)[0]["content"])
try:
    age_out_media(media, keep_recent=0)
except ValueError as e:
    print("  refused:", e)
Output · real, python3 demo_tool_results.py22 lines
full history              tokens~ 3157
simple clearing (Part 4)  tokens~  741
result policy             tokens~ 1061   stored outside: 10 results
orphaned calls/results: none

One stub, as the model sees it:
  [cleared: lookup_order result, 253 tokens. Digest: order A1: status shipped, 24 lines. Stored as lookup_order#1; call fetch_result('lookup_order#1') to re-read]

The model re-reads A1 through the handle, one page at a time:
  page 0: 400 chars, has_more=True
  page 1: 400 chars, has_more=True
  bad handle -> {'error': 'unknown handle lookup_order#99'}

A result still in use is kept whole:
  c1 cleared? False | c2 cleared? True

Truncate with a marker (good for a log):
  START build compiling module ... ok. compiling module ... ok [... 451 characters elided ...]  FAILED: test_login expected 200 got 500

Non-text parts:
  [image removed: photo of a swollen battery pack. File kept at uploads/img_1.png; re-open with read_file]
  refused: describe uploads/img_2.png before dropping it: the description is all that survives

Read the numbers. The policy cut 3,157 estimated tokens to 1,061 and stored 10 results outside the window; the two newest stayed whole. Simple clearing from 4.2 reached 741 because its placeholder is shorter, but that placeholder says nothing about what was cleared or how to get it back. Each annotated stub here costs a few dozen tokens more, and in return the model can re-read the result page by page. Which trade is right depends on how often the agent needs old results again. The in_use argument is the escape hatch for a result the next step still needs. No call lost its result.

4.6 Non-text parts in history#

Everything above assumed content is a string. Real conversations also carry images, PDFs, audio clips and uploaded files, and they age differently from prose:

  • They cannot be folded into a text summary losslessly. A summarizer can describe an image ("photo of a swollen battery pack") but cannot carry the pixels. Once the part leaves the window, the detail is gone unless you kept the file.
  • They are priced differently. An image costs a fixed block of tokens per resolution tier, audio bills per second and a PDF bills per page, not per character. A characters-per-token guess undercounts them badly; use the provider's count endpoint or modality-aware rules (03.6 covers how parts are sent; 03.7, Part 2 covers counting).
  • The lifecycle is the tool-result lifecycle, one tier up. Keep recent media verbatim. For older media, replace the part with a text description plus a handle the model can re-fetch. If the file still exists in your store, the handle makes the detail retrievable on demand; if it does not, the description is all that survives, so generate it before dropping the part.
Part type While recent After it ages out
Image or screenshot Verbatim part Generated caption plus file handle
PDF or document Verbatim (or its extracted text) Summary of contents plus a handle to re-extract
Audio or video Verbatim while relevant Transcript if you have one plus a handle; raw media is rarely worth keeping
Generated artifact (chart, rendered output) Verbatim while referenced Description plus a note that it can be regenerated

Two rules: never drop media you have not described first, and keep the underlying file, because a handle to nothing is worse than a stub. age_out_media in tool_results.py enforces the first rule: it raises an error if a part has no description. The storage shape is yours; each provider's wire format (image blocks on Anthropic, input_image on OpenAI) is the business of 03.6.


Part 5: Putting them together, and testing with probes#

5.1 One long chat, every strategy#

demo_short_term.py builds a 49-message support chat. Message 1 holds a rule and a fact. Twelve tool lookups follow, each with a 400-character record. It then applies each strategy and checks whether the rule and the fact are still visible to the model.

python
# demo_short_term.py: one long support chat, four strategies, and a retention check
from short_term import (FakeSummarizer, RollingSummary, clear_tool_results,
                        sliding_window, total, truncate_to_budget)

RULE = "Never email the customer; phone only."
FACT = "Order A17 costs $40."

chat = [{"role": "user", "content": f"Hi. {RULE} {FACT}"}]
for i in range(1, 13):
    chat.append({"role": "assistant", "content": f"Checking step {i}.", })
    chat.append({"role": "assistant", "content": "lookup_order", "call_id": f"c{i}"})
    chat.append({"role": "tool", "content": "RECORD " + "x" * 400, "call_id": f"c{i}"})
    chat.append({"role": "user", "content": f"Okay, next question number {i}."})


def report(name: str, msgs: list[dict]) -> None:
    text = " ".join(m["content"] for m in msgs)
    print(f"{name:<28} messages={len(msgs):>3}  tokens~{total(msgs):>4}  "
          f"rule kept={('phone only' in text)!s:<5}  fact kept={('A17' in text)!s}")


report("full history", chat)
report("sliding window (3 turns)", sliding_window(chat, 3))
report("token truncation (300)", truncate_to_budget(chat, 300))

pinned = [{**chat[0], "pinned": True}] + chat[1:]
report("truncation + pinned rule", truncate_to_budget(pinned, 300))

rs = RollingSummary(FakeSummarizer(), keep_recent=6)
for m in chat:
    rs.add(m)
report("rolling summary", rs.window())
print("  summarizer calls:", rs.summarizer.calls, "| summary:", rs.summary)

report("clear old tool results", clear_tool_results(chat, keep_last=2))

# Pipeline order that works well: clear -> summarise -> truncate as the last resort
rs2 = RollingSummary(FakeSummarizer(), keep_recent=6)
for m in clear_tool_results(chat, keep_last=2):
    rs2.add(m)
report("clear + rolling summary", rs2.window())

# Pairs are never split
cut = truncate_to_budget(chat, 300)
ids_call = {m["call_id"] for m in cut if m["role"] == "assistant" and "call_id" in m}
ids_res = {m["call_id"] for m in cut if m["role"] == "tool"}
print("tool calls and results still paired after truncation:", ids_call == ids_res)
Output · real, python3 demo_short_term.py9 lines
full history                 messages= 49  tokens~1591  rule kept=True   fact kept=True
sliding window (3 turns)     messages=  9  tokens~ 273  rule kept=False  fact kept=False
token truncation (300)       messages=  9  tokens~ 273  rule kept=False  fact kept=False
truncation + pinned rule     messages= 10  tokens~ 292  rule kept=True   fact kept=True
rolling summary              messages=  8  tokens~ 281  rule kept=True   fact kept=True
  summarizer calls: 6 | summary: Never email the customer; phone only. Order A17 costs $40.
clear old tool results       messages= 49  tokens~ 661  rule kept=True   fact kept=True
clear + rolling summary      messages=  8  tokens~ 281  rule kept=True   fact kept=True
tool calls and results still paired after truncation: True

What the numbers say:

  • The sliding window and plain token truncation both cut 1,591 estimated tokens to about 273 and both lost the rule and the fact. They look fine on a dashboard and fail on the first email.
  • Truncation plus a pinned message kept both for 292 tokens. A one-line change (pinned) fixed it.
  • The rolling summary kept both in about 281 tokens, by keeping only the sentences that matter. With the fake summarizer it called the summarizer 6 times. A real summarizer costs a model call each time, so batch folding matters.
  • Tool-result clearing alone cut 1,591 to 661 and kept everything the model said and was told. Combined with the rolling summary it reached the same size as the summary alone, because old tool outputs were already gone before folding.
  • Truncation never split a call from its result.

5.2 A probe test#

A probe is a string that must still be visible after trimming ("phone only", "A17", "$40"). A strategy passes if every probe is present. This is the smallest useful evaluation of compaction, and it needs no model. eval_compaction.py runs four strategies against four probes.

python
# eval_compaction.py: probe-based fidelity check for each short-term strategy (no model needed)
from short_term import FakeSummarizer, RollingSummary, clear_tool_results, sliding_window, truncate_to_budget

chat = [{"role": "user", "content": "Hi. Never email the customer; phone only. Order A17 costs $40. Budget limit is $50."}]
for i in range(1, 13):
    chat += [{"role": "assistant", "content": "lookup_order", "call_id": f"c{i}"},
             {"role": "tool", "content": "RECORD " + "x" * 400, "call_id": f"c{i}"},
             {"role": "user", "content": f"Okay, next question number {i}."}]

PROBES = {                      # name -> a string that must still be visible to the model
    "constraint": "phone only",
    "entity id": "A17",
    "amount": "$40",
    "latest turn": "number 12",
}

def rolling(msgs):
    rs = RollingSummary(FakeSummarizer(), keep_recent=6)
    for m in msgs:
        rs.add(m)
    return rs.window()

STRATEGIES = {
    "sliding window (3)": lambda m: sliding_window(m, 3),
    "truncate (300 tokens)": lambda m: truncate_to_budget(m, 300),
    "clear tool results": lambda m: clear_tool_results(m, 2),
    "rolling summary": rolling,
}

print(f"{'strategy':<24}" + "".join(f"{p:<13}" for p in PROBES) + "pass (all probes)")
for name, fn in STRATEGIES.items():
    text = " ".join(m["content"] for m in fn(chat))
    hits = {p: needle in text for p, needle in PROBES.items()}
    print(f"{name:<24}" + "".join(f"{('yes' if h else 'NO'):<13}" for h in hits.values()) + str(all(hits.values())))
Output · real, python3 eval_compaction.py5 lines
strategy                constraint   entity id    amount       latest turn  pass (all probes)
sliding window (3)      NO           NO           NO           yes          False
truncate (300 tokens)   NO           NO           NO           yes          False
clear tool results      yes          yes          yes          yes          True
rolling summary         yes          yes          yes          yes          True

The two destructive strategies fail three of four probes. The two that preserve information pass. In real systems, probes are written by hand from the facts a conversation must not lose, and the summarizer is a real model, so the matrix is the interesting part: it tells you which facts a given strategy loses before your users do. 10A.11, 6.2 explains why probes beat text-overlap scores.


Part 6: Provider-side compaction and context editing (as of 1 December 2026)#

Reference

Providers now run some of these strategies server-side: the API itself folds old context into a summary item, or clears stale content by rule. The API mechanics are in 03.2, 7.4; this part is the decision layer: what exists, what is stable and what is beta, what it costs you in visibility, and when to pick it over your own code. Facts below were checked against the official docs on 1 December 2026 unless a row says otherwise. Several features are beta and will change: check the pages before relying on any name.

Provider Feature What it does Status on 1 December 2026
OpenAI context_management with {"type": "compaction", "compact_threshold": N} on /responses Server compacts when the rendered token count crosses the threshold and emits an encrypted compaction item Documented in the compaction guide; no beta label on the page
OpenAI /responses/compact Stateless: send a window, get a compacted window back to pass on as is Documented; ZDR-friendly
Anthropic Compaction on demand (compaction={"type": "summarize"}, header compact-2026-09-04) One request returns a signed compaction block holding a readable summary Beta
Anthropic Compaction at a token threshold ({"type": "compact_20260112"} edit, header compact-2026-01-12) API summarises inside normal requests when input reaches your trigger Beta
Anthropic Context editing (clear_tool_uses_20250919, clear_thinking_20251015, header context-management-2025-06-27) Clears old tool results or thinking blocks by rule, applied server-side; your copy stays complete Beta
Anthropic Memory tool (memory_20250818) Claude reads and writes files under /memories; your code runs the file operations Stable, no beta header (see 08B.4)
OpenAI truncation="auto" Silently drops the oldest items to fit Marked deprecated in the API reference (per 03.2, 7.4, November 2026; not re-checked). Do not use it: it was always lossy and silent
Anthropic Client-side SDK compaction (tool_runner) The SDK writes a summary and swaps it in for you TypeScript and Ruby SDKs only, not Python (per 04.7, November 2026; unverified as of 2026-12-02). Python users write the loop themselves
Gemini None for generateContent The long-context docs describe context caching as the optimisation and list dropping or summarising old messages as techniques you apply yourself No built-in history compaction on the plain API
Gemini Managed Agents compaction (about 135k tokens), Live API sliding-window compression Compaction inside Google's agent platform; compression for realtime voice sessions Platform features, not the plain chat API (per 04.7, November 2026; unverified as of 2026-12-02)
OpenRouter context-compression plugin Removes or truncates messages from the middle of a prompt that does not fit Documented plugin; on by default for endpoints with 8k tokens of context or less

6.1 OpenAI#

Per OpenAI's compaction guide, you add context_management to a Responses request. The compaction item is "encrypted and opaque": you cannot read or edit it, you replay every returned output item in order, and with stateless input arrays you may drop items before the latest compaction item, but you should not prune when using previous_response_id. The standalone /responses/compact endpoint is stateless and rejects histories that contain configuration_update items.

python
# openai_compaction_illustrative.py  (needs OPENAI_API_KEY; illustrative)
from openai import OpenAI

client = OpenAI()
response = client.responses.create(
    model="gpt-6-luna",
    input=conversation_items,            # your list of input items, grown turn by turn
    context_management=[{"type": "compaction", "compact_threshold": 200000}],
)
conversation_items += response.output    # keep EVERY output item, including the compaction item

Output (illustrative): normal answer text. Once the threshold is crossed mid-conversation, response.output also contains an encrypted compaction item. Printing it shows an opaque blob, not a summary. That opacity is the main cost: you cannot test what the model still remembers by reading it. Use probes (Part 5) instead.

6.2 Anthropic#

Anthropic gives you two compaction styles plus context editing. The compaction block holds readable summary text and a signature: "Send it in future requests exactly as it came." If you change it, the API returns an error.

python
# anthropic_compaction_illustrative.py  (needs ANTHROPIC_API_KEY; illustrative; features are beta)
import anthropic

client = anthropic.Anthropic()

# (a) On demand: you choose when. One request returns only a compaction block.
summary = client.beta.messages.create(
    model="claude-opus-5-5", max_tokens=4096, betas=["compact-2026-09-04"],
    messages=history, compaction={"type": "summarize"},
)
if summary.stop_reason == "compaction":               # check before looking for the block
    history = [{"role": "assistant", "content": summary.content}]   # the block replaces what it summarised

# (b) Context editing: clear old tool results by rule. Your local history stays complete.
reply = client.beta.messages.create(
    model="claude-opus-5-5", max_tokens=4096, betas=["context-management-2025-06-27"],
    messages=history, tools=my_tools,
    context_management={"edits": [{
        "type": "clear_tool_uses_20250919",
        "trigger": {"type": "input_tokens", "value": 30000},   # default is 100,000
        "keep": {"type": "tool_uses", "value": 3},              # default is 3
        "clear_at_least": {"type": "input_tokens", "value": 5000},
        "exclude_tools": ["web_search"],
    }]},
)

Output (illustrative): in (a), summary.stop_reason is "compaction" and summary.content[0] is a block with type="compaction", readable summary text and a signature. In (b), a normal reply; once the trigger is reached the server replaces the oldest tool results with placeholder text and the usage shows fewer input tokens.

Notes from the docs worth keeping in mind:

  • Compaction at a token threshold defaults to a 150,000-token trigger with a 50,000-token minimum. Thinking blocks from before a compaction block are not carried forward, so the summary is all the model has of that earlier work: say in your instructions what it must retain.
  • Context editing's defaults are a 100,000-token trigger and keeping the 3 newest tool uses.
  • You cannot send compaction and context_management on the same request.
  • Clearing tool results invalidates the cached prompt prefix, which is why clear_at_least exists: clear enough to be worth the cache miss. This connects to cost (11B.8, 11B.4).
  • The docs' own guidance on compaction is "Use on-demand compaction wherever it is available."
  • Images, documents and fetched URLs inside summarised messages are gone once the block replaces them; restate or re-upload what a later turn needs.
  • Anthropic's context editing page says server-side compaction is the primary strategy for most long-running conversations, and context editing is the surgical option for tool-heavy loops.

6.3 Gemini and OpenRouter#

Gemini has no documented history compaction for generateContent as of 1 December 2026. Context caching is a cost optimisation, not history management, and the Interactions API's previous_interaction_id is server-side state, not compaction. You manage history yourself: a rolling summary, a sliding window or the ConversationManager of 04.7, Part 11. The open-source Gemini CLI does client-side chat-history compression you can read as a reference.

OpenRouter is stateless by design but offers the context-compression plugin (plugins: [{"id": "context-compression"}]). Its page says endpoints with 8k tokens of context or less use it by default, and you can turn it off with "enabled": false. It truncates, it does not summarize: it removes or truncates messages from the middle of the prompt until it fits, so no gist is preserved. Treat it as a safety net for small-context models, not a conversation strategy.

6.4 Server-side or your own?#

Provider compaction or editing Your own code (this lesson)
Effort One parameter The code above, plus tests
Control Threshold or on-demand trigger; limited say over what is kept (you may supply your own summary instructions on Anthropic on-demand, not on all paths) Full: pins, ids, rules, importance, shedding order
Visibility Opaque item (OpenAI) or readable but provider-written (Anthropic); you cannot inspect what was dropped You see and log everything: a drop log, replayable
Debugging "What did the model see?" is harder because the compacted state is opaque Full transparency
Portability One provider's request shape Any provider, including OpenRouter and local models
Cost Compaction is model inference you pay for, inside or beside the request The same: a summarization call is a model call, often on a cheaper model
Maturity (1 Dec 2026) OpenAI documented; Anthropic features beta; Gemini none Yours to test and tune

The practical split: use provider compaction as the safety net (it catches what your code missed, especially inside long agent loops) and use your own policy for what must survive (pins, ids, rules, the result policy of Part 4, memory). They compose: your code decides what should be in the window, and the provider's compaction guarantees the window never overflows. Where a provider's compaction is stable and fits, it is reasonable to lean on it and spend your complexity budget elsewhere. Either way, test with probes, because "the provider compacts for me" is not a test result.


Part 7: Long tasks across many windows: files and git as the memory#

Deep-dive

Some agent tasks (a migration, a multi-hour research job, a feature built over dozens of commits) outlast any single window and any single compaction. The pattern that Anthropic describes for these runs treats the window as disposable and puts the durable state in files. It is provider-neutral in spirit, so it is worth learning even if you never use Claude. The sources are Anthropic's Effective harnesses for long-running agents and the "multisession software development pattern" section of the memory tool docs (both checked 2 December 2026). This is the same "write" move as in 04.6, 1.6: save state outside the window, then read it back when needed. The harness view of the same idea is 08A.4.

7.1 The pattern in six steps#

  1. Use a different prompt for the first window. The first window sets up the framework: write the tests, create setup scripts, define the task list. Later windows iterate on that list.
  2. Keep structured state in a structured file. Put the task list (tests or features with a status) in JSON, and guard it with an explicit rule. Anthropic's article quotes the instruction "It is unacceptable to remove or edit tests because this could lead to missing or buggy functionality", and says JSON was chosen because models are less likely to alter it inappropriately than Markdown. Use JSON for state that has a schema and plain text for free-form progress notes.
  3. Write progress notes and commit often. A progress.txt that says what was done, what is next and what to avoid, plus git history, gives the next window a log and restorable checkpoints.
  4. Script the start-up. A setup script (for example init.sh) that starts servers and runs tests and linters stops every new window from re-deriving the environment, and lets it catch existing bugs before starting new work.
  5. Choose between a fresh window and compaction (7.3).
  6. Give the agent a way to verify its work (tests, a browser or computer-use tool), because over long runs nobody is checking each step. Mark a task done only after an end-to-end check, not when the code is written.
text
project/
  tests.json        # structured: id, name, status (passing / failing / not_started)
  progress.txt      # free text: "Session 3: fixed token validation. Next: test #2. Do not remove tests."
  init.sh           # starts the dev server, runs the linter and the test suite
  .git/             # log and checkpoints

7.2 Run it: task list, progress notes and a start-up prompt#

progress_files.py builds the files in a temporary folder and shows the three moves that make the pattern safe: a guard that only lets a test's status change, a progress file that is rewritten when it grows instead of appended forever, and a start-up prompt that tells a fresh window exactly where to look. It does not run init.sh; it only writes it.

python
# progress_files.py: files as the memory for a task that outlives one window (tests.json + progress.txt)
from __future__ import annotations

import json
import tempfile
from pathlib import Path

MAX_PROGRESS_LINES = 6
RULE = "It is unacceptable to remove or edit tests: only change their status."


def init_project(root: Path) -> None:
    """The first window's job: write the task list, the notes file and the start-up script. No feature work."""
    tests = [{"id": i, "name": name, "status": "not_started"}
             for i, name in enumerate(["token validation", "refresh flow", "logout", "rate limit"], start=1)]
    (root / "tests.json").write_text(json.dumps(tests, indent=2))
    (root / "progress.txt").write_text("Session 1: created tests.json and init.sh. Next: test 1.\n")
    (root / "init.sh").write_text("#!/bin/sh\n# start the dev server, run the linter and the test suite\n")


def update_tests(root: Path, changes: dict[int, str]) -> None:
    """Only the status field may change. Removing, renaming or adding tests is refused."""
    tests = json.loads((root / "tests.json").read_text())
    known = {t["id"] for t in tests}
    if not set(changes) <= known:
        raise ValueError(f"unknown test ids {sorted(set(changes) - known)}. {RULE}")
    for t in tests:
        if t["id"] in changes:
            if changes[t["id"]] not in {"not_started", "failing", "passing"}:
                raise ValueError(f"bad status {changes[t['id']]!r}")
            t["status"] = changes[t["id"]]
    (root / "tests.json").write_text(json.dumps(tests, indent=2))


def append_progress(root: Path, line: str) -> None:
    """Rewrite instead of growing without bound: old lines are folded into one 'Earlier:' line."""
    lines = (root / "progress.txt").read_text().splitlines() + [line]
    if len(lines) > MAX_PROGRESS_LINES:
        old, lines = lines[:-3], lines[-3:]
        lines = [f"Earlier: {len(old)} older notes folded; see git log for detail."] + lines
    (root / "progress.txt").write_text("\n".join(lines) + "\n")


def startup_prompt(root: Path) -> str:
    """What a fresh window is told. Prescriptive: where to look, what to run, what not to touch."""
    tests = json.loads((root / "tests.json").read_text())
    counts = {s: sum(t["status"] == s for t in tests) for s in ("passing", "failing", "not_started")}
    nxt = next((t for t in tests if t["status"] != "passing"), None)
    return "\n".join([
        "You are continuing a long task. Your previous context is gone; the files are the memory.",
        "1. Run pwd. You can only read and write files in this directory.",
        "2. Read progress.txt, tests.json and the git log.",
        "3. Run init.sh, then one fundamental check before new work.",
        f"State: {counts}. Next: {('test ' + str(nxt['id']) + ' (' + nxt['name'] + ')') if nxt else 'nothing, all passing'}.",
        f"Rule: {RULE}",
        "Progress notes so far:", (root / "progress.txt").read_text().rstrip(),
    ])


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as d:
        root = Path(d)
        init_project(root)
        print("== window 1 wrote:", sorted(p.name for p in root.iterdir()))
        update_tests(root, {1: "passing"})
        append_progress(root, "Session 2: token validation passing. Next: test 2. Do not remove tests.")
        print("\n== start-up prompt for window 2 ==")
        print(startup_prompt(root))
        try:
            update_tests(root, {9: "passing"})
        except ValueError as e:
            print("\nrefused edit:", e)
        for n in range(3, 8):
            append_progress(root, f"Session {n}: worked on test {min(n, 4)}.")
        print("\n== progress.txt after five more sessions (bounded, not growing) ==")
        print((root / "progress.txt").read_text().rstrip())
Output · real, python3 progress_files.py20 lines
== window 1 wrote: ['init.sh', 'progress.txt', 'tests.json']

== start-up prompt for window 2 ==
You are continuing a long task. Your previous context is gone; the files are the memory.
1. Run pwd. You can only read and write files in this directory.
2. Read progress.txt, tests.json and the git log.
3. Run init.sh, then one fundamental check before new work.
State: {'passing': 1, 'failing': 0, 'not_started': 3}. Next: test 2 (refresh flow).
Rule: It is unacceptable to remove or edit tests: only change their status.
Progress notes so far:
Session 1: created tests.json and init.sh. Next: test 1.
Session 2: token validation passing. Next: test 2. Do not remove tests.

refused edit: unknown test ids [9]. It is unacceptable to remove or edit tests: only change their status.

== progress.txt after five more sessions (bounded, not growing) ==
Earlier: 4 older notes folded; see git log for detail.
Session 5: worked on test 4.
Session 6: worked on test 4.
Session 7: worked on test 4.

Read it as a story. Window 1 wrote three files and no feature code. Window 2 starts with nothing in its context except the prompt, and the prompt is prescriptive: where to look, what to run, which rule to obey, and which test is next. The edit that names an unknown test is refused. After five more sessions the notes file still has four lines, because old lines were folded into one "Earlier" line and the detail lives in git.

7.3 Fresh window or compaction?#

Anthropic's guidance is that the latest Claude models are very good at rediscovering state from the filesystem, so a brand-new window can beat compaction, provided you are prescriptive about how it starts. The prompt in 7.2 is the model for that: "Run pwd; you can only read and write files in this directory", "read the progress file, the task list and the git log", and "run a fundamental check before new work". Which to prefer depends on where the state lives.

Your situation Prefer
The state lives only in the conversation (decisions, preferences, open questions) Compaction or your own summary (Part 3, Part 6)
The state is on disk or in git and a script can rebuild the environment A fresh window with a prescriptive start-up prompt
Both, and the task is long Fresh windows, with a short pinned goal plus the progress file

Tell the model what your harness does. Anthropic's guidance notes that some Claude models can track their remaining context and, left uninformed, may start wrapping up as the limit approaches (unverified as of 2026-12-02: this point is carried from lesson 04.7, which checked it on 8 November 2026). If your harness compacts automatically or lets the agent save notes, say so in the prompt, in words like: your context will be compacted as it nears its limit, so do not stop early; save progress and state to memory before it refreshes. Without that information the model has no reason to keep going.

7.4 State files are context too#


Part 8: Sub-context isolation#

Deep-dive

Sometimes the problem is not that the history is too big. It is that the task is too big for one context. A research question needing twenty document reads, a codebase exploration touching fifty files or a data-analysis task over a huge table would flood the main conversation with intermediate work that the final answer does not need. Sub-context isolation is the answer: hand the sub-task to a separate model call with its own fresh context, and take back only a summary. The orchestration side (fan-out, agent-as-a-tool and multi-agent teams) is in 08A.11 and 08D.3; this part is the context-management view.

8.1 The delegation pattern#

flowchart TB
    MAIN["Main conversation<br/>(goal, decisions, pinned facts)"] -->|"delegate: 'research X'<br/>+ only the context it needs"| SUB["Sub-call<br/>fresh context window"]
    SUB -->|"tool calls, reads, reasoning<br/>(all local to the sub-call)"| SUBOUT["Sub-call returns<br/>a short distilled result"]
    SUBOUT --> MAIN
    MAIN --> NEXT["Next turn: main window<br/>stays small"]

The sub-call gets the specific sub-task, the minimal context it needs (a few documents, a file list, a schema) and instructions for what to return. It does all the noisy work in its own window, which it can compact freely because nothing it does needs to persist. What crosses the boundary back is only the distilled result: findings, conclusions, artifacts, typically a few hundred tokens and up to a couple of thousand for a rich research task. Anthropic's context-engineering post describes sub-agents this way: focused tasks in clean context windows, each returning "a condensed, distilled summary of its work (often 1,000-2,000 tokens)". The main context stays clean by construction, not by trimming after the fact.

8.2 What crosses the boundary, and what it costs#

Crosses back Stays in the sub-call
The answer, findings or artifact Raw documents read, intermediate reasoning, dead ends
Key facts with provenance ("from doc X") The full text of doc X
Decisions made and why The exploration path
Errors hit and how they were resolved Stack traces, retry logs

Costs and caveats:

  • More calls, more latency. A sub-call is a full model invocation, or several if it uses tools. Parallel sub-calls help but add orchestration.
  • The summary is a bottleneck. Whatever the sub-call leaves out of its return is gone from the main agent's world. If the main agent later needs a detail the summary dropped, it must re-delegate, which is expensive. Write the "what to return" spec carefully, and ask for findings with provenance, not just conclusions.
  • Context crosses the boundary twice, so choose it deliberately. Give the sub-call the minimum it needs (a summary of the goal plus the specific files or documents), not the whole main history.
  • It is the same pattern as a result handle (4.4): the sub-call is a fancy fetch tool. If all you need is one document's content, a read_file call already gives you just-in-time retrieval without a sub-agent.

8.3 Run it: twenty documents, a few dozen tokens back#

sub_context.py plays both sides with no model. The "sub-call" scans 20 documents and keeps only sentences that mention the keyword, each tagged with the document it came from. The numbers show what the main window pays with and without delegation, and the last line shows the bottleneck.

python
# sub_context.py: delegate a noisy sub-task to a fresh context and take back only a distilled result
from __future__ import annotations

import re

from short_term import count_tokens

FILLER = "The committee reviewed routine matters and recorded the minutes in the usual format. " * 6
DOCS = {f"doc_{i}": FILLER for i in range(1, 21)}
DOCS["doc_4"] = FILLER + "The refund window was changed to 45 days on 3 March. " + FILLER
DOCS["doc_11"] = FILLER + "Refunds above $500 need manager approval. " + FILLER
DOCS["doc_17"] = FILLER + "The refund window used to be 30 days before the change. " + FILLER


def tok(text: str) -> int:
    return count_tokens({"content": text})


def research(keyword: str, with_provenance: bool = True, cap: int = 3) -> tuple[str, int]:
    """The sub-call: reads every document in ITS OWN window. Returns (summary, tokens it had to read)."""
    read, findings = 0, []
    for doc_id, text in DOCS.items():
        read += tok(text)
        for sentence in re.split(r"(?<=[.!?])\s+", text):
            if keyword in sentence.lower():
                findings.append(f"{sentence} (from {doc_id})" if with_provenance else sentence)
    return "Findings: " + " | ".join(dict.fromkeys(findings[:cap])), read


main = [{"role": "user", "content": "Policy question: what is our refund window and who approves large refunds?"}]
before = sum(tok(m["content"]) for m in main)

# Without delegation, the main window would hold every document the agent read.
inline = before + sum(tok(t) for t in DOCS.values())

summary, read_in_sub = research("refund")
main.append({"role": "tool", "content": summary})
after = sum(tok(m["content"]) for m in main)

print(f"main window before:               ~{before:>5} tokens")
print(f"documents the sub-call read:      ~{read_in_sub:>5} tokens (stay in the sub-call)")
print(f"main window if done inline:       ~{inline:>5} tokens")
print(f"main window after delegation:     ~{after:>5} tokens")
print("\nWhat came back:")
print(" ", summary)

plain, _ = research("refund", with_provenance=False)
print("\nSame task, no 'with citations' in the return spec:")
print(" ", plain)
print("\nThe summary is a bottleneck: can the main agent now answer 'which meeting changed it'?",
      "date" in summary.lower() and "meeting" in summary.lower())
Output · real, python3 sub_context.py12 lines
main window before:               ~   22 tokens
documents the sub-call read:      ~ 3041 tokens (stay in the sub-call)
main window if done inline:       ~ 3063 tokens
main window after delegation:     ~   77 tokens

What came back:
  Findings: The refund window was changed to 45 days on 3 March. (from doc_4) | Refunds above $500 need manager approval. (from doc_11) | The refund window used to be 30 days before the change. (from doc_17)

Same task, no 'with citations' in the return spec:
  Findings: The refund window was changed to 45 days on 3 March. | Refunds above $500 need manager approval. | The refund window used to be 30 days before the change.

The summary is a bottleneck: can the main agent now answer 'which meeting changed it'? False

The sub-call read about 3,041 tokens that never entered the main window, which grew from 22 to 77 tokens instead of about 3,063. The citations (from doc_4) cost a few tokens and let the main agent say where a claim came from. The last line shows the price: the findings say nothing about which meeting changed the window, so answering that means delegating again. Decide what the main agent will need before you write the return spec.


Part 9: Evaluate it#

Compaction can silently destroy exactly the facts you needed. Evaluation here asks one question: after trimming, does the model still behave as if it remembered?

Concept lessons (read first)

What to measure

Question Metric Pass rule (starting point)
Did the facts survive? Probe retention rate: probes present / probes written 100% for rules and ids; at least 90% for soft facts
Does the model act on them? Paired continuation: same next question with full history and with trimmed history; compare answers Same answer on 95% or more of pairs
Is the summary honest? Unsupported-claim count: summary sentences not backed by the source 0 for rules and ids
Is it worth it? Compression ratio vs fidelity Report both; never ratio alone
Does repeated compaction drift? Probe retention after 1, 2, 3 compactions No drop across the first two
Did we break the API shape? Orphaned tool calls or results after trimming 0
Can the model get a cleared result back? Re-fetch success: stubs whose handle resolves to the original text / stubs written 100%
Does a fresh window resume correctly? Facts in the start-up prompt (state counts, next task, the rule) match the files All match; no test removed or renamed
Does delegation lose what the main agent needs? Return completeness: required facts present in the sub-call's return / required facts 100% for ids and decisions; each claim has a source

A tiny eval you can run now. Inputs: chat in eval_compaction.py with four probes. Metric: probe retention per strategy. Pass rule: 100% on all four probes. Result above: sliding window and truncation fail (0 of 3 non-recent probes), clearing and rolling summary pass. Run orphans from tool_results.py on the output of every strategy as well: it should print nothing. Next step: replace FakeSummarizer with a real call, add 10 more probes, add the paired-continuation check, and run it in CI whenever the summary prompt or the window size changes.

DeepEval lessons (required track)

Inspect lessons (optional)

The revision-1 bullet for this item: evaluating memory and compaction (write and read quality, compaction fidelity, long-session tests) links to 10A.11 for the concepts and to 10B.4, 10B.6 and 10B.15 §10.3 for the tooling.


Common misconceptions#

  • "Summaries are lossless." They are lossy by design. The question is which facts you lose.
  • "The newest messages are all that matter." Early rules and ids often matter most.
  • "A bigger window means we do not need this." Quality can drop and cost grows with length even when everything fits (08B.5, Part 3).
  • "Provider compaction is a feature I can stop testing." The compaction item may be opaque. Probes and paired continuations still apply.
  • "Dropping the oldest message is always safe." It is not if it breaks a tool call and result pair.
  • "Clearing a tool result deletes the fact." Only the long output. Keep the extracted fact in a note or the summary if later steps need it.
  • "Summarise on every turn to be safe." That multiplies cost and compounds error. Fold in batches.
  • "Delete old tool results and the problem is gone." A bare placeholder invites the model to guess. Say what was cleared and how to get it back, and make sure the fetch tool exists.
  • "A sub-agent always saves context." It saves the main window, but whatever its return leaves out is gone, and it costs extra calls and latency. If one read_file call is enough, use that.
  • "A progress file is a log I can keep appending to." It becomes the new flood. Rewrite it short and keep the detail in git.
  • "Memory across sessions is just a longer window." It is a different system with its own store, write path and risks (08B.4).

Key takeaways#

  • Decide the keep-list first (rules, constraints, ids, corrections, open tool pairs, recent turns), then write the trimming policy.
  • Sliding windows and plain truncation are cheap and silently forget. Pin what must stay.
  • Never drop one half of a tool call and result pair.
  • Rolling summaries cost a model call, drift over repeated folds and need a keep-list in the prompt. Fold in batches.
  • Clear old tool results first: biggest saving, no model call.
  • Provider features (OpenAI compaction, Anthropic compaction and context editing, as of 1 December 2026, several in beta) do part of this server-side. They are a safety net, not a test result.
  • Test with probes: a trimming strategy is only as good as the facts it provably keeps.
  • Manage tool results by policy: recent and small stay whole, the rest becomes an annotated stub with a digest and a handle, and the fetch path must exist before you stub anything.
  • Describe an image or file before you drop it from history, and keep the file.
  • For tasks that outlive a window, put state in files (a guarded task list, a short progress note, git) and start each window with a prescriptive prompt. A fresh window can beat compaction.
  • Delegate noisy sub-tasks to a fresh context, give it only what it needs, and specify a return with provenance. Prompt-level context management stays in 04.7.

Terms introduced in this lesson#

Term Meaning
Short-term memory The part of a session the model can see on this call; the conversation state inside the context window
Context window The maximum number of tokens a model can read in one request
Sliding window Keeping only the last N turns
Token-aware truncation Dropping the oldest messages until the total fits a token budget
Pinned message A message that trimming must never remove
Rolling summary A running summary updated as old messages are folded into it
Fold Replacing a batch of old messages with an update to the summary
Tool-result clearing Replacing old, bulky tool outputs with a short placeholder
Call/result pair A tool call and its matching result, which must be kept or dropped together
Probe A string that must still be visible after trimming; used to test compaction
Compaction Replacing older context with a shorter, model-written summary (client-side or provider-side)
Context editing Rule-based, server-side clearing of old tool results or thinking blocks (Anthropic)
Compaction item / block The provider's stored result of compaction: opaque and encrypted (OpenAI) or readable and signed (Anthropic)
Keep-list The explicit list of what must survive trimming verbatim
Result policy Rules that decide, per tool result, whether it stays whole, is truncated or becomes a stub with a handle
Stub A short placeholder that says what was cleared, how big it was and how to get it back
Handle A meaningful identifier (a path, query id or result id) that lets the model re-fetch stored content
Just-in-time retrieval Keeping identifiers in context and loading the content through a tool only when it is needed
Progress file A short notes file (what is done, what is next, what to avoid) that the next context window reads first
Start-up prompt The prescriptive first message for a fresh window: where to look, what to run, which rules to obey
Sub-context isolation Handing a sub-task to a separate call with a fresh context and taking back only a distilled result
Distilled result The short, sourced summary a sub-call returns to the main conversation

Exercises#

  1. Pin by pattern. Write auto_pin(msgs) that sets pinned on any message containing never, always or only, then rerun the demo with plain truncation. Which probes now pass? Hint: reuse the regex idea from FakeSummarizer, and check that pinned messages alone do not exceed the budget, otherwise truncate_to_budget stops early.
  2. Pairs. Add a test that builds a history where the oldest message is a tool result and show that truncate_to_budget removes its call too. Then break the pairing on purpose and write a checker orphans(msgs) that returns call ids without results. Hint: compare the set of call_id values on assistant calls with those on tool messages.
  3. Batch size. Change keep_recent to 2, 6 and 12 and count summarizer calls for the 49-message chat. Which setting costs least and which keeps the most verbatim context? Hint: the fold trigger is keep_recent * 2, so a larger keep_recent folds less often but keeps more raw text.
  4. A distorting summarizer. Write a LossySummarizer that rewrites "never" as "prefers" and rerun eval_compaction.py with a probe for the exact word "never". Does your probe catch it? Hint: probe on the exact phrase "Never email", not on "phone only".
  5. Cache-aware clearing. Add a clear_at_least_tokens parameter to clear_tool_results that skips clearing when it would free fewer tokens than the threshold. Show a case where skipping is right. Hint: compute total(msgs) - total(cleared) first and return the original list if it is too small.
  6. Real summarizer, offline. Replace FakeSummarizer with a function that returns canned summaries from a dict keyed by the batch's first message, to simulate a model that forgets one fact. Measure which probes fail. Hint: it is the same interface, (old_summary, msgs) -> str, so nothing else changes.
  7. Handles for pages. Add a tool-style function fetch_result(handle, page) around ResultStore.fetch and write a loop that re-reads a stored result until has_more is false. Check that the text you reassemble equals the original. Hint: pages are slices of the stored string, so join them in order and compare.
  8. A stricter task-list guard. In progress_files.py, make update_tests refuse a status change from passing back to not_started unless a reason string is given, and log the reason in progress.txt. Hint: read the current status before applying the change.
  9. A better return spec. In sub_context.py, extend research to return the date or sentence number of each finding along with its source, then re-ask "which document changed the window?" Show which question the old return could not answer and the new one can. Hint: add fields to the finding string and count the extra tokens.

Check yourself#

  1. What is short-term memory, and how does it relate to the context window?
  2. Name five things the keep-list says to keep word for word.
  3. Why are a sliding window and token truncation dangerous even when they "work"?
  4. Why must a tool call and its result be dropped together?
  5. Why fold a rolling summary in batches instead of every turn?
  6. Name three ways a summary can fail.
  7. What does tool-result clearing keep, what does it remove, and why tell the model it happened?
  8. What is a probe, and what does a probe retention matrix tell you?
  9. Name the two OpenAI compaction mechanisms and the three Anthropic ones from the 1 December 2026 docs, with the beta status of the Anthropic ones.
  10. Why does Anthropic's clear_at_least parameter exist, and why is a compaction item hard to test by reading it?
  11. Name three treatments for a bulky tool result besides clearing it, and say when each fits.
  12. What must be true of a handle and of the tool that resolves it, for stubbing to be safe?
  13. Why describe an image before you drop it from history?
  14. Give three things a start-up prompt for a fresh window should say, and one reason a fresh window can beat compaction.
  15. What does a sub-context return, what stays behind, and what is the main risk of the summary?
  16. What do Gemini's plain API and OpenRouter's context-compression plugin each give you for long history, and what is the limit of each?

Further resources#


← 08B.2 — Memory for Agents: Short-Term and Long-Term | Module 08B overview | 08B.4 — Long-Term Memory and Memory Operations →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close