1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
|
#!/usr/bin/env python3
"""PreToolUse hook for Bash: silent-unless-suspicious gate on `git commit`.
Reads tool-call JSON from stdin. If the Bash command is a `git commit`,
parse the message, run safety checks, and only emit a confirmation modal
when one of them fires:
- AI-attribution patterns in the commit message (Co-Authored-By: Claude,
robot emoji, etc.) — the primary leak we want to catch
- Message could not be parsed from the command line (no -m / HEREDOC;
likely to drop into $EDITOR, which silently blocks Claude)
- Zero staged files (the commit will fail; better to ask why)
- git author unusable (user.name / user.email not configured)
On a clean, well-formed commit, exit 0 with no output — the commit runs
without a modal. Non-git-commit Bash calls also exit 0 silent.
Previously this hook asked on every commit; that produced too many benign
modals for Craig's workflow. The attribution-scan safety is preserved;
the always-on review is not.
Wire in ~/.claude/settings.json (or per-project .claude/settings.json):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/git-commit-confirm.py"
}
]
}
]
}
}
"""
import re
import subprocess
import sys
from _common import (
read_payload,
read_referenced_file,
respond_ask,
respond_deny,
scan_attribution,
)
MAX_FILES_SHOWN = 25
MAX_MESSAGE_LINES = 30
# Recognized full-suite test runners across languages.
TEST_RUNNER_RE = re.compile(
r"\b("
r"make\s+(?:test|check)"
r"|pytest"
r"|go\s+test"
r"|cargo\s+test"
r"|npm\s+(?:run\s+)?test"
r"|yarn\s+test"
r"|pnpm\s+(?:run\s+)?test"
r"|jest|vitest|bats|tox|rspec|phpunit|ctest"
r")\b"
)
GIT_COMMIT_RE = re.compile(r"(?:^|[\s;&|()\n])git\s+(?:-[^\s]+\s+)*commit\b")
BUNDLED_TEST_REASON = (
"Blocked: a test run is bundled with `git commit` in one command, where a "
"red suite won't stop the commit. Run the full test suite as its own step, "
"read the result, and commit only on zero failures (see verification.md)."
)
UNPARSEABLE_MESSAGE = (
"(commit message not parseable from command line; "
"will be edited interactively)"
)
def main() -> int:
payload = read_payload()
if payload.get("tool_name") != "Bash":
return 0
cmd = payload.get("tool_input", {}).get("command", "")
if not is_git_commit(cmd):
return 0
# Hard gate: a test run bundled into the commit command is denied outright,
# because an ungated chain lets a red suite commit anyway.
if detect_bundled_test_run(cmd):
respond_deny(BUNDLED_TEST_REASON)
return 0
message = extract_commit_message(cmd)
staged = get_staged_files()
stats = get_diff_stats()
author = get_author()
issues = collect_issues(message, staged, author)
if not issues:
return 0 # silent pass-through on clean commits
reason = format_confirmation(message, staged, stats, author, issues)
attribution_hits = [
i for i in issues if i.startswith("AI-attribution")
]
system_message = (
f"WARNING — {attribution_hits[0]}. "
"Policy forbids AI credit in commits."
if attribution_hits else None
)
respond_ask(reason, system_message=system_message)
return 0
def collect_issues(message: str, staged: list[str], author: str) -> list[str]:
"""Return a list of human-readable issues worth asking the user about.
Empty list → silent pass-through. Any hits → modal.
"""
issues: list[str] = []
hits = scan_attribution(message)
if hits:
issues.append("AI-attribution pattern in message: " + "; ".join(hits))
if message == UNPARSEABLE_MESSAGE:
issues.append(
"commit message not parseable from command — editor will open"
)
if not staged:
issues.append("no staged files — the commit will fail")
if author.startswith("(") and author.endswith(")"):
issues.append(f"git author unusable: {author}")
return issues
def detect_bundled_test_run(cmd: str):
"""Return a truthy reason if a `git commit` is chained after a test run in
one command via an ungated connector (a red suite wouldn't stop the commit).
`&&` between the test run and the commit is the one safe connector — the
commit runs only on a green suite — and is allowed. Any other chaining (`;`,
`&`, `|`, `||`, newline, or a pipe that masks the suite's exit) is flagged.
The test runner is matched only in the command *prefix* before `git commit`,
so a runner name inside the commit message never trips the detector.
"""
if not cmd:
return None
commit = GIT_COMMIT_RE.search(cmd)
if not commit:
return None
prefix = cmd[: commit.start()]
runs = list(TEST_RUNNER_RE.finditer(prefix))
if not runs:
return None
# Everything between the last test run and the commit. Strip the safe `&&`
# connectors; anything left that chains commands means the commit isn't
# gated on the suite's success.
segment = prefix[runs[-1].end():].replace("&&", "")
if re.search(r"[;|\n&]", segment):
return BUNDLED_TEST_REASON
return None
def is_git_commit(cmd: str) -> bool:
"""True if the command invokes `git commit` (possibly with env/cd prefix)."""
# Strip leading assignments and subshells; find a `git commit` word boundary
return bool(re.search(r"(?:^|[\s;&|()])git\s+(?:-[^\s]+\s+)*commit\b", cmd))
def extract_commit_message(cmd: str) -> str:
"""Parse the commit message from either HEREDOC or -m forms."""
# HEREDOC form: -m "$(cat <<'EOF' ... EOF)" or -m "$(cat <<EOF ... EOF)"
heredoc = re.search(
r"<<-?\s*['\"]?(\w+)['\"]?\s*\n(.*?)\n\s*\1\b",
cmd,
re.DOTALL,
)
if heredoc:
return heredoc.group(2).strip()
# One or more -m flags (simple single/double quotes)
flags = re.findall(r"-m\s+([\"'])(.*?)\1", cmd, re.DOTALL)
if flags:
# Multiple -m flags join with blank line (git's own behavior)
return "\n\n".join(msg for _, msg in flags).strip()
# --message=... form
long_form = re.findall(r"--message[=\s]([\"'])(.*?)\1", cmd, re.DOTALL)
if long_form:
return "\n\n".join(msg for _, msg in long_form).strip()
# File-backed message: -F <file> / --file <file> / --file=<file>.
# Read the file so its text is attribution-scanned. If it can't be read
# safely, fall through to UNPARSEABLE_MESSAGE so the hook asks (fail-safe).
file_flag = re.search(
r"(?:^|\s)(?:-F|--file)[=\s]+(\"[^\"]+\"|'[^']+'|\S+)", cmd
)
if file_flag:
path = file_flag.group(1).strip("\"'")
text = read_referenced_file(path)
if text is not None:
return text.strip()
return UNPARSEABLE_MESSAGE
def get_staged_files() -> list[str]:
try:
out = subprocess.run(
["git", "diff", "--cached", "--name-only"],
capture_output=True,
text=True,
timeout=5,
)
return [line for line in out.stdout.splitlines() if line.strip()]
except (subprocess.SubprocessError, OSError, FileNotFoundError):
return []
def get_diff_stats() -> str:
try:
out = subprocess.run(
["git", "diff", "--cached", "--shortstat"],
capture_output=True,
text=True,
timeout=5,
)
return out.stdout.strip() or "(no staged changes — commit may fail)"
except (subprocess.SubprocessError, OSError, FileNotFoundError):
return "(could not read diff stats)"
def get_author() -> str:
"""Report the git author identity that will own the commit."""
try:
name = subprocess.run(
["git", "config", "user.name"],
capture_output=True,
text=True,
timeout=3,
).stdout.strip()
email = subprocess.run(
["git", "config", "user.email"],
capture_output=True,
text=True,
timeout=3,
).stdout.strip()
if name and email:
return f"{name} <{email}>"
return "(git user.name / user.email not configured)"
except (subprocess.SubprocessError, OSError, FileNotFoundError):
return "(could not read git config)"
def format_confirmation(
message: str, files: list[str], stats: str, author: str, issues: list[str]
) -> str:
lines = ["Create commit? (flagged for review)", ""]
lines.append("Issues detected:")
for issue in issues:
lines.append(f" ! {issue}")
lines.append("")
lines.append("Author:")
lines.append(f" {author}")
lines.append("")
lines.append("Message:")
msg_lines = message.splitlines() or ["(empty)"]
for line in msg_lines[:MAX_MESSAGE_LINES]:
lines.append(f" {line}")
if len(msg_lines) > MAX_MESSAGE_LINES:
lines.append(f" ... ({len(msg_lines) - MAX_MESSAGE_LINES} more lines)")
lines.append("")
lines.append(f"Staged files ({len(files)}):")
for f in files[:MAX_FILES_SHOWN]:
lines.append(f" - {f}")
if len(files) > MAX_FILES_SHOWN:
lines.append(f" ... and {len(files) - MAX_FILES_SHOWN} more")
lines.append("")
lines.append(f"Stats: {stats}")
lines.append("")
lines.append("Review the issues above before proceeding.")
return "\n".join(lines)
if __name__ == "__main__":
sys.exit(main())
|