security_reminder_hook.py 109 KB

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