spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

claude-code / plugins / security-guidance / hooks / security_reminder_hook.py
2,189 lines · 101.1 KBRaw
1#!/usr/bin/env python3
2"""
3Security Guidance Plugin for Claude Code
4
5A hooks-based plugin that guides Claude toward writing more secure code. It runs as
6UserPromptSubmit, PostToolUse, and Stop hooks via the Claude Code plugin system.
7
8## Architecture
9
10The plugin has two layers:
11
121. **Pattern-based rules (PostToolUse, every edit)**: Fast regex checks that run on
13 every file write. Detects common vulnerabilities like hardcoded secrets, SQL injection,
14 command injection, path traversal, and insecure session configs. Injects brief warnings
15 via additionalContext.
16
172. **Stop hook (final review)**: When Claude finishes, uses `git diff` against a
18 baseline SHA (captured at UserPromptSubmit) to get only the code changed during the
19 session. Runs two Haiku analyses on the diff:
20 a) Concrete vulnerability scan with severity ratings
21 b) Areas-of-concern analysis identifying categories to investigate
22 Exits with code 2 to force Claude to continue and address findings.
23
24## How the git baseline works
25
26On each UserPromptSubmit, the plugin runs `git stash create` to get a SHA representing
27the current working tree state (HEAD + any uncommitted changes). This SHA is saved to
28the session state file. When the Stop hook fires, it runs `git diff <baseline_sha>` to
29get only the changes made since that snapshot. After analysis, the baseline is updated
30so the next Stop hook iteration only sees new changes.
31
32This means:
33- Only code Claude actually changed is reviewed (not pre-existing code)
34- Mid-session commits are handled correctly (diff is against the snapshot, not HEAD)
35- Each turn only reviews new changes (baseline updates after each stop hook)
36
37## Configuration
38
39Kill switches:
40- SECURITY_GUIDANCE_DISABLE: "1" to fully disable the plugin (alias for ENABLE_SECURITY_REMINDER=0)
41- ENABLE_SECURITY_REMINDER: "0" to fully disable the plugin (legacy name)
42
43Per-feature toggles (all default enabled; set to "0" to disable):
44- ENABLE_PATTERN_RULES: PostToolUse regex warnings on Edit/Write
45- ENABLE_CODE_SECURITY_REVIEW: Stop-hook git-diff LLM review
46- ENABLE_COMMIT_REVIEW: PostToolUse[Bash] commit security review
47
48Other:
49- SECURITY_REVIEW_MODEL: Model for LLM review (default: claude-opus-4-7)
50- ANTHROPIC_API_KEY: Required for LLM-based reviews
51- ANTHROPIC_AUTH_TOKEN: Alternative to API key — OAuth access token sent as Bearer auth.
52 Claude Code passes this automatically for OAuth-authenticated users.
53"""
54
55try:
56 import fcntl
57except ImportError:
58 fcntl = None
59import contextlib
60import glob
61import json
62import os
63import random
64import re
65import subprocess
66import sys
67import threading
68import urllib.request
69from datetime import datetime
70from enum import IntEnum
71from typing import Optional, Tuple, Dict, Any, List
72
73# review_api is the importable surface for the agentic-review prompts,
74# schemas, and pure filters. External callers (e.g. agentic review harnesses)
75# import review_api directly so they run the same eval-covered prompts
76# without going through the CC hook protocol. The underscored names below
77# alias into it so this script stays the single CC-hook entrypoint.
78sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
79import review_api # noqa: E402
80from _base import ( # noqa: E402,F401
81 DEBUG_LOG_FILE, DEBUG_LOG_MAX_BYTES, debug_log,
82 PROVENANCE_TAG, PROVENANCE_BANNER,
83 _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK,
84 _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics,
85)
86import extensibility # noqa: E402
87import secretpaths # noqa: E402
88from patterns import ( # noqa: E402,F401
89 _JS_EXTS, _PY_EXTS, _DOC_EXTS,
90 _UNSAFE_DESERIALIZATION_REMINDER, _UNSAFE_YAML_LOAD_REMINDER,
91 _UNSAFE_TORCH_LOAD_REMINDER, SECURITY_PATTERNS, RuleId,
92 _RULE_NAME_TO_ID, rule_names_to_mask,
93)
94from session_state import ( # noqa: E402,F401
95 _state_key, get_state_file, get_lock_file, cleanup_old_state_files,
96 load_state, save_state, with_locked_state,
97)
98from gitutil import ( # noqa: E402,F401
99 GIT_CMD,
100 _git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index,
101 _git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range,
102 _detect_main_branch, _git_reflog_recent_commits, _git_name_only,
103 _git_status_porcelain, _is_ancestor, get_git_diff,
104 SOURCE_CODE_EXTENSIONS, SOURCE_CODE_BASENAMES,
105 NON_SOURCE_EXTENSIONLESS_BASENAMES, SKIP_PATH_PATTERNS,
106 SKIP_FILE_SUFFIXES, _SECURITY_RISK_PATH_TOKENS,
107 _LOW_PRIORITY_SUFFIXES, _LOW_PRIORITY_PATH_TOKENS,
108 _prioritize_diff_files, _is_reviewable_source,
109 extract_file_paths_from_diff, parse_diff_into_files,
110 filter_preexisting_from_diff,
111)
112from diffstate import ( # noqa: E402,F401
113 STOP_LOOP_STATE_TTL_SEC, PREVIOUS_FINDINGS_TTL_SEC,
114 save_baseline_sha, load_baseline_sha, record_touched_path,
115 consume_stop_state, restore_unreviewed_stop_state,
116 get_baseline_file_content, capture_git_baseline,
117 _REVIEWED_SHAS_BASENAME, _REVIEWED_SHAS_CAP,
118 _reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas,
119 UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set,
120)
121import llm # noqa: E402 module ref for reassignable globals (_last_call_claude_http_error etc.)
122from llm import ( # noqa: E402,F401
123 ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, HAS_API_CREDENTIALS,
124 SECURITY_REVIEW_MODEL, CLAUDE_CODE_SYSTEM_PROMPT,
125 _last_call_claude_http_error,
126 ensure_anthropic_reachable,
127 _last_review_truncated_bytes, _auth_prefer_token,
128 DIFF_PER_FILE_BYTES, DIFF_TOTAL_BYTES, _AGENTIC_INVESTIGATE_SYSTEM,
129 _FINDINGS_SCHEMA, _SURVIVED_SCHEMA, _REWAKE_SUMMARY_BUDGET,
130 _cap_files_for_prompt, _build_auth_headers, _call_claude, _call_claude_dual_or,
131 _format_vulns_guidance, _format_vulns_summary, _finding_keys, _dedup_against_state,
132 analyze_code_security, _agentic_commit_review_enabled, agentic_review,
133 analyze_security_concerns,
134)
135
136# LLM-based code security review (enabled by default when API key is available)
137# Empty string or unset = enabled (default); "0" = disabled
138_enable_code_review_str = os.environ.get("ENABLE_CODE_SECURITY_REVIEW", "1")
139ENABLE_CODE_SECURITY_REVIEW = _enable_code_review_str != "0"
140
141# Pattern-based rules (enabled by default; set to "0" to use only LLM review)
142# Empty string or unset = enabled (default); "0" = disabled
143_enable_pattern_str = os.environ.get("ENABLE_PATTERN_RULES", "1")
144ENABLE_PATTERN_RULES = _enable_pattern_str != "0"
145
146# Per-feature kill switches. Each defaults to enabled. Set to "0" to disable
147# just that one feature without touching the rest. Motivated by feedback that
148# autonomous-agent setups sometimes need to disable specific injection points
149# (e.g. the PreToolUse[Task] prompt append, which can read as prompt injection
150# to hardened subagents) while keeping the rest of the plugin active. See
151# README for a full description of each feature.
152# Commit review also honors legacy SECURITY_GUIDANCE_COMMIT_REVIEW=off; see
153# is_commit_review_enabled().
154ENABLE_COMMIT_REVIEW = os.environ.get("ENABLE_COMMIT_REVIEW", "1") != "0"
155# Stop-hook git-diff review only — does NOT gate the commit/push reviews.
156# Lets multi-agent / shared-worktree deployments keep the commit reviewer
157# (anchored to a fixed SHA from the worker's own `git commit` stdout) while
158# turning off the Stop-hook diff (anchored on baseline_sha…HEAD, which a
159# sibling agent in the same worktree can move under us). The pre-existing
160# ENABLE_CODE_SECURITY_REVIEW gate is shared between Stop and commit/push
161# and stays for backwards compat as the all-LLM-review master switch.
162ENABLE_STOP_REVIEW = os.environ.get("ENABLE_STOP_REVIEW", "1") != "0"
163
164# Master kill switch. Either SECURITY_GUIDANCE_DISABLE=1 or
165# ENABLE_SECURITY_REMINDER=0 disables the plugin entirely. Kept as two names
166# because ENABLE_SECURITY_REMINDER predates the rename and some users already
167# have it baked into shell rc files; SECURITY_GUIDANCE_DISABLE reads correctly
168# as a kill switch (no double-negative).
169_disable_str = os.environ.get("SECURITY_GUIDANCE_DISABLE", "").strip().lower()
170SECURITY_GUIDANCE_DISABLED = (
171 _disable_str in ("1", "true", "yes", "on")
172 or os.environ.get("ENABLE_SECURITY_REMINDER", "1") == "0"
173)
174
175# Maximum number of times the stop hook can fire per user turn.
176# Allows iterative fixing: Claude stops → review → fix → stop → review again.
177# Set to 0 for unlimited (like the old plugin). Default 3 for iterative fixing.
178MAX_STOP_HOOK_FIRINGS = int(os.environ.get("MAX_STOP_HOOK_FIRINGS", "3"))
179
180# Cap on source files sent to the LLM reviewer per Stop fire. A stale baseline
181# meeting an ungitignored build directory can produce an enormous spurious
182# diff; unbounded diffs burn tokens and risk 400 on context length.
183MAX_DIFF_FILES = int(os.environ.get("MAX_DIFF_FILES", "30"))
184
185# Appended to all exit(2) guidance so the asyncRewake auto-turn doesn't
186# cause the model to abandon the user's original request.
187CONTINUATION_SUFFIX = (
188 "\n\nAfter addressing or acknowledging this finding, continue with the "
189 "user's original request or continue waiting for their reply — this "
190 "review is supplementary feedback, not a replacement for your previous "
191 "response."
192)
193
194def emit_metrics(metrics, rewake_summary=None):
195 """
196 Write a SyncHookJSONOutput line to stdout for Claude Code to pick up.
197 For asyncRewake (Stop) hooks, CC scans stdout for the first {-prefixed line
198 that validates as SyncHookJSONOutput and emits the hook metrics event.
199 For sync (PostToolUse) hooks, the metrics key in the normal JSON response
200 is picked up directly.
201
202 Constraints: keys ^[a-z][a-z0-9_]{0,39}$, values bool|finite-number,
203 20-key cap (was 10 in older CC versions).
204
205 `pv` and the tok_*/cost_usd usage block are PREPENDED so they survive any
206 future overflow — CC keeps only the first 20 keys, so insertion order
207 decides what drops. The old `len(metrics) < 10` guard was load-bearing for
208 the same reason but stale: once `rate_count` was added to every
209 commit-review emit, the with-vulns dict hit 10 keys, `pv` was skipped, and
210 findings metrics landed without a plugin version attached, breaking
211 per-version breakdowns.
212
213 `rewake_summary` (asyncRewake only): per-run override of the static
214 rewakeSummary in hooks.json, shown to the user in the terminal as the
215 task-notification one-liner. Must be in the same JSON line as the metrics
216 because CC stops scanning stdout after the first {-prefixed line.
217 """
218 head = {}
219 if _PV and "pv" not in metrics:
220 head["pv"] = _PV
221 head.update(_usage_metrics())
222 if head:
223 metrics = {**head, **metrics}
224 out = {"metrics": metrics}
225 if rewake_summary:
226 out["rewakeSummary"] = rewake_summary
227 print(json.dumps(out), flush=True)
228
229# =====================================================================
230# State management
231# =====================================================================
232
233#
234# Low-level state-file plumbing (_state_key, get_state_file,
235# get_lock_file, cleanup_old_state_files, load_state, save_state,
236# with_locked_state) moved to session_state.py and re-exported above.
237
238def atomic_check_and_mark_warning(session_id, warning_key):
239 """
240 Atomically check if a warning has been shown and mark it as shown if not.
241 Returns True if this is the first time seeing this warning (should show it),
242 False if it was already shown (should skip it).
243 """
244 def _check(state):
245 warnings = state["shown_warnings"]
246 if warning_key in warnings:
247 return False
248 warnings.append(warning_key)
249 return True
250
251 result = with_locked_state(session_id, _check)
252 return result if result is not None else True
253
254def atomic_check_counter(session_id, counter_key, max_count):
255 """
256 Atomically check if a counter has reached its limit and increment if not.
257 Returns True if the counter is below max_count (should proceed),
258 False if it has reached or exceeded max_count (should skip).
259 """
260 def _check(state):
261 counters = state.get("counters", {})
262 current = counters.get(counter_key, 0)
263 if current >= max_count:
264 return False
265 counters[counter_key] = current + 1
266 state["counters"] = counters
267 return True
268
269 result = with_locked_state(session_id, _check)
270 return result if result is not None else True
271
272def atomic_check_rate_limit(session_id, key, max_per_window, window_s):
273 """Rolling-window rate limit: allow at most `max_per_window` calls per
274 `window_s` seconds, per (session_id, key).
275
276 Returns (allowed: bool, count_in_window: int). count_in_window is the
277 post-decision count (i.e., includes this call if allowed) so callers can
278 emit it directly as a telemetry gauge.
279
280 Replaces session-lifetime `atomic_check_counter` for commit-review and
281 push-sweep. Telemetry showed a small but persistent share of sessions hit
282 the lifetime cap, and those were multi-day persistent sessions that then
283 lost coverage for many subsequent commits — not burst abusers. A rolling
284 hour keeps the same cost ceiling for any 1h window while letting long
285 sessions regain coverage.
286
287 State key: rate_limits: {"<key>": [ts, ts, ...]}. Timestamps are pruned
288 on every call so the list is bounded by max_per_window; no migration
289 needed from the old `counters` dict — different key.
290 """
291 import time as _time
292 now = _time.time()
293 cutoff = now - window_s
294
295 def _check(state):
296 buckets = state.setdefault("rate_limits", {})
297 ts_list = buckets.get(key, [])
298 # Prune; tolerate non-numeric junk from a corrupted state file.
299 ts_list = [t for t in ts_list if isinstance(t, (int, float)) and t > cutoff]
300 if len(ts_list) >= max_per_window:
301 buckets[key] = ts_list
302 return False, len(ts_list)
303 ts_list.append(now)
304 buckets[key] = ts_list
305 return True, len(ts_list)
306
307 result = with_locked_state(session_id, _check)
308 # State unavailable → fail-open (same posture as atomic_check_counter).
309 return result if result is not None else (True, 0)
310
311# =====================================================================
312# Warning outcome tracking
313#
314# Records each pattern warning as pending when it fires. At Stop, sweep
315# all pending entries: re-read each file, re-check patterns, and emit a
316# fixed-vs-unresolved tally. No per-edit work — pending is recorded only
317# when a pattern matches (rare), and the sweep runs once at session end.
318#
319# State key: pending_warnings: {"<file>:<rule>": true}
320# =====================================================================
321
322def record_pending_warnings(session_id, file_path, rule_names):
323 """Mark file:rule pairs as pending for the Stop-hook outcome sweep."""
324 def _record(state):
325 pending = state.get("pending_warnings")
326 if not isinstance(pending, dict):
327 pending = {}
328 state["pending_warnings"] = pending
329 for rule in rule_names:
330 pending[f"{file_path}:{rule}"] = True
331 with_locked_state(session_id, _record)
332
333def sweep_pending_warnings(session_id):
334 """
335 Stop-hook final sweep. Re-read every file in pending_warnings, re-check
336 patterns, and return (fixed, unresolved, unresolved_mask). Clears state.
337 A file that's been deleted counts as fixed — the dangerous code is gone.
338 Never raises — this is telemetry and must not break the Stop hook.
339 """
340 def _sweep(state):
341 try:
342 pending = state.get("pending_warnings")
343 if not isinstance(pending, dict) or not pending:
344 return 0, 0, 0
345
346 by_file = {}
347 for key in pending:
348 if not isinstance(key, str) or ":" not in key:
349 continue
350 fp, _, rule = key.rpartition(":")
351 by_file.setdefault(fp, set()).add(rule)
352
353 unresolved = []
354 fixed = 0
355 for fp, rules in by_file.items():
356 try:
357 with open(fp, "r", errors="replace") as f:
358 still_matching = {r for r, _ in check_patterns(fp, f.read())}
359 except (OSError, IOError):
360 still_matching = set()
361 for rule in rules:
362 if rule in still_matching:
363 unresolved.append(rule)
364 else:
365 fixed += 1
366
367 state["pending_warnings"] = {}
368 # Filter to known rules so a renamed/removed rule in old state
369 # doesn't KeyError rule_names_to_mask.
370 known = [r for r in unresolved if r in _RULE_NAME_TO_ID]
371 return fixed, len(unresolved), rule_names_to_mask(known)
372 except Exception as e:
373 debug_log(f"sweep_pending_warnings failed: {e}")
374 return 0, 0, 0
375
376 result = with_locked_state(session_id, _sweep)
377 return result if result is not None else (0, 0, 0)
378
379# =====================================================================
380# Git baseline management
381# =====================================================================
382
383# =====================================================================
384# Pattern matching
385# =====================================================================
386
387def check_patterns(file_path, content):
388 """Check if file path or content matches any security patterns. Returns ALL matches."""
389 normalized_path = file_path.lstrip("/")
390 matches = []
391
392 for pattern in list(SECURITY_PATTERNS) + extensibility.user_patterns():
393 # path_filter is a gate: when present, the rule only applies to
394 # matching paths. Distinct from path_check, which is itself a
395 # positive match condition (e.g. .github/workflows/).
396 if "path_filter" in pattern:
397 try:
398 if not pattern["path_filter"](normalized_path):
399 continue
400 except Exception:
401 continue
402
403 matched = False
404
405 if "path_check" in pattern:
406 try:
407 if pattern["path_check"](normalized_path):
408 matched = True
409 except Exception:
410 pass
411
412 if not matched and "substrings" in pattern and content:
413 for substring in pattern["substrings"]:
414 if substring in content:
415 matched = True
416 break
417
418 if not matched and "regex" in pattern and content:
419 try:
420 if re.search(pattern["regex"], content):
421 matched = True
422 except Exception:
423 pass
424
425 if matched:
426 matches.append((pattern["ruleName"], pattern["reminder"]))
427
428 return matches
429
430def extract_content_from_input(tool_name, tool_input):
431 """Extract content to check from tool input based on tool type."""
432 if tool_name == "Write":
433 return tool_input.get("content", "")
434 elif tool_name == "Edit":
435 return tool_input.get("new_string", "")
436 elif tool_name == "MultiEdit":
437 edits = tool_input.get("edits", [])
438 if edits:
439 return " ".join(edit.get("new_string", "") for edit in edits)
440 return ""
441 return ""
442
443# =====================================================================
444# Hook handlers
445# =====================================================================
446
447def handle_user_prompt_submit(input_data):
448 """
449 Handle UserPromptSubmit — capture git baseline SHA.
450 Called on every user prompt. Updates the baseline so the stop hook
451 only reviews changes made since the last prompt.
452
453 Does NOT reset touched_paths/fire_count/previous_findings — those are
454 consumed by Stop (consume_stop_state) and time-expired respectively.
455 UPS racing the asyncRewake Stop hook caused a meaningful share of reviews
456 to be lost when the wipe landed before Stop's state read.
457
458 """
459 cwd = input_data.get("cwd", "")
460 if not cwd:
461 debug_log("UPS: no cwd, skipping baseline capture")
462 sys.exit(0)
463
464 session_id = input_data.get("session_id", "default")
465 # stash-create and ls-files both walk the worktree (~2-5s each in a very
466 # large repo). Run them concurrently so UPS latency stays ≈ max(both).
467 import concurrent.futures as _cf
468 with _cf.ThreadPoolExecutor(max_workers=2) as _ex:
469 _f_sha = _ex.submit(capture_git_baseline, cwd)
470 _f_ut = _ex.submit(_list_untracked, cwd)
471 sha = _f_sha.result()
472 # Always capture the untracked snapshot. `git stash create` returns
473 # empty when there are no TRACKED changes, but pre-existing untracked
474 # files still need to be excluded from the next Stop's review_set —
475 # otherwise an untracked-only working tree gets every untracked file
476 # reviewed on every turn until something tracked is dirtied.
477 untracked_now = _f_ut.result() or {}
478 head = _git_rev_parse_head(cwd)
479
480 # If the previous turn's Stop hook never ran (user interrupt, follow-up
481 # during work, tool-reject, model crash, maxTurns, PostToolUse block…),
482 # touched_paths is still populated because consume_stop_state is the only
483 # consumer and it runs under the state lock. Overwriting baseline_sha now
484 # would re-baseline *past* those unreviewed edits, making them permanently
485 # invisible to the next Stop. Preserve the old baseline so the next Stop
486 # diffs the aborted turn's edits plus the new turn's edits together.
487 preserved = {"value": False}
488
489 def _save(state):
490 # Only preserve if there's actually an old baseline to preserve.
491 # First UPS of a session can have touched_paths if PostToolUse
492 # somehow ran first (print mode, odd harnesses) — in that case
493 # we still need to capture a baseline.
494 if state.get("touched_paths") and state.get("baseline_sha"):
495 preserved["value"] = True
496 return
497 if sha:
498 state["baseline_sha"] = sha
499 state["head_at_capture"] = head
500 # untracked_at_baseline is independent of whether the stash produced
501 # a SHA — write it unconditionally so compute_v2_review_set's
502 # preexisting-untracked exclusion works in untracked-only trees.
503 state["untracked_at_baseline"] = untracked_now
504 with_locked_state(session_id, _save)
505
506 if preserved["value"]:
507 debug_log(
508 "UPS: preserving prior baseline — previous Stop hook never "
509 "consumed touched_paths (likely user interrupt / aborted turn)"
510 )
511 elif sha:
512 debug_log(f"Captured git baseline: {sha[:12]}")
513 else:
514 debug_log("Failed to capture git baseline (not a git repo?)")
515
516 sys.exit(0)
517
518def _resolve_amend_pre_sha(repo_root, expected_post_sha=None):
519 """For a `git commit --amend` we just ran, return the pre-amend SHA via
520 reflog, or None if it can't be safely determined.
521
522 expected_post_sha: the post-amend SHA the caller parsed from bash stdout
523 (or reflog). If provided, HEAD@{0} of `repo_root` must match it (prefix
524 compare — bash stdout SHAs are abbreviated, reflog %H is 40 chars) before
525 we trust the reflog-derived pre-amend SHA. This guards against the
526 cross-repo case (`cd ../other && git commit --amend && cd -`) where
527 `repo_root` happens to have its own recent amend that's unrelated to
528 the bash command we're reviewing.
529
530 We require HEAD@{0}'s reflog subject to start with `commit (amend)` —
531 otherwise our `--amend` regex matched something that didn't actually
532 perform an amend (e.g., `git commit --amend --dry-run`, aliased commands,
533 aborted amends), and HEAD@{1} would be the wrong commit. Also requires
534 HEAD@{1} to NOT itself be an amend, since back-to-back amends would have
535 HEAD@{1} as the previous-amend's post state — the original commit we
536 want to compare against is then HEAD@{2}, but at that point we're
537 reaching and fall back to a full review.
538
539 Bytes + decode('utf-8', errors='replace'): reflog subjects embed commit
540 subjects, which git stores as raw bytes (commit messages may be latin-1
541 / cp1252 / etc.). text=True would raise UnicodeDecodeError (a
542 ValueError, not OSError) on non-UTF8 bytes and crash the hook.
543 """
544 if not repo_root:
545 return None
546 try:
547 r = subprocess.run(
548 [*GIT_CMD, "log", "-g", "-2", "--format=%H|%gs", "HEAD"],
549 cwd=repo_root, capture_output=True, timeout=5,
550 )
551 except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
552 return None
553 if r.returncode != 0:
554 return None
555 stdout_text = r.stdout.decode("utf-8", errors="replace")
556 lines = [ln for ln in stdout_text.splitlines() if "|" in ln]
557 if len(lines) < 2:
558 return None
559 head0_sha, _, head0_subj = lines[0].partition("|")
560 head1_sha, _, head1_subj = lines[1].partition("|")
561 if not head0_subj.startswith("commit (amend)"):
562 return None
563 if head1_subj.startswith("commit (amend)"):
564 return None
565 # Cross-repo guard: the post-amend SHA the caller is about to review must
566 # match HEAD@{0} of repo_root. Otherwise the bash command was likely run
567 # in a different repo than repo_root, and the reflog we just read is
568 # unrelated. Prefix-compare: expected_post_sha is typically the 7-char
569 # abbreviated SHA captured from bash stdout by _COMMIT_SHA_RE (git's
570 # default core.abbrev floor), while head0_sha is the full 40-char %H —
571 # strict equality would always fail and silently disable the delta path.
572 if expected_post_sha and not head0_sha.startswith(expected_post_sha):
573 return None
574 return head1_sha or None
575
576# git-only signals that corroborate a real commit object — NOT emitted by
577# pre-commit / lint-staged / husky hook output, which can contain bracketed
578# labels like `[pre-commit abc1234]` that otherwise look like a commit line.
579_COMMIT_DIFFSTAT_PATTERNS = [
580 re.compile(r'\b\d+ files? changed'),
581 re.compile(r'^ create mode ', re.MULTILINE),
582 re.compile(r'^ delete mode ', re.MULTILINE),
583 re.compile(r'^ rename ', re.MULTILINE),
584]
585
586# Capture-group form of the [branch sha] pattern. Mirrors Claude Code's own
587# commit-id parsing, but tolerates spaces before the
588# sha (covers `[detached HEAD abc1234]`). 7–40 hex chars: git's abbrev floor
589# through full sha; the abbrev resolves fine with `git show`. Anchored to
590# line-start so a `[hex]` in the commit subject (`[main abc] Revert [e38]`)
591# or trailing hook output isn't picked up and fed to `git show`.
592_COMMIT_SHA_RE = re.compile(r'^\[[^\]]*?\b([0-9a-f]{7,40})\]', re.MULTILINE)
593
594# Regex matching `git commit` commands. Mirrors Claude Code's own commit
595# detection — it does NOT tolerate `git -c k=v commit` global options, which
596# keeps this hook aligned with CC's commit attribution on what counts as a
597# commit.
598_GIT_COMMIT_RE = re.compile(r'\bgit\s+commit(?:\s|$)')
599_GIT_AMEND_RE = re.compile(r'\s--amend\b')
600
601# Rolling-window cap on LLM commit-review calls. See atomic_check_rate_limit
602# docstring for the rationale that motivated the switch from a lifetime cap.
603# `MAX_COMMIT_REVIEWS_PER_SESSION` is read for backward-compat with users who
604# tuned it; the value is reinterpreted as per-hour.
605MAX_COMMIT_REVIEWS_PER_HOUR = int(
606 os.environ.get("MAX_COMMIT_REVIEWS_PER_HOUR")
607 or os.environ.get("MAX_COMMIT_REVIEWS_PER_SESSION", "20")
608)
609COMMIT_REVIEW_RATE_WINDOW_S = int(
610 os.environ.get("COMMIT_REVIEW_RATE_WINDOW_S", "3600")
611)
612
613# ─── push-sweep ─────────────────────────────────────────────────────────────
614#
615# Mirrors Claude Code's own push-command matching — tolerates `git -C <p>` /
616# `git -c k=v` global options. The hooks.json `Bash(git push:*)` matcher
617# (subcommand prefix) doesn't, but those forms are rare in practice
618# and the python only ever runs after CC's matcher fired, so this regex is a
619# defensive re-gate, not a widening — `git -C path push` won't reach python
620# unless chained with a plain `git push` in the same compound command.
621#
622# `gh pr create` is intentionally NOT a separate hooks.json matcher: gh runs
623# `git push` as a child process, which CC's matcher doesn't observe (it sees
624# only the top-level `gh pr create` argv). A separate `Bash(gh pr create:*)`
625# entry would buy minimal extra coverage (sessions that push only via gh) at
626# the cost of an extra python spawn on every `... && gh pr create` compound
627# (the common case). Those sessions are caught on their next standalone `git push`.
628_GIT_PUSH_RE = re.compile(
629 r'\bgit(?:\s+-[cC]\s+\S+|\s+--\S+=\S+)*\s+push\b'
630)
631
632# `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on
633# force, `* [new branch]` on first push). The left sha is where the remote
634# was BEFORE this push — exactly the base we need. Captures (old, new,
635# local-ref) so the handler can verify the pushed ref == HEAD before
636# diffing — `git push origin other` while on a different branch would
637# otherwise diff the wrong range.
638_PUSH_RANGE_RE = re.compile(
639 r'^\s*\+?\s*([0-9a-f]{7,40})\.\.\.?([0-9a-f]{7,40})\s+(\S+)\s+->\s+\S+',
640 re.MULTILINE,
641)
642
643MAX_PUSH_SWEEP_FILES = int(os.environ.get("SG_PUSH_SWEEP_MAX_FILES", "30"))
644MAX_PUSH_SWEEP_RANGE = int(os.environ.get("SG_PUSH_SWEEP_MAX_RANGE", "50"))
645PUSH_SWEEP_REPORT_CAP = int(os.environ.get("SG_PUSH_SWEEP_REPORT_CAP", "3"))
646
647def _claim_bash_hook_once(input_data):
648 """De-dupe across hooks.json `if` matchers firing for the same Bash call.
649
650 `git commit -m x && git push` matches both `Bash(git commit:*)` and
651 `Bash(git push:*)` `if` configs → CC spawns this script twice with the
652 SAME `tool_use_id`. The first spawn atomically creates a
653 sentinel under `.git/`; subsequent spawns see it and exit early. Avoids
654 redundant LLM calls (and the redundant asyncRewake) on compound commands.
655
656 Returns True if this spawn won the claim (or no de-dupe is possible),
657 False if another spawn already claimed it.
658
659 Sentinel is per-clone (`.git/sg-hook-once-<tool_use_id>`), not /tmp,
660 so concurrent CC sessions in *different* repos don't collide. Stale
661 sentinels (>5min) are GC'd opportunistically.
662 """
663 tuid = input_data.get("tool_use_id")
664 cwd = input_data.get("cwd")
665 if not tuid or not cwd:
666 return True
667 gd = _git_dir(_git_toplevel(cwd) or cwd)
668 if not gd:
669 return True
670 # GC: best-effort sweep of stale sentinels so they don't accumulate.
671 import time as _time
672 now = _time.time()
673 try:
674 for name in os.listdir(gd):
675 if name.startswith("sg-hook-once-"):
676 p = os.path.join(gd, name)
677 try:
678 if now - os.path.getmtime(p) > 300:
679 os.unlink(p)
680 except OSError:
681 pass
682 except OSError:
683 pass
684 # Sanitize tuid into a filesystem-safe basename — defensive, the value is
685 # CC-generated (toolu_<b64ish>), but it ends up in a path.
686 safe = re.sub(r"[^A-Za-z0-9_-]", "_", tuid)[:80]
687 sentinel = os.path.join(gd, f"sg-hook-once-{safe}")
688 try:
689 fd = os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
690 os.close(fd)
691 return True
692 except FileExistsError:
693 return False
694 except OSError:
695 # Can't write sentinel (read-only fs, perms) — proceed rather than
696 # silently dropping the review.
697 return True
698
699def is_push_sweep_enabled():
700 """Gate for the push-sweep PostToolUse[Bash] hook.
701
702 Enabled by default. ENABLE_COMMIT_REVIEW=0 remains the unconditional
703 kill switch (push-sweep reuses the same review pipeline and budget).
704 SG_PUSH_SWEEP is the per-user override (=1/on or =0/off) checked
705 next so users can opt out.
706 """
707 if not ENABLE_COMMIT_REVIEW:
708 return False
709 v = os.environ.get("SG_PUSH_SWEEP", "").strip().lower()
710 if v in ("1", "on"):
711 return True
712 if v in ("0", "off"):
713 return False
714 return True
715
716PUSH_SWEEP_ENABLED = is_push_sweep_enabled()
717
718def _compute_push_sweep_base(prev_upstream, push_range, reviewed):
719 """Advance the diff base past the contiguous reviewed prefix.
720
721 Spec: review `git diff B..HEAD` where `B` is the newest commit such that
722 `prev_upstream..B` is entirely in `reviewed`. Returns (B, unreviewed_tail).
723 `B == None` means the whole range is reviewed (caller should skip).
724 `push_range` must be oldest→newest.
725
726 Examples (✓=reviewed, ✗=not):
727 [✓1, ✗2, ✓3] → B=1, tail=[2,3] (cannot trim suffix; Read is at HEAD)
728 [✓1, ✓2, ✓3] → B=None (all reviewed → skip)
729 [✗1, ✓2, ✗3] → B=prev_upstream, tail=[1,2,3]
730 [] → B=None
731 """
732 i = 0
733 while i < len(push_range) and push_range[i] in reviewed:
734 i += 1
735 if i == len(push_range):
736 return None, []
737 base = push_range[i - 1] if i > 0 else prev_upstream
738 return base, push_range[i:]
739
740def _push_section(bash_output):
741 """Return the slice of `bash_output` that contains the push's range lines.
742
743 `_PUSH_RANGE_RE` is not push-specific — `git fetch` and `git pull` print
744 range lines (`abc..def branch -> origin/branch`) in the same format. On
745 chained calls the Bash tool returns combined stdout+stderr, so a naive
746 `_PUSH_RANGE_RE.finditer(bash_output)` matches both sections and a
747 fetch+push compound trips the multi-ref skip.
748
749 `git push` prints `To <remote>` immediately before its range lines;
750 `git fetch`/`git pull` prints `From <remote>` before theirs. The slice
751 is symmetric: start at the LAST `To <remote>` header (strips fetch output
752 that ran *before* the push, e.g. `git fetch && git push`), and end at
753 the next `From <remote>` after that (strips fetch output that ran
754 *after* the push, e.g. `git push && git fetch`).
755
756 If no `To ` header is present (push failed before connecting, output
757 suppressed by `-q`) the full buffer is returned and the caller's
758 other guards handle it.
759 """
760 if not bash_output:
761 return ""
762 # Match line-anchored "To " — look for "\nTo " or "To " at start-of-string.
763 idx = bash_output.rfind("\nTo ")
764 if idx >= 0:
765 section = bash_output[idx:]
766 elif bash_output.startswith("To "):
767 section = bash_output
768 else:
769 return bash_output
770 # Strip a trailing fetch/pull `From <remote>` block (push && fetch /
771 # push && pull, or any wrapper that re-syncs after the push).
772 end = section.find("\nFrom ")
773 if end >= 0:
774 section = section[:end]
775 return section
776
777def _detect_prev_upstream(repo_root, bash_output):
778 """Where the remote was BEFORE this push.
779
780 Preference order:
781 1. Parse `abc..def` from push stdout — authoritative, exact.
782 2. `<branch>@{u}@{1}` — the remote-tracking ref's reflog position before
783 this push moved it. PostToolUse runs after `git push` completes, so
784 `@{u}` is already updated and `@{u}@{1}` is the prior value.
785 3. merge-base with the detected main branch — first push of a new
786 branch (`* [new branch]` in output, no upstream reflog yet).
787 Returns a resolvable ref/sha or None.
788 """
789 m = _PUSH_RANGE_RE.search(_push_section(bash_output or ""))
790 if m:
791 return m.group(1)
792 # @{u}@{1} — only meaningful if an upstream is configured.
793 for ref in ("@{u}@{1}", "@{push}@{1}"):
794 try:
795 r = subprocess.run(
796 [*GIT_CMD, "rev-parse", "--verify", "-q", ref],
797 cwd=repo_root, capture_output=True, text=True, timeout=5,
798 )
799 if r.returncode == 0 and r.stdout.strip():
800 return r.stdout.strip()
801 except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
802 pass
803 main = _detect_main_branch(repo_root)
804 if main:
805 try:
806 r = subprocess.run(
807 [*GIT_CMD, "merge-base", "HEAD", main],
808 cwd=repo_root, capture_output=True, text=True, timeout=5,
809 )
810 if r.returncode == 0 and r.stdout.strip():
811 return r.stdout.strip()
812 except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
813 pass
814 return None
815
816def is_commit_review_enabled():
817 """Gate for the commit-review PostToolUse[Bash] hook.
818
819 Commit review is enabled by default; ENABLE_COMMIT_REVIEW=0 remains the
820 unconditional kill switch and SECURITY_GUIDANCE_COMMIT_REVIEW (on/off)
821 remains a legacy per-user override; everything else defaults on.
822 commit_review_on is still emitted in metrics for continuity.
823 """
824 if not ENABLE_COMMIT_REVIEW:
825 return False
826 override = os.environ.get("SECURITY_GUIDANCE_COMMIT_REVIEW", "").strip().lower()
827 if override in ("on", "off"):
828 return override == "on"
829 return True
830
831COMMIT_REVIEW_ENABLED = is_commit_review_enabled()
832
833
834def _finding_snapshot(v):
835 """What previous_findings keeps of a finding. Stop and commit review
836 dedupe on (filePath, category); vulnerableCode only feeds the reviewer's
837 do-not-re-flag list, so it is stored masked — the state file must not
838 become a copy of a credential that lived in the working tree."""
839 category = v.get("category", "Unknown")
840 return {
841 "filePath": v.get("filePath", ""),
842 "category": category,
843 "vulnerableCode": review_api.redact_secret_values(v.get("vulnerableCode", ""), category=category),
844 }
845
846
847def _agentic_review_with_race(
848 repo_root: str,
849 diff_files: List[Tuple[str, str]],
850 rel_touched: List[str],
851 previous_findings: List[Dict[str, Any]],
852) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]:
853 """Race the agentic reviewer against a delayed single-shot fallback.
854
855 Agentic starts at t=0. After SG_AGENTIC_RACE_DELAY_S (default 180s), the
856 single-shot diff reviewer also starts. Whichever finishes first wins. If
857 agentic finishes before the delay elapses, the fallback never runs.
858
859 Metrics added:
860 race_winner : 1 = agentic won, 2 = fallback won (CC accepts only
861 bool/finite-number metric values — strings would discard the dict)
862 race_delay_s : the configured delay
863 race_started : 1 if the fallback was actually launched, else 0
864
865 Only the commit-review handler calls this — external harnesses invoke
866 agentic_review() directly and are unaffected. SG_AGENTIC_NO_RACE=1
867 disables the race for any other caller that wants pure agentic.
868 """
869 import queue as _queue
870 import threading as _th
871 import time as _t
872
873 if os.environ.get("SG_AGENTIC_NO_RACE") == "1":
874 return agentic_review(repo_root, diff_files, rel_touched)
875
876 delay_s = int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180"))
877 q: "_queue.Queue[Tuple[str, Any]]" = _queue.Queue(maxsize=1)
878 fallback_started = _th.Event()
879
880 def _agentic() -> None:
881 try:
882 r = agentic_review(repo_root, diff_files, rel_touched)
883 except Exception as e: # pragma: no cover — crash → let fallback win
884 r = (None, [], {"agentic_fallback": f"race_crash:{type(e).__name__}"})
885 try:
886 q.put_nowait(("agentic", r))
887 except _queue.Full:
888 pass
889
890 def _fallback() -> None:
891 _t.sleep(delay_s)
892 if not q.empty():
893 return # agentic finished within the delay — never start fallback
894 fallback_started.set()
895 try:
896 g, v = analyze_code_security(
897 diff_files, is_diff=True, previous_findings=previous_findings
898 )
899 except Exception as e: # pragma: no cover
900 g, v = None, []
901 try:
902 q.put_nowait(("fallback", (g, v, {"agentic": False})))
903 except _queue.Full:
904 pass
905
906 _th.Thread(target=_agentic, daemon=True).start()
907 _th.Thread(target=_fallback, daemon=True).start()
908
909 winner, (g, v, m) = q.get()
910 m = dict(m) # don't mutate the callee's metrics dict
911 m["race_winner"] = 1 if winner == "agentic" else 2
912 m["race_delay_s"] = delay_s
913 m["race_started"] = 1 if fallback_started.is_set() else 0
914 return g, v, m
915
916def handle_commit_review_posttooluse(input_data):
917 """PostToolUse handler for Bash — reviews git commits for security issues.
918
919 Runs as asyncRewake: detects `git commit` in the Bash command, parses
920 the resulting SHA(s) from the Bash stdout `[branch sha] msg` line, runs
921 `git show -p <sha>` per SHA, sends the combined diff through
922 analyze_code_security, and exits with code 2 (stderr findings) to wake
923 the model. Deduplicates against the shared previous_findings state so
924 the Stop hook won't re-flag the same (filePath, vulnerableCode) pair.
925 """
926 session_id = input_data.get("session_id", "default")
927 tool_input = input_data.get("tool_input", {})
928 tool_response = input_data.get("tool_response", {})
929 cwd = input_data.get("cwd", "")
930
931 command = tool_input.get("command", "")
932 if not isinstance(command, str) or not _GIT_COMMIT_RE.search(command):
933 # Defensive only — hooks.json's `"if": "Bash(git commit:*)"` is the
934 # real gate so CC never spawns python3 for ls/grep/etc. This catches
935 # cases where CC's command matching fails open and spawns the hook anyway.
936 sys.exit(0)
937
938 debug_log(f"Commit review: detected git commit in command")
939
940 # Bash tool_response has no exit_code field (only stdout, stderr,
941 # interrupted), so success is inferred from the output text — the same
942 # heuristic Claude Code itself uses.
943 if not isinstance(tool_response, dict):
944 tool_response = {}
945 stdout = tool_response.get("stdout", "") or ""
946 stderr = tool_response.get("stderr", "") or ""
947 bash_output = stdout + "\n" + stderr
948 interrupted = bool(tool_response.get("interrupted"))
949
950 # Require BOTH a line-anchored `[branch sha]` AND a git-only diffstat
951 # signal before treating the tool call as a successful commit. The old
952 # `any()` check false-positived on (a) pre-commit/husky/lint-staged hooks
953 # emitting labels like `[pre-commit abc1234]`, and on (b) chained
954 # `git commit || git log --stat` where `N files changed` appears in output
955 # even though the commit itself failed.
956 commit_succeeded = (
957 not interrupted
958 and _COMMIT_SHA_RE.search(bash_output) is not None
959 and any(p.search(bash_output) for p in _COMMIT_DIFFSTAT_PATTERNS)
960 )
961
962 # commit_review_on emitted on every path so telemetry can filter on
963 # commit_review and group by commit_review_on.
964 _base = {"commit_review": True, "commit_review_on": COMMIT_REVIEW_ENABLED}
965
966 # Reflog fallback for hidden stdout. Analysis of skip_reason=21 emissions
967 # showed a large share were commits that DID succeed
968 # but whose `[branch sha]` line was hidden by piping/redirection/-q
969 # (e.g., `git commit -m ... 2>&1 | tail -3`). A HEAD@{0}
970 # reflog check substantially reduced this skip; follow-up analysis found
971 # the residual is dominated by (a) chained commands moving HEAD@{0} past
972 # `commit:` (`git commit && git push`), and (b) the `_obvious_noop` guard
973 # false-positiving on chained `git status` output after a successful -q
974 # commit. Widening to the last-5-entries × 120s scan and dropping the noop
975 # guard fixes both. The reviewed-shas dedup below prevents the wider window
976 # from re-reviewing a prior Bash call's commit, and is the same file
977 # push-sweep reads — so a SHA is reviewed at most once across both
978 # surfaces. See _git_reflog_recent_commits docstring for cross-repo /
979 # race safety.
980 _reflog_shas: List[str] = []
981 _skip_21_sub = 0
982 if not commit_succeeded and not interrupted and cwd:
983 _root = _git_toplevel(cwd)
984 _fresh, _stale = _git_reflog_recent_commits(_root)
985 if _fresh:
986 _already = _load_reviewed_shas(_root)
987 _reflog_shas = [s for s in _fresh if s not in _already]
988 if _reflog_shas:
989 commit_succeeded = True
990 debug_log(
991 f"Commit review: stdout had no `[branch sha]`; reflog "
992 f"shows {len(_reflog_shas)} fresh unreviewed commit(s) "
993 f"({_reflog_shas[0][:12]}...)"
994 )
995 else:
996 # Fresh commit(s) in reflog but all already in
997 # sg-reviewed-shas — likely a Bash retry or the commit was
998 # reviewed via a prior fire. Correct to skip; sub=2 lets telemetry
999 # split this from genuine fails.
1000 _skip_21_sub = 2
1001 elif _stale:
1002 _skip_21_sub = 3 # commit entries exist but all >120s old
1003 else:
1004 _skip_21_sub = 4 # no commit-action entries — genuine fail
1005
1006 if not commit_succeeded:
1007 debug_log("Commit review: commit did not succeed, skipping")
1008 emit_metrics({"skipped": True, "skip_reason": 21, **_base,
1009 **({"skip_21_sub": 1} if interrupted
1010 else {"skip_21_sub": _skip_21_sub} if _skip_21_sub
1011 else {})})
1012 sys.exit(0)
1013
1014 if not COMMIT_REVIEW_ENABLED:
1015 debug_log("Commit review: disabled, skipping")
1016 emit_metrics({"skipped": True, "skip_reason": 32, **_base})
1017 sys.exit(0)
1018
1019 if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS:
1020 debug_log("Commit review: LLM review disabled or no API credentials")
1021 emit_metrics({"skipped": True, "skip_reason": 22, **_base})
1022 sys.exit(0)
1023
1024 if not ensure_anthropic_reachable():
1025 debug_log("Commit review: api.anthropic.com unreachable")
1026 emit_metrics({"skipped": True, "skip_reason": 24, **_base})
1027 sys.exit(0)
1028
1029 if not cwd:
1030 debug_log("Commit review: no cwd")
1031 emit_metrics({"skipped": True, "skip_reason": 25, **_base})
1032 sys.exit(0)
1033
1034 repo_root = _git_toplevel(cwd)
1035 if not repo_root:
1036 debug_log("Commit review: not in a git repo")
1037 emit_metrics({"skipped": True, "skip_reason": 26, **_base})
1038 sys.exit(0)
1039
1040 # Pin the review to the exact SHA the Bash command produced, parsed from
1041 # its stdout. Reviewing HEAD instead is wrong when the commit was made in
1042 # a different repo than the hook's cwd (`cd ../other && git commit && cd -`,
1043 # subshells), or when a second commit lands before this async hook reaches
1044 # `git show` — both would review an unrelated commit. The reflog-action
1045 # fallback above is the narrow exception: it only fires when output gave
1046 # us nothing AND the cwd repo's own reflog confirms a `commit:` just
1047 # happened there, which rules out the cross-repo case.
1048 #
1049 # Take only the LAST match: pre-commit/husky hooks can print bracketed
1050 # labels like `[pre-commit abc1234]` that precede the real `[branch sha]`
1051 # line; chained commands like `git commit && git commit` produce multiple
1052 # real SHAs and we want the most recent. The real commit line is always
1053 # last in git's own output — the earlier matches are either decoys or
1054 # superseded commits.
1055 if _reflog_shas:
1056 # Output-based detection already failed above; the reflog SHAs are the
1057 # authoritative ones. Don't re-parse bash_output here — any bracketed
1058 # token it contains is by construction NOT the `[branch sha]` line
1059 # (or commit_succeeded would have been True via the fast path). The
1060 # list is newest-first and may contain >1 entry when a single Bash
1061 # call made multiple commits (`git commit -m a && git commit -m b`);
1062 # all are reviewed.
1063 shas = _reflog_shas
1064 else:
1065 all_shas = _COMMIT_SHA_RE.findall(bash_output)
1066 shas = [all_shas[-1]] if all_shas else []
1067 if not shas:
1068 debug_log("Commit review: no SHA in commit output")
1069 emit_metrics({"skipped": True, "skip_reason": 33, **_base})
1070 sys.exit(0)
1071 if _reflog_shas:
1072 # Observability: track how often the fallback path is hit so
1073 # future analysis can split on it.
1074 # `reflog_shas_n` lets telemetry measure how often the widened scan picked
1075 # up >1 commit (i.e., chained `git commit && git commit`).
1076 _base = {**_base, "sha_via_reflog": True,
1077 "reflog_shas_n": len(_reflog_shas)}
1078
1079 # `git commit --amend`: review only the delta added by the amend
1080 # (pre-amend..post-amend) instead of the full amended commit. Without this,
1081 # the amend re-reviews the entire commit including code already reviewed
1082 # on the original commit, costing 30-60s of LLM time and re-flagging
1083 # findings the user may have just amended IN ORDER TO fix. Pre-amend
1084 # SHA comes from the reflog and is validated to be an amend (see
1085 # _resolve_amend_pre_sha) — otherwise we fall back to full-commit review.
1086 #
1087 # Three guards skip the delta path and fall back to full `git show`
1088 # review. All three close variants of "chained `git commit && git commit
1089 # --amend` in one Bash call", which would otherwise enter the delta path,
1090 # see an empty `git diff sha_wip sha_amend`, emit skip_reason=35, and
1091 # silently drop the first commit's content from review (no prior
1092 # PostToolUse fired for it — same Bash call):
1093 #
1094 # 1. `not _reflog_shas`: reflog fallback path was taken (both commits'
1095 # bash output suppressed via -q / pipe / redirect). The multi-SHA scan
1096 # already populates `shas` with every fresh commit (amend + any
1097 # pre-amend WIP) and the loop below `git show`s each, so coverage is
1098 # correct without delta — and the delta path doesn't compose with a
1099 # multi-SHA `shas` list (it would diff every entry against the same
1100 # pre-amend SHA). Losing the 30-60s saving on the reflog-fallback
1101 # fraction is an acceptable trade.
1102 #
1103 # 2. `len(all_shas) <= 1`: both commits visible (no -q). Two `[branch
1104 # sha]` lines in bash_output → all_shas len 2. Only defined on the
1105 # bash-output path; short-circuit ordering keeps it unevaluated when
1106 # `_reflog_shas` is non-empty.
1107 #
1108 # 3. `commit_invocations <= 1`: asymmetric — first commit -q, amend
1109 # visible. Fast-path fires on the amend's `[branch sha]` line (so
1110 # `_reflog_shas` stays empty), all_shas = [sha_amend] (len 1) — guards
1111 # 1 and 2 both pass. The command string itself is the only remaining
1112 # signal that two commits happened. False-positives (e.g.
1113 # `git commit --amend -m "fix git commit bug"`) are safe — they fall
1114 # back to full review.
1115 is_amend = bool(_GIT_AMEND_RE.search(command))
1116 commit_invocations = len(_GIT_COMMIT_RE.findall(command))
1117 pre_amend_sha = None
1118 if (is_amend and not _reflog_shas and len(all_shas) <= 1
1119 and commit_invocations <= 1):
1120 pre_amend_sha = _resolve_amend_pre_sha(repo_root, expected_post_sha=shas[0])
1121 if is_amend and pre_amend_sha:
1122 _base = {**_base, "amend_delta_review": True}
1123 debug_log(
1124 f"Commit review: --amend detected; reviewing delta "
1125 f"{pre_amend_sha[:12]}..{shas[-1][:12]}"
1126 )
1127
1128 # --no-color: `color.ui=always` would emit ANSI escapes that corrupt
1129 # parse_diff_into_files' header match. Bytes + errors='replace': commits
1130 # can contain non-UTF8 source (latin-1, cp1252) and text=True would raise
1131 # UnicodeDecodeError outside the except clause.
1132 diff_files = []
1133 resolved = 0
1134 for sha in shas:
1135 try:
1136 if pre_amend_sha:
1137 # Delta review: pre-amend → post-amend. `git diff` (not show)
1138 # so the output is a pure unified diff with no commit header.
1139 result = subprocess.run(
1140 [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", pre_amend_sha, sha, "--"],
1141 cwd=repo_root, capture_output=True, timeout=15
1142 )
1143 else:
1144 result = subprocess.run(
1145 [*GIT_CMD, "show", "-p", "--no-color", "--no-ext-diff", sha, "--"],
1146 cwd=repo_root, capture_output=True, timeout=15
1147 )
1148 except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
1149 _cmd = "git diff" if pre_amend_sha else "git show"
1150 debug_log(f"Commit review: {_cmd} {sha} error: {e}")
1151 continue
1152 if result.returncode != 0:
1153 # SHA not in this repo (cross-repo commit) or already gc'd. Better
1154 # to skip than to fall back to HEAD and review the wrong commit.
1155 _cmd = "git diff" if pre_amend_sha else "git show"
1156 debug_log(f"Commit review: {_cmd} {sha} rc={result.returncode}")
1157 continue
1158 resolved += 1
1159 diff_files.extend(parse_diff_into_files(
1160 result.stdout.decode("utf-8", errors="replace")))
1161
1162 # Dedup by path. The widened reflog scan can return >1 SHA (e.g.
1163 # `git commit && git commit --amend` within 120s); a path that appears in
1164 # both diffs would consume two MAX_DIFF_FILES slots and be re-analyzed.
1165 # `shas` is newest-first so the first occurrence is the most recent
1166 # version of the file — keep it.
1167 if len(shas) > 1:
1168 _seen = set()
1169 diff_files = [
1170 (fp, c) for fp, c in diff_files
1171 if not (fp in _seen or _seen.add(fp))
1172 ]
1173
1174 if resolved == 0:
1175 debug_log("Commit review: no parsed SHA resolved in cwd repo")
1176 emit_metrics({"skipped": True, "skip_reason": 28, **_base,
1177 "shas_found": len(shas)})
1178 sys.exit(0)
1179
1180 # Empty amend delta = message-only amend (or whitespace-only that the
1181 # diff already collapses). No code to review; skip cleanly. skip_reason=35.
1182 # Gated on resolved > 0 so subprocess failures (caught with `continue`
1183 # above) don't get mislabeled as message-only — they fall through to
1184 # skip_reason=28 correctly.
1185 if pre_amend_sha and not diff_files:
1186 debug_log("Commit review: --amend produced empty delta (message-only?), skipping")
1187 emit_metrics({"skipped": True, "skip_reason": 35, **_base,
1188 "files_reviewed": 0})
1189 sys.exit(0)
1190
1191 debug_log(f"Commit review: {resolved}/{len(shas)} sha(s) resolved, "
1192 f"{len(diff_files)} files")
1193 if not diff_files:
1194 debug_log("Commit review: no reviewable source files in commit")
1195 emit_metrics({"skipped": True, "skip_reason": 30, **_base})
1196 sys.exit(0)
1197
1198 # Large commits (initial scaffolds, big refactors) used to bail here with
1199 # skip_reason=31. Large multi-file changes are exactly where
1200 # cross-file source→sink vulns hide. Reviewing nothing is
1201 # worse than reviewing the riskiest 30 — _cap_files_for_prompt already
1202 # bounds total bytes downstream so this can't blow context.
1203 # `diff_files_dropped` lets telemetry measure how often the prioritizer engages
1204 # and how much it drops; skip_reason=31 is now reserved for the truly
1205 # pathological case (e.g. >300 source files — almost certainly a bad
1206 # baseline, not a real commit).
1207 if len(diff_files) > 10 * MAX_DIFF_FILES:
1208 debug_log(f"Commit review: pathological diff ({len(diff_files)} files), skipping")
1209 emit_metrics({"skipped": True, "skip_reason": 31, **_base,
1210 "diff_files_count": len(diff_files)})
1211 sys.exit(0)
1212 diff_files, _dropped = _prioritize_diff_files(diff_files, MAX_DIFF_FILES)
1213 if _dropped:
1214 debug_log(f"Commit review: prioritized to {len(diff_files)} files "
1215 f"(dropped {_dropped} lower-risk)")
1216 _base = {**_base, "diff_files_dropped": _dropped}
1217
1218 # Rolling-hour rate limit on LLM spend, so only burn a slot once we know
1219 # we'll actually call analyze_code_security — skip 28/30/31/33 above are
1220 # free. `rate_count` is emitted on every fire (not just rejections) so
1221 # telemetry can show how close to the cap sessions run.
1222 _allowed, _rate_n = atomic_check_rate_limit(
1223 session_id, "CommitReview",
1224 MAX_COMMIT_REVIEWS_PER_HOUR, COMMIT_REVIEW_RATE_WINDOW_S)
1225 _base = {**_base, "rate_count": _rate_n}
1226 if not _allowed:
1227 debug_log("Commit review: hourly rate limit reached, skipping")
1228 emit_metrics({"skipped": True, "skip_reason": 23, **_base})
1229 sys.exit(0)
1230
1231 # Read previous_findings for dedup (shared with Stop hook)
1232 import time as _time
1233 now = _time.time()
1234
1235 def _read_previous(state):
1236 findings_ts = state.get("previous_findings_ts", 0)
1237 if (now - findings_ts) > PREVIOUS_FINDINGS_TTL_SEC:
1238 return []
1239 return list(state.get("previous_findings", []))
1240
1241 previous_findings = with_locked_state(session_id, _read_previous) or []
1242
1243 review_start = _time.time()
1244
1245 agentic_metrics: Dict[str, Any] = {}
1246 if _agentic_commit_review_enabled():
1247 rel_touched = [fp for fp, _ in diff_files]
1248 concrete_guidance, vulns, _am = _agentic_review_with_race(
1249 repo_root, diff_files, rel_touched, previous_findings
1250 )
1251 agentic_metrics.update(_am)
1252 # Fall back to single-shot only on agentic FAILURE (SDK/investigate
1253 # crash). If agentic completed and returned 0 findings, trust that.
1254 if agentic_metrics.get("agentic_fallback"):
1255 concrete_guidance, vulns = analyze_code_security(
1256 diff_files, is_diff=True, previous_findings=previous_findings
1257 )
1258 else:
1259 concrete_guidance, vulns = analyze_code_security(
1260 diff_files, is_diff=True, previous_findings=previous_findings
1261 )
1262
1263 # push-sweep state: record this commit as reviewed (full 40-hex sha) so a
1264 # later `git push` can advance its diff base past it. Recorded here — after
1265 # the review ran but before any exit path — so it's marked regardless of
1266 # whether findings were emitted. `shas` holds abbreviated refs from
1267 # `[branch sha]`; resolve to full so set-membership in the push-sweep is
1268 # exact. Best-effort; failures here never block the review result.
1269 try:
1270 full_shas = []
1271 for s in shas:
1272 r = subprocess.run(
1273 [*GIT_CMD, "rev-parse", "--verify", "-q", s],
1274 cwd=repo_root, capture_output=True, text=True, timeout=5,
1275 )
1276 if r.returncode == 0:
1277 full_shas.append(r.stdout.strip())
1278 _append_reviewed_shas(repo_root, full_shas, vulns_found=len(vulns or []))
1279 except Exception:
1280 pass
1281
1282 review_ms = int((_time.time() - review_start) * 1000)
1283 # `survived` is the raw self-refute count BEFORE the high/critical-only
1284 # severity filter; `survived_after_sev` is the count the user actually
1285 # sees. Include `survived_after_sev` ONLY when the filter actually
1286 # dropped candidates — otherwise it's redundant with `survived` and eats
1287 # into CC's 10-key emit cap, pushing files_reviewed/review_ms out of the
1288 # emitted metrics.
1289 #
1290 # CC accepts only booleans and finite numbers as metric values.
1291 # A null or string value makes CC discard the ENTIRE dict, so:
1292 # - candidates/survived are omitted when None (early-return at
1293 # candidates==0, or any fallback path)
1294 # - agentic_fallback is mapped to an int reason code; the string detail
1295 # stays in debug_log for diagnosis
1296 _sev_raw = agentic_metrics.get("survived")
1297 _sev_post = agentic_metrics.get("survived_after_sev")
1298 _cand = agentic_metrics.get("candidates")
1299 _fb = agentic_metrics.get("agentic_fallback")
1300 # 1 = SDK import failed (claude_agent_sdk not installed)
1301 # 2 = investigate stage failed (CLI/network/model error or schema-retry exhausted)
1302 _fb_code = (1 if _fb and _fb.startswith("import:") else 2) if _fb else None
1303 _race = agentic_metrics.get("race_winner")
1304 _agentic_m = (
1305 # `agentic` = which path produced the result, not which was attempted.
1306 # On race-loss the _fallback() metrics dict has agentic=False — emitting
1307 # True there blends the high-find-rate single-shot race-loss bucket into
1308 # `agentic=true` queries and overstates agentic yield.
1309 {"agentic": bool(agentic_metrics.get("agentic")),
1310 **({"candidates": _cand} if _cand is not None else {}),
1311 **({"survived": _sev_raw} if _sev_raw is not None else {}),
1312 **({"survived_after_sev": _sev_post}
1313 if _sev_post is not None and _sev_post != _sev_raw else {}),
1314 **({"agentic_fallback": _fb_code} if _fb_code is not None else {}),
1315 # 1 = agentic won, 2 = single-shot fallback won. review_ms already
1316 # captures timing; race_winner lets telemetry segment recall by which path
1317 # actually produced the result.
1318 **({"race_winner": _race} if _race is not None else {})}
1319 if agentic_metrics.get("agentic") or _fb or _race is not None
1320 else {}
1321 )
1322
1323 if not concrete_guidance:
1324 debug_log("Commit review: no security issues found")
1325 emit_metrics({
1326 "vulns_found": 0, **_base, **_agentic_m,
1327 "files_reviewed": len(diff_files), "review_ms": review_ms,
1328 **({
1329 "api_error": llm._last_call_claude_http_error
1330 } if llm._last_call_claude_http_error is not None else {}),
1331 })
1332 sys.exit(0)
1333
1334 # Late dedup: drop only what a concurrent Stop hook wrote while our LLM
1335 # ran. Anything in `previous_findings` (the pre-LLM snapshot) that the
1336 # LLM chose to re-flag is an intentional "fix incomplete" verdict.
1337 new_vulns, n_deduped = _dedup_against_state(
1338 session_id, vulns, prompted=_finding_keys(previous_findings)
1339 )
1340
1341 if not new_vulns:
1342 debug_log("Commit review: all findings already known, skipping")
1343 emit_metrics({
1344 "vulns_found": 0, **_base, **_agentic_m, "deduped": n_deduped,
1345 "files_reviewed": len(diff_files), "review_ms": review_ms,
1346 })
1347 sys.exit(0)
1348
1349 # Record new findings into shared state. Key on (filePath, category) —
1350 # vulnerableCode bytes drift between fires (diff context lines shift) so
1351 # matching on it under-dedupes; this aligns with Stop's _record_fire.
1352 finding_snapshots = [_finding_snapshot(v) for v in new_vulns]
1353
1354 def _record_findings(state):
1355 existing = [f for f in state.get("previous_findings", []) if isinstance(f, dict)]
1356 seen = {(f.get("filePath", ""), f.get("category", "")) for f in existing}
1357 for f in finding_snapshots:
1358 key = (f["filePath"], f["category"])
1359 if key not in seen:
1360 seen.add(key)
1361 existing.append(f)
1362 state["previous_findings"] = existing
1363 state["previous_findings_ts"] = _time.time()
1364 with_locked_state(session_id, _record_findings)
1365
1366 sev = {"critical": 0, "high": 0, "medium": 0}
1367 for v in new_vulns:
1368 s = v.get("severity", "medium")
1369 if s in sev:
1370 sev[s] += 1
1371
1372 emit_metrics({
1373 "vulns_found": len(new_vulns), **_base, **_agentic_m,
1374 "critical_count": sev["critical"], "high_count": sev["high"],
1375 "files_reviewed": len(diff_files), "review_ms": review_ms,
1376 **({"deduped": n_deduped} if n_deduped else {}),
1377 }, rewake_summary=_format_vulns_summary(new_vulns, prefix="Commit security review found"))
1378
1379 # Rebuild guidance from new_vulns only — concrete_guidance from the LLM
1380 # still lists deduped entries.
1381 sys.stderr.write(PROVENANCE_BANNER + "\n\n"
1382 + _format_vulns_guidance(new_vulns)
1383 + CONTINUATION_SUFFIX + "\n")
1384 sys.exit(2)
1385
1386def handle_push_sweep_posttooluse(input_data):
1387 """Review the just-pushed range as one diff, advancing the base past the
1388 contiguous prefix of already-per-commit-reviewed shas.
1389
1390 Spec: review `git diff B..HEAD` where `B` is the newest commit such that
1391 `prev_upstream..B` is entirely in `.git/sg-reviewed-shas`. Skip if
1392 `B == HEAD`. Mark `B..HEAD` reviewed afterward.
1393
1394 Diff and Read are both at HEAD (push doesn't move the working tree), so the
1395 agentic reviewer sees a consistent view — a vuln introduced in commit A and
1396 removed in commit B is absent from the net diff by construction. Any
1397 reviewed commits in the tail (after the first unreviewed one) are included
1398 in the diff; their findings are dropped by `_dedup_against_state` against
1399 `previous_findings` the per-commit hook already recorded.
1400
1401 Metrics: `push_sweep: True` is the telemetry splitter; `pushed`/`unreviewed`/
1402 `prefix_advanced` give the funnel; skip_reasons 40-49 are reserved for
1403 this surface.
1404 """
1405 tool_input = input_data.get("tool_input", {}) or {}
1406 tool_response = input_data.get("tool_response", {}) or {}
1407 command = tool_input.get("command", "") or ""
1408 cwd = input_data.get("cwd")
1409 session_id = input_data.get("session_id", "")
1410 bash_output = (
1411 (tool_response.get("stdout", "") or "")
1412 + "\n"
1413 + (tool_response.get("stderr", "") or "")
1414 )
1415 interrupted = tool_response.get("interrupted", False)
1416
1417 # Re-gate: hooks.json `if` matched, but confirm with the broader regex
1418 # (defensive — `git -C`/`-c` forms won't reach here via the hooks.json
1419 # prefix matcher alone, but a compound with a plain `git push` would).
1420 if not _GIT_PUSH_RE.search(command):
1421 sys.exit(0)
1422
1423 _base = {"push_sweep": True, "push_sweep_on": PUSH_SWEEP_ENABLED}
1424
1425 if not PUSH_SWEEP_ENABLED:
1426 emit_metrics({"skipped": True, "skip_reason": 40, **_base})
1427 sys.exit(0)
1428 if interrupted:
1429 emit_metrics({"skipped": True, "skip_reason": 21, **_base})
1430 sys.exit(0)
1431 if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS:
1432 emit_metrics({"skipped": True, "skip_reason": 22, **_base})
1433 sys.exit(0)
1434 if not cwd:
1435 emit_metrics({"skipped": True, "skip_reason": 25, **_base})
1436 sys.exit(0)
1437 repo_root = _git_toplevel(cwd)
1438 if not repo_root:
1439 emit_metrics({"skipped": True, "skip_reason": 26, **_base})
1440 sys.exit(0)
1441
1442 # Guard: the sweep diffs `base..HEAD` and the agent Reads the working
1443 # tree, so the pushed ref MUST be HEAD or the review is of the wrong
1444 # range. `git push origin other` while checked out elsewhere, or a
1445 # multi-ref push, are skipped (skip_reason 44). Check the new-tip from
1446 # the `abc..def local -> remote` line against HEAD.
1447 #
1448 # Scope range-line detection to the push section of bash_output: a chained
1449 # `git fetch && git push` produces fetch range lines that the regex would
1450 # otherwise match too, false-tripping multi-ref. `_push_section` slices
1451 # forward from the last `To <remote>` header.
1452 #
1453 # If there are no range lines, we MUST also see a positive push-success
1454 # signal (`* [new branch]` or `Everything up-to-date`) AND verify the
1455 # pushed local ref resolves to HEAD before falling through to the
1456 # @{u}@{1}/merge-base detection. Without this, two real cases misdirect
1457 # the sweep: `git push origin feature2` while on `feature1` (no range
1458 # line, no HEAD check → reviews wrong branch and poisons reviewed-shas),
1459 # and rejected pushes (no range line, no `interrupted` signal → reviews
1460 # unpushed local commits and marks them reviewed). skip_reason=46 covers
1461 # both.
1462 head = None
1463 try:
1464 r = subprocess.run([*GIT_CMD, "rev-parse", "HEAD"], cwd=repo_root,
1465 capture_output=True, text=True, timeout=5)
1466 head = r.stdout.strip() if r.returncode == 0 else None
1467 except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
1468 pass
1469 push_section = _push_section(bash_output or "")
1470 range_matches = list(_PUSH_RANGE_RE.finditer(push_section))
1471 if range_matches and head:
1472 # Multi-ref push (multiple range lines) or pushed-tip ≠ HEAD → skip.
1473 if len(range_matches) > 1:
1474 emit_metrics({"skipped": True, "skip_reason": 44, **_base})
1475 sys.exit(0)
1476 new_tip = range_matches[0].group(2)
1477 if not head.startswith(new_tip):
1478 debug_log(f"Push sweep: pushed tip {new_tip} != HEAD {head[:12]}")
1479 emit_metrics({"skipped": True, "skip_reason": 44, **_base})
1480 sys.exit(0)
1481 elif head:
1482 # No range lines. Need a positive push-success signal — otherwise
1483 # the push may have failed and we'd review unpushed local commits.
1484 new_branch_matches = re.findall(
1485 r"^\s*\*\s+\[new branch\]\s+(\S+)\s+->\s+\S+",
1486 push_section, re.M)
1487 up_to_date = "Everything up-to-date" in push_section
1488 # `git push -q` suppresses all output on success. Distinguish quiet-
1489 # success from a failed push (which has error text) by checking the
1490 # upstream's reflog: a successful push leaves @{u}@{1} (the prior
1491 # value) different from @{u} (now equal to HEAD). A rejected push
1492 # would not advance @{u}, so this signal is push-specific.
1493 quiet_success = False
1494 if not (bash_output or "").strip() and not interrupted:
1495 try:
1496 r_cur = subprocess.run(
1497 [*GIT_CMD, "rev-parse", "--verify", "-q", "@{u}"],
1498 cwd=repo_root, capture_output=True, text=True, timeout=5)
1499 r_prev = subprocess.run(
1500 [*GIT_CMD, "rev-parse", "--verify", "-q", "@{u}@{1}"],
1501 cwd=repo_root, capture_output=True, text=True, timeout=5)
1502 cur = r_cur.stdout.strip() if r_cur.returncode == 0 else ""
1503 prev_u = r_prev.stdout.strip() if r_prev.returncode == 0 else ""
1504 quiet_success = bool(cur and prev_u and cur == head and prev_u != cur)
1505 except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
1506 pass
1507 if not (new_branch_matches or up_to_date or quiet_success):
1508 debug_log("Push sweep: no push-success signal in bash output")
1509 emit_metrics({"skipped": True, "skip_reason": 46, **_base})
1510 sys.exit(0)
1511 # `* [new branch] local -> remote`: verify the pushed local ref
1512 # resolves to HEAD. `git push origin feature2` while on feature1
1513 # would otherwise review feature1's commits and poison its
1514 # reviewed-shas state.
1515 for local_ref in new_branch_matches:
1516 try:
1517 r = subprocess.run(
1518 [*GIT_CMD, "rev-parse", "--verify", "-q", local_ref],
1519 cwd=repo_root, capture_output=True, text=True, timeout=5,
1520 )
1521 local_sha = r.stdout.strip() if r.returncode == 0 else ""
1522 except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
1523 local_sha = ""
1524 if local_sha and local_sha != head:
1525 debug_log(f"Push sweep: new-branch {local_ref} ({local_sha[:12]}) != HEAD {head[:12]}")
1526 emit_metrics({"skipped": True, "skip_reason": 44, **_base})
1527 sys.exit(0)
1528
1529 prev_upstream = _detect_prev_upstream(repo_root, bash_output)
1530 if not prev_upstream:
1531 debug_log("Push sweep: could not determine prev_upstream")
1532 emit_metrics({"skipped": True, "skip_reason": 41, **_base})
1533 sys.exit(0)
1534
1535 push_range = _git_rev_list_range(repo_root, prev_upstream, "HEAD")
1536 if not push_range:
1537 emit_metrics({"skipped": True, "skip_reason": 42, **_base, "pushed": 0})
1538 sys.exit(0)
1539 if len(push_range) > MAX_PUSH_SWEEP_RANGE:
1540 # Huge first-push of a long-lived branch — Stop hook is the backstop.
1541 emit_metrics({"skipped": True, "skip_reason": 43, **_base,
1542 "pushed": len(push_range)})
1543 sys.exit(0)
1544
1545 reviewed = _load_reviewed_shas(repo_root)
1546 base, tail = _compute_push_sweep_base(prev_upstream, push_range, reviewed)
1547 prefix_advanced = len(push_range) - len(tail)
1548 if base is None:
1549 debug_log("Push sweep: every pushed commit already reviewed")
1550 emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0,
1551 "prefix_advanced": prefix_advanced})
1552 sys.exit(0)
1553
1554 debug_log(f"Push sweep: range={len(push_range)} prefix_advanced="
1555 f"{prefix_advanced} base={base[:12]} tail={len(tail)}")
1556
1557 diff_text = _git_diff_range(repo_root, base, "HEAD")
1558 if diff_text is None:
1559 # Diff failed (non-zero exit / 30s timeout / git missing). Do NOT
1560 # mark `tail` reviewed — we did not actually review it. Marking
1561 # them would silently advance the prefix past unreviewed commits
1562 # forever (the whole point of push-sweep is to catch outside-CC
1563 # commits, and a 50-commit range over large files can hit the
1564 # 30s timeout). skip_reason=45 lets a retry / smaller subsequent
1565 # push still cover them, mirroring how skip_reason=31 handles
1566 # too-many-files without recording the tail.
1567 emit_metrics({**_base, "pushed": len(push_range),
1568 "unreviewed": len(tail), "skip_reason": 45})
1569 sys.exit(0)
1570 diff_files = parse_diff_into_files(diff_text)
1571 if not diff_files:
1572 emit_metrics({**_base, "pushed": len(push_range),
1573 "unreviewed": len(tail), "skip_reason": 30})
1574 # Still mark tail reviewed — there's nothing to review.
1575 _append_reviewed_shas(repo_root, tail, vulns_found=0)
1576 sys.exit(0)
1577 # Same prioritize-don't-bail logic as commit-review (see comment there).
1578 # push-sweep ranges are net diffs over many commits so they hit the cap
1579 # more often; reviewing the riskiest MAX_PUSH_SWEEP_FILES is strictly
1580 # better than reviewing none. We still mark `tail` reviewed afterward —
1581 # the dropped files are by construction the low-risk ones (config, .gen,
1582 # tests, migrations), and NOT advancing the base would make the next
1583 # push re-hit the same overflow with an even larger range. Per-commit
1584 # review remains the primary surface for those files. The 10×
1585 # pathological guard stays so a 500-file vendored-dir push doesn't burn
1586 # a counter slot.
1587 if len(diff_files) > 10 * MAX_PUSH_SWEEP_FILES:
1588 emit_metrics({**_base, "pushed": len(push_range),
1589 "unreviewed": len(tail), "skip_reason": 31,
1590 "diff_files_count": len(diff_files)})
1591 sys.exit(0)
1592 diff_files, _dropped = _prioritize_diff_files(diff_files, MAX_PUSH_SWEEP_FILES)
1593 if _dropped:
1594 _base = {**_base, "diff_files_dropped": _dropped}
1595
1596 _allowed, _rate_n = atomic_check_rate_limit(
1597 session_id, "PushSweep",
1598 MAX_COMMIT_REVIEWS_PER_HOUR, COMMIT_REVIEW_RATE_WINDOW_S)
1599 _base = {**_base, "rate_count": _rate_n}
1600 if not _allowed:
1601 emit_metrics({"skipped": True, "skip_reason": 23, **_base})
1602 sys.exit(0)
1603
1604 import time as _time
1605 now = _time.time()
1606 previous_findings = with_locked_state(
1607 session_id,
1608 lambda s: list(s.get("previous_findings", []))
1609 if (now - s.get("previous_findings_ts", 0)) <= PREVIOUS_FINDINGS_TTL_SEC
1610 else []
1611 ) or []
1612
1613 review_start = _time.time()
1614 rel_touched = [fp for fp, _ in diff_files]
1615 if _agentic_commit_review_enabled():
1616 concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race(
1617 repo_root, diff_files, rel_touched, previous_findings
1618 )
1619 if agentic_metrics.get("agentic_fallback"):
1620 concrete_guidance, vulns = analyze_code_security(
1621 diff_files, is_diff=True, previous_findings=previous_findings
1622 )
1623 else:
1624 concrete_guidance, vulns = analyze_code_security(
1625 diff_files, is_diff=True, previous_findings=previous_findings
1626 )
1627 agentic_metrics = {}
1628 review_ms = int((_time.time() - review_start) * 1000)
1629
1630 # The tail is now covered by this net-diff review.
1631 _append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or []))
1632
1633 new_vulns, n_deduped = _dedup_against_state(
1634 session_id, vulns or [], prompted=_finding_keys(previous_findings)
1635 )
1636
1637 # Metrics — keep within the 10-key cap; agentic sub-metrics are dropped
1638 # here in favour of the push-sweep funnel keys (telemetry can join on session_id
1639 # to the per-commit fires for agentic detail). rewake_summary must ride
1640 # this line (CC reads only the first {-prefixed stdout line); it's a
1641 # no-op when new_vulns is empty since we exit 0 below.
1642 emit_metrics({
1643 **_base, "pushed": len(push_range), "unreviewed": len(tail),
1644 "prefix_advanced": prefix_advanced, "vulns_found": len(new_vulns),
1645 "files_reviewed": len(diff_files), "review_ms": review_ms,
1646 **({"deduped": n_deduped} if n_deduped else {}),
1647 }, rewake_summary=_format_vulns_summary(new_vulns, prefix="Push security review found"))
1648
1649 if not new_vulns:
1650 debug_log("Push sweep: no new findings")
1651 sys.exit(0)
1652
1653 # First-push of a big branch can surface many findings at once across
1654 # week-old code. Report only the top-N by severity so the asyncRewake
1655 # isn't a wall of text; the rest go to telemetry (vulns_found is the
1656 # full count) and into previous_findings so Stop / next commit-review
1657 # don't re-flag them. Stable sort: severity, then category for
1658 # determinism in tests.
1659 _sev_rank = {"critical": 0, "high": 1, "medium": 2, "low": 3}
1660 new_vulns.sort(key=lambda v: (_sev_rank.get(v.get("severity", "medium"), 2),
1661 v.get("category", "")))
1662 reported = new_vulns[:PUSH_SWEEP_REPORT_CAP]
1663 n_suppressed = len(new_vulns) - len(reported)
1664
1665 # Record only the REPORTED findings into shared state. previous_findings
1666 # means "the user was told about this — don't repeat it"; suppressed
1667 # findings were NOT told, so recording them would silently bury them
1668 # against any future commit-review/Stop that touches the same code. The
1669 # range is marked reviewed in `.git/sg-reviewed-shas` regardless, so the
1670 # push-sweep itself won't re-find them; leaving them out of
1671 # previous_findings keeps the door open for the per-commit hook to
1672 # surface them later if the code is touched again.
1673 snapshots = [_finding_snapshot(v) for v in reported]
1674 def _record(state):
1675 existing = [f for f in state.get("previous_findings", [])
1676 if isinstance(f, dict)]
1677 seen = {(f.get("filePath", ""), f.get("category", "")) for f in existing}
1678 for f in snapshots:
1679 k = (f["filePath"], f["category"])
1680 if k not in seen:
1681 seen.add(k); existing.append(f)
1682 state["previous_findings"] = existing
1683 state["previous_findings_ts"] = _time.time()
1684 with_locked_state(session_id, _record)
1685
1686 # Prefer the LLM's formatted guidance (richer context, fix suggestions)
1687 # when NOTHING was dropped from the LLM's full vuln list; fall back to
1688 # re-formatting from `reported` whenever either the cap suppressed
1689 # findings OR `_dedup_against_state` dropped findings the user has
1690 # already been shown. concrete_guidance is built against the LLM's
1691 # full pre-dedup list, so leaking it past dedup re-surfaces findings
1692 # the per-commit hook already reported (the [✓1, ✗2, ✓3] case where
1693 # the tail reviewed commits' findings are in previous_findings).
1694 if n_suppressed or n_deduped:
1695 guidance = _format_vulns_guidance(reported) or ""
1696 else:
1697 guidance = concrete_guidance or _format_vulns_guidance(reported) or ""
1698 sys.stderr.write(
1699 PROVENANCE_BANNER + "\n\n" + guidance + CONTINUATION_SUFFIX + "\n"
1700 )
1701 sys.exit(2)
1702
1703def handle_stop_hook(input_data):
1704 """
1705 Handle the Stop hook — final security check using git diff.
1706 Diffs against the baseline SHA captured at UserPromptSubmit to review
1707 only code changed during this turn. Runs two Haiku analyses and
1708 exits with code 2 to force Claude to continue and fix issues.
1709
1710 Also sweeps pending pattern warnings to emit a session-level
1711 fixed/unresolved tally; the sweep needs no LLM and measures
1712 pattern-rule efficacy.
1713 """
1714 session_id = input_data.get("session_id", "default")
1715 stop_hook_active = input_data.get("stop_hook_active", False)
1716 cwd = input_data.get("cwd", "")
1717
1718 # Recursion guard FIRST — consume_stop_state clears touched_paths, and CC
1719 # sets stop_hook_active session-wide while any asyncRewake Stop is in
1720 # flight, so a concurrent active=True fire winning the lock would discard
1721 # paths the concurrent active=False fire needs.
1722 if stop_hook_active:
1723 debug_log("Stop hook: stop_hook_active=True, skipping to avoid recursion")
1724 emit_metrics({"skipped": True, "skip_reason": 1, "diff_strategy_v2": True})
1725 sys.exit(0)
1726
1727 # Snapshot all state under one lock BEFORE any slow work (sweep file I/O,
1728 # git, network). asyncRewake Stop runs in the background; the next turn's
1729 # UPS/PostToolUse can fire while we're still here. The snapshot is immune
1730 # to those writes — they affect the NEXT Stop fire's snapshot.
1731 snap = consume_stop_state(session_id)
1732 fire_count = snap["fire_count"]
1733 touched_paths = snap["touched_paths"]
1734 baseline_sha = snap["baseline_sha"]
1735 snap_baseline = baseline_sha # pre-reassignment value for restore-on-transient-skip
1736 head_at_capture = snap["head_at_capture"]
1737 untracked_at_baseline = snap.get("untracked_at_baseline") or {}
1738 previous_findings = snap["previous_findings"]
1739
1740 # Sweep pattern-warning outcomes (pure local work; stop_hook_active is
1741 # already guaranteed False here so no double-count guard needed).
1742 sweep = {}
1743 warn_fixed, warn_unresolved, warn_unresolved_mask = sweep_pending_warnings(session_id)
1744 if warn_fixed or warn_unresolved:
1745 sweep = {
1746 "warn_fixed": warn_fixed,
1747 "warn_unresolved": warn_unresolved,
1748 "warn_unresolved_mask": warn_unresolved_mask,
1749 }
1750
1751 v2_metrics = {}
1752
1753 def _skip(reason, restore=False, **extra):
1754 if restore:
1755 restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline)
1756 # CC truncates metrics to 10 keys by
1757 # insertion order. v2_metrics (3) must precede sweep (3) so the v2
1758 # diagnostics survive when extra adds touched_paths_count + ip_* keys.
1759 emit_metrics({
1760 "skipped": True, "skip_reason": reason, "fire_index": fire_count + 1,
1761 "diff_strategy_v2": True,
1762 **v2_metrics, **extra, **sweep,
1763 })
1764 sys.exit(0)
1765
1766 # Limit stop hook firings per asyncRewake loop to prevent infinite loops.
1767 # fire_count auto-expires after STOP_LOOP_STATE_TTL_SEC so a stale count
1768 # from a prior turn doesn't block this one.
1769 if MAX_STOP_HOOK_FIRINGS > 0 and fire_count >= MAX_STOP_HOOK_FIRINGS:
1770 debug_log(f"Stop hook: already fired {fire_count} times (max {MAX_STOP_HOOK_FIRINGS}), skipping")
1771 _skip(2)
1772
1773 if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS:
1774 debug_log("Stop hook: LLM review disabled or no API credentials")
1775 _skip(3)
1776
1777 # Stop-hook-only kill switch — placed after consume_stop_state so
1778 # touched_paths is still cleared each turn (a disabled Stop hook that
1779 # never consumed state would accumulate stale paths) and after the sweep
1780 # so pattern-warning efficacy metrics still emit. The commit/push reviews
1781 # have their own gates (ENABLE_COMMIT_REVIEW / ENABLE_CODE_SECURITY_REVIEW).
1782 if not ENABLE_STOP_REVIEW:
1783 debug_log("Stop hook: ENABLE_STOP_REVIEW=0")
1784 # 50+ for opt-out skips that aren't push-sweep (which owns 40-49).
1785 _skip(50)
1786
1787 if not ensure_anthropic_reachable():
1788 debug_log("Stop hook: api.anthropic.com unreachable")
1789 _skip(10, restore=True)
1790
1791 if not cwd:
1792 debug_log("Stop hook: no cwd")
1793 _skip(4)
1794
1795 review_paths, diff_base, repo_root, untracked, v2_metrics = compute_v2_review_set(
1796 cwd, baseline_sha, head_at_capture, untracked_at_baseline
1797 )
1798 if not review_paths:
1799 debug_log("Stop hook: empty review set")
1800 _skip(9, touched_paths_count=len(touched_paths))
1801 debug_log(f"Stop hook: review_set={len(review_paths)} base={diff_base[:12]} dirty_now={v2_metrics['dirty_now_count']} changed_since={v2_metrics['changed_since_count']}")
1802 # Run from repo_root so the toplevel-relative review_paths resolve.
1803 # Diff CONTENT against the turn-start stash (baseline_sha) so the LLM
1804 # sees only this-turn edits — diffing against HEAD includes the user's
1805 # pre-turn uncommitted WIP, which inflates review_ms and can re-flag
1806 # the same pre-existing pattern every turn. The file LIST still comes
1807 # from git state (compute_v2_review_set), so Bash/subagent edits are
1808 # caught either way. Fall back to diff_base (HEAD/head_at_capture)
1809 # when the stash is missing or pruned.
1810 content_base = baseline_sha or diff_base
1811 diff_output = get_git_diff(repo_root, content_base, full_context=False,
1812 paths=review_paths, untracked_paths=untracked)
1813 if diff_output is None and content_base != diff_base:
1814 debug_log(f"Stop hook: diff against {content_base[:12]} failed — falling back to {diff_base}")
1815 diff_output = get_git_diff(repo_root, diff_base, full_context=False,
1816 paths=review_paths, untracked_paths=untracked)
1817 # filter_preexisting_from_diff needs a resolvable pre-turn ref; fall
1818 # back to HEAD when UPS never captured a baseline (print mode).
1819 if not baseline_sha:
1820 baseline_sha = "HEAD"
1821
1822 if not diff_output or not diff_output.strip():
1823 debug_log("Stop hook: no changes since baseline")
1824 _skip(6)
1825
1826 # Parse diff into per-file content
1827 diff_files = parse_diff_into_files(diff_output)
1828 if not diff_files:
1829 debug_log("Stop hook: no source code files in diff")
1830 _skip(7)
1831
1832 # Mirror commit-review: hard-bail only on pathological diffs (>300 files,
1833 # usually a bad baseline), otherwise prioritize by security-risk path
1834 # tokens and review the top MAX_DIFF_FILES. Stop is the only surface for
1835 # uncommitted edits; the old hard-skip at >30 files dropped the 31-300
1836 # bucket entirely, which is where cross-file source→sink vulns hide.
1837 # _cap_files_for_prompt already bounds bytes downstream.
1838 _stop_dropped = 0
1839 if len(diff_files) > 10 * MAX_DIFF_FILES:
1840 debug_log(f"Stop hook: pathological diff ({len(diff_files)} files > "
1841 f"{10 * MAX_DIFF_FILES}), skipping")
1842 _skip(8, diff_files_count=len(diff_files))
1843 if len(diff_files) > MAX_DIFF_FILES:
1844 diff_files, _stop_dropped = _prioritize_diff_files(
1845 diff_files, MAX_DIFF_FILES)
1846 debug_log(f"Stop hook: prioritized to {len(diff_files)} files "
1847 f"(dropped {_stop_dropped} lower-risk)")
1848
1849 # Filter out pre-existing content from file rewrites
1850 diff_files = filter_preexisting_from_diff(diff_files, cwd, baseline_sha)
1851
1852 debug_log(f"Stop hook: reviewing {len(diff_files)} changed files (standard diff)")
1853
1854 import time as _time
1855 stop_review_start = _time.time()
1856
1857 # Stop hook is single-shot only. Agentic review is wired into
1858 # handle_commit_review_posttooluse (PostToolUse on `git commit`) — commits
1859 # are slower-OK and benefit from the deeper context-reading loop.
1860 concrete_guidance, vulns = analyze_code_security(
1861 diff_files, is_diff=True, previous_findings=previous_findings
1862 )
1863 # NOTE: analyze_security_concerns disabled — it produces too many false positives
1864 # on pre-existing patterns in starter code. The concrete vulnerability analysis
1865 # is more precise and has severity filtering (high/critical only).
1866
1867 stop_review_elapsed = _time.time() - stop_review_start
1868 debug_log(f"Stop hook: LLM reviews took {stop_review_elapsed:.1f}s total")
1869
1870 review_ms = int(stop_review_elapsed * 1000)
1871 fire_index = fire_count + 1
1872
1873 # Late dedup: drop only what a concurrent commit-review wrote while our
1874 # LLM ran. Anything already in `previous_findings` (the consume_stop_state
1875 # snapshot) that the LLM re-flagged is an intentional "fix incomplete"
1876 # verdict and passes through.
1877 if vulns:
1878 vulns, n_deduped = _dedup_against_state(
1879 session_id, vulns, prompted=_finding_keys(previous_findings)
1880 )
1881 if n_deduped and not vulns:
1882 debug_log("Stop hook: all findings already delivered by commit-review")
1883 _skip(35, deduped=n_deduped, review_ms=review_ms)
1884 concrete_guidance = _format_vulns_guidance(vulns)
1885
1886 if concrete_guidance:
1887 finding_snapshots = [_finding_snapshot(v) for v in vulns]
1888 # Update baseline so next stop hook iteration only sees new changes
1889 new_sha = capture_git_baseline(cwd)
1890 new_untracked_baseline = _list_untracked(cwd) if new_sha else None
1891
1892 def _record_fire(state):
1893 state["stop_hook_fire_count"] = fire_index
1894 state["stop_hook_fire_count_ts"] = _time.time()
1895 # Re-read under lock — the commit-review PostToolUse hook may have
1896 # appended findings since consume_stop_state snapshotted.
1897 # Dedupe on (filePath, category) — vulnerableCode includes diff
1898 # context lines that drift between fires, so byte-identical
1899 # matching let the same finding accumulate as "new" each fire.
1900 existing = [f for f in state.get("previous_findings", []) if isinstance(f, dict)]
1901 seen = {(f.get("filePath", ""), f.get("category", "")) for f in existing}
1902 for f in finding_snapshots:
1903 key = (f["filePath"], f["category"])
1904 if key not in seen:
1905 seen.add(key)
1906 existing.append(f)
1907 state["previous_findings"] = existing
1908 state["previous_findings_ts"] = _time.time()
1909 if new_sha:
1910 state["baseline_sha"] = new_sha
1911 state["untracked_at_baseline"] = new_untracked_baseline
1912 with_locked_state(session_id, _record_fire)
1913
1914 if new_sha:
1915 debug_log(f"Updated git baseline after stop hook: {new_sha[:12]}")
1916
1917 sev = {"critical": 0, "high": 0, "medium": 0}
1918 for v in vulns:
1919 s = v.get("severity", "medium")
1920 if s in sev:
1921 sev[s] += 1
1922 # 8 base keys + at most 2 sweep keys = 10 (cap). Drop the mask here.
1923 # untracked_baseline_n is the signal for whether the UPS-time
1924 # untracked-snapshot capture actually ran.
1925 sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"}
1926 emit_metrics({
1927 "vulns_found": len(vulns),
1928 "untracked_baseline_n": len(untracked_at_baseline),
1929 "diff_strategy_v2": True,
1930 "critical_count": sev["critical"],
1931 "high_count": sev["high"],
1932 "files_reviewed": len(diff_files),
1933 "touched_paths_count": len(touched_paths),
1934 "review_ms": review_ms,
1935 "fire_index": fire_index,
1936 **({"diff_truncated": llm._last_review_truncated_bytes}
1937 if llm._last_review_truncated_bytes else {}),
1938 **sweep_trimmed,
1939 }, rewake_summary=_format_vulns_summary(vulns))
1940
1941 # Exit code 2 with stderr forces Claude to continue and fix
1942 sys.stderr.write(PROVENANCE_BANNER + "\n\n" + concrete_guidance + CONTINUATION_SUFFIX + "\n")
1943 sys.exit(2)
1944
1945 if llm._last_call_claude_http_error is not None:
1946 debug_log(f"Stop hook: API call failed with status {llm._last_call_claude_http_error}")
1947 restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline)
1948 else:
1949 debug_log("Stop hook: no security issues found")
1950 # CC truncates metrics to 10 keys by
1951 # insertion order. The previous **sweep,**v2_metrics tail meant the 3
1952 # v2_metrics keys were always sliced off this most-common path, so the
1953 # diff-strategy diagnostics never reached telemetry. Drop sweep here (it's
1954 # PostToolUse-warning state, orthogonal to diff-strategy comparison).
1955 # 6 base + optional api_error + 3 v2_metrics = ≤10.
1956 emit_metrics({
1957 "vulns_found": 0,
1958 "diff_strategy_v2": True,
1959 "files_reviewed": len(diff_files),
1960 "touched_paths_count": len(touched_paths),
1961 "review_ms": review_ms,
1962 "fire_index": fire_index,
1963 **({"api_error": llm._last_call_claude_http_error} if llm._last_call_claude_http_error is not None else {}),
1964 **({"diff_truncated": llm._last_review_truncated_bytes}
1965 if llm._last_review_truncated_bytes else {}),
1966 **v2_metrics,
1967 })
1968 sys.exit(0)
1969
1970_SDK_BOOTSTRAP_THROTTLE = os.path.join(
1971 os.environ.get("SECURITY_WARNINGS_STATE_DIR")
1972 or os.path.expanduser("~/.claude/security"),
1973 ".sdk_bootstrap_spawned")
1974
1975def _maybe_bootstrap_agent_sdk_async():
1976 """Fire-and-forget SDK bootstrap, for remote-pod environments.
1977
1978 Under CLAUDE_CODE_SYNC_PLUGIN_INSTALL=true (CCR-style remote pods),
1979 plugins are synced *after* SessionStart fires, so the SessionStart
1980 `ensure_agent_sdk.py` hook never runs and the agentic commit reviewer
1981 falls back 100% of the time. A PostToolUse hook firing is itself proof
1982 the plugin is now registered, so re-trigger the bootstrap here.
1983 Detached, so the ~17s venv build never blocks the hook — the first
1984 1-2 commits of a remote session still fall back while it builds, then
1985 every subsequent commit gets the agentic path. ensure_agent_sdk.py
1986 is idempotent and O_EXCL-locked, so concurrent/repeat spawns are safe;
1987 the throttle file only avoids spawning dozens of subprocesses during
1988 the build window. No-ops in ~10ms on local installs (SDK already
1989 importable).
1990 """
1991 try:
1992 import importlib.util
1993 if importlib.util.find_spec("claude_agent_sdk") is not None:
1994 return
1995 import time as _t
1996 try:
1997 if _t.time() - os.path.getmtime(_SDK_BOOTSTRAP_THROTTLE) < 300:
1998 return
1999 except OSError:
2000 pass
2001 os.makedirs(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE), exist_ok=True)
2002 # Touch the throttle BEFORE spawning so a burst of PostToolUse
2003 # fires in the same second don't each spawn a subprocess.
2004 open(_SDK_BOOTSTRAP_THROTTLE, "w").close()
2005 script = os.path.join(
2006 os.path.dirname(os.path.abspath(__file__)), "ensure_agent_sdk.py")
2007 subprocess.Popen(
2008 [sys.executable, script],
2009 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
2010 stdin=subprocess.DEVNULL, start_new_session=True,
2011 )
2012 except Exception:
2013 pass # best-effort; never break the hook over a bootstrap attempt
2014
2015def main():
2016 """Main hook function."""
2017 debug_log(f"Hook called with args: {sys.argv}")
2018
2019 # Master kill switch — honors ENABLE_SECURITY_REMINDER=0 (legacy) and
2020 # SECURITY_GUIDANCE_DISABLE=1 (clearer name, no double negative). Emit
2021 # empty metrics so asyncRewake hooks (Stop) don't hang waiting for stdout
2022 # output that never comes.
2023 if SECURITY_GUIDANCE_DISABLED:
2024 emit_metrics({"skipped": True, "skip_reason": -1})
2025 sys.exit(0)
2026
2027 # Periodically clean up old state files (10% chance per run)
2028 if random.random() < 0.1:
2029 cleanup_old_state_files()
2030
2031 # Read input from stdin
2032 try:
2033 raw_input = sys.stdin.read()
2034 input_data = json.loads(raw_input)
2035 except json.JSONDecodeError as e:
2036 debug_log(f"JSON decode error: {e}")
2037 emit_metrics({"skipped": True, "skip_reason": -2})
2038 sys.exit(0)
2039
2040 session_id = input_data.get("session_id", "default")
2041 tool_name = input_data.get("tool_name", "")
2042 tool_input = input_data.get("tool_input", {})
2043 hook_event_name = input_data.get("hook_event_name", "")
2044 debug_log(f"Processing: hook_event={hook_event_name}, tool={tool_name}")
2045
2046 # Load project-specific security guidance and custom patterns once
2047 # per invocation. Failures are non-fatal (debug-logged) so a malformed
2048 # config never prevents the built-in checks from running.
2049 extensibility.load_for_session(input_data.get("cwd"))
2050 secretpaths.load_for_session(input_data.get("cwd"))
2051
2052 # Remote-pod SDK-bootstrap rescue: PostToolUse is the earliest hook event
2053 # that is guaranteed to fire *after* async plugin sync (its firing proves
2054 # the plugin is registered), so it's where we recover the SessionStart
2055 # bootstrap that remote pods miss under CLAUDE_CODE_SYNC_PLUGIN_INSTALL.
2056 # Fires on Edit/Write too (not just Bash), so the venv is usually built
2057 # before the first `git commit`.
2058 if hook_event_name == "PostToolUse":
2059 _maybe_bootstrap_agent_sdk_async()
2060
2061 # Handle UserPromptSubmit — capture git baseline
2062 if hook_event_name == "UserPromptSubmit":
2063 handle_user_prompt_submit(input_data)
2064 return
2065
2066 # Handle Stop hook — final security check
2067 if hook_event_name == "Stop":
2068 handle_stop_hook(input_data)
2069 return
2070
2071 # Handle PostToolUse[Bash] — commit review or push sweep (asyncRewake).
2072 #
2073 # hooks.json has two `if` configs under the Bash matcher (`git commit:*`
2074 # and `git push:*`). CC evaluates each `if` independently and spawns this
2075 # script ONCE PER MATCH — so `git commit -m x && git push` spawns python
2076 # twice with the same command string and the same tool_use_id. The python
2077 # cannot tell which `if` fired it.
2078 #
2079 # Routing therefore MUST check commit FIRST so that compound commit+push
2080 # commands continue to hit commit-review (the pre-existing behaviour) on
2081 # the commit-matcher invocation. The push-matcher invocation of the SAME
2082 # compound command is deduped by `_claim_bash_hook_once` below: the second
2083 # spawn loses the tool_use_id sentinel race and exits early with
2084 # `bash_hook_dedup`, so commit-review runs exactly once. The alternative —
2085 # checking push first — would silently DROP commit-review
2086 # on `git commit && git push`, which is a regression.
2087 #
2088 # The push-sweep does NOT run on the compound call. That's acceptable: the
2089 # just-made commit is recorded by commit-review, so the next standalone
2090 # push sees it as reviewed and the sweep base advances past it. Older
2091 # unreviewed commits in the range are caught on that next push.
2092 if tool_name == "Bash" and hook_event_name == "PostToolUse":
2093 cmd = (input_data.get("tool_input") or {}).get("command", "") or ""
2094 if not (_GIT_COMMIT_RE.search(cmd) or _GIT_PUSH_RE.search(cmd)):
2095 return
2096 if not _claim_bash_hook_once(input_data):
2097 # Another spawn for this same tool_use_id already claimed the
2098 # work (compound matched multiple `if` configs). Emit a single
2099 # metric so telemetry can count how often the de-dupe kicks in.
2100 print(json.dumps({"metrics": {"bash_hook_dedup": True}}), flush=True)
2101 sys.exit(0)
2102 if _GIT_COMMIT_RE.search(cmd):
2103 handle_commit_review_posttooluse(input_data)
2104 elif _GIT_PUSH_RE.search(cmd):
2105 handle_push_sweep_posttooluse(input_data)
2106 return
2107
2108 # Handle PostToolUse — pattern-based checks only (no LLM review per-edit)
2109 if tool_name in ["Edit", "Write", "MultiEdit", "NotebookEdit"]:
2110 file_path = tool_input.get("file_path") or tool_input.get("notebook_path") or ""
2111 if not file_path:
2112 sys.exit(0)
2113
2114 # Skip plan files
2115 plans_dir = os.path.expanduser("~/.claude/plans")
2116 if file_path.startswith(plans_dir):
2117 sys.exit(0)
2118
2119 record_touched_path(session_id, file_path)
2120
2121 content = extract_content_from_input(tool_name, tool_input)
2122
2123 all_guidance = []
2124 raw_pattern_matches = []
2125 if ENABLE_PATTERN_RULES:
2126 pattern_matches = check_patterns(file_path, content)
2127 raw_pattern_matches = pattern_matches
2128 if pattern_matches:
2129 debug_log(f"Pattern matches for {file_path}: {[r for r, _ in pattern_matches]}")
2130
2131 # For Write tool, filter out patterns that existed in the baseline version
2132 # This prevents flagging pre-existing insecure patterns when Claude rewrites a file
2133 if tool_name == "Write" and pattern_matches:
2134 cwd = os.environ.get("CLAUDE_PROJECT_DIR", os.getcwd())
2135 baseline_content = get_baseline_file_content(session_id, file_path, cwd)
2136 if baseline_content is not None:
2137 baseline_matches = set(r for r, _ in check_patterns(file_path, baseline_content))
2138 pattern_matches = [(r, msg) for r, msg in pattern_matches if r not in baseline_matches]
2139 if pattern_matches:
2140 debug_log(f"New patterns (not in baseline): {[r for r, _ in pattern_matches]}")
2141 else:
2142 debug_log("All patterns existed in baseline, skipping")
2143
2144 for rule_name, reminder in pattern_matches:
2145 warning_key = f"{file_path}-{rule_name}"
2146 if atomic_check_and_mark_warning(session_id, warning_key):
2147 all_guidance.append(reminder)
2148
2149 # Record matched rules as pending so the Stop-hook sweep can
2150 # later tally fixed vs unresolved. Only runs when patterns match.
2151 if pattern_matches:
2152 record_pending_warnings(session_id, file_path,
2153 [r for r, _ in pattern_matches])
2154
2155 # Emit metrics when raw patterns matched (even if all were baseline-suppressed
2156 # or dedup'd — pattern_hits reflects warnings actually shown, may be 0).
2157 # Gate on raw matches so clean edits don't flood the metrics event.
2158 # rule_id: RuleId of the first raw match (values stay small/enumerable in telemetry)
2159 # rule_mask: bitmask of ALL raw matches — POPCOUNT gives raw hit count,
2160 # (mask >> N) & 1 tests for a specific rule
2161 if raw_pattern_matches:
2162 raw_names = [r for r, _ in raw_pattern_matches]
2163 output = {"metrics": {
2164 "pattern_hits": len(all_guidance),
2165 # User-defined patterns (rule_name="user:*") have no static
2166 # RuleId; emit -1 so the metrics pipeline can distinguish.
2167 "rule_id": int(_RULE_NAME_TO_ID.get(raw_names[0], -1)),
2168 "rule_mask": rule_names_to_mask(raw_names),
2169 **({"pv": _PV} if _PV else {}),
2170 }}
2171 if all_guidance:
2172 output["hookSpecificOutput"] = {
2173 "hookEventName": "PostToolUse",
2174 "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance),
2175 }
2176 print(json.dumps(output))
2177 elif all_guidance:
2178 # Defensive: pattern rules disabled but guidance somehow set (shouldn't happen)
2179 print(json.dumps({
2180 "hookSpecificOutput": {
2181 "hookEventName": "PostToolUse",
2182 "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance),
2183 }
2184 }))
2185
2186 sys.exit(0)
2187
2188if __name__ == "__main__":
2189 main()