Claude Code Hooks in Practice: Make AI Run Tests Automatically After Writing Code

Use Hooks to turn soft prompt constraints into enforced automated quality gates.
This article introduces Claude Code's Hooks mechanism to solve the pain point of AI coding assistants "thinking they're done but not running tests." The core idea is that prompts and rules files are only probabilistic suggestions that the model can ignore, while hooks are deterministically triggered local scripts before and after tool calls, achieving hard blocking via exit code 2. The article breaks down three key events: PreToolUse scans and blocks high-risk commands before execution, PostToolUse automatically formats and checks syntax after file changes to save context, and Stop forces unit tests to run when the model is about to hand in work—no ending until all tests pass. Together they form a complete pipeline of pre-execution protection, post-modification cleanup, and pre-delivery testing, with a recommended rollout order of Stop→PostToolUse→PreToolUse.
Claude Code Hooks in Practice: Make AI Run Tests Automatically After Writing Code
The most frustrating thing about using an AI coding assistant isn't that it can't write code—it's that it "thinks it's done." You've emphasized in your rules file over and over: "Run tests after every code change." But when it gets busy, it just hands in the work anyway. The root cause is simple: prompts are only soft suggestions. The model can follow them, or it can ignore them.
To enforce something 100%, you need to use Claude Code's Hooks mechanism. The idea is straightforward—before and after the model executes a tool, the system deterministically triggers local scripts, turning "soft constraints" into "hard gates" and giving your AI coding assistant its own security checkpoint.

What Hooks Actually Are: Deterministically Triggered Local Scripts
Hooks are local scripts that the system triggers at fixed moments before and after the model calls a tool. They're written in the .claude-settings.json configuration file at the project root and don't rely on the model's "self-discipline"—as long as the event conditions are met, they will execute without fail.
This is the fundamental difference between Hooks and prompts: prompts request that the model follow rules; hooks are system-level enforcement. The former is a suggestion letter; the latter is a traffic light. In the video, the creator summarized this mechanism as "three core hook events + exit code 2 hard blocking." Understand these two parts, and you've grasped all the key concepts.
The entry file for hook configuration: The .claude-settings.json mentioned in the original text is located at the project root. Its core is the hooks field, grouped by event name (such as PreToolUse, PostToolUse, Stop). Each event has an array of matchers attached; a matcher can specify matcher (such as tool names Bash, Write, Edit) and a hooks list. Each item in the list declares type: "command" and a command field pointing to a local script path or command. The script receives a JSON context via standard input (including tool name, tool parameters, session information), so validation scripts can read the command about to be executed before making a judgment. Configuration supports two levels: project-level and user-level. Project-level configuration overrides user-level settings with the same name, making it easy for teams to distribute gate rules alongside the repository.
The Three Core Hook Events
PreToolUse: The First Line of Defense Before Execution
PreToolUse triggers before the model is about to execute a terminal command or modify a file. The most typical security use case is having a validation script scan the command about to be executed—once it detects a high-risk operation like force push, it immediately writes the reason to standard error and returns exit code 2.
When Claude Code receives exit code 2, it immediately hard-blocks the operation and passes the blocking reason back to the model, forcing it to find a safer approach. This is like installing a "pre-operation reviewer" for the AI—dangerous actions are cut off before they land.

Exit code semantics: The exit code of a hook script determines Claude Code's subsequent behavior. 0 means allow, 2 means block and feed the stdout/stderr content back to the model as error information, and other non-zero values mean non-blocking errors (only a warning, but the operation is not aborted). Therefore, in PreToolUse, only returning 2 can truly block a command; if the script crashes and returns 1, the operation will still continue. This is especially important to watch out for when writing security blocking scripts—it's recommended to do parameter validation and exception handling at the beginning of the script to ensure that dangerous commands reliably return 2 rather than accidentally returning 1.
PostToolUse: Automatic Cleanup After Writing
PostToolUse triggers automatically after the model finishes writing or modifying a file. The most classic use is automatically running code formatting or syntax checking.
Don't underestimate this step. AI-generated code often stumbles on small things like indentation, quotes, and line breaks. Having the model repeatedly fix these itself is slow and wastes context budget. Let the hook script handle formatting automatically, and the model can save its precious context for real logic problems.

Stop: The Best "No Handing In Yet" Gate
The Stop event triggers when the model thinks it's done and is about to return the conversation to you. This is the most powerful part of the entire mechanism: you attach automated test commands to the Stop hook, and as long as not all unit tests pass, the script returns exit code 2.
At this point, the model can't stop even if it wants to—it's forced to continue fixing bugs until all tests pass before it's allowed to hand in the work. This is exactly how "make AI run tests itself after writing code" is implemented, and it's the key step in transforming AI from a "generator" into a "responsible engineer."

The loop risk of Stop hooks: Returning exit code 2 from a Stop hook makes the model continue working, but if the tests themselves have environment issues (such as missing dependencies, test timeouts, port conflicts), the model may repeatedly try but never get the tests to pass, creating a long ineffective loop that continuously consumes tokens. In practice, it's recommended to add timeout control and a failure count limit to the Stop script (for example, recording the number of retries in the current round via environment variables or a temporary file, and after exceeding the threshold, returning 0 to allow completion with a notice). Also make sure the test command itself is fast and stable enough—avoid attaching unstable integration tests to this gate.
Three-Layer Hard Gate Combination: A Reusable Configuration Approach
String the three events together, and you get a complete quality pipeline:
- Before execution, use PreToolUse to prevent mistakes—block all high-risk commands;
- After modification, use PostToolUse for automatic formatting cleanup, ensuring consistent code style and clean syntax;
- Before handoff, use Stop to force-run unit tests—no ending the conversation until all tests pass.
The value of this combination is that it front-loads quality constraints and automates them. In the past, code review relied on humans checking line by line after AI delivery; now the gate blocks substandard output from within the process. According to the Bilibili creator's demo, this configuration can be directly used as a template in any project.
Why This Is More Reliable Than Writing Prompts
From an engineering perspective, Hooks solve the most fundamental trust problem in AI programming. Model output is uncertain, while engineering processes require certainty. Prompts, rules files, and system instructions are all probabilistic constraints—the same rule works this time but may be ignored next time. Hook scripts are deterministic—trigger conditions are hardcoded in the configuration, and execution results are predictable and reproducible.
This also means that the way we use AI programming tools is shifting from "training the model" to "building processes." Rather than repeatedly reminding the model to run tests, it's better to weld testing into the delivery step with a few lines of script.
The boundary between probabilistic and deterministic constraints: LLM behavior is determined by sampling from probability distributions. System prompts, CLAUDE.md rules files, and conversational reminders only increase the probability that the model follows rules—they cannot guarantee 100% execution, especially after long contexts and multiple rounds of tool calls, where the weight of early instructions gets diluted. Hooks, however, run in the host program outside the model, belonging to the control plane rather than the generation plane. Their triggering and exit code judgments are ordinary program logic, unaffected by sampling randomness. This also explains why the industry generally adopts a layered design of "model handles planning and generation, external programs handle validation and blocking" when building Agent systems: moving high-reliability requirements from inside the model to outside the model is a key engineering approach for taking Agents from demos to production.
Getting Started Tips
If you're ready to implement this in your own project, start with a minimal viable configuration: first add only the Stop hook to run unit tests and experience the effect of "the model getting stuck and continuing to fix bugs." Once you confirm the flow works smoothly, add PostToolUse formatting, and finally add PreToolUse high-risk command blocking. After these three steps, your AI coding assistant transforms from an "enthusiastic but forgetful intern" into an engineering team member with built-in gates.
Related articles

Big Tech Architect Reveals: From Vibe Coding to Agent Full-Stack Development in Practice
A ByteDance-background architect shares the AI Coding advancement path: from Vibe Coding to Agent full-stack development, covering interview dimensions, SDD/TDD practices, AI efficiency implementation, and full-stack learning routes, with a seven-question self-check framework.

ByteDance Architect Breaks Down Full-Stack AI Coding Practices: From Vibe Coding to Agent Deployment
A ByteDance architect's perspective on the AI Coding progression path: from Vibe Coding to Spec Coding to full-stack Agent product deployment, covering interview focus areas, engineering use of SDD/TDD, team-level AI efficiency system design, and the full-stack skill stack—suitable for developers interested in AI programming and upgrading development models.

OpenUI: An Open Standard for Generative UI
OpenUI (thesysdev/openui) is an open standard for generative UI written in TypeScript with 16K+ GitHub stars. This article analyzes its positioning and value.