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