At 09:16 the coding agent saves its second edit of the morning. It is working on services/orders/handlers/create_order.py, adding the optional field delivery_note to the order API for work item ORD-2187. The edit leaves a variable called note that nothing uses. It is a small mistake, and on its own it breaks nothing.
The agent does not notice. It moves on to the serializer, the model and the tests, and builds four more files on top of the handler.
If nothing checks the edit, the first signal arrives minutes later, from CI, after the commit and the push. By then the agent has finished, the developer has moved to something else, and a one-line fix costs a CI run and a second look at work everyone thought was done.
Times and durations on this page are illustrative.
A check that runs after every edit must be fast and deterministic. A check that needs judgment belongs later, where it runs once.
1. Why the cheapest check runs inside the editing loop#
The developer gives the coding agent one task and lets it work. The agent reads files, asks for an edit, reads the result, asks for the next edit, runs a command, and repeats until it decides it is finished. Everything it does between receiving a message and handing control back is one turn. For ORD-2187, one turn produces six edited files.
During that turn, the agent holds the whole task in its context: the work item, the files it read, the reason for each edit. A mistake found now is fixed in seconds, by the same agent, with nothing to re-explain. A mistake found after the commit needs a new session, and after the pull request opens it also needs a CI run and other people's attention. So the cost of the same mistake rises at every stage after this one, and the editing loop is the cheapest place there will ever be to find it.
That raises an obvious question: what should check the work here, and when? The two ideas most teams try first both fail, for different reasons.
2. The first idea: tell the agent to run the linter#
The simplest approach costs nothing to set up. Add a line to the project's instructions: "After every edit, run the linter on the file you changed." A capable agent often does exactly that.
The trouble is the word "often". An instruction is text that the model weighs together with everything else in its context, and late in a long session, with dozens of files read, it can be skipped. Nothing records whether it ran, so nobody can tell a clean file from an unchecked one. The cause is that the check is one of the model's choices, and a choice can go the other way.
The fix is to take the check out of the model's choices.
The software that runs the agent can start a command itself, at a fixed moment, every time: after each edit, or when the agent tries to finish. That software is the harness (the program that runs and controls the agent: it runs the tools, applies permissions and starts these commands).
The command is a hook: a script the harness executes when a named event happens. The model does not decide whether a hook runs. It only sees what the hook reports, and reacts to it. An instruction guides the model; a hook runs on every edit, whether the model remembers or not.
3. The stronger idea: ask a model to review every edit#
Once hooks exist, a more ambitious idea follows. A linter catches unused variables, but not a handler that validates the wrong thing. Why not have a model look at each edit and say whether it is good? In Claude Code this is one entry in the settings: besides shell commands, a hook can send a prompt to a model, or start a small agent that reads files before it answers.
It fails because of how often the editing loop runs.
The agent may make dozens of edits in one task, so a model review after each one multiplies cost and delay by the number of edits. It also judges a file in the middle of a change, which is often incomplete on purpose: the handler reads a field the model class does not have yet. And a model's verdict can vary between runs, so the agent cannot tell whether its fix worked or the reviewer simply answered differently this time. The cause is a mismatch: a check that needs judgment is placed where the work is unfinished and the check runs dozens of times.
Judgment still matters. It belongs where the change is complete and the check runs once: a model reviews the whole diff at the pull request stage.
4. The careful idea: run everything, every time#
The opposite instinct is to be thorough: run the type check and the full test suite after each edit, or at least before the agent finishes. Nothing would get past it.
Two things break it.
The first is arithmetic. Suppose an agent makes fifty edits in one task and the check after each edit takes two seconds: that adds 50 x 2 = 100 seconds, close to two minutes, of waiting to one task. A full suite that takes minutes, run fifty times, makes the agent unusable.
The second is reach. The end-to-end tests need a complete running copy of the system, and a laptop cannot hold one. So "everything" is not available here at any price.
The three failures point at the design. The check must run outside the model's choices (section 2). It must be deterministic and cheap enough to run dozens of times (section 3). And the expensive part must run once, not per edit (section 4).
5. The design that holds: one fast check per edit, the affected tests before the agent stops#
The design splits the work by how often each moment happens. After each edit, a hook formats and lints the one file that changed. It is fast because it sees one file, and it is deterministic because a linter gives the same answer for the same file.
When the agent tries to end its turn, a second hook runs the type check for the service and only the tests affected by the change. That runs once per attempt to finish, so it can afford a minute or two. A model does not take part in either check.
The sequence below shows who acts. The model asks for edits. The harness performs them and starts the hooks. The hooks report back, and the model reacts.
Diagram: The editing loop · who checks what, and when
Time runs down the page. The model asks for edits; the harness runs them and fires the hooks. The model never decides whether a hook runs. It only sees the result.
- Developer to Coding agent: Task: add delivery_note. The developer states the task once.
- Coding agent to Hook after edit: Edit written to one file. The harness fires this hook after every edit tool call. The edit has already happened.
- Hook after edit to Coding agent: F841 on line 27. The hook returns a block decision with a reason. The model reads it as feedback and fixes the line.
- Coding agent to Hook after edit: Edit written again. Same hook, same file.
- Hook after edit to Coding agent: Clean. Exit code 0. Nothing is added to the conversation.
- Coding agent to Stop hook: I am finished. The model tries to end its turn. The harness fires the stop hook first.
- Stop hook to Coding agent: 1 affected test fails: continue. Exit code 2 with the failures. The harness keeps the agent working.
- Coding agent to Stop hook: Fixed. Finished. The agent edits, the after-edit hook passes, and it tries to stop again.
- Stop hook to Coding agent: 14 tests pass. Exit code 0. The turn ends. Had they still failed after this one send-back, the hook would let the agent stop and log it.
- Coding agent to Developer: Done, with the tests it ran. The developer gets a change that already passed the cheap checks.
Notice what the model never does: start a hook, or skip one. A check that depends on the model's memory became a check that depends only on the harness.
The design uses three moments in all. The third guards commands rather than edits, and it belongs to the next stage.
| Moment | Hook event | Job | Budget |
|---|---|---|---|
| After each edit | PostToolUse on the edit tools | Format and fast lint, the changed file only. Send failures back to the agent. | Well under a second |
| Before the agent stops | Stop | Type check the service, then run the tests affected by the change. If they fail, send the agent back to work. | A minute or two |
| Before a risky command | PreToolUse on the shell tool | Stop a command before it runs. Acme's only one guards git push. Covered on the Commit page. | Under 5 seconds |
Three parts act at each moment, and they are worth keeping apart.
The harness runs the hook. The hook script decides pass or fail. The model only sees the result as feedback and reacts to it.
The facts about each event, such as what input it receives and whether it can block, are on the Hooks reference page.
The budget column follows from the arithmetic in section 4. An agent can make fifty edits in one task, so a two-second check after each edit adds almost two minutes; the after-edit hook must stay near-instant, and anything slower moves to the stop moment, which happens once or twice per task.
With the design in view, the five approaches can be compared side by side.
| Approach | What it buys | What goes wrong | Use it when |
|---|---|---|---|
| A. Instructions only (tell the agent "always run the linter") | Zero setup | The model can skip it in a long context. Nothing proves it ran. | A prototype, one person |
| B. Deterministic hook after each edit | Errors corrected while the context is fresh. Runs every time. | Slow hooks make every edit slow. A one-file check misses the callers it broke, and a mid-change file is often wrong on purpose. | Always, for format and lint on the changed file |
| C. Model-based hook after each edit (ask a model "is this edit good?") | Catches things a linter cannot | Runs on every edit, dozens of times per task. Cost and delay multiply. Its verdict can vary between runs. | Almost never in the inner loop |
| D. Type check and tests at the stop moment | The agent cannot declare "done" on red tests | A flaky test could trap the agent in a loop. The script must not send it back forever: if the tests still fail after one send-back in the same turn, it lets the agent stop and records why. | Always, with affected tests only |
| E. Full test suite at the stop moment | Highest confidence before commit | Minutes per attempt, and end-to-end tests cannot run on a laptop | Small repositories only |
Recommended default: B plus D. Approach B catches the cheap mistakes within a second of making them. Approach D catches the ones that only show when the files work together, once, before the agent says it is done. Approach C stays out of the editing loop; a model reviews the whole diff once, at the pull request stage.
6. How the two hooks are wired#
The configuration below is what puts B and D in place at Acme. It shows two things: which event starts which script, and the time limit for each. A successful run of it proves only that the harness starts the scripts at the right moments. Whether a script checks the right things is up to the script.
Hooks live in the project's .claude/settings.json. The file is committed, so every developer gets the same hooks, and so does every CI run of Claude Code started without --bare (a mode that loads only what flags name).
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{ "type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/check-changed-file.sh",
"timeout": 20 }]
}],
"Stop": [{
"hooks": [{ "type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/affected-tests.sh",
"timeout": 180 }]
}]
}
}
The matcher limits the first hook to the two edit tools. The timeout values, in seconds, are ceilings for a hung script, not targets: the after-edit check should finish far below 20 seconds. The Stop entry has no matcher, because that event runs on every attempt to stop.
The two scripts are small. check-changed-file.sh reads the edited file's path from the hook input and, for a Python file, runs ruff check on that one file. affected-tests.sh runs pyright on the service, then passes the changed files to the team's shared selector, tools/affected-tests.sh, which the pre-push git hook and CI also call.
The stop script has one more rule, and it removes the loop risk named in approach D. If the tests still fail after one send-back in the same turn, it lets the agent stop and appends a line to .claude/stop-gate.log. The full scripts are on the Hooks page: after each edit and before the agent stops.
Each script talks back to the agent in one of two ways, and the two events differ.
| Hook | To pass | To send the agent back to work |
|---|---|---|
PostToolUse | Exit 0 | Print JSON with "decision": "block" and a "reason", and exit 0. The edit already happened; the reason tells the agent what to fix. |
Stop | Exit 0 | Exit 2 with the failure on standard error, or JSON with "decision": "block". The agent continues. |
A pass from these hooks is narrow evidence. It says the changed files are lint-clean, the service type checks, and the tests the selector chose pass. It does not say the change is right, that the selector chose every test that matters, or that another service still works.
7. One change through the loop: #4812, 09:12 to 09:31#
The design now meets the running example. What enters: the task from work item ORD-2187, "Let a customer add delivery instructions to an order". What must leave: six edited files on the branch feat/order-delivery-note that pass lint, the type check and the affected tests. No commit exists yet.
| Time | What happens | Who acts | Result |
|---|---|---|---|
| 09:12 | The task is given to the coding agent | The developer | The agent starts to read services/orders |
| 09:14 | First edit: api/openapi/orders.yaml | The model asks; the harness writes the file and runs check-changed-file.sh | Clean |
| 09:16 | Second edit: services/orders/handlers/create_order.py. ruff runs on that one file. | The model, then the PostToolUse hook script | One lint error. The script returns it as feedback. |
| 09:17 | The unused variable is removed | The model | The hook script runs again. Clean. |
| 09:18 to 09:28 | The other four files are edited | The model | Every edit passes the hook |
| 09:29 | The model says it is finished | The model; the harness fires the Stop event | The harness starts affected-tests.sh |
| 09:29 | pyright, then the affected tests | The Stop hook script | test_create_order.py fails. Exit code 2. The agent must continue. |
| 09:31 | services/orders/serializers.py now returns the field. The agent stops again. | The model, then the same hook script | 14 tests pass. The agent stops. |
Two outputs from that morning show what the model actually reads. The first demonstrates the after-edit hook doing its job: one file, one error, a precise instruction, under a second. It proves the hook caught an unused variable. It says nothing about whether the handler is correct.
The PostToolUse hook script printed this at 09:16. The harness placed the reason next to the edit's result, where the model read it.
{
"decision": "block",
"reason": "Lint failed on services/orders/handlers/create_order.py. Fix these lines, change nothing else:\nservices/orders/handlers/create_order.py:27:5: F841 Local variable `note` is assigned to but never used\nFound 1 error."
}
The second shows why the stop moment exists. Every file was lint-clean, yet the change did not do what the task asked: the response had no delivery_note. Only a test that exercises the files together could see that. It proves the agent could not declare "done" on a red test; it does not prove that 14 tests cover the change.
The Stop hook script wrote this to standard error at 09:29 and exited with code 2. The output is illustrative.
affected-tests.sh: pyright services/orders: 0 errors
affected-tests.sh: 1 test file selected from the diff
FAILED services/orders/tests/test_create_order.py::test_response_includes_delivery_note
assert "delivery_note" in response.json()
AssertionError: the response has no key "delivery_note"
1 failed, 13 passed in 3.4s
The same stage can end in three ways. #4812 took the first path, after the second path twice; the third is a labelled "suppose".
| Outcome | What happened | What happens next |
|---|---|---|
| It passes | At 09:31 lint, the type check and the 14 affected tests are clean | The agent stops. The change goes to the commit. |
| A check stops it and the agent fixes it by itself | This is what happened twice: the unused variable at 09:16 and the failing test at 09:29. Each time the model read the hook output and corrected the file. | The same check runs again and passes. No person was needed. |
| A check stops it and a person must decide | Suppose the agent's fix at 09:31 had not worked, and the tests still failed after that one send-back. The script then lets the agent stop and writes why to .claude/stop-gate.log. | The developer reads the failure and decides: give the agent a hint, or fix the code by hand. Whether the test or the code is wrong is a judgment the hook must not make. |
8. Limits of the editing loop#
The design is cheap and reliable, but it has edges. Each one below is a place where the loop does less than it seems to.
| Limit | Why it matters |
|---|---|
A PostToolUse hook cannot undo the edit | It reports after the fact. To prevent an edit, use PreToolUse or a deny rule. |
| The after-edit hook sees only the edit tools | In Claude Code, a hook matched to the edit tools does not run when a shell command, or a program outside the agent, rewrites the file. The Stop hook still sees the result, because it checks every changed file. |
| The stop loop is capped | Claude Code ends the turn after 8 stop-hook continuations in a row. The count resets when the agent calls a tool, so a loop that keeps editing is not capped by this. Acme's script stops sending the agent back after one retry; bound unattended runs with a turn limit and a budget as well. |
| A hook that times out renders no decision | The harness cancels it and discards its output. For the Stop hook, that means the agent stops unchecked, and onFailure has no effect on Stop hooks. Set the stop timeout above the slowest expected test run, and keep the selection small. For guards that must fail closed, set onFailure explicitly (see Commit). Give every unattended run a total turn limit and time limit as well. |
| Project hooks wait for workspace trust | In an interactive session, Claude Code runs hooks only after the developer accepts the workspace trust dialog for the folder. A -p run does not show the dialog and runs the project's hooks. |
| Hooks are not a security boundary | They see what the agent does through its tools. A developer can work outside the agent. The gate is on the server; see Commit. |
9. Side questions#
| Question | Short answer |
|---|---|
| Why not let the agent run the linter itself? | It often will. The hook is for the times it does not, and it costs almost nothing when the file is clean. |
| What if the affected-test selection is wrong? | Then the stop hook passes and CI catches it. The hook reduces wasted CI runs; it does not replace CI. |
| Can the hook call a remote service? | Yes. Besides commands, Claude Code hooks can be HTTP calls, calls to a tool on a tool server, a prompt to a model or a small agent. Keep the inner loop local and deterministic, so it works offline and stays fast. |
| Does this work in CI too? | Yes, if the run does not use --bare. A headless run (-p) loads the same project hooks, so an agent that fixes a build in CI gets the same checks; --bare skips them. Claude Code's documentation recommends --bare for scripted calls and says it will become the default for -p, so check this after each upgrade. |
| Do other coding agents have hooks? | Many have an equivalent: a command the agent's program runs at a fixed moment. The event names and fields on this page are Claude Code's. |
At 09:31 the six files pass every check in the loop, and two mistakes are still inside them. The handler does not enforce the 500-character limit that the contract promises, and the contract lists delivery_note as required, which would break every existing client.
No hook could have caught either one. A lint rule sees one file, and the affected tests see one service; neither knows what the contract promises other teams.
The lesson is about placement, not strength. Put the checks that are fast and certain where they run dozens of times, and leave the questions that need the whole change, or a person, to the stages that see it. The review stage finds both mistakes.
Next: at 09:33 the agent turns those six files into a commit, and a different set of hooks decides whether that commit may exist. The commit.