Review the Plan, Not Just the Diff: Gating Coding Agents Before They Write Code
A wrong plan is cheap to fix before implementation and expensive after. Here is a small Claude Code hook that rejects vague plans, then flags edits that drift from the one you approved.
Your coding agent presents a plan. It is long, confident, and neatly bulleted. You skim it, approve it, and twenty minutes later you are reading a 900-line diff that rewrote a module you never wanted touched.
The mistake was visible in the plan. It just was not easy to see, because the plan said "update the relevant services" instead of naming files, and "verify it works" instead of naming a command.
Plan review is the cheapest checkpoint you have: no code exists yet, so changing direction costs one message. Tooling is catching up to this. Plannotator, for example, opens agent plans and diffs in a browser so you can annotate them and send feedback back to the agent. A better review surface helps, but a human should not spend attention on problems a script can catch.
This post builds that script as three small gates:
- Lint the plan before you ever see it.
- Snapshot the file list when you approve it.
- Check for drift when the agent says it is done.
If hooks are new to you, start with our Claude Code hooks guide and come back.
Why plans go wrong
Most bad plans fail in one of four ways:
| Failure | What it looks like | What to require |
|---|---|---|
| Vague scope | "Refactor the auth layer" | An explicit list of files with a reason for each |
| No proof of success | "Make sure everything works" | A runnable verification command |
| Silent scope growth | Cleanup and renames bundled into a bug fix | An "Out of scope" section |
| Too big to review | 30 files in one pass | A file limit that forces phases |
None of these checks needs a model. They are string checks, which makes them fast, free, and consistent.
The plan contract
Tell the agent the format up front so most plans pass on the first attempt. Add this to your CLAUDE.md:
## Plan format
Every plan must contain these level-two headings:
- Goal
- Files (one bullet per file: `path/from/repo/root` : reason)
- Verification (include the exact command in backticks)
- Out of scope
List exact files, no globs or directories. Maximum 12 files per plan.
The instruction shapes behaviour. The hook enforces it.
The gate script
Claude Code calls a tool named ExitPlanMode to present a plan for approval, and hooks can match it. According to the hooks reference, the plan Markdown is injected into tool_input.plan (with tool_input.planFilePath) before a PreToolUse hook runs. After approval, PostToolUse receives it in tool_response.plan. Hook fields change between releases, so check the reference against your installed version.
Save this as .claude/hooks/plan_gate.py. It uses only the standard library (Python 3.9+) and assumes your project directory is the root of a git repository.
#!/usr/bin/env python3
"""Plan gate for Claude Code. Usage: plan_gate.py lint | snapshot | drift"""
import hashlib
import json
import os
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(os.environ.get("CLAUDE_PROJECT_DIR", ".")).resolve()
STATE_DIR = ROOT / ".claude" / "state"
REQUIRED = ["Goal", "Files", "Verification", "Out of scope"]
MAX_FILES = 12
PROTECTED = ("migrations/", ".github/", ".env", ".claude/")
def sections(plan):
"""Map each '## Heading' to the text under it."""
parts = re.split(r"^##[ \t]+(.+?)[ \t]*$", plan, flags=re.M)
return {h.lower(): body.strip() for h, body in zip(parts[1::2], parts[2::2])}
def planned_files(plan):
"""Backticked path at the start of each bullet under '## Files'."""
body = sections(plan).get("files", "")
return re.findall(r"^\s*[-*]\s+`([^`]+)`", body, flags=re.M)
def lint(plan):
found = sections(plan)
problems = [f"Add a non-empty '## {name}' section."
for name in REQUIRED if not found.get(name.lower())]
files = planned_files(plan)
if found.get("files") and not files:
problems.append("List each file as a bullet: - `path/to/file` : reason")
if len(files) > MAX_FILES:
problems.append(f"{len(files)} files is too many. Split into phases "
f"of {MAX_FILES} or fewer and plan only phase one.")
for f in files:
if "*" in f or f.endswith("/"):
problems.append(f"'{f}' is a glob or directory. Name exact files.")
if f.removeprefix("./").startswith(PROTECTED):
problems.append(f"'{f}' is protected. Remove it and tell the user "
"why it needs a manual change.")
check = found.get("verification", "")
if check and "`" not in check:
problems.append("Verification must include a runnable command in backticks.")
return problems
def git(*args):
out = subprocess.run(["git", *args], cwd=ROOT, check=True,
capture_output=True).stdout.decode()
return [p for p in out.split("\0") if p]
def digest(path):
p = ROOT / path
return hashlib.sha256(p.read_bytes()).hexdigest() if p.is_file() else None
def changed_since(base):
"""Tracked changes since `base` (committed or not) plus untracked files."""
tracked = git("diff", "--name-only", "--no-renames", "-z", base)
untracked = git("ls-files", "--others", "--exclude-standard", "-z")
return {p for p in tracked + untracked if not p.startswith(".claude/state/")}
def state_file(event):
return STATE_DIR / f"plan-{event['session_id']}.json"
def cmd_lint(event):
tool_input = event["tool_input"]
plan = tool_input.get("plan")
if not plan and tool_input.get("planFilePath"):
plan = Path(tool_input["planFilePath"]).read_text()
if not plan:
raise ValueError("no plan text in hook input")
problems = lint(plan)
if problems:
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason":
"Plan rejected. Fix these and submit again:\n- "
+ "\n- ".join(problems),
}}))
# No output on success: the normal human approval prompt still appears.
def cmd_snapshot(event):
plan = event["tool_response"]["plan"]
base = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, check=True,
capture_output=True, text=True).stdout.strip()
STATE_DIR.mkdir(parents=True, exist_ok=True)
state_file(event).write_text(json.dumps({
"base": base,
"files": [f.removeprefix("./") for f in planned_files(plan)],
# Files already dirty at approval time, so they are not blamed later.
"dirty": {p: digest(p) for p in changed_since(base)},
}))
def cmd_drift(event):
path = state_file(event)
if event.get("stop_hook_active") or not path.exists():
return
state = json.loads(path.read_text())
touched = {p for p in changed_since(state["base"])
if p not in state["dirty"] or digest(p) != state["dirty"][p]}
extra = sorted(touched - set(state["files"]))
if extra:
print(json.dumps({
"decision": "block",
"reason": "These files changed but are not in the approved plan:\n- "
+ "\n- ".join(extra)
+ "\nRevert them, or explain to the user why each one "
"was necessary.",
}))
if __name__ == "__main__":
try:
command = {"lint": cmd_lint, "snapshot": cmd_snapshot,
"drift": cmd_drift}[sys.argv[1]]
command(json.load(sys.stdin))
except Exception as exc:
# Exit code 2 blocks. Any other non-zero code would let the action through.
print(f"plan_gate failed: {exc!r}", file=sys.stderr)
sys.exit(2)
Wire it up
Add this to .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "ExitPlanMode",
"hooks": [
{ "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/plan_gate.py\" lint" }
]
}
],
"PostToolUse": [
{
"matcher": "ExitPlanMode",
"hooks": [
{ "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/plan_gate.py\" snapshot" }
]
}
],
"Stop": [
{
"hooks": [
{ "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/plan_gate.py\" drift" }
]
}
]
}
}
Add .claude/state/ to .gitignore, then start a session in plan mode:
claude --permission-mode plan
What happens in a session
Suppose the agent submits a plan that lists src/ under Files and has no Verification section. The lint step returns a deny decision, the plan never reaches your approval prompt, and Claude receives this:
Plan rejected. Fix these and submit again:
- Add a non-empty '## Verification' section.
- 'src/' is a glob or directory. Name exact files.
The agent revises and resubmits. When a plan passes, the hook prints nothing. That is deliberate: the gate can only reject. It never approves on your behalf, so the normal approval prompt still appears and you still make the call.
After implementation, drift compares everything changed since approval with the approved file list. If billing.py changed and was never mentioned, the agent is stopped once and asked to revert it or justify it. Drift is not always wrong. Real work uncovers files nobody predicted. The point is that it gets said out loud instead of being buried in a diff.
Two details make this check usable on a real repo. It diffs against the commit recorded at approval, so an agent that commits mid-task does not hide changes. It also hashes files that were already modified, so your own work in progress is not blamed on the agent unless it changes again.
Where each check belongs
| Checkpoint | Catches | Misses | Cost |
|---|---|---|---|
| Plan lint (this hook) | Vague, oversized, or off-limits plans | Plans that are well formed but wrong | Near zero |
| Human plan review | Wrong approach, wrong assumptions | Implementation bugs | Minutes |
| Scope drift check | Unplanned file changes | Bad edits inside planned files | Near zero |
| Tests and CI | Behaviour regressions | Anything untested | CI minutes |
| Diff review | Design and quality issues | Whatever the reviewer skims | Highest |
The linter does not judge whether the plan is good. It makes sure the plan is reviewable, so your attention goes to approach and assumptions. Three questions are worth asking of every plan that passes:
- What does this assume about the code that the agent has not read?
- Would the verification command fail if the change were wrong?
- What is the smallest version of this that delivers the goal?
Common pitfalls
Using exit code 1 to block. It is a non-blocking error for these hooks. The script exits 2 on any runtime error, including unreadable input, so a failing lint step fails closed. The tradeoff is that a bug in your gate stops all plans, which is annoying but visible. If python3 is missing or the script has a syntax error, the command fails with a different code and nothing is blocked, so test the wiring once with a deliberately bad plan.
Assuming every hook can block. PostToolUse runs after the tool has finished. If snapshot fails, you will see an error, but there is no state file and the drift check silently passes. Treat a snapshot error as something to fix immediately.
Treating the protected list as enforcement. It only checks what the plan says. An agent can omit a migration from the plan and edit it anyway. The drift check reports that afterwards. To prevent it, add a PreToolUse hook on Edit|Write, or use permission deny rules.
Forgetting ignored files. Git-ignored files such as .env never show up in the drift check. Protect secrets separately.
Confusing a guardrail with a sandbox. An agent with shell access could edit the hook or its state files. These gates catch mistakes and drift, not a hostile process. Use isolation for that.
Looping forever. A Stop hook that always blocks will keep the agent running. The stop_hook_active check limits this one to a single nudge. The consequence is that a second unplanned edit made after the nudge is not re-flagged in that turn.
Pulling mid-task. Merging or rebasing brings in other people's commits, which appear as drift. Approve a fresh plan after syncing.
Over-tightening the contract. If a one-line typo fix needs four sections, people will bypass the system. Use plan mode for changes that deserve it, and tune REQUIRED and MAX_FILES to your team.
Rollout checklist
- Add the plan format to
CLAUDE.md - Copy the script and register all three hooks
- Edit
PROTECTEDto match your repo - Submit a deliberately bad plan and confirm it is rejected
- Edit an unlisted file and confirm the drift message appears
- After a week, review which rules fired and delete the noisy ones
Next steps
Start with the linter alone for a few days and note which rejections actually improved the plan. Then add the drift check. Once both are stable, consider running the verification command from the approved plan in CI, after reviewing what it is allowed to execute.
If you want to practise building agent workflows with real guardrails, evals, and production patterns, join our AI Engineering cohort.
Want to build this yourself?
Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.