Git hooks for AI engineering
By Flavio
Tagged: Git
Use Git hooks as deterministic guardrails for AI coding agents, with fast checks before commits, stronger checks before pushes, and CI as the final gate.
AI coding agents can rewrite a lot of code in seconds. That speed is great, until small mistakes slip past you because things moved too fast. An agent can forget to run a test, stage an unrelated file, or break a project rule without noticing.
Git hooks give you a deterministic checkpoint right inside Git itself. Whenever a Git event happens, the hook runs, whether the commit came from Cursor, Codex, Claude Code, a desktop Git client, or your own terminal. That makes them a great fit for repos where AI agents do a lot of the editing.
Why Git hooks fit AI engineering
We already write plenty of instructions for agents, whether in an AGENTS.md, project rules, a prompt, or a detailed plan. Those instructions steer the agent in the right direction, though an agent can still drift or skip a step before committing.
A Git hook checks the change right before it enters history. It runs the exact same command every time and blocks the commit if anything fails. I rely on instructions to explain how the project works and what conventions to follow, then let Git hooks catch quick, mechanical mistakes locally before CI verifies everything on a clean machine. Turning those repeatable checks into scripts saves you from spotting the same avoidable errors by hand during review.
Git hooks and agent hooks are different
The word hook comes up in two different places when working with AI tools, and it’s easy to mix them up.
An agent hook triggers around something the agent does, like right before it runs a shell command or right after a tool call. In Claude Code, you can even handle that inside the session with a mod instead of calling an external command.
A Git hook, on the other hand, triggers around Git’s own lifecycle events:
pre-commit
commit-msg
post-commit
pre-push
Because agent hooks live inside a specific tool, they only fire when you use that tool. Once you have a couple of different agents, an IDE, and your terminal all touching the same codebase, Git is the one boundary every change has to cross before it gets committed or pushed. That’s why I prefer Git hooks for repository-level checks, since every tool hits them automatically.
Where Git hooks live
Git stores local hooks inside its hooks directory. Don’t assume the path is always .git/hooks, since a repository’s configuration can point somewhere else. You can ask Git for the exact path directly:
git rev-parse --git-path hooks
Inside that directory, you’ll probably see files ending in .sample. Git ignores those until you remove the .sample suffix and match the exact hook name.
The file also needs to be executable, so update its permissions once you create it:
chmod +x .git/hooks/pre-commit
Whenever a hook silently does nothing, the filename and permissions are the first two things to check.
Start with a fast pre-commit check
A pre-commit hook runs right before Git creates a commit. If you’re working on an agent-built JavaScript project, a good starting script looks like this:
#!/bin/sh
git diff --cached --check || exit 1
npm run check:commit
Save that file as .git/hooks/pre-commit and make it executable. The first command inspects the staged patch for whitespace errors and unresolved conflict markers, and the second calls a normal project command.
Your project might define that command like this:
{
"scripts": {
"check:commit": "npm run lint && npm run test:fast"
}
}
The exact checks depend on the repo, just keep them fast enough that running them on every commit doesn’t feel painful.
Git checks the exit status of the hook: 0 lets the commit go through, and anything non-zero aborts it. When an agent hits a failed hook, the loop works nicely:
- the agent edits the code
- the agent tries to commit
- the hook flags a problem and stops the commit
- the agent reads the error and fixes it
- the next commit goes through
Because the agent sees the failure output right in its terminal, it can usually fix the issue on its own without you stepping in.
Make failures easy for an agent to fix
Agents recover much faster when a check points to a concrete problem. A vague error like this doesn’t help much:
Validation failed
Compare that with a message that tells you what broke:
src/auth/session.ts imports src/ui/modal.ts
Server code cannot import browser components.
Print the file, the rule that failed, and the expected fix whenever you can. It helps humans just as much as agents, because nobody wants to dig through a hook script just to figure out why a commit got rejected.
Put project rules in normal scripts
I like to keep Git hook files short. Ideally, the hook just calls a normal project command:
#!/bin/sh
npm run check:commit
Put the real checks in package.json, a shell script, or a small program under scripts/. That way you get one command that works in every context:
npm run check:commit
An agent can run it before committing, the Git hook runs it again at commit time, and CI can call the exact same command later. Keeping the checks in regular project files also means nothing important gets buried inside .git.
Use hooks to protect architectural boundaries
Linting and tests are the obvious checks, though hooks can also enforce rules specific to your own codebase. For instance, a project might require that:
- browser code never imports server-only modules
- generated files match their source files
- database migrations accompany schema changes
- public functions include input validation
- documentation changes accompany public API changes
You can turn rules like these into regular scripts:
#!/bin/sh
npm run check:boundaries &&
npm run check:generated &&
npm run test:fast
An agent prompt is great for explaining why an architectural boundary exists, while a script verifies that the new code still respects it. Don’t go overboard trying to encode every stylistic preference, though. Stick to rules that are objective, quick to run, and expensive to forget.
Check the staged snapshot
When Git creates a commit, it commits the staged snapshot (also called the index), not necessarily whatever happens to be sitting in your editor. If you’re doing partial staging, or if several tasks share the same working directory, the file on disk can have extra changes that aren’t staged yet.
You can inspect the exact patch Git is about to commit with:
git diff --cached
Because of that difference, my advice is to keep pre-commit hooks read-only. Let them report problems without rewriting files behind your back. Automatic formatters often modify the complete file on disk, which can mix staged work with changes you meant to leave unstaged. If you do use lint-staged or another tool that rewrites staged files, test partial staging carefully before relying on it.
Catch secrets before an agent commits them
When an agent is debugging an issue, it sometimes inspects configuration files and accidentally copies a secret into a patch. Running a secret scanner in your pre-commit hook is a good way to catch that early:
#!/bin/sh
npm run secrets:check
Use a dedicated secret scanner here rather than a quick regular expression. A tiny regex usually misses real credentials while constantly flagging harmless strings.
A local hook lowers the odds of a leak, though you should still run secret scanning in CI and on your remote repository too. And if a real secret does enter Git history, removing the line in a later commit isn’t enough: revoke and replace the credential right away.
Require useful commit messages
Left on their own, agents can write vague commit subjects like update files or fix stuff. Since the commit-msg hook receives the commit message file as its first argument, you can use it to reject known bad subjects:
#!/bin/sh
message_file=$1
subject=$(sed -n '1p' "$message_file")
case "$subject" in
"update files"|"fix stuff"|"changes")
echo "Write a commit subject that explains the change"
exit 1
;;
esac
Save that as .git/hooks/commit-msg.
I wouldn’t build a complicated grammar for commit messages, because a hook can’t decide whether a message accurately describes the patch. Catching empty messages and a short denylist of useless subjects is plenty, and you can evaluate the wording during review.
Keep in mind that each Git hook receives different information, so check the Git hooks documentation before wiring up a hook you haven’t used before.
Run wider checks before a push
A pre-push hook runs right before Git sends commits to the remote. That makes it a better spot for slower checks that would drag down the commit loop:
#!/bin/sh
npm test &&
npm run build
Agents often create several small commits while working through a task and push them together. Running the full suite once at push time keeps each individual commit fast. I still keep very long browser suites out of pre-push, though, because slow hooks train both people and agents to bypass them. Leave expensive integration and browser tests for CI.
Record completed agent work after a commit
Once Git finishes creating a commit, it runs the post-commit hook. Returning an error at this point can’t stop or remove the commit, which makes post-commit a natural fit for logs and notifications.
You can set up a small local commit log like this:
#!/bin/sh
subject=$(git log -1 --pretty=%s)
printf '%s\n' "$subject" >> .git/commit-log.txt
Because that file stays inside .git, it never shows up as a project change in your working tree.
I use a more complete version of this to log every Git commit to one plain text file. Since Git records the completed event no matter which agent made the commit, I get a compact record of finished work without saving prompts, transcripts, or tool output.
Share hooks with every agent environment
Files inside .git/hooks stay local, and Git doesn’t include them when someone clones the repo. If you want shared hooks across environments, keep them in a tracked directory instead:
.githooks/
pre-commit
commit-msg
pre-push
Then point Git at that directory in the clone:
git config core.hooksPath .githooks
You can verify the setting with:
git config --get core.hooksPath
Every local or remote agent environment needs to run that setup, because a tracked hook sits idle until Git knows where to look. You can add the command to your project’s setup script, or in a JavaScript repo you can use Husky to install and share hooks.
Personally, I stick to core.hooksPath for a few short shell scripts, and I’d only use Husky when a JavaScript team already depends on its workflow. Make sure you read any shared hooks before enabling them, since a cloned hook is executable code coming straight from the repository.
Tell agents not to bypass hooks
Git lets a commit skip pre-commit and commit-msg with a single flag:
git commit --no-verify -m 'skip local checks'
And a push can skip pre-push the same way:
git push --no-verify
Make sure your agent instructions say not to use --no-verify. Even with that rule in place, an agent or a person can still bypass the hook, delete it, or work in a clone where hooks were never configured. That’s why required rules also need to run in CI, where local flags can’t sidestep them.
Only bypass a hook when the hook itself is broken and you understand the risk, then fix it immediately afterward.
Hooks and CI have different jobs
Local hooks give an agent fast feedback while it’s working, and CI verifies the result in a clean environment. I often run the exact same command in both places:
npm run check:commit
That way the hook catches a mistake before it leaves your machine, and CI catches it again if the hook was missing or skipped. Branch protection can require CI to pass, whereas it has no way to enforce a local hook the remote never sees. Think of hooks as speeding up the local workflow while CI enforces the shared standard for the repo.
Know what hooks cannot catch
Because a Git hook only runs at a Git event, it can’t help while an agent holds uncommitted changes. It also can’t tell whether the implementation solves the right problem, or catch a misleading test that happens to pass.
Subjective rules are out of reach for hooks too. A script can’t reliably decide whether code is clear, whether an abstraction is justified, or whether a user interface feels right.
Hooks work best for concrete, deterministic checks like:
- lint passes
- types check
- tests pass
- generated files are current
- forbidden dependencies are absent
- known secret patterns are absent
Leave judgment calls, like readability and design tradeoffs, to human or agent review.
How I use Git hooks with AI agents
In my own projects, I keep the commit hook quick: it checks the staged patch, lint, types, and fast tests, using the same focused loop I wrote about in How to speed up tests for AI coding agents.
Then the push hook runs the full test suite and production build, and CI repeats the required checks on a clean machine. On top of that, I run a post-commit hook for my work log so every successful commit gets recorded across whichever tool I used.
You don’t need a pile of hooks to get value out of this, just a handful of deterministic checks right where agent work turns into repository history.
If staging and commits are still new to you, start with my free Git course. Hooks make a lot more sense once the everyday Git workflow feels familiar.
Want me to talk about your product? You can sponsor this site.
Related posts about git: