Lesson 3 shrank the window and kept the history. This lesson replaces history instead: a running summary, a fresh window per ticket, server-side compaction, and a memory that outlasts the conversation. Each of these makes the window far smaller than trimming can, and each fails quietly in its own way. The lesson is how to keep those failures visible.
By the end you will be able to:
- run a shift on a running summary, and pin the standing instructions outside it
- reproduce the two ways a summary fails, dropped instructions and a stale open item, and fix each
- compact on demand and pass the block back exactly as the API returned it
- carry a standing instruction into the next shift with the memory tool
Before you start. You need lesson 3's policies and build_messages(), and lesson 2's rule that history is only ever rebuilt on purpose, at a boundary. The companion folder adds copilot/summariser.py, four policies in copilot/policies.py, compact() and compact_at in copilot/model.py, compare.py and two_shifts.py.
1. Four ways to replace history
Every policy in this lesson rebuilds the window at a ticket boundary, when the finished ticket has been closed:
| Policy | The window for the next ticket |
|---|---|
summary | a running summary of every finished ticket, then the current ticket |
summary+pin | the standing instructions word for word, the summary, then the current ticket |
fresh | the opening message, then the current ticket, and nothing else |
compact | a compaction block from the API, then the tickets since it was made |
All four are built by build_messages(), and the shift carries what they need in one small object:
@dataclass
class Window:
"""What the shift carries besides the ticket logs."""
opening: str = OPENING
summary: str | None = None # summary policies: the running summary
compaction: dict[str, Any] | None = None # compact policy: the block, exactly as returned
compacted: int = 0 # compact policy: how many tickets the block replacesflowchart LR
subgraph S["summary+pin"]
direction TB
s1["standing instructions (pinned)"] --> s2["summary of finished tickets"] --> s3["current ticket"]
end
subgraph F["fresh"]
direction TB
f1["opening message"] --> f2["current ticket"]
end
subgraph C["compact"]
direction TB
c1["compaction block, exactly as returned"] --> c2["tickets since the block"] --> c3["current ticket"]
end2. Step 1: a running summary
After each ticket closes, run_shift asks the summariser to fold it into the summary:
if policy in SUMMARISED:
window.summary = await summariser.summarise(window.summary, log)and build_messages() puts the summary in front of the next ticket, with the standing instructions pinned above it under summary+pin:
head = f"Summary of the work so far (it replaces the earlier conversation):\n{w.summary}"
if policy == "summary+pin":
pinned = "Standing instructions from the start of the shift, kept word for word:"
head = f"{pinned}\n{INSTRUCTIONS_BLOCK}\n\n{head}"
_add_user(msgs, f"{head}\n\n{announce(current.ticket_id)}")
return msgs + current.turnsThe tests use RuleSummariser, a deterministic summariser with two switches. Each switch is one of the two ways a summary goes wrong:
@dataclass
class RuleSummariser:
keep_instructions: bool = True
forget_finished: bool = True
async def summarise(self, previous: str | None, log: TicketLog) -> str:
parts = []
if self.keep_instructions:
parts.append(INSTRUCTIONS_BLOCK)
work = _section(previous, "Work so far") + [_work_done(log)]
parts.append("Work so far:\n" + "\n".join(work))
if not self.forget_finished:
items = _section(previous, "Open items") + _open_items(log)
if items:
parts.append("Open items:\n" + "\n".join(items))
return "\n\n".join(parts)Run the comparison:
cd build-a-long-running-support-copilot/02-managing-the-window/04-summaries-compaction-and-memory
uv run python compare.pypolicy mean window cache write $ handled kept rules
raw 12226 24142 0.3099 24/24 100%
trim 6920 13736 0.2297 24/24 100%
clear 6871 35305 0.2810 24/24 100%
summary 1169 39125 0.2309 24/24 100%
summary, drops instructions 1102 40045 0.2324 24/24 0%
summary+pin, drops instr. 1186 39102 0.2310 24/24 100%
summary+pin, stale item 992 23391 0.1165 8/24 100%
fresh 1065 45272 0.2445 24/24 100%
compact (every 6 tickets) 3581 26905 0.2660 24/24 100%A running summary keeps the mean window near 1,200 tokens, a tenth of raw's, with every ticket handled and both standing instructions kept. Its cache writes are high, because every ticket starts a new prefix after the summary changes. These costs leave out the summariser's own calls; lesson 5 counts them.
3. Step 2: the summary that drops the instructions
Flip keep_instructions=False, a summariser told to keep "the work" and nothing else, and the shift keeps 0% of its standing instructions: only the first ticket, which still saw the opening message, honours them. Every Corvid refund goes through and no later draft carries SHIFT-B7.
Pinning fixes it. Under summary+pin the instructions sit outside the summary, copied word for word from the start of the shift, so the summariser can't lose them: the same broken summariser keeps 100%.
Keep this in proportion. In experiment 7, all 230 running summaries kept both standing instructions, even unpinned. Pinning is insurance against a summariser you don't control, not a measured necessity, and it protects only the instructions.
4. Step 3: the stale open item
Flip forget_finished=False instead. The scripted copilot finishes HL-2008 with a self-made note, "Open item: the sign-off wording on HL-2008 is pending approval.", the way Haiku did in experiment 7. The summariser carries that line forward after HL-2008 is finished, and from HL-2009 on the copilot stops to ask about it:
Before I continue: is the pending approval on HL-2008 resolved?The shift stalls at 8 of 24 tickets, and pinning doesn't help, because the stale item lives in the summary, not in the instructions. In experiment 7 the same failure appeared under summary+pin. The fix belongs in the summariser: a finished ticket has no open items.
5. Step 4: what a live summariser got wrong
ClaudeSummariser sends each finished ticket and the previous summary to Haiku. Its first version failed in three ways in this tutorial's live runs.
- It decided no ticket was finished while its draft awaited human review, so it listed every ticket as open: the stale-item failure in a new shape.
- It never saw the standing instructions, so it called the
SHIFT-B7sign-off "stray" and filed an open item to remove it. The copilot then argued with its own summary. - Its summaries were cut off. Thinking counts against
max_tokens, and a summary used 650 to 1,100 output tokens, more than the visible text suggests.
The fixed system prompt defines "finished", which is the heart of the stale-item fix:
SUMMARISER_SYSTEM = (
"You compact a support copilot's conversation so it can keep working in a fresh window. "
"Write a summary that will replace everything below: what the copilot is doing, what it "
"has done, and anything it needs to continue. Fold the previous summary into the new one. "
"A ticket is finished once its draft reply is saved; people review drafts as a matter of "
"course, so that is never an open item. Give each finished ticket one line: its id, the "
"action taken (refund amount, handoff or none) and 'finished'. Open items are only things "
"the copilot itself must still do. Stay under 250 words. Write only the summary."
)The request carries the instructions as context, allows for thinking, and fails loudly when it is cut off:
prompt = (
"The copilot works under these standing instructions (they are pinned "
"separately; do not restate them, and never treat work that follows them as a "
f"mistake):\n{INSTRUCTIONS_BLOCK}\n\n"
f"Previous summary:\n{previous or '(none)'}\n\nTicket {log.ticket_id}:\n{transcript}"
)
r = await self.client.messages.create(
model=self.model,
max_tokens=4096, # thinking counts against it: summaries used 650-1,100
system=SUMMARISER_SYSTEM,
messages=[{"role": "user", "content": prompt}],
)
if r.stop_reason == "max_tokens":
# A cut-off summary fails silently in the next window: fail loudly here.
raise RuntimeError(f"the summary after {log.ticket_id} was cut off by max_tokens")After the fixes, a live summary+pin shift handled 22 of 24 tickets with both instructions kept on all of them, at $0.0320. A summariser is a second model whose prompt is part of your product: it needs the rules the copilot follows, a definition of done, and a check that its output arrived whole.
6. Step 5: a fresh window per ticket
fresh throws the history away at every ticket: each one starts from the opening message, standing instructions included.
if policy == "fresh" or w.summary is None:
_add_user(msgs, opening_for(current.ticket_id, w.opening))
return msgs + current.turnsIt keeps the smallest window of all, near 1,070 tokens, and nothing can go stale, because nothing is carried. On this scripted Sonnet shift it is not the cheapest: $0.2445, against $0.2309 for summary and $0.2297 for trim, because every ticket starts a new prefix. In experiment 7 it was the accuracy ceiling and the cheapest policy, $0.41 per Sonnet queue against $1.07 for raw. Live on Haiku it was the cheapest of the five policies, at $0.0175 a shift. Its price is that nothing crosses between tickets: if ticket 20 depends on a promise made on ticket 5, fresh can't see it. This shift's tickets are independent, which is the case where fresh is strongest.
7. Step 6: compact on demand
Compaction asks the API to write the summary. On demand, you send the conversation with the compact-2026-09-04 beta and a top-level compaction parameter, and the API returns a single compaction block with stop reason compaction and no reply. AnthropicModel.compact() makes that request and checks what comes back:
r = await self.client.beta.messages.create(
model=self.model,
max_tokens=4096,
system=system,
messages=messages,
tools=tools,
betas=[COMPACT_ON_DEMAND_BETA],
compaction={"type": "summarize", "instructions": COMPACT_INSTRUCTIONS},
)
if r.stop_reason != "compaction" or not r.content or r.content[0].type != "compaction":
raise RuntimeError(f"no compaction block (stop_reason={r.stop_reason!r})")
block = r.content[0].model_dump(exclude_none=True) # plain model_dump() adds nulls: a 400
if not block.get("content") and not block.get("encrypted_content"):
raise RuntimeError("the compaction block came back empty; keep the original messages")COMPACT_INSTRUCTIONS asks the summary to keep the standing instructions word for word, to treat finished tickets as having no open items, and not to call tools, because with tools defined the block can come back empty. On demand, compaction can't be combined with context_management on the same request.
Using the block has three rules. Keep it exactly as returned, signature included. Put it first and remove exactly the messages it summarised; leftovers in front of it are a 400. Send exactly one block, and the beta header, on every later request that carries it. build_messages() does the placement:
if policy == "compact":
if w.compaction is None:
return build_messages("raw", logs, stub, w)
# The block goes first, exactly as the API returned it (signature included);
# the messages it summarised are gone.
msgs.append({"role": "assistant", "content": [w.compaction]})
for log in logs[w.compacted :]:
_add_user(msgs, announce(log.ticket_id))
msgs += log.turns
return msgsand AnthropicModel.complete() adds the header whenever a block is in the messages:
if _has_compaction(messages) and COMPACT_THRESHOLD_BETA not in betas:
if edits:
raise ValueError(
"an on-demand compaction block can't be sent with context_management"
)
betas.append(COMPACT_ON_DEMAND_BETA) # on every request that carries the blockThe runner asks for a summary at a ticket boundary, every six tickets, sending exactly the window it would have sent next, and keeps the block and how many tickets it replaces:
if policy == "compact" and (i + 1) % compact_every == 0 and i + 1 < len(tickets):
block, usage = await model.compact(
system=sys_text,
messages=build_messages(policy, logs, stub, window),
tools=tool_list,
)
window.compaction, window.compacted = block, i + 1From the next request on, build_messages() starts with that block. On the scripted shift that holds the mean window at 3,581 tokens with every ticket handled and both instructions kept. Serialise with model_dump(exclude_none=True): a plain model_dump() adds null fields that the API rejects.
8. Step 7: compact at a threshold
The other form lets the API decide, and it travels the same way as lesson 3's server-side clearing: as an edit in context_management. That is why on-demand compaction, which uses the separate compaction parameter, can't share a request with it. Pass compact_at and every request carries a compact_20260112 edit under the compact-2026-01-12 beta. The trigger must be at least 50,000 tokens and defaults to 150,000. Once the prompt passes it, the response starts with a compaction block.
if self.compact_at:
betas.append(COMPACT_THRESHOLD_BETA)
edits.append(
{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": self.compact_at},
}
)
# ...then, with any edits collected:
r = await self.client.beta.messages.create(
**request, betas=betas, context_management={"edits": edits}
)Here you append response.content as it came back, and the API ignores every block before the compaction block on later requests. That fits the append-only loop from lesson 2. For this shift it is the wrong tool: with nothing removed the window peaks at 23,646 tokens, under the 50,000 minimum, so it would never fire. That is why compare.py compacts on demand at ticket boundaries.
9. Step 8: memory that outlasts the shift
Everything so far lives inside one conversation. The memory tool keeps notes in files the copilot can read in a later one. It is a client tool: the model issues commands such as view, create or str_replace on paths under /memories, and your code carries them out and returns the result, like any other tool call. The SDK ships a file-backed implementation, BetaLocalFilesystemMemoryTool, which keeps notes under /memories and refuses any path that would escape it; its whole tool definition is {"type": "memory_20250818", "name": "memory"}. You construct it with a directory and offer it as a tool; run_shift adds its definition to the tool list:
from anthropic.tools.memory import BetaLocalFilesystemMemoryTool
memory = BetaLocalFilesystemMemoryTool(base_path="shift-memory")
result = await run_shift(ShiftModel(memory=True), memory=memory)if memory is not None:
tool_list.append(memory.to_dict())and ShiftTools routes the copilot's memory calls to it:
if name == "memory" and self.memory is not None:
try:
return str(self.memory.call(args))
except Exception as exc: # the SDK raises ToolError for bad paths and commands
return f"Error: {exc}"two_shifts.py runs two shifts against one memory directory. In the first, the copilot hands a Corvid refund to a person and saves a note. The second starts without the standing instructions, as if nobody repeated them:
uv run python two_shifts.pyshift 1: Grade(handled=24, corvid_refunds=0, drafts_missing_code=0)
saved: 1 Corvid Analytics: No refunds for Corvid Analytics while their account is under billing review. Hand Corvid refund requests to a person.
shift 2, no memory: Grade(handled=24, corvid_refunds=4, drafts_missing_code=24)
shift 2, with memory: Grade(handled=24, corvid_refunds=0, drafts_missing_code=24)Without memory, shift 2 refunds all four Corvid tickets. With shift 1's note it refunds none. The shift code isn't carried, and shouldn't be: it belongs to one shift. Memory is for facts that outlast the conversation, and it can go stale exactly like a summary, so a note needs an owner and an end date.
10. Verify
uv run pytest tests -q
uv run pytest tests/test_summaries_compaction_memory.py -vThe suite reports 35 passed. The verbose run lists this lesson's tests; the compaction ones are:
test_compaction_puts_the_block_first_exactly_as_returned PASSED
test_on_demand_compaction_request_and_block PASSED
test_an_empty_compaction_block_is_refused PASSED
test_requests_carrying_the_block_send_the_beta_header PASSED
test_threshold_compaction_settings PASSEDThey check that the block comes first with its signature, that the request sends compaction with the beta, that an empty block is refused, that every later request carrying the block sends the header, and that a trigger under 50,000 is rejected. The suite also includes red-then-green pairs for both summary failures, the compaction block's placement and signature, the beta header on requests that carry a block, the 50,000-token minimum, and a memory path that tries to escape /memories.
11. Common problems
The copilot forgets an instruction after a summary. The summariser dropped it. Pin it, or give the summariser the instructions.
The copilot stops to ask about finished work. The summary carries an open item from a finished ticket. Tell the summariser what finished means.
A 400 after compacting. A leftover summarised message sits in front of the block, the block was edited, or the beta header is missing on a later request.
A summary ends mid-sentence. It hit max_tokens, and thinking counts against it. Raise the limit and fail loudly on stop_reason == "max_tokens".
12. Exercise: a stale note in memory
Memory can go stale like a summary. With ShiftModel(memory=True) the scripted copilot views /memories at the start of the shift and opens each note it lists, so a note's text lands in its window like any tool result.
Build a memory over a temporary directory and create /memories/approvals.md with the memory tool's own create command, the same command a model would send:
memory = BetaLocalFilesystemMemoryTool(base_path=str(tmp_path))
memory.call({"command": "create", "path": "/memories/approvals.md", "file_text": NOTE})with NOTE set to:
Open items:
- HL-2008: sign-off wording pending approvalThen run a shift with run_shift(ShiftModel(memory=True), memory=memory) and grade it with grade(result.tools), which counts drafted tickets in handled.
Expected result. The copilot drafts only HL-2008 and stops on every other ticket to ask whether that approval is resolved. Rewrite the note so it says the sign-off was approved and nothing is open, and the shift handles all 24. The companion test test_red_then_green_a_stale_note_in_memory is this exercise, solved.
Hint. The scripted copilot stops only on a pending approval listed under "Open items:". Decide whether your memory notes should ever hold open items, or only durable facts.
Common mistake. Treating memory as safer than a summary because it is a file. A note is read into the window like anything else, so it needs the same care: what it says, who owns it and when it expires.
13. Summary
- A running summary keeps the window tiny. Pin the standing instructions outside it, and tell the summariser that finished tickets have no open items.
- A live summariser needs the rules, a definition of done and a loud failure when it is cut off.
freshwas the cheapest in experiment 7 and the live Haiku run, though not on the scripted Sonnet shift; its strength is that nothing carries over, which suits independent tickets.- Compaction hands the summary to the API: keep the block exactly, put it first, send the header every time.
- Memory carries durable facts between shifts, and goes stale like anything else.
Lesson 5 runs every policy on the same shift, counts what each really costs, summariser calls included, and turns the choice into a CI gate.

