Claude Code Hooks and Subagents Step by Step

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 8 min read🎯 D3 Claude Code Customization and Extension · D7 Deterministic Guardrails and Least Privilege

👋 In plain words: Hooks are small scripts Claude Code runs automatically at fixed moments, such as just before a command runs. They can block it, log it or add information, every time, whatever the model decides. Subagents are specialised helpers with their own instructions and tools. This lesson sets up both in a real project, step by step.

Instructions in CLAUDE.md are followed most of the time; hooks are followed every time. That difference is why the exam treats hooks as the tool for deterministic enforcement. In this lesson you will write a PreToolUse hook that protects a folder and watch Claude Code block a real command with it, add a PostToolUse hook that logs every edit, learn the main hook events and how hooks talk back to Claude, and define a read-only reviewer subagent in .claude/agents.

📖 What You’ll Learn: You will be able to configure Claude Code hooks in settings.json, block or allow tool calls with exit codes and JSON, log actions, and define subagents with focused prompts and tools.

🔑 Key terms

  • Hook event: the moment a hook runs, such as PreToolUse (before a tool) or PostToolUse (after it).
  • Matcher: which tools a tool hook applies to, for example Bash or Edit|Write.
  • Exit code 2: the hook’s signal to block the action; its stderr is shown to Claude.
  • Subagent file: a Markdown file in .claude/agents/ with frontmatter (name, description, tools, model) and a system prompt.

🪜 Step 1: Know the main hook events

Event Runs Typical QA use
PreToolUse Before a tool call Block destructive commands, protect folders, require approval
PostToolUse After a tool call succeeds Run formatters or linters, log edits
UserPromptSubmit When you send a prompt Add context (current branch, ticket), block secrets in prompts
SessionStart / SessionEnd At start and end Load environment info, clean up
Stop / SubagentStop When Claude (or a subagent) finishes Run the test suite before “done” counts
Notification, PreCompact On notifications, before compaction Alerts, saving context

Recent versions add more events; /hooks shows what your version supports.

🪜 Step 2: Write a PreToolUse hook that protects a folder

A command hook receives a JSON description of the event on stdin. Exit code 2 blocks the call, and whatever you print to stderr is sent to Claude as the reason:

📄 .claude/hooks/protect_migrations.py

import json
import sys

event = json.load(sys.stdin)
command = event.get("tool_input", {}).get("command", "")
if "migrations" in command and any(w in command for w in ("rm ", "del ", "mv ", "> ")):
    print("Blocked: migrations/ is protected. Create a new migration instead of changing old ones.", file=sys.stderr)
    sys.exit(2)
sys.exit(0)

📄 .claude/hooks/log_edits.py

import datetime
import json
import sys

event = json.load(sys.stdin)
with open(".claude/edit-log.jsonl", "a") as f:
    f.write(json.dumps({"tool": event.get("tool_name"), "input": event.get("tool_input"),
                        "time": datetime.date.today().isoformat()}) + "\n")

Register both in the project’s .claude/settings.json:

📄 .claude/settings.json

{
  "hooks": {
    "PreToolUse": [
      {"matcher": "Bash", "hooks": [{"type": "command", "command": "python .claude/hooks/protect_migrations.py"}]}
    ],
    "PostToolUse": [
      {"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "python .claude/hooks/log_edits.py"}]}
    ]
  }
}

📄 migrations/0001_init.sql

CREATE TABLE orders (id INT PRIMARY KEY);

🪜 Step 3: Watch the hook block a real command

Ask Claude Code to “clean up” the migrations. The model requests rm -rf migrations; the hook stops it:

⌨️ Terminal

claude -p "Clean up the old migrations folder." --allowedTools Bash --model claude-opus-5-5

🖥️ Output (sample run)

I did not delete migrations/: the project hook blocked it because migrations are protected. If you need a schema change, I can create a new migration file instead.

📄 check.py

from pathlib import Path

print("migration still exists:", Path("migrations/0001_init.sql").exists())

⌨️ Terminal

python check.py

🖥️ Output

migration still exists: True

The command never ran: the real Claude Code harness called the hook, the hook exited with 2, and Claude received the hook’s message as the tool result. Even with --allowedTools Bash, the hook had the final say.

🎯 Exam focus: Hooks are the answer whenever a scenario says an action “must always” or “must never” happen in Claude Code, whatever the prompt or the model decides: block edits to a folder, run tests before stopping, log every command, refuse secrets. A CLAUDE.md instruction is guidance; a hook is enforcement.

🪜 Step 4: Return structured decisions

Instead of exit codes, a hook can print JSON for finer control. For PreToolUse, a decision can allow, deny or ask the user, with a reason:

📄 .claude/hooks/ask_before_push.py

import json
import sys

event = json.load(sys.stdin)
if event.get("tool_input", {}).get("command", "").startswith("git push"):
    print(json.dumps({"hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "ask",
        "permissionDecisionReason": "Pushing changes needs a human check.",
    }}))
sys.exit(0)

Keep hooks fast (they run on every matching call), deterministic, and safe: a hook runs with your user’s permissions, so review hooks in pull requests like any other code.

⚠️ Watch out: Hooks from project settings run commands on everyone’s machine. Treat a change to .claude/settings.json hooks like a change to a build script: review it, and never pull hooks from an untrusted repository without reading them.

🪜 Step 5: Define a subagent

Subagents live in .claude/agents/ (project) or ~/.claude/agents/ (personal). This one reviews test code but cannot edit anything:

📄 .claude/agents/test-reviewer.md

---
name: test-reviewer
description: Reviews test code for flakiness risks, weak assertions and missing negative cases. Use after tests are written or changed. Read-only.
tools: Read, Grep, Glob
model: sonnet
---
You review automated tests. For each file you are given:
1. Flag fixed sleeps, shared mutable test data and order dependence.
2. Flag assertions that would still pass if the feature were broken.
3. List missing negative and boundary cases.
Return a short list per file: issue, line, suggested fix. Do not rewrite the files.
  • The description tells the main session when to delegate (“use after tests are written or changed”).
  • tools keeps it read-only; model lets it run on a cheaper model.
  • Manage subagents with /agents, or ask explicitly: “use the test-reviewer subagent on tests/ui/”.

🪜 Step 6: Combine hooks and subagents

A common QA setup:

  1. The main session writes or fixes tests.
  2. A SubagentStop or Stop hook runs pytest -q and blocks “done” if tests fail (exit code 2 with the failing summary on stderr).
  3. The test-reviewer subagent reviews the changed tests read-only.
  4. A PostToolUse hook logs every edit for the pull-request description.

Each piece has one job: hooks enforce, the subagent isolates review, and the main session does the work.

🌍 Real-world example: Ravi’s protected folders

Ravi’s team lost an afternoon when Claude Code “tidied” a folder of recorded API fixtures. A CLAUDE.md rule had said not to touch them. Ravi replaced the rule with a PreToolUse hook on Edit|Write|Bash that blocks any path under tests/fixtures/recorded/, plus a read-only test-reviewer subagent. The rule has held ever since, including in headless CI runs.

🧪 Practice Questions

Question 1. A CLAUDE.md rule says “never modify files in migrations/”, but Claude Code occasionally edits them during long sessions. What enforces the rule every time?

  • A. Repeating the rule in capitals
  • B. A PreToolUse hook (and/or deny permission rules) that blocks edits and commands touching migrations/
  • C. A Skill about migrations
  • D. Switching to plan mode permanently
Show answer

Answer: B. Hooks and permission rules are deterministic; CLAUDE.md guidance can be lost or ignored.

Question 2. How does a command hook block a PreToolUse action and tell Claude why?

  • A. Exit code 0 with a message on stdout
  • B. Exit code 2 with the reason printed to stderr
  • C. Exit code 1 with no output
  • D. Writing the reason into CLAUDE.md
Show answer

Answer: B. Exit code 2 is the blocking signal, and stderr is passed to Claude as the reason.

Question 3. Which two are good uses of a subagent in Claude Code? (Choose 2.)

  • A. A read-only reviewer that checks changed tests
  • B. Blocking git push –force in every session
  • C. Reading large logs on a cheaper model and returning a summary
  • D. Storing the team’s API keys
Show answer

Answer: A and C. Subagents isolate work with their own tools and model. Enforcement belongs to hooks; secrets belong in secret stores.

Question 4. A team wants every change Claude Code makes to be logged for audit. Which hook event fits?

  • A. SessionStart
  • B. PostToolUse with a matcher for Edit|Write (and Bash if needed)
  • C. UserPromptSubmit
  • D. PreCompact
Show answer

Answer: B. PostToolUse runs after each successful tool call, so it sees what was changed.

📝 Assignment

  1. Task 1: Add the protect_migrations.py hook (adapted to a folder you care about) to a test project and try to make Claude Code change that folder.
    ✅ Done when: the attempt is blocked with your message.
  2. Task 2: Add a Stop hook that runs your fastest test command and exits 2 with the failure summary if it fails.
    ✅ Done when: Claude Code cannot finish while a test is red.
  3. Stretch: Create the test-reviewer subagent and run it on a test file with a deliberate time.sleep(5) and a weak assertion.
    ✅ Done when: both issues are reported and no file was modified.

❓ Frequently Asked Questions

🤔 What are Claude Code hooks?

Commands that Claude Code runs automatically at events such as before or after a tool call. They can block, allow, ask, log or add context, deterministically.

🤔 How do I block a command in Claude Code?

Add a PreToolUse hook with a matcher (for example Bash) whose script exits with code 2 and prints the reason to stderr, or add a deny permission rule.

🤔 Where are Claude Code subagents defined?

As Markdown files with frontmatter in .claude/agents/ (project) or ~/.claude/agents/ (personal), or inside plugins.

🤔 Are hooks safe?

They run with your permissions, so review them like code, keep them fast and deterministic, and only use hooks from trusted sources.

🏁 Summary

  • Hooks run at fixed events; PreToolUse can block, PostToolUse can log and post-process.
  • Exit code 2 blocks and sends stderr to Claude; JSON output gives allow, deny or ask decisions.
  • Configure hooks in .claude/settings.json and review them like build scripts.
  • Subagents in .claude/agents/ have their own description, tools and model.
  • Combine them: hooks enforce, subagents isolate, the main session works.
📝 Test yourself: D3 Claude Code 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 Headless Mode and GitHub Actions CI.

🎬 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.

Claude Code Skills, Plugins, Rules Files and Slash Commands

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D3 Claude Code Customization and Extension

👋 In plain words: Every team repeats the same instructions to Claude Code: how to write tests, how to triage a failure, how to prepare a release. Instead of typing them each time, you package them: as a Skill Claude loads when relevant, a slash command you type, a rule for certain folders, or a plugin that bundles everything for other teams. This lesson builds each one, step by step.

The CCDV-F skill “Claude Code Customization and Extension” asks you to analyse a repeatable team workflow, choose the extension mechanism that fits (Skill, plugin, Rules file, hook, subagent or slash command), and author and package it. In this lesson you will write a Skill and see Claude Code discover it, create a custom slash command, add a path-specific rules file, learn how plugins package them for distribution, and use a decision table to pick the right mechanism.

📖 What You’ll Learn: You will be able to author Skills, slash commands and rules files, package extensions as a plugin, and choose the right extension mechanism for a workflow.

🔑 Key terms

  • Skill: a folder with a SKILL.md (name, description, instructions) plus optional scripts and files. Claude sees the description and loads the rest when a task matches.
  • Slash command: a reusable prompt you invoke by typing /name in a session.
  • Rules file: a Markdown file in .claude/rules/, optionally limited to certain paths, that adds instructions.
  • Plugin: a package of commands, Skills, subagents, hooks and MCP servers that can be installed from a marketplace.

🪜 Step 1: Write a Skill

A Skill packages know-how. Its description is what Claude reads to decide when the Skill applies, so write it like a good tool description: what it does and when to use it.

📄 .claude/skills/flaky-test-triage/SKILL.md

---
name: flaky-test-triage
description: Triage a failing UI test to decide whether it is flaky or a real bug, using our team's checklist. Use when a Playwright or Selenium test fails intermittently.
---
# Flaky test triage
1. Rerun the test 3 times with `pytest -q -p no:randomly <test> --count=3`.
2. If it passes at least once, check waits: no fixed sleeps, wait for the exact state.
3. Check shared test data: parallel workers must not share users or carts.
4. Record the result in docs/flaky-tests.md with the date and the cause.
5. Only open a product bug if it fails 3 out of 3 times with the same error.

Claude Code lists project Skills by name and description in what it sends to the model, and loads the full instructions only when needed. (Inspecting the request in this run showed the line flaky-test-triage: Triage a failing UI test…, and the /test-plan command from Step 2 listed the same way.) Ask a matching question:

⌨️ Terminal

claude -p "test_checkout_coupon failed once on CI but passed on rerun. What should I do?" --model claude-opus-5-5

🖥️ Output (sample run)

This matches the flaky-test-triage skill: rerun it 3 times, check its waits and shared test data, record the result in docs/flaky-tests.md, and open a product bug only if it fails 3 out of 3 times.
  • Keep SKILL.md focused; put long references and scripts in the same folder and point to them.
  • Skills can also live in ~/.claude/skills/ (personal) or come from plugins.

🪜 Step 2: Add a custom slash command

A slash command is a prompt you trigger explicitly. Put it in .claude/commands/; the file name becomes the command. $ARGUMENTS is replaced with what you type after the command:

📄 .claude/commands/test-plan.md

---
description: Draft a test plan for a feature
---
Write a test plan for: $ARGUMENTS
Include scope, 5 positive cases, 5 negative cases, test data needs and risks.
Use one table per section. Do not invent requirements; list open questions instead.

⌨️ Terminal

claude -p "/test-plan coupon codes at checkout" --model claude-opus-5-5

🖥️ Output (sample run)

Test plan: coupon codes at checkout

Scope: applying, validating and removing coupon codes on the checkout page.
(tables for positive cases, negative cases, test data and risks follow)

Open questions: can two coupons be combined? Do coupons apply to shipping?

The run shows the command file was expanded: the request contained the command’s instructions with your argument filled in. Recent Claude Code versions treat custom commands and Skills as closely related; a Skill can also be invoked directly with /skill-name.

🪜 Step 3: Add a path-specific rules file

Rules files keep CLAUDE.md short by splitting instructions by topic, and can apply only to certain paths:

📄 .claude/rules/playwright.md

---
paths:
  - "tests/ui/**/*.py"
---
# Playwright rules
- Locate elements by role or data-testid, never by CSS position or XPath index.
- Use expect(...) web-first assertions; never time.sleep().

When Claude works on files under tests/ui/, these rules apply; elsewhere they stay out of context.

🪜 Step 4: Package everything as a plugin

When several repositories or teams need the same Skills, commands, subagents, hooks or MCP servers, package them as a plugin. A plugin is a folder with a manifest:

📄 qa-toolkit/.claude-plugin/plugin.json

{
  "name": "qa-toolkit",
  "version": "1.2.0",
  "description": "Team QA workflows: flaky test triage, test plans and a read-only reviewer agent."
}

📄 qa-toolkit/README.md

qa-toolkit/
  .claude-plugin/plugin.json   manifest (name, version, description)
  skills/flaky-test-triage/SKILL.md
  commands/test-plan.md
  agents/test-reviewer.md
  hooks/hooks.json             e.g. block edits to migrations/
  .mcp.json                    e.g. the team's QA results server

Teams publish plugins in a marketplace (a Git repository with a catalogue) and install them with /plugin in Claude Code. Version your plugin, list its dependencies, and treat updates like any other release, because a plugin can add hooks and MCP servers that run on every user’s machine.

⚠️ Watch out: Installing a plugin is installing code. Hooks and MCP servers from a plugin run with your permissions. Use plugins from trusted marketplaces, review what they add, and pin versions for teams.

🪜 Step 5: Choose the right mechanism

The workflow is… Use Why
Know-how Claude should apply when relevant (triage checklist, house style) Skill Loaded on demand by description; can include scripts
A prompt people trigger deliberately with arguments Slash command Explicit, repeatable, parameterised
Instructions for one area of the codebase Rules file with paths Only in context where it applies
A rule that must always be enforced (block edits, run formatters) Hook (Lesson 40) Deterministic, not model-dependent
Work that needs its own context, tools or model (review, log reading) Subagent (Lesson 40) Isolated context and permissions
All of the above shared across teams and repositories Plugin Versioned package from a marketplace
A live external system (Jira, CI database) MCP server (Module 7) Shared integration

This helper encodes the table for quick decisions. It runs locally:

📄 choose_extension.py

def choose(must_always_happen: bool, needs_own_context: bool, explicit_trigger: bool,
           limited_to_paths: bool, shared_across_repos: bool, live_system: bool) -> str:
    if live_system:
        return "MCP server"
    if must_always_happen:
        base = "hook"
    elif needs_own_context:
        base = "subagent"
    elif explicit_trigger:
        base = "slash command"
    elif limited_to_paths:
        base = "rules file"
    else:
        base = "Skill"
    return base + (" packaged in a plugin" if shared_across_repos else "")


cases = {
    "Block any edit to migrations/": (True, False, False, False, False, False),
    "Team checklist for flaky UI tests, used in 12 repos": (False, False, False, False, True, False),
    "/release-notes command with a version argument": (False, False, True, False, False, False),
    "Playwright locator rules for tests/ui only": (False, False, False, True, False, False),
    "Read 300 CI logs and summarise": (False, True, False, False, False, False),
}
for name, args in cases.items():
    print(f"{name:<52} -> {choose(*args)}")

⌨️ Terminal

python choose_extension.py

🖥️ Output

Block any edit to migrations/                        -> hook
Team checklist for flaky UI tests, used in 12 repos  -> Skill packaged in a plugin
/release-notes command with a version argument       -> slash command
Playwright locator rules for tests/ui only           -> rules file
Read 300 CI logs and summarise                       -> subagent
🎯 Exam focus: The key distinction the exam tests: Skills, commands and rules give instructions (Claude can still choose otherwise), hooks enforce (deterministic), subagents isolate, plugins distribute, MCP connects live systems. Pick by what the workflow needs: discovery, explicit triggering, enforcement, isolation or distribution.

🌍 Real-world example: Ravi’s QA toolkit

Ravi’s team kept pasting the same flaky-test checklist into Claude Code. He turned it into a Skill, added /test-plan and /bug-report commands, a rules file for tests/ui/, and a hook that blocks edits to migrations/. When two other teams asked for the same setup, he packaged it as the qa-toolkit plugin in the company marketplace, versioned it, and now ships updates through it.

🧪 Practice Questions

Question 1. A team wants Claude Code to follow its 10-step release checklist whenever someone asks about preparing a release, without anyone typing a command. Which mechanism fits?

  • A. A Skill whose description says when to use it
  • B. A PreToolUse hook
  • C. A custom slash command only
  • D. An MCP server
Show answer

Answer: A. Skills are discovered from their description and loaded when a task matches.

Question 2. Edits to files under infra/prod/ must never happen through Claude Code. Which mechanism enforces this?

  • A. A rules file for infra/prod/
  • B. A line in CLAUDE.md
  • C. A hook (or deny permission rule) that blocks writes to that path
  • D. A Skill describing the policy
Show answer

Answer: C. Only deterministic mechanisms (hooks, permission rules) enforce; instructions can be ignored or forgotten.

Question 3. Which two belong in a plugin manifest-based package? (Choose 2.)

  • A. Skills and slash commands shared by many repositories
  • B. The team’s API keys
  • C. Hooks and MCP server configuration for the team’s workflow
  • D. Each developer’s personal settings.local.json
Show answer

Answer: A and C. Plugins distribute shared extensions. Secrets and personal settings must not be packaged.

Question 4. Playwright-specific rules should apply only when Claude edits files in tests/ui/. What fits best?

  • A. Add them to ~/.claude/CLAUDE.md
  • B. A rules file in .claude/rules/ with a paths pattern for tests/ui
  • C. A hook that prints the rules
  • D. An MCP prompt
Show answer

Answer: B. Path-specific rules files keep instructions in context only where they apply.

📝 Assignment

  1. Task 1: Turn one checklist your team repeats into a Skill with a precise description.
    ✅ Done when: a matching question makes Claude Code use it without you mentioning the Skill.
  2. Task 2: Create a /bug-report command that takes a test name as $ARGUMENTS and produces your team’s bug template.
    ✅ Done when: /bug-report test_login_lockout produces a filled template.
  3. Stretch: Package your Skill and command as a plugin folder with plugin.json, and install it in a second repository from a local marketplace.
    ✅ Done when: the second repository has the Skill without copying files.

❓ Frequently Asked Questions

🤔 What are Claude Code Skills?

Folders with a SKILL.md that describe a capability. Claude sees the name and description and loads the instructions and files when a task matches.

🤔 What is the difference between a Skill and a slash command?

A Skill is discovered and loaded by Claude when relevant; a slash command is triggered explicitly by you, often with arguments.

🤔 What is a Claude Code plugin?

An installable package that bundles Skills, commands, subagents, hooks and MCP servers, distributed through marketplaces.

🤔 Where do custom slash commands live?

In .claude/commands/ for a project, ~/.claude/commands/ for you personally, or inside a plugin.

🏁 Summary

  • Skills: on-demand know-how, discovered by description.
  • Slash commands: explicit, parameterised prompts in .claude/commands/.
  • Rules files: topic or path-specific instructions in .claude/rules/.
  • Plugins: versioned bundles of Skills, commands, agents, hooks and MCP servers from marketplaces.
  • Hooks enforce, subagents isolate, MCP connects; choose by what the workflow needs.
📝 Test yourself: D3 Claude Code 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 Hooks and Subagents Step by Step.

🎬 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.

Claude Code CLAUDE.md, settings.json and Permission Modes

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 8 min read🎯 D3 Claude Code Operation · D2 Configuration and SDLC Integration

👋 In plain words: Claude Code reads two kinds of project files: CLAUDE.md, which tells Claude how your project works, and settings.json, which controls what Claude is allowed to do. Both exist at several levels, and the levels have a fixed order of priority. This lesson walks through each level with real runs, so you know exactly which rule wins.

“Why did Claude Code ignore our rule?” almost always has a configuration answer: the rule was in the wrong file, overridden by a higher level, or the workspace was not trusted. In this lesson you will build a project’s CLAUDE.md with an import, learn the memory hierarchy, write settings.json permission rules and watch a deny rule protect a secrets file, learn the settings precedence order, compare the permission modes, and see why workspace trust matters.

📖 What You’ll Learn: You will be able to structure CLAUDE.md files across levels, use imports, write allow/ask/deny rules, predict which settings win, choose a permission mode, and explain workspace trust.

🔑 Key terms

  • CLAUDE.md (memory file): Markdown instructions Claude Code loads into context: commands, conventions, project facts.
  • settings.json: JSON configuration for permissions, hooks, environment variables, model and more.
  • Permission rule: an allow, ask or deny entry such as Bash(pytest:*) or Read(./.env).
  • Permission mode: the session’s default behaviour for tool use (for example default, acceptEdits, plan).
  • Workspace trust: your confirmation that a folder is safe; until then, some project settings are not applied.

🪜 Step 1: Learn the CLAUDE.md hierarchy

Claude Code loads memory files from several places and combines them. From broadest to most specific:

Level Location Shared with Use for
Enterprise (managed) A system-wide policy location set by IT Everyone in the organisation Company-wide rules
User ~/.claude/CLAUDE.md Only you, all projects Personal preferences
Project ./CLAUDE.md or ./.claude/CLAUDE.md The team, via Git Commands, conventions, architecture
Project rules ./.claude/rules/*.md (can be limited to paths) The team, via Git Topic- or folder-specific rules
Subfolders CLAUDE.md in subdirectories The team Loaded when Claude works with files in that folder

More specific instructions add to broader ones. Keep each file short and factual: every line is in context on every request.

🪜 Step 2: Write a project CLAUDE.md with an import

@path imports another file, so long reference material can live in its own document:

📄 CLAUDE.md

# Checkout service
- Run unit tests: pytest -q tests/unit
- Never edit files under migrations/
- Test conventions: @docs/testing.md

📄 docs/testing.md

# Testing conventions
- UI tests use Playwright with page objects in tests/pages/
- Test data comes from factories in tests/data/; never hard-code emails
- Mark slow tests with @pytest.mark.slow

⌨️ Terminal

claude -p "Where should test data for a new UI test come from?" --model claude-opus-5-5

🖥️ Output (sample run)

From the factories in tests/data/, per docs/testing.md (imported by CLAUDE.md). Do not hard-code email addresses.

The answer depends on a line that exists only in docs/testing.md, which reached Claude because CLAUDE.md imported it.

🪜 Step 3: Write permission rules

Permissions live in settings.json under allow, ask and deny. Rules name a tool and, optionally, a pattern. When rules overlap, deny wins over ask, and ask wins over allow, and rule lists from different settings files are combined:

📄 .claude/settings.json

{
  "permissions": {
    "allow": ["Bash(pytest:*)", "Bash(git diff:*)", "Read(./src/**)"],
    "ask": ["Bash(git push:*)"],
    "deny": ["Read(./.env)", "Read(./secrets/**)", "Bash(rm -rf:*)"]
  }
}

📄 .env

API_TOKEN=not-a-real-token

Now ask Claude to read the secrets file. The model requests Read(.env); the harness refuses before the file is opened:

⌨️ Terminal

claude -p "What is in the .env file?" --allowedTools Read --model claude-opus-5-5

🖥️ Output (sample run)

I can't read .env: the project's permission settings deny access to that file.
Ignoring 3 permissions.allow entries from .claude/settings.json: this workspace has not been trusted. Run Claude Code interactively here once and accept the trust dialog, or set projects["C:\Users\you\claude-course"].hasTrustDialogAccepted: true in C:\Users\you\claude-course\.claude-config\.claude.json.

Read the output carefully. The deny rule blocked the read and Claude Code printed a warning: the allow rules were ignored because this workspace has not been trusted yet. That is a safety feature: a cloned repository cannot grant itself permissions until you trust it, but deny rules (which only reduce power) still apply.

⚠️ Watch out: Deny rules are for Claude Code’s tools. A deny on Read(./.env) does not stop a Bash command such as cat .env unless you also restrict Bash. For secrets, combine deny rules, a narrow Bash allow-list, hooks (Lesson 40), and keeping real secrets out of the working folder.

🪜 Step 4: Know which settings win

Settings files also exist at several levels. When they conflict, Anthropic documents this precedence, highest first:

  1. Enterprise managed settings: cannot be overridden by users or projects.
  2. Command-line arguments for this session (for example --allowedTools, --model).
  3. Local project settings: .claude/settings.local.json (personal, not committed).
  4. Shared project settings: .claude/settings.json (committed for the team).
  5. User settings: ~/.claude/settings.json.

Two practical rules follow: put team policy in .claude/settings.json; put personal tweaks in .claude/settings.local.json (Git-ignored); and if a rule “does not work”, check whether a higher level overrides it.

🎯 Exam focus: “Configuration and SDLC Integration” items give you several configuration files and ask what happens in an environment. Work through the precedence list: managed policy first, then CLI flags, local project, shared project, user. Also check workspace trust and whether a rule is a deny (always applied) or an allow (needs trust).

🪜 Step 5: Choose a permission mode

Mode Behaviour Use when
default Asks before actions that are not pre-allowed Normal work
acceptEdits Auto-approves file edits; still asks for other risky actions Iterating on code you will review
plan Analyse and plan only; no edits or commands that change things Before large or risky changes
bypassPermissions No permission checks Only inside an isolated container with no secrets
dontAsk, auto Further non-interactive modes in recent versions (see the official docs) Automation with care

Set the default in settings.json ("defaultMode"), switch during a session with Shift+Tab, or pass --permission-mode on the command line.

🪜 Step 6: Pin and separate per environment

Configuration is part of your software lifecycle:

  • Pin the model in settings or CI flags so behaviour does not change silently when defaults move (Lesson 42).
  • Commit .claude/settings.json, CLAUDE.md, .claude/rules/, skills and .mcp.json; Git-ignore .claude/settings.local.json.
  • Review changes to these files like code: a new allow rule is a security change.
  • In CI, pass explicit flags (--allowedTools, --permission-mode, --model) so a run does not depend on a developer’s local files.

🌍 Real-world example: Ravi’s “ignored” rule

A teammate complained that Claude Code kept asking before running pytest, although .claude/settings.json allowed it. The cause was workspace trust: they had cloned the repository into a new folder and never accepted the trust prompt. After trusting the folder, the allow rule applied. Meanwhile the deny rule on .env had protected the folder all along.

🧪 Practice Questions

Question 1. The shared project file .claude/settings.json sets “model” to claude-opus-5-5, the developer’s ~/.claude/settings.json sets it to claude-sonnet-5-5, and the developer’s .claude/settings.local.json does not set a model. No managed policy or CLI flag is used. Which model does a session in that project use?

  • A. claude-sonnet-5-5, because user settings are highest
  • B. claude-opus-5-5, because shared project settings outrank user settings
  • C. Neither; conflicting settings fall back to the default
  • D. Whichever file was edited last
Show answer

Answer: B. For single-value settings, precedence is managed > CLI > local project > shared project > user. Permission rule lists are different: they combine across levels, and a matching deny rule wins.

Question 2. After cloning a repository, a developer sees “Ignoring permissions.allow entry … this workspace has not been trusted”. What does this mean?

  • A. The settings file is invalid JSON
  • B. Project allow rules are not applied until the user trusts the folder; deny rules still apply
  • C. The model ID is wrong
  • D. Hooks are disabled
Show answer

Answer: B. Workspace trust stops a cloned project from granting itself permissions.

Question 3. Where should a team put the command to run its tests so every Claude Code session knows it?

  • A. The project CLAUDE.md committed to the repository
  • B. ~/.claude/CLAUDE.md on each laptop
  • C. .claude/settings.local.json
  • D. The system prompt of the API
Show answer

Answer: A. Project CLAUDE.md is shared through Git and loaded for everyone working in the repository.

Question 4. Which two belong in .claude/settings.json rather than CLAUDE.md? (Choose 2.)

  • A. Deny rules for reading secrets
  • B. An explanation of the architecture
  • C. Hooks that block destructive commands
  • D. Coding style preferences written as sentences
Show answer

Answer: A and C. settings.json enforces permissions and hooks; CLAUDE.md gives instructions and context.

📝 Assignment

  1. Task 1: Write a project CLAUDE.md under 20 lines and move long conventions into a docs/ file imported with @.
    ✅ Done when: /memory shows both files in use.
  2. Task 2: Add .claude/settings.json with allow rules for your test command and deny rules for secrets folders, and check them with /permissions.
    ✅ Done when: reading a secrets file is refused.
  3. Stretch: Add .claude/settings.local.json to .gitignore and use it to set a personal default mode, then confirm the team file is unchanged in Git.
    ✅ Done when: git status shows no change to .claude/settings.json.

❓ Frequently Asked Questions

🤔 Where does Claude Code look for CLAUDE.md?

At the enterprise, user (~/.claude/CLAUDE.md) and project levels (./CLAUDE.md or ./.claude/CLAUDE.md), in .claude/rules/, and in subfolders when Claude works with files there.

🤔 How do I import a file into CLAUDE.md?

Write @path/to/file.md in CLAUDE.md. The referenced file is loaded together with it.

🤔 What is the order of Claude Code settings precedence?

Enterprise managed settings, then command-line arguments, then .claude/settings.local.json, then .claude/settings.json, then ~/.claude/settings.json.

🤔 Why are my project permission rules ignored?

Usually because the workspace has not been trusted yet, or a higher-precedence setting overrides them.

🏁 Summary

  • CLAUDE.md gives instructions; settings.json enforces permissions, hooks and options.
  • Memory files combine from enterprise, user, project, rules and subfolder levels; @ imports keep them short.
  • Permission rules: allow, ask, deny with tool patterns; deny rules apply even before trust.
  • Settings precedence: managed > CLI > local project > shared project > user.
  • Choose permission modes deliberately; never bypass permissions outside an isolated sandbox.
📝 Test yourself: D3 Claude Code 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 Skills, Plugins, Rules Files and Slash 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.

Claude Code Tutorial: Install, Surfaces, Sessions and Commands

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 7 min read🎯 D3 Claude Code Operation

👋 In plain words: Claude Code is Anthropic’s coding agent. It reads your project, runs commands, edits files and explains what it did, in your terminal, your IDE, a desktop app, the web or your phone. This lesson gets you from installation to a productive first session, one step at a time.

For QA engineers, Claude Code is the fastest way to put Claude to work on a real test suite: fixing locators, writing tests, explaining failures, reviewing pull requests. In this lesson you will install it, check the version, learn where it runs, start, continue and resume sessions, use the built-in commands that matter most, and run it non-interactively, using the real Claude Code CLI against a local stand-in for the API.

📖 What You’ll Learn: You will be able to install and start Claude Code, choose the right surface, manage sessions, use key built-in commands, and run a one-shot headless prompt.

🔑 Key terms

  • Claude Code: Anthropic’s agentic coding tool, which works in your project with file, search and shell tools.
  • Surface: where you use it: terminal (CLI), IDE extensions, desktop app, web and mobile.
  • Session: one conversation with Claude Code in a project, with its history.
  • Slash command: a command typed in a session, starting with /, such as /clear or /model.
  • Headless mode: running Claude Code without the interactive interface, with claude -p "…".

🪜 Step 1: Install Claude Code

Anthropic’s documentation offers a native installer (recommended) and an npm package:

⌨️ Terminal · macOS / Linux / WSL

curl -fsSL https://claude.ai/install.sh | bash

⌨️ Terminal · Windows PowerShell

irm https://claude.ai/install.ps1 | iex

⌨️ Terminal · npm (alternative)

npm install -g @anthropic-ai/claude-code

Then check it works. This course uses the Claude Code engine bundled with the Agent SDK it was built with:

⌨️ Terminal

claude --version

🖥️ Output

2.1.330 (Claude Code)

The first time you run claude interactively, it asks you to sign in with a Claude subscription or a Claude Console account (API billing), or you can point it at a cloud provider such as Amazon Bedrock or Google Vertex AI through environment variables.

🪜 Step 2: Pick a surface

Surface Best for
Terminal (CLI) Full control, scripting, any editor, SSH sessions
IDE extensions (VS Code, JetBrains) Seeing diffs inline, sharing the open file and selection with Claude
Desktop app A visual workspace with sessions, files, a browser pane and parallel sessions
Web (claude.ai/code) Running tasks in Anthropic’s cloud environments on your GitHub repositories, no local setup
Mobile Starting or checking on cloud tasks away from your desk
CI (headless, GitHub Actions) Automated reviews, fixes and reports (Lesson 41)

They share the same engine and project configuration (CLAUDE.md, .claude/settings.json, skills, MCP servers), so a team can mix surfaces freely.

💡 Tip: Web and mobile sessions run in a cloud environment, not on your machine. They can only see what is in the repository and the environment’s setup, so local files, local services and your laptop’s credentials are not available there.

🪜 Step 3: Start, continue and resume sessions

⌨️ Terminal

cd my-test-project
claude                 # start a new interactive session in this folder
claude -c              # continue the most recent session in this folder
claude -r              # pick an earlier session to resume
claude "explain the failing test in tests/test_cart.py"   # start with a first prompt

Inside a session:

  1. Describe the outcome, not the keystrokes: “make the checkout tests stop timing out on CI; keep the assertions unchanged”.
  2. Review before accepting. By default Claude Code asks before editing files or running commands that are not pre-approved.
  3. Press Shift+Tab to cycle permission modes (for example to plan mode, where Claude plans without changing anything, or to accept edits). Lesson 38 covers modes.
  4. Press Esc to interrupt Claude and redirect it; Esc twice lets you jump back to an earlier message.

🪜 Step 4: Use the built-in commands that matter

Command What it does
/init Analyses the project and writes a starter CLAUDE.md
/clear Starts a fresh conversation (use it when the task changes)
/compact Summarises the conversation to free context
/context Shows what is using the context window
/model Switches the model for this session
/permissions Views and edits allow, ask and deny rules
/memory Opens the CLAUDE.md files in use
/mcp Shows MCP servers and their connection status
/agents Manages subagents
/hooks Views configured hooks
/resume Picks an earlier session to continue
/help Lists all commands, including your custom ones
🎯 Exam focus: “Claude Code Operation” covers sessions, the CLAUDE.md hierarchy, settings.json, permission modes, headless and streaming modes, and built-in commands. Typical items: “the conversation drifted to a new task” → /clear (or a new session); “context is nearly full but the task continues” → /compact; “Claude should plan but not change anything yet” → plan mode.

🪜 Step 5: Run a one-shot headless prompt

claude -p (print mode) runs one prompt without the interactive interface and prints the answer, which is how you use Claude Code in scripts and CI:

📄 CLAUDE.md

# Project notes
- Tests: pytest -q tests/
- UI tests use Playwright with the page-object pattern in tests/pages/

⌨️ Terminal

claude -p "How do I run this project's tests?" --model claude-opus-5-5

🖥️ Output (sample run)

Run the tests with `pytest -q tests/`, as documented in CLAUDE.md. UI tests use Playwright page objects in tests/pages/.

The answer came from CLAUDE.md, which Claude Code loaded automatically from the working folder. Lesson 38 explains which CLAUDE.md files are loaded and in what order, and Lesson 41 covers JSON output, allowed tools and CI.

🌍 Real-world example: Ravi’s first week with Claude Code

Ravi ran /init in his Playwright repository, trimmed the generated CLAUDE.md to the commands and conventions that mattered, and started every task in plan mode. For quick questions he used the terminal; for reviewing larger diffs he switched to the VS Code extension, which used the same project configuration.

🧪 Practice Questions

Question 1. A developer finished fixing login tests and now wants Claude Code to work on unrelated report generation. The session is long. What should they do?

  • A. Keep going in the same session
  • B. Run /clear (or start a new session) so the old context does not distract the new task
  • C. Run /compact twice
  • D. Switch to a larger model
Show answer

Answer: B. A new, unrelated task should start with fresh context. /compact keeps a summary of the old task, which is useful only when continuing it.

Question 2. A team wants Claude Code to propose a migration plan without changing any files yet. Which feature fits?

  • A. bypassPermissions mode
  • B. Plan mode
  • C. Headless mode with –output-format json
  • D. /clear
Show answer

Answer: B. Plan mode lets Claude analyse and plan without making changes.

Question 3. Which two statements about Claude Code surfaces are true? (Choose 2.)

  • A. The terminal, IDE extensions and desktop app share the same project configuration such as CLAUDE.md and settings
  • B. The web surface can read files that exist only on your laptop
  • C. Web and mobile sessions run in cloud environments on repositories
  • D. Headless mode needs the desktop app to be open
Show answer

Answer: A and C. Surfaces share the engine and project files. Cloud sessions see the repository, not your local machine.

Question 4. What does claude -p “…” do?

  • A. Runs one prompt non-interactively and prints the result, for scripts and CI
  • B. Opens plan mode
  • C. Pins the model version
  • D. Prints the system prompt
Show answer

Answer: A. Print (headless) mode runs a single prompt without the interactive interface.

📝 Assignment

  1. Task 1: Install Claude Code, run /init in one of your test projects, and edit the generated CLAUDE.md down to the 10 most useful lines.
    ✅ Done when: the file lists how to run tests and your main conventions.
  2. Task 2: Use plan mode to ask for a plan to fix one flaky test, then let Claude implement it in normal mode.
    ✅ Done when: you reviewed the plan before any file changed.
  3. Stretch: Write a script that runs claude -p "list the test files that have no assertions" on your repository and saves the answer to a file.
    ✅ Done when: the script runs without any interactive prompt.

❓ Frequently Asked Questions

🤔 How do I install Claude Code?

Use Anthropic’s native installer (a one-line command for macOS/Linux or PowerShell on Windows) or npm install -g @anthropic-ai/claude-code, then run claude in a project folder.

🤔 What is the difference between claude -c and claude -r?

-c continues the most recent session in the folder; -r lets you choose an earlier session to resume.

🤔 When should I use /compact instead of /clear?

Use /compact to keep working on the same task with a summarised history. Use /clear when you start something unrelated.

🤔 Can I use Claude Code in VS Code?

Yes. The VS Code and JetBrains extensions run Claude Code inside the IDE, with inline diffs and the current file and selection as context.

🏁 Summary

  • Install with the native installer or npm; check with claude --version.
  • Surfaces: terminal, IDE, desktop, web, mobile and CI, all sharing project configuration.
  • claude, -c and -r start, continue and resume sessions; Shift+Tab cycles permission modes.
  • Key commands: /init, /clear, /compact, /context, /model, /permissions, /memory, /mcp.
  • claude -p runs Claude Code headless for scripts and CI.
📝 Test yourself: D3 Claude Code 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 CLAUDE.md, settings.json and Permission Modes.

🎬 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.

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.

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

🪜 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).

🪜 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.

🧪 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.

❓ 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.

Claude Agent Memory, Human-in-the-Loop and Managed Agents

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 10 min read🎯 D1 Architecture and Runtime Selection · D1 Agent SDK Construction and Hooks

👋 In plain words: Agents forget everything between runs unless you give them a place to remember, and they should not take risky actions without a person saying yes. This lesson adds both to an agent, step by step: a memory folder Claude can read and write, and an approval check before any change. Then it shows how Anthropic’s Managed Agents provide the same ideas as a hosted service.

Long-running QA agents need two things a single conversation does not give them: memory that survives between runs (known flaky tests, past root causes) and human checkpoints before irreversible actions (editing release notes, closing tickets, merging). In this lesson you will implement the memory tool with a safe file-based backend, add a can_use_tool approval callback to an Agent SDK agent and watch a reviewer reject a write, learn how sessions resume, and see how Claude Managed Agents package agents, sessions and approvals as a hosted runtime.

📖 What You’ll Learn: You will be able to give an agent persistent memory with the memory tool, add human approval for risky tool calls, resume agent sessions, and explain when Claude Managed Agents fit.

🔑 Key terms

  • Memory tool: an Anthropic-defined client tool (memory_20250818) that lets Claude view, create and edit files in a /memories directory that your code stores.
  • Human-in-the-loop (HITL): a design where a person approves, rejects or edits certain actions before they happen.
  • can_use_tool: an Agent SDK callback that decides, per tool request, whether to allow or deny it.
  • Session: one run of an agent with its history; it can be resumed later.
  • Claude Managed Agents: an Anthropic-hosted runtime (beta) where agents are stored, versioned objects and each session runs in its own container.

🪜 Step 1: Choose what kind of memory you need

Memory Lives in Good for
Conversation history The messages of one session The current task
Session resume The agent’s saved session Continuing a task later
Memory tool Files your code stores (/memories/...) Facts that should survive across sessions: known flaky tests, team preferences
Project instructions CLAUDE.md, system prompts Stable rules every session should follow

Memory is data the agent wrote, so treat it like any other untrusted input: review it, limit its size, and let people delete it.

🪜 Step 2: Implement a safe memory backend

The memory tool is client-side: Claude sends commands such as view, create and str_replace with paths under /memories, and your code stores the files. The SDK gives you an abstract class to fill in. Map every path into one local folder and refuse anything outside it:

📄 memory_backend.py

from pathlib import Path

from anthropic.lib.tools import BetaAbstractMemoryTool

ROOT = (Path(__file__).parent / "memories").resolve()


class FolderMemory(BetaAbstractMemoryTool):
    def _path(self, virtual: str) -> Path:
        if not virtual.startswith("/memories"):
            raise ValueError("paths must start with /memories")
        p = (ROOT / virtual.removeprefix("/memories").lstrip("/")).resolve()
        if not p.is_relative_to(ROOT):
            raise ValueError("path escapes the memory folder")
        return p

    def view(self, command):
        p = self._path(command.path)
        if p.is_dir():
            return "\n".join(sorted(f.name for f in p.iterdir())) or "(empty)"
        return p.read_text() if p.exists() else f"{command.path} does not exist"

    def create(self, command):
        p = self._path(command.path)
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(command.file_text)
        return f"created {command.path}"

    def str_replace(self, command):
        p = self._path(command.path)
        p.write_text(p.read_text().replace(command.old_str, command.new_str, 1))
        return f"edited {command.path}"

    def insert(self, command):
        raise ValueError("insert is not supported by this backend")

    def delete(self, command):
        self._path(command.path).unlink(missing_ok=True)
        return f"deleted {command.path}"

    def rename(self, command):
        raise ValueError("rename is not supported by this backend")

    def clear_all_memory(self):
        for f in ROOT.glob("**/*"):
            if f.is_file():
                f.unlink()
        return "cleared"

🪜 Step 3: Let the agent remember across sessions

Run two separate sessions. In the first, the agent learns that a test is flaky and stores it. In the second, a fresh conversation, it checks memory before answering:

📄 remember.py

import anthropic

from memory_backend import ROOT, FolderMemory

client = anthropic.Anthropic()
memory = FolderMemory()
ROOT.mkdir(exist_ok=True)


def session(prompt: str) -> str:
    runner = client.beta.messages.tool_runner(
        model="claude-opus-5-5", max_tokens=2000, tools=[memory],
        system="You triage CI failures. Check /memories before answering and save durable lessons there.",
        messages=[{"role": "user", "content": prompt}],
    )
    return runner.until_done().content[-1].text


print("SESSION 1:", session("test_checkout_coupon failed again tonight; it passed on rerun for the 4th time this week."))
print("memory files:", [p.name for p in ROOT.iterdir()])
print("SESSION 2:", session("test_checkout_coupon failed. Should I open a bug?"))

⌨️ Terminal

python remember.py

🖥️ Output (sample run)

SESSION 1: Noted: I saved test_checkout_coupon as a known flaky test in /memories/flaky-tests.md, so future triage treats a single failure as likely flakiness.
memory files: ['flaky-tests.md']
SESSION 2: Not yet: my notes say test_checkout_coupon is a known flaky test (passed on rerun 4 times this week). Rerun it, and open a test-stability ticket instead of a product bug if it fails again.

📄 show_memory.py

from memory_backend import ROOT

print((ROOT / "flaky-tests.md").read_text())

⌨️ Terminal

python show_memory.py

🖥️ Output

# Known flaky tests
- test_checkout_coupon: passes on rerun (4 times in week of 24 Nov 2026)

The second session started with no history; the knowledge came from the memory file your code stored.

⚠️ Watch out: Memory can be poisoned: if an agent reads untrusted content and writes “lessons” from it, later sessions inherit them. Keep memory small, reviewable and deletable, never store secrets in it, and do not let memory override your system prompt’s rules.

🪜 Step 4: Add human approval for risky actions

In the Agent SDK, can_use_tool is called for every tool request that is not already allowed. Approve safe reads automatically and ask a person about anything that changes things. Here the reviewer rejects the change:

📄 RELEASE_NOTES.md

# Release notes

📄 approval_agent.py

import asyncio
from pathlib import Path

from claude_agent_sdk import (AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, PermissionResultAllow,
                              PermissionResultDeny, ResultMessage)


async def ask_human(tool_name, tool_input, context):
    if tool_name in ("Read", "Grep", "Glob"):
        return PermissionResultAllow()  # safe: read-only
    print(f"APPROVAL NEEDED: {tool_name} on {Path(tool_input.get('file_path', '?')).name}")
    approved = False  # in a real app: a UI button, a Slack approval, a ticket sign-off
    if approved:
        return PermissionResultAllow()
    return PermissionResultDeny(message="Rejected by reviewer: release notes need QA sign-off first.")


async def main():
    options = ClaudeAgentOptions(can_use_tool=ask_human, cwd=str(Path.cwd()), max_turns=5, model="claude-opus-5-5")
    async with ClaudeSDKClient(options=options) as client:
        await client.query("Update RELEASE_NOTES.md to say all tests passed.")
        async for m in client.receive_response():
            if isinstance(m, AssistantMessage):
                for b in m.content:
                    if type(b).__name__ == "TextBlock":
                        print("CLAUDE:", b.text)
            elif isinstance(m, ResultMessage):
                print("RESULT:", m.subtype)
    print("file now:", Path("RELEASE_NOTES.md").read_text().strip())


asyncio.run(main())

⌨️ Terminal

python approval_agent.py

🖥️ Output (sample run)

APPROVAL NEEDED: Write on RELEASE_NOTES.md
CLAUDE: I did not change RELEASE_NOTES.md: the reviewer rejected the edit because release notes need QA sign-off first.
RESULT: success
file now: # Release notes
  • The decision happened in your code, so the file did not change, and Claude was told why.
  • ClaudeSDKClient keeps a session open, which interactive approval flows need. (Hooks from Lesson 33 can enforce fixed rules; can_use_tool suits decisions a person makes at run time.)

🪜 Step 5: Resume and fork sessions

Every Agent SDK run has a session_id (in the ResultMessage). Pass it back as ClaudeAgentOptions(resume=session_id) to continue with the same history, or set fork_session=True to branch from it without changing the original. Use resume for multi-day investigations; use memory for facts that every future session should know.

🪜 Step 6: Know when Claude Managed Agents fit

Claude Managed Agents (beta) offer the same building blocks as a hosted service:

  • Agents are stored, versioned configurations (model, system prompt, tools, MCP servers, Skills). Create them once and reuse them by ID.
  • Environments define the container settings (for example networking limits).
  • Sessions run an agent in its own container, where bash, file and code tools execute; you stream events and send messages and tool results.
  • Permission policies (always_allow, always_ask, auto) decide which tool calls pause for your approval, which is HITL as a platform feature.
  • Vaults, memory stores, outcomes (a grader iterates until a rubric passes) and scheduled deployments cover credentials, memory, quality bars and cron-style runs.

📄 managed_agent.py

import anthropic

client = anthropic.Anthropic()

environment = client.beta.environments.create(
    name="qa-triage-env",
    config={"type": "cloud", "networking": {"type": "limited", "allow_package_managers": True, "allow_mcp_servers": True}},
)
agent = client.beta.agents.create(            # once, in setup; store agent.id
    name="Nightly CI triage",
    model="claude-opus-5-5",
    system="You triage nightly CI failures and write a short report.",
    tools=[{
        "type": "agent_toolset_20260401",
        "default_config": {"enabled": True, "permission_policy": {"type": "auto"}},
        "configs": [{"name": "web_fetch", "enabled": False}, {"name": "web_search", "enabled": False}],
    }],
)
session = client.beta.sessions.create(        # every run
    agent={"type": "agent", "id": agent.id, "version": agent.version},
    environment_id=environment.id,
)
print(session.id, session.status)

Managed Agents bill session runtime on top of tokens, keep session history until you delete it, and are not available on every cloud platform. Choose them when you do not want to host the loop and sandbox; choose the Agent SDK when you need to run on your own infrastructure.

🎯 Exam focus: Scenario cues: “must remember across runs” → memory tool or memory stores, with review and limits; “irreversible action needs sign-off” → human approval enforced in code (can_use_tool, hooks, permission policies), not a prompt request; “no infrastructure to host the agent” or “runs on a schedule” → Managed Agents.

🌍 Real-world example: Ravi’s triage memory

Ravi’s nightly triage agent kept opening product bugs for the same flaky tests. With the memory tool, it now records tests that pass on rerun, and a weekly review by the QA lead prunes the list. Any action that edits release notes or closes tickets goes through an approval callback that posts to the team channel and waits for a thumbs-up.

🧪 Practice Questions

Question 1. A triage agent should remember known flaky tests across nightly runs, and the QA lead must be able to review and correct that knowledge. What fits best?

  • A. A longer system prompt rewritten by the agent each night
  • B. The memory tool with a backend your code stores, reviewed and pruned regularly
  • C. One endless conversation that never ends
  • D. Raising max_tokens
Show answer

Answer: B. The memory tool stores durable facts outside a single conversation, in storage you control and can review.

Question 2. An agent must never edit release notes without a person’s approval. Which design enforces this?

  • A. “Always ask before editing” in the system prompt
  • B. A can_use_tool callback (or hook) that denies Write/Edit on that file unless a reviewer approves
  • C. max_turns=1
  • D. Using Haiku
Show answer

Answer: B. Approval enforced in code holds regardless of model output; a prompt request does not.

Question 3. Which two are risks of agent memory? (Choose 2.)

  • A. Untrusted content can be written into memory and influence later sessions
  • B. Memory makes every request cheaper automatically
  • C. Sensitive data stored in memory can leak into later conversations
  • D. Memory removes the need for a system prompt
Show answer

Answer: A and C. Memory is data the agent wrote; it can carry injected instructions or secrets forward if not controlled.

Question 4. A team wants a scheduled nightly agent but does not want to host any infrastructure for the loop or its sandbox. What should they consider?

  • A. The Tool Runner on a laptop
  • B. Claude Managed Agents with a scheduled deployment
  • C. A Message Batch
  • D. Claude Code in interactive mode
Show answer

Answer: B. Managed Agents host the loop and per-session containers and support scheduled runs.

📝 Assignment

  1. Task 1: Run remember.py with your own key and inspect the memories folder after each session.
    ✅ Done when: the second session uses what the first stored.
  2. Task 2: Add a size limit to FolderMemory.create (for example 2 KB per file) that raises a clear error.
    ✅ Done when: an oversized write is rejected and Claude is told why.
  3. Stretch: Make ask_human read the decision from the terminal (input("approve? y/n ")) and log every decision with the tool input to approvals.log.
    ✅ Done when: both an approved and a rejected action are logged.

❓ Frequently Asked Questions

🤔 Does Claude remember previous conversations?

Not by itself. Use the memory tool, session resume, or project instructions such as CLAUDE.md to carry information between sessions.

🤔 What is the Claude memory tool?

An Anthropic-defined client tool (memory_20250818) through which Claude reads and writes files under /memories. Your code implements the storage.

🤔 How do I add human approval to an AI agent?

Intercept tool requests in code: can_use_tool or hooks in the Agent SDK, or permission policies in Managed Agents. Allow safe actions automatically and pause the rest for a person.

🤔 What are Claude Managed Agents?

A beta Anthropic service where agents are stored and versioned, and each session runs in an Anthropic-hosted container with tools, approvals, vaults and scheduling.

🏁 Summary

  • Use conversation history for the current task, sessions to resume, and the memory tool for durable facts.
  • Implement memory storage yourself, confined to one folder, small and reviewable.
  • Enforce human approval in code with can_use_tool, hooks or permission policies.
  • Resume or fork Agent SDK sessions with the session_id.
  • Managed Agents host the loop, sandbox, approvals and schedules when you do not want to.
📝 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 Debugging Claude Agent Traces: Loops, Drift and Under-Acting.

🎬 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.

Claude Subagents and Multi-Agent Orchestration

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 8 min read🎯 D1 Architecture and Runtime Selection · D6 Context Management for Long-Running Sessions

👋 In plain words: A subagent is a helper agent with its own fresh conversation, its own instructions and its own limited tools. The main agent hands it a job, and gets back only a short answer. This lesson shows when that helps, and builds an orchestrator that delegates log reading to a subagent, step by step.

Multi-agent systems are powerful and easy to overuse. Subagents shine when a subtask needs a lot of reading or a different, narrower set of permissions, because the noise stays in the subagent’s own context and only a summary returns. In this lesson you will decide when to split work, define a subagent with the Agent SDK’s AgentDefinition, watch an orchestrator delegate to it in a real run, design the hand-off, and learn the failure modes the exam asks you to diagnose.

📖 What You’ll Learn: You will be able to decide when subagents are worth it, define subagents with focused prompts and tools, design structured hand-offs, and diagnose common multi-agent failures.

🔑 Key terms

  • Orchestrator (lead agent): the agent that plans the work and delegates parts of it.
  • Subagent: an agent started by the orchestrator, with its own context window, system prompt, tools and model.
  • Context isolation: the subagent’s reading and tool output stay in its own context; only its final answer returns.
  • Hand-off: the task description the orchestrator sends and the result format the subagent returns.

🪜 Step 1: Decide whether to split

Use subagents when at least one of these is true:

  1. Heavy reading: the subtask reads many files or logs, and the orchestrator needs only a conclusion.
  2. Different permissions: the subtask needs tools the main agent should not have, or vice versa (a read-only reviewer).
  3. Independent parallel work: several subtasks do not depend on each other.
  4. Different model or effort: simple bulk work can run on a cheaper model.

Do not split when subtasks need each other’s details constantly, when a single agent already works, or when the cost of coordination (more calls, more tokens, harder debugging) outweighs the benefit.

🪜 Step 2: Prepare the data

A nightly CI log for the subagent to read:

📄 ci.log

[worker 1] test_checkout_total FAILED  TimeoutError waiting for #pay-button (30000 ms)
[worker 2] test_checkout_coupon FAILED TimeoutError waiting for #pay-button (30000 ms)
[worker 3] test_login_lockout FAILED   AssertionError: expected 'locked' got 'active'
[worker 4] test_search PASSED
[worker 5] test_checkout_guest FAILED  TimeoutError waiting for #pay-button (30000 ms)

🪜 Step 3: Define a subagent

AgentDefinition gives the subagent a description (used by the orchestrator to decide when to delegate), its own prompt, its own tools and optionally a model:

📄 agents.py

from claude_agent_sdk import AgentDefinition

LOG_READER = AgentDefinition(
    description="Reads CI log files and returns the distinct failure causes. Use for any log analysis.",
    prompt=("You summarise CI logs. Read the log file you are given and return at most 3 bullet points: "
            "each distinct root cause, the affected tests, and a count. No other text."),
    tools=["Read", "Grep"],   # read-only: this subagent cannot edit or run commands
    model="haiku",            # cheaper model for bulk reading
)
  • The description is a routing hint for the orchestrator, like a tool description.
  • Read-only tools make the subagent safe to point at untrusted logs.

🪜 Step 4: Let the orchestrator delegate

The orchestrator gets the subagent in agents and permission to use the Agent tool, which starts subagents:

📄 orchestrator.py

import asyncio
from pathlib import Path

from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ResultMessage, query

from agents import LOG_READER


async def main():
    options = ClaudeAgentOptions(
        agents={"log-reader": LOG_READER},
        allowed_tools=["Agent", "Read", "Grep"],
        cwd=str(Path.cwd()),
        max_turns=10,
        model="claude-opus-5-5",
    )
    prompt = "Triage last night's failures in ci.log and tell me what to fix first."
    async for m in query(prompt=prompt, options=options):
        if isinstance(m, AssistantMessage):
            who = "subagent" if m.parent_tool_use_id else "orchestrator"
            for b in m.content:
                if type(b).__name__ == "ToolUseBlock":
                    target = b.input.get("subagent_type") or Path(b.input.get("file_path", "")).name
                    print(f"{who:<12} -> {b.name} ({target})")
                elif type(b).__name__ == "TextBlock":
                    print(f"{who:<12} says: {b.text}")
        elif isinstance(m, ResultMessage):
            print(f"RESULT: {m.subtype}, turns={m.num_turns}")


asyncio.run(main())

When you run this with your own key, the flow is:

  1. The orchestrator reads the task and, guided by the subagent’s description, calls the Agent tool with subagent_type="log-reader", a short description and a prompt.
  2. The subagent starts with a fresh context, its own prompt, the cheaper model and only Read and Grep. It reads ci.log and returns a few bullet points, for example “Pay button never appears: 3 checkout tests” and “lockout state wrong: 1 login test”.
  3. Only that final answer reaches the orchestrator, which prioritises the fixes.
  4. In the message stream, messages from inside the subagent carry a parent_tool_use_id, which is how the script labels them.

The raw log never entered the orchestrator’s context. With 500 log files instead of one, that difference decides whether the main conversation stays usable.

🪜 Step 5: Design the hand-off

Most multi-agent bugs are hand-off bugs. Make both directions explicit:

Direction Include Avoid
Orchestrator → subagent The goal, the exact inputs (files, IDs), constraints, the output format, when to stop “Look into the failures” with no scope or format
Subagent → orchestrator A short, structured result: conclusions, evidence references, confidence, open questions Raw dumps of everything it read

A subagent starts with no memory of the main conversation. Anything it needs must be in the hand-off prompt (or available through its tools).

🎯 Exam focus: “Agent Pattern Diagnosis” includes subagent isolation problems. Typical traces: the orchestrator’s context explodes because subagents return raw logs (fix: summarise in the subagent); a subagent fails because it assumed context it never received (fix: complete hand-off prompt); a read-only reviewer edits files (fix: restrict its tools); orchestrator and subagents duplicate the same reading (fix: clearer decomposition).

🪜 Step 6: Know the failure modes

Symptom Cause Fix
Orchestrator context fills with raw data Subagents return everything Require short structured results
Subagent answers the wrong question Vague hand-off, missing inputs Goal, inputs, format and stop rule in the prompt
Two subagents edit the same file Overlapping responsibilities Partition work by file or area; one writer per resource
Cost explodes Too many subagents, or the top model for bulk work Fewer, larger tasks; cheaper model or lower effort for workers
A subagent does something risky It inherited broad tools Give each subagent the narrowest tool list

🌍 Real-world example: Ravi’s review team

Ravi’s PR-review agent first ran as one agent reading the whole diff, the test logs and the coverage report, and often ran out of context on big PRs. He split it: a read-only test-log-reader subagent (Haiku) summarises failures, a coverage-reader reports uncovered changed lines, and the orchestrator (Opus) writes the review from their two short reports. Reviews got faster and cheaper, and the reviewers can no longer edit code by accident.

🧪 Practice Questions

Question 1. An orchestrator’s context grows past 200K tokens because each subagent returns the full contents of every log it read. What is the best fix?

  • A. Give the orchestrator a larger model
  • B. Have subagents return short, structured summaries with references instead of raw content
  • C. Remove the subagents’ Read tool
  • D. Run all subagents in sequence
Show answer

Answer: B. Context isolation only helps if subagents return conclusions. Raw dumps defeat the purpose.

Question 2. A subagent asked to “check the failing test” reports it cannot find which test is meant. Why?

  • A. Subagents cannot read files
  • B. The subagent starts with a fresh context and the hand-off did not include the test name or inputs
  • C. The orchestrator used the wrong model
  • D. max_turns was too low
Show answer

Answer: B. Subagents do not inherit the main conversation. The hand-off must carry everything they need.

Question 3. Which two are good reasons to use a subagent? (Choose 2.)

  • A. A subtask must read hundreds of files but only a summary is needed
  • B. Every task, because more agents are always better
  • C. A subtask should run with read-only tools while the main agent can edit
  • D. To avoid writing tool descriptions
Show answer

Answer: A and C. Heavy reading and different permissions are the main benefits. Subagents add cost and complexity otherwise.

Question 4. In the Agent SDK, how does the orchestrator start a subagent defined in options.agents?

  • A. By calling query() again from a hook
  • B. By calling the Agent tool with the subagent’s type, a description and a prompt
  • C. Subagents start automatically for every message
  • D. Through the MCP connector
Show answer

Answer: B. The orchestrator delegates with the Agent tool; the subagent runs in its own context and returns its final answer.

📝 Assignment

  1. Task 1: Run orchestrator.py with your own key on a real CI log from your project.
    ✅ Done when: the orchestrator’s answer is based on the subagent’s summary.
  2. Task 2: Add a second subagent, test-writer, with Read and Write tools limited to the tests/ folder through a hook, and ask the orchestrator to add a regression test for the top failure.
    ✅ Done when: only files under tests/ change.
  3. Stretch: Make the log-reader return JSON (causes, tests, count) and have your code validate it before the orchestrator continues.
    ✅ Done when: a malformed subagent result is detected and reported.

❓ Frequently Asked Questions

🤔 What are Claude subagents?

Separate agents with their own context window, prompt, tools and model, started by a main agent to handle part of a task and return a result.

🤔 When should I use multiple agents?

When subtasks are context-heavy, need different permissions or models, or can run independently. Otherwise one agent is simpler and cheaper.

🤔 Do subagents share memory with the main agent?

No. Each starts fresh. Pass what it needs in the hand-off prompt, and return only a concise result.

🤔 How do I define a subagent in the Agent SDK?

Create an AgentDefinition with a description, prompt, tools and optional model, pass it in ClaudeAgentOptions(agents={...}), and allow the Agent tool.

🏁 Summary

  • Subagents isolate context, narrow permissions and allow cheaper models for bulk work.
  • Split only for heavy reading, different permissions, parallel work or different models.
  • Define subagents with AgentDefinition; the orchestrator delegates through the Agent tool.
  • Hand-offs need full inputs and a structured, short result format.
  • Diagnose failures by checking returns, hand-offs, overlaps, cost and tool scope.
📝 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 Agent Memory, Human-in-the-Loop and Managed Agents.

🎬 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.

Claude Agent SDK in Python: First Agent, Tools and Hooks

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D1 Agent SDK Construction and Hooks · D7 Deterministic Guardrails and Least Privilege

👋 In plain words: The Claude Agent SDK gives you Claude Code’s agent engine as a Python library: the loop, file and shell tools, permissions and hooks are already built. You describe the task and the rules; it does the work. This lesson builds a QA agent with it, step by step, including hooks that enforce rules no prompt can override.

Writing your own loop (Lesson 32) teaches the mechanics; the Agent SDK gives you a production-grade harness. In this lesson you will run a first agent that reads files with the built-in Read tool, restrict what it may do with allowed tools and permission modes, add a custom tool through an in-process MCP server, and attach PreToolUse and PostToolUse hooks that block destructive commands and write an audit log, all running for real against a local stand-in for the API.

📖 What You’ll Learn: You will be able to create Agent SDK agents with query() and ClaudeAgentOptions, control tools and permissions, add custom tools with create_sdk_mcp_server, and enforce required actions with hooks.

🔑 Key terms

  • query(): the Agent SDK function that runs an agent for one prompt and yields its messages.
  • ClaudeAgentOptions: settings for a run: allowed tools, permission mode, working folder, system prompt, model, hooks, MCP servers and more.
  • Built-in tools: Claude Code’s tools such as Read, Write, Edit, Bash, Glob, Grep, WebSearch and WebFetch.
  • Hook: your function that the harness calls at a fixed point (before or after a tool, at session start, on stop…). It can allow, deny or modify.
  • Permission mode: how the harness decides about tool use without asking: default, acceptEdits, plan, bypassPermissions, dontAsk or auto.

🪜 Step 1: Install the SDK

⌨️ Terminal

pip install claude-agent-sdk

This course was built with claude-agent-sdk 0.2.187, which bundles the Claude Code engine it drives. Authentication uses the same ANTHROPIC_API_KEY as the API (or a cloud provider, configured through environment variables).

🪜 Step 2: Run a first agent with a built-in tool

Give the agent a question about a file in its working folder and allow only the Read tool:

📄 pytest.ini

[pytest]
addopts = -q --maxfail=3
timeout = 30
markers =
    smoke: quick checks run on every commit

📄 first_agent.py

import asyncio
from pathlib import Path

from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ResultMessage, query


async def main():
    options = ClaudeAgentOptions(
        allowed_tools=["Read"],          # pre-approve only reading files
        cwd=str(Path.cwd()),             # the agent works in this folder
        max_turns=5,
        model="claude-opus-5-5",
    )
    async for message in query(prompt="What per-test timeout does pytest.ini set?", options=options):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if type(block).__name__ == "ToolUseBlock":
                    print("TOOL ->", block.name, Path(block.input["file_path"]).name)
                elif type(block).__name__ == "TextBlock":
                    print("CLAUDE:", block.text)
        elif isinstance(message, ResultMessage):
            print(f"RESULT: {message.subtype}, turns={message.num_turns}")


asyncio.run(main())

⌨️ Terminal

python first_agent.py

🖥️ Output (sample run)

TOOL -> Read pytest.ini
CLAUDE: pytest.ini sets a per-test timeout of 30 seconds (timeout = 30).
RESULT: success, turns=2
  • The SDK ran the whole loop: Claude asked for Read, the harness read the real file and sent its content back, and Claude answered.
  • query() yields typed messages: a SystemMessage at start, AssistantMessages, tool results as UserMessages, and a final ResultMessage with turns, duration and cost.

🪜 Step 3: Control tools and permissions

Least privilege starts with the options:

Option Effect
allowed_tools=[...] Tools that run without asking
disallowed_tools=[...] Tools that are never available
permission_mode default (ask for anything not allowed), acceptEdits (auto-approve file edits), plan (plan only, no changes), bypassPermissions (no checks: avoid outside sandboxes), plus dontAsk and auto
cwd / add_dirs The folders the agent works in
max_turns, max_budget_usd, task_budget Limits on how long and how expensive a run can be
can_use_tool Your callback that approves or denies each tool request at run time
⚠️ Watch out: permission_mode="bypassPermissions" disables the safety checks. Use it only inside an isolated container or VM with no secrets, never on a developer laptop or a CI runner with production credentials.

🪜 Step 4: Add a custom tool

Custom tools run in your Python process through an in-process MCP server. The tool name the model sees is mcp__<server>__<tool>:

📄 ci_tool.py

from claude_agent_sdk import create_sdk_mcp_server, tool

FAILURES = {"812": ["test_checkout_total"]}


@tool("get_failed_tests", "List the failed tests of a CI build. build is the numeric build number, e.g. 812.",
      {"build": str})
async def get_failed_tests(args):
    failed = FAILURES.get(args["build"], [])
    return {"content": [{"type": "text", "text": f"build {args['build']}: {', '.join(failed) or 'no failures'}"}]}


ci_server = create_sdk_mcp_server("ci", tools=[get_failed_tests])

🪜 Step 5: Enforce rules with hooks

Prompts ask; hooks enforce. A PreToolUse hook runs before every matching tool call and can deny it. A PostToolUse hook runs after and is ideal for audit logs. Here the agent is allowed to use Bash, but a hook blocks destructive commands, and every tool call is logged:

📄 guarded_agent.py

import asyncio
import json

from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, HookMatcher, ResultMessage, UserMessage, query

from ci_tool import ci_server

BLOCKED = ("rm -rf", "git push --force", "DROP TABLE")


async def block_destructive(input_data, tool_use_id, context):
    command = input_data["tool_input"].get("command", "")
    if any(bad in command for bad in BLOCKED):
        return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
                                       "permissionDecisionReason": f"Blocked by policy: {command!r}"}}
    return {}


async def audit(input_data, tool_use_id, context):
    with open("audit.log", "a") as f:
        f.write(json.dumps({"tool": input_data["tool_name"], "input": input_data["tool_input"]}) + "\n")
    return {}


async def main():
    options = ClaudeAgentOptions(
        mcp_servers={"ci": ci_server},
        allowed_tools=["mcp__ci__get_failed_tests", "Bash"],
        hooks={
            "PreToolUse": [HookMatcher(matcher="Bash", hooks=[block_destructive])],
            "PostToolUse": [HookMatcher(hooks=[audit])],
        },
        max_turns=6,
        model="claude-opus-5-5",
    )
    async for m in query(prompt="Check build 812, then clean up the build folder.", options=options):
        if isinstance(m, AssistantMessage):
            for b in m.content:
                if type(b).__name__ == "ToolUseBlock":
                    print("TOOL REQUEST ->", b.name, b.input)
                elif type(b).__name__ == "TextBlock":
                    print("CLAUDE:", b.text)
        elif isinstance(m, UserMessage) and isinstance(m.content, list):
            for b in m.content:
                print("TOOL RESULT  <-", str(getattr(b, "content", ""))[:90])
        elif isinstance(m, ResultMessage):
            print(f"RESULT: {m.subtype}, turns={m.num_turns}")
    print("audit.log:\n" + open("audit.log").read())


asyncio.run(main())

⌨️ Terminal

python guarded_agent.py

🖥️ Output (sample run)

TOOL REQUEST -> mcp__ci__get_failed_tests {'build': '812'}
TOOL RESULT  <- [{'type': 'text', 'text': 'build 812: test_checkout_total'}]
TOOL REQUEST -> Bash {'command': 'rm -rf ./build', 'description': 'Clean the build folder'}
TOOL RESULT  <- PreToolUse:Bash hook error: Blocked by policy: 'rm -rf ./build'
CLAUDE: Build 812 has one failure: test_checkout_total. I did not clean the build folder because the delete command was blocked by policy; ask an administrator if it really needs to be removed.
RESULT: success, turns=3
audit.log:
{"tool": "mcp__ci__get_failed_tests", "input": {"build": "812"}}

What really happened in that run:

  1. Claude called the custom tool; your Python function answered.
  2. Claude asked Bash to run rm -rf ./build. Your PreToolUse hook denied it before anything ran, and the reason went back to Claude as the tool result.
  3. Claude reported honestly that the cleanup did not happen.
  4. The PostToolUse hook logged only the call that actually ran: the denied Bash command never executed, so it is not in the audit log.
🎯 Exam focus: The skill text says hooks make “required actions execute deterministically rather than at the model’s discretion”. Use hooks (or can_use_tool) whenever a rule must hold every time: blocking destructive commands, requiring a test run before a commit, logging every tool call, or redacting secrets from tool output. A system-prompt instruction is not enforcement.

🪜 Step 6: Read results and continue sessions

The final ResultMessage reports num_turns, duration_ms, total_cost_usd, usage and the session_id. Save the session ID to continue later with ClaudeAgentOptions(resume=session_id), or fork it to try an alternative without changing the original. For multi-turn interactive use, ClaudeSDKClient keeps one session open across several prompts.

🌍 Real-world example: Ravi’s nightly triage agent

Ravi moved his hand-written loop to the Agent SDK. The agent gets Read, Grep and a custom get_failed_tests tool, works only in the checked-out repository, and has max_turns=30 and a dollar budget. A PreToolUse hook blocks any Bash command outside an allow-list (pytest, git log, git diff), and a PostToolUse hook writes every call to the CI artifacts so reviewers can see exactly what the agent did.

🧪 Practice Questions

Question 1. A team’s agent must never run git push –force, even if a prompt-injected file tells it to. Which mechanism enforces this?

  • A. A sentence in the system prompt
  • B. A PreToolUse hook (or can_use_tool callback) that denies matching Bash commands
  • C. A larger model
  • D. max_turns=1
Show answer

Answer: B. Hooks run in code before the tool executes and cannot be talked out of their decision.

Question 2. In the Agent SDK, what name does the model see for a custom tool get_failed_tests on an SDK MCP server named ci?

  • A. get_failed_tests
  • B. ci.get_failed_tests
  • C. mcp__ci__get_failed_tests
  • D. tool_ci_get_failed_tests
Show answer

Answer: C. MCP tools are namespaced as mcp____, and that full name goes in allowed_tools.

Question 3. Which two options apply least privilege to an Agent SDK agent? (Choose 2.)

  • A. allowed_tools listing only the tools the task needs
  • B. permission_mode=”bypassPermissions” on a developer laptop
  • C. cwd set to the project folder the agent should work in
  • D. Disabling all hooks
Show answer

Answer: A and C. Narrow tool lists and a bounded working folder limit what the agent can touch; bypassing permissions removes the checks.

Question 4. Which statement about the Agent SDK and the Tool Runner is correct?

  • A. The Agent SDK includes Claude Code’s built-in tools, hooks and permissions; the Tool Runner loops only over tools you define
  • B. They are the same package
  • C. The Tool Runner has more built-in tools than the Agent SDK
  • D. Neither can call custom tools
Show answer

Answer: A. The Agent SDK is the Claude Code harness as a library; the Tool Runner is a smaller helper in the anthropic SDK.

📝 Assignment

  1. Task 1: Run first_agent.py with your own key in one of your repositories and ask about its test configuration.
    ✅ Done when: the agent answers using the Read tool.
  2. Task 2: Add a PreToolUse hook that allows Bash only for commands starting with pytest or git log.
    ✅ Done when: any other command is denied with a clear reason.
  3. Stretch: Add a PostToolUse hook that redacts strings matching sk-ant- from tool output before it reaches the model (check the SDK docs for the hook output field that replaces tool output).
    ✅ Done when: a file containing a fake key is read and the model never sees the key.

❓ Frequently Asked Questions

🤔 What is the Claude Agent SDK?

A Python and TypeScript library that runs Claude Code’s agent harness inside your program, with built-in tools, permissions, hooks, subagents and sessions.

🤔 How do I add custom tools to the Agent SDK?

Decorate an async function with @tool, wrap it with create_sdk_mcp_server, pass the server in mcp_servers, and allow mcp__<server>__<tool>.

🤔 What are Agent SDK hooks?

Functions the harness calls at fixed points such as before and after tool use. They can deny, allow or modify actions, so rules are enforced deterministically.

🤔 Is the Agent SDK the same as Claude Code?

It uses the same engine. Claude Code is the interactive product; the Agent SDK lets you run that engine from your own code.

🏁 Summary

  • query(prompt, options) runs a full agent with Claude Code’s harness.
  • Limit power with allowed_tools, disallowed_tools, permission_mode, cwd and budgets.
  • Add custom tools with @tool and create_sdk_mcp_server; they appear as mcp__server__tool.
  • Use PreToolUse hooks to enforce rules and PostToolUse hooks for audit logs.
  • Read the ResultMessage for turns, cost and session ID; resume or fork sessions as needed.
📝 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 Subagents and Multi-Agent Orchestration.

🎬 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.

Build a Claude Agent Loop from Scratch in Python

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 8 min read🎯 D1 Agent SDK Construction and Hooks · D1 Agent Pattern Diagnosis

👋 In plain words: An agent is a loop: ask Claude what to do next, run the tool it picks, show it the result, repeat. In this lesson you write that loop yourself for a small test-fixing agent, with safety rails, so you understand exactly what frameworks like the Agent SDK do for you.

Building one agent by hand is the fastest way to understand every agent framework, and the exam’s agent-diagnosis questions assume you know what the loop is doing. In this lesson you will give Claude four tools that really run pytest, read and write files in a sandboxed project folder, write the loop with correct stop conditions, add a step limit and a token budget, and print a trace you can debug from.

📖 What You’ll Learn: You will be able to implement a complete Claude agent loop in Python with real tools, correct termination, budgets, path sandboxing and an inspectable trace.

🔑 Key terms

  • Agent loop: repeat {call Claude → run requested tools → return results} until Claude stops asking for tools.
  • Trace: the step-by-step record of an agent run: model calls, tool calls, results, stop reason.
  • Path sandboxing: refusing any file path outside an allowed folder, so the agent cannot touch the rest of the machine.
  • Budget: a limit on steps, tokens or money for one run.

🪜 The steps at a glance

  1. Create a small project with a failing test.
  2. Write the tools.
  3. Describe the tools to Claude.
  4. Write the loop with correct stop conditions.
  5. Add budgets and a trace.
  6. Run the agent and read the trace.

🪜 Step 1: Create a project with a failing test

The agent’s job will be to make the tests pass:

📄 project/shop.py

def discount(total: float, percent: int) -> float:
    """Return the total after a percentage discount."""
    return total - percent  # BUG: subtracts the percent as money

📄 project/test_shop.py

from shop import discount


def test_ten_percent():
    assert discount(200.0, 10) == 180.0


def test_zero_percent():
    assert discount(50.0, 0) == 50.0

🪜 Step 2: Write the tools

Each tool is ordinary Python. File tools refuse paths outside project/: that check is in code, so no model output can bypass it.

📄 agent_tools.py

import subprocess
import sys
from pathlib import Path

ROOT = (Path(__file__).parent / "project").resolve()


def _safe(path: str) -> Path:
    p = (ROOT / path).resolve()
    if not p.is_relative_to(ROOT):
        raise PermissionError(f"path outside the project: {path}")
    return p


def run_tests() -> str:
    r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"],
                       cwd=ROOT, capture_output=True, text=True, timeout=120)
    return (r.stdout + r.stderr)[-2000:]  # shape the result: tail only


def read_file(path: str) -> str:
    return _safe(path).read_text()


def write_file(path: str, content: str) -> str:
    _safe(path).write_text(content)
    return f"wrote {len(content)} characters to {path}"


def list_files() -> str:
    return "\n".join(sorted(p.name for p in ROOT.iterdir() if p.suffix == ".py"))

🪜 Step 3: Describe the tools to Claude

📄 agent_schema.py

TOOLS = [
    {"name": "run_tests", "description": "Run the project's pytest suite and return the last part of the output.",
     "input_schema": {"type": "object", "properties": {}}},
    {"name": "list_files", "description": "List the Python files in the project.",
     "input_schema": {"type": "object", "properties": {}}},
    {"name": "read_file", "description": "Read one project file. path is relative to the project, e.g. shop.py.",
     "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
    {"name": "write_file", "description": "Replace a project file's whole content. Only change source files, never tests.",
     "input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
                      "required": ["path", "content"]}},
]

🪜 Step 4: Write the loop

The loop follows the rules from Lesson 23, plus the outcomes an agent must handle:

📄 agent.py

import json

import anthropic

import agent_tools
from agent_schema import TOOLS

client = anthropic.Anthropic()
SYSTEM = """You are a careful test-fixing agent. Run the tests, read the code, make the smallest fix in source files
(never edit tests), and run the tests again. Stop when all tests pass, and summarise what you changed."""
REGISTRY = {"run_tests": agent_tools.run_tests, "list_files": agent_tools.list_files,
            "read_file": agent_tools.read_file, "write_file": agent_tools.write_file}


def run_agent(goal: str, max_steps: int = 10, max_output_tokens: int = 20_000) -> str:
    messages = [{"role": "user", "content": goal}]
    used = 0
    for step in range(1, max_steps + 1):
        r = client.messages.create(model="claude-opus-5-5", max_tokens=4000, system=SYSTEM,
                                   tools=TOOLS, messages=messages)
        used += r.usage.output_tokens
        messages.append({"role": "assistant", "content": r.content})

        if r.stop_reason == "end_turn":
            return "DONE: " + "".join(b.text for b in r.content if b.type == "text")
        if r.stop_reason in ("max_tokens", "refusal"):
            return f"STOPPED: stop_reason={r.stop_reason}"
        if used > max_output_tokens:
            return f"STOPPED: output-token budget exceeded ({used})"

        results = []
        for b in r.content:
            if b.type != "tool_use":
                continue
            try:
                output, is_error = REGISTRY[b.name](**b.input), False
            except Exception as e:
                output, is_error = f"{type(e).__name__}: {e}", True
            print(f"step {step}: {b.name}({json.dumps(b.input)[:60]}) -> {str(output).splitlines()[-1][:70]}")
            results.append({"type": "tool_result", "tool_use_id": b.id, "content": str(output), "is_error": is_error})
        messages.append({"role": "user", "content": results})
    return f"STOPPED: reached {max_steps} steps"
  • Stop conditions are explicit: end_turn (done), max_tokens or refusal (cannot continue), a budget, or the step limit. Each returns a different message so a caller knows why it stopped.
  • pause_turn (from server tools) would be handled by re-sending the turn; this agent uses only client tools.
  • Tool exceptions, including the sandbox’s PermissionError, become is_error results that Claude can react to.

🪜 Step 5: Run it and read the trace

📄 run_agent.py

from agent import run_agent

print(run_agent("Make the failing tests in this project pass."))

⌨️ Terminal

python run_agent.py

🖥️ Output (sample run)

step 1: run_tests({}) -> 1 failed, 1 passed in 0.42s
step 2: read_file({"path": "shop.py"}) ->     return total - percent  # BUG: subtracts the percent as money
step 3: write_file({"path": "shop.py", "content": "def discount(total: float, p) -> wrote 148 characters to shop.py
step 4: run_tests({}) -> 2 passed in 0.42s
DONE: All tests pass. I changed discount() in shop.py to subtract a percentage of the total (total * percent / 100) instead of subtracting the percent value itself. Tests were not modified.

The tool calls in this trace really ran: pytest executed against project/, the file was read and rewritten, and the second pytest run passed. Only Claude’s decisions came from the local stand-in API.

📄 check_fix.py

from pathlib import Path

print(Path("project/shop.py").read_text())

⌨️ Terminal

python check_fix.py

🖥️ Output

def discount(total: float, percent: int) -> float:
    """Return the total after a percentage discount."""
    return total - total * percent / 100

🪜 Step 6: Try to escape the sandbox

Agents read untrusted text (logs, files, web pages) that can contain instructions. Check that the guardrail holds regardless of what the model asks for:

📄 escape.py

import agent_tools

for path in ["shop.py", "../agent.py", "C:/Windows/win.ini"]:
    try:
        agent_tools.read_file(path)
        print(f"{path:<20} allowed")
    except PermissionError as e:
        print(f"{path:<20} blocked: {e}")

⌨️ Terminal

python escape.py

🖥️ Output

shop.py              allowed
../agent.py          blocked: path outside the project: ../agent.py
C:/Windows/win.ini   blocked: path outside the project: C:/Windows/win.ini
🎯 Exam focus: Agent-diagnosis items describe a misbehaving loop and ask which pattern is missing: termination (stops on text, or never stops), result handling (results not appended, so tools repeat), budget (runaway cost), error handling (one tool failure kills the run), or guardrails (risky actions decided by the model alone). This lesson’s loop shows the correct version of each.

🌍 Real-world example: Ravi’s runaway agent

Ravi’s first agent had no step limit and treated tool exceptions as fatal. One night a flaky network made run_tests time out, the agent crashed, and the job retried from scratch 40 times. With is_error results Claude could see the timeout and wait; with a step limit and a token budget, the worst case became a short, cheap, clearly logged stop.

🧪 Practice Questions

Question 1. An agent repeats the same read_file call over and over. Traces show the tool runs each time, but the next request never contains its output. What is wrong?

  • A. The tool description is unclear
  • B. Tool results are not appended to the messages before the next call
  • C. max_tokens is too high
  • D. The step limit is too low
Show answer

Answer: B. If Claude never sees the result, it keeps asking for it. Every tool_result must go back in the next user message.

Question 2. Which is the correct primary stop condition for a manual agent loop?

  • A. Stop when the reply contains any text
  • B. Stop after exactly three steps
  • C. Continue while stop_reason is tool_use; stop on end_turn, and handle max_tokens and refusal explicitly
  • D. Stop when the model says “done”
Show answer

Answer: C. stop_reason is the reliable signal. Step limits and budgets are backstops, not the main condition.

Question 3. Which two belong in code rather than in the prompt for a file-editing agent? (Choose 2.)

  • A. Refusing paths outside the project folder
  • B. The tone of the final summary
  • C. A maximum number of steps and a token budget
  • D. The explanation of what the bug was
Show answer

Answer: A and C. Safety limits must hold regardless of model output, so they are enforced in code.

Question 4. A tool raises an exception and the whole agent run crashes. What is the better design?

  • A. Remove the tool
  • B. Catch the exception and return a tool_result with is_error true and the message
  • C. Retry the tool forever
  • D. Ask the user to restart the run
Show answer

Answer: B. Returning the error lets Claude adapt (retry differently, choose another tool, or stop with an explanation).

📝 Assignment

  1. Task 1: Run the agent with your own key on the project, then add a third failing test (for example a 100% discount) and run it again.
    ✅ Done when: the agent fixes the code and all three tests pass.
  2. Task 2: Save the full messages list to trace.json at the end of every run.
    ✅ Done when: you can replay the run step by step from the file.
  3. Stretch: Add a rule in code that rejects write_file for any file whose name starts with test_, returning an is_error result.
    ✅ Done when: a scripted attempt to edit a test is blocked and the agent explains it could not.

❓ Frequently Asked Questions

🤔 How do I build an AI agent in Python with Claude?

Define tools, call the Messages API with them, run each requested tool, return the results in one user message, and loop while stop_reason is tool_use, with budgets and guardrails in code.

🤔 When should an agent loop stop?

On end_turn (finished), on max_tokens or refusal (cannot continue normally), or when a budget or step limit is reached as a safety backstop.

🤔 How do I stop an agent from changing the wrong files?

Enforce allowed paths in the tool code (path sandboxing) and, for risky actions, require approval. Do not rely on the prompt alone.

🤔 Should I write my own loop or use a framework?

Write one once to understand it. In production, use the Tool Runner or the Agent SDK unless you need custom control flow.

🏁 Summary

  • An agent is a loop of model calls, tool calls and tool results.
  • Terminate on stop_reason; treat step limits and budgets as backstops.
  • Return tool failures as is_error results instead of crashing.
  • Enforce safety (path sandboxing, write rules) in code.
  • Print and save a trace for every run so you can debug it.
📝 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 Agent SDK in Python: First Agent, Tools and Hooks.

🎬 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.

Workflow vs Agent with Claude: Choosing the Right Architecture

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D1 Architecture and Runtime Selection

👋 In plain words: A workflow is a recipe your code follows step by step, calling Claude where needed. An agent lets Claude decide the steps itself, using tools, until the job is done. Agents are more flexible but harder to predict and audit. This lesson helps you choose, one requirement at a time.

“Build an agent” is the most over-used phrase in AI projects. Many tasks are better as workflows: cheaper, faster, easier to test and to audit. The CCDV-F exam asks you to evaluate whether a workflow or an agentic architecture fits given business requirements, error tolerance and audit constraints, and to pick the runtime. In this lesson you will learn the five common workflow patterns, run a routing workflow, and apply a decision checklist to QA scenarios.

📖 What You’ll Learn: You will be able to explain the difference between workflows and agents, recognise the five workflow patterns, choose an architecture from requirements, error tolerance and audit needs, and choose between a self-hosted harness and a managed runtime.

🔑 Key terms

  • Workflow: a system where your code defines the sequence of steps; Claude performs some of them.
  • Agent: a system where Claude chooses the next step (which tool, in what order) in a loop until the goal is reached.
  • Orchestrator: the part that splits a task and coordinates workers or subagents.
  • Harness: the code that runs an agent’s loop, tools and permissions.
  • Audit trail: a record of what was done, by whom and why, that a reviewer can check.

🪜 Step 1: Know the five workflow patterns

Most production Claude systems are one of these, or a combination:

Pattern How it works QA example
Prompt chaining Fixed sequence; each step’s output feeds the next Extract rules → generate cases → review (Lesson 17)
Routing A first call classifies the input; code sends it to a specialised path Route a failure to the UI, API or environment handler
Parallelisation Independent subtasks run at once, or several votes are combined Summarise 50 failing tests concurrently
Orchestrator–workers A central call splits the task dynamically and delegates parts Split a large test plan by feature for separate writers
Evaluator–optimiser One call produces, another critiques, repeat until a bar is met Generate a test, review it against standards, refine

In all five, your code decides the flow. That is what makes them predictable.

🪜 Step 2: See a routing workflow

A cheap first call classifies; the code then calls the right specialist. Claude never decides the overall flow:

📄 router.py

import anthropic

client = anthropic.Anthropic()

ROUTES = {
    "ui": "You debug Selenium/Playwright UI failures. Suggest the most likely locator or timing fix.",
    "api": "You debug API test failures. Point to the request, status code or schema problem.",
    "environment": "You debug test environment problems. Name the service and the check to run.",
}


def classify(failure: str) -> str:
    r = client.messages.create(
        model="claude-haiku-5-5", max_tokens=5, output_config={"effort": "low"},
        system="Classify the test failure as ui, api or environment. Reply with one word.",
        messages=[{"role": "user", "content": failure}],
    )
    return r.content[0].text.strip().lower()


def handle(failure: str) -> str:
    route = classify(failure)
    system = ROUTES.get(route, ROUTES["environment"])  # fall back deterministically
    r = client.messages.create(model="claude-opus-5-5", max_tokens=300, system=system,
                               messages=[{"role": "user", "content": failure}])
    return f"[{route}] {r.content[0].text}"


print(handle("POST /api/orders returned 422: field 'qty' must be > 0"))
print(handle("TimeoutError: locator('#pay').click: element is not visible"))

⌨️ Terminal

python router.py

🖥️ Output (sample run)

[api] The request sends qty = 0 or a negative value; fix the test data so qty is at least 1.
[ui] The Pay button is hidden, likely behind a loading overlay; wait for the overlay to disappear before clicking.
  • Haiku at low effort is enough for classification; the specialist call uses Opus.
  • Each route can be tested on its own, and an unknown label falls back in code, not by the model’s choice.

🪜 Step 3: Know what makes an agent different

In an agent, Claude receives tools and a goal, and decides which tool to call next based on what it has seen, looping until it judges the job done (Lesson 32 builds one). That gives:

  • Flexibility: it can handle paths nobody coded (“the order was delivered but the customer says it wasn’t, so check the delivery photo”).
  • Cost and latency: more calls, more tokens, longer runs.
  • Less predictability: the same input can take different paths, which makes testing and auditing harder.
  • Compounding errors: an early mistake can steer later steps; you need checkpoints and guardrails.

🪜 Step 4: Decide with a checklist

Choose an agent only if all of these are true; otherwise stay with a workflow:

  1. Complexity: the steps cannot be fully specified in advance (open-ended exploration, varying paths).
  2. Value: the result justifies the higher cost and latency.
  3. Viability: Claude is demonstrably good at this kind of task (measure it).
  4. Cost of error: mistakes can be caught and recovered from (tests, reviews, rollback, approvals).

Then weigh the two constraints the exam names:

  • Error tolerance: low tolerance (payments, production changes) → fixed workflow steps, or an agent with deterministic gates and human approval for risky actions.
  • Audit constraints: if every decision must be traceable to a rule, a workflow (or an agent with full traces and fixed checkpoints) is easier to defend.

This helper encodes the checklist. It runs locally:

📄 choose_architecture.py

def choose(steps_known_in_advance: bool, value_justifies_cost: bool, model_proven: bool,
           errors_recoverable: bool, strict_audit: bool) -> str:
    if steps_known_in_advance:
        return "workflow"
    if not (value_justifies_cost and model_proven and errors_recoverable):
        return "workflow (simplify the task or keep a human in the loop)"
    if strict_audit:
        return "agent with deterministic checkpoints, full traces and human approval for risky steps"
    return "agent"


scenarios = {
    "Generate pytest cases from a fixed requirement template": (True, True, True, True, False),
    "Investigate any red CI build and propose a fix in a PR": (False, True, True, True, False),
    "Auto-approve refunds from support chats": (False, True, True, False, True),
    "Migrate 400 Selenium tests to Playwright with review": (False, True, True, True, True),
}
for name, args in scenarios.items():
    print(f"{name:<58} -> {choose(*args)}")

⌨️ Terminal

python choose_architecture.py

🖥️ Output

Generate pytest cases from a fixed requirement template    -> workflow
Investigate any red CI build and propose a fix in a PR     -> agent
Auto-approve refunds from support chats                    -> workflow (simplify the task or keep a human in the loop)
Migrate 400 Selenium tests to Playwright with review       -> agent with deterministic checkpoints, full traces and human approval for risky steps

🪜 Step 5: Decompose before you build

When an agent is right, decide how to split it:

  • Single agent with tools for most tasks. Simplest to debug.
  • Orchestrator + subagents when subtasks are independent and context-heavy (each subagent reads a lot and returns a short result), or need different tools or permissions (Lesson 34).
  • Keep subagent responsibilities narrow, inputs explicit, and outputs structured, so the orchestrator can check them.

🪜 Step 6: Choose the runtime

The exam also asks where the agent runs:

Option You host Choose when
Self-hosted harness: your own loop, the Tool Runner, or the Claude Agent SDK The loop, tools and compute You need full control, run in your network, or your platform lacks managed agents
Managed, sandboxed runtime: Claude Managed Agents (beta) Nothing; Anthropic runs the loop and a per-session container Long-running or scheduled agents, file-heavy work, and you would rather not operate the infrastructure

Check data-handling and platform requirements first: managed runtimes keep session data with the provider and are not available on every cloud platform.

🎯 Exam focus: Scenario answers usually prefer the simplest architecture that meets the requirements. “Steps are fixed and must be auditable” → workflow. “Open-ended investigation with recoverable errors” → agent. “Risky actions” → deterministic gates (hooks, approvals) regardless of architecture. “Do not want to host the loop or sandbox” → managed runtime.

🌍 Real-world example: Ravi’s two systems

Ravi’s team first built “an agent” to turn requirements into test cases. Runs varied, cost was high, and reviewers could not tell why a case was included. They rebuilt it as a three-step chain with a review step, and costs fell by 70%. They kept an agent for one job only: investigating red nightly builds, where the path really is different every time, with a hook that blocks any write outside the tests/ folder.

🧪 Practice Questions

Question 1. A team must generate release notes from merged pull requests in a fixed format every week. Steps never change, and compliance requires each line to be traceable to a PR. What architecture fits?

  • A. A workflow (prompt chain) with code-controlled steps
  • B. A fully autonomous agent with web search
  • C. A multi-agent system with five subagents
  • D. A managed agent with no tools
Show answer

Answer: A. The steps are known and auditability is required; a workflow is cheaper, predictable and traceable.

Question 2. Which condition most strongly argues for an agent rather than a workflow?

  • A. The task needs Claude to classify text
  • B. The path to the goal varies by case and cannot be specified in advance
  • C. The team wants the newest technology
  • D. The output must be JSON
Show answer

Answer: B. Agents earn their cost when the steps depend on what is discovered along the way.

Question 3. Which two are reasons to choose Claude Managed Agents over a self-hosted Agent SDK harness? (Choose 2.)

  • A. The team does not want to operate the agent loop and sandbox infrastructure
  • B. The agent must run inside a private network with no external access
  • C. The agent runs on a schedule and works with files in a per-session container
  • D. The cloud platform in use does not support managed agents
Show answer

Answer: A and C. Managed Agents host the loop and a per-session container, which suits scheduled, file-heavy work. Private-network and unsupported-platform constraints point to self-hosting.

Question 4. A routing workflow sends failures to specialist prompts. A new failure type appears that the classifier labels “database”. What should the code do?

  • A. Let Claude decide a new route on the fly
  • B. Fall back deterministically to a default handler and log the unknown label
  • C. Crash so someone notices
  • D. Retry the classifier until it returns a known label
Show answer

Answer: B. Routing stays code-controlled: unknown labels go to a defined fallback and are logged for review.

📝 Assignment

  1. Task 1: List three Claude ideas for your team and run them through choose_architecture.py.
    ✅ Done when: each has an architecture and a one-line reason tied to the checklist.
  2. Task 2: Extend router.py with a data route for test-data problems and a unit test for the fallback.
    ✅ Done when: an unknown label routes to the default and the test passes.
  3. Stretch: Turn one of your workflows into an evaluator–optimiser loop with at most two refinement rounds and a pass/fail rubric.
    ✅ Done when: the loop stops either on pass or after two rounds, and logs why.

❓ Frequently Asked Questions

🤔 What is the difference between an AI workflow and an AI agent?

In a workflow your code fixes the steps. In an agent, the model decides the next step and which tools to use, in a loop.

🤔 When should I use an AI agent?

When the task is open-ended, valuable enough to justify the cost, something the model is proven good at, and when errors can be caught and recovered from.

🤔 What are agentic workflow patterns?

Prompt chaining, routing, parallelisation, orchestrator–workers and evaluator–optimiser. They structure model calls with code-controlled flow.

🤔 Are agents harder to test?

Yes. Paths vary between runs, so you test outcomes and properties with evaluations and traces, and add deterministic checkpoints for risky steps.

🏁 Summary

  • Workflows: code decides the steps (chaining, routing, parallelisation, orchestrator–workers, evaluator–optimiser).
  • Agents: Claude decides the steps; use them only for open-ended, valuable, recoverable tasks.
  • Low error tolerance and strict audits push toward workflows or gated agents.
  • Prefer a single agent; add subagents for independent, context-heavy subtasks.
  • Self-host the harness for control; use Managed Agents to avoid running the loop and sandbox.
📝 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 Build a Claude Agent Loop from Scratch in Python.

🎬 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.