Debugging Claude Agent Traces: Loops, Drift and Under-Acting

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 10 min read🎯 D1 Agent Pattern Diagnosis · D4 Failure-Mode Diagnosis

👋 In plain words: When an agent misbehaves, the trace (the list of what it said, which tools it called and what came back) tells you why. Testers already know how to read logs; this lesson teaches you to read agent traces the same way, and builds a small script that flags the most common agent bugs automatically.

Advertisement

Agent bugs rarely look like crashes. They look like an agent that keeps calling the same tool, answers without checking anything, stops halfway, or forgets a rule it was given an hour ago. The CCDV-F exam gives you a trace or a description and asks which design pattern is missing or misapplied. In this lesson you will learn six common failure patterns, read example traces for each, and build a trace analyser in Python that detects them.

📖 What You’ll Learn: You will be able to read an agent trace, recognise runaway loops, under-acting, ignored tool errors, early termination, context loss and subagent leakage, and choose the pattern that corrects each.

🔑 Key terms

  • Trace: the ordered record of an agent run: model turns, tool calls with inputs, tool results and stop reasons.
  • Under-acting: the agent answers without using the tools it needed, often by guessing.
  • Over-acting: the agent calls more tools than the task needs, wasting time and money.
  • Runaway loop: the agent repeats the same action without progress until a limit stops it.
  • Context loss: the agent stops following an instruction or fact from earlier in the run.

🪜 Step 1: Capture traces in a usable shape

Save every run as a list of steps. A compact format is enough:

📄 traces.py

def tool(name, inp, result, error=False):
    return {"type": "tool", "name": name, "input": inp, "result": result, "is_error": error}


def text(t, stop=None):
    return {"type": "text", "text": t, "stop_reason": stop}


TRACES = {
    "runaway": [tool("get_build", {"id": "812"}, "build 812: 3 failures")] * 6 + [text("…", "max_turns")],
    "under_acting": [text("Build 812 failed because of a database timeout.", "end_turn")],
    "ignored_error": [tool("get_logs", {"build": "812"}, "PermissionError: token expired", error=True),
                      text("The logs show no errors, so the build is healthy.", "end_turn")],
    "early_stop": [text("I'll check the logs for build 812 now.", "end_turn")],
    "context_loss": [tool("write_file", {"path": "tests/test_cart.py"}, "ok"),
                     tool("write_file", {"path": "src/cart.py"}, "ok"),
                     text("Done.", "end_turn")],
    "healthy": [tool("get_build", {"id": "812"}, "build 812: 3 failures"),
                tool("get_logs", {"build": "812"}, "TimeoutError waiting for #pay-button x3"),
                text("All 3 failures are the Pay button timeout; fix the payment widget first.", "end_turn")],
}
RULES = {"context_loss": "Only edit files under tests/."}

🪜 Step 2: Learn the six failure patterns

Pattern in the trace Missing or misapplied design pattern Fix
Same tool, same input, again and again; ends on a turn limit Loop termination / result handling: results not appended, or no progress check Append every tool_result; detect repeats; budgets as backstops
A confident answer with no tool calls, when data was needed Tool-use guidance (under-acting) Tell the agent when it must use tools; good tool descriptions; evaluate grounding
A tool returned is_error, then the agent claims success Error handling and honesty Surface errors; instruct to report failures; check claims against results
“I’ll check now” then end_turn Termination check in the harness or prompt Loop on stop_reason; for a final reply that only promises work, continue or flag it
Acting against an earlier rule (editing src/ when told “tests only”) Context management + deterministic guardrail Re-state rules, keep them in the system prompt, and enforce with a hook
Orchestrator context full of a subagent’s raw output Subagent isolation Subagents return short structured summaries
Advertisement

🪜 Step 3: Build a trace analyser

Each check looks for one signature. This runs locally on the example traces:

📄 analyse.py

import json

from traces import RULES, TRACES


def find_problems(trace: list[dict], rule: str | None = None) -> list[str]:
    problems = []
    tools = [s for s in trace if s["type"] == "tool"]
    final = trace[-1] if trace and trace[-1]["type"] == "text" else None

    calls = [json.dumps([s["name"], s["input"]], sort_keys=True) for s in tools]
    if any(calls.count(c) >= 3 for c in set(calls)):
        problems.append("runaway loop: the same tool call repeated 3+ times")
    if final and final["stop_reason"] in ("max_turns", "max_tokens"):
        problems.append(f"ended on a limit ({final['stop_reason']}), not on end_turn")
    promise_only = bool(final) and final["text"].lower().startswith(("i'll", "i will", "let me"))
    if not tools and final and not promise_only and any(ch.isdigit() for ch in final["text"]):
        problems.append("under-acting: specific claims with no tool calls")
    admits_failure = bool(final) and any(w in final["text"].lower() for w in ("could not", "couldn't", "failed to", "unable"))
    if any(s["is_error"] for s in tools) and final and not admits_failure:
        problems.append("ignored tool error: final answer does not report it")
    if final and final["stop_reason"] == "end_turn" and promise_only:
        problems.append("early stop: the final turn only promises work")
    if rule and rule.startswith("Only edit files under tests/"):
        bad = [s["input"]["path"] for s in tools if s["name"] == "write_file" and not s["input"]["path"].startswith("tests/")]
        if bad:
            problems.append(f"rule violated (context loss / missing guardrail): wrote {bad}")
    return problems


if __name__ == "__main__":
    for name, trace in TRACES.items():
        found = find_problems(trace, RULES.get(name))
        print(f"{name:<14} {'OK' if not found else '; '.join(found)}")

⌨️ Terminal

python analyse.py

🖥️ Output

runaway        runaway loop: the same tool call repeated 3+ times; ended on a limit (max_turns), not on end_turn
under_acting   under-acting: specific claims with no tool calls
ignored_error  ignored tool error: final answer does not report it
early_stop     early stop: the final turn only promises work
context_loss   rule violated (context loss / missing guardrail): wrote ['src/cart.py']
healthy        OK
  • Each check is cheap and deterministic. Run it on every production trace and alert on hits.
  • Some checks are heuristics (for example “specific claims with no tool calls”); treat hits as “look at this”, and confirm with a person or an LLM judge (Lesson 46).
Advertisement

🪜 Step 4: Isolate where the failure starts

For each flagged trace, find the first step where things went wrong, then ask whether the cause is in the harness (your code) or in the model’s behaviour:

  1. Harness causes: results not appended, wrong stop condition, tool exceptions swallowed, rules not enforced in code, context pruned too aggressively.
  2. Model causes: a vague tool description, missing instructions on when to use tools, an ambiguous goal, too low an effort level for the task.

Fix harness causes in code first: they are deterministic and easy to test. Then fix model causes with descriptions, prompts and examples, and re-run the trace checks plus your evaluation set.

💡 Tip: Replay is your friend. Save the full messages of a failing run and re-send them with the same model and settings after a fix. If the trace was caused by your harness, you can often reproduce it without calling the API at all, using a mocked client (Lesson 47).

🪜 Step 5: Pick the corrective pattern

📄 fix_map.py

FIXES = {
    "runaway loop": "append every tool_result; stop on repeated identical calls; keep max_turns as a backstop",
    "ended on a limit": "check why progress stopped; raise limits only after fixing the cause",
    "under-acting": "state when tools are required; sharpen tool descriptions; evaluate grounding",
    "ignored tool error": "return is_error results; instruct to report failures; verify claims against results",
    "early stop": "loop on stop_reason; treat promise-only final turns as incomplete",
    "rule violated": "keep the rule in the system prompt and enforce it with a PreToolUse hook",
}

from analyse import find_problems  # noqa: E402
from traces import RULES, TRACES  # noqa: E402

for name in ["runaway", "ignored_error", "context_loss"]:
    for problem in find_problems(TRACES[name], RULES.get(name)):
        key = next(k for k in FIXES if problem.startswith(k))
        print(f"{name}: {key} -> {FIXES[key]}")

⌨️ Terminal

python fix_map.py

🖥️ Output

runaway: runaway loop -> append every tool_result; stop on repeated identical calls; keep max_turns as a backstop
runaway: ended on a limit -> check why progress stopped; raise limits only after fixing the cause
ignored_error: ignored tool error -> return is_error results; instruct to report failures; verify claims against results
context_loss: rule violated -> keep the rule in the system prompt and enforce it with a PreToolUse hook
🎯 Exam focus: The skill “Agent Pattern Diagnosis” names tool-use loop termination, subagent isolation, memory and context-window management. In each item, find the first wrong step in the trace, decide whether a harness pattern is missing, and pick the fix that addresses the cause: “raise max_turns” or “use a bigger model” are almost always distractors.

🌍 Real-world example: Ravi’s “healthy build” report

Ravi’s agent once reported “no errors, build healthy” for a red build. The trace showed get_logs had returned is_error: true (an expired token), and the agent answered anyway. The fix had two parts: the system prompt now says “if any tool fails, say so and stop”, and a trace check fails the run whenever an error result is followed by a success claim.

Advertisement

🧪 Practice Questions

Question 1. A trace shows the agent calling get_build with the same ID six times, each returning the same result, then stopping at max_turns. What is the most likely harness defect?

  • A. The model is too small
  • B. Tool results are not being appended to the conversation (or repeats are not detected)
  • C. The tool description is too long
  • D. Streaming is disabled
Show answer

Answer: B. If Claude never sees the result, it asks again. Appending results and detecting repeats fixes the cause; a turn limit only stops it.

Question 2. An agent answers “Build 812 failed because of a database timeout” without calling any tool. The logs show a different cause. Which pattern is missing?

  • A. Subagent isolation
  • B. Guidance that requires tool use for factual claims about builds (the agent under-acted)
  • C. Prompt caching
  • D. Batch processing
Show answer

Answer: B. The agent guessed instead of checking. Instructions on when tools are required, good tool descriptions and grounding checks address it.

Question 3. Which two trace signatures indicate a problem even when the run ended with end_turn? (Choose 2.)

  • A. A tool returned is_error and the final answer claims success
  • B. The agent called two different tools once each
  • C. The final message only says “I’ll check the logs now”
  • D. The final message cites tool results
Show answer

Answer: A and C. Ignored errors and promise-only endings are failures that a normal stop reason can hide.

Question 4. The system prompt said “only edit files under tests/”, but after a long run the agent edited src/cart.py. What is the strongest fix?

  • A. Repeat the rule three times in the prompt
  • B. Enforce the rule with a PreToolUse hook, and keep it in the system prompt
  • C. Shorten the run
  • D. Switch to a different model
Show answer

Answer: B. Context loss makes prompt-only rules unreliable over long runs; a hook enforces the rule deterministically.

📝 Assignment

  1. Task 1: Export the trace of one of your own agent runs (from Lesson 32 or 33) into the traces.py format and run analyse.py on it.
    ✅ Done when: the analyser runs on your trace and you can explain each result.
  2. Task 2: Add a check for over-acting: more than N tool calls for a task that a healthy trace finishes in fewer.
    ✅ Done when: a padded copy of the healthy trace is flagged and the original is not.
  3. Stretch: Turn find_problems into a pytest suite that runs over every trace in a traces/ folder and fails CI on any hit.
    ✅ Done when: adding a bad trace file makes the suite fail.
Advertisement

❓ Frequently Asked Questions

🤔 How do I debug an AI agent?

Record full traces, find the first wrong step, decide whether the cause is in your harness or in the model’s behaviour, fix the cause, and replay the trace.

🤔 What is under-acting in AI agents?

The agent answers without using the tools it needed, so its answer is a guess. Clear guidance on when tools are required and grounding checks reduce it.

🤔 Why does my agent repeat the same tool call?

Usually because the tool result never reaches the next request, or the result does not give the model what it needs to move on. Append every result and make results actionable.

🤔 Should I raise max_turns when an agent hits it?

Only after you know why it ran out. Most runaway loops are harness or tool-design bugs; more turns just cost more.

🏁 Summary

  • Save every agent run as a trace of model turns, tool calls, results and stop reasons.
  • Six common patterns: runaway loops, under-acting, ignored errors, early stops, context loss, subagent leakage.
  • Detect them with cheap deterministic checks, then confirm by reading the first wrong step.
  • Fix harness causes in code first, then model causes with prompts and tool descriptions.
  • Enforce critical rules with hooks; limits are backstops, not fixes.
📝 Test yourself: D1 Agents and Workflows practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Code Tutorial: Install, Surfaces, Sessions and Commands.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.