Skip to content
stacks

Make Claude Code run tests before it's done

Make Claude Code run tests before finishing with explicit CLAUDE.md commands, a Stop hook that blocks failed checks, and a full verification run.

Published 7 min read

To make Claude Code run tests before it says it's done, put the exact commands in CLAUDE.md and add a Stop hook that runs them and blocks stopping on failure.

Require evidence in the handoff: the command, its result, and the pass, fail and skip counts. Include lint, typecheck, build and an app startup check in the definition of done. Unit tests alone can pass while the application fails to start.

Why does Claude Code say it's done when the tests fail?

A completion message can arrive without a successful test run. The agent may have run a focused test, missed a failure elsewhere, or stopped after editing the code. Ask which command ran against the final changes before treating the message as evidence.

Instructions help establish that expectation, but they can be skipped. Anthropic describes CLAUDE.md as context rather than enforced configuration in its guide to project instructions. A sentence saying "always test your changes" leaves the agent to choose both the command and the stopping condition.

An unavailable test runner needs a blocked handoff. If dependencies cannot install or a required tool is missing, ask the agent to name the problem and the checks it couldn't run. "I couldn't run the tests" gives you a decision to make; reporting completion hides it.

How do I make Claude Code run tests before it's done?

Put the project's verification commands in its root CLAUDE.md. Run them yourself first so the instructions refer to working scripts. /init can draft that file, but review the commands it discovers before relying on them; Anthropic documents it in the project instruction setup guide.

A package script gives the checks one entry point. For an npm project that already has these scripts, a check script could contain:

package.json scripts entry
"check": "npm run lint && npm run typecheck && npm test && npm run build"

The chain stops at the first failure. Add the missing scripts before using it, and make sure the test command exits after one run. A watch process will wait for more changes instead of returning a result.

The instruction should define what the handoff includes. This example assumes you've added and manually run npm run check:

CLAUDE.md verification section
Before reporting done, run npm run check from the repository root.
Fix failures in the implementation and rerun after the final edit.
Do not delete or skip tests, or weaken lint and typecheck settings.
Report the command, exit status, and test pass/fail/skip counts.
If a tool or permission blocks a check, report it as unverified.

Ask for the relevant output when reviewing a result. A run with every test skipped needs investigation even if the command exits successfully. Keep the output associated with the final revision: changing code after a green run makes that evidence stale.

Can a Stop hook force Claude Code to run the tests?

A command-based Stop hook runs each time Claude finishes responding, including after a plain answer, and can return failures to the agent. Add this entry to the existing hooks object in .claude/settings.json, preserving other settings. The shell script below uses jq, which must be installed.

Stop hook configuration
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "sh \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/verify-before-stop.sh",
            "timeout": 600
          }
        ]
      }
    ]
  }
}

The script runs the same package command and sends diagnostics to stderr. Exit 2 blocks stopping and gives Claude feedback, as documented in Anthropic's hook input and output guide.

.claude/hooks/verify-before-stop.sh
#!/bin/sh
input=$(cat)
active=$(printf '%s' "$input" | jq -r '.stop_hook_active') || { echo 'verify-before-stop: jq failed or is missing' >&2; exit 1; }
if [ "$active" = true ]; then
  exit 0
fi
cd "$CLAUDE_PROJECT_DIR" || exit 2
if npm run check >&2; then
  exit 0
fi
printf '%s\n' 'Checks failed. Fix the reported failures and rerun npm run check.' >&2
exit 2

The stop_hook_active guard allows stopping on the continuation triggered by this hook. It prevents a repeated blocking loop. The next stop can occur without rerunning repairs, so require fresh output in the handoff. Anthropic's Stop hook reference describes that field and the hook's limits. Test both paths with a known failing check and a passing one before relying on the wiring.

Each repository still needs its own check command and hook maintenance. If the command omits a build or stops before starting the app, the hook leaves those gaps intact. The handoff should state what actually ran.

What should "done" check besides unit tests?

The checks should cover how someone will use the result. For a web app, require dependencies to install, lint and typecheck to pass, tests to run, and a production build to complete. Then start the application and request a known local URL. A build can succeed with a runtime configuration error waiting until startup.

The startup check needs a lifecycle. Start the server on a free port, wait for an HTTP response within a timeout, and stop the process you started. Otherwise an older server can answer the request, or the check can leave a background process running after it finishes.

Manual QA covers behavior the commands don't exercise. Open the changed page, follow its main interaction, and inspect errors or warnings. For a UI change, a successful health endpoint tells you little about whether the new form works. Name the behavior checked in the handoff so the reviewer can distinguish it from the automated coverage.

How can one command define done for the agent?

stacks (@steamfield/stacks) gives a project a recorded verification procedure. stacks new writes starter files, a build brief and .stacks/manifest.json, including the verify steps. It doesn't install dependencies or run a generator during scaffolding. The brief tells the agent to finish when verify exits 0 with outcome green.

The scripted demo shows a greeting regression in a Go CLI project. The test expects Hello, world!, but the implementation returns Hi!. The agent restores the default in the code and reruns verify. The displayed command output was captured from a real 0.7.0 run; playback executes nothing and calls no model.

Agent + stacks
Demo

You: Check the greeting change before you call it done.

Agent: I’ll run the full recorded checks.

●Bash(stacks verify)
verify: failed (full run; 8 passed, 1 failed, 0 skipped; 10.9s)
failed check test (exit 2, 1.2s) exited with status 2
| expected: "Hello, world!"
| actual : "Hi!"
Output abbreviated
●Bash(cat internal/config/config.go)
v := viper.New()
v.SetDefault("greeting", "Hi!")
v.SetDefault("json", false)
Output abbreviated

Agent: The tests expect Hello, world!, but the default is Hi!. I’ll restore the default in the code.

●Bash(sed -i '' 's/SetDefault("greeting", "Hi!")/SetDefault("greeting", "Hello, world!")/' internal/config/config.go)
●Bash(stacks verify)
verify: green (full run; 9 passed, 0 failed, 0 skipped; 5.7s)
Output abbreviated

Agent: All nine recorded checks passed in the full run. The greeting default is restored.

Example agent conversation. Playback can be paused.

A test fails, the agent restores the greeting in the code, and the full verify run comes back green.

Verify reads only the project's manifest. It finds the nearest .stacks/manifest.json by walking up from the current directory, and it doesn't consult the registry during a run. From inside the project, the full run is:

Terminal
stacks verify

The phases control failure handling. Setup stops at its first failure; the check phase runs every check so you can see multiple failures together. Serve steps start a server, probe it over HTTP and stop it. Teardown always runs after those phases, including after a failure. The verify reference explains the ordering and timeouts.

The manifest determines whether a run includes a server probe or a build. Verify runs the declared steps. For a serve probe, it refuses a port that already answers and checks that the server stops afterward. The probe accepts any HTTP status below 500, so it doesn't establish that a particular page returned 200 or that a user journey works.

The brief guides the agent, while the manifest supplies the executable checks. Editing .stacks/BRIEF.md changes no check that verify runs. Review the manifest when deciding whether the recorded procedure covers your project's definition of done.

How do I read a failed verify run?

Start with the failed step and its diagnostic output. The report names the command and distinguishes a step failure from an environment problem or timeout. A missing command, reported with failure kind env, needs a tool installed or an environment corrected. A test assertion needs investigation in the code it exercises.

Focused reruns shorten the repair loop. If the manifest has steps named lint and test, you can select them:

Focused rerun
stacks verify --only lint,test

A successful focused run reports partial and exits 0. Setup and teardown still run, but omitted checks remain unproven. Run plain stacks verify after the repair and require green before the completion handoff. The command reference lists the selection flags.

Automation must inspect the outcome as well as the process exit. Use machine-readable output when another script decides whether the work passed:

Machine-readable result
stacks verify --json

The result is one VerifyResult on stdout, with live step events on stderr. Read its outcome field; both green and partial exit 0. A failed step or changed verification procedure exits 5. The output and exit-code reference describes the result contract.

A changed outcome means the recorded procedure no longer matches its digest, so nothing ran. With the local state record present, verify compares the steps, environment defaults and preset against both recorded copies. The agent should report the change and stop. A person can review and accept an intentional change from a terminal; that acceptance is refused under a detected agent.

The digest doesn't protect the contents of tests or the code a step executes. An emptied test target can still return success. Review those diffs, and remember that a fresh clone has only the manifest's digest until it has a local state record. Keep deleted assertions and weakened lint settings in the code review even when verify is green; the guide to stopping Claude Code from changing tests covers deny rules for test paths.