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

Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live

An agent misbehaves and the log is all you have. Five short traces, five signatures, and a small reader that names the missing pattern (loop bound, loop test, isolation, memory or context management) and the fix that treats the cause.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Spot five trace signatures: a repeated call, a leak, a forgotten fact, a growing context and a tool_use that never ran
  • Name the missing pattern behind each: loop bound, loop test, subagent isolation, memory, context management
  • Write small Python checks that diagnose a trace
  • Choose a memory scope (turn, session or persistent) by how long a fact must live

Before you start

  • The agentic loop and stop_reason
  • Memory and context-window patterns for Claude agents

A stock checker asks about item K-204 and gets "0 in stock". Then it asks again, and again: four times, the same call and the same answer. Then the harness kills it, because the call budget is spent. Which pattern is missing? The log doesn't say. You read it, and you name it.

This article teaches one skill: read an agent's trace, find its signature, and name the missing design pattern. The five traces are test data from our own agents, and the reader is plain Python with no model call.

One sign, one missing pattern

Think of a dashboard light. It doesn't tell you the engine is broken; it points at the part that's missing. A trace works the same way: it shows a symptom, and the missing pattern is the cause.

Trace signature to missing pattern What the trace shows What is missing the same call, again and again loop bound a tool_use asked for, never run loop test a subagent mentions what it wasn't briefed on subagent isolation asks again for a fact it was told memory context grows every call, never cleared context management
A loop can fail two ways: it has no bound, or it stops on the wrong test.

traces.py: five agents, five logs

Each step is a tuple: a call number, a kind and some text.

"""Five trace excerpts from our test agents. A step is (call, kind, text)."""

# Agent 1: stock_checker asks the same question again and again
LOOP = [
    (1, "tool_use", "check_stock K-204"), (1, "result", "0 in stock"),
    (2, "tool_use", "check_stock K-204"), (2, "result", "0 in stock"),
    (3, "tool_use", "check_stock K-204"), (3, "result", "0 in stock"),
    (4, "tool_use", "check_stock K-204"), (4, "result", "0 in stock"),
    (5, "end", "killed by the harness: call budget spent"),
]

# Agent 2: reply_reviewer is a subagent, briefed on ticket T-9 only
LEAK = [
    (1, "brief", "review the draft reply for T-9"),
    (1, "context", "inherited 14 messages from the parent"),
    (1, "text", "Draft is fine. Also apologise for the T-8 delay."),
]

# Agent 3: delivery_planner, two sessions
FORGOT = [
    (1, "user", "fact: address = Dock 4"),
    (2, "text", "Noted. Delivery goes to Dock 4."),
    (3, "end", "session ended"),
    (1, "text", "Which address should I use?"),
]

# Agent 4: log_digger reads one big log page per call
OVERFLOW = [
    (1, "context", "1200"), (2, "context", "5800"),
    (3, "context", "10400"), (4, "context", "15000"),
    (5, "context", "19600"), (6, "context", "24200"),
    (6, "end", "stopped: context over the budget"),
]

# Agent 5: migration_checker has a plan of four steps
PREMATURE = [
    (1, "text", "Step 1 of 4: checking the tables."),
    (1, "tool_use", "list_tables"),
    (1, "stop", "tool_use"),
    (1, "end", "harness returned after the text block"),
]

reader.py: one check per signature

"""Read a trace, find its signature, name the missing pattern."""
import re

LIMIT = 20000   # our own context budget for the test agents


def kinds(steps, kind):
    return [text for _, k, text in steps if k == kind]


def loops(steps):
    uses = kinds(steps, "tool_use")
    top = max(uses, key=uses.count, default="")
    if uses.count(top) >= 3:
        return f"{top} repeated {uses.count(top)} times"


def stops_early(steps):
    answered = {call for call, k, _ in steps if k == "result"}
    for call, kind, text in steps:
        if kind == "tool_use" and call not in answered:
            return f"{text} was asked for and never run"


def ids(steps, kind):
    return set(re.findall(r"T-\d+", " ".join(kinds(steps, kind))))


def leaks(steps):
    extra = ids(steps, "text") - ids(steps, "brief")
    if extra:
        return f"{' '.join(sorted(extra))} is not in its brief"


def forgets(steps):
    facts, ended = {}, False
    for _, kind, text in steps:
        if kind == "user" and text.startswith("fact: "):
            key, value = text[6:].split(" = ")
            facts[key] = value
        elif text == "session ended":
            ended = True
        elif ended and kind == "text":
            for key, value in facts.items():
                if f"Which {key}" in text:
                    return (f"asks for the {key} again, "
                            f"it was {value}")


def overflows(steps):
    sizes = [int(text) for text in kinds(steps, "context")]
    rising = all(a < b for a, b in zip(sizes, sizes[1:]))
    if len(sizes) > 2 and rising and sizes[-1] > LIMIT:
        return (f"context {sizes[0]} -> {sizes[-1]} chars, "
                "never cleared")


CHECKS = [
    (loops, "loop bound", "cap the turns, stop when nothing changes"),
    (stops_early, "loop test", "go on while stop_reason is tool_use"),
    (leaks, "subagent isolation", "hand it only its brief"),
    (forgets, "memory", "save facts to notes, view them first"),
    (overflows, "context management", "clear old results or compact"),
]


def diagnose(steps):
    for check, missing, fix in CHECKS:
        found = check(steps)
        if found:
            return found, missing, fix
    return "no signature found", "none", "read more of the trace"
  • loops finds the call made most often; three or more of the same call is a loop.
  • stops_early collects every call that got a result. A tool_use without one never ran.
  • leaks compares the ticket ids in the subagent's output with the ids in its brief. An extra id is a leak.
  • forgets keeps each stated fact, marks where the session ended, and flags a question about a known fact after the reset.
  • overflows wants a size that only rises and ends above the budget. The 20,000 character budget is our own example number, not a platform limit.

Five traces, five names

trace 1 stock_checker: check_stock K-204 repeated 4 times
  missing: loop bound -> cap the turns, stop when nothing changes
trace 2 reply_reviewer: T-8 is not in its brief
  missing: subagent isolation -> hand it only its brief
trace 3 delivery_planner: asks for the address again, it was Dock 4
  missing: memory -> save facts to notes, view them first
trace 4 log_digger: context 1200 -> 24200 chars, never cleared
  missing: context management -> clear old results or compact
trace 5 migration_checker: list_tables was asked for and never run
  missing: loop test -> go on while stop_reason is tool_use

Traces 1 and 5 are both loop problems, with two different holes. The stock checker has no bound. The migration checker stopped on the wrong test: the stop reason was tool_use, but the harness returned after the text block. The right test is covered in the agentic loop and stop_reason.

Treat the cause, not the symptom

Each trace has a tempting fix that hides the symptom. The pattern removes the cause.

TraceTempting fixThe pattern
It loopsTell it to try harderCap the turns, stop when nothing changes
The subagent leaksTell it to ignore the restHand it only its brief (see context isolation with subagents)
It forgotA bigger windowSave facts to notes and view them first (see memory patterns)
The window overflowsA shorter questionClear old results, or compact (both in beta)
It stopped earlyA longer promptGo on while the stop reason is tool_use

A bigger window still resets. A shorter question doesn't shrink old results. Telling a subagent to ignore something doesn't hide it.

How long must the fact live?

The memory fix raises a design question: how long should an agent keep a fact? scopes.py answers it with two yes-or-no questions: is the fact needed after the reply, and is it needed after a window reset?

"""Memory scope: how long must an agent's facts live?"""

AGENTS = [
    # name, needs it after reply, needs it after reset
    ("invoice_formatter", False, False),
    ("support_chat", True, False),
    ("onboarding_guide", True, True),
]

WHERE = {"turn": "this request only",
         "session": "the chat's messages list",
         "persistent": "the memory tool"}


def scope(after_reply, after_reset):
    if not after_reply:
        return "turn"
    if not after_reset:
        return "session"
    return "persistent"
memory scope
  invoice_formatter turn        this request only
  support_chat      session     the chat's messages list
  onboarding_guide  persistent  the memory tool
  • The invoice formatter handles one invoice per request. Nothing is needed after the reply: a turn.
  • The support chat remembers the order during one chat, but not after a reset: a session, held in the messages list.
  • The onboarding guide remembers preferences for next week. That must survive a reset: persistent, in the memory tool.

Pick the shortest scope that still works, and keep nothing longer than the agent needs.

Quick recap

  1. Read the signature: what repeats, what leaks, what never ran, what grows.
  2. Name the missing pattern: loop bound, loop test, subagent isolation, memory or context management.
  3. Pick the fix that adds that pattern, not a patch on the symptom.

Try it yourself

Write a sixth trace where a subagent calls the same tool four times and mentions a ticket outside its brief. Run diagnose on it. It reports only the first match in CHECKS; change it to report every signature it finds, and decide which fix you'd apply first.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 33 of 66

Previous
Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
Next post
Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One

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

  • One sign, one missing pattern
  • traces.py: five agents, five logs
  • reader.py: one check per signature
  • Five traces, five names
  • Treat the cause, not the symptom
  • How long must the fact live?
  • Quick recap
  • Try it yourself
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.