The first four sessions taught you how Claude Code works (core-1), how its context is assembled (core-2), how to give it durable knowledge (core-3) and how to run a tight daily loop with it (core-4). This session is about the step after that: turning work you repeat into workflows that run the same way every time, check their own output, and stay inside a boundary you chose.

A workflow in Claude Code is assembled from parts you already know, each used for the job it does best. A workflow skill carries the procedure. Hooks and scripts carry the steps that must never vary. A dynamic workflow script carries a fan-out that is too big for one conversation. Review loops and verification subagents carry quality. The sandbox and permission rules carry safety. By the end you will be able to:

Version stampEverything here is as of 2026-10-24 (Claude Code v2.1.310). Claude Code ships weekly, so features that need a minimum version say "requires v2.1.xxx+" next to them. Check claude --version before you rely on one.

Workflow Skills

A workflow skill is a procedure you invoke by name. Before Claude reads it, Claude Code renders it: it substitutes your arguments, runs any injected shell commands and pastes in their output. The skill arrives with the data it needs and a fixed sequence of steps. This topic covers the four levers that make a skill behave like a workflow rather than a tip sheet: frontmatter, arguments, dynamic context injection and bundled scripts.

Skills as Workflows

In core-2 you met skills as on-demand knowledge: a SKILL.md file whose description sits in context and whose body loads when it's relevant. A workflow skill uses the same file format for a different job. Its body is a procedure, with inputs, ordered steps, checks and an output contract, and its frontmatter controls who may start it, which tools it may use without asking, and where it runs. Custom commands were merged into skills in v2.1.3: .claude/commands/deploy.md and .claude/skills/deploy/SKILL.md both create /deploy and behave the same way, so everything below applies to both. The skill directory is the better home, because it can hold scripts and reference files.

Several of Claude Code's own features are workflow skills. /batch, /code-review, /simplify, /verify, /loop and /debug are bundled skills. They are "prompt-based: they give Claude detailed instructions and let it orchestrate the work using its tools", unlike built-in commands that execute fixed logic. When you write your own, you're using the same mechanism the product team uses.

What happens when you type /release-notes 2.4.0 v2.3.0

  1. Resolve. Claude Code finds the skill by name. Enterprise skills beat personal ones, personal beat project, and a skill beats a .claude/commands/ file with the same name.
  2. Render. It substitutes $ARGUMENTS, $0, named arguments and ${CLAUDE_*} variables, then runs every !`command` and replaces each one with its output. If any injected command fails, the whole invocation aborts.
  3. Deliver. The rendered body enters the conversation. With context: fork it becomes the prompt of a new subagent instead, which doesn't see your conversation.
  4. Grant. Tools listed in allowed-tools are pre-approved for this turn only. The grant clears when you send your next message.
  5. Persist. The content stays in context for the rest of the session and isn't re-read. After auto-compaction, the most recent invocation of each skill is re-attached, keeping its first 5,000 tokens, within a combined 25,000-token budget.
Rendering happens in Claude Code, before the model sees anything. That is why injected output is real data rather than a request to fetch it, and why a failed injected command means Claude never sees the skill at all. Hover a part of the file for when it is processed, switch between source and rendered, or drag explode. Paths and command output are illustrative.

The frontmatter that turns a skill into a workflow

FieldWhat it does for a workflowDefault
disable-model-invocationtrue: only you can start it, and its description leaves context. Use it for anything with side effects: deploys, commits, publishing.false
argument-hint, argumentsAutocomplete hint such as [version] [since-tag]; named positional arguments for $name.none
allowed-toolsPre-approves tools for the invoking turn. It does not restrict which tools exist; use disallowed-tools or deny rules for that.none
context: fork, agent, backgroundRun the skill in a fresh subagent (general-purpose by default, or Explore, Plan, a custom agent). Background by default; background: false waits for the result (requires v2.1.218+). It always waits in -p and SDK runs.inline
model, effortModel for the rest of the turn (not saved) and effort while the skill is active.session
hooks, paths, shellHooks registered on invocation for the rest of the session; globs that limit automatic activation; bash or powershell for injected commands.none / none / bash

.claude/skills/release-notes/SKILL.md

---
name: release-notes
description: Draft release notes for a version from merged commits. Use when the user asks for release notes or a changelog entry for a tag.
argument-hint: [version] [since-tag]
arguments: [version, since]
disable-model-invocation: true
allowed-tools: Bash(python3 ${CLAUDE_SKILL_DIR}/scripts/collect.py *)
---

# Release notes for $version

## Context (rendered before you read this)
- Branch: !`git branch --show-current`
- Recent history: !`git log --oneline -15`

## Steps
1. Run `python3 ${CLAUDE_SKILL_DIR}/scripts/collect.py --since $since --json` and read its JSON.
2. Group entries into Features, Fixes and Breaking changes. Use [style.md](style.md) for tone.
3. Write `docs/releases/$version.md`. Don't add entries the script didn't return.

## Done when
- Every bullet cites a commit hash from the script output.
- A "Breaking changes" section exists (write "None" if it's empty).
- You print the file path and the counts the script reported.
Change a field or a toggle: the generated file annotates each line with what it causes, and the line you changed last carries the highlight. The lint rules come from the skills docs: side-effecting workflows should set disable-model-invocation: true; allowed-tools pre-approves rather than restricts and isn't gated by workspace trust; the listing truncates description plus when_to_use at 1,536 characters; a forked skill doesn't see your conversation.
✗ A tip sheet that calls itself a workflow

"Release notes: look at recent commits, group them sensibly, write something nice." No inputs, no fixed data source, no definition of done. Claude can trigger it whenever "release" appears in conversation, and every run gathers different context.

✓ A workflow skill

Named inputs ($version, $since), context injected at render time, one script that produces the facts, steps in order, and a "Done when" list that requires evidence. disable-model-invocation: true because it writes a file.

PitfallsOver-triggering. A model-invocable workflow with a broad description starts when you didn't ask; set disable-model-invocation: true or tighten the description. Assuming allowed-tools sandboxes the skill. It only pre-approves; every other tool stays callable under your normal rules. Trusting repo skills blindly. "A skill can grant itself broad tool access, so review the allowed-tools of skills checked into a repository before you run Claude Code there", including in -p runs in untrusted folders. Forked edits and /rewind. A forked skill that runs in the background, the default, edits outside your checkpoints: rewinding restores only the files Claude had already edited in your conversation, so use git for the rest. A foreground fork (background: false) is restored as usual. Silent YAML errors. Malformed frontmatter loads the skill with no fields, so /name still works but matching breaks; run claude --debug. Keep SKILL.md under 500 lines and move reference material into supporting files.

Arguments

Arguments turn one skill into a family of runs. Whatever follows the skill name becomes the argument string. You can read it four ways:

PlaceholderExpands toWhen nothing matches
$ARGUMENTSThe full argument string, exactly as typedEmpty string
$ARGUMENTS[N], $NThe Nth argument, 0-based, split with shell-style quoting ("hello world" is one argument)Stays as literal text and doesn't count as receiving an argument
$nameThe argument at the position of name in the arguments frontmatter listExpands to an empty string, and does count
${CLAUDE_SESSION_ID}, ${CLAUDE_EFFORT}, ${CLAUDE_SKILL_DIR}, ${CLAUDE_PROJECT_DIR}Session ID, effort level, the skill's own directory, the project rootn/a; replaced after arguments are inserted

Four rules catch people out. First, if you pass arguments but no placeholder receives one, Claude Code appends ARGUMENTS: <your input> to the end of the content, so Claude still sees it. Second, argument values are inserted literally: /summarize "$ARGUMENTS from yesterday" doesn't expand the $ARGUMENTS inside the value. Third, to write a literal dollar before a digit, such as a price, escape it as \$1.00. Only a single backslash directly before the token escapes it, and a backslash never stops ${CLAUDE_*} substitution. Fourth, argument-hint is only an autocomplete hint. It doesn't validate anything, so a workflow that needs a version number should say what to do when $version is empty, or check it in a script.

Two more invocation details matter for workflows. You can stack skills at the terminal prompt: /write-tests /fix-issue 123 loads both and passes 123 to each. Claude Code expands the first skill plus up to five more, but stops at a forked skill such as /code-review, and claude -p and the SDK load only the first. And Claude can pass arguments too when it invokes a model-invocable skill itself, which is one more reason to describe the expected arguments in the body.

A faithful toy of the documented substitution rules: shell-style splitting, 0-based indexes, literal unmatched indexes, empty unmatched names, the ARGUMENTS: fallback, single-backslash escapes, and ${CLAUDE_*} replaced after arguments are inserted. Paths and IDs are illustrative. In what Claude receives, an underline marks an argument (its index raised beside it), a dashed box marks text left literal, and a dotted underline marks a ${CLAUDE_*} value; the resolution list repeats each mark with its reason.
Permission rules for skillsSkills are a tool (Skill) with rule syntax Skill(name) for an exact match and Skill(name *) for any arguments. A deny rule Skill(deploy *) keeps Claude from starting /deploy on its own, even if someone removes disable-model-invocation from the file.

Dynamic Context Injection

Dynamic context injection runs shell commands while Claude Code renders the skill and pastes their output in place. The inline form is !`git diff HEAD`. For several commands, open a fenced block with ```!. "The command output replaces the placeholder, so Claude receives actual data, not the command itself." Compare this with writing "first run git diff" in the body. Injection costs no tool-call round trip, Claude doesn't decide what to fetch, and every run starts from the same facts.

.claude/skills/pr-summary/SKILL.md

---
name: pr-summary
description: Summarize changes in a pull request
context: fork
agent: Explore
allowed-tools: Bash(gh *)
---

## Pull request context
- PR diff: !`gh pr diff`
- PR comments: !`gh pr view --comments`
- Changed files: !`gh pr diff --name-only`

## Environment
```!
node --version
git status --short
```

## Your task
Summarize this pull request for a reviewer: intent, risky files, missing tests.

That example comes from the docs, and it shows the usual pairing. Injection gathers the facts, context: fork with agent: Explore keeps the bulky diff out of your main context, and allowed-tools: Bash(gh *) pre-approves the injected gh calls.

How injected commands run

  • Syntax. The inline form is recognized only at the start of a line or right after whitespace. In KEY=!`cmd` the placeholder stays literal and nothing runs. Output is inserted as plain text and isn't re-scanned, so a command can't emit a placeholder for a later pass.
  • Execution. Commands run through the Bash tool (or PowerShell with shell: powershell), in the session's current working directory, which moves when Claude runs cd. Use ${CLAUDE_SKILL_DIR} or ${CLAUDE_PROJECT_DIR} in paths. Stderr is merged into stdout. Each command gets the Bash tool's default 2-minute timeout. A timed-out command that the Bash tool moves to the background doesn't abort the skill: the injected text names the background task instead. Output past the inline ceiling arrives as a file path plus a preview.
  • Failure. "A failed command aborts the entire skill invocation." Claude never sees the content; you see Shell command failed for pattern "..." with the stderr. Any non-zero exit counts, except exit 1 from search and comparison commands such as grep. Append || true to a check you expect to exit non-zero.
  • Permissions. Injected commands never prompt. A deny-rule match aborts with Shell command permission check failed for pattern "...". Outside auto mode, any result other than allow also aborts, including a rule that would normally ask, so pre-approve non-read-only commands with allowed-tools. In auto mode, a command that would need approval doesn't abort. The skill loads with an instruction for Claude to run the command first, and that call goes through the classifier. That auto-mode exception doesn't apply to a forked skill that sets agent, such as the pr-summary example above, where the invocation still aborts, so pre-approve its commands.
  • Policy. "disableSkillShellExecution": true replaces each command with [shell command execution disabled by policy] for user, project, plugin and additional-directory skills. Bundled and managed skills are unaffected, and the setting is most useful in managed settings. Skills synced from your claude.ai account never run injected commands on your machine (requires v2.1.228+).
Toy model of the documented render rules. Outputs are illustrative. Each injected line rides the belt through the permission check and the run station; one failure stops the belt and voids the page. Try Manual mode without the gh pre-approval, then switch to auto (it loads with an instruction instead), then turn on the forked-skill toggle (it aborts again). Remove || true from the tag lookup in a repository with no tags, and finally turn on the policy setting.
Deep dive: injection, caching, re-invocation and the untrusted-argument question

When the data is captured. Injection runs once, at render time. If the skill then edits files, the injected git status is stale for the rest of the turn. Tell the skill to re-check state with its own tool calls after it changes anything.

Re-invocation. Invoked content persists across turns and isn't re-read. "When Claude re-invokes a skill whose rendered content is identical to the copy already in context, Claude Code adds a short note that the skill is already loaded rather than a second copy of the content." If the injected output changed, for example a new diff, the new rendering enters context again. A skill that injects a large diff and runs every few minutes, such as under /loop, grows your context with every changed rendering. Fork it with context: fork so the bulk lands in a subagent.

Arguments inside injected commands. The docs specify that substitution runs once over the file and that output isn't re-scanned. They don't say whether argument placeholders inside an injected command line are expanded before it runs. Don't build shell command lines from arguments. Pass arguments to a script through Claude's own Bash call, where the permission system sees the final command, or validate them in the script.

Security posture. Injected commands run with your user permissions when someone types /skill-name, and a project skill comes from whoever last edited .claude/skills/. The sandbox, if it's on, covers these commands because they go through the Bash tool. For an organization, disableSkillShellExecution in managed settings is the switch that users can't override. Source: skills: Inject dynamic context.

Scripts in Skills

A skill directory can hold more than SKILL.md. Reference files are read only when the body points Claude to them. Scripts are "executed, not loaded", so a 400-line parser costs no context, only its output does. The split follows the code-versus-model rule from the next topic: let a script do the parts with one right answer (collect, parse, validate, render, count) and let Claude do the parts that need judgment (group, explain, choose).

.claude/skills/release-notes/
├── SKILL.md            # overview, steps, done-when (under 500 lines)
├── style.md            # tone and examples: loaded only when SKILL.md links to it
└── scripts/
    ├── collect.py      # git log + PR titles -> JSON; exits 2 on a bad tag
    └── render.py       # JSON -> Markdown skeleton; deterministic

The key variable is ${CLAUDE_SKILL_DIR}, the directory that holds SKILL.md. For plugin skills it's the skill's subdirectory, not the plugin root. Claude Code substitutes it in two places, the body and Bash rules in allowed-tools, so one variable gives you a stable path and a matching pre-approval:

~/.claude/skills/render-chart/SKILL.md

---
name: render-chart
description: Render a chart from a CSV file
allowed-tools: Bash(${CLAUDE_SKILL_DIR}/scripts/render.sh *)
---

Run `${CLAUDE_SKILL_DIR}/scripts/render.sh <csv-file>` to render the chart.

Design the script as a contract. It should read flags, not ambient state, and write machine-readable output (JSON on stdout) with human-readable errors on stderr. Exit codes should mean something: 0 for success, 1 for "found problems", 2 for bad input. Keep output short, because anything past the Bash tool's inline ceiling arrives as a file path plus a preview. The docs' "Generate visual output" pattern takes this further: a bundled Python script writes an interactive HTML file, such as a codebase explorer, and opens it in the browser. Claude orchestrates the run and never holds the HTML in context.

#!/usr/bin/env python3
"""collect.py --since TAG [--json]: list commits since TAG as JSON. Exit 2 on a bad tag."""
import argparse, json, subprocess, sys

ap = argparse.ArgumentParser()
ap.add_argument("--since", required=True)
ap.add_argument("--json", action="store_true")
a = ap.parse_args()
r = subprocess.run(["git", "log", "--format=%h%x09%s", f"{a.since}..HEAD"], capture_output=True, text=True)
if r.returncode != 0:
    print(f"unknown tag {a.since!r}: {r.stderr.strip()}", file=sys.stderr)
    sys.exit(2)
rows = [dict(zip(("hash", "subject"), line.split("\t", 1))) for line in r.stdout.splitlines() if line]
print(json.dumps({"since": a.since, "count": len(rows), "commits": rows}) if a.json else "\n".join(x["subject"] for x in rows))
PitfallsRelative paths. scripts/collect.py breaks as soon as Claude has cd'd elsewhere; always use ${CLAUDE_SKILL_DIR}. Broad pre-approvals. allowed-tools: Bash(python3 *) pre-approves every Python one-liner for that turn; scope the rule to the script path. Noisy output. A script that prints 5,000 lines of progress wastes context and may arrive as a file; print a summary and write details to a file the skill can point to. Hidden dependencies. A script that needs pip install fails on a teammate's machine; stick to the standard library or document the setup in the skill. Windows. With shell: bash and no Git Bash, the invocation fails before any command runs.

What you build: a /release-notes [since-ref] [audience] skill in core-5/workflow_skill/kit/. It has named arguments, an inline !`…` and a fenced ```! injection, a bundled script reached through ${CLAUDE_SKILL_DIR}, a linked style guide and disable-model-invocation: true. The validator checks every frontmatter field, runs each injected command through the course's permission engine ("runs" or "would abort"), renders the skill for real in a temp repo with a tag and seven commits, and runs the script's tests. It's offline; it needs git. The kit's skill is a print-only sibling of this article's example, not the same file. It shares the /release-notes name but takes arguments: [since, audience] and builds on scripts/changes.py, and it prints the notes instead of writing docs/releases/$version.md. Install one or the other, because two skills with the same name in one repo collide.

cd labs && python3 core-5/workflow_skill.py
python3 core-5/workflow_skill.py --deny 'Bash(python3 *)'          # a deny rule aborts the invocation
python3 core-5/workflow_skill.py --mode auto --strip-allowed-tools
cp -r core-5/workflow_skill/kit/.claude <your-repo>/              # then: /release-notes v1.2.0 developers

What to observe: the rendered prompt Claude receives, with real git output in place of each ! line. Then the same render with allowed-tools removed fails with Shell command permission check failed for pattern …, which is exactly the pre-approval rule from this article.

Open the lab walkthrough

Exercise: ship a /release-notes skill in your own repo

Create .claude/skills/release-notes/ with the SKILL.md above, adapted to your repo, plus a collect.py that prints JSON. Then: (1) run /release-notes 9.9.9 does-not-exist and confirm the script's exit 2 reaches Claude as an error it reports, not a guess; (2) add an injected !`git describe --tags --abbrev=0` line in a repo or branch with no tags and watch the invocation abort; (3) fix it with || true; (4) check /context before and after to see what the rendered skill costs.

Show a solution

(1) Because collect.py exits 2 with a message on stderr, Claude's Bash call returns the error. The "Don't add entries the script didn't return" line in the body keeps it from improvising. (2) git describe exits 128 with "fatal: No names found", so you see Shell command failed for pattern "git describe --tags --abbrev=0" and Claude never reads the skill. (3) With || true the line renders as empty output and the run continues. Better still, have the body say "if no tag is shown, ask for $since". (4) /context shows the rendered skill in the messages bucket, and its size depends mostly on the injected git log. Cap it with -15 or move it into the script.

Key takeaways

  • A workflow skill is a procedure with inputs, steps and a definition of done. Its frontmatter decides who can start it (disable-model-invocation), what it may run without asking (allowed-tools, turn-scoped and not restrictive) and where it runs (context: fork).
  • Arguments follow precise rules: 0-based indexes, unmatched indexes stay literal, unmatched names go empty, values are inserted literally, and the ARGUMENTS: line is appended when no placeholder receives anything.
  • !`cmd` runs at render time. A failure or a non-allowed permission result aborts the whole invocation (outside auto mode, and in auto mode too for a forked skill that sets agent), and disableSkillShellExecution turns it off by policy.
  • Bundle scripts for deterministic work and call them through ${CLAUDE_SKILL_DIR} in both the body and allowed-tools.

Deterministic Steps

The model is the right engine for judgment and the wrong one for steps that must happen the same way every time. Claude Code gives you three places to put those steps: hooks fire on lifecycle events, scripts run inside skills and workflows, and workflow scripts hold the control flow of a large fan-out in code. This topic covers how to split a process between code and model, and how to run that split at scale.

Hooks for Formatting and Linting

Writing "always run Prettier after editing" in CLAUDE.md works most of the time, which isn't the same as every time. CLAUDE.md is delivered as context, "not enforced configuration". A PostToolUse hook is enforced. The best-practices guide's own formatter example makes the point: "whether Claude remembers the rule no longer matters, because Claude isn't the one running it." Formatting and linting are the classic first hooks because they have exactly one right answer and cost nothing to get right.

The docs' recipe is one line in .claude/settings.json. It runs after every Edit or Write, pulls the absolute file path out of the hook's JSON input with jq, and formats that file:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }
        ]
      }
    ]
  }
}

Formatting needs no feedback, since the file is simply fixed. Linting does, because Claude has to change code. A PostToolUse hook can't undo the edit ("the tool has already executed"), but it can put a message next to the tool result. You can exit with code 2, which shows stderr to Claude. Or you can print JSON with "decision": "block" and a reason, which "adds the reason next to the tool result" while Claude still sees the original output. The JSON form is easier to keep structured:

#!/usr/bin/env bash
# .claude/hooks/format-and-lint.sh · PostToolUse (Edit|Write): format the edited file, lint it, feed problems back.
set -uo pipefail
input=$(cat)
file=$(jq -r '.tool_input.file_path // empty' <<<"$input")
[[ -z "$file" || ! -f "$file" ]] && exit 0
case "$file" in *.ts|*.tsx|*.js|*.jsx) ;; *) exit 0 ;; esac   # only files these tools understand
# Use the edited file's own checkout: in a worktree, $CLAUDE_PROJECT_DIR still points at the main one.
root=$(git -C "$(dirname "$file")" rev-parse --show-toplevel 2>/dev/null || jq -r '.cwd // empty' <<<"$input")
[ -n "$root" ] && cd "$root" || exit 0              # no root found: fail open
bin=node_modules/.bin

[ -x "$bin/prettier" ] && "$bin/prettier" --write "$file" >/dev/null 2>&1   # silent; no Prettier = skip

[ -x "$bin/eslint" ] || exit 0                         # no ESLint installed: fail open
out=$("$bin/eslint" "$file" 2>&1); rc=$?            # default (stylish) formatter
if [ "$rc" -eq 1 ]; then                               # 1 = lint errors; 2 = config or internal error
  jq -n --arg r "ESLint problems in $file (fix before continuing):
$(head -c 3000 <<<"$out")" '{decision: "block", reason: $r}'
fi
exit 0                                                 # clean or broken config: don't block the session
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-and-lint.sh",
            "timeout": 60,
            "statusMessage": "Formatting and linting"
          }
        ]
      }
    ]
  }
}
chmod +x .claude/hooks/format-and-lint.sh
echo '{"hook_event_name":"PostToolUse","tool_name":"Edit","tool_input":{"file_path":"'"$PWD"'/src/app.ts"}}' \
  | CLAUDE_PROJECT_DIR="$PWD" .claude/hooks/format-and-lint.sh; echo "exit=$?"
# then, in a session: /hooks shows the hook and its source; claude --debug logs each run

      
One Edit call drawn as a U: down from Claude through PreToolUse and the permission check to the write, then back up through PostToolUse, where the format-and-lint hook loops out and returns its decision before Claude reads. Click or focus a stop, or play the call, to see the JSON at that moment. The event order and JSON fields follow the hooks reference. File names and lint output are illustrative.

Design rules for format and lint hooks

  • Matchers are exact or regex. Edit|Write contains only letters and |, so it's an exact list. Edit.* is an unanchored regex that also matches NotebookEdit. Matchers are case-sensitive.
  • Bash edits don't fire it. "Claude Code doesn't run a PostToolUse hook matching Edit|Write when a Bash command or a process outside Claude Code rewrites the same file." The hooks guide gives three ways to cover that. You can also match Bash|PowerShell and have the script list changed files with git status --porcelain. You can add a Stop hook that scans the tree once per turn. Or you can use a FileChanged hook, which fires whatever wrote the file. Its matcher registers each |-separated segment as a literal filename in the working directory, so a file like src/api/client.ts needs absolute paths returned as watchPaths from a SessionStart or CwdChanged hook; the matcher then filters by basename. In auto mode, or with bashEditDiffEnabled, a Bash PostToolUse hook also receives the changed files in tool_response.bashEditDiff (requires v2.1.269+).
  • Keep it fast and per file. The hook runs on every edit. Format and lint one file. Leave the full test suite for CI, a Stop hook (next topic) or an "async": true hook, which can't block and whose output arrives on the next turn.
  • Fail open on tool trouble. If the formatter or linter is missing, or ESLint exits 2 (a configuration or internal error), exit 0 and fix the setup outside the session. Only ESLint's exit 1 ("at least one linting error") becomes a reason. ESLint v9 removed formatters such as unix from core, so keep the default formatter or install one explicitly. Any exit code other than 0 or 2 is a non-blocking error that shows up as noise. Default timeouts are 600 seconds for command hooks; set a smaller timeout.
  • Resolve tools from the code being edited. ${CLAUDE_PROJECT_DIR} stays at the root where the session started, even after Claude enters a worktree, while the hook input's cwd follows Claude. That's why the script finds node_modules/.bin and the lint config via the git toplevel of the edited file, falling back to cwd, rather than cd "$CLAUDE_PROJECT_DIR". Use ${CLAUDE_PROJECT_DIR} to locate the hook script itself, not the code it checks.
  • Prefer exec form for paths. The hooks reference also accepts "command": "python3", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/format_on_edit.py"] (requires v2.1.139+), which avoids shell-quoting a path placeholder. The lab kit uses it; the shell form above works on older versions.
  • Know what it runs as. "Command hooks execute shell commands with your full user permissions", outside the sandbox. A hook committed to .claude/settings.json is code your teammates run.

What you build: a PostToolUse hook (matcher Edit|Write, exec form with ${CLAUDE_PROJECT_DIR}) that formats the edited file and tells Claude through additionalContext when the file changed under it. It reports a file that no longer parses with decision: "block" + reason. The lab validates the settings entry, prints how each matcher is read, and runs 10 cases through common/hooks.py: 8 PostToolUse payloads, a Read payload (the wrong tool for this hook) and non-JSON stdin. Offline, standard library only.

cd labs && python3 core-5/format_hook.py
python3 core-5/format_hook.py --print-snippet                     # the settings block to merge
mkdir -p <repo>/.claude && cp -Rn core-5/format_hook/kit/.claude/. <repo>/.claude/

What to observe: the matcher table (Edit|Write is exact; Edit.* also catches NotebookEdit). A clean file stays silent. The syntax-error case returns decision: block, which blocks nothing; it puts the reason in front of Claude. Non-JSON stdin exits 1 as a non-blocking error, so the hook fails open.

Open the lab walkthrough

Code Versus Model Decisions

Every step in a workflow sits somewhere between two poles. At one end are steps with a crisp correct answer that must happen every time: format, block a path, count, compare, run the tests. At the other are steps that need judgment: is this design sound, which failures share a cause, what should this message say. The rule: if it must happen, or there is one right answer, put it in code. If it needs judgment, give it to the model, and enforce when the judgment happens with a hook.

Click a station to swap it between a gear (a script or a hook) and a lens (the model), then run it ten times; the ten outputs land as small multiples. Steps with one right answer vary when the model does them and never when code does, while judgment steps should vary. Error rates are illustrative (a toy model); the principle is the docs': hooks are deterministic, CLAUDE.md instructions advisory.

Claude Code gives you a ladder of mechanisms, from advisory to enforced at the OS level:

MechanismWho enforces itUse it forBreaks when
CLAUDE.md or .claude/rules/Nobody: it's contextConventions and taste: "prefer composition", naming, architecture notesThe rule must hold every time. Compaction can also drop path-scoped rules until they reload
Skill stepsNobody: a procedure Claude followsOrdered work with judgment in between: release, triage, migrationA step is skipped or reordered under pressure
Prompt or agent hookClaude Code decides when; a model decides whetherJudgment at a fixed point: "are all requested tasks complete?" at StopThe check is really deterministic (slower, costs tokens, can be wrong)
Command hook or scriptClaude Code runs it; the exit code decidesFormat, lint, compare, count, re-inject context after compactionIt's slow, flaky, or tries to encode judgment in regexes
Permission ruleClaude Code, before the tool runs; "Deny rules block in every mode"Never read .env, never fetch outside a domain, always ask before git pushYou treat a Bash deny as a boundary: Bash(rm *) doesn't stop /bin/rm or bash -c
SandboxThe operating systemWhat shell commands and their children can read, write and reachYou assume it covers file tools, MCP or hooks (it doesn't)

Two common mistakes run in opposite directions. The first is putting must-rules in prose: "NEVER commit secrets" in CLAUDE.md is a hope, while Read(./.env) in permissions.deny is a fact. The second is putting judgment in code: a regex hook that tries to decide whether a function is "too complex" will be wrong in both directions, while a prompt hook or a review subagent can weigh context. Prompt hooks ("type": "prompt") send the hook input to a model and expect {"ok": true} or {"ok": false, "reason": "..."}. Agent hooks ("type": "agent", experimental) can also read files and run commands, for up to 50 turns.

Choose a mechanism for each requirement, then check. Several items have a best answer and an acceptable one. The feedback explains the trade-off, following the docs' guidance that must-happen rules belong in hooks or permissions, not prose.
Deep dive: hook precedence, permission interplay and why a timeout isn't a gate

Hooks and rules are separate layers. "PreToolUse hook decisions don't bypass permission rules": a hook's allow can't override a deny rule, but a hook's deny "blocks the tool even in bypassPermissions mode". A hook that exits 2 "stops the tool call before permission rules are evaluated". When several PreToolUse hooks disagree, "precedence is deny > defer > ask > allow", and one hook's deny doesn't stop its siblings from running. All additionalContext strings are kept. With several updatedInputs, Claude Code doesn't merge them or guarantee which one the tool runs with.

Fail-open by default. A settings hook that times out, can't start or prints invalid JSON is a non-blocking error unless it sets "onFailure": "block" (requires v2.1.295+, on command and http hooks). So "don't count on a stalled hook to act as a gate". For a hard allow or deny, use permission rules. The SDK documents callback-hook timeouts differently, so don't use timeouts as policy anywhere.

Mods. A mod that handles tool.check answers after permission rules and PreToolUse hooks have decided. With managed settings on the machine, or a Team or Enterprise /login as the session's credential, deny-rule refusals and hook blocks stay in place. With neither, "the mod can approve a call that a deny rule refuses or a PreToolUse hook blocked", and an API-key or CLAUDE_CODE_OAUTH_TOKEN session counts as neither. So install only mods you trust, and rely on managed settings (or a Team/Enterprise login) when hooks and deny rules must hold. Sources: hooks reference, hooks guide, permissions: precedence among rules, hooks, and mods.

Batch and Workflow Runs

Some tasks are too big for one conversation: migrate 300 components, audit every route handler, research a question across 40 sources. Claude Code has three ways to run them, and they differ in who holds the plan.

/batch <instruction> is a bundled skill. It "researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan." Once you approve, it "spawns one background subagent per unit in an isolated worktree. Each subagent implements its unit, runs tests, and publishes its change." It needs a git repository or a WorktreeCreate hook; outside git it requires v2.1.281+. Use it when the units are independent and each one is a reviewable change: /batch migrate src/ from JavaScript to TypeScript.

Dynamic workflows (v2.1.154+) go further. Claude writes a JavaScript script that orchestrates subagents, and a runtime runs it in the background while your session stays responsive. Ask in plain words ("use a workflow to…") or include the keyword ultracode; press Option+W or Alt+W to dismiss the highlight if you didn't mean it. /effort ultracode makes Claude plan a workflow for every substantive task in the session, which uses more tokens and skips the size warning. The keyword only works in prompts you type, not in -p, scheduled tasks or relayed PR comments. Workflows are available on all paid plans, with API access, and on Bedrock, Agent Platform and Foundry. On Pro, turn them on in /config.

ultracode: audit every API endpoint under src/routes/ for missing auth checks

use a workflow to run npx tsc --noEmit and keep fixing the reported errors until the
type check passes or two rounds in a row make no progress

Before a run starts, the CLI shows the planned phases with Yes, run it, Yes, and don't ask again (for named workflows), View raw script and No. In auto mode you're asked only on the first launch; in Manual and acceptEdits, every run. /workflows opens the progress view, with p to pause, x to stop, r to restart an agent and s to save the script as a command. Saved scripts live in .claude/workflows/ (shared with the repo) or ~/.claude/workflows/ (personal), run as /<name>, and read invocation input from a global args. The bundled /deep-research <question> is a workflow too.

A claude -p loop is the third option: your own shell script calls headless Claude once per item, as covered in core-4. The docs' example pairs --allowedTools "Edit,Bash(git commit *)" with --permission-mode dontAsk, so anything else that would need approval is denied. Test on two or three items, refine the prompt, then run the rest.

/batchDynamic workflowclaude -p loopSkill + subagents
Who holds the planClaude's decomposition, approved by youA script; the runtime executes itYour shell scriptClaude, turn by turn
Intermediate resultsEach unit's branch and worktreeScript variables, not Claude's contextFiles and stdout you captureClaude's context window
Scale5–30 unitsDozens to hundreds of agents (16 concurrent by default, 1,000 per run)Any; you parallelizeA few delegated tasks per turn
InterruptionUnits run as background subagents; your session stays freePause and resume in the same sessionYour script's problemRestarts the turn
Best forOne big change split into reviewable PRsAudits, cross-checked research, fix-until-green loopsCI and pipelines, one prompt per fileSmall fan-outs with judgment between steps
Cost and permissions"A single run can use meaningfully more tokens than working through the same task in conversation." The task panel shows a Large workflow warning when a run schedules more than 25 agents or its projected total passes 1.5 million tokens. The warning is advisory and doesn't pause the run. Run on a slice first, for example one directory, and set the workflowSizeGuideline setting (small <5, medium <10, large <50 agents; requires v2.1.219+) to steer how big Claude makes its scripts. In claude -p and the SDK no approval prompt appears: add Workflow or Workflow(<name>) to your allow rules, or the launch goes through normal permission evaluation and may be denied. Turn workflows off with "disableWorkflows": true or CLAUDE_CODE_DISABLE_WORKFLOWS=1.

Graphs of Steps

A workflow script is a graph you can read. Each agent() call is a node that spawns one subagent. pipeline(items, fn) fans out one node per item. parallel([...]) runs a set of nodes together and waits for all of them. phase(title) groups the nodes that follow under a heading in the progress view. Edges are ordinary JavaScript data flow: one stage's return value is the next stage's input. A schema on an agent() call makes that subagent return JSON of a given shape, which is how you give a graph typed edges.

.claude/workflows/audit-routes.js (saved with s in /workflows)

export const meta = {
  name: 'audit-routes',
  description: 'Audit route handlers for missing auth checks, verify each finding, rank the survivors',
}

phase('Discover')
const found = await agent(`List every .ts file under ${args?.dir ?? 'src/routes/'}.`, {
  schema: { type: 'object', required: ['files'], properties: { files: { type: 'array', items: { type: 'string' } } } },
})
if (!found) return 'Discover was stopped or failed; nothing was audited.'   // agent() resolves to null on stop or API error

phase('Audit')
const audits = await pipeline(found.files, (file) =>
  agent(`Audit ${file} for missing authentication checks. Return findings with line numbers, or an empty list.`, {
    label: file,
    schema: { type: 'object', required: ['findings'], properties: { findings: { type: 'array', items: { type: 'object' } } } },
  }),
)
const findings = audits.filter(Boolean).flatMap((a) => a.findings)

phase('Verify')
const checks = await pipeline(findings, (f) =>
  agent(`Try to refute this finding by reading the code and its callers: ${JSON.stringify(f)}`, {
    schema: {
      type: 'object', required: ['verdict', 'evidence'],
      properties: { verdict: { type: 'string', enum: ['CONFIRMED', 'REFUTED'] }, evidence: { type: 'string' } },
    },
  }),
)
const confirmed = findings.filter((f, i) => checks[i]?.verdict === 'CONFIRMED')   // the filter is code, not judgment

phase('Report')
return await agent(`Rank and deduplicate these confirmed findings into one report:\n${JSON.stringify(confirmed)}`)
Intermediate results stay in script variables, so Claude's context receives only the final report. The verify stage is the "repeatable quality pattern" the docs describe: independent agents try to refute each finding before it's reported. Hover a node for its line of the script; the counts n and k depend on the files.

The runtime's rules (they shape how you design the graph)

  • No mid-run user input. A run pauses only for agent permission prompts and usage-limit waits. For sign-off between stages, run each stage as its own workflow.
  • The script coordinates; agents act. The script has no direct filesystem or shell access, and import() fails before the run starts. Put library work inside an agent's task.
  • Limits. Up to 16 concurrent agents by default, fewer when Claude Code has fewer CPUs available (CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS, 1–256, requires v2.1.269+), at most 4,096 items per parallel() or pipeline() call, and 1,000 agents per run.
  • Determinism for replay. Date.now(), Math.random() and a no-argument new Date() throw inside the script, so a relaunched run repeats the same agent() calls. Pass a timestamp in through args.
  • Nulls and failures. An agent() call you stop, or one that hits an unrecoverable API error, resolves to null, even when awaited directly, so guard before reading fields (the if (!found) line above). A call that fails behaves differently. That happens when an agent stalls on all six attempts, or when output still misses its schema after five tries. Inside parallel() or pipeline() the failure becomes null in the results and the run carries on, which is why results get filtered. Awaited directly, it ends the run. For a slow, silent agent, pass stallMs on its agent() call.
  • Isolation for edits. For fan-outs that change files, ask for each item to be processed "in an isolated copy so edits don't conflict", as the docs' migration example does (workflows).
  • Schemas are checked. A self-contradictory schema fails before the subagent starts. Output that still fails validation after five attempts fails the call (MAX_STRUCTURED_OUTPUT_RETRIES).
Toy model. Each column is one wave of agents, no taller than the concurrency cap, and the two rulers mark the documented thresholds. Agent counts and caps follow the workflows docs: 16 concurrent by default, 4,096 items per call, 1,000 agents per run, and the Large workflow warning above 25 agents, above a size guideline you chose, or above 1.5M projected tokens. Minutes and tokens per agent are illustrative inputs, not measurements.
The replay rule from the docs: agents replay in start order. Completed agents return saved results until the first agent whose prompt differs or that failed; that agent and every agent that started after it run again, even ones that completed. On the tape, the playhead replays saved frames up to that splice; the frames after it are re-recorded. Agent names are illustrative.
Deep dive: caching across a fan-out, model choice per stage, and the classifier

Shared prefixes. Two agents with the same model, effort, agent type, tools, output schema and working directory build the same tools-and-system-prompt prefix. A sibling that starts after the first agent's response begins reads its cache. Claude Code holds matching agents for up to CLAUDE_CODE_WORKFLOW_PREFIX_STAGGER_MS (5,000 ms by default) so they read the shared prefix instead of each writing it. Workflow agents fall outside the main conversation's TTL bucket, so their cache lasts five minutes by default, even on a subscription. subagentPromptCacheTtl: "1h" extends it, and the API bills 1-hour writes at a higher rate. Design implication: keep the per-item part of each prompt at the end and the shared instructions identical.

Models per stage. Workflow agents pick models in the same order as subagents. A model the script names for a stage counts as the per-invocation choice; otherwise the agent runs on your session model. A discover stage can run on a cheaper model while the audit stage uses the strongest. An org availableModels allowlist substitutes a blocked model.

Auto mode. "The prompt your script passes to agent() doesn't count as a request from you when the classifier reviews that subagent's actions, because Claude Code marks it as text the script computed." A script can't launder intent through a generated prompt.

Resumes across sessions. Backgrounding the session, or exiting with "Move to background and exit" when agent view is on, carries the run over. claude --resume can replay saved results when you ask Claude to relaunch. A fresh session starts the workflow over. Source: Orchestrate subagents at scale with dynamic workflows; SDK version in cookbook: dynamic workflows.

Exercise: one hook, one workflow

(1) Install the format-and-lint hook in a repo with Prettier and ESLint. Pipe a fake payload through it to test, then ask Claude to add a deliberately unused variable and watch the reason come back. (2) In the same repo, ask: "use a workflow to audit every file under one small directory for X, and adversarially verify each finding." Before approving, choose View raw script and identify the phases. After the run, open /workflows, press s, save it to .claude/workflows/, and rerun it on another directory by passing the path as input.

Show a solution

(1) The pipe test should print nothing for a clean file and a {"decision":"block","reason":"ESLint problems…"} object for a file with an unused variable. In a session, Claude's next step reads the reason next to the Edit result and removes the variable. If nothing happens, check /hooks (is it listed, from which source?), that the script is executable, and claude --debug for Hook output does not start with {, which usually means shell-profile noise. (2) The raw script should show phase() calls matching the plan. If Claude hard-coded the directory, edit the saved .js to read args (as in the example above), run /reload-skills, and invoke /audit-routes with the new path in your prompt. Note the per-agent token figures in /workflows before you scale up.

Key takeaways

  • Must-happen steps go in hooks, scripts or permission rules. Judgment goes to the model, and a prompt or agent hook can fix when that judgment happens.
  • Format and lint with a PostToolUse Edit|Write hook: fix silently, and report lint problems with decision: "block" + reason. For files rewritten by Bash, also match Bash|PowerShell and check git status --porcelain, or watch them with FileChanged and watchPaths.
  • /batch splits one change into 5–30 worktree-isolated units. Dynamic workflows run a script of agent(), pipeline(), parallel() and phase() with hard caps and a deterministic replay rule.
  • Watch the Large workflow warning, start on a slice, and pre-approve Workflow for headless runs.

Quality

The cheapest quality gain in agentic work is a check Claude can run and a demand for evidence. The docs' best practices put it as "Give Claude something it can run that comes back pass or fail", and Boris Cherny of the Claude Code team estimates that verification makes the result "two to three times better" (how the Claude Code team does code review). This topic builds the pieces: checklists Claude can satisfy, review loops that converge, verifiers with fresh context, and quality markers a machine can check.

Checklists

A checklist is your definition of done, written so that an agent can satisfy it and a checker can confirm it. Classify each item by how it will be confirmed:

  • Command items have an exit code: tests pass, tsc --noEmit is clean, lint is clean. A hook or script checks them; the model shouldn't be trusted to.
  • Evidence items need an artifact Claude has to show: the test output, the command it ran and what it returned, a screenshot path, the file it wrote. The docs: "ask Claude for evidence: the command it ran and its output, or the screenshot."
  • Judgment items need a reviewer: every requirement in PLAN.md is implemented, nothing outside the task's scope changed, the error copy reads well. A fresh-context subagent or a prompt hook checks these.

Where the checklist lives depends on its scope. A skill's "Done when" section holds a workflow's own criteria. A short "Definition of done" in CLAUDE.md holds repo-wide habits; keep it to a few lines, because CLAUDE.md loads into every session and the target is under 200 lines in total. A /goal condition holds a one-off objective. "After each turn, a model checks whether the condition holds", and the goal clears when it's met or judged impossible (requires v2.1.139+). A Stop hook holds rules for every session in a scope. A PR template holds what humans review.

/goal every test in tests/api passes, `npx tsc --noEmit` exits 0, and CHANGELOG.md has an entry for this change
Tick the items you want in your definition of done. Each item lands on the axis where it can actually be confirmed, from a script to a reviewer, and items nobody can confirm fall off the end. Hover a marker for its mechanism. Vague items are flagged, following Anthropic's Opus 5.5 prompting guide: say what "done" looks like, and delete "think carefully" lines.
PitfallsCheckbox theater: Claude ticks "tests pass" without running them, so require the output, not the tick. The 30-item list: long generic lists get skimmed; keep five to eight items, and put the rest in hooks. Rituals: Anthropic's Opus 5.5 prompting guide says "Delete 'think carefully' lines. Opus 5.5 already thinks before every reply", and to "say what 'done' looks like and when you want it to stop and ask". That advice is model-specific, so re-check it when you change models. Forbidding without an alternative: "don't mock the database" works better as "use the test container from scripts/db.sh".

Review Loops

A writer/reviewer loop separates making from judging. The docs recommend it because a fresh reviewer "hasn't seen your reasoning", and "A second session is also the easiest independent reviewer you can get." You can run it with two sessions (one writes the rate limiter, another reviews @src/middleware/rateLimiter.ts "without having watched it being written", and you paste the findings back) or inside one session with a subagent reviewer. Claude Code ships three reviewers as bundled commands:

CommandLooks forHow it runs
/code-review [low|medium|high|xhigh|max|ultra] [--fix] [--comment] [target]Correctness bugs in the branch diff, a PR, a path or a range; cleanups too, depending on model and effortA background subagent with its own context; --fix applies findings (a background run's edits to files Claude hadn't already edited aren't restored by /rewind, so use git to revert); ultra runs a multi-agent cloud review. /review is an alias
/simplify [target]Reuse, simplification, efficiency and abstraction level. "The review doesn't look for correctness bugs"Four review agents in parallel; applies the fixes
/security-reviewInjection, auth issues and data exposure in the diff between your branch and origin's default branchOn demand; needs an origin remote (see the Security topic)

To check the diff against your plan rather than for generic bugs, write the review prompt yourself, as the docs show: "use a subagent to review the rate limiter diff against SPEC.md, check every requirement is implemented and the listed edge cases have tests, report gaps that affect correctness and skip style"

The hard part is convergence. "A reviewer that's asked to find problems will always find something. If you fix every finding, you end up with extra abstraction layers and tests for cases that can't happen." Three controls keep a loop honest. Scope the criteria: report only gaps that affect correctness or the stated requirements, and skip style. Scope the input: review the diff, not the whole file, or the reviewer keeps finding problems in old code. Cap the rounds: when the Claude Code team wrote up its own review pipeline, one PR had gone through "more than fifty rounds of review", about 59% of the findings were in old code, and "after three rounds, the reviewer asks the author to step back".

Toy model with illustrative numbers. Each round the reviewer finds a share of the real defects (recall) and also raises nits and old-code findings at fixed rates. The writer fixes what it's told, and every fixed nit has a small chance of adding complexity or a new defect. The controls mirror the docs' advice: correctness-only criteria, diff-scoped input and a round cap, drawn as the hatched wall. Hover or focus a round on the chart for its values.
Deep dive: why separate evaluators work, and how to make one skeptical

Anthropic's harness-design post reports that self-evaluating agents "tend to respond by confidently praising the work", and that "tuning a standalone evaluator to be skeptical turns out to be far more tractable than making a generator critical of its own work".

The mechanics behind this are context and incentives. The writer's context holds every rationalization it made along the way; a reviewer that sees only the diff and the criteria can't inherit them. Two prompt moves make reviewers useful rather than noisy. First, ask for refutation with evidence (the file and line, and the input that breaks it), so a finding the reviewer can't support doesn't survive. Second, rank by impact and stop at a fixed count, so nits sink below the cut. The workflow version is the verify stage in the previous topic: independent agents try to refute each finding before it's reported.

External reviewers, whether CI bots or PR comments, deserve the same skepticism. One community practitioner (Jesse Vincent, community post) has Claude judge pasted review comments by asking "should we hire this reviewer", because agents are "quite credulous". The evaluator-optimizer cookbook shows the bare loop on the Client SDK.

Sources: best practices: adversarial review, harness design for long-running apps, how the Claude Code team does code review.

Verification Subagents

A verification subagent is a reviewer with a narrow job: decide whether finished work meets its criteria, and report rather than fix. It works because a fresh subagent "never saw your conversation" and "isn't swayed by the reasoning that produced the code" (the best-practices page, on /code-review). Define it once in .claude/agents/ and every session in the repo can use it:

.claude/agents/verifier.md

---
name: verifier
description: Independently verifies a finished change against its plan and acceptance criteria. Use after implementation and before reporting a task as done.
tools: Read, Bash
model: opus
---
You verify. You never edit files and never fix problems.

Inputs: the task's acceptance criteria (or PLAN.md) and the diff (`git diff main...HEAD`).
For each criterion:
1. Find the code that satisfies it. Cite file:line.
2. Run the narrowest command that proves it (a single test, a type check, a curl against the dev server) and quote the output.
3. Mark it PASS, FAIL (with the failing input) or UNVERIFIED (say what you couldn't run).

Then list changes outside the task's scope. Report gaps that affect correctness or the stated
requirements; put style preferences under "Optional".

Then ask for it by name: "Use the verifier subagent to check this branch against PLAN.md." Three design choices matter. Read plus Bash lets it run tests and search with grep and find. On macOS, Linux and WSL the Glob and Grep tools are absent by default, and listing them next to Bash doesn't bring them back. Bash can still write files, so the prompt's "never edit" matters. For a stricter, judge-only verifier, use tools: Read, Grep, Glob: with Bash left out, a subagent that lists Glob or Grep gets them back, and it can only judge evidence the implementer collected. Evidence in, not claims: give it the diff and the criteria, never the implementer's summary of what it did. A strong model for judgment, while mechanical lookups can run cheaper. Subagent permissionMode is ignored in auto mode, so don't rely on it as the boundary.

Verifying against the running app: /verify, /run, /run-skill-generator

Tests can pass while the feature is broken. One rule first: since v2.1.215 the bundled /verify "runs only when you invoke it", so a CLAUDE.md line telling Claude to run it does nothing. A project skill named verify, including the one /verify records, stays model-invocable. The bundled /verify skill confirms a change "by building your project's app, running it, and observing the result, rather than relying on tests or type checks" (commands). /run launches and drives the app, and /run-skill-generator records how to build and launch your project as a committed skill at .claude/skills/run-<name>/. When /verify has to work out the steps itself, it writes them to .claude/skills/verify/SKILL.md, and at the repo root that recorded skill replaces the bundled one. From v2.1.286, if a session starts with a skill named verify or simplify in place (yours, not the bundled one), Claude Code's commit instructions tell Claude to run it right before each commit, except for docs-only or test-only changes.

Each gate is independent of the one before it. The Stop hook and /goal decide whether Claude is sent back to keep working (the dashed loop); the verifier and /code-review decide whether the work is right (the solid loops). Neither replaces CI or the human owner as the gate that holds. Hover a station for what it checks.

For unattended runs, an agent hook on Stop sends Claude back to work while a check fails, in one config block. Agent hooks are experimental, with a 60-second default timeout and up to 50 tool-use turns. The docs' example verifies the test suite:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "agent",
            "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",
            "timeout": 120
          }
        ]
      }
    ]
  }
}
A Stop hook is a nudge, not a gateThree documented limits keep it from guaranteeing anything. It fails open: a Stop hook that times out or crashes lets the turn end, and "onFailure": "block" "has no effect" on Stop, SubagentStop, TaskCompleted and TeammateIdle hooks. Size timeout for your suite, because 120 seconds is short for most test runs. The loop cap isn't a budget: Claude Code overrides a Stop hook after 8 consecutive blocks with no tool call in between, and the count resets every time Claude calls a tool, so a run-tests / block / run-tests loop isn't bounded by it. Use --max-turns or --max-budget-usd in headless runs. It runs in your session: anything that can skip or stop the session skips the hook. Treat Stop hooks and /goal as a way to keep Claude working; the gate that holds is CI, or a human, checking the result.
PitfallsA verifier that can edit will make the tests pass rather than tell you they failed. A verifier in the same context (asking the implementer to "double-check") inherits its blind spots. Verifying the summary: "I added tests for all edge cases" isn't evidence; the diff and the test run are. Gate loops: a Stop hook that can never be satisfied keeps Claude working. Claude Code overrides it after 8 consecutive blocks with no tool call in between (CLAUDE_CODE_STOP_HOOK_BLOCK_CAP), and the count resets on each tool call. Prompt hooks can return "impossible": true to let the stop through.

Quality Markers

Quality markers are the observable signals that work is done and trustworthy. A reviewer, a hook or a CI job can check them without redoing the work. In practice they are the commands Claude ran with their exit codes, test counts (passed, failed, skipped), screenshot paths compared against a design, the diff's scope ("touched 4 files, all under src/billing/"), and an explicit list of what wasn't verified. The docs: "reading the output is faster than rerunning the check yourself. For a session you weren't watching, it's also the only evidence you have."

Markers become powerful when a machine checks them. There are two common setups.

Interactive: a Stop command hook. The Stop input carries last_assistant_message and stop_hook_active. A small script can send Claude back once when the final message lacks an evidence section. With the stop_hook_active guard it blocks the first stop and allows the next one, so it's a one-time nudge, not a gate. A hard requirement needs your own counter or state file, and still has the fail-open limits above. Remember that "Stop hooks fire whenever Claude finishes responding, not only at task completion", including when Claude stops to ask you a question.

#!/usr/bin/env bash
# Stop hook: don't let Claude finish without evidence. Registered under "Stop" in .claude/settings.json.
input=$(cat)
[ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ] && exit 0          # already continued once: allow the stop
msg=$(jq -r '.last_assistant_message // ""' <<<"$input")
case "$msg" in *\?) exit 0 ;; esac                                          # Claude is asking you something
missing=()
grep -qiE '^#*\s*evidence' <<<"$msg"                 || missing+=("an Evidence section")
grep -qiE '([0-9]+ (passed|failed))|exit (code )?[0-9]' <<<"$msg" || missing+=("test counts or command exit codes")
grep -qiE 'unverified|not verified|could not (run|verify)' <<<"$msg" || missing+=("a list of what you could not verify (or 'none')")
if [ ${#missing[@]} -gt 0 ]; then
  jq -n --arg r "Before finishing, add: $(IFS=';'; echo "${missing[*]}"). Quote the commands you ran and their output." \
    '{decision: "block", reason: $r}'
fi
exit 0

Headless: a structured completion report. With claude -p --output-format json --json-schema '…', the result's structured_output field holds an object in your shape. CI can then fail the job on tests_failed > 0 or a non-empty unverified list without parsing prose. Treat a success result without structured_output as a failure. Check the result's stop_reason first, then terminal_reason, then subtype, the order the Python SDK reference gives: a refusal has stop_reason: "refusal", usually with subtype: "success", and real runs have returned an API failure as subtype: "success" with terminal_reason: "api_error". Allow a few turns, because structured output arrives through a tool call.

claude -p "Implement the change in TASK.md, run the tests, and report." \
  --permission-mode acceptEdits --allowedTools "Bash(npm test *)" --max-turns 30 \
  --output-format json \
  --json-schema '{"type":"object","required":["tests_run","tests_failed","commands","unverified"],
    "properties":{"tests_run":{"type":"integer"},"tests_failed":{"type":"integer"},
    "commands":{"type":"array","items":{"type":"string"}},"unverified":{"type":"array","items":{"type":"string"}}}}' \
  | jq -e '.stop_reason != "refusal" and .terminal_reason == "completed"
          and (.structured_output | .tests_failed == 0 and (.unverified | length) == 0)'
Toggle what Claude's final message contains: the markers the hook looks for are highlighted, missing ones show as ghost lines, and the stamp is the decision. The decision panel reproduces the Stop hook's logic (the evidence section, counts or exit codes, the unverified list, the question carve-out, the stop_hook_active guard). The "reviewer trust" meter is a toy weighting, not a measurement.
Deep dive: markers at team scale, and markers that lie

Team scale. Per-session markers roll up through OpenTelemetry: claude_code.commit.count, claude_code.pull_request.count, claude_code.lines_of_code.count, claude_code.code_edit_tool.decision, and events such as tool_result and hook_execution_complete. Telemetry is opt-in (CLAUDE_CODE_ENABLE_TELEMETRY=1) and "Cost metrics are approximations". The analytics dashboard labels attributed PRs claude-code-assisted and calls its attribution "deliberately conservative". See agents-5: Observability.

Goodhart. Any marker an agent can produce without doing the work will be produced without doing the work. "12 passed" in prose is cheap; a test run inside the transcript is not. Prefer markers tied to tool results the harness recorded, such as a PostToolUse log of test commands with their exit codes, over strings in the final message. The Stop hook above is a nudge, not proof; a verifier that reruns the narrowest test is proof. In evals, grade outcomes rather than paths, and read the transcripts (agents-5: Evals).

Exercise: a verifier, a cap and a gate

(1) Add the verifier agent above to a repo. Implement a small change, then ask Claude to use the verifier against your acceptance criteria. (2) Run one review round with /code-review and one with the plan-based prompt, and compare what each found. (3) Install the evidence Stop hook and finish a task. Did Claude add an Evidence section on the second attempt? (4) Write a CLAUDE.md line that caps review rounds.

Show a solution

(1) A good verifier report lists each criterion with PASS/FAIL/UNVERIFIED, a file:line and quoted command output. If it starts editing, you gave it Edit or Write: check its tools. (2) /code-review finds bugs in the diff. The plan-based prompt finds missing requirements and scope creep, which a bug finder doesn't look for. You usually want both. (3) The first stop is blocked with the hook's reason; Claude adds the section; the second stop has stop_hook_active: true, so the hook allows it. (4) For example: "Review loops: at most three rounds. After round three, list remaining findings as Optional and stop; act only on correctness or requirement gaps."

Key takeaways

  • Classify checklist items as command, evidence or judgment, and route each to a hook, a demand for output, or a reviewer.
  • Review loops converge only with correctness-only criteria, diff-scoped input and a round cap (about three).
  • Verifiers need fresh context, evidence rather than claims, and tools that can't fix. /verify checks the running app, not just the tests.
  • Make quality markers machine-checkable: a Stop hook interactively (a one-time nudge with the stop_hook_active guard, and it fails open), --json-schema → structured_output headless, checked after stop_reason and terminal_reason. CI is the gate that holds.

User Interfaces

UI work fails in a specific way: the code compiles, the tests pass, and the screen is wrong. The fix is the same as everywhere else in this session: give Claude a check it can run. For UI that check is visual. Claude needs a screenshot of the result, the real browser with its console, the design it's aiming for, and your design system's tokens and components, so its output is constrained to what your product actually uses.

Visual Iteration with Screenshots

Claude reads images as well as text. Getting one into a session takes a second: drag and drop it into the window, paste with Ctrl+V (Alt+V on Windows and WSL), or give a path. Each image becomes an [Image #N] chip, and Cmd+Click (Ctrl+Click) opens it. The contrast between a weak and a strong UI prompt is the whole method in one line:

✗ No check

make the dashboard look better. Claude has no target and no way to see its result, so "better" is whatever it imagines.

✓ A visual check

[paste screenshot] implement this design, take a screenshot of the result, compare it to the original, then list the differences and fix them. There's a target, an observation and an explicit diff step.

The loop is target → implement → screenshot → list differences → fix → screenshot. It converges only when the comparison is fair. Use the same viewport size (state it: 1280×800 desktop, 390×844 mobile), the same data, the same theme and the same zoom. The step that does the work is "list differences": a written list of mismatches ("card padding 16px vs 24px in the design; primary button uses #2563eb instead of --color-primary") turns a fuzzy impression into a checklist Claude can work through and you can audit.

Screenshots can come from you, from the Chrome integration ("Take a screenshot of the checkout page and save it to disk"), from a browser-automation MCP server such as Playwright's, or from a script in a skill. For regressions, don't rely on eyeballing. A bundled script that captures fixed-viewport screenshots and computes a pixel or perceptual diff against a baseline gives a number and a diff image. Claude then explains the diff rather than hunting for it.

Toy model with illustrative numbers. The mock component has eight visual properties; the current build differs from the design in six. Each iteration fixes what the feedback makes visible: vague words rarely pin down a property and sometimes regress one, an itemized screenshot comparison lists the visible mismatches, and a diff script lists every mismatch including the subtle ones. On the build, a numbered mark is a mismatch this feedback names; a ? mark is a mismatch it doesn't show you.
Deep dive: images, context and cache

Images are context. Every screenshot stays in history and is sent on every later request until it's removed. The API limits how many images a request can carry, and Claude Code also caps their total size. When the next request would pass either limit, "Claude Code removes a batch of the oldest images and PDFs from what it sends". Claude can no longer see them, so share an image again if it's still needed. Removing them changes earlier messages, so the next request reprocesses the conversation from there: "you see one slower turn per batch rather than one with each new screenshot". Practical rules: crop to the component under work, save screenshots to disk and reference them by path when Claude only needs the file, and /clear between unrelated visual tasks. Source: prompt caching: accumulating many images.

Chrome Integration

Claude in Chrome connects Claude Code to your actual browser through the Claude in Chrome extension. Claude opens tabs, clicks, types, reads the DOM and console, records GIFs and saves screenshots, "in a visible Chrome window in real time". It shares your browser's login state, so it can test the authenticated parts of your app without fixtures. It also works in Edge and is detected in other Chromium browsers (Brave, Arc, Vivaldi, Opera).

NeedHow
RequirementsExtension version 1.0.36+, a direct Anthropic plan (Pro, Max, Team, Enterprise), and a session signed in with /login. API keys and claude setup-token tokens keep it off. Not on WSL, Bedrock, Agent Platform or Foundry
Startclaude --chrome, or /chrome → Enabled by default. In VS Code, type @browser
Status and repair/chrome shows "Status: Enabled" and "Extension: Installed", manages permissions, reconnects, and picks a browser when several are connected
One-shot task/claude-in-chrome [task], a bundled skill: "testing a page, filling a form, or reading console logs"
Tool list/mcp → claude-in-chrome → View tools
Permission prompts for browser actions start with "Claude in Chrome wants to"; site-level permissions are inherited from the extension's settings. In auto mode, a classifier-approved browser call skips the extension's per-site check for that call, unless your permission rules deny a site to Claude in Chrome. Hover the numbered checkpoints, the cable or the tab group. The terminal and the page are illustrative.
youI changed the signup validation. Open localhost:3000/signup, submit it empty and then with an invalid email. Check that the inline errors appear, read the console for errors, and save a screenshot of each state to ./shots/.
browser · navigatelocalhost:3000/signup (new tab in this session's tab group)
browser · click + readSubmit → 2 inline errors rendered; console: 1 warning "Each child in a list should have a unique key"
screenshotsaved ./shots/signup-empty.png, ./shots/signup-bad-email.png
assistantEmpty submit shows both errors. Invalid email shows "Enter a valid email" but the field border doesn't turn red (the design says it should). Console: a key warning from FieldList.tsx:41. I'll fix both and re-take the screenshots.
Pitfalls and boundariesYour logins are the blast radius. Claude acts as you on every site you're signed into, so manage per-site permissions in the extension and be careful in auto mode. Web pages are untrusted input. Text on a page can try to instruct Claude. Context cost. "Enabling Chrome by default increases context usage since the browser tools and their instructions are always loaded"; connect with --chrome when you need it. Recordings leak. A GIF "captures everything visible in the browser, including account details on logged-in pages". Uploads are filtered. Claude refuses files it isn't allowed to read, uploads over 10 MB in total, hard-linked files, and credential-named files such as .env, .pem, .key or anything under .ssh (requires v2.1.293+). Ask for specific logs. "Tell Claude what patterns to look for rather than asking for all console output."

Design System Context

Without your design system in context, Claude produces plausible UI that matches nobody's product: invented hex colors, one-off spacing, a new button instead of yours. You fix that by giving it three things at the right scope. The tokens are the named colors, type and spacing. The component inventory says what exists and where. The rules say "use X, never Y". And something has to check the output.

## Design system
- Tokens: src/styles/tokens.css (colors --color-*, spacing --space-1..8 on a 4px scale, radius --radius-sm|md|lg)
- Components: src/components/ui/ (Button, Input, Card, Dialog, Toast). Check index.ts before writing a new one.
- Visual changes: screenshot at 1280x800 and 390x844 and compare with the design before reporting done.
---
paths:
  - "src/components/**"
  - "src/**/*.css"
---
# UI rules
- Never hard-code colors, font sizes or spacing: use var(--color-*), var(--space-*), var(--text-*).
- Compose from src/components/ui before creating components; extend with variants, not copies.
- Every interactive element needs a visible focus state and an accessible name.
- Dark mode: test both themes; tokens switch automatically, literals don't.
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/token-lint.sh", "timeout": 30 }
        ]
      }
    ]
  }
}

The split follows how each file loads. CLAUDE.md loads in every session, so it holds only pointers. A path-scoped rule (the only frontmatter field rules read is paths:) loads when Claude reads or edits matching files, so the detailed UI rules cost nothing during backend work. One caveat: path-scoped rules reload on demand after compaction rather than being re-injected. The token check is a deterministic hook, because "is this hex value a token?" has one right answer. The same idea scales up in two of Claude Code's own features. Artifacts look for "an existing design system in your project before choosing" a palette, and treat "your design system as higher precedence than its own choices, and your prompt as higher precedence than both". The /design-sync [hint] skill converts your repo's React design system and uploads it to Claude Design, "so designs it produces use your real components" (run /design-login first; Anthropic API only).

A deterministic check of the kind you'd run in the PostToolUse hook above. It flags literal colors, off-scale spacing and literal font sizes, shows the nearest token as a diff with each hunk's rule, and shows the decision: "block" JSON the hook would return. Edit the CSS (it re-lints as you type) or press lint; the token table is an illustrative design system.
PitfallsDumping the whole design-system doc into CLAUDE.md taxes every session, so point to it and scope the rules by path. Tokens in prose only: "use our blue" isn't checkable, but --color-primary plus a lint hook is. Inventing components: without "check index.ts first", Claude writes a new Button next to yours. Testing one theme: literals break dark mode while tokens don't, so screenshot both.

Design Tools via MCP

MCP connects Claude Code to the tools where designs live and to browsers that can render them. The MCP docs' examples include "Update our standard email template based on the new Figma designs that were posted in Slack", and Chrome's capabilities include "build a UI from a Figma mock, then open it in the browser to verify it matches". Three connections cover most UI work:

# Figma: the plugin is Figma's recommended Claude Code setup (MCP server settings plus Figma's skills)
claude plugin install figma@claude-plugins-official
# ...or, if you can't install plugins, add Figma's hosted server by hand, then authenticate it in /mcp
claude mcp add --transport http figma https://mcp.figma.com/mcp

# Playwright MCP for repeatable screenshots: headless, in-memory profile, fixed viewport
claude mcp add playwright -- npx @playwright/mcp@latest --headless --isolated --viewport-size 1280x800

Both setups come from the vendors, not the Claude Code docs: Figma: remote server installation and the Playwright MCP README. The claude mcp add … -- <command> form is the documented stdio syntax. Playwright MCP runs headed with a persistent profile by default, which is why the flags matter for repeatability. Run /mcp in a session to see what loaded and to authenticate.

Choose by job. Figma MCP answers "what should this look like": frames, layout, variables and component names from the design file. Claude in Chrome answers "what does it look like in my real browser, logged in", with your session and your extensions. Playwright MCP with --headless --isolated and a fixed viewport answers "what does it look like, the same way every time", which suits regression screenshots and pre-merge checks. Scope matters too. claude mcp add defaults to local scope (you, this project). --scope project writes .mcp.json for the team, and Claude Code prompts each teammate to approve those servers in interactive sessions.

Claude Code also has design surfaces of its own. /design [brief] drafts mockups, flows or landing pages as artboards on one canvas, published as a Claude Design artifact you edit in the browser and export as PNG or PDF (requires v2.1.265+, Anthropic API, artifacts available). /dataviz [request] applies chart-design guidance and validates palettes for colorblind safety and contrast with a bundled script.

Figma provides the target, rules and components constrain the implementation, the token hook checks every edit deterministically, a browser screenshot closes the visual loop, and /verify, which you invoke yourself, checks behavior in the running app. A project verify skill can also run before each commit. The component is drawn as five stacked planes, from the layout frame at the base to behaviour on top, and each check is pinned to the plane it verifies. Hover a plane or its numbered check; the component is illustrative.
Trust and limits"Verify you trust each server before connecting it. Servers that fetch external content can expose you to prompt injection risk." A comment in a shared design file is untrusted text like any web page. MCP output is capped: Claude Code warns above 10,000 tokens and limits output to 25,000 tokens by default (MAX_MCP_OUTPUT_TOKENS), so ask for one frame or node, not a whole file. Tool search defers MCP tool definitions until needed, so connected-but-idle design servers cost little context.

Exercise: close the visual loop on one component

Pick a component with a design (a Figma frame or a screenshot). (1) Add the CLAUDE.md design-system block and a path-scoped ui.md rule. (2) Ask Claude to implement or adjust the component, then take screenshots at two viewports with claude --chrome (or Playwright MCP), compare them to the design, list the differences and fix them. (3) Add a token-lint hook and confirm it catches a literal hex value. Count iterations until the difference list is empty.

Show a solution

A clean run looks like this. The first screenshot plus an itemized list of 4–8 differences; Claude fixes them; a second comparison lists 0–2 subtle ones (letter spacing, shadow), fixed on the third pass. If the list never shrinks, the comparison isn't fair: check viewport and theme. If Claude keeps writing literals, check that the rule's paths match the files it's editing (/context shows loaded memory files) and that the hook runs (/hooks). The token hook should return {"decision":"block","reason":"…#2563eb is not a token; use var(--color-primary)…"}.

Key takeaways

  • UI work needs a visual check: target, screenshot, an itemized difference list, fix, repeat, at a fixed viewport, theme and data set.
  • Claude in Chrome drives your real, logged-in browser (console, DOM, GIFs, screenshots); it needs /login on a direct plan, and your logins are its blast radius.
  • Put design-system pointers in CLAUDE.md, detailed UI rules in path-scoped rules, and the "is this a token?" check in a hook.
  • Use Figma MCP for the target, Playwright MCP for repeatable screenshots and Chrome for the real browser, and treat design-file text as untrusted.

Security

Security in Claude Code workflows has two halves. Reviewing the code Claude writes is a quality problem, so you layer reviewers. Containing what Claude can touch while it works is a boundary problem: the sandbox, permission rules and where your secrets live. Anthropic's containment post makes the second half concrete. A pasted "can you run this for me?" prompt exfiltrated credentials in 24 of 25 attempts, and "the only defense that holds in this situation is the environment". Everything here is defensive configuration you apply to your own setup.

Security Review

/security-review runs an on-demand pass over "the changes on your current branch", meaning the diff between your branch and origin's default branch. It looks for "risks like injection, auth issues, and data exposure". It needs an origin remote; if it fails with an ambiguous argument error, the errors reference covers it. It's one layer of several, and the docs lay the layers out explicitly:

Each layer catches what the earlier ones missed. None of the review layers is a boundary: the security-guidance docs say "None of the layers block writes or commits", and every reviewer can miss issues. Boundaries are the bottom band. Send the risky action, which is illustrative, and take walls down to see what still holds.
  • The security-guidance plugin (/plugin install security-guidance@claude-plugins-official) reviews Claude's own work at three depths. Each file edit gets a pattern match with no model call (eval(, pickle, dangerouslySetInnerHTML, edits under .github/workflows/). The end of each turn gets a background model review of everything that changed. Each commit or push Claude makes gets a deeper agentic review that reads callers and sanitizers. The reviewers run in a fresh context: "the reviewer starts from the diff, has no investment in the original approach". Enable it for the team with "enabledPlugins": {"security-guidance@claude-plugins-official": true} in .claude/settings.json.
  • The Claude Security plugin (/plugin install claude-security@claude-plugins-official, then /claude-security) runs a multi-agent scan of a repository or a diff. It maps the architecture, builds a threat model, hunts, independently reviews every finding and suggests patches for you to apply. It uses dynamic workflows, so it inherits their availability and cost profile.
  • Code Review is the managed PR-time service (Team and Enterprise). Your existing CI scanners keep the "language-specific rules, supply-chain checks, and policy enforcement" that the plugins don't attempt.
  • Your own reviewer. The security-reviewer example in the plugin docs (injection, authentication and secrets-handling risks in the changed files) and the best-practices page's read-only reviewer (tools: Read, Grep, Glob) are good templates for repo-specific concerns. The vulnerability detection agent cookbook builds the SDK version: read-only tools, a threat model and a structured triage report.
PitfallsDiff blindness: /security-review covers the branch diff only. To review code you already have, ask for a review of a specific directory or run /claude-security. Treating findings as a gate: review output is advice, and a clean report doesn't prove safety. Reviewing what you can't see: every one of these reads source in your checkout, "not a running site or deployed service". Uncapped review noise: the convergence rules from Quality apply. Ask for exploitability and evidence, and rank by impact.

Sandboxing

"The sandbox is off by default." Turn it on with /sandbox, whose panel has Mode, Overrides and Config tabs and saves to .claude/settings.local.json, or with "sandbox": {"enabled": true} in ~/.claude/settings.json for every project. Once it's on, Claude's shell commands and every process they start run inside an OS boundary: Seatbelt on macOS, bubblewrap plus socat on Linux and WSL2. On native Windows there is no sandbox. The defaults are worth memorizing, because they're narrower than people assume in one direction and wider in the other:

AccessDefault inside the sandboxChange with
WritesWorking directory, a per-user temp dir, added directories. Protected paths (.claude settings, skills, agents, hooks, .mcp.json, shell rc files, .git hooks and config, most of ~/.claude) stay write-deniedfilesystem.allowWrite / denyWrite
Reads"Most of the machine, including credential files such as ~/.ssh and ~/.aws/credentials"filesystem.denyRead / allowRead, credentials
NetworkNo direct route; a local proxy checks each host against allowed domains, "which start empty"network.allowedDomains / deniedDomains
EnvironmentInherited, "including any secrets in its environment"credentials env entries, CLAUDE_CODE_SUBPROCESS_ENV_SCRUB

Equally important is what the sandbox doesn't cover. "The sandbox wraps shell commands." Claude's file tools (Read, Edit, Write) and web tools follow permission rules instead: "A denyRead entry doesn't stop the Read tool". Hooks, local MCP servers, plugin monitors, LSP servers, the status line and apiKeyHelper run with your full access. Commands you type at the ! prompt run unsandboxed in most sessions. So pair sandbox paths with permission rules. Read and Edit deny rules apply to the file tools and to file commands Claude Code recognizes in Bash (cat, head, tail, sed, tee from v2.1.269, output redirects, and < input redirects from v2.1.257), and "paths and domains from both sandbox settings and permission rules are merged into the final sandbox configuration".

{
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "allowUnsandboxedCommands": false,
    "filesystem": { "denyRead": ["~/.ssh", "~/.aws", "~/.config/gcloud"] },
    "credentials": {
      "files":   [{ "path": "~/.aws/credentials", "mode": "deny" }],
      "envVars": [{ "name": "NPM_TOKEN", "mode": "deny" }]
    },
    "network": { "allowedDomains": ["registry.npmjs.org", "pypi.org", "files.pythonhosted.org"] }
  },
  "permissions": {
    "deny": ["Read(~/.ssh/**)", "Read(~/.aws/**)", "Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)"]
  }
}

This belongs in ~/.claude/settings.json. It turns the sandbox on and refuses to start without it (failIfUnavailable), and it turns off the "unsandboxed retry escape hatch". Without that, a command that fails in the sandbox may be retried with dangerouslyDisableSandbox: Manual mode prompts "Bash command (unsandboxed)", auto mode sends it to the classifier, and dontAsk denies it. The block also hides credential directories from subprocesses, unsets a token, allows only package registries on the network, and mirrors the read blocks as permission rules so the Read tool honors them too. Verify the setup by asking Claude (not typing it yourself) to run touch ~/sandbox-probe, which should fail with Operation not permitted on macOS or Read-only file system on Linux, and curl --noproxy '*' https://example.com, which should fail with Could not resolve host.

Rules from the sandboxing and permissions docs: the sandbox covers Bash and its children only; denyRead doesn't stop the Read tool; Read deny rules cover the Read tool, recognized file commands and redirections, and are merged into the sandbox; hooks and ! commands run outside; unlisted hosts prompt in Manual, are refused in auto unless the command listed them and the classifier approved, and are refused in dontAsk. Each probe is a dot where it runs, and its arrow ends where it's decided: at a wall, at a prompt, at the classifier, or at its target. Probe commands are illustrative; outcomes are a faithful toy, not a test of your machine.
Deep dive: auto-allow, domain fronting, admin locks and when to use a container instead

Auto-allow is not auto mode. With the sandbox in auto-allow mode (autoAllowBashIfSandboxed defaults to true), sandboxed commands run without prompts, even in Manual mode. The sandbox boundary replaces the prompt. Exceptions still prompt: Bash deny-rule matches, critical-path rm, content-scoped ask rules such as Bash(git push *), and plan mode. Auto mode is a separate classifier; the two combine.

Network allowlists are capability grants. The proxy decides from the client-supplied hostname and "does not terminate or inspect TLS", so "code running inside the sandbox can potentially use domain fronting". The docs warn that "allowing broad domains such as github.com can create paths for data exfiltration". Anthropic's containment post describes exfiltration through an allowlisted api.anthropic.com. Keep the list to what builds need, and use strictAllowlist (user, managed or --settings only; requires v2.1.219+) to refuse instead of prompting.

Other escalation paths. allowUnixSockets on /var/run/docker.sock "effectively grants access to the host system". allowWrite on a $PATH directory or shell rc file enables code execution elsewhere. excludedCommands run with full access. Organizations can lock reads and domains with allowManagedReadPathsOnly and allowManagedDomainsOnly.

When the sandbox isn't enough. It "reduces risk but is not a complete isolation boundary": file tools, MCP and hooks sit outside it. For unattended runs, and for any use of --dangerously-skip-permissions, run the whole Claude Code process in a container or VM with no credentials mounted. Bypass mode offers "no protection against prompt injection or unintended actions" and belongs only in "isolated containers and VMs". See agents-5: Guardrails and sandbox environments.

Dependency Review

An agent adds dependencies faster than a person does, and it chooses them from memory. That creates four supply-chain risks you should design for. Look-alike names sit one typo from a popular package. A package that doesn't exist can be registered by an attacker who anticipated the name. Install-time scripts run code on npm install. And silent transitive growth means the lockfile adds 40 packages for one import. Review them with the session's own pattern: deterministic checks decide, the model explains.

  • Make installs visible. Add ask rules such as "ask": ["Bash(npm install *)", "Bash(npm i *)", "Bash(pnpm add *)", "Bash(pip install *)", "Bash(uv add *)"]. Explicit ask rules are among the "actions no mode auto-approves", so they prompt even in auto mode. (Entering auto mode separately drops broad allow rules such as Bash(*), wildcarded interpreters and package-manager run commands.)
  • Narrow the network. With the sandbox on and allowedDomains limited to your registries, an install script can't phone home to an arbitrary host. Remember hooks and MCP servers run outside that boundary.
  • Check the lockfile diff in code. A /dep-review skill can inject !`git diff --stat -- package.json package-lock.json` and run a bundled script that lists added packages and their facts: registry existence, age, install scripts, advisories from your audit tool, and name distance to popular packages. Claude then explains each flag and proposes alternatives, such as an existing dependency or the standard library.
  • Keep CI authoritative. Your dependency scanner and lockfile policy run on every PR regardless of what the agent did.
  • Extensions are dependencies too. "A Claude Code plugin you install can execute arbitrary code on your machine with your user privileges". Plugin auto-update can change files you reviewed; read hooks/hooks.json, .mcp.json and bin/ first. Anthropic's containment post warns that a remote MCP server can change behavior at any point after you've approved it, and the MCP docs confirm a connected server can change the tools it offers mid-session (dynamic tool updates). Review a repo's .claude/skills (their allowed-tools and ! lines) like code.
Illustrative, fictional packages and numbers. Drag the two policy thresholds on the chart (or use the sliders) and watch the verdicts change. The "model's job" column is what you'd ask Claude to do for each flagged entry; the verdict itself never depends on the model.

Secrets Hygiene

A secret can leak in a Claude Code session in five directions, and each has its own control. Map them before you rely on any single setting:

Where it leaksHowControl
Into contextClaude reads .env, an @.env mention, cat of a key file, a stack trace that prints configRead(./.env), Read(./secrets/**) deny rules. "If your project has a .claudeignore file, it has no effect"
Into transcriptsEverything in context is written to plaintext JSONL under ~/.claude/projects/Keep secrets out of context; cleanupPeriodDays (default 30) controls retention
Into subprocessesBash, hooks and stdio MCP servers inherit your environmentCLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 strips credentials (it leaves GitHub tokens and proxy settings); sandbox.credentials env deny or mask
Into the repoA literal token in a committed .mcp.json or settings.json env block${VAR} and ${VAR:-default} expansion in .mcp.json, headersHelper, apiKeyHelper; a pre-commit scan hook
Off the machinecurl to any host (sandbox off), raw API bodies in telemetry, a shared artifact or GIF, a /heapdump fileSandbox network allowlist; keep OTEL_LOG_RAW_API_BODIES and OTEL_LOG_TOOL_CONTENT off (they're off by default); /heapdump "contains your full conversation and credentials, so don't share it"

Two refinements go beyond deny-listing. Masking lets a sandboxed command use a credential it never sees. With "mode": "mask", commands get a per-session placeholder and the sandbox proxy substitutes the real value on outbound requests to the hosts you allow. It requires network.tlsTerminate and is honored only from user, managed or --settings settings, never from a repo's files. A commit-time scan is a PreToolUse hook that refuses commits whose staged content matches secret patterns. It reports file names, not values, so the secret doesn't enter context through the error message either:

#!/usr/bin/env bash
# PreToolUse (Bash, if: "Bash(git commit *)"): block commits whose staged content looks like a secret.
# Illustrative patterns: use your organization's secret scanner in real repos. Defense in depth, not the boundary.
pattern='AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----|ghp_[A-Za-z0-9]{36}|sk-ant-[A-Za-z0-9_-]{20,}'
files=$( { git diff --cached --name-only --diff-filter=ACM; git diff --name-only --diff-filter=ACM; } | sort -u |
  while read -r f; do   # staged blobs plus tracked working-tree changes, so `git commit -a` is covered too
    { git show ":$f" 2>/dev/null; cat "$f" 2>/dev/null; } | grep -qE "$pattern" && echo "$f"
  done)
if [ -n "$files" ]; then
  printf 'Commit blocked: content in these files matches a secret pattern (values not shown):\n%s\nRemove it, load it from the environment, and re-stage.\n' "$files" >&2
  exit 2
fi
exit 0
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "if": "Bash(git commit *)", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/scan-staged.sh" }
        ]
      }
    ]
  },
  "permissions": {
    "deny": ["Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)"]
  }
}
{
  "mcpServers": {
    "tracker": {
      "type": "http",
      "url": "${TRACKER_URL:-https://tracker.example.com/mcp}",
      "headers": { "Authorization": "Bearer ${TRACKER_TOKEN}" }
    }
  }
}
Edit the settings and .mcp.json fragments, then scan: literal tokens are redacted with "would leak", ${VAR} references are outlined as safe slots, and risky settings are underlined with a margin note. The checks are simple, illustrative patterns based on the controls in the table: literal tokens versus ${VAR} references, telemetry content flags, retention, missing .env deny rules and a .claudeignore mention. Don't paste real secrets; it all runs locally in this page.

What you build: a PASS/WARN/FAIL/MANUAL checklist over a repo. It looks for credential-shaped strings (redacted to four characters and a length), key and .env files, unpinned dependencies and install scripts, and the Claude Code config the repo ships: broad allow rules, defaultMode, hooks, env secrets, helpers, .mcp.json literals and unpinned servers, and skills' allowed-tools. It uses the course's permission engine to answer "can Claude's Read tool open .env?". Read-only and offline.

cd labs && python3 core-5/security_review.py      # seeded sample repo + tiny-app
python3 core-5/security_review.py --repo ~/code/my-app              # a path to your repo, outside labs/; read-only
python3 core-5/security_review.py --repo ~/code/my-app --strict --json  # exit 1 on FAIL; JSON report in core-5/out/

What to observe: the seeded repo trips each check once, and tiny-app passes everything except the MANUAL items. Every verdict comes from a rule you can read, so the model's role is to explain and propose fixes, not to decide.

Open the lab walkthrough

Exercise: harden your own setup in 20 minutes

(1) Run /sandbox, enable it, and ask Claude to run the two probe commands. (2) Add denyRead for ~/.ssh and a Read(~/.ssh/**) deny rule, then ask Claude to read a harmless file you created at ~/.ssh/probe.txt three ways: the Read tool, cat, and a one-line Python script. (3) Grep your repo's .mcp.json and .claude/settings.json for literal tokens. (4) Run /security-review on your current branch.

Show a solution

(1) touch ~/sandbox-probe fails with Operation not permitted (macOS) or Read-only file system (Linux), and curl --noproxy '*' fails with Could not resolve host. If Claude offers to retry unsandboxed, decline, then set allowUnsandboxedCommands: false. (2) With only denyRead, the Read tool can still read the file; with the Read deny rule, the Read tool and cat are refused by the permission system; the Python script is stopped only by the sandbox, which merges both. (3) Replace literals with ${VAR} expansion and rotate anything that was committed. (4) If it fails with ambiguous argument, your clone has no origin default branch reference; see the errors reference.

Key takeaways

  • Layer reviewers (security-guidance plugin, /security-review, /claude-security, Code Review, CI). None of them is a boundary.
  • The sandbox is off by default, covers shell commands only, and by default reads ~/.ssh. Add denyRead plus Read deny rules, restrict domains, and turn off the unsandboxed retry.
  • For dependencies: ask rules on installs, registry-only egress, a deterministic lockfile check, and CI as the authority. Treat plugins, MCP servers and repo skills as dependencies.
  • Secrets leak into context, transcripts, subprocesses, the repo and off the machine, and each direction has its own control.

Business

The same machinery that ships code also produces the documents a business runs on: status reports, dashboards, product analyses, research briefs. The rule from Deterministic Steps applies with extra force here, because a wrong number in a report is worse than a wrong line of code: nobody runs a test on it. Numbers come from code, prose comes from the model, and every claim can be traced to its source. This topic also turns the lens inward, using /insights to improve your own workflows.

Reports and Dashboards

Claude Code has three output channels for reports, and the choice depends on who reads them and where.

Artifacts are "a live, interactive web page that Claude Code publishes from your session to a private URL on claude.ai". The page updates in place as the session continues, and you can share it from the page header. Ask in plain language: "Build a dashboard artifact of last week's deploy failures by service and keep it updated as you investigate." An artifact can also pull live data through your claude.ai connectors each time someone opens it (requires v2.1.209+). The call runs "through the viewing account's own connection", so two viewers can see different data, and local .mcp.json servers can feed the build but not the published page. The limits are real. It's one self-contained page with "no backend". A strict CSP allows only Google Fonts and five public CDN hosts. The rendered page must be 16 MiB or smaller. Artifacts need Pro, Max, Team or Enterprise, a /login session and the Anthropic API, and they're off by default in -p, the SDK and the GitHub Action. Reopen the latest with Ctrl+], list them with /artifacts (requires v2.1.208+), and turn them off with "enableArtifact": false or an Artifact deny rule.

Local HTML from a skill script is the docs' "Generate visual output" pattern: a bundled script renders an interactive HTML file and opens it in the browser. It works on every provider, offline and in CI, and nothing is published. Headless structured reports run claude -p --output-format json --json-schema '…', take the structured_output object and render it with your own template. Put that on a schedule with cloud scheduled tasks or GitHub Actions (autonomy-4). Two bundled skills help with presentation: /dataviz for chart form, color and accessibility, and /slides [brief] for a deck artifact (requires v2.1.265+).


      
Toy pipeline with illustrative data. Step through it: at the claim check, every number in the prose gets a thread to its key in metrics.json, and a number with no key is left dangling. The claim check is a deterministic script that finds every number in the prose and requires a matching key in metrics.json. Switch to "the model computes the numbers" to see what slips through without it.

.claude/skills/weekly-report/SKILL.md

---
name: weekly-report
description: Build the weekly delivery report. Use when asked for the weekly report or delivery metrics.
disable-model-invocation: true
allowed-tools: Bash(python3 ${CLAUDE_SKILL_DIR}/scripts/*.py *)
---
1. Run `python3 ${CLAUDE_SKILL_DIR}/scripts/pull.py --week $ARGUMENTS` (read-only queries; writes data/raw.json).
2. Run `python3 ${CLAUDE_SKILL_DIR}/scripts/metrics.py` → metrics.json. Never compute a number yourself.
3. Write report.md. Every number must be written as it appears in metrics.json, followed by its key in brackets, e.g. "42 deploys [deploys.total]".
4. Run `python3 ${CLAUDE_SKILL_DIR}/scripts/claim_check.py report.md metrics.json`. Fix every unmatched number it lists.
5. Ask whether to publish it as an artifact. Show the claim-check output either way.
PitfallsMental arithmetic: a model summing a column in its head is the commonest report bug; make it call a script. Snapshots that look live: an artifact built from session data is a snapshot unless it uses connectors, so label it with its as-of time. Over-sharing: artifact content is stored on Anthropic infrastructure and visible to whoever you share it with; Claude Code asks before changing an artifact you shared publicly, and admins control public sharing and retention. Huge inline data: "Have the page summarize large datasets rather than inline them in full."

Product Analysis

Claude Code can analyze a product from two sides. From the code: which features exist, which analytics events fire where, which feature flags are dead, and which user flows touch a given table. These are exploration questions that suit Explore subagents or a workflow that fans out over modules. From the data: funnels, cohorts, experiment readouts, support themes. Here access and discipline matter more than model strength.

  • Read-only access by construction. Connect the warehouse or analytics tool through an MCP server or CLI using read-only credentials. Prefer CLIs where they exist (they "don't add any per-tool listing", per the costs page), and pass large exports as files, not pastes.
  • Question first. Use plan mode to agree on the question, the metric, the comparison and the minimum effect worth acting on before any query runs. An open-ended "find interesting insights" across many segments mostly finds noise; the simulator below shows how much.
  • Compute in code, keep the queries. SQL and scripts go into the repo next to the report, so anyone can rerun them. The model's job is to propose hypotheses, write the queries, and explain results along with their sample sizes and uncertainty.
  • Outside research. /deep-research <question> is a bundled workflow that "fans out web searches … cross-checks the sources it finds, votes on each claim" and filters out claims that didn't survive. Claims it couldn't check are listed as unverified rather than refuted. You start it yourself: since v2.1.218 it "runs only when you invoke it". It requires the WebSearch tool, which isn't available on Amazon Bedrock.
Toy statistics, deterministic seed. Every metric in every segment is drawn from the same distribution, so there is nothing real to find, yet some comparisons cross p < α by chance. Compare an open-ended hunt with a pre-registered question, and see what a multiple-comparison correction does. Rows are segments and columns metrics; a highlighted cell is a "significant" result. Hover a cell, or tab into the grid and use the arrow keys, to read its p-value.
Deep dive: making analyses reproducible with Claude Code

Treat an analysis like code. Keep a analysis/<question>/ folder with QUESTION.md (the pre-registered question, metric, comparison, threshold), queries/*.sql, compute.py and report.md, and commit it. Then three Claude Code features make it rigorous. A Stop or /goal condition can require that "every number in report.md appears in outputs/metrics.json". A verifier subagent can be asked to refute the conclusion, checking for alternative explanations, segment mix shifts and novelty effects. A --json-schema run can emit {"decision": "...", "effect": ..., "n": ..., "confidence": "..."} for a decision log. delivery-5: Synthesis applies this to post-release signals.

Usage Insights

/insights turns the analysis inward. It's "a report on how you work rather than how many tokens you've used". It reads your recent sessions on this machine and writes an HTML report covering what you work on, friction points "such as misunderstood requests or buggy code", and suggestions for using Claude Code better. When auto mode is available and your recent sessions mostly ran without it, the report can also estimate how many permission prompts auto mode could have handled.

FactDetail
ScopeUp to 200 sessions it hasn't seen before per run; very short ones skipped. The header shows e.g. 200 sessions (412 total). Sessions from other devices and claude.ai aren't included; not available in cloud sessions
Output~/.claude/usage-data/report.html, plus a timestamped copy per run; deleted on the cleanupPeriodDays schedule (30 days by default)
CostAny plan, any provider; the analysis tokens count against your plan or API usage
Related/usage for this session's cost and tokens; /skill-doctor for unused skills and their context cost (v2.1.252+, and it needs feature-flag fetching); /doctor for a fixing setup checkup; team dashboards at claude.ai/analytics/claude-code (Team/Enterprise) and platform.claude.com/claude-code (Console); OpenTelemetry for per-user metrics
The funnel narrows from up to 200 unseen sessions to the frictions the report names, then to one change, reviewed and committed; the next run measures it before you pick the next friction. The report is diagnosis, not treatment. Each friction it names maps to a mechanism from this session or an earlier one, and the change goes in through review like any other config change (see autonomy-5: Feedback for doing this at team scale).
Pick a friction pattern of the kind the report describes. The recommendation names the mechanism, why it beats the alternatives, and the artifact to add. Example findings are illustrative; the mechanisms and their config come from this session.

Exercise: one insight, one change, one measurement

Run /insights and open ~/.claude/usage-data/report.html. Pick the friction with the most sessions behind it, implement exactly one change for it (a hook, a skill, a CLAUDE.md line, a permission rule or a verification step), and note the date. Run /insights again in two weeks and compare.

Show a solution

A typical first run surfaces repeated approvals for the same safe commands, so run /fewer-permission-prompts to write a project allowlist, or consider auto mode. It also surfaces "Claude claimed done but tests failed", so add the Stop agent hook or a /goal condition from Quality, and misunderstood requests, so start bigger tasks in plan mode or with an AskUserQuestion interview and a written spec. Change one thing at a time so the next report can tell you whether it worked. The second report only analyzes sessions it hasn't seen, so it reflects the new setup.

Key takeaways

  • Choose the report channel by audience: artifacts for live shareable pages (claude.ai login, Anthropic API, no backend), local HTML from a skill script for anywhere, --json-schema headless runs for pipelines.
  • Numbers come from scripts and queries, with a claim check that ties every number in the prose to a computed key.
  • Product analysis needs read-only access, a pre-registered question and queries kept in the repo. Open-ended slicing manufactures findings.
  • /insights diagnoses your own friction from local sessions. Map each finding to one mechanism, change one thing, and measure again.

Session wrap-up

A Claude Code workflow is a set of parts, each doing the job it's best at. Skills carry the procedure: arguments, context injected at render time, bundled scripts and a definition of done. Hooks, scripts and permission rules carry the steps that must never vary. /batch and dynamic workflows carry fan-outs too large for one conversation, as graphs with hard caps and deterministic replay. Reviewers, verifiers and Stop gates carry quality, and they converge only with scoped criteria and round caps. Screenshots, the real browser and your design system carry UI correctness. The sandbox, deny rules and secret controls carry safety, and they hold even when the model is wrong. Scripts and claim checks carry the numbers in reports, and /insights tells you which part of your setup to improve next.

Where this goes nextWhat it adds
agents-3: Skills and PluginsAuthoring, testing and distributing skills, hooks and workflows as plugins
agents-4: OrchestrationWorktrees, merge points and cross-agent protocols behind /batch and workflows
agents-5: Guardrails and EvalsHooks as policy, the auto mode classifier, eval harnesses for skills and agents
delivery-4: Quality GatesVerification of product outcomes: CI gates, release blockers, human approval
autonomy-4: Hooks and PipelinesEvent-driven automation beyond code, built on this session's workflow design
autonomy-5: FeedbackTurning transcripts, telemetry and /insights into a self-improving setup

Labs for this session

All three run offline from labs/ with Python 3.9+ and the standard library. None calls the model or needs the claude CLI. See labs/core-5/README.md for real output excerpts.

The kit is a print-only /release-notes [since-ref] [audience] built on scripts/changes.py, a sibling of the article's example. You get frontmatter checks, a permission verdict for every injected command, a real render in a temp repo, and the bundled script's tests. Install the kit with cp -r core-5/workflow_skill/kit/.claude <repo>/.

cd labs && python3 core-5/workflow_skill.py

Open the lab walkthrough

Matcher reading, exec-form settings, additionalContext versus decision: "block", and fail-open behavior on bad input.

cd labs && python3 core-5/format_hook.py

Open the lab walkthrough

PASS/WARN/FAIL/MANUAL over a seeded sample or your own repo (--repo ~/code/my-app, a path to your repo, outside labs/), with redacted matches.

cd labs && python3 core-5/security_review.py

Open the lab walkthrough

What to do next

  1. Turn your most-repeated procedure into a workflow skill with disable-model-invocation: true, injected context, a bundled script and a "Done when" list.
  2. Add the format-and-lint hook and the evidence Stop hook to one repo, and commit them so the team gets them.
  3. Enable the sandbox with denyRead for credential directories, matching Read deny rules and a registry-only domain list, then run the two probes.
  4. Run /insights, fix one friction, and schedule the follow-up run.