Lesson 6.218 min · 5 cards · 8 exercises · 1 mission

Hooks that format, check and test

PostToolUse checks each file right after an edit, Stop won't let Claude finish while tests are red, and why you need both.

Lesson 1.2 taught you to write the criterion "done when npm test passes". Lesson 2.1 put the test command in CLAUDE.md. Both are requests. This lesson turns them into things that always happen: every time Claude edits a .js file, a hook checks its syntax; every time Claude is about to say "done", a hook runs the tests, and if they fail, Claude isn't allowed to stop.

Two moments to check

There are two good places to attach automatic checks:

Moment Event Good for
Right after each file edit PostToolUse Fast, per-file work: formatting, syntax checks, linting
Before Claude finishes answering Stop Slower, project-wide work: running the test suite

The first catches mistakes early, in the file just edited. The second is the safety net: however an error slipped in, Claude can't say "done" while the tests are red. As you're about to see, you need both.

Check syntax after every edit

todo-api has no lint tool installed, but Node ships node --check, which checks a file's syntax without running it. Create .claude/hooks/check-js.sh:

Terminal
#!/bin/bash
# PostToolUse: syntax-check every .js file Claude edits or writes
FILE=$(jq -r '.tool_input.file_path // empty')
[[ "$FILE" == *.js ]] || exit 0
if ! OUT=$(node --check "$FILE" 2>&1); then
  echo "Syntax error in $FILE:" >&2
  echo "$OUT" >&2
  exit 2
fi

Remember chmod +x .claude/hooks/check-js.sh. The script reads the edited file's path from the JSON input (tool_input.file_path), skips anything that isn't .js, and if the syntax is wrong it prints the error to stderr and exits with code 2.

On PostToolUse, exit 2 can't undo anything: the file is already edited. Instead, Claude Code shows the stderr to Claude, so Claude knows straight away that it broke something. In our test, we asked Claude to use Edit to insert a line with a syntax error into src/app.js. The hook ran right after the edit, and Claude reported that the hook had caught the syntax error.

If your project uses Prettier, the docs provide a ready-made auto-format hook built the same way: matcher Edit|Write, then npx prettier --write --ignore-unknown "$f", with f being the path from jq.

The gap: Claude doesn't only edit with Edit

On our first try, we just said "add exactly this line to the end of src/app.js". Claude chose the quickest route: a Bash command, printf … >> src/app.js. The hook matching Edit|Write never ran, because Claude never used Edit or Write. The broken line got through.

The docs are explicit about this: Claude can change files with shell commands. There are three ways to close the gap:

  • Add a Stop hook that checks the whole project every turn, so whatever route an error took, it's caught before Claude finishes. That's what this lesson does.
  • Also match Bash and have the script read git status --porcelain to see which files just changed.
  • Use the FileChanged event when you need to react every time a specific file changes on disk, whoever changed it.

The general lesson: a PostToolUse hook keyed on a tool name only sees that tool. Don't trust it as your only check.

Not done while the tests are red

Create .claude/hooks/tests-before-stop.sh:

Terminal
#!/bin/bash
# Stop: don't let Claude finish while npm test fails
INPUT=$(cat)
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
  exit 0  # Claude was already sent back once; let it stop
fi
cd "$CLAUDE_PROJECT_DIR" || exit 0
[ -z "$(git status --porcelain -- src test)" ] && exit 0  # nothing changed in code
if ! OUT=$(npm test 2>&1); then
  echo "npm test fails. Fix it before you finish:" >&2
  echo "$OUT" | grep -E -A4 "✖|Error" | head -30 >&2
  exit 2
fi

On Stop, exit 2 stops Claude from stopping: Claude receives the stderr as its reason to keep going. Three details matter:

  • stop_hook_active is true when Claude is already continuing because of this hook. Exit early then, so you don't block forever on a condition that may never be met. Claude Code has its own limit too: after 8 blocks in a row with no tool call from Claude, it overrides the next one.
  • Skip when no code changed: Stop runs after every answer, even a plain question. The git status --porcelain line avoids running the tests for nothing.
  • Send the right lines: our first version used tail -25 and only sent a wall of stack trace, losing the SyntaxError line. A grep for ✖ and Error sends exactly what Claude needs.

In our test, after the bad line was inserted with Edit, the Stop hook blocked with the SyntaxError line on top. Claude removed the line, ran npm test itself, saw 5/5 pass, and only then stopped.

An interesting twist: after the Bash insertion, Claude didn't remove the line. It explained that removing it would undo what you'd asked for, and stopped on the second attempt. The hook kept its promise: Claude couldn't say "done" without knowing the tests were red. What happens next is still your call.

Slow tests run in the background

todo-api's tests run in under a second. A real suite can take minutes, and a synchronous hook makes Claude wait all that time. Add "async": true to run the hook in the background:

JSON
{ "type": "command", "command": "…/run-tests.sh", "async": true }

Claude carries on at once; when the script finishes, the additionalContext it prints reaches Claude on the next turn. The price: an async hook can't block anything, because what it would stop has already happened. With claude -p, async hooks still running when the session ends are cancelled.

A sensible split: quick checks (syntax, formatting) as synchronous PostToolUse; a long test suite as async PostToolUse for early warnings; and the "not done while red" gate as a synchronous Stop.

The hook set for todo-api

Put together in .claude/settings.json:

JSON
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-js.sh" }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/tests-before-stop.sh" }
        ]
      }
    ]
  }
}

Commit both .claude/settings.json and the .claude/hooks/ folder so the whole team shares the same safety net. Check with /hooks, and test each script with sample JSON before you trust it.

With this set in place, handing Claude issue #3 (the ?done= filter) works very differently: every edited file gets a syntax check, and Claude can't report done until the tests pass. Lesson 6.3 does the opposite: instead of checking afterwards, we block in advance the things that must never happen.

Practice lesson 6.2

5 flashcards, 8 exercises checked right on the page, 1 mission on your machine.

Start practice

Related reference

Type to search the reference, templates and lessons.