diff options
| author | Claude <noreply@anthropic.com> | 2026-11-06 00:54:48 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-06 00:54:48 +0000 |
| commit | 7aba3deae3ff17d032c37e07d2929d1426b34278 (patch) | |
| tree | 9c482f9acda1599bd2f9bed95a6a46b75e634e80 /plugins/security-guidance/hooks/security_reminder_hook.py | |
| parent | 5472f5f56e0070feeeb464318b316714fe3e9105 (diff) | |
| parent | b8331dd69ab3e132bbf8cd6e89b5d8c1747e21b1 (diff) | |
Merge remote-tracking branch 'origin/main' into add-plugin/xcodeadd-plugin/xcode
Diffstat (limited to 'plugins/security-guidance/hooks/security_reminder_hook.py')
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 1302 |
1 files changed, 1065 insertions, 237 deletions
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 48a7eb49..7c84357f 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -23,7 +23,7 @@ The plugin has two layers: ## How the git baseline works -On each UserPromptSubmit, the plugin runs `git stash create` to get a SHA representing +On each UserPromptSubmit, the plugin takes a snapshot commit to get a SHA representing the current working tree state (HEAD + any uncommitted changes). This SHA is saved to the session state file. When the Stop hook fires, it runs `git diff <baseline_sha>` to get only the changes made since that snapshot. After analysis, the baseline is updated @@ -46,10 +46,12 @@ Per-feature toggles (all default enabled; set to "0" to disable): - ENABLE_COMMIT_REVIEW: PostToolUse[Bash] commit security review Other: -- SECURITY_REVIEW_MODEL: Model for LLM review (default: claude-opus-4-7) +- SECURITY_REVIEW_MODEL: Model for LLM review (default: the newest Opus) - ANTHROPIC_API_KEY: Required for LLM-based reviews - ANTHROPIC_AUTH_TOKEN: Alternative to API key — OAuth access token sent as Bearer auth. - Claude Code passes this automatically for OAuth-authenticated users. + Claude Code passes this to the plugin's hooks for signed-in users, unless + telemetry or nonessential traffic is turned off. With neither, the LLM + reviews are skipped and the user is told once (see README, Credentials). """ try: @@ -66,6 +68,7 @@ import re import subprocess import sys import threading +import time import urllib.request from datetime import datetime from enum import IntEnum @@ -82,8 +85,11 @@ from _base import ( # noqa: E402,F401 DEBUG_LOG_FILE, DEBUG_LOG_MAX_BYTES, debug_log, PROVENANCE_TAG, PROVENANCE_BANNER, _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, - _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, - state_dir as _resolve_state_dir, + _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, _net_error_metric, + _USAGE_CONTEXT, _log_usage, + launcher_direct_metric, launcher_probe_metrics, state_dir as _resolve_state_dir, + write_hook_output as _write_hook_output, portable_output, + llm_reviews_switched_off, agent_sdk_installed, make_state_dir, ) import extensibility # noqa: E402 from patterns import ( # noqa: E402,F401 @@ -97,9 +103,11 @@ from session_state import ( # noqa: E402,F401 load_state, save_state, with_locked_state, ) from gitutil import ( # noqa: E402,F401 - GIT_CMD, apply_safe_git_env, + GIT_CMD, apply_safe_git_env, remove_copies_on_termination, + on_windows_drive, _git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index, _git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range, + _git_toplevel_and_head, _git_head_at, _detect_main_branch, _git_reflog_recent_commits, _git_name_only, _git_status_porcelain, _is_ancestor, get_git_diff, SOURCE_CODE_EXTENSIONS, SOURCE_CODE_BASENAMES, @@ -117,7 +125,12 @@ from diffstate import ( # noqa: E402,F401 get_baseline_file_content, capture_git_baseline, _REVIEWED_SHAS_BASENAME, _REVIEWED_SHAS_CAP, _reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas, + _full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight, + _diff_review_started, _diff_review_done, UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set, + touched_scope, review_scope_code, + baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS, + KEPT_NO_CAPTURE, KEPT_UNREVIEWED, ) from reporesolve import ( # noqa: E402,F401 RES_NONE, RES_CWD, RES_COMMAND, RES_SHA_SCAN, RES_TOUCHED_PATHS, RES_HINT, @@ -125,6 +138,8 @@ from reporesolve import ( # noqa: E402,F401 toplevel_from_command, repo_containing_commit, scan_roots, resolve_repo_root, save_repo_hint, load_repo_hint, ) +import diffstate # noqa: E402 module ref for last_baseline_fail +import gitutil # noqa: E402 module ref for per-run counters import llm # noqa: E402 module ref for reassignable globals (_last_call_claude_http_error etc.) from llm import ( # noqa: E402,F401 ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, HAS_API_CREDENTIALS, @@ -189,6 +204,13 @@ MAX_STOP_HOOK_FIRINGS = int(os.environ.get("MAX_STOP_HOOK_FIRINGS", "3")) # diff; unbounded diffs burn tokens and risk 400 on context length. MAX_DIFF_FILES = int(os.environ.get("MAX_DIFF_FILES", "30")) +# Changed source paths past which the Stop review is skipped before any diff. +# A set this large is a repo at $HOME or an unignored cache, not edits; no +# platform takes that many paths in one git command, and only resolving them +# takes seconds. Paths the review never reads (an unignored node_modules) do +# not count: they must not hide the one edited source file beside them. +MAX_REVIEW_SET_PATHS = int(os.environ.get("MAX_REVIEW_SET_PATHS", "100000")) + # Appended to all exit(2) guidance so the asyncRewake auto-turn doesn't # cause the model to abandon the user's original request. CONTINUATION_SUFFIX = ( @@ -198,6 +220,48 @@ CONTINUATION_SUFFIX = ( "response." ) +# New files named in the notice for a failed `git add -N`. +_LEFT_OUT_NAMES_SHOWN = 5 + +# Extra keys emit_metrics appends to every row this invocation emits. +_TAIL_METRICS: Dict[str, Any] = {} +# Of those, the ones that go after the others whenever they were set: a row +# over CC's key cap loses them before any older review key. Only the launcher +# keys below come later; those are also on every smaller row of the session. +_LAST_METRIC_KEYS = ("diff_seen",) + +# The launcher's slow interpreter probes, if any. After the keys above. +_LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics() +# Whether the launcher skipped a packaged alias. Only on rows sent anyway. +_LAUNCHER_DIRECT: Dict[str, Any] = launcher_direct_metric() + +# Reviewer context diagnostics from llm.agentic_review, most useful first. +_REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls") +# How much work the agentic reviewer did, from llm.agentic_review: turns, and +# time waiting on the model. They tell more turns from slower turns when +# review_ms moves. +_REVIEWER_EFFORT_KEYS = ("rv_turns", "rv_api_ms") +# A clean commit review row has one free key under CC's key cap once +# rv_tool_calls is on it, so the two are sent as one number: +# rv_effort = rv_turns * _EFFORT_TURNS_UNIT + rv_api_ms (capped below the unit) +_EFFORT_TURNS_UNIT = 10_000_000 +# The packed value queued for this row. Emitted after every other key, the +# launcher's included, so it never displaces one at the cap. +_REVIEWER_EFFORT_METRICS: Dict[str, Any] = {} + + +def _note_reviewer_context(agentic_metrics): + """Queue the agentic reviewer's context and effort diagnostics for this row.""" + for key in _REVIEWER_CONTEXT_KEYS: + if agentic_metrics.get(key): + _TAIL_METRICS[key] = agentic_metrics[key] + turns = agentic_metrics.get("rv_turns") or 0 + api_ms = agentic_metrics.get("rv_api_ms") or 0 + if turns or api_ms: + _REVIEWER_EFFORT_METRICS["rv_effort"] = ( + turns * _EFFORT_TURNS_UNIT + min(api_ms, _EFFORT_TURNS_UNIT - 1)) + + def emit_metrics( metrics, rewake_summary=None, @@ -228,31 +292,22 @@ def emit_metrics( task-notification one-liner. Must be in the same JSON line as the metrics because CC stops scanning stdout after the first {-prefixed line. - `additional_context` (asyncRewake findings): model-visible guidance text. - Delivery channel depends on `hook_event_name` because CC's hook-output - contract is NOT symmetric across events: - - - PostToolUse (commit-review, push-sweep): surfaced via the modern - hookSpecificOutput.additionalContext protocol. `PostToolUse` is a - member of CC's hookSpecificOutput discriminated union - (coreSchemas.ts), so the JSON validates and metrics/rewakeSummary - are consumed. See #1375 / #1783 for why this replaced the legacy - stderr + exit(2) shape for PostToolUse. - - - Stop / SubagentStop: there is NO `Stop` member in that union, so - emitting hookSpecificOutput{hookEventName:"Stop"} makes the whole - line fail isSyncHookJSONOutput validation — which on the asyncRewake - path silently drops metrics AND rewakeSummary, and (because the - legacy stderr write was removed) leaks the raw JSON to the model as - the rewake body. CC's asyncRewake delivery actually reads - `stderr || stdout` for the model-visible body and only scans stdout - JSON for metrics+rewakeSummary — it never reads additionalContext - on this path. So for Stop we use the documented clean pattern: - guidance on stderr, valid JSON (metrics + rewakeSummary + - top-level decision/reason) on stdout. The top-level decision:"block" - + reason also covers the sync-fallback path (single-shot `claude -p`, - where asyncRewake degrades to a sync Stop hook that reads - decision/reason). See #2159. + `additional_context` (asyncRewake findings, exit-2 callers only): + model-visible guidance text, written to stderr for every event. CC's + asyncRewake delivery reads `stderr || stdout` for the model-visible body + and only scans stdout JSON for metrics+rewakeSummary — it never reads + additionalContext on this path. stdout keeps one valid JSON line so + metrics + rewakeSummary survive: + + - Stop / SubagentStop: also top-level decision:"block" + reason, for + the sync-fallback path (single-shot `claude -p`, where asyncRewake + degrades to a sync Stop hook that reads decision/reason). There is + no `Stop` member in CC's hookSpecificOutput union, so that field + must not be used here. + + - PostToolUse (commit-review, push-sweep): stderr only. In the + sync-fallback path CC shows the model an exit-2 PostToolUse hook's + stderr, so additionalContext would repeat the text. Empty/None additional_context emits neither channel (back-compat for metrics-only callers). @@ -263,40 +318,147 @@ def emit_metrics( surface; systemMessage adds a per-fire override when the static rewakeMessage isn't specific enough for the finding being shown. - `hook_event_name` (used only when additional_context is set): selects the - delivery channel above. Defaults to "PostToolUse" (commit-review and + `hook_event_name` (used only when additional_context is set): whether to + add decision/reason as above. Defaults to "PostToolUse" (commit-review and push-sweep are the most common callers); handle_stop_hook passes "Stop". """ + _log_usage(_usage_metrics()) head = {} if _PV and "pv" not in metrics: head["pv"] = _PV - head.update(_usage_metrics()) + # sg-python.sh could only start this interpreter by its real path: the + # names on PATH were launcher aliases that cannot read the plugin files. + if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": + head["launcher_fallback"] = 1 + if _precheck_miss: + # Up front: this is the key that says a text check would have lost a + # review, so it must not be the one cut by the key cap. + head["precheck_miss"] = 1 + usage = _usage_metrics() + head.update(usage) + # Why the last call got no HTTP response (api_error -1 says only that it + # did not). Ahead of the row's own keys: on a failed review this is the + # key that says what failed, so it is not the one to lose to the key cap. + net_err = _net_error_metric() + if net_err: + head["net_err"] = net_err if head: metrics = {**head, **metrics} + # Diagnostic keys go last, so they are the first dropped when a row is + # over CC's key cap and never displace an existing key. + tail = {} + if llm._store_certs_skipped: + # The Windows certificate store held entries OpenSSL cannot read and + # the plugin's API calls ran on the store without them. + tail["tls_store_skipped"] = llm._store_certs_skipped + if usage or "review_ms" in metrics or metrics.get("review_failed"): + # Review rows say whether the plugin's calls went through a gateway, + # so the error rate behind gateways can be read per plugin version. + cfg = llm.gateway_cfg() + if cfg: + tail["gateway_cfg"] = cfg + if not llm._send_strict_mcp: + # An inner CLI refused --strict-mcp-config (a machine with a + # managed-mcp.json) and the review was started again without it. + tail["strict_mcp_off"] = 1 + tail.update(_TAIL_METRICS) + for k in _LAST_METRIC_KEYS: + if k in tail: + tail[k] = tail.pop(k) + tail.update(_LAUNCHER_METRICS) + tail.update(_REVIEWER_EFFORT_METRICS) + # Last of all: the first key a full row loses. + tail.update(_LAUNCHER_DIRECT) + metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} if rewake_summary: out["rewakeSummary"] = rewake_summary if additional_context: + # Guidance on stderr, the asyncRewake body channel (`stderr || stdout`). + sys.stderr.write(additional_context) + sys.stderr.flush() if hook_event_name in ("Stop", "SubagentStop"): - # Stop is NOT in CC's hookSpecificOutput union — emitting it there - # fails schema validation and drops metrics+rewakeSummary (#2159). - # Clean pattern: guidance on stderr (the asyncRewake body channel, - # delivered via `stderr || stdout`), top-level decision/reason for - # the sync-fallback path. stdout JSON stays valid so metrics + - # rewakeSummary survive. - sys.stderr.write(additional_context) - sys.stderr.flush() + # Sync-fallback path for Stop reads decision/reason. out["decision"] = "block" out["reason"] = additional_context - else: - # PostToolUse et al. — valid union member; modern protocol. - out["hookSpecificOutput"] = { - "hookEventName": hook_event_name, - "additionalContext": additional_context, - } if system_message: out["systemMessage"] = system_message - print(json.dumps(out), flush=True) + _write_hook_output(out) + + +def _llm_review_off(session_id): + """Why no LLM review can run: (log text, extra metrics), or None.""" + if not ENABLE_CODE_SECURITY_REVIEW: + return "LLM review disabled", {} + if not llm.can_review(session_id): + return ("no API credentials and no Claude apps gateway sign-in", + {"no_creds": True}) + return None + + +# Claude Code hands a signed-in user's credentials to this plugin's hooks, +# but not in a session started with one of these set. +_NO_CREDENTIALS_NOTICE_INTERVAL_SEC = 7 * 24 * 3600 + + +def _credential_withholding_env_vars(): + names = [v for v in ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", + "DISABLE_TELEMETRY") if os.environ.get(v)] + if os.environ.get("DO_NOT_TRACK", "").strip().lower() in ( + "1", "true", "yes", "on"): + names.append("DO_NOT_TRACK") + return names + + +def _no_credentials_notice(file_path, session_id): + """Text telling the user the LLM reviews are not running, or None. + + With no credential and no Claude apps gateway sign-in, every Stop, + commit and push review is skipped, and nothing else tells the user. + Returned for an edit inside a git repo (the reviews only look at those), + at most once a week per install: the marker file in the state dir holds + the time of the last notice, or of the last check that found the reviews + running through a Claude apps gateway sign-in. A marker that can't be + written means no notice rather than one on every edit. The caller is the + Edit/Write hook because the review hooks run in the background, where + Claude Code does not show a systemMessage. + """ + import time as _time + try: + marker = os.path.join(_resolve_state_dir(), ".no_credentials_notice") + try: + age = _time.time() - os.path.getmtime(marker) + if 0 <= age < _NO_CREDENTIALS_NOTICE_INTERVAL_SEC: + return None + except OSError: + pass + if not _git_toplevel(os.path.dirname(os.path.abspath(file_path))): + return None + make_state_dir(os.path.dirname(marker)) + with open(marker, "w"): + pass + # In a session signed in to a Claude apps gateway the reviews do run, + # through the user's claude (llm.gateway_review_cli). `claude auth + # status` runs only after the marker is written, so an edit waits for + # it at most once a week. + if llm.can_review(session_id): + return None + except OSError: + return None + withheld_by = _credential_withholding_env_vars() + if withheld_by: + why = ("Claude Code does not pass your sign-in to plugins while " + + " or ".join(withheld_by) + " is set") + else: + why = "No Anthropic credentials were passed to the plugin's hooks" + rest = (", so only the pattern warnings on edits are active" + if ENABLE_PATTERN_RULES else "") + return ( + "security-guidance: the AI security review of your changes is not " + f"running. {why}{rest}. See \"Credentials\" in the plugin README. " + "Set ENABLE_CODE_SECURITY_REVIEW=0 to turn the review off and hide " + "this notice, which is shown at most once a week." + ) # ===================================================================== # State management @@ -405,7 +567,10 @@ def record_pending_warnings(session_id, file_path, rule_names): def sweep_pending_warnings(session_id): """ Stop-hook final sweep. Re-read every file in pending_warnings, re-check - patterns, and return (fixed, unresolved, unresolved_mask). Clears state. + patterns, and return (fixed, unresolved, unresolved_mask, fired_mask). + fired_mask has a bit for every built-in rule that matched an edit since + the last sweep (whether or not its reminder was shown again), so the two + masks give, per rule, fired and still matching. Clears state. A file that's been deleted counts as fixed — the dangerous code is gone. Never raises — this is telemetry and must not break the Stop hook. """ @@ -413,18 +578,24 @@ def sweep_pending_warnings(session_id): try: pending = state.get("pending_warnings") if not isinstance(pending, dict) or not pending: - return 0, 0, 0 + return 0, 0, 0, 0 by_file = {} for key in pending: if not isinstance(key, str) or ":" not in key: continue fp, _, rule = key.rpartition(":") + if fp.endswith(":user"): + # User rules are named "user:<name>"; keep them apart + # from a built-in rule of the same name. + fp, rule = fp[:-len(":user")], "user:" + rule by_file.setdefault(fp, set()).add(rule) unresolved = [] + fired = set() fixed = 0 for fp, rules in by_file.items(): + fired |= rules try: with open(fp, "r", errors="replace") as f: still_matching = {r for r, _ in check_patterns(fp, f.read())} @@ -440,13 +611,14 @@ def sweep_pending_warnings(session_id): # Filter to known rules so a renamed/removed rule in old state # doesn't KeyError rule_names_to_mask. known = [r for r in unresolved if r in _RULE_NAME_TO_ID] - return fixed, len(unresolved), rule_names_to_mask(known) + return (fixed, len(unresolved), rule_names_to_mask(known), + rule_names_to_mask(fired)) except Exception as e: debug_log(f"sweep_pending_warnings failed: {e}") - return 0, 0, 0 + return 0, 0, 0, 0 result = with_locked_state(session_id, _sweep) - return result if result is not None else (0, 0, 0) + return result if result is not None else (0, 0, 0, 0) # ===================================================================== # Git baseline management @@ -456,11 +628,30 @@ def sweep_pending_warnings(session_id): # Pattern matching # ===================================================================== +def _notebook_cell_sources(content): + """Cell sources of a saved notebook, or None when content is not one (a + single cell's source, say).""" + if not isinstance(content, str) or not content.lstrip("\ufeff \t\r\n").startswith("{"): + return None + try: + sources = [cell.get("source", "") for cell in json.loads(content.lstrip("\ufeff"))["cells"]] + return "\n".join(src if isinstance(src, str) else "".join(src) for src in sources) + except Exception: + return None + def check_patterns(file_path, content): """Check if file path or content matches any security patterns. Returns ALL matches.""" normalized_path = file_path.lstrip("/") matches = [] + # A saved notebook is JSON: its string escapes hide code from the rules + # ("\nos.system(" has no word boundary) and its outputs can run to + # megabytes. Check the cells as written instead. + if normalized_path.endswith(".ipynb"): + cell_sources = _notebook_cell_sources(content) + if cell_sources is not None: + content = cell_sources + for pattern in list(SECURITY_PATTERNS) + extensibility.user_patterns(): # path_filter is a gate: when present, the rule only applies to # matching paths. Distinct from path_check, which is itself a @@ -499,7 +690,7 @@ def check_patterns(file_path, content): return matches -def extract_content_from_input(tool_name, tool_input): +def extract_content_from_input(tool_name, tool_input, tool_response=None): """Extract content to check from tool input based on tool type.""" if tool_name == "Write": return tool_input.get("content", "") @@ -510,12 +701,54 @@ def extract_content_from_input(tool_name, tool_input): if edits: return " ".join(edit.get("new_string", "") for edit in edits) return "" + elif tool_name == "NotebookEdit": + # A deleted cell adds no code. A failed edit comes back as an error + # in the response, with the notebook unchanged. + if tool_input.get("edit_mode") == "delete": + return "" + if isinstance(tool_response, dict) and tool_response.get("error"): + return "" + new_source = tool_input.get("new_source", "") + return new_source if isinstance(new_source, str) else "" return "" # ===================================================================== # Hook handlers # ===================================================================== +def _store_baseline_fail(state, fail): + """Keep diffstate.last_baseline_fail next to the baseline_sha it describes.""" + if fail: + state["baseline_fail"] = fail + else: + state.pop("baseline_fail", None) + + +# A prompt waits for this hook, so one this slow is worth a metrics row. Faster +# prompts send none: the row would be one more event per prompt for every user. +SLOW_PROMPT_MS = 1000 + + +def _slow_prompt_metrics(cwd, total, baseline, untracked, captured, baseline_fail): + """The metrics row for a slow prompt. Times are seconds, spent in + handle_user_prompt_submit (the launcher reports its own). Counts and flags + only, never a path. Telemetry only.""" + metrics = { + "ups_ms": int(total * 1000), + "ups_baseline_ms": int(baseline * 1000), + "ups_untracked_ms": int(untracked * 1000), + } + if diffstate.last_index_entries is not None: + metrics["ups_index_entries"] = diffstate.last_index_entries + if on_windows_drive(cwd): + metrics["ups_wsl_drive"] = 1 + if not captured: + metrics["ups_no_baseline"] = 1 + if baseline_fail: + metrics["ups_baseline_fail"] = baseline_fail + return metrics + + def handle_user_prompt_submit(input_data): """ Handle UserPromptSubmit — capture git baseline SHA. @@ -528,36 +761,65 @@ def handle_user_prompt_submit(input_data): to be lost when the wipe landed before Stop's state read. """ + import time as _time + started = _time.monotonic() cwd = input_data.get("cwd", "") if not cwd: debug_log("UPS: no cwd, skipping baseline capture") sys.exit(0) session_id = input_data.get("session_id", "default") - # stash-create and ls-files both walk the worktree (~2-5s each in a very - # large repo). Run them concurrently so UPS latency stays ≈ max(both). - import concurrent.futures as _cf - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - # Always capture the untracked snapshot. `git stash create` returns - # empty when there are no TRACKED changes, but pre-existing untracked - # files still need to be excluded from the next Stop's review_set — - # otherwise an untracked-only working tree gets every untracked file - # reviewed on every turn until something tracked is dirtied. - untracked_now = _f_ut.result() or {} + # The untracked snapshot has one reader: the Stop-hook diff review, which + # skips before reading it when either of these switches is off (see + # handle_stop_hook). Listing the worktree on every prompt then buys + # nothing, so only the turn baseline (still read by the Write pattern + # filter) is captured. + snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW + spent = {"baseline": 0.0, "untracked": 0.0} + + def _timed(key, fn, repo_cwd): + began = _time.monotonic() + try: + return fn(repo_cwd) + finally: + spent[key] += _time.monotonic() - began + + def _capture(repo_cwd): + if not snapshot_untracked: + return _timed("baseline", capture_git_baseline, repo_cwd), None + # the baseline snapshot and ls-files both walk the worktree (~2-5s each in a + # very large repo). Run them concurrently so UPS latency stays + # ≈ max(both). + import concurrent.futures as _cf + with _cf.ThreadPoolExecutor(max_workers=2) as _ex: + _f_sha = _ex.submit(_timed, "baseline", capture_git_baseline, repo_cwd) + _f_ut = _ex.submit(_timed, "untracked", _list_untracked, repo_cwd) + # Taken whether or not the snapshot produced a SHA. The baseline + # falls back to HEAD when there are no TRACKED changes, but + # pre-existing untracked files still need to be excluded from the + # next Stop's review_set — otherwise an untracked-only working + # tree gets every untracked file reviewed on every turn until + # something tracked is dirtied. + return _f_sha.result(), _f_ut.result() or {} + + captured_at = _time.time() + sha, untracked_now = _capture(cwd) + # No repo here and none remembered: the listing above failed, it did not + # come back empty. + no_repo = False if not sha and not _git_toplevel(cwd): hint = load_repo_hint(session_id) if hint: debug_log(f"UPS: cwd is not a git repo; using repo hint {hint!r}") cwd = hint - with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, cwd) - _f_ut = _ex.submit(_list_untracked, cwd) - sha = _f_sha.result() - untracked_now = _f_ut.result() or {} - head = _git_rev_parse_head(cwd) + sha, untracked_now = _capture(cwd) + else: + no_repo = True + baseline_fail = diffstate.last_baseline_fail + # The repo root rides on the same git call as HEAD. + root, head = (None, None) if no_repo else _git_toplevel_and_head(cwd) + if sha and not head: + head = _git_rev_parse_head(cwd) # If the previous turn's Stop hook never ran (user interrupt, follow-up # during work, tool-reject, model crash, maxTurns, PostToolUse block…), @@ -575,14 +837,44 @@ def handle_user_prompt_submit(input_data): # we still need to capture a baseline. if state.get("touched_paths") and state.get("baseline_sha"): preserved["value"] = True + # A baseline captured while the Stop review was off has no + # snapshot beside it. Without one the next Stop would take every + # untracked file in the tree as written this turn. + if untracked_now is not None and "untracked_at_baseline" not in state: + state["untracked_at_baseline"] = untracked_now + # Once a prompt failed to capture, the baseline is old whatever + # later prompts did. + state["baseline_kept"] = ( + KEPT_NO_CAPTURE + if not sha or state.get("baseline_kept") == KEPT_NO_CAPTURE + else KEPT_UNREVIEWED) return if sha: state["baseline_sha"] = sha state["head_at_capture"] = head - # untracked_at_baseline is independent of whether the stash produced - # a SHA — write it unconditionally so compute_v2_review_set's - # preexisting-untracked exclusion works in untracked-only trees. - state["untracked_at_baseline"] = untracked_now + state.pop("turn_touched", None) + _store_baseline_fail(state, baseline_fail) + # A Stop review that ends up in another checkout does not use + # this baseline. + state["baseline_root"] = root + state.pop("baseline_kept", None) + elif state.get("baseline_sha"): + state["baseline_kept"] = KEPT_NO_CAPTURE + # When the turn began: what a Stop review in another checkout has + # to go on. + state["prompt_at"] = captured_at + # untracked_at_baseline is independent of whether the snapshot produced + # a SHA, so compute_v2_review_set's preexisting-untracked exclusion + # works in untracked-only trees. None means no snapshot was taken + # (Stop review off): drop the previous one, which belongs to an older + # baseline. + if untracked_now is None: + state.pop("untracked_at_baseline", None) + elif not no_repo: + # no_repo: the earlier baseline stays (above), and so does the + # snapshot that belongs to it. An empty one in its place would + # make every untracked file in that repo look new. + state["untracked_at_baseline"] = untracked_now with_locked_state(session_id, _save) if preserved["value"]: @@ -599,6 +891,13 @@ def handle_user_prompt_submit(input_data): debug_log(f"Failed to capture git baseline (cwd={cwd!r}) — not a git repo, " f"or git invocation failed (check log entries above)") + total = _time.monotonic() - started + debug_log(f"UPS: took {total:.2f}s (baseline {spent['baseline']:.2f}s, " + f"untracked {spent['untracked']:.2f}s)") + if (total * 1000 >= SLOW_PROMPT_MS or _LAUNCHER_METRICS) and not portable_output(): + emit_metrics(_slow_prompt_metrics( + cwd, total, spent["baseline"], spent["untracked"], bool(sha), baseline_fail)) + sys.exit(0) def _resolve_amend_pre_sha(repo_root, expected_post_sha=None): @@ -677,26 +976,33 @@ _COMMIT_DIFFSTAT_PATTERNS = [ # or trailing hook output isn't picked up and fed to `git show`. _COMMIT_SHA_RE = re.compile(r'^\[[^\]]*?\b([0-9a-f]{7,40})\]', re.MULTILINE) -# Regex matching `git commit` commands. Mirrors Claude Code's own commit -# detection — it does NOT tolerate `git -c k=v commit` global options, which -# keeps this hook aligned with CC's commit attribution on what counts as a -# commit. +# Regex matching `git commit` commands, global options included (see below). # # Also matches `gt create` and `gt modify` — Graphite's stacked-PR wrapper # around git. `gt create` produces a new commit (mapped to git commit # semantics); `gt modify` amends the current commit (mapped to git commit -# --amend, also flagged by _GIT_AMEND_RE below). The hooks.json matcher -# widening for `gt create:*` / `gt modify:*` / `gt submit:*` ships in the -# same change set — without that widening this regex change is dead code -# because the hook subprocess never spawns for gt invocations. See #2048. +# --amend, also flagged by _GIT_AMEND_RE below). hooks.json has a +# `Bash(gt *)` entry so the hook subprocess spawns for gt invocations. +# +# Global options allowed between `git` and the subcommand, shared by +# _GIT_COMMIT_RE and _GIT_PUSH_RE: `-C <path>`, `-c key=val`, `--opt=val`, +# the long options that take a separate value, and flags that take none +# (`--no-pager`, `-p`). A value may be quoted in part (`-c user.name="A B"`). +_GIT_OPT_VALUE = r'''(?:[^\s"']|"[^"]*"|'[^']*')+''' +_GIT_VALUE_OPTS = r'git-dir|work-tree|namespace|config-env|attr-source' +_GIT_GLOBAL_OPTS = ( + r'(?:\s+-[Cc]\s+' + _GIT_OPT_VALUE + + r'|\s+--[^\s=]+=' + _GIT_OPT_VALUE + + r'|\s+--(?:' + _GIT_VALUE_OPTS + r')\s+' + _GIT_OPT_VALUE + # `--help` / `--version` run no subcommand. + + r'|\s+(?:--(?!(?:' + _GIT_VALUE_OPTS + r'|help|version)\s)[^\s=]+|-[pP])(?=\s))*' +) _GIT_COMMIT_RE = re.compile( - # `git -C <path>` and `git -c key=val` global options are allowed between - # `git` and `commit` (mirrors the long-standing tolerance in - # _GIT_PUSH_RE). Without this, `git -C /repo commit` is silently dropped - # by the handler — see #2089's secondary finding. The gt branch has no - # global-option layer to worry about. - r'\bgit(?:\s+-[Cc]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+' - r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+commit\b' + # Without the global-option tolerance, `git -C /repo commit` is silently + # dropped by the handler — see #2089's secondary finding. The gt branch + # has no global-option layer to worry about. + # `(?!-)`: not the plumbing commands `git commit-graph` / `git commit-tree`. + r'\bgit' + _GIT_GLOBAL_OPTS + r'\s+commit\b(?!-)' r'|\bgt\s+(?:create|modify)\b' ) # Match either the `--amend` flag (with the leading whitespace boundary @@ -721,11 +1027,9 @@ COMMIT_REVIEW_RATE_WINDOW_S = int( # ─── push-sweep ───────────────────────────────────────────────────────────── # # Mirrors Claude Code's own push-command matching — tolerates `git -C <p>` / -# `git -c k=v` global options. The hooks.json `Bash(git push:*)` matcher -# (subcommand prefix) doesn't, but those forms are rare in practice -# and the python only ever runs after CC's matcher fired, so this regex is a -# defensive re-gate, not a widening — `git -C path push` won't reach python -# unless chained with a plain `git push` in the same compound command. +# `git -c k=v` global options, as the hooks.json `Bash(git*push*)` matcher +# does. That matcher also lets through e.g. `git stash push`; this regex is +# what decides whether the command is a push. # # `gh pr create` is intentionally NOT a separate hooks.json matcher: gh runs # `git push` as a child process, which CC's matcher doesn't observe (it sees @@ -733,14 +1037,13 @@ COMMIT_REVIEW_RATE_WINDOW_S = int( # entry would buy minimal extra coverage (sessions that push only via gh) at # the cost of an extra python spawn on every `... && gh pr create` compound # (the common case). Those sessions are caught on their next standalone `git push`. -# Matches `git push` (with optional `-c k=v` / `-C path` global options -# CC's hooks.json matcher doesn't tolerate) OR `gt submit` — Graphite's +# Matches `git push` (with optional `-c k=v` / `-C path` global options) +# OR `gt submit` — Graphite's # stacked-PR push command. gt submit forwards to `git push` internally, # but the bash hook fires on Claude's top-level command so we need to # recognize gt submit at the matcher level. See #2048. _GIT_PUSH_RE = re.compile( - r'(?:\bgit(?:\s+-[cC]\s+(?:"[^"]*"|\'[^\']*\'|[^\s"\']\S*)|\s+--[^\s=]+=\S+' - r'|\s+--(?:git-dir|work-tree)\s+\S+)*\s+push\b|\bgt\s+submit\b)' + r'(?:\bgit' + _GIT_GLOBAL_OPTS + r'\s+push\b|\bgt\s+submit\b)' ) # `git push` stdout: "abc1234..def5678 branch -> branch" (or `+abc..def` on @@ -757,12 +1060,61 @@ _PUSH_RANGE_RE = re.compile( MAX_PUSH_SWEEP_FILES = int(os.environ.get("SG_PUSH_SWEEP_MAX_FILES", "30")) MAX_PUSH_SWEEP_RANGE = int(os.environ.get("SG_PUSH_SWEEP_MAX_RANGE", "50")) PUSH_SWEEP_REPORT_CAP = int(os.environ.get("SG_PUSH_SWEEP_REPORT_CAP", "3")) +# How long a push review waits for a commit review that is still running on +# the pushed commits, before reviewing them itself. Longer than the agentic +# race delay, so a commit review that fell back to single-shot can finish. +try: + INFLIGHT_WAIT_S = int(os.environ.get("SG_INFLIGHT_WAIT_S", "") or 240) +except ValueError: + INFLIGHT_WAIT_S = 240 + +# Word pairs a shell `case` pattern (`*git*commit*|*git*push*|...`) would look +# for in the raw hook input: wider than _GIT_COMMIT_RE / _GIT_PUSH_RE, so a +# command those match always contains one of these pairs in this order. +_SHELL_PRECHECK_PAIRS = ( + ("git", "commit"), ("git", "push"), + ("gt", "create"), ("gt", "modify"), ("gt", "submit"), +) +# One in this many unmatched Bash calls reports, to keep the row count down. +_UNMATCHED_BASH_SAMPLE = 10 +# Set when a command that is reviewed would not have passed the text check. +_precheck_miss = False + + +def _shell_precheck_passes(raw): + """True when `raw` holds one of _SHELL_PRECHECK_PAIRS, first word first. + + Measurement only. Tells how many hook starts that match no commit or push + a text check in the launcher could avoid (`precheck_skip`), and whether + that check would ever drop a command that is reviewed (`precheck_miss`). + """ + for first, second in _SHELL_PRECHECK_PAIRS: + at = raw.find(first) + if at != -1 and raw.find(second, at + len(first)) != -1: + return True + return False + + +def _unmatched_bash_sampled(input_data): + """Pick the same one call in _UNMATCHED_BASH_SAMPLE in every start of it. + + One Bash call can start this hook once per hooks.json entry, so the choice + is made from the call's id: all its starts report or none do. A call with + no id is not reported. + """ + tool_use_id = input_data.get("tool_use_id") + if not isinstance(tool_use_id, str) or not tool_use_id: + return False + digest = hashlib.sha256(tool_use_id.encode("utf-8", "replace")).digest() + return int.from_bytes(digest[:4], "big") % _UNMATCHED_BASH_SAMPLE == 0 + def _claim_bash_hook_once(input_data): """De-dupe across hooks.json `if` matchers firing for the same Bash call. - `git commit -m x && git push` matches both `Bash(git commit:*)` and - `Bash(git push:*)` `if` configs → CC spawns this script twice with the + `git commit -m x && git push` matches both `Bash(git*commit*)` and + `Bash(git*push*)` `if` configs, and a command CC cannot parse runs every + `if` config → CC spawns this script more than once with the SAME `tool_use_id`. The first spawn atomically creates a sentinel under `.git/`; subsequent spawns see it and exit early. Avoids redundant LLM calls (and the redundant asyncRewake) on compound commands. @@ -893,6 +1245,17 @@ def _push_section(bash_output): section = section[:end] return section +def _push_in_output(bash_output): + """True when Bash output shows a git push that updated a remote branch.""" + section = _push_section(bash_output or "") + if not section.lstrip("\n").startswith("To "): + return False + return bool(_PUSH_RANGE_RE.search(section)) or "[new branch]" in section + +# Only words the failed-review notice; `gh pr create` alone is not routed to +# the push review. +_MAY_PUSH_VIA_GH_RE = re.compile(r"\bgh\s+pr\s+create\b") + def _detect_prev_upstream(repo_root, bash_output): """Where the remote was BEFORE this push. @@ -956,26 +1319,90 @@ def is_commit_review_enabled(): COMMIT_REVIEW_ENABLED = is_commit_review_enabled() +_HOOK_STARTED = time.monotonic() + +# Seconds into the hook after which neither side of a commit or push review's +# race waits for the other any longer; well inside Claude Code's 10-minute hook +# timeout. +_RACE_MAX_WAIT_S = 480 +# Seconds after which the review ends even if a side is still waiting on a +# request that does not answer, with time left to tell the session before +# Claude Code kills the hook. The inner CLI exits with the hook. The same limit +# holds for a commit or push review's single-shot review outside a race. +_RACE_END_S = 570 +# api_error for a race that hit that deadline with no verdict. +_RACE_TIMED_OUT = -2 + +def _hook_spent_s() -> float: + return time.monotonic() - _HOOK_STARTED + +def _single_shot_review( + diff_files: List[Tuple[str, str]], + previous_findings: List[Dict[str, Any]], +) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: + """A single-shot review as (guidance, vulns, metrics); failures are in the + metrics, not raised.""" + try: + g, v = analyze_code_security( + diff_files, is_diff=True, previous_findings=previous_findings + ) + # Read on this thread: the outcome is per thread. + failed = llm.last_review_failed() + return g, v, {"agentic": False, "review_failed": failed, + "api_error": llm.last_review_status() if failed else None} + except Exception as e: + debug_log(f"single-shot review crashed: {type(e).__name__}: {e}") + return None, [], {"agentic": False, "review_failed": True, "api_error": None} + +def _single_shot_review_in_time( + diff_files: List[Tuple[str, str]], + previous_findings: List[Dict[str, Any]], +) -> Tuple[Optional[str], List[Dict[str, Any]], bool, Optional[int]]: + """A single-shot review outside a race, as (guidance, vulns, failed, status). + + It ends at _RACE_END_S into the hook, whatever is pending. + """ + done: List[Any] = [] + worker = threading.Thread( + target=lambda: done.append(_single_shot_review(diff_files, previous_findings)), + daemon=True, + ) + worker.start() + worker.join(timeout=max(0.0, _RACE_END_S - _hook_spent_s())) + if not done: + debug_log("single-shot review: nothing returned in time") + return None, [], True, _RACE_TIMED_OUT + g, v, m = done[0] + return g, v, m["review_failed"], m["api_error"] + def _agentic_review_with_race( repo_root: str, diff_files: List[Tuple[str, str]], rel_touched: List[str], previous_findings: List[Dict[str, Any]], + spent_s: float = 0.0, ) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: """Race the agentic reviewer against a delayed single-shot fallback. Agentic starts at t=0. After SG_AGENTIC_RACE_DELAY_S (default 180s), the - single-shot diff reviewer also starts. Whichever finishes first wins. If - agentic finishes before the delay elapses, the fallback never runs. + single-shot diff reviewer also starts. Whichever finishes first wins, + except that a single-shot review with no verdict waits for agentic up to + _RACE_MAX_WAIT_S from the start, and that if agentic fails after the + fallback started, the fallback's result (or, past the deadline, no + verdict) is returned so the caller never starts another review. If agentic + finishes before the delay, the fallback never runs. + + `spent_s`, the time the hook has already run, comes off the delay and both + limits: the hook's time limit does not restart with the race. Metrics added: race_winner : 1 = agentic won, 2 = fallback won (CC accepts only bool/finite-number metric values — strings would discard the dict) - race_delay_s : the configured delay + race_delay_s : the delay used race_started : 1 if the fallback was actually launched, else 0 - Only the commit-review handler calls this — external harnesses invoke - agentic_review() directly and are unaffected. SG_AGENTIC_NO_RACE=1 + Only the commit-review and push-sweep handlers call this — external + harnesses invoke agentic_review() directly and are unaffected. SG_AGENTIC_NO_RACE=1 disables the race for any other caller that wants pure agentic. """ import queue as _queue @@ -985,9 +1412,16 @@ def _agentic_review_with_race( if os.environ.get("SG_AGENTIC_NO_RACE") == "1": return agentic_review(repo_root, diff_files, rel_touched) - delay_s = int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) + delay_s = max(0, int(os.environ.get("SG_AGENTIC_RACE_DELAY_S", "180")) - int(spent_s)) + if spent_s >= 1: + debug_log(f"Review race: {spent_s:.0f}s already spent, fallback starts after {delay_s}s") q: "_queue.Queue[Tuple[str, Any]]" = _queue.Queue(maxsize=1) fallback_started = _th.Event() + fallback_done = _th.Event() + agentic_done = _th.Event() + fallback_result: Dict[str, Any] = {} + deadline = _t.monotonic() + max(0.0, _RACE_MAX_WAIT_S - spent_s) + timed_out = (None, [], {"agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) def _agentic() -> None: try: @@ -998,33 +1432,173 @@ def _agentic_review_with_race( q.put_nowait(("agentic", r)) except _queue.Full: pass + agentic_done.set() def _fallback() -> None: _t.sleep(delay_s) - if not q.empty(): + if agentic_done.is_set(): return # agentic finished within the delay — never start fallback fallback_started.set() + result = _single_shot_review(diff_files, previous_findings) + fallback_result["r"] = result + fallback_done.set() + if result[2]["review_failed"]: + # A failed fallback does not win: the agentic review's inner + # CLI may still get a verdict where direct calls cannot. + agentic_done.wait(timeout=max(0.0, deadline - _t.monotonic())) try: - g, v = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings - ) - except Exception as e: # pragma: no cover - g, v = None, [] - try: - q.put_nowait(("fallback", (g, v, {"agentic": False}))) + q.put_nowait(("fallback", result)) except _queue.Full: pass _th.Thread(target=_agentic, daemon=True).start() _th.Thread(target=_fallback, daemon=True).start() - winner, (g, v, m) = q.get() - m = dict(m) # don't mutate the callee's metrics dict + try: + winner, (g, v, m) = q.get(timeout=max(0.0, _RACE_END_S - spent_s)) + except _queue.Empty: + debug_log("review race: nothing returned in time") + winner, (g, v, m) = "fallback", timed_out + # What the agentic run saw of its directory, and how much work it did, + # is kept when the fallback's result replaces it below. + reviewer_context = ( + {k: m[k] for k in _REVIEWER_CONTEXT_KEYS + _REVIEWER_EFFORT_KEYS if k in m} + if winner == "agentic" else {} + ) + if winner == "agentic" and m.get("agentic_fallback") and fallback_started.is_set(): + # The caller would rerun the single-shot review the fallback has + # already started; use its result instead. + if fallback_done.wait(timeout=max(0.0, deadline - _t.monotonic())): + winner, (g, v, m) = "fallback", fallback_result["r"] + else: + winner, (g, v, m) = "fallback", timed_out + m = {**m, **reviewer_context} # a copy: don't mutate the callee's metrics dict m["race_winner"] = 1 if winner == "agentic" else 2 m["race_delay_s"] = delay_s m["race_started"] = 1 if fallback_started.is_set() else 0 return g, v, m +def _review_failure_reason(status): + """(failure type, reason, likely cause or "") for a review with no verdict. + + `status` is llm.last_review_status(): an HTTP status, -1 for a network + error or timeout, None when the reply could not be read; or + _RACE_TIMED_OUT. + """ + gateway = (", or an LLM gateway may need its key in ANTHROPIC_CUSTOM_HEADERS" + if os.environ.get("ANTHROPIC_BASE_URL", "").strip() else "") + if status == _RACE_TIMED_OUT: + return ("timeout", "the review did not finish in time", "") + if llm._is_3p_provider(): + return ("provider", "the review through the cloud provider got no answer", + "The plugin's log has the provider's error.") + if llm._gateway_cli: + pinned = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() + return ("gateway", "the review through Claude Code on the Claude apps gateway returned no result", + "The plugin's log has the reason. If it says the sign-in has expired, run /login again." + + (f" SECURITY_REVIEW_MODEL ({pinned}) may also name a model the gateway does " + "not serve." if pinned else "")) + if status == 401: + return ("auth", "the API rejected the plugin's credentials (HTTP 401)", + f"The sign-in may have expired or been revoked{gateway}.") + if status == 403: + return ("auth", "the API refused access (HTTP 403)", + f"The account may lack access to the review model{gateway}.") + if status == 429 or (isinstance(status, int) and status >= 500): + return ("busy", f"the API was busy or unavailable (HTTP {status})", + "This is usually temporary.") + if status == -1: + return ("network", "the model could not be reached (network error or timeout)", "") + if isinstance(status, int): + pinned = os.environ.get("SECURITY_REVIEW_MODEL", "").strip() + return ("request", f"the API refused the request (HTTP {status})", + f"SECURITY_REVIEW_MODEL ({pinned}) may name a model this account " + "cannot use." if pinned else "") + return ("reply", "the model's reply could not be read", "") + + +def _left_out_files_notice(session_id, repo_root, untracked, diff_output): + """(one line for the terminal, text for Claude) naming the source files a + failed `git add -N` kept out of this Stop review, or None. + + Each set of files gets one notice a session: the wake ends in another Stop + that fails the same way, and a notice there would wake Claude for ever. So + no notice unless the mark is saved. Paths are JSON quoted in ASCII: a file + name can hold a line break. + """ + in_diff = set(extract_file_paths_from_diff(diff_output or "")) + + def has_content(p): + try: + return os.path.getsize(os.path.join(repo_root, p)) > 0 + except OSError: + return False + + names = sorted(p for p in untracked or () + if p not in in_diff and _is_reviewable_source(p) and has_content(p)) + if not names: + return None + key = "new_files_left_out:" + hashlib.sha256( + "\0".join(names).encode("utf-8", "replace")).hexdigest()[:16] + if not atomic_check_and_mark_warning(session_id, key): + return None + if key not in load_state(session_id).get("shown_warnings", ()): + return None + _TAIL_METRICS["add_fail_told"] = len(names) + shown = ", ".join(json.dumps(p) for p in names[:_LEFT_OUT_NAMES_SHOWN]) + if len(names) > _LEFT_OUT_NAMES_SHOWN: + shown += f" and {len(names) - _LEFT_OUT_NAMES_SHOWN} more" + return (f"Security review left out new files: {shown}. Log: {DEBUG_LOG_FILE}", + f"The security review did not see these new files, so it did not " + f"review them: {shown}. git could not add them to the review's " + f"diff. Tell the user this in one sentence, and that details are " + f"in {DEBUG_LOG_FILE}.") + + +def _exit_review_failed(kind, session_id, metrics, status, pushed="no"): + """End a commit ("Commit") or push ("Push") review that got no verdict. + + Never reports the code as clean. Tells Claude once per session for each + kind of review and failure; repeats are only logged. `pushed` ("yes", + "maybe" or "no"): whether the commit's own command also pushed it. Exits. + """ + failure, reason, cause = _review_failure_reason(status) + debug_log(f"{kind} review: got no verdict ({reason}); not marked reviewed") + metrics = {"review_failed": True, + **({"api_error": status} if status is not None else {}), + **metrics, "vulns_found": 0} + # A commit its own command pushed gets its own notice: no later push + # re-checks it. + told_key = f"review_failed:{kind}:{failure}" + (":pushed" if pushed == "yes" else "") + if not atomic_check_and_mark_warning(session_id, told_key): + emit_metrics(metrics) + sys.exit(0) + subject = "this push" if kind == "Push" else "this commit" + if kind == "Push": + after = ("It was for the pushed commits not already reviewed when they " + "were committed, and a later push will not re-check them.") + elif pushed == "yes": + after = "The same command pushed it, so a later push will not re-check it." + elif not PUSH_SWEEP_ENABLED: + after = "" + elif pushed == "maybe": + after = ("If the same command pushed it, a later push will not re-check " + "it; otherwise a later push from Claude Code will.") + else: + after = "If it is pushed later from Claude Code, the push review will check it." + notice = " ".join(part for part in ( + f"The security review of {subject} did not complete: {reason}.", cause, after, + f"Tell the user this in one sentence, and that details are in {DEBUG_LOG_FILE}.", + ) if part) + # The notice goes on stderr: Claude Code shows Claude an asyncRewake + # hook's stderr, else its stdout, which carries the metrics line. + sys.stderr.write(PROVENANCE_BANNER + "\n\n" + notice + "\n") + sys.stderr.flush() + emit_metrics(metrics, + rewake_summary=(f"{kind} security review did not complete: {reason}. " + f"Log: {DEBUG_LOG_FILE}")) + sys.exit(2) + def handle_commit_review_posttooluse(input_data): """PostToolUse handler for Bash — reviews git commits for security issues. @@ -1036,15 +1610,17 @@ def handle_commit_review_posttooluse(input_data): the Stop hook won't re-flag the same (filePath, vulnerableCode) pair. """ session_id = input_data.get("session_id", "default") + _USAGE_CONTEXT["review"] = "commit" tool_input = input_data.get("tool_input", {}) tool_response = input_data.get("tool_response", {}) cwd = input_data.get("cwd", "") command = tool_input.get("command", "") if not isinstance(command, str) or not _GIT_COMMIT_RE.search(command): - # Defensive only — hooks.json's `"if": "Bash(git commit:*)"` is the - # real gate so CC never spawns python3 for ls/grep/etc. This catches - # cases where CC's command matching fails open and spawns the hook anyway. + # hooks.json's `"if": "Bash(git*commit*)"` only keeps CC from + # spawning python3 for ls/grep/etc. It lets through other git commands + # with "commit" in them (`git merge --no-commit`), and CC runs the hook + # anyway when it cannot parse the command; this regex decides. sys.exit(0) debug_log(f"Commit review: detected git commit in command") @@ -1113,8 +1689,13 @@ def handle_commit_review_posttooluse(input_data): _root = repo_root _fresh, _stale = _git_reflog_recent_commits(_root) if _fresh: + # Commits an earlier call's review is still working on are that + # review's: it records them when it has a verdict. (Read before + # the reviewed set, so one that ends in between counts as reviewed.) + _inflight = _load_inflight_shas(_root, _fresh) _already = _load_reviewed_shas(_root) - _reflog_shas = [s for s in _fresh if s not in _already] + _reflog_shas = [s for s in _fresh + if s not in _already and s not in _inflight] if _reflog_shas: commit_succeeded = True debug_log( @@ -1126,8 +1707,9 @@ def handle_commit_review_posttooluse(input_data): # Fresh commit(s) in reflog but all already in # sg-reviewed-shas — likely a Bash retry or the commit was # reviewed via a prior fire. Correct to skip; sub=2 lets telemetry - # split this from genuine fails. - _skip_21_sub = 2 + # split this from genuine fails. sub=5: at least one is still + # being reviewed by an earlier call. + _skip_21_sub = 5 if any(s not in _already for s in _fresh) else 2 elif _stale: _skip_21_sub = 3 # commit entries exist but all >120s old else: @@ -1146,9 +1728,10 @@ def handle_commit_review_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 32, **_base}) sys.exit(0) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - debug_log("Commit review: LLM review disabled or no API credentials") - emit_metrics({"skipped": True, "skip_reason": 22, **_base}) + off = _llm_review_off(session_id) + if off: + debug_log(f"Commit review: {off[0]}") + emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base}) sys.exit(0) if not ensure_anthropic_reachable(): @@ -1387,52 +1970,48 @@ def handle_commit_review_posttooluse(input_data): previous_findings = with_locked_state(session_id, _read_previous) or [] + # Tell a push review (or the next commit's reflog scan) that these commits + # are being reviewed, so it does not start a second review of them. + _mark_inflight(repo_root, _full_shas(repo_root, shas)) + # Count only: keyed on what the reviewer is sent, after the byte caps. + _diff_token, _seen_m = _diff_review_started( + repo_root, _cap_files_for_prompt(diff_files), tip=shas[0]) + _TAIL_METRICS.update(_seen_m) + review_start = _time.time() agentic_metrics: Dict[str, Any] = {} if _agentic_commit_review_enabled(): rel_touched = [fp for fp, _ in diff_files] concrete_guidance, vulns, _am = _agentic_review_with_race( - repo_root, diff_files, rel_touched, previous_findings + repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s() ) agentic_metrics.update(_am) + if _am.get("child_stderr"): + # Lines the inner CLI wrote to stderr during the review: how often + # the condition that used to replace the findings body occurs. Not + # counted when the single-shot fallback wins the race. + _TAIL_METRICS["child_stderr"] = _am["child_stderr"] + _note_reviewer_context(agentic_metrics) + review_failed = bool(agentic_metrics.get("review_failed")) + api_status = agentic_metrics.get("api_error") # Fall back to single-shot only on agentic FAILURE (SDK/investigate # crash). If agentic completed and returned 0 findings, trust that. if agentic_metrics.get("agentic_fallback"): - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) else: - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) - # push-sweep state: record this commit as reviewed (full 40-hex sha) so a - # later `git push` can advance its diff base past it. Recorded here — after - # the review ran but before any exit path — so it's marked regardless of - # whether findings were emitted. `shas` holds abbreviated refs from - # `[branch sha]`; resolve to full so set-membership in the push-sweep is - # exact. Best-effort; failures here never block the review result. - try: - full_shas = [] - for s in shas: - # See #2099: drop text=True; decode manually for cp1252 safety. - r = subprocess.run( - [*GIT_CMD, "rev-parse", "--verify", "-q", s], - cwd=repo_root, capture_output=True, timeout=5, - ) - if r.returncode == 0: - full_shas.append(r.stdout.decode("utf-8", errors="replace").strip()) - _append_reviewed_shas(repo_root, full_shas, vulns_found=len(vulns or [])) - except Exception: - pass - review_ms = int((_time.time() - review_start) * 1000) # `survived` is the raw self-refute count BEFORE the high/critical-only # severity filter; `survived_after_sev` is the count the user actually # sees. Include `survived_after_sev` ONLY when the filter actually # dropped candidates — otherwise it's redundant with `survived` and eats - # into CC's 10-key emit cap, pushing files_reviewed/review_ms out of the + # into CC's metric-key cap, pushing files_reviewed/review_ms out of the # emitted metrics. # # CC accepts only booleans and finite numbers as metric values. @@ -1468,6 +2047,37 @@ def handle_commit_review_posttooluse(input_data): else {} ) + if review_failed: + # Not marked reviewed, so a later push review from Claude Code still + # covers it. + _exit_review_failed("Commit", session_id, { + **_base, **_agentic_m, + "files_reviewed": len(diff_files), "review_ms": review_ms, + }, api_status, pushed=( + "yes" if _push_in_output(bash_output) + else "maybe" if _GIT_PUSH_RE.search(command) or _MAY_PUSH_VIA_GH_RE.search(command) + else "no")) + + # push-sweep state: record this commit as reviewed (full 40-hex sha) so a + # later `git push` can advance its diff base past it. Recorded only after a + # review that got a verdict, whether or not it found anything. `shas` holds abbreviated refs from + # `[branch sha]`; resolve to full so set-membership in the push-sweep is + # exact. Best-effort; failures here never block the review result. + try: + full_shas = [] + for s in shas: + # See #2099: drop text=True; decode manually for cp1252 safety. + r = subprocess.run( + [*GIT_CMD, "rev-parse", "--verify", "-q", s], + cwd=repo_root, capture_output=True, timeout=5, + ) + if r.returncode == 0: + full_shas.append(r.stdout.decode("utf-8", errors="replace").strip()) + _append_reviewed_shas(repo_root, full_shas, vulns_found=len(vulns or [])) + except Exception: + pass + _diff_review_done(_diff_token) + if not concrete_guidance: debug_log("Commit review: no security issues found") emit_metrics({ @@ -1525,9 +2135,8 @@ def handle_commit_review_posttooluse(input_data): sev[s] += 1 # Rebuild guidance from new_vulns only — concrete_guidance from the LLM - # still lists deduped entries. Pass via additional_context so CC surfaces - # the reason via hookSpecificOutput.additionalContext instead of empty - # stdout (#1783) / stderr-only "json output validation failed" (#1375). + # still lists deduped entries. emit_metrics writes it to stderr, the body + # of the asyncRewake notice. _commit_guidance = (PROVENANCE_BANNER + "\n\n" + _format_vulns_guidance(new_vulns) + CONTINUATION_SUFFIX + "\n") @@ -1542,8 +2151,6 @@ def handle_commit_review_posttooluse(input_data): # exit(2) is preserved per the asyncRewake protocol — it's what CC # uses as the "force fix" signal that triggers the rewakeMessage flow. - # The stderr.write was removed; additional_context above now carries - # the same text via the modern JSON channel. See #1358/#1375/#1783. sys.exit(2) def handle_push_sweep_posttooluse(input_data): @@ -1570,6 +2177,7 @@ def handle_push_sweep_posttooluse(input_data): command = tool_input.get("command", "") or "" cwd = input_data.get("cwd") session_id = input_data.get("session_id", "") + _USAGE_CONTEXT["review"] = "push" bash_output = ( (tool_response.get("stdout", "") or "") + "\n" @@ -1577,9 +2185,8 @@ def handle_push_sweep_posttooluse(input_data): ) interrupted = tool_response.get("interrupted", False) - # Re-gate: hooks.json `if` matched, but confirm with the broader regex - # (defensive — `git -C`/`-c` forms won't reach here via the hooks.json - # prefix matcher alone, but a compound with a plain `git push` would). + # Re-gate: hooks.json `if` matched (or CC could not parse the command + # and ran every entry), so confirm with the regex. if not _GIT_PUSH_RE.search(command): sys.exit(0) @@ -1591,8 +2198,9 @@ def handle_push_sweep_posttooluse(input_data): if interrupted: emit_metrics({"skipped": True, "skip_reason": 21, **_base}) sys.exit(0) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - emit_metrics({"skipped": True, "skip_reason": 22, **_base}) + off = _llm_review_off(session_id) + if off: + emit_metrics({"skipped": True, "skip_reason": 22, **off[1], **_base}) sys.exit(0) if not cwd: emit_metrics({"skipped": True, "skip_reason": 25, **_base}) @@ -1722,13 +2330,27 @@ def handle_push_sweep_posttooluse(input_data): "pushed": len(push_range)}) sys.exit(0) - reviewed = _load_reviewed_shas(repo_root) + # A commit review that is still running on these commits records them + # once it has a verdict. Wait for it instead of reviewing the same diff a + # second time; if it ends without one, they are reviewed here. + reviewed, _waited = _reviewed_after_inflight( + repo_root, push_range, INFLIGHT_WAIT_S) + _wait_m = {} + if _waited: + _wait_m = {"inflight_wait_s": max(1, int(round(_waited)))} + debug_log(f"Push sweep: waited {_waited:.0f}s for a running commit review") base, tail = _compute_push_sweep_base(prev_upstream, push_range, reviewed) prefix_advanced = len(push_range) - len(tail) if base is None: debug_log("Push sweep: every pushed commit already reviewed") emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0, - "prefix_advanced": prefix_advanced}) + "prefix_advanced": prefix_advanced, **_wait_m}) + sys.exit(0) + if _waited and head and _git_rev_parse_head(repo_root) != head: + # Same guard as above: the diff and the reviewer's file reads are + # both taken at HEAD, and HEAD left the pushed tip during the wait. + debug_log("Push sweep: HEAD moved while waiting, skipping") + emit_metrics({"skipped": True, "skip_reason": 44, **_base, **_wait_m}) sys.exit(0) debug_log(f"Push sweep: range={len(push_range)} prefix_advanced=" @@ -1781,6 +2403,11 @@ def handle_push_sweep_posttooluse(input_data): emit_metrics({"skipped": True, "skip_reason": 23, **_base}) sys.exit(0) + _mark_inflight(repo_root, tail) + _diff_token, _seen_m = _diff_review_started( + repo_root, _cap_files_for_prompt(diff_files)) + _TAIL_METRICS.update(_seen_m) + import time as _time now = _time.time() previous_findings = with_locked_state( @@ -1794,40 +2421,54 @@ def handle_push_sweep_posttooluse(input_data): rel_touched = [fp for fp, _ in diff_files] if _agentic_commit_review_enabled(): concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race( - repo_root, diff_files, rel_touched, previous_findings + repo_root, diff_files, rel_touched, previous_findings, spent_s=_hook_spent_s(), ) + if agentic_metrics.get("child_stderr"): + _TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"] + _note_reviewer_context(agentic_metrics) + review_failed = bool(agentic_metrics.get("review_failed")) + api_status = agentic_metrics.get("api_error") if agentic_metrics.get("agentic_fallback"): - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) else: - concrete_guidance, vulns = analyze_code_security( - diff_files, is_diff=True, previous_findings=previous_findings + concrete_guidance, vulns, review_failed, api_status = _single_shot_review_in_time( + diff_files, previous_findings ) agentic_metrics = {} review_ms = int((_time.time() - review_start) * 1000) + if review_failed: + # Not marked reviewed. A later push does not re-check these commits: + # its range starts from the new upstream. + _exit_review_failed("Push", session_id, { + **_base, **_wait_m, "pushed": len(push_range), "unreviewed": len(tail), + "files_reviewed": len(diff_files), "review_ms": review_ms, + }, api_status) # The tail is now covered by this net-diff review. _append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or [])) + _diff_review_done(_diff_token) new_vulns, n_deduped = _dedup_against_state( session_id, vulns or [], prompted=_finding_keys(previous_findings) ) - # Metrics — keep within the 10-key cap; agentic sub-metrics are dropped + # Metrics — keep within CC's metric-key cap; agentic sub-metrics are dropped # here in favour of the push-sweep funnel keys (telemetry can join on session_id # to the per-commit fires for agentic detail). rewake_summary must ride # this line (CC reads only the first {-prefixed stdout line); the emit # is deferred to the two exit points below so the with-vulns path can - # also pass additional_context in the same JSON line (#1375/#1783) — - # the by-design "CC keeps only the first JSON line" constraint means - # we can't emit twice. Builds the shared metrics dict here; vulns path + # also pass additional_context in the same emit_metrics call — the + # by-design "CC keeps only the first JSON line" constraint means we + # can't emit twice. Builds the shared metrics dict here; vulns path # adds additional_context, no-vulns path emits as-is. _push_metrics = { **_base, "pushed": len(push_range), "unreviewed": len(tail), "prefix_advanced": prefix_advanced, "vulns_found": len(new_vulns), "files_reviewed": len(diff_files), "review_ms": review_ms, **({"deduped": n_deduped} if n_deduped else {}), + **_wait_m, } _push_rewake_summary = _format_vulns_summary(new_vulns, prefix="Push security review found") @@ -1887,15 +2528,23 @@ def handle_push_sweep_posttooluse(input_data): else: guidance = concrete_guidance or _format_vulns_guidance(reported) or "" # Emit metrics + additional_context together — single JSON line is the - # contract CC's hook parser expects. exit(2) preserved as the asyncRewake - # "force fix" trigger (see comment near handle_commit_review_posttooluse). - # See #1358 / #1375 / #1783. + # contract CC's hook parser expects; the guidance itself goes to stderr. + # exit(2) preserved as the asyncRewake "force fix" trigger (see comment + # near handle_commit_review_posttooluse). emit_metrics(_push_metrics, rewake_summary=_push_rewake_summary, additional_context=(PROVENANCE_BANNER + "\n\n" + guidance + CONTINUATION_SUFFIX + "\n"), hook_event_name="PostToolUse") sys.exit(2) +def _stop_diff_truncated(): + """Bytes of reviewable diff the Stop review did not send: cut while + reading git's output, plus what the prompt caps dropped after that. + As the metric to emit, or nothing when there were none.""" + n = llm._last_review_truncated_bytes + gitutil._diff_read["cut_bytes"] + return {"diff_truncated": n} if n else {} + + def handle_stop_hook(input_data): """ Handle the Stop hook — final security check using git diff. @@ -1935,23 +2584,61 @@ def handle_stop_hook(input_data): head_at_capture = snap["head_at_capture"] untracked_at_baseline = snap.get("untracked_at_baseline") or {} previous_findings = snap["previous_findings"] + # Only when it happened: state lost to an unreadable file, and saves that + # overwrote another hook's (possible only without locking). SubagentStop + # does not clear them, so it does not report them either. + if not is_subagent: + for _k in ("state_resets", "state_overwrites"): + if isinstance(snap.get(_k), int) and snap[_k] > 0: + _TAIL_METRICS[_k] = snap[_k] # Sweep pattern-warning outcomes (pure local work; stop_hook_active is # already guaranteed False here so no double-count guard needed). sweep = {} - warn_fixed, warn_unresolved, warn_unresolved_mask = sweep_pending_warnings(session_id) + (warn_fixed, warn_unresolved, warn_unresolved_mask, + warn_fired_mask) = sweep_pending_warnings(session_id) if warn_fixed or warn_unresolved: sweep = { "warn_fixed": warn_fixed, "warn_unresolved": warn_unresolved, "warn_unresolved_mask": warn_unresolved_mask, } + # The two masks also ride the tail, so the reviewed rows below, which + # leave `sweep` or its mask out, carry them when there is room under the + # key cap. Per rule they give how often it fired and how often the + # flagged code was still there at Stop. warn_fired_mask goes after + # warn_unresolved_mask: a row cut at the cap loses it first, and a row + # without it is left out of the per-rule read instead of counting its + # rules as fixed. + if warn_unresolved_mask: + _TAIL_METRICS["warn_unresolved_mask"] = warn_unresolved_mask + if warn_fired_mask: + _TAIL_METRICS["warn_fired_mask"] = warn_fired_mask v2_metrics = {} + left_out = False + restore_paths = touched_paths + + def _left_out_notice(): + # Asked for as the row goes out: the mark must not outlive a hook + # killed during the review. + if not left_out: + return None + return _left_out_files_notice(session_id, repo_root, untracked, diff_output) + + def _left_out_wake(): + """emit_metrics arguments that wake Claude to say new files were left out.""" + notice = _left_out_notice() + if not notice: + return {} + return {"rewake_summary": notice[0], "hook_event_name": hook_event_name, + "additional_context": (PROVENANCE_BANNER + "\n\n" + notice[1] + + CONTINUATION_SUFFIX + "\n")} def _skip(reason, restore=False, **extra): if restore: - restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) + restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline) + wake = _left_out_wake() # CC truncates metrics to 10 keys by # insertion order. v2_metrics (3) must precede sweep (3) so the v2 # diagnostics survive when extra adds touched_paths_count + ip_* keys. @@ -1959,8 +2646,12 @@ def handle_stop_hook(input_data): "skipped": True, "skip_reason": reason, "fire_index": fire_count + 1, "diff_strategy_v2": True, **v2_metrics, **extra, **sweep, - }) - sys.exit(0) + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), + }, **wake) + sys.exit(2 if wake else 0) # Limit stop hook firings per asyncRewake loop to prevent infinite loops. # fire_count auto-expires after STOP_LOOP_STATE_TTL_SEC so a stale count @@ -1969,9 +2660,12 @@ def handle_stop_hook(input_data): debug_log(f"Stop hook: already fired {fire_count} times (max {MAX_STOP_HOOK_FIRINGS}), skipping") _skip(2) - if not ENABLE_CODE_SECURITY_REVIEW or not HAS_API_CREDENTIALS: - debug_log("Stop hook: LLM review disabled or no API credentials") - _skip(3) + off = _llm_review_off(session_id) + if off: + debug_log(f"Stop hook: {off[0]}") + # When the sign-in check gave no answer, this turn's changes are kept + # for the next Stop review. + _skip(3, restore=llm._gateway_check_unanswered, **off[1]) # Stop-hook-only kill switch — placed after consume_stop_state so # touched_paths is still cleared each turn (a disabled Stop hook that @@ -2008,37 +2702,116 @@ def handle_stop_hook(input_data): save_repo_hint(session_id, repo_cwd) cwd = repo_cwd + # The baseline belongs to the checkout the prompt hook captured it in. + # When the turn ends in another one (the session entered a worktree, or + # the edits were in a different repo), it says nothing about what changed + # here: this checkout's older commits would look like commits made this + # turn, and its files would be diffed against the other checkout's. Use + # what this checkout can say for itself instead: its own HEAD when the + # turn began (from its reflog) for commits, HEAD for file contents, and + # file times for which uncommitted files were already there. + origin = None + if repo_cwd: + try: + origin = baseline_origin(repo_cwd, snap_baseline, snap["baseline_root"]) + except Exception as e: + debug_log(f"Stop hook: baseline origin check failed: {e}") + foreign_baseline = origin in FOREIGN_ORIGINS + since_ns = None + if foreign_baseline: + at = snap["prompt_at"] + at = at if isinstance(at, (int, float)) and 0 < at < 1e11 else None + baseline_sha = None + head_at_capture = _git_head_at(repo_cwd, at) if at else None + untracked_at_baseline = {} + since_ns = int(at * 1e9) if at else None + debug_log(f"Stop hook: baseline {str(snap_baseline)[:12]} is from another " + f"checkout (origin {origin}); this one was at " + f"{str(head_at_capture)[:12]} when the turn began") + review_paths, diff_base, repo_root, untracked, v2_metrics = compute_v2_review_set( - cwd, baseline_sha, head_at_capture, untracked_at_baseline + cwd, baseline_sha, head_at_capture, untracked_at_baseline, since_ns=since_ns ) + # Sent even when 0, once git status has worked. + if origin is not None and v2_metrics.get("dirty_now_count", -1) >= 0: + _TAIL_METRICS["bl_origin"] = baseline_origin_metric(origin, snap["baseline_kept"]) + v2_metrics = {**res_metrics, **v2_metrics} + # Count-only view of how the review set relates to what the session's + # edit tools wrote. Only when a repo was read; never fails the review. + def _note_scope(files): + try: + if "scope" not in _scope: + _scope["scope"] = touched_scope( + repo_root, input_data.get("cwd", ""), snap["turn_touched"]) + # -1: the stored baseline could not be used in this repo. + fail = (3 if v2_metrics.get("changed_since_count") == -1 + else snap.get("baseline_fail")) + _TAIL_METRICS["review_scope"] = review_scope_code( + repo_root, *_scope["scope"], files, fail) + except Exception as e: + debug_log(f"review scope telemetry skipped: {e}") + _scope = {} + if v2_metrics.get("dirty_now_count", -1) >= 0: + _note_scope(review_paths) if not review_paths: debug_log("Stop hook: empty review set") _skip(9, touched_paths_count=len(touched_paths)) 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']}") + if (len(review_paths) > MAX_REVIEW_SET_PATHS + and sum(_is_reviewable_source(os.path.relpath(p, repo_root)) + for p in review_paths) > MAX_REVIEW_SET_PATHS): + debug_log(f"Stop hook: pathological review set (more than " + f"{MAX_REVIEW_SET_PATHS} paths), skipping") + _skip(8) # Run from repo_root so the toplevel-relative review_paths resolve. - # Diff CONTENT against the turn-start stash (baseline_sha) so the LLM + # Diff CONTENT against the turn-start snapshot (baseline_sha) so the LLM # sees only this-turn edits — diffing against HEAD includes the user's # pre-turn uncommitted WIP, which inflates review_ms and can re-flag # the same pre-existing pattern every turn. The file LIST still comes # from git state (compute_v2_review_set), so Bash/subagent edits are # caught either way. Fall back to diff_base (HEAD/head_at_capture) - # when the stash is missing or pruned. + # when the baseline commit is missing or pruned. content_base = baseline_sha or diff_base diff_output = get_git_diff(repo_root, content_base, full_context=False, paths=review_paths, untracked_paths=untracked) - if diff_output is None and content_base != diff_base: + if (diff_output is None and content_base != diff_base + and "gave_up" not in gitutil._path_list_too_long): debug_log(f"Stop hook: diff against {content_base[:12]} failed — falling back to {diff_base}") diff_output = get_git_diff(repo_root, diff_base, full_context=False, paths=review_paths, untracked_paths=untracked) + # Only when it happened: a failed `git add -N` (first, so a row at CC's key + # cap keeps it), MiB of git diff output read, reviewable files whose diff + # was cut while reading it, diffs that hit the timeout. + for _k, _v in (("add_fail", gitutil._add_failed["code"]), + ("diff_mb", gitutil._diff_read["bytes"] >> 20), + ("diff_cut_files", gitutil._diff_read["cut_files"]), + ("diff_timeout", gitutil._diff_read["timeouts"])): + if _v: + _TAIL_METRICS[_k] = _v # filter_preexisting_from_diff needs a resolvable pre-turn ref; fall # back to HEAD when UPS never captured a baseline (print mode). if not baseline_sha: baseline_sha = "HEAD" + # New files a failed `git add -N` hid: when nothing gets reviewed they are + # put back, listed as touched so the next prompt keeps this baseline even + # if an edit tool never wrote them. A review of the tracked files goes on + # without them, rather than repeating that review every turn. + left_out = gitutil._add_failed["left_out"] + if left_out: + restore_paths = list(touched_paths) + [ + os.path.join(repo_root, p) for p in untracked or ()] + if not diff_output or not diff_output.strip(): + if "gave_up" in gitutil._path_list_too_long: + debug_log("Stop hook: changed paths do not fit the git commands, skipping") + _skip(8) + if "none_reviewable" in gitutil._path_list_too_long: + debug_log("Stop hook: no source code files among the changed paths") + _skip(7) debug_log("Stop hook: no changes since baseline") - _skip(6) + _skip(6, restore=left_out) diff_hash = hashlib.sha256(diff_output.encode("utf-8", "replace")).hexdigest() if snap.get("reviewed_diff_hash") == diff_hash: @@ -2049,7 +2822,7 @@ def handle_stop_hook(input_data): diff_files = parse_diff_into_files(diff_output) if not diff_files: debug_log("Stop hook: no source code files in diff") - _skip(7) + _skip(7, restore=left_out) # Mirror commit-review: hard-bail only on pathological diffs (>300 files, # usually a bad baseline), otherwise prioritize by security-risk path @@ -2070,8 +2843,13 @@ def handle_stop_hook(input_data): # Filter out pre-existing content from file rewrites diff_files = filter_preexisting_from_diff(diff_files, cwd, baseline_sha) + if "scope" in _scope: + _note_scope([fp for fp, _ in diff_files]) debug_log(f"Stop hook: reviewing {len(diff_files)} changed files (standard diff)") + secret_named = gitutil.count_secret_named(diff_files) + if secret_named: + _TAIL_METRICS["secret_named_reviewed"] = secret_named import time as _time stop_review_start = _time.time() @@ -2116,7 +2894,12 @@ def handle_stop_hook(input_data): ] # Update baseline so next stop hook iteration only sees new changes new_sha = None if is_subagent else capture_git_baseline(cwd) + new_base_fail = diffstate.last_baseline_fail new_untracked_baseline = _list_untracked(cwd) if new_sha else None + # After a baseline from another checkout, the rest of it is replaced + # too, below. + new_head = (_git_rev_parse_head(cwd) + if new_sha and foreign_baseline and not head_at_capture else None) def _record_fire(state): if is_subagent: @@ -2141,6 +2924,14 @@ def handle_stop_hook(input_data): if new_sha: state["baseline_sha"] = new_sha state["untracked_at_baseline"] = new_untracked_baseline + _store_baseline_fail(state, new_base_fail) + state["baseline_root"] = repo_root + state.pop("baseline_kept", None) + if foreign_baseline: + # The stored HEAD is the other checkout's. Keep the one + # this review used, so a later Stop this turn still sees + # commits made (or amended) here since the prompt. + state["head_at_capture"] = head_at_capture or new_head with_locked_state(session_id, _record_fire) if new_sha: @@ -2155,11 +2946,10 @@ def handle_stop_hook(input_data): # untracked_baseline_n is the signal for whether the UPS-time # untracked-snapshot capture actually ran. sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"} - # Pass guidance via additional_context so CC surfaces the findings via - # hookSpecificOutput.additionalContext instead of stderr-only (which - # was the cause of "json output validation failed" / empty-reason UI in - # #1375 / #1783). exit(2) preserved as the asyncRewake "force fix" - # signal — that's the documented mechanism. See #1358 / #1375 / #1783. + left_out_notice = _left_out_notice() + # Guidance goes to stderr plus top-level decision/reason (see + # emit_metrics). exit(2) preserved as the asyncRewake "force fix" + # signal — that's the documented mechanism. emit_metrics({ "vulns_found": len(vulns), "untracked_baseline_n": len(untracked_at_baseline), @@ -2170,30 +2960,38 @@ def handle_stop_hook(input_data): "touched_paths_count": len(touched_paths), "review_ms": review_ms, "fire_index": fire_index, - **({"diff_truncated": llm._last_review_truncated_bytes} - if llm._last_review_truncated_bytes else {}), + **_stop_diff_truncated(), **({"repo_resolution": repo_res} if res_metrics else {}), **sweep_trimmed, + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), }, rewake_summary=_format_vulns_summary(vulns), - additional_context=(PROVENANCE_BANNER + "\n\n" - + concrete_guidance + CONTINUATION_SUFFIX + "\n"), + additional_context=(PROVENANCE_BANNER + "\n\n" + concrete_guidance + + ("\n\n" + left_out_notice[1] if left_out_notice else "") + + CONTINUATION_SUFFIX + "\n"), hook_event_name=hook_event_name) sys.exit(2) - if llm._last_call_claude_http_error is not None: - debug_log(f"Stop hook: API call failed with status {llm._last_call_claude_http_error}") - restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline) + stop_review_failed = llm.last_review_failed() + if stop_review_failed: + debug_log(f"Stop hook: review got no verdict " + f"({_review_failure_reason(llm.last_review_status())[1]})") + restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline) else: debug_log("Stop hook: no security issues found") if is_subagent: record_reviewed_diff(session_id, diff_hash) - # CC truncates metrics to 10 keys by - # insertion order. The previous **sweep,**v2_metrics tail meant the 3 - # v2_metrics keys were always sliced off this most-common path, so the - # diff-strategy diagnostics never reached telemetry. Drop sweep here (it's - # PostToolUse-warning state, orthogonal to diff-strategy comparison). - # 6 base + optional api_error + 3 v2_metrics = ≤10. + wake = _left_out_wake() + # CC keeps the first 20 metric keys (10 in older versions), in insertion + # order, after the pv and usage keys emit_metrics puts first. The previous + # **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced + # off this most-common path, so the diff-strategy diagnostics never reached + # telemetry. Drop sweep here (it's PostToolUse-warning state, orthogonal to + # diff-strategy comparison). emit_metrics({ + **({"review_failed": True} if stop_review_failed else {}), "vulns_found": 0, "diff_strategy_v2": True, "files_reviewed": len(diff_files), @@ -2201,11 +2999,14 @@ def handle_stop_hook(input_data): "review_ms": review_ms, "fire_index": fire_index, **({"api_error": llm._last_call_claude_http_error} if llm._last_call_claude_http_error is not None else {}), - **({"diff_truncated": llm._last_review_truncated_bytes} - if llm._last_review_truncated_bytes else {}), + **_stop_diff_truncated(), **v2_metrics, - }) - sys.exit(0) + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), + }, **wake) + sys.exit(2 if wake else 0) _SDK_BOOTSTRAP_THROTTLE = os.path.join(_resolve_state_dir(), ".sdk_bootstrap_spawned") @@ -2223,19 +3024,22 @@ def _maybe_bootstrap_agent_sdk_async(): is idempotent and O_EXCL-locked, so concurrent/repeat spawns are safe; the throttle file only avoids spawning dozens of subprocesses during the build window. No-ops in ~10ms on local installs (SDK already - importable). + importable, or already installed under the state dir, which is not on + sys.path here) and when the environment turns the LLM reviews off. """ try: import importlib.util if importlib.util.find_spec("claude_agent_sdk") is not None: return + if llm_reviews_switched_off() or agent_sdk_installed(_resolve_state_dir()): + return import time as _t try: if _t.time() - os.path.getmtime(_SDK_BOOTSTRAP_THROTTLE) < 300: return except OSError: pass - os.makedirs(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE), exist_ok=True) + make_state_dir(os.path.dirname(_SDK_BOOTSTRAP_THROTTLE)) # Touch the throttle BEFORE spawning so a burst of PostToolUse # fires in the same second don't each spawn a subprocess. open(_SDK_BOOTSTRAP_THROTTLE, "w").close() @@ -2253,6 +3057,7 @@ def main(): """Main hook function.""" debug_log(f"Hook called with args: {sys.argv}") apply_safe_git_env() + remove_copies_on_termination() # Master kill switch — honors ENABLE_SECURITY_REMINDER=0 (legacy) and # SECURITY_GUIDANCE_DISABLE=1 (clearer name, no double negative). Emit @@ -2276,6 +3081,7 @@ def main(): sys.exit(0) session_id = input_data.get("session_id", "default") + _USAGE_CONTEXT["session_id"] = re.sub(r"[^A-Za-z0-9_.-]", "_", str(session_id))[:80] tool_name = input_data.get("tool_name", "") tool_input = input_data.get("tool_input", {}) hook_event_name = input_data.get("hook_event_name", "") @@ -2307,11 +3113,15 @@ def main(): # Handle PostToolUse[Bash] — commit review or push sweep (asyncRewake). # - # hooks.json has two `if` configs under the Bash matcher (`git commit:*` - # and `git push:*`). CC evaluates each `if` independently and spawns this + # hooks.json has three `if` configs under the Bash matcher (`git*commit*`, + # `git*push*` and `gt *`), kept to one per kind because CC runs EVERY + # entry when it cannot parse the command (loops, some substitutions): one + # entry per spelling meant one python per entry on those calls. CC + # evaluates each `if` independently and spawns this # script ONCE PER MATCH — so `git commit -m x && git push` spawns python # twice with the same command string and the same tool_use_id. The python - # cannot tell which `if` fired it. + # cannot tell which `if` fired it, which is also why the three entries + # share one rewakeMessage. # # Routing therefore MUST check commit FIRST so that compound commit+push # commands continue to hit commit-review (the pre-existing behaviour) on @@ -2329,12 +3139,27 @@ def main(): if tool_name == "Bash" and hook_event_name == "PostToolUse": cmd = (input_data.get("tool_input") or {}).get("command", "") or "" if not (_GIT_COMMIT_RE.search(cmd) or _GIT_PUSH_RE.search(cmd)): + # Measurement only: this start matched no commit or push. Count + # it, and say whether a plain text check could have told so before + # Python. Both values carry the sample weight, so they sum to + # estimates of all such starts. + if _unmatched_bash_sampled(input_data) and not portable_output(): + skip = 0 if _shell_precheck_passes(raw_input) else _UNMATCHED_BASH_SAMPLE + emit_metrics({"bash_no_match": _UNMATCHED_BASH_SAMPLE, "precheck_skip": skip}) return + if not _shell_precheck_passes(raw_input): + # The text check would have dropped a command that is reviewed. + # Rides on whichever row this start emits; nothing is skipped. + global _precheck_miss + _precheck_miss = True if not _claim_bash_hook_once(input_data): # Another spawn for this same tool_use_id already claimed the # work (compound matched multiple `if` configs). Emit a single # metric so telemetry can count how often the de-dupe kicks in. - print(json.dumps({"metrics": {"bash_hook_dedup": True}}), flush=True) + dedup = {"bash_hook_dedup": True} + if _precheck_miss and not portable_output(): + dedup = {"pv": _PV, "precheck_miss": 1, **dedup} + _write_hook_output({"metrics": dedup}) sys.exit(0) if _GIT_COMMIT_RE.search(cmd): handle_commit_review_posttooluse(input_data) @@ -2355,7 +3180,8 @@ def main(): record_touched_path(session_id, file_path) - content = extract_content_from_input(tool_name, tool_input) + content = extract_content_from_input( + tool_name, tool_input, input_data.get("tool_response")) all_guidance = [] raw_pattern_matches = [] @@ -2395,30 +3221,32 @@ def main(): # rule_id: RuleId of the first raw match (values stay small/enumerable in telemetry) # rule_mask: bitmask of ALL raw matches — POPCOUNT gives raw hit count, # (mask >> N) & 1 tests for a specific rule + output = {} if raw_pattern_matches: raw_names = [r for r, _ in raw_pattern_matches] - output = {"metrics": { + output["metrics"] = { "pattern_hits": len(all_guidance), # User-defined patterns (rule_name="user:*") have no static # RuleId; emit -1 so the metrics pipeline can distinguish. "rule_id": int(_RULE_NAME_TO_ID.get(raw_names[0], -1)), "rule_mask": rule_names_to_mask(raw_names), **({"pv": _PV} if _PV else {}), - }} - if all_guidance: - output["hookSpecificOutput"] = { - "hookEventName": "PostToolUse", - "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), - } - print(json.dumps(output)) - elif all_guidance: - # Defensive: pattern rules disabled but guidance somehow set (shouldn't happen) - print(json.dumps({ - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), - } - })) + **_LAUNCHER_METRICS, + } + if all_guidance: + output["hookSpecificOutput"] = { + "hookEventName": "PostToolUse", + "additionalContext": PROVENANCE_TAG + "\n\n" + "\n\n".join(all_guidance), + } + # The LLM reviews are on but can't run: say so. + if (ENABLE_CODE_SECURITY_REVIEW and not HAS_API_CREDENTIALS + and (ENABLE_STOP_REVIEW or COMMIT_REVIEW_ENABLED + or PUSH_SWEEP_ENABLED)): + notice = _no_credentials_notice(file_path, session_id) + if notice: + output["systemMessage"] = notice + if output: + _write_hook_output(output) sys.exit(0) |
