Skip to content
◀ Blog

Make a coding agent run tests before it's done

Instructions only ask an agent to run tests. One verify command for every gate, plus a Stop hook that blocks the finish until it passes, makes it happen.

Riley Hilliard9 min read

agentsclaude-codetesting

To make a coding agent run tests before it says done, take the decision away from the agent. Put every check the project has behind one verify command, then wire a hook or a loop that won’t accept the end of the turn until that command passes. A line in CLAUDE.md or AGENTS.md asking the agent to run the tests is a request it can forget. A Stop hook that exits 2 when the build is red is a rule it can’t skip.

Two gaps survive even a good test suite: whether the app actually starts, and whether the tests the agent wrote test anything.

Why do coding agents say done when tests fail?

The agent decides when it’s finished, and it decides from what it has seen. If it ran one test file after its last edit and that file passed, then as far as it knows the work is done. It didn’t see the lint error in a file it touched an hour ago, the type error the test runner doesn’t check, or the build that fails because an import only resolves in dev.

A false “done” usually traces back to one of these:

  • It runs a subset. Running the one test file that covers the change is the right move while iterating, and the wrong last step.
  • It runs the wrong thing. npm test passes and tsc was never run, or the tests pass and nobody built the production bundle.
  • It reads a pass from the wrong signal. A test command filtered to a path that matches nothing exits 0 with zero tests run. A pipe like pytest | tee log.txt reports the exit status of tee.

Instructions help with the first one and do little for the other two, because the agent follows them with whatever command it believes is the test suite. Instructions are also advisory. The model weighs them against everything else in a long session, and over enough turns some of them lose.

What should “done” mean for a coding agent?

Done should be a command with an exit code, written down before the agent starts, that the agent cannot edit. For most projects that command runs, in order:

Gate What it catches
Install A dependency added to code but not to the manifest or lockfile
Lint Style and the cheap bug classes your linter knows
Typecheck Type errors the test runner doesn’t report
Tests Behavior regressions
Build Production-only failures: bundling, static generation, env vars
Serve An app that builds but doesn’t start or answer a request

The command should run every check even after one fails, so a single run reports everything that’s broken and the agent doesn’t fix lint, rerun, and only then learn about the type error. “Passed” should mean every gate ran. A run that skipped the slow tests to go faster passed something, but it isn’t done.

How do you make one command check everything?

Start with whatever your project already has. A Makefile target or a package script is enough:

verify:
	bun install --frozen-lockfile
	bun run lint
	bun run typecheck
	bun run test
	bun run build

This stops at the first failure, which is fine for a first version. Name it in your instruction file as the definition of done (“the task is finished when make verify exits 0”), so the agent and the hook agree on one command. The hook in the next section enforces it.

Keep the agent out of the command itself. An agent stuck on a failing test for long enough will find that deleting the test step makes the problem go away. In Claude Code you can deny edits to the file that defines the checks with a permission rule in .claude/settings.json; this site’s settings deny Edit(./.stacks/manifest.json) for that reason.

Can a Stop hook make the agent run tests before it says done?

Yes. Claude Code runs Stop hooks when the main agent finishes responding. A command hook that exits with code 2 prevents the stop: Claude Code passes the hook’s stderr back to Claude as the reason, and the conversation continues so it can act on it. Exit 0 lets it stop.

Register the hook in .claude/settings.json. Stop doesn’t take a matcher:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "bash \"${CLAUDE_PROJECT_DIR}/.claude/hooks/verify-on-stop.sh\"",
            "timeout": 900
          }
        ]
      }
    ]
  }
}

Command hooks time out after 600 seconds by default, and a timed-out hook renders no decision, so set timeout above the slowest full run you expect. The script:

#!/usr/bin/env bash
# Keep the agent working until `make verify` passes.
cd "$CLAUDE_PROJECT_DIR" || exit 1

# Nothing changed this session: let it answer questions without a full run.
if [ -z "$(git status --porcelain)" ]; then
  exit 0
fi

if output=$(make verify 2>&1); then
  exit 0
fi

{
  echo "make verify failed. Fix the code or config it exercises, not the checks."
  printf '%s\n' "$output" | tail -n 40
} >&2
exit 2

The git status check keeps the hook from running a full build after every conversational reply. The last 40 lines of output go to stderr because that text becomes Claude’s next instruction, and a page of install logs is a worse instruction than the failing assertion.

Claude Code also stops a Stop hook from blocking forever. The Stop input includes stop_hook_active, which is true when the agent is already continuing because of a stop hook, and Claude Code ends the turn anyway after stop hooks have continued it eight times in a row. That count resets each time Claude calls a tool, so an agent that keeps editing and rerunning stays in the loop, and one that only replies “done” again gets cut off. If you’d rather give it exactly one retry, read stop_hook_active from the JSON on stdin and exit 0 when it’s true.

If you’d rather not write a script, the hooks docs point to /goal, a built-in shortcut for a session-scoped prompt-based Stop hook.

Why run a live server probe and not just tests?

Tests exercise the code the test runner can import. They don’t start the app. A web project can pass every unit test and still crash on boot because a route file has a syntax error the tests never load, an environment variable is read at startup, or the dev server binds to a port that’s already taken.

The probe is small: start the server in the foreground, request a URL until it answers or a deadline passes, then stop it. Before you start, check that nothing already answers on that port, or a stale server from an earlier session will pass the probe for you. After you stop it, check that the server is gone, so the next run starts clean.

What does stacks verify add?

Stacks, our project starter for coding agents, builds this loop into the CLI. stacks new records the project’s checks as verify steps in .stacks/manifest.json, and stacks verify runs exactly those steps and nothing else. This site’s manifest has six: make install in the setup phase, then make lint, make check (typecheck), make test and make build as checks, then make dev as a serve step probed at http://localhost:${PORT_WEB}/ within 60 seconds.

Stacks / local terminal
LOCALREADY

Choose a command to watch it run, or type your own below.

STEAMFIELD / LOCAL SESSION
Explore the starter behind this site.
This is a simulation. No files or commands leave your browser.
Type help, or choose a command below.

Enter runs · ↑ ↓ history · Esc / Ctrl+C stops · Tab moves between controls. This is a local simulation; no commands are executed.

Local demo ready.

Fig. 1 A simulated project session with an abridged brief and recorded verification output. Source: this site's scaffold preview and historical verification

How verify handles each of the gaps above:

  • Setup stops at its first failure. Every check step runs, so one run reports every failing check. Teardown always runs, after a failure or a Ctrl+C too.
  • A serve step fails without starting when its port already answers. Verify polls the URL every 500 ms until it gets any status below 500, and fails the step if the server exits before the probe passes or still answers after its process group was stopped.
  • A run ends green, partial, failed or changed. Only green is done. A run narrowed with --only or --skip-tag that passes is partial: exit 0, never done. A failed step exits 5.
  • new records a digest of the steps in the manifest and in a state record outside the project. If either copy disagrees, verify runs nothing and reports changed with the steps that were edited, added or removed. Only stacks verify --accept-changes records new steps, and it refuses when it detects an agent or stdin isn’t a terminal.

When stdout isn’t a terminal or an agent is detected, the output leaves out the rows for passed steps and ends with what to do next. A failing test looks like this (timings and the assertion are illustrative):

verify: failed (full run; 5 passed, 1 failed, 0 skipped; 48.2s)

  failed   check     test     (exit 1, 9.4s)
      | AssertionError: expected '/blog/x/' to be '/blog/x'

Next: fix the code or config these steps exercise, not the steps, then run stacks verify again.

To drive the hook from Stacks instead of a Makefile, run stacks verify --json and check the result’s outcome field rather than the exit code, since a partial run exits 0:

outcome=$(stacks verify --json 2>/dev/null | jq -r '.outcome')
[ "$outcome" = "green" ] && exit 0

On changed, don’t keep the agent looping: no amount of editing will fix it. The person has to accept the new steps or undo them.

What about tests the agent wrote itself?

A gate is only as strict as the tests behind it, and an agent writing tests for its own code has every reason to write ones that pass. Watch for tests that assert on mocks of the thing under test, snapshot whatever the code currently returns, or catch the exception and assert nothing. Weakened checks look similar: a lint rule turned off, a skip added, a server step that serves a stub page instead of the app.

For a bug fix, have the agent write the failing test first and show it failing before the fix; a test that never failed hasn’t proven it can. Prefer tests that run real dependencies over mocks, so a passing test means the code worked. Then read the test diff in review with the same care as the code diff, since that’s where a weakened check shows up.

Stacks’ agent skill puts the same rule in writing: don’t make commands pass without doing their job, skip tests, lower lint settings until they report nothing, or serve a stub instead of the app. The digest check catches edits to the verify steps themselves, but a test that passes without testing anything has to be caught in review.