security_reminder_hook.py 108 KB

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