Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
Four support-desk transcripts, four different failures. Name the failure first (tool bloat, side-job bloat, a long dialogue or a lost rule), then pick prune, isolate, compact or a fresh session with a handoff.
What you will learn
- Tell bloat (size) from drift (a lost rule or fact) in a long session
- Match each failure to its fix: prune, isolate, compact or start fresh
- Write a triage function that checks a broken rule first, then side-job share, then tool share
- Build a handoff that carries the goal, the rule and the verified facts into a fresh session
Before you start
- Context engineering for a long-running agent
- Basic Python
Picture a support desk with one chat that has been open all day. Somewhere along the way the agent forgets a rule it was given at the start, and nobody notices. There are four fixes on the table: compact, prune, isolate, and start fresh. The skill is choosing between them, and that starts with naming the failure.
The moves themselves (clearing tool results, compacting, a notes file) are built step by step in context engineering for a long-running agent. This article is about the decision.
Two ways a long session goes wrong
- Bloat is about size. Tool output fills the window, every turn sends the whole history again, and in the end the API says the prompt is too long.
- Drift is about what the model still holds. A rule from the start is ignored. An answer the user already rejected comes back. A fact the agent knew is asked for again.
Both show up in numbers you can measure: the share of the window that is tool output, the share that belongs to a side job, and how often the rule is broken.
Four fixes, and what each one treats
The API features behind these fixes (context editing, compaction and the memory tool) are in memory and context-window patterns for Claude agents.
| Fix | What it does | Treats |
|---|---|---|
| Prune | Your code trims each tool result: header, note, one row | Bloat from tool output |
| Isolate | A side job runs in a subagent; only its result comes back | Bloat from a side job |
| Compact | Older turns are summarised and the thread carries on | A long dialogue, facts intact |
| Start fresh | A new session from a handoff: goal, rule, facts, next step | Drift: a rule or fact already lost |
Pick by the symptom, not by the newest feature. Each fix keeps something different.
Decide in this order
When a fresh session beats compaction
Compaction looks like the natural fix for any long chat, so let's be precise about where it fails. The older turns are about to be summarised. They hold the desk rule (never promise a delivery date), a big tool result and a few answers. The summary says: steps done, order looked up, address checked. The rule didn't make it in, and nobody saw it go. The very next reply promises a delivery date.
Now the fresh start. A handoff holds the goal, the rule, the facts, what's done and what comes next. The tool output, the dead ends and the apologies stay behind. A summary keeps what the model thought mattered. A handoff keeps what you decided must last.
A fresh session wins when the rule or the facts are already gone, or when the history is full of wrong turns. Claude Code offers the same choice when you return to a session: resume it, fork it, or start fresh.
triage.py: name the failure in code
"""Name the context failure first, then pick the fix."""
from transcript import Transcript
def window(t: Transcript):
"""Turns since the last summary: all the model sees."""
return t.turns[t.last_summary():]
def signals(t: Transcript):
turns = window(t)
total = sum(x.tokens for x in turns)
tool = sum(x.tokens for x in turns if x.kind == "tool")
side = sum(x.tokens for x in turns if x.job == "side")
banned = t.notes["banned"]
said = [x for x in turns if x.kind == "assistant"]
broken = sum(banned in x.text.lower() for x in said)
return {"total": total, "broken": broken,
"tool": tool / total, "side": side / total}
def diagnose(t: Transcript):
s = signals(t)
if s["broken"]:
return "drift: the rule is lost", "fresh"
if s["side"] >= 0.4:
return "bloat: a side job", "isolate"
if s["tool"] >= 0.6:
return "bloat: tool output", "prune"
return "a long dialogue, facts intact", "compact"
Two details matter. window reads only the turns since the last summary, because that's all the model sees. And the broken-rule check comes first in diagnose, in the same order as the diagram.
handoff.py: only what the next session needs
"""A handoff: only what the next session needs."""
from transcript import Transcript
def build_handoff(t: Transcript):
n = t.notes
top = [f"Goal: {n['goal']}", f"Rule: {n['rule']}"]
lines = ["HANDOFF"] + top + ["Facts:"]
lines += [f"- {fact}" for fact in t.facts]
lines += [f"Done: {n['done']}", f"Next: {n['next']}"]
return "\n".join(lines)
The goal and the rule go first, because those two must not drift. Then only verified facts, one line each. Done and Next tell the new session where to pick up. No tool output, no dead ends, no apologies cross over.
Four sessions, four answers
The project diagnoses four of our own transcripts (token counts are our numbers), then carries the last one into a fresh session. The replies come from a stand-in model on a mock transport, scripted to follow the desk rule only when the rule is in the request. That's the demo's choice, not a claim about a model.
transcript window tool side broken failure fix
t0_planning_chat 14k 0% 0% 0 a long dialogue, facts intact compact
t1_refund_desk 66k 97% 0% 0 bloat: tool output prune
t2_log_hunt 39k 96% 93% 0 bloat: a side job isolate
t3_shipping_promise 3k 0% 0% 2 drift: the rule is lost fresh
HANDOFF
Goal: tell the customer the parcel status
Rule: never promise a delivery date
Facts:
- ORD-5120 is with the carrier since Monday
- the carrier gives no delivery date
Done: order and address checked
Next: share the latest scan, no date
same session 6 msgs It will be delivered by Friday.
fresh + handoff 1 msgs I can't promise a date. The latest carrier scan is Tuesday.
Look at t3_shipping_promise. It's tiny, only 3k tokens, yet the rule was broken twice. A bigger window or pruning wouldn't help, because the problem isn't size. t2_log_hunt is 96% tool output, but it's tagged as a side job, so the answer is isolate, not prune: the raw logs belong in a subagent, which is the subject of context isolation through subagents.
Common mistakes
- Compact every long session. A summary can drop the rule, silently.
- Start fresh at the first long chat. That throws away work that was fine.
- Prune whatever is biggest. Pruning can't bring a lost rule back.
- A bigger context window. It delays bloat and does nothing for drift.
Recap
| Symptom | Failure | Fix |
|---|---|---|
| Old tool output piling up | Bloat | Prune |
| A side job floods the window | Bloat | Isolate in a subagent |
| Long dialogue, facts intact | Neither yet | Compact |
| A rule or fact is lost | Drift | Start fresh with a handoff |
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.