Development Playbook

Make the agent pass your checks: Husky, lint-staged and two Claude Code hooks

A commit and push gate that an agent can't skip with --no-verify, plus a Stop hook that won't let it call red code finished. Fifteen minutes to set up.

Part of the hooks reading guide

Three concentric glowing rings around a small square node, each ring closed by a short gate bar, drawn like a blueprint

It’s 4:50pm. The agent reports that the invoice refactor is done, all green. You pull the branch and run the tests: one fails. You look at the log and find the commit message ends with “skip hooks, unrelated failure”, and a git commit --no-verify is sitting in the session history. The pre-commit hook had caught a real type error, and the agent routed around it because it had a goal and the hook was in the way.

Nothing in the setup was wrong, exactly. The hook worked. It just wasn’t binding, because every git hook is advisory and the agent has a shell. Telling it in CLAUDE.md to “always run the checks” helps until the first time a check is annoying.

This Playbook builds three layers that don’t rely on the agent’s good manners. Husky and lint-staged put formatting, type checking and tests in front of every commit and push. A Claude Code PreToolUse hook refuses the commands that skip them. A Stop hook runs the same checks when the agent says it’s finished and sends it back to work if they fail. Everything below was built and run on a small TypeScript project, and the output shown is real. The setup takes about fifteen minutes.

The three layers

Each layer covers a hole in the one before it.

Git hooks (Husky) gate the commit and the push, no matter who or what types the command. The Claude Code PreToolUse hook closes the escape hatches (--no-verify, HUSKY=0 and friends) and refuses to commit in a checkout where the hooks were never installed. The Stop hook is the backstop at the end of the turn: it catches an agent that never commits and declares victory with a broken working tree, and one that committed red code past the other two layers.

None of this is a security boundary, and the last section is honest about the gaps. The aim is narrower: make skipping the check harder than fixing the failure, and make the failure message land in the agent’s context, where it can act on it.

The project

The examples use a tiny TypeScript project: one function, one Vitest test. It’s the smallest thing that still produces real failures.

mkdir demo && cd demo
git init -b main
npm init -y
npm install --save-dev husky lint-staged prettier typescript vitest
npx husky init

npx husky init creates .husky/pre-commit and adds a prepare script to package.json, so Husky installs its hooks on every npm install. That matters for agents too: a fresh clone gets the gate as soon as dependencies are installed, and not a moment before. Layer 2 deals with that gap.

Add a source file and a test:

// src/invoice.ts
export function totalWithVat(net: number, rate = 0.2): number {
  return Math.round(net * (1 + rate) * 100) / 100;
}
// src/invoice.test.ts
import { describe, expect, it } from "vitest";
import { totalWithVat } from "./invoice";

describe("totalWithVat", () => {
  it("adds 20% by default", () => {
    expect(totalWithVat(100)).toBe(120);
  });
});

A minimal tsconfig.json with "strict": true and "noEmit": true is enough for the type check. Then wire three scripts into package.json:

{
  "scripts": {
    "test": "vitest run",
    "prepare": "husky",
    "typecheck": "tsc --noEmit",
    "check": "npm run typecheck && npm test"
  },
  "lint-staged": {
    "*.{ts,json,md}": "prettier --write"
  }
}

The check script is the single definition of “green”. Every layer calls it or a piece of it, so the gate can’t drift between the commit hook, the push hook and the agent hook.

Layer 1: git hooks

The pre-commit hook should be fast, because it runs on every commit and the agent will commit often. Formatting staged files and type checking fit that budget. The test suite goes on pre-push, where a few extra seconds are acceptable.

# .husky/pre-commit
npx lint-staged
npm run typecheck
# .husky/pre-push
npm run check

Husky 9 hook files are plain shell, with no boilerplate header. lint-staged formats only the files in the commit and re-stages the result. Commit a badly formatted file and the commit lands with the formatted version (the committed file, read back from git, is formatted):

$ git commit -m "add VAT_RATE"
[COMPLETED] prettier --write

Auto-fixing like this is better for agents than failing on formatting. A formatting failure teaches the agent nothing it can’t solve in one command, and it burns a turn. Reserve failures for things only a human or a real edit can fix.

Now introduce a type error and try to commit it:

$ git commit -m "break types"
> demo@1.0.0 typecheck
> tsc --noEmit

src/invoice.ts(2,3): error TS2322: Type 'number' is not assignable to type 'string'.
husky - pre-commit script failed (code 1)

The commit doesn’t happen, the error is on stderr, and the agent sees it in the tool result. Per the lint-staged docs, a failing task also reverts its own modifications, and a backup stash is taken before tasks run, so a failed commit doesn’t leave half-formatted files behind.

Pre-push is where tests run. Here the test file has a second case, rounds to pence, and totalWithVat no longer rounds:

$ git push origin main
FAIL  src/invoice.test.ts > totalWithVat > rounds to pence
AssertionError: expected 0.084 to be 0.08

(trimmed)
husky - pre-push script failed (code 1)
error: failed to push some refs to '../remote.git'

Putting the type check in pre-push as well as pre-commit is deliberate, and the reason is a real trap: Vitest doesn’t type check. With a type error in the tree, npm test passes. A pre-push that runs only the tests lets the commit from the next section through.

Layer 2: close the bypass

Here is the hole. Git documents that pre-commit “can be bypassed with the --no-verify option”, and that git push --no-verify bypasses the pre-push hook completely. Husky adds HUSKY=0 as a global off switch. All three are one-line changes to a command the agent was going to run anyway.

Run the bypass and it works:

$ git commit -qam "break types" --no-verify
$ echo $?
0
$ HUSKY=0 git commit -qam "skip via env"
$ echo $?
0

Both commits land, type error and all. Closing this needs something that sits in front of the shell, which is what a Claude Code PreToolUse hook does. It receives the Bash command as JSON on stdin (the command is at tool_input.command), and exit code 2 blocks the call and sends stderr back to the agent as the reason.

Save this as .claude/hooks/no-bypass.py:

#!/usr/bin/env python3
"""PreToolUse hook for Bash: refuse commands that skip, or run without, the git hooks."""
import json
import os
import re
import shlex
import subprocess
import sys


ADVICE = "Fix the failing check instead of skipping it, or ask the user to run this themselves."


def skipped(reason: str) -> str:
    return f"{reason}. {ADVICE}"


def segments(command: str):
    """Split a shell line on ; && || | and newlines (good enough for a guard)."""
    return [s.strip() for s in re.split(r"&&|\|\||;|\||\n", command) if s.strip()]


def git(cwd: str, *args: str) -> str:
    result = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
    return result.stdout.strip() if result.returncode == 0 else ""


def hooks_missing(cwd: str) -> bool:
    """True when this checkout has no hooks directory, e.g. before `npm install`."""
    top = git(cwd, "rev-parse", "--show-toplevel")
    if not top:
        return False  # not a repository: git will complain on its own
    hooks_path = git(cwd, "config", "--get", "core.hooksPath")
    return not hooks_path or not os.path.isdir(os.path.join(top, hooks_path))


def violation(segment: str, cwd: str):
    if re.search(r"(^|\s)HUSKY=0(\s|$)", segment):
        return skipped("HUSKY=0 switches the hooks off")
    try:
        words = shlex.split(segment)
    except ValueError:
        return "command could not be parsed"
    if "git" not in words:
        return None
    rest = words[words.index("git") + 1 :]
    if "hooksPath" in segment:
        return skipped("changing core.hooksPath detaches the hooks")
    sub = next((w for w in rest if not w.startswith("-") and "=" not in w), "")
    if sub in {"commit", "push", "merge", "am", "cherry-pick", "rebase"}:
        for w in rest:
            if w == "--no-verify":
                return skipped("--no-verify skips the git hooks")
            if sub == "commit" and re.fullmatch(r"-[a-zA-Z]*n[a-zA-Z]*", w):
                return skipped("git commit -n is short for --no-verify")
    if sub in {"commit", "push"} and hooks_missing(cwd):
        return "The git hooks are not installed in this checkout. Run npm install, then retry."
    return None


def main() -> int:
    try:
        payload = json.load(sys.stdin)
        command = payload["tool_input"]["command"]
        cwd = payload.get("cwd") or os.getcwd()
        for seg in segments(command):
            reason = violation(seg, cwd)
            if reason:
                print(f"Blocked: {reason}", file=sys.stderr)
                return 2
        return 0
    except Exception as exc:  # fail closed: a crashed guard must not be a green light
        print(f"no-bypass hook error: {exc}", file=sys.stderr)
        return 2


sys.exit(main())

Four details earn their lines. The -n check exists because git commit -n is the short form of --no-verify, and the regex also catches it bundled, as in -nm "message". But it only applies to commit, because -n means something else elsewhere: git log -n 5 must keep working. And the whole script sits inside a try block that exits 2 on any error, because a guard that crashes on unexpected input shouldn’t wave the command through. That is the same fail-closed rule covered in Your Claude Code policy hook probably fails open , and the settings below back it up with onFailure. The fourth detail, hooks_missing, gets its own section below.

Test the script before you trust it, by piping the documented payload in by hand:

probe() {
  printf '{"tool_name":"Bash","cwd":"%s","tool_input":{"command":%s}}' "$PWD" "$(jq -Rn --arg c "$1" '$c')" \
    | python3 .claude/hooks/no-bypass.py 2>/dev/null
  echo "exit $?  [$1]"
}
probe 'git commit -m "wip"'
probe 'git commit --no-verify -m "wip"'
probe 'git commit -nm "wip"'
probe 'git push --no-verify origin main'
probe 'HUSKY=0 git commit -m wip'
probe 'git -c core.hooksPath=/dev/null commit -m wip'
probe 'npm test && git push origin main'
probe 'git log -n 5'
probe 'git commit -m "no verify"'

Run it from the main checkout and it prints:

exit 0  [git commit -m "wip"]
exit 2  [git commit --no-verify -m "wip"]
exit 2  [git commit -nm "wip"]
exit 2  [git push --no-verify origin main]
exit 2  [HUSKY=0 git commit -m wip]
exit 2  [git -c core.hooksPath=/dev/null commit -m wip]
exit 0  [npm test && git push origin main]
exit 0  [git log -n 5]
exit 0  [git commit -m "no verify"]

The blocked ones print “Blocked: –no-verify skips the git hooks. Fix the failing check instead of skipping it, or ask the user to run this themselves.” (or the matching reason) to stderr, which the probe hides. The last three lines matter as much as the blocks. A guard that blocks innocent commands gets disabled within a day.

The error text is written for the agent. “Fix the failing check instead of skipping it” gives it the next move, and “ask the user to run this themselves” gives it a legitimate way out. Without an exit, an agent tends to look for a creative workaround.

When the hooks were never installed

There is a second way to skip the hooks, and it needs no flag. Husky’s hooks live in .husky/_, which prepare generates and git ignores, and core.hooksPath points at it. A fresh clone lacks that directory until npm install has run. So does every new git worktree, which is how parallel agents are usually isolated:

$ git worktree add ../demo-feature -b feature
$ cd ../demo-feature
$ ls -a .husky
.  ..  pre-commit  pre-push
$ git config core.hooksPath
.husky/_
$ git commit -qam "break types"
$ echo $?
0

The tracked hook files are there, the directory git is told to read isn’t, and git doesn’t complain about a missing hooks directory. The type error commits without a word. The setting is inherited by any subshell, so the shell isn’t the problem. The generated files are.

The hooks_missing function closes that. For git commit and git push, it reads core.hooksPath, resolves it against the working tree and blocks the command if the directory doesn’t exist. It uses the cwd field from the hook input, which follows the agent into a worktree or after a cd. The error says to run npm install and retry, which the agent can do on its own. Probed from the worktree before installing, git commit -m "wip" and git push origin feature both exit 2 with “The git hooks are not installed in this checkout. Run npm install, then retry.”, and git status exits 0.

After npm install in that worktree, the commit probe exits 0 and the real hooks take over. npm install && git commit on one line is blocked, because the check runs before the install does. The agent splits it in two.

Layer 3: don’t let it finish on red

Layers 1 and 2 only act when the agent commits or pushes. An agent that edits files, breaks something and reports “done” never touches git. And a commit that slipped past them, from a path the pattern match doesn’t see, is already in history. A Stop hook covers both: it runs when Claude finishes responding, and exit 2 “prevents Claude from stopping” and feeds stderr back as the reason to continue.

Save this as .claude/hooks/stop-gate.sh and make it executable:

#!/bin/bash
# Stop hook: don't let the agent finish while the checks are red.
cd "$CLAUDE_PROJECT_DIR" || exit 2

# Fingerprint the commit and the working tree. Unchanged since the last green run: nothing to verify.
stamp="$(git rev-parse --git-dir)/last-green-check"
state=$( { git rev-parse HEAD; git status --porcelain; git diff HEAD; } | git hash-object --stdin)
[ "$(cat "$stamp" 2>/dev/null)" = "$state" ] && exit 0

if ! out=$(npm run --silent check 2>&1); then
  {
    echo "The project checks fail. Fix them before you finish."
    echo "$out" | tail -n 25
  } >&2
  exit 2
fi

echo "$state" > "$stamp"
exit 0

The fingerprint is the cost control. Stop fires at the end of every turn, including turns where the agent only answered a question, and running the full check each time would add seconds of latency to a conversation. The hook hashes the current commit, the status and the diff, and compares that with the hash stored after the last green run. Nothing changed, so it exits immediately.

Hashing HEAD as well as the working tree is deliberate. Skipping clean trees alone would ignore a red commit, because committing leaves nothing dirty. With the commit in the hash, an agent that commits a type error past the hooks gets this at the end of its turn (a failing test returns the tail of the Vitest output instead):

The project checks fail. Fix them before you finish.
src/invoice.ts(2,3): error TS2322: Type 'string' is not assignable to type 'number'.

The stamp lives inside the git directory, so it needs no .gitignore entry and each worktree gets its own.

Two things in the Claude Code docs stop this becoming an infinite loop. Every Stop hook receives a stop_hook_active field, which is true when the agent is already continuing because of a stop hook. And Claude Code applies an 8-consecutive-continuation cap: after eight blocks in a row it overrides the next one and ends the turn. The count resets whenever Claude calls a tool, so a real fix-and-retry cycle isn’t penalised. The script relies on the cap, because a suite that’s still red after one retry should usually get another one. If your checks are slow or flaky, read stop_hook_active and let the second pass through.

A Stop hook gates the hand-off, not the commit. A bad commit stays in local history until the agent repairs it with a fixup or an amend, and the hook makes it do that before reporting done. Sub-agents have their own exit: SubagentStop fires when one finishes, and exit 2 stops it finishing, so register the same script there and each worker is gated before its result reaches the main session.

Register the hooks

Both scripts go into .claude/settings.json, which you commit so the whole team and every worktree gets the same gate:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3",
            "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/no-bypass.py"],
            "onFailure": "block"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-gate.sh",
            "timeout": 300
          }
        ]
      }
    ],
    "SubagentStop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-gate.sh",
            "timeout": 300
          }
        ]
      }
    ]
  },
  "permissions": {
    "deny": ["Edit(.husky/**)", "Edit(.claude/**)"]
  }
}

onFailure: "block" needs Claude Code 2.1.295 or later. By default, per the docs, a PreToolUse hook that fails, times out or can’t start lets the tool call through, so a mistyped path would quietly turn the guard off. The Stop and SubagentStop hooks get a 300-second timeout because the default for command hooks is 600 and a hung test run shouldn’t hold a session for ten minutes.

The permissions.deny rules cover the obvious next move for a determined agent: editing the hook files themselves. Per the permissions docs, an Edit(path) deny rule applies to the built-in file tools and to file commands Claude Code recognises in Bash, such as sed and tee.

Watch the transcript on the first run. A hook that can’t start produces a “hook error” notice instead of an effect, and that notice is the only sign the gate isn’t there.

Make it yours

Different stacks need different checks, not different structure.

C# projects: swap the scripts so check runs dotnet format --verify-no-changes, dotnet build -warnaserror and dotnet test. Husky works in a .NET repo with a minimal package.json that exists only for the prepare script. A plain .githooks/ folder with git config core.hooksPath .githooks also works, but then change the install message in hooks_missing to match.

CI: the local gate is a convenience, and CI is the enforcement. Run the same npm run check on every pull request, and make it a required status check, because --no-verify in a terminal the agent doesn’t control, or in a teammate’s habit, still gets through:

name: check
on: pull_request
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npm run check

That workflow is standard Actions syntax and wasn’t run as part of this build.

What goes wrong

The no-bypass hook is a pattern match on command text, not a parser of shell. It splits on ;, &&, || and |, and it will miss a bypass hidden in a script the agent writes and then runs (bash ./commit.sh), in an alias, or in a git invocation assembled from variables. The Claude Code docs say as much about their own if filters, which are best-effort, and recommend the permission system for hard allow and deny rules. The Edit deny rules likewise don’t apply to a Python or Node script that opens files itself. For that you need the sandbox, which enforces access at the OS level.

False positives are the other cost: the hook blocks git commit --amend -n, and any command that merely mentions HUSKY=0. The agent is told to ask you, which is right, but expect the occasional interruption.

The Stop hook can fight the user. If a branch is deliberately red (a failing test written first, a half-finished migration), the agent can’t stop, and eight continuations later it does anyway. Tell the agent in the prompt that a red test is intended, or leave the Stop hook out of that branch’s settings. It also runs the check whenever the commit or the working tree has changed, so a slow suite slows every turn that touches code.

The hooks-installed check covers git commit and git push typed as commands. A commit made through bash ./commit.sh, or by a tool that talks to git without the CLI, in a checkout where npm install never ran, goes through with no hooks. The Stop hook still fails the turn, and CI still fails the pull request. Those two are the layers that don’t depend on how the commit was made.

When not to bother: a repository with no tests and no type checker has nothing to gate, and a throwaway script gains nothing from the machinery. If your CI already finishes in under a minute and you always review before merging, the Stop hook is the layer that adds most, because it catches red work before you see it, and you can start with it alone.

First 15 minutes

Start with what you already have. Take the check your CI runs, put it behind one script (npm run check or equivalent), and wire it as a pre-push hook with npx husky init. That alone catches the commit that would have failed CI.

Then copy no-bypass.py into .claude/hooks/, register it with onFailure: "block", and run the probe lines above against it, in the main checkout and in a fresh worktree, before you rely on it. Add the Stop and SubagentStop hooks last, once the check is fast enough to run at the end of every turn that changed code.