Blocks Claude from ending a turn while code under guarded paths that this session changed has not passed the repository's check command since. It counts files…

A Claude Code mod. It stops Claude from ending a turn while changed code has not passed the repository's check command.
done-gate: 2 file(s) changed since the last passing check (src/greet.py, tests/test_greet.py).
Run `bash scripts/check.sh` and fix any failure before you finish.
git checkout, switch, merge, pull, rebase, reset or fetch counts nothing, so branch switches and merges are not the session's changes. Edits by another agent between commands do not count.checks and ends without error covers every change the session made before it. At the end of a main-loop turn, if a file changed since the last pass is under paths, the mod blocks the turn once and names the check. With resolve, the repository's own command decides instead (below).Each repository opts in with .claude/done-gate.json. Without that file the mod does nothing.
{
"checks": ["^bash scripts/verify\\.sh"],
"paths": ["src/", "crates/"],
"hint": "bash scripts/verify.sh <lane>"
}
checks: regular expressions matched against the Bash command. Required.paths: path prefixes from the repository root that need proof. Empty or absent means every file.hint: the command named in the block message. Defaults to the first pattern.resolve: optional. A command and its arguments, run from the repository root, that decides which checks are unmet. It reads JSON on stdin, { "changed": [files the session changed], "passes": [{ "command", "changed": [files the session changed since that command passed] }] }, and prints one unmet check per line (nothing when all are met). With resolve, paths and hint are unused. Use it when the repository already owns a map from paths to checks, so the map has one owner.Limits: a check passes when the tests it runs pass, so deleting a failing test passes too. A change another process makes while one of the session's Bash commands runs counts as the session's; so does the whole diff of a chained command such as git checkout x && make, and of git commands not listed above (git stash pop, git restore). Files a background Bash command changes after it returns, or that an MCP tool or NotebookEdit writes, do not count. The tree id is written through a private index at .git/done-gate.index; git add --all there writes blob objects to .git/objects, which git gc removes when unreferenced.
Needs function hooks (early access): Claude Code 2.1.287 or later. Test with claude plugin test plugins/done-gate.
hooks/done-gate.ts 128 lines1/**
2 * done-gate — Claude Mod (EARLY ACCESS)
3 *
4 * Blocks the main loop from ending a turn while changed files have not passed
5 * the checks they need.
6 *
7 * - Counts only the session's own changes: each file an Edit or Write
8 * names, and each file a Bash command changes (a git tree id of the whole
9 * working tree, through a private index under .git, before and after the
10 * command). A lone HEAD-moving git command counts nothing.
11 * - `tool.call` on Bash: a command matching `checks` that ends without error
12 * covers every change the session made before it.
13 * - `classic.Stop`: with `resolve`, the repository's command reads the
14 * changed files and passes on stdin and prints each unmet check; without
15 * it, any file under `paths` changed since the last pass is unmet. Blocks
16 * once; the retry (`stop_hook_active`) ends the turn with a toast.
17 * - Inactive in a repository without `.claude/done-gate.json`.
18 */
19import type { EngineInterface, Register } from 'claude-code'
20import { CONFIG_PATH, configFault, decide, decideResolved, isCheck, isHeadMove, parseConfig } from './gate.ts'
21import type { Config, Pass, Verdict } from './gate.ts'
22
23type Repo = { root: string; config: Config } | { root: string; fault: string }
24
25const touches: string[] = []
26let lastPassAt = 0
27const passAt = new Map<string, number>()
28let queue: Promise<unknown> = Promise.resolve()
29
30const serial = <T>(work: () => Promise<T>): Promise<T> => {
31 const run = queue.then(work, work)
32 queue = run.catch(() => undefined)
33 return run
34}
35
36async function git($: EngineInterface, cwd: string, args: string[], env?: Record<string, string>) {
37 const { exitCode, stdout, stderr } = await $.process.run(['git', ...args], { cwd, env })
38 if (exitCode !== 0) throw new Error(`git ${args[0]}: ${stderr.trim()}`)
39 return stdout.trim()
40}
41
42async function repoOf($: EngineInterface): Promise<Repo | undefined> {
43 const cwd = await $.session.cwd()
44 const root = await git($, cwd, ['rev-parse', '--show-toplevel']).catch(() => undefined)
45 if (root === undefined) return undefined
46 const path = `${root}/${CONFIG_PATH}`
47 if (!(await $.fs.exists(path))) return undefined
48 const parsed = parseConfig(await $.fs.read(path))
49 return 'error' in parsed ? { root, fault: parsed.error } : { root, config: parsed }
50}
51
52const treeOf = ($: EngineInterface, root: string) =>
53 serial(async () => {
54 const index = await git($, root, ['rev-parse', '--path-format=absolute', '--git-path', 'done-gate.index'])
55 const env = { GIT_INDEX_FILE: index }
56 await git($, root, ['add', '--all'], env)
57 return git($, root, ['write-tree'], env)
58 })
59
60const changedBetween = async ($: EngineInterface, root: string, from: string, to: string) =>
61 from === to ? [] : (await git($, root, ['diff', '--name-only', from, to])).split('\n').filter(Boolean)
62
63const touchedSince = (at: number) => [...new Set(touches.slice(at))].sort()
64
65async function unmetChecks($: EngineInterface, root: string, resolve: string[]) {
66 const passes: Pass[] = [...passAt].map(([command, at]) => ({ command, changed: touchedSince(at) }))
67 const stdin = JSON.stringify({ changed: touchedSince(0), passes })
68 const { exitCode, stdout, stderr } = await $.process.run(resolve, { cwd: root, stdin })
69 if (exitCode !== 0) throw new Error(`resolve exited ${exitCode}: ${stderr.trim()}`)
70 return stdout.split('\n').map(line => line.trim()).filter(Boolean)
71}
72
73async function verdictAtStop($: EngineInterface, isRetry: boolean): Promise<Verdict> {
74 const repo = await repoOf($)
75 if (repo === undefined) return { kind: 'pass' }
76 if ('fault' in repo) return isRetry ? { kind: 'pass' } : configFault(repo.fault)
77 if (repo.config.resolve !== undefined) {
78 const unmet = await unmetChecks($, repo.root, repo.config.resolve)
79 return decideResolved({ unmet, isRetry })
80 }
81 return decide({ config: repo.config, unproven: touchedSince(lastPassAt), isRetry })
82}
83
84export const register: Register = on => {
85 on('session.start', ($, e, next) => {
86 touches.length = 0
87 lastPassAt = 0
88 passAt.clear()
89 return next(e)
90 })
91
92 on('tool.call', { tool: ['Edit', 'Write'] }, async ($, e, next) => {
93 const ran = await next(e)
94 if (ran.deny !== undefined || ran.isError === true) return ran
95 const repo = await repoOf($).catch(() => undefined)
96 if (repo !== undefined && e.file_path.startsWith(`${repo.root}/`)) touches.push(e.file_path.slice(repo.root.length + 1))
97 return ran
98 })
99
100 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
101 const repo = await repoOf($).catch(() => undefined)
102 if (repo === undefined || !('config' in repo)) return next(e)
103 const before = isHeadMove(e.command) ? undefined : await treeOf($, repo.root).catch(() => undefined)
104 const ran = await next(e)
105 if (ran.deny !== undefined) return ran
106 if (before !== undefined) {
107 const after = await treeOf($, repo.root).catch(() => undefined)
108 if (after !== undefined) touches.push(...(await changedBetween($, repo.root, before, after).catch(() => [])))
109 }
110 if (ran.isError !== true && isCheck(repo.config, e.command)) {
111 lastPassAt = touches.length
112 passAt.set(e.command.trim(), touches.length)
113 }
114 return ran
115 })
116
117 on('classic.Stop', async ($, e, next) => {
118 const verdict = await verdictAtStop($, e.stop_hook_active)
119 if (verdict.kind === 'block') return { block: verdict.reason }
120 if (verdict.kind === 'release') $.ui.toast(`done-gate: ${verdict.reason}`)
121 return next(e)
122 }).catch(($, e, next) =>
123 e.stop_hook_active || next.called
124 ? next(e)
125 : { block: 'done-gate: its check failed to run. Say in your reply that the work is unverified.' },
126 )
127}
128hooks/gate.ts 100 lines1export type Config = {
2 checks: RegExp[]
3 paths: string[]
4 hint: string
5 resolve?: string[]
6}
7
8export type ConfigError = { error: string }
9
10export type Verdict =
11 | { kind: 'pass' }
12 | { kind: 'block'; reason: string }
13 | { kind: 'release'; reason: string }
14
15export type Pass = { command: string; changed: string[] }
16
17export const CONFIG_PATH = '.claude/done-gate.json'
18
19const isStrings = (value: unknown): value is string[] =>
20 Array.isArray(value) && value.every(item => typeof item === 'string')
21
22export function parseConfig(text: string): Config | ConfigError {
23 let raw: unknown
24 try {
25 raw = JSON.parse(text)
26 } catch {
27 return { error: 'is not valid JSON' }
28 }
29 if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
30 return { error: 'must be a JSON object' }
31 }
32 const { checks, paths = [], hint, resolve } = raw as Record<string, unknown>
33 if (!isStrings(checks) || checks.length === 0) {
34 return { error: '"checks" must be a non-empty list of regular expressions' }
35 }
36 if (!isStrings(paths)) return { error: '"paths" must be a list of path prefixes' }
37 if (hint !== undefined && typeof hint !== 'string') return { error: '"hint" must be a string' }
38 if (resolve !== undefined && (!isStrings(resolve) || resolve.length === 0)) {
39 return { error: '"resolve" must be a non-empty command and argument list' }
40 }
41 let compiled: RegExp[]
42 try {
43 compiled = checks.map(pattern => new RegExp(pattern))
44 } catch {
45 return { error: '"checks" holds an invalid regular expression' }
46 }
47 return { checks: compiled, paths, hint: hint ?? checks[0], resolve }
48}
49
50export const isCheck = (config: Config, command: string): boolean =>
51 config.checks.some(pattern => pattern.test(command))
52
53const HEAD_MOVE = /^\s*git\s+(?:checkout|switch|merge|pull|rebase|reset|fetch)\b[^;&|]*$/
54
55// A lone HEAD-moving git command changes files the session did not author; a chained one counts in full.
56export const isHeadMove = (command: string): boolean => HEAD_MOVE.test(command)
57
58const guardedFiles = (config: Config, changed: readonly string[]): string[] =>
59 config.paths.length === 0
60 ? [...changed]
61 : changed.filter(file => config.paths.some(prefix => file.startsWith(prefix)))
62
63const listed = (items: readonly string[]) =>
64 items.slice(0, 3).join(', ') + (items.length > 3 ? `, +${items.length - 3} more` : '')
65
66function verdict(unmet: readonly string[], isRetry: boolean, block: string): Verdict {
67 if (unmet.length === 0) return { kind: 'pass' }
68 if (isRetry) return { kind: 'release', reason: `finished without a passing check (${listed(unmet)})` }
69 return {
70 kind: 'block',
71 reason:
72 `${block} Run each command as given, with no pipe, redirect or chained command, so its exit code is the check's. ` +
73 'If the check cannot run here, say why in your reply.',
74 }
75}
76
77export function decide(input: { config: Config; unproven: readonly string[]; isRetry: boolean }): Verdict {
78 const files = guardedFiles(input.config, input.unproven)
79 return verdict(
80 files,
81 input.isRetry,
82 `done-gate: ${files.length} file(s) changed since the last passing check (${listed(files)}). ` +
83 `Run \`${input.config.hint}\` and fix any failure before you finish.`,
84 )
85}
86
87export function decideResolved(input: { unmet: readonly string[]; isRetry: boolean }): Verdict {
88 return verdict(
89 input.unmet,
90 input.isRetry,
91 `done-gate: these checks have not passed on the current files: ${input.unmet.join('; ')}. ` +
92 'Run them and fix any failure before you finish.',
93 )
94}
95
96export const configFault = (error: string): Verdict => ({
97 kind: 'block',
98 reason: `done-gate: ${CONFIG_PATH} ${error}. Fix it or remove it before you finish.`,
99})
100