security_reminder_hook.py 114 KB

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