Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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.

FixWhat it doesTreats
PruneYour code trims each tool result: header, note, one rowBloat from tool output
IsolateA side job runs in a subagent; only its result comes backBloat from a side job
CompactOlder turns are summarised and the thread carries onA long dialogue, facts intact
Start freshA new session from a handoff: goal, rule, facts, next stepDrift: a rule or fact already lost

Pick by the symptom, not by the newest feature. Each fix keeps something different.

Decide in this order

Four questions, first yes wins 1. Did the session break a rule? yes start fresh 2. Side job is 40% or more of the window? yes isolate 3. Tool output is 60% or more of the window? yes prune otherwise: compact
A lost rule is checked first, because no other fix can bring it back. The 40% and 60% thresholds are our own numbers for this demo.

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

SymptomFailureFix
Old tool output piling upBloatPrune
A side job floods the windowBloatIsolate in a subagent
Long dialogue, facts intactNeither yetCompact
A rule or fact is lostDriftStart fresh with a handoff

Keep going in Claude · 43 of 66

Previous
Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
Next post
Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Two ways a long session goes wrong
  • Four fixes, and what each one treats
  • Decide in this order
  • When a fresh session beats compaction
  • triage.py: name the failure in code
  • handoff.py: only what the next session needs
  • Four sessions, four answers
  • Common mistakes
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.