Lifecycle Hooks for AI Coding Tools: A Practical Guide
Lifecycle hooks turn AI coding rules from things you hope the model remembers into commands that always run at specific tool lifecycle events. This guide explains when to use convention files versus hooks, the three main trigger levels (session, turn, and tool call), the shared configuration structure and exit-code protocol, and three hands-on examples: auto-formatting after edits, blocking dangerous commands before execution, and injecting real-time context into the conversation. It closes with a rollout path and common pitfalls.
1. The Starting Problem: Why Rules in a Convention File Fail
Once AI is involved in coding, teams usually accumulate a set of non-negotiable rules: format every file automatically after each change; never run destructive commands such as recursive deletes; always run static checks and tests before committing. The most common way to enforce them is to write a line in the convention file at the project root — “remember to format,” “don’t run dangerous commands.”
The problem isn’t that the model disobeys. It’s that the nature of the constraint is wrong. A convention file is essentially a prompt: it enters the model’s context, and the model decides on its own whether to comply. The longer the context and the more turns there are, the more likely such soft constraints get diluted. On top of that, they can’t be verified — you have no way to prove that formatting actually ran after a given change.
Lifecycle hooks solve a different class of problem: they turn a rule from “hope the model remembers” into “always executes when the event occurs.” A hook is a command you register in advance that an AI coding tool triggers automatically at a specific lifecycle event, usually a shell command or script. The executor is the tool itself, not the model, so the outcome is independent of the model’s state, context length, or attention distribution at that moment.
This yields a clear selection principle:
- Preferences where an occasional miss is acceptable can stay in the convention file, such as naming style preferences or the language used for comments.
- Constraints where a miss is unacceptable must be pushed down into hooks, such as security red lines, formatting consistency, and pre-commit gates.
The deciding question fits in one sentence: if what you need when a rule is violated is after-the-fact accountability, a prompt is enough; if what you need is for the violation to never happen at all, only a hook will do.
2. Three Trigger Levels: Per Session, Per Turn, Per Tool Call
Hooks attach to lifecycle events. The event models of mainstream AI coding tools in the industry roughly fall into three rhythms, and understanding these rhythms matters more than memorizing event names.
| Level | Trigger point (general description) | Can block? | Typical uses |
|---|---|---|---|
| Session | Session creation, or resuming an existing session | Generally no | Load project state, output pending items, prepare the runtime environment |
| Turn | User submits a message, before the model starts processing | Yes | Input validation, injecting live context, appending constraints |
| Tool call (pre) | Tool is about to run, no side effects yet | Yes | Intercept dangerous commands, rewrite arguments, permission checks |
| Tool call (post) | Tool finished, before the result is returned to the model | Yes | Auto-formatting, running tests, trimming and redacting results |
| Wrap-up | A turn ends or the session terminates | Generally no | Generate summaries, archive logs, clean up temporary resources |
Each level has its own role, and mixing them produces configurations that are hard to maintain:
- The session level suits “preparation,” not “validation,” because there is no clear object to reject.
- The turn level is the best place to inject content and intercept user input, since the model’s reply hasn’t been generated yet and rewriting is cheapest here.
- The tool call level is the real execution gate; all side-effect-related automation belongs here, especially the “pre-intercept + post-process” pair.
One point deserves emphasis: whether a hook can block determines how it must be designed. Validation inside a non-blocking event is meaningless — at most it can emit a warning. Only blocking events can carry real gate logic.
3. Configuration Structure and the Data Contract
Field names differ across tools, but the data contract of the hook mechanism is highly consistent, so mastering the contract makes it portable.
Configuration usually lives in a project-level or user-level config file, organized by event type into a set of matching rules, each specifying a match pattern and the command to run:
{"hooks": {"PreToolUse": [{"matcher": "Bash","hooks": [{ "type": "command", "command": "$CLAUDE_PROJECT_DIR/.hooks/guard.sh" }]}],"PostToolUse": [{"matcher": "Edit|Write","hooks": [{ "type": "command", "command": "$CLAUDE_PROJECT_DIR/.hooks/format.sh" }]}]}}
Three points matter. First, the matcher decides which class of tools the rule applies to: too broad causes collateral damage, too narrow leaves gaps, so start with a broad match, observe the logs, then tighten. Second, the command receives a JSON event object on standard input containing the session identifier, event name, tool name, tool arguments, and the tool’s result (post events only). Third, exit codes and structured output together form the decision protocol:
- Exit code 0: allow; in most events, standard output is passed back as context.
- Exit code 2: block; the content of standard error is returned to the model as the reason, and the model adjusts its next action accordingly.
- Any other non-zero: treated as an error in the script itself, usually logged as a warning without blocking the flow.
- Output JSON with decision/permission fields: enables finer-grained “allow / deny / needs human confirmation” control.
Two engineering disciplines are worth enforcing: hook scripts must be idempotent and fast, because they may fire at high frequency; and scripts must handle their own exceptions internally, so that one missing formatting tool doesn’t fail the whole turn.
4. Practice 1: Auto-Format After Changes
The post hook is the most typical automation landing point. The script parses the changed file path from standard input and formats only files inside the project that are under version control, avoiding accidental changes to dependency directories:
#!/usr/bin/env bashset -euo pipefailinput=$(cat)file=$(printf '%s' "$input" | jq -r '.tool_input.file_path // empty')[ -z "$file" ] && exit 0case "$file" in"$CLAUDE_PROJECT_DIR"/*) ;;*) exit 0 ;;esacext="${file##*.}"case "$ext" inpy) fmt=(ruff format) ;;ts|tsx|js|jsx) fmt=(prettier --write) ;;go) fmt=(gofmt -w) ;;*) exit 0 ;;esac"${fmt[@]}" "$file" >/dev/null 2>&1 || trueexit 0
The || true and exit 0 here deliberately ensure that a formatting failure doesn’t interrupt the main flow, while failure details are written to a log file for troubleshooting. If the team requires “non-compliant means you cannot continue,” switch to exit code 2 and write a summary of the formatting diff to standard error, so the model can fix it in the next turn.
5. Practice 2: Blocking Dangerous Commands Before They Run
The pre hook is the security gate. Its value isn’t recognizing every dangerous phrasing, but establishing a stable, auditable interception layer. Detection should be based on structured parsing rather than substring matching: do lexical splitting first, then match against risk patterns:
#!/usr/bin/env bashset -euo pipefailinput=$(cat)cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // empty')[ -z "$cmd" ] && exit 0risky='rm[[:space:]]+-[a-zA-Z]*r[a-zA-Z]*f|mkfs|dd[[:space:]]+if=|:\(\)\{.*\};:|git[[:space:]]+push.*--force|chmod[[:space:]]+-R[[:space:]]+777[[:space:]]+/'if printf '%s' "$cmd" | grep -Eq "$risky"; thenecho "Command blocked by security policy: this involves irreversible or out-of-scope operations. Use a reversible approach or request human confirmation." >&2exit 2fiexit 0
Three practical lessons: first, the block message must state “why” and “what you can do instead,” otherwise the model keeps trying near-variants; second, persist interception events in structured form to build an auditable security ledger; third, route high-risk but necessary operations to a “needs human confirmation” branch rather than a blanket denial, otherwise people will bypass or disable the hook.
6. Practice 3: Injecting Real-Time Context into the Conversation
The turn-level hook is best at closing the model’s “information lag.” A static convention file can’t reflect the current branch, uncommitted changes, live alerts, or the latest build status — and those are exactly the decision inputs. The script reads the event and outputs dynamic information as additional context:
#!/usr/bin/env bashset -euo pipefailcat >/dev/nullbranch=$(git branch --show-current 2>/dev/null || echo unknown)dirty=$(git status --porcelain | wc -l | tr -d ' ')cat <<EOF[Live context]Current branch: $branchUncommitted changed files: $dirtyLatest build: failed (3 unit tests failing)EOFexit 0
Context injection must be restrained: include only information strongly relevant to the current task and of manageable size, or it will crowd out the effective context window and amplify the very dilution problem soft constraints suffer from. If the runtime has a logging service, monitoring alerts, or a container platform, the hook can pull a recent alert summary through a controlled interface, but it must handle timeouts and graceful degradation — a hook must never become a blocking point for the session.
7. Rollout Path and Common Pitfalls
A four-step rollout is recommended: first, list the team’s red lines and mark each as “tolerable to miss” or not; then leave the tolerable items in the convention file and write the intolerant ones as hooks; next, run in observe-only mode (“log but don’t block”) for one to two weeks to collect false positives; finally, tighten the matching rules and wire the hooks into continuous integration, so local hooks and pipeline gates use the same set of scripts and the two standards don’t drift apart.
Common pitfalls include: running long tasks inside a hook and making the interaction sluggish; scripts depending on undeclared external commands; matchers that are too broad and modify generated files or third-party directories; vague block reasons that make the model retry repeatedly; and writing secrets into hook scripts or logs. The corresponding fixes are to set timeouts, validate dependencies explicitly, restrict paths to a whitelist, output structured reasons, and redact logs.
In the end, hooks aren’t about adding restrictions to the model — they move engineering certainty from human diligence onto the toolchain. When formatting, testing, and security checks all run automatically on events, the floor of AI output is raised, and only then can teams confidently hand it larger, more complete tasks.
