AI Coding Hooks: Automating Formatting and Security Checks
Relying on convention files to enforce coding standards is unreliable because they are prompts for the model rather than rules enforced by software. This article explains how hooks solve that gap by triggering predefined commands at fixed lifecycle points of an AI coding tool, regardless of the model's state. It covers the three mounting layers (session, prompt submission, and pre/post tool use), the configuration structure, and the three ways a hook returns a decision: exit codes, structured JSON output, and silent modification. Three practical examples are included: auto-formatting after file writes, blocking dangerous commands before execution, and injecting real-time context before the model sees a request. The article closes with adoption advice and common pitfalls.
1. The Problem: Why Conventions Written as Prompts Are Not Reliable
When teams use AI coding tools, they usually maintain a convention file that spells out coding style, pre-commit checks, and prohibited operations. The value of these conventions is clear, but the enforcement mechanism has an inherent flaw: they are prompts for the model to read, not rules enforced by a program. The longer the context and the more complex the task, the higher the chance the model misses one of the conventions. More critically, adherence is neither observable nor reproducible—you cannot prove that a given rule was applied this time.
Three categories of engineering requirements cannot tolerate even a single miss:
- Safety red lines: for example, no recursive deletion, no force push, no rewriting committed history;
- Formatting consistency: for example, format on save, zero static-check warnings;
- Pre-commit quality gates: for example, unit tests must pass, dependency vulnerability scans must show no high-severity findings.
Handing these requirements to a prompt outsources determinism to probability. The right approach is to hand them to hooks—commands that the tool automatically triggers at fixed lifecycle points, independent of the model’s state at that moment.
2. What Hooks Actually Are: From “Hope It Remembers” to “It Always Runs”
A hook is a command you define in advance and that the AI coding tool executes automatically at a specific moment, usually a script or a single command-line call. When an event occurs, the tool fires the hooks attached to it and passes context data through standard input or arguments. Once the hook finishes, it signals “allow” or “block” via its exit code or structured output.
The boundary with convention files is clear:
| Dimension | Convention file (prompt) | Hook (program execution) |
|---|---|---|
| Who executes | The model judges on its own | The tool runtime |
| Determinism | Probabilistic, may be missed | Runs whenever the event fires |
| Observability | Hard to verify | Logs and exit codes available |
| Fit | Style preferences, design advice | Safety, formatting, quality gates |
The rule of thumb is simple: any rule that causes a problem if missed once should be pushed down to a hook.
3. Lifecycle Mounting Points: Three Cadences
Hooks attach to lifecycle points of a session and fall into three layers by trigger frequency.
Per session: triggered when a session starts or resumes, suitable for loading project state, initializing a virtual environment, or printing outstanding TODOs. This layer only does preparation and usually does not need blocking capability.
Per conversation turn: triggered when the user submits a message, before the model processes it, suitable for validating input and injecting live context (current branch, list of changed files, summary of failing tests). This layer can block, keeping a non-compliant request from ever reaching the model.
Per tool call: the finest-grained and most critical layer, with two timings, before and after the call.
- Before: triggered before a command or file write actually executes; it can read the full arguments and decide to allow or reject, making it the main battleground for safety red lines;
- After: triggered after the action is complete but before the result is returned to the model, suitable for formatting, generating signatures, and appending audit logs; it can also feed results back to the model by modifying the output.
Together, the three layers form a complete loop of prepare, validate, and backstop.
4. Configuration Structure and Decision Mechanisms
Hook configuration is usually grouped by event, with several matcher rules and commands under each group. An illustrative configuration follows (pseudocode, structure only):
{"hooks": {"PreToolUse": [{ "matcher": "Bash", "command": "scripts/guard.sh" }],"PostToolUse": [{ "matcher": "Write|Edit", "command": "scripts/format.sh" }],"UserPromptSubmit": [{ "command": "scripts/inject-context.sh" }]}}
Once a hook has the data, it has three ways to respond:
- Exit code: 0 means allow; non-zero means failure, and standard error is passed back to the model as feedback;
- Structured output: return JSON with a decision field on standard output to explicitly express “reject execution” with a reason; some events also support adding context or updating the input;
- Silent modification: a post-call hook rewrites the file or output directly, achieving “format as you go”.
Engineering recommendations: keep matcher rules as narrow as possible to avoid a global hook slowing down every call; scripts must have timeouts and be idempotent; log all blocking behavior in a structured form for auditing and review.
5. Three Common Practical Scenarios
Scenario 1: Auto-format after a write. Mounted after the tool call and matching file-write actions, the script checks the file extension and invokes the corresponding formatter, overwriting the file in place. Key point: failures must not block the main flow—warn only, so a formatter exception does not abort the task.
#!/usr/bin/env bash# Pseudocode: read event data and format by extensionf=$(jq -r '.file_path' )case "$f" in*.py) ruff format "$f" ;;*.ts|*.js) prettier --write "$f" ;;esac
Scenario 2: Block dangerous commands. Mounted before the tool call and matching command-execution actions, it uses a strategy of allowlist first with a denylist as backstop: when patterns such as recursive deletion, force push, or global history rewriting are matched, it returns a rejection and passes the reason back to the model so it switches to a safe approach.
#!/usr/bin/env bashd=$(jq -r '.arguments.command' )if echo "$d" | grep -Eq 'rm[[:space:]]+-rf|push[[:space:]]+--force|reset[[:space:]]+--hard'; thenecho "Dangerous operation blocked by security policy. Please use a non-destructive approach." >&2exit 2fi
Scenario 3: Inject live context. Mounted before the user submits a message, the script collects the current branch, changed files, and the latest test result, assembles them into a short summary, and outputs it so the model can act on it without manual copy and paste. Note: control the injection size and include only conclusive information so it does not eat into the context budget.
6. Adoption Advice and Common Pitfalls
- Layer responsibilities: prompts handle “how to do it better”, hooks handle “what must be done”;
- Least surprise: hook behavior should be predictable and switchable off; maintain one shared configuration in the team and put it under version control;
- Performance first: pre-call hooks must be fast; make heavy work asynchronous or cached;
- Portability: avoid depending on single-platform features in scripts; declare paths and interpreters explicitly;
- Observability: both blocking and formatting should produce logs, feeding into a common logging service with monitoring and alerting to form a quality trend dashboard.
In engineering practice on cloud platforms such as Baidu AI Cloud, these “deterministic gates” are typically combined with general capabilities like pipelines, container platforms, and logging with monitoring and alerting: hooks guarantee compliance for a single action locally, while the pipeline performs a second check at merge time, forming a two-layer defense. Once you understand the mounting points, data structure, and decision mechanisms, you can turn any rule that “must never be missed” into a verifiable, auditable automation capability.
