diff options
| author | Claude <noreply@anthropic.com> | 2026-11-05 00:55:20 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-05 00:55:20 +0000 |
| commit | 94aad60c27bde35441c9b05c515f74fe67e10837 (patch) | |
| tree | b60b6d71987457d8b4f4d00daa562288f37d27ce /plugins/security-guidance/hooks | |
| parent | fa4eb54397ee2faccb6940512a19c017cb1337f3 (diff) | |
Merged candidate for security-guidance 2.0.18 with platform tests (6999 update)mhegazy/sg2018batch
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 145 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 159 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/ensure_agent_sdk.py | 156 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/extensibility.py | 29 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 229 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 295 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 325 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/session_state.py | 21 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/sg-python.sh | 155 |
9 files changed, 1257 insertions, 257 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index 28b189a4..99607e4a 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -9,9 +9,17 @@ import glob import json import os import re +import stat +import sys import threading from datetime import datetime +if os.name == "nt": + # Unless this variable exists, Windows looks for a program that is started + # by name in the working directory before PATH. + os.environ.setdefault("NoDefaultCurrentDirectoryInExePath", "1") + + def state_dir(): """Return the absolute path of the plugin's state directory. @@ -42,6 +50,26 @@ def state_dir(): return os.path.abspath(os.path.expanduser(d)) +def make_state_dir(d=None): + """Create the state dir (or `d`) with access for its user alone, and + narrow the default one to that if it is already there, so a umask such as + 002 does not leave the reviewer's venv, logs and session state open to the + rest of a shared group. A folder named by SECURITY_WARNINGS_STATE_DIR + that already exists is the user's to set. Raises OSError like os.makedirs.""" + if d is None: + d = state_dir() + os.makedirs(d, mode=0o700, exist_ok=True) + if (os.name != "nt" and not os.environ.get("SECURITY_WARNINGS_STATE_DIR", "").strip() + and os.path.abspath(d) == state_dir()): + try: + st = os.lstat(d) + if stat.S_ISDIR(st.st_mode) and st.st_uid == os.getuid() and st.st_mode & 0o077: + os.chmod(d, 0o700) + except OSError: + pass + return d + + def llm_reviews_switched_off(): """True when the environment turns off every review that calls a model: the kill switch (SECURITY_GUIDANCE_DISABLE=1 / ENABLE_SECURITY_REMINDER=0), @@ -212,7 +240,7 @@ _USAGE = { # reported it manually. "http_err_last": 0, # most recent HTTP error code this invocation "http_err_count": 0, # total HTTP errors (4xx + 5xx + network) - "net_err": 0, # why the last call got no HTTP response, 0 if it got one + "net_err": 0, # why the deciding call got no HTTP response, 0 if it got one # For the usage log line only: model ids as recorded (the requested alias # on the Agent SDK path), and whether any call had no price-table entry. "models": [], @@ -308,7 +336,9 @@ def _record_net_error(code): raises outside its own error type (a default TLS context that cannot be built, a connection closed before the reply) has no `api_error` at all. Emitted as `net_err` on the row of a hook whose last call failed this - way; a later call clears it.""" + way; a later call clears it, and so does a call that gets through beside + it (a second probe, the other leg of a dual review, the agentic run that + wins a race).""" try: c = int(code) except (TypeError, ValueError): @@ -378,6 +408,117 @@ def launcher_probe_metrics(): return {"launcher_probe_ms": min(total, cap), "launcher_probe_max_ms": min(slowest, cap)} +def launcher_direct_metric(): + """`launcher_direct` when sg-python.sh ran this hook with the interpreter + behind a packaged Windows alias instead of the alias: 1 from the path it + remembered (one process for the hook), 2 when it had just worked that + path out. Read once, like the probe timings. + """ + how = os.environ.pop("SG_LAUNCHER_DIRECT", "") + return {"launcher_direct": int(how)} if how in ("1", "2") else {} + + +# Reparse tags that redirect every open below them: symbolic links and +# junctions. App execution aliases (the entries under WindowsApps) carry +# another tag and are not counted. +_SYMLINK_TAG, _MOUNT_POINT_TAG = 0xA000000C, 0xA0000003 + + +def _is_link(path, st, readlink): + """True iff `path` (with lstat result `st`) is a symbolic link or a + junction, None when that cannot be told (Python older than 3.8 has no + reparse tag). A volume mounted at a folder has the junction tag too; its + target is the bare volume name.""" + if not getattr(st, "st_file_attributes", 0) & 0x400: # FILE_ATTRIBUTE_REPARSE_POINT + return False + tag = getattr(st, "st_reparse_tag", None) + if tag is None: + return None + if tag == _MOUNT_POINT_TAG: + try: + target = readlink(path).lstrip("\\?").rstrip("\\").lower() + except (OSError, ValueError, NotImplementedError): + return True + return not (target.startswith("volume{") and target.endswith("}")) + return tag == _SYMLINK_TAG + + +def interp_reparse_metric(executable=None, base_prefix=None, environ=None, platform=None, + lstat=None, readlink=None): + """`interp_reparse`, on Windows: whether the interpreter running this + hook is reached through a symbolic link or junction. Bits: + + 1 the path of the executable goes through one + 2 the path of the standard library (sys.base_prefix) goes through one + 4 such a path, as spelled, is under the user's AppData folders (a + uv-managed Python, for one) + 8 one of the two paths could not be checked + + 0 is sent too, so a Windows row without the key is a row that lost it, + not a "no". Measurement only, on the SessionStart row. It sizes how many + sessions start Python through such a link: inside the packaged Claude + Desktop app, Windows leaks kernel memory on every file opened that way, + and each hook starts an interpreter. See anthropics/claude-code#96870. + + No process is started: one lstat per folder on the two paths, up to the + first link. Where the link points is not followed, and an 8.3 short name + on one side reads as "not under AppData" (bit 4 missing, 1 and 2 right). + The plugin's own folders are not looked at. + + The arguments stand in for the interpreter and the system in tests. + """ + if (platform or sys.platform) != "win32": + return {} + executable = sys.executable if executable is None else executable + base_prefix = getattr(sys, "base_prefix", "") if base_prefix is None else base_prefix + environ = os.environ if environ is None else environ + lstat = lstat or os.lstat + readlink = readlink or os.readlink + + def spelled(p): + # For comparing only: lower case, no \\?\ prefix. + p = os.path.normcase(p) + return p[4:] if p.startswith("\\\\?\\") and not p.startswith("\\\\?\\unc\\") else p + + value = 0 + roots = [] + for name in ("APPDATA", "LOCALAPPDATA"): + try: + root = environ.get(name) + if root: + roots.append(spelled(os.path.abspath(root)).rstrip("\\/")) + except Exception: + pass + checked = {} + for bit, start in ((1, executable), (2, base_prefix)): + try: + if not start: + continue + p = start = os.path.abspath(start) + linked = False + while not linked: + parent = os.path.dirname(p) + if parent == p: + break + if p not in checked: + try: + checked[p] = _is_link(p, lstat(p), readlink) + except FileNotFoundError: + checked[p] = False + if checked[p] is None: + value |= 8 + linked = bool(checked[p]) + p = parent + if linked: + value |= bit + here = spelled(start) + if any(here == r or here.startswith(r + os.sep) for r in roots): + value |= 4 + except Exception: + value |= 8 + return {"interp_reparse": value} + + def _usage_metrics(): """Snapshot the accumulator as metric keys. Returns {} when no API calls AND no HTTP errors were made so skip-path emits don't burn key budget. diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 9ba40385..34655335 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -13,11 +13,12 @@ import sys import time from _base import debug_log, portable_output, _PV +import gitutil from gitutil import ( GIT_CMD, _git_dir, _git_toplevel, _git_status_porcelain, _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, - index_entry_count, + _secret_rename_origins, index_entry_count, ) from session_state import with_locked_state from extensibility import _same_dir @@ -319,7 +320,7 @@ def get_baseline_file_content(session_id, file_path, cwd): # How the last capture_git_baseline call got its SHA: 0 a real snapshot, -# 1 `stash create` failed and HEAD was returned, 2 no index copy and HEAD was +# 1 the snapshot failed and HEAD was returned, 2 no index copy and HEAD was # returned. With 1 or 2 the next Stop review cannot tell the turn's changes # from uncommitted work that was already there. Stored with baseline_sha. # Telemetry only. @@ -328,29 +329,110 @@ last_baseline_fail = 0 last_index_entries = None +# Who the snapshot commit is made by. Set on every commit-tree call, so the +# user's own name never appears on a commit they did not make and a repo with +# no identity configured still works. The commit object does land in +# `.git/objects`, but nothing refers to it, like the one `git stash create` +# used to make here: it is prunable from the moment it is written. +_SNAPSHOT_IDENT = { + "GIT_AUTHOR_NAME": "security-guidance", "GIT_AUTHOR_EMAIL": "security-guidance@localhost", + "GIT_COMMITTER_NAME": "security-guidance", "GIT_COMMITTER_EMAIL": "security-guidance@localhost", +} + +# The whole snapshot, not one command: `stash create` was capped at 15 s and a +# per-command cap would let a slow filesystem hold the prompt for far longer. +_SNAPSHOT_BUDGET_S = 15 + + +def _snapshot_commit(cwd, env, head_tree): + """A commit of every tracked change, on the index copy `env` names. + + Returns its SHA, "" when nothing tracked has changed (so the caller uses + HEAD, `head_tree` being HEAD's tree), or None when git refused or the + time budget ran out. + + No `--missing-ok`: git counts a partial clone's promisor blobs as + present, so write-tree neither fetches nor fails on one, and the + existence check it would turn off is worth keeping. + """ + deadline = time.monotonic() + _SNAPSHOT_BUDGET_S + + def run(args, extra=None): + left = deadline - time.monotonic() + if left <= 0: + raise subprocess.TimeoutExpired(args, _SNAPSHOT_BUDGET_S) + return subprocess.run( + [*GIT_CMD, *args], cwd=cwd, capture_output=True, timeout=left, + env={**env, **(extra or {})}, + ) + + # No pathspec: `add -u` has staged the whole work tree, whatever directory + # of it `cwd` is, since git 2.0. `-- :/` would say the same but fails + # outright under a user's GIT_LITERAL_PATHSPECS. + add = run(["add", "-u"]) + if add.returncode != 0: + debug_log(f"Snapshot: add -u failed: {_stderr_of(add)}") + return None + tree = run(["write-tree"]) + sha = (tree.stdout or b"").decode("utf-8", errors="replace").strip() + if tree.returncode != 0 or not sha: + debug_log(f"Snapshot: write-tree failed: {_stderr_of(tree)}") + return None + if sha == head_tree: + return "" + if gitutil.last_dropped_gitlinks: + # A nested repository's entry is gone from the index copy, so the + # tree cannot equal HEAD's even on a clean work tree. Ask whether + # anything but those entries differs, rather than writing a commit + # object on every prompt in a repo with submodules. + same = run(["diff-tree", "--quiet", "--ignore-submodules=all", head_tree, sha]) + if same.returncode == 0: + return "" + commit = run(["-c", "commit.gpgsign=false", "commit-tree", sha, "-p", "HEAD", + "-m", "security-guidance turn baseline"], _SNAPSHOT_IDENT) + out = (commit.stdout or b"").decode("utf-8", errors="replace").strip() + if commit.returncode != 0 or not out: + debug_log(f"Snapshot: commit-tree failed: {_stderr_of(commit)}") + return None + return out + + +def _stderr_of(result): + return (result.stderr or b"").decode("utf-8", errors="replace").strip()[:200] + + def capture_git_baseline(cwd): """ Capture a git ref representing the current working tree state. - Uses `git stash create` which creates a commit object for the current state - (HEAD + uncommitted changes) without modifying the stash list or working tree. + Builds a commit object for the current state (HEAD + uncommitted changes) + without touching the stash list or the working tree: `add -u` stages every + tracked change into a throwaway index copy, `write-tree` turns that into a + tree, and `commit-tree` hangs it off HEAD. Falls back to HEAD if the working tree is clean. Returns the SHA string, or None if not in a git repo or if the repo has no commits. - `stash create` runs on a throwaway copy of the index (GIT_INDEX_FILE), so - its `index.lock` and `index.stash.<pid>` files land next to the copy, not - in `.git`: it cannot collide with a concurrent git command, and a timeout - kill cannot leave a lock that blocks the user's next one. - GIT_OPTIONAL_LOCKS does not cover stash. Copying the real index without a - lock is safe: git replaces it by atomic rename. - - NOTE: `git stash create` does NOT capture untracked files. UPS pairs this + This was `git stash create`, which does the same thing in one command but + checks the work tree on a single thread, while `add -u` uses git's index + preload (one thread per 500 entries, up to 20). On a filesystem where each + file status is slow — a WSL repository on a Windows drive, a network mount + — that is the whole cost of the prompt: see #6854, where `stash create` + took 4 s on 1,424 files and never finished on 10,000. + + The commands run on a throwaway copy of the index (GIT_INDEX_FILE), so + their `index.lock` lands next to the copy, not in `.git`: they cannot + collide with a concurrent git command, and a timeout kill cannot leave a + lock that blocks the user's next one. GIT_OPTIONAL_LOCKS does not cover + these. Copying the real index without a lock is safe: git replaces it by + atomic rename. + + NOTE: the snapshot does NOT capture untracked files. UPS pairs this SHA with a `_list_untracked()` snapshot stored as `untracked_at_baseline`, and `compute_v2_review_set` subtracts that set so pre-existing untracked files are not reviewed as Claude-authored. UPS takes no snapshot while the Stop review, its only reader, is switched off. """ # stdout is a SHA so text=True is safe on stdout, but a non-ASCII - # filename in `git stash create`'s STDERR warning (e.g. a worktree + # filename in git's STDERR warning (e.g. a worktree # with `Ávila_report.txt` triggers a quotePath/locale warning) would # trip the stderr reader thread on Windows cp1252. Decode both streams # leniently for symmetry with _list_untracked. See #2056. @@ -358,15 +440,19 @@ def capture_git_baseline(cwd): last_baseline_fail = 0 last_index_entries = None try: - # Check if HEAD exists (i.e., repo has at least one commit) + # HEAD's commit and its tree in one call: the commit is the answer + # for a clean tree, the tree is what the snapshot is compared with. + # A failure here means the repo has no commits — skip the review + # rather than create commits in the user's repo. head_check = subprocess.run( - [*GIT_CMD, "rev-parse", "HEAD"], + [*GIT_CMD, "rev-parse", "HEAD", "HEAD^{tree}"], cwd=cwd, capture_output=True, timeout=5 ) - if head_check.returncode != 0: - # No commits yet — skip review rather than creating commits in the user's repo + head_out = (head_check.stdout or b"").decode("utf-8", errors="replace").split() + if head_check.returncode != 0 or len(head_out) != 2: debug_log("No commits in repo, skipping baseline capture") return None + head_sha, head_tree = head_out sha = "" # untracked_paths=[]: a plain copy of the index, no `add -N` pass. @@ -375,25 +461,14 @@ def capture_git_baseline(cwd): # back to HEAD. if env is not None: last_index_entries = index_entry_count(env["GIT_INDEX_FILE"]) - result = subprocess.run( - [*GIT_CMD, "stash", "create"], - cwd=cwd, capture_output=True, timeout=15, env=env - ) - sha = (result.stdout or b"").decode("utf-8", errors="replace").strip() - if not sha and result.returncode != 0: + sha = _snapshot_commit(cwd, env, head_tree) + if sha is None: last_baseline_fail = 1 + sha = "" else: last_baseline_fail = 2 - if sha: - return sha - - # Working tree is clean — stash create returns empty. Use HEAD. - result = subprocess.run( - [*GIT_CMD, "rev-parse", "HEAD"], - cwd=cwd, capture_output=True, timeout=5 - ) - sha = (result.stdout or b"").decode("utf-8", errors="replace").strip() - return sha if sha else None + # No snapshot: nothing tracked has changed, or it could not be taken. + return sha or head_sha except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: debug_log(f"Failed to capture git baseline: {e}") return None @@ -997,12 +1072,12 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel review_set = (files dirty vs current HEAD, plus files committed this turn when HEAD advanced linearly) ∩ (files whose content differs from the - pre-turn stash baseline). The first term is immune to checkout/pull + pre-turn baseline). The first term is immune to checkout/pull ballooning; the second filters out the user's untouched pre-turn WIP. Falls back to dirty_now alone when no baseline is available. untracked_at_baseline: {repo-root-relative path: mtime_ns} captured at - UPS. `git stash create` doesn't include untracked files, so without this + UPS. The baseline snapshot doesn't include untracked files, so without this snapshot a pre-existing untracked file looks "new since baseline" forever. A file is excluded only if it was untracked at baseline AND its mtime is unchanged — an in-place edit during the turn is still reviewed. @@ -1073,11 +1148,11 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel dirty_now |= _git_name_only(repo, f"{head_at_capture}..HEAD") or set() diff_base = head_at_capture - # changed_since: tracked files vs the stash baseline (no `add -N` — the - # stash never contained untracked files anyway), then union with + # changed_since: tracked files vs the turn baseline (no `add -N` — the + # baseline never contained untracked files anyway), then union with # currently-untracked. The previous `include_untracked=True` arm cost a # full `git add -N .` (slow in large repos) per call to surface - # untracked files in the diff output — but `git diff <stash>` already + # untracked files in the diff output — but `git diff <baseline>` already # lists them as "only in worktree" without that, and we have the explicit # set from status regardless. if baseline_sha: @@ -1087,9 +1162,13 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel else: changed_since = None # changed_since is None on missing baseline OR on git error (e.g. the - # dangling stash SHA was pruned). Either way, don't intersect with ∅ — + # dangling baseline SHA was pruned). Either way, don't intersect with ∅ — # that would silently zero the review set. Fall back to dirty_now. review_set = (dirty_now & changed_since) if changed_since is not None else dirty_now + # Kept beside its new name so that the content diff pairs the two. + secret_origins = { + old for new, old in _secret_rename_origins.items() if new in review_set} + review_set = review_set | secret_origins review_paths = [os.path.join(repo, p) for p in sorted(review_set)] untracked_in_review = sorted(new_untracked & review_set) @@ -1101,4 +1180,6 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel # Only emit when nonzero to stay under the 10-key telemetry cap. if preexisting_unchanged: metrics["preexisting_untracked_excluded"] = len(preexisting_unchanged) + if secret_origins: + metrics["secret_renamed"] = len(secret_origins) return review_paths, diff_base, repo, untracked_in_review, metrics diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index d3aaf96b..30119f8c 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -28,10 +28,11 @@ from pathlib import Path # here to match the existing local name (state_dir was already a local var in # main() and _maybe_emit_user_notice). from _base import ( - launcher_probe_metrics, portable_output, state_dir as _resolve_state_dir, + interp_reparse_metric, launcher_direct_metric, launcher_probe_metrics, portable_output, + state_dir as _resolve_state_dir, write_hook_output, ) -from _base import llm_reviews_switched_off +from _base import llm_reviews_switched_off, make_state_dir def _spawn_cwd() -> str: @@ -46,8 +47,7 @@ def _spawn_cwd() -> str: """ d = _resolve_state_dir() try: - os.makedirs(d, exist_ok=True) - return d + return make_state_dir(d) except OSError: return str(Path(__file__).resolve().parent.parent) @@ -77,6 +77,8 @@ SKIP_COOLDOWN = 9 # a recent build was signal-killed (memory pressure) — no # repro confirmed the dominant Linux BUILD_FAILED is a # SIGKILL/SIGSEGV of the memory-heavy venv+pip subprocess # (rc<0, empty streams). See #2154 follow-up. + # Also, for a shorter time, after a pip install ran out + # of time (sdk_timeout_cooldown says which). See #6979. SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would # load the SDK (kill switch included), so nothing is # installed. See #5331. @@ -86,6 +88,14 @@ SKIP_REVIEWS_OFF = 10 # the environment turns off every review that would # session). Keyed by marker mtime. SIGNAL_KILL_COOLDOWN_SEC = 24 * 3600 +# How long to skip rebuilds after a pip install ran out of time. On a +# connection too slow to fetch the SDK wheel inside the limit, every attempt +# downloads most of the wheel and throws it away, and attempts come at every +# SessionStart and every 5 minutes from the tool hooks. Shorter than the +# signal-kill window because a slow or stalled connection is often temporary. +# See #6979. +PIP_TIMEOUT_COOLDOWN_SEC = 3600 + # Phase + err-kind integer encoding for sdk_bootstrap_phase / sdk_bootstrap_err. # @@ -241,23 +251,37 @@ def _is_signal_kill(returncode) -> bool: return returncode < 0 or returncode in (134, 137, 139) -def _cooldown_remaining(state_dir) -> float: - """Seconds left in the signal-kill cooldown (0 if none/expired). Reads the - marker's mtime; a missing/unreadable marker means not in cooldown.""" - marker = Path(state_dir) / "agent-sdk-venv.cooldown" +_SIGNAL_KILL_MARKER = "agent-sdk-venv.cooldown" +_PIP_TIMEOUT_MARKER = "agent-sdk-venv.timeout" + + +def _marker_remaining(state_dir, name, window) -> float: + """Seconds left of the `window` that started at the marker's mtime; a + missing/unreadable marker means not in cooldown.""" try: - age = time.time() - marker.stat().st_mtime + age = time.time() - (Path(state_dir) / name).stat().st_mtime except OSError: return 0.0 - return max(0.0, SIGNAL_KILL_COOLDOWN_SEC - age) + # A marker stamped in the future (clock set back since) counts as fresh. + return min(float(window), max(0.0, window - age)) + + +def _cooldown_remaining(state_dir) -> float: + """Seconds left in the signal-kill cooldown (0 if none/expired).""" + return _marker_remaining(state_dir, _SIGNAL_KILL_MARKER, SIGNAL_KILL_COOLDOWN_SEC) + +def _timeout_cooldown_remaining(state_dir) -> float: + """Seconds left in the pip-timeout cooldown (0 if none/expired).""" + return _marker_remaining(state_dir, _PIP_TIMEOUT_MARKER, PIP_TIMEOUT_COOLDOWN_SEC) -def _write_cooldown(state_dir) -> None: - """Start/refresh the signal-kill cooldown so we stop re-attempting a build - that keeps getting killed every session. Best-effort.""" + +def _write_cooldown(state_dir, name=_SIGNAL_KILL_MARKER) -> None: + """Start/refresh a cooldown (the signal-kill one unless named) so we stop + re-attempting a build that keeps failing the same way. Best-effort.""" try: - Path(state_dir).mkdir(parents=True, exist_ok=True) - (Path(state_dir) / "agent-sdk-venv.cooldown").write_text( + make_state_dir(str(state_dir)) + (Path(state_dir) / name).write_text( time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())) except OSError: pass @@ -429,6 +453,8 @@ _SDK_IMPORT_PROBE = ( # Set by main() when the venv's probe exited with _PROBE_EMPTIED. _venv_was_emptied = False +# Set by main() when it skipped the build for the pip-timeout cooldown. +_skipped_for_pip_timeout = False def _target_dir(state_dir) -> Path: @@ -455,6 +481,63 @@ def _target_sdk_importable(state_dir) -> bool: return False +# pip keeps every wheel it downloads in a `pip-unpack-*` folder under the temp +# dir and removes it only when it exits normally. An install killed at the +# timeout (or by the OOM killer) left those folders in the system temp dir, +# one attempt after another. See #6979. So pip gets a temp folder of its own +# under the state dir: removed when the attempt ends, however it ends, and +# swept on a later run when the bootstrap itself was killed first. +_PIP_TIMEOUT_SEC = 120 +# Older than any install can be: the folder of a bootstrap that was killed. +_PIP_TEMP_STALE_SEC = 15 * 60 + + +def _pip_temp_root(state_dir) -> Path: + return Path(state_dir) / "pip-tmp" + + +def _sweep_pip_temp(state_dir) -> None: + """Remove pip temp folders left by a bootstrap that was killed before it + could remove its own. Best-effort; a folder still in use is too young.""" + try: + entries = list(_pip_temp_root(state_dir).iterdir()) + except OSError: + return # the usual case: nothing was ever left + import shutil + now = time.time() + for entry in entries: + try: + if now - entry.stat().st_mtime > _PIP_TEMP_STALE_SEC: + shutil.rmtree(entry, ignore_errors=True) + except OSError: + pass + + +def _run_pip_install(cmd, state_dir): + """Run a `pip install` command under the timeout, with its temp files in + a folder of ours. Raises what subprocess.run(check=True) raises. Falls + back to the inherited temp dir when the folder can't be made.""" + import shutil + import tempfile + tmp = env = None + try: + root = _pip_temp_root(state_dir) + root.mkdir(parents=True, exist_ok=True) + tmp = tempfile.mkdtemp(dir=root) + # tempfile reads TMPDIR, TEMP, TMP in that order on every platform. + env = {**os.environ, "TMPDIR": tmp, "TEMP": tmp, "TMP": tmp} + except OSError: + pass + try: + return subprocess.run( + cmd, capture_output=True, timeout=_PIP_TIMEOUT_SEC, check=True, + cwd=_spawn_cwd(), env=env, + ) + finally: + if tmp is not None: + shutil.rmtree(tmp, ignore_errors=True) + + def _build_via_target(state_dir) -> tuple[int, str, str]: """Fallback install when `python -m venv` can't bootstrap pip (ensurepip missing — Debian python3-venv absent, or a python.org/pyenv build without @@ -468,12 +551,12 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: preference (ARM64 Windows cryptography).""" target = _target_dir(state_dir) try: - subprocess.run( + _run_pip_install( [sys.executable, "-m", "pip", "install", "--target", str(target), "--upgrade", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), + state_dir, ) return BUILT_TARGET, "", "" except subprocess.CalledProcessError as e: @@ -484,6 +567,7 @@ def _build_via_target(state_dir) -> tuple[int, str, str]: return BUILD_FAILED, "pip_target", f"signal_killed:{e.returncode}" return BUILD_FAILED, "pip_target", _pip_err_from_stderr(e.stderr) except subprocess.TimeoutExpired: + _write_cooldown(state_dir, _PIP_TIMEOUT_MARKER) return BUILD_FAILED, "pip_target", "subprocess_timeout" except Exception as e: errno = getattr(e, "errno", None) @@ -544,10 +628,16 @@ def _install_context_metrics(outcome, state_dir) -> dict: dependencies do not load there. See #5706. sdk_venv_emptied: the venv's SDK package directory had lost its files - and this run went on to rebuild it, whatever the outcome. See #6612.""" + and this run went on to rebuild it, whatever the outcome. See #6612. + + sdk_timeout_cooldown: this run skipped the build (SKIP_COOLDOWN) because + a pip install ran out of time, not because one was signal-killed. See + #6979.""" out = {} if _venv_was_emptied: out["sdk_venv_emptied"] = 1 + if _skipped_for_pip_timeout: + out["sdk_timeout_cooldown"] = 1 if outcome not in (NOOP_VENV, BUILT, BUILT_TARGET, NOOP_TARGET): return out try: @@ -593,8 +683,11 @@ def main() -> tuple[int, str, str]: err_phase / err_kind are non-empty only on BUILD_FAILED — they let telemetry split bootstrap failures by root cause. """ - global _venv_was_emptied + global _venv_was_emptied, _skipped_for_pip_timeout _venv_was_emptied = False + _skipped_for_pip_timeout = False + # Before any early return: nothing else ever clears the state dir. + _sweep_pip_temp(_resolve_state_dir()) # The SDK only serves the LLM reviews. With those switched off, or the # whole plugin (SECURITY_GUIDANCE_DISABLE=1), a venv of a few hundred MB # would be built for code that never runs, and the notice below would @@ -676,12 +769,16 @@ def main() -> tuple[int, str, str]: # system/venv/target still short-circuits above. if _cooldown_remaining(state_dir) > 0: return SKIP_COOLDOWN, "", "" + # Likewise after a pip install that ran out of time, for a shorter while. + if _timeout_cooldown_remaining(state_dir) > 0: + _skipped_for_pip_timeout = True + return SKIP_COOLDOWN, "", "" err_phase = "" err_kind = "" we_own_sentinel = False try: - state_dir.mkdir(parents=True, exist_ok=True) + make_state_dir(str(state_dir)) # O_EXCL makes the sentinel an atomic lock — if two SessionStarts # race past the exists() check above, only one creates it. try: @@ -712,11 +809,11 @@ def main() -> tuple[int, str, str]: # --no-cache-dir trims pip's peak memory (no cache read/write/unpack # buffering) — helps marginal low-memory machines get under the OOM # threshold that kills the dominant Linux builds (CCR repro). - subprocess.run( + _run_pip_install( [str(venv_py), "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--prefer-binary", "--no-cache-dir", "claude-agent-sdk"], - capture_output=True, timeout=120, check=True, cwd=_spawn_cwd(), + state_dir, ) return BUILT, "", "" except subprocess.CalledProcessError as e: @@ -814,6 +911,10 @@ def main() -> tuple[int, str, str]: return _build_via_target(state_dir) return BUILD_FAILED, err_phase, err_kind except subprocess.TimeoutExpired: + # Only the download is known to repeat; a slow `python -m venv` is + # more likely a busy machine, and the next attempt may be quicker. + if err_phase == "pip": + _write_cooldown(state_dir, _PIP_TIMEOUT_MARKER) return BUILD_FAILED, err_phase, "subprocess_timeout" except Exception as e: # Embed errno for OSError-family exceptions ("exc:OSError:28") so @@ -847,8 +948,9 @@ def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None: Currently only HOOK_PY_INCOMPATIBLE qualifies. BUILD_FAILED is intentionally excluded — it covers transient causes (network failure, - pip registry hiccup, in-flight rebuild) where the next session may - succeed and a permanent notice would mislead. + pip registry hiccup, in-flight rebuild, a download that ran out of + time) where a later session may succeed and a permanent notice would + mislead. """ if outcome != HOOK_PY_INCOMPATIBLE: return None @@ -857,7 +959,7 @@ def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None: marker = state_dir / f".agentic_unavailable_notice_v{pv or 0}" if marker.exists(): return None - state_dir.mkdir(parents=True, exist_ok=True) + make_state_dir(str(state_dir)) # Write timestamp + Python version so the marker is self-documenting # if a user goes looking. O_EXCL would be racier with no real win # (two concurrent SessionStarts both showing the notice once is fine). @@ -977,6 +1079,10 @@ if __name__ == "__main__": if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": metrics["launcher_fallback"] = 1 metrics.update(launcher_probe_metrics()) + metrics.update(launcher_direct_metric()) + # Last, so it is the first key a row over Claude Code's key cap (20, 10 + # in older versions) loses. + metrics.update(interp_reparse_metric()) response: dict[str, object] = {"metrics": metrics} # One-time user-visible notice when the agentic reviewer is dead on # arrival. Uses hookSpecificOutput.additionalContext (SessionStart's diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index ed332c99..d27e9173 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -30,6 +30,9 @@ Trust model: built-in ones. Reminder length is capped. - Custom regexes are validated at load for catastrophic-backtracking structure and skipped (with a debug log) if they look ReDoS-prone. + - A project file that is a link, or sits under a ``.claude`` that is one, is + skipped (with a debug log). User files may be links, as dotfile managers + make them. - Built-in patterns cannot be disabled. ``ENABLE_PATTERN_RULES=0`` disables all pattern checks; there is no per-rule kill switch in v1. """ @@ -125,13 +128,30 @@ def _config_paths(cwd: Optional[str], basename: str) -> List[Tuple[str, str]]: return paths +def _readable_config(path: str, cwd: Optional[str]) -> bool: + """Whether a config file may be read. A project file (`cwd` given) must be + a regular file at that very place: a link, or a `.claude` that is one, + would bring in text from wherever it points.""" + if cwd is None or not os.path.lexists(path): + return True + expected = os.path.join(os.path.realpath(cwd), os.path.relpath(path, cwd)) + real = os.path.realpath(path) + if os.path.normcase(real) == os.path.normcase(expected) and os.path.isfile(real): + return True + debug_log(f"extensibility: skipping {path}: a link, or not a regular file") + return False + + def _load_guidance(cwd: Optional[str]) -> str: parts = [] for label, path in _config_paths(cwd, GUIDANCE_BASENAME): + if not _readable_config(path, cwd if label.startswith("Project") else None): + continue try: with open(path, encoding="utf-8") as f: txt = f.read().strip() - except OSError: + except (OSError, UnicodeDecodeError) as e: + debug_log(f"extensibility: skipping {path}: {type(e).__name__}") continue if txt: parts.append(f"### {label} security guidance\n{txt}") @@ -148,9 +168,14 @@ def _load_guidance(cwd: Optional[str]) -> str: return combined +_GUIDANCE_END_TAG = re.compile(r"<(\s*/\s*project-security-guidance)", re.IGNORECASE) + + def _wrap_guidance(guidance: str) -> str: if not guidance: return "" + # The block ends at its own closing tag, not at one in the text it holds. + guidance = _GUIDANCE_END_TAG.sub(r"<\1", guidance) return ( "\n\n<project-security-guidance>\n" "The user has provided project-specific security guidance below. " @@ -178,6 +203,8 @@ def _load_user_patterns(cwd: Optional[str]) -> List[Dict[str, Any]]: # One unusable file is skipped on its own, so the rules from the # other locations still load. try: + if not _readable_config(candidate, cwd if label.startswith("Project") else None): + continue found = _rules_from_file(candidate, label) except Exception as e: debug_log(f"extensibility: skipping {candidate}: {type(e).__name__}: {e}") diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index ec51e3c6..4c363ef4 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -27,8 +27,39 @@ import time from _base import debug_log +def _git_program(windows=os.name == "nt"): + """How to start git. On Windows a bare name is looked up in the process's + working directory before PATH, and the hooks run in the project, so a + `git.exe` there would start in place of the installed one. Name the first + git.exe on PATH instead, leaving out relative entries, the working + directory, and folders inside the project (unless the project holds the + home folder, and with it the user's own tools). With none, a path that + does not exist: git is reported missing, as it would be anywhere else.""" + if not windows: + return "git" + def norm(p): + return os.path.normcase(os.path.normpath(p)) + try: + cwd = norm(os.getcwd()) + except OSError: + cwd = "" + home = norm(os.path.expanduser("~")) + os.sep + roots = [norm(r) for r in (cwd, os.environ.get("CLAUDE_PROJECT_DIR")) if r] + roots = [r.rstrip(os.sep) + os.sep for r in roots if not home.startswith(r.rstrip(os.sep) + os.sep)] + for d in os.environ.get("PATH", "").split(os.pathsep): + d = d.strip().strip('"') + if not d or not os.path.isabs(d) or norm(d) == cwd: + continue + if any((norm(d) + os.sep).startswith(r) for r in roots): + continue + path = os.path.join(d, "git.exe") + if os.path.isfile(path): + return path + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "git.exe") + + GIT_CMD = [ - "git", + _git_program(), "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", # core.quotePath=false: emit raw UTF-8 in path-emitting commands instead @@ -62,6 +93,10 @@ GIT_CMD = [ # _drop_gitlinks for the commands that take no such setting. "-c", "diff.ignoreSubmodules=all", "-c", "diff.submodule=short", + # `git log` and `git show` print commit metadata for the hooks to parse. + # With log.showSignature set they would also verify each signed commit, + # adding lines to the output and starting the program gpg.program names. + "-c", "log.showSignature=false", ] # diff.ignoreSubmodules is a default that the repository's own settings for @@ -74,6 +109,7 @@ SAFE_GIT_CONFIG = ( ("core.hooksPath", "/dev/null"), ("diff.ignoreSubmodules", "all"), ("diff.submodule", "short"), + ("log.showSignature", "false"), ) # The hook's git runs in the background beside the session's own git. Without @@ -295,12 +331,17 @@ _path_list_too_long = set() # A failed `git add --intent-to-add` during this hook run, for the Stop hook's # metrics: kind * 100000 + the paths the add was given. One number because a -# review row is near CC's key cap. A failed add leaves the new files out of the -# diff, so a turn that only added files looks like a turn with no changes; a -# timeout loses the whole diff. kind: 1 git could not write the empty blob to -# the object store, 2 any other git error, 3 timeout. A git that speaks another -# language counts as 2. -_add_failed = {"code": 0} +# review row is near CC's key cap. kind: 1 git could not write the empty blob +# to the object store and the retry failed too, 2 any other git error, 3 +# timeout, 4 the retry with a private object directory worked. A git that +# speaks another language reports a failed retry as 2. With 1 to 3 the new +# files are not in the diff, so a turn that only added files looks like a turn +# with no changes. `left_out` says so for the last get_git_diff alone: the code +# stays set through a fallback diff that worked. +_add_failed = {"code": 0, "left_out": False} + +# Next to an index copy: where a retried `git add -N` stores the empty blob. +_OBJECTS_DIR_SUFFIX = ".objects" def _too_many_args(e): @@ -398,8 +439,9 @@ def _owner_is_gone(name): def _sweep_stale_indexes(dirpath, uid): - """Delete index copies in `dirpath` that a killed run left behind. Only - regular files owned by `uid` (None: no ownership check) are touched. + """Delete index copies in `dirpath` that a killed run left behind, and + their private object directories. Only regular files and directories owned + by `uid` (None: no ownership check) are touched. A copy goes as soon as the hook that made it is gone: a killed hook can leave one per run, and index-sized files fill a disk long before the age @@ -422,12 +464,16 @@ def _sweep_stale_indexes(dirpath, uid): p = os.path.join(dirpath, name) try: st = os.lstat(p) - if not stat.S_ISREG(st.st_mode): + is_dir = stat.S_ISDIR(st.st_mode) and name.endswith(_OBJECTS_DIR_SUFFIX) + if not (is_dir or stat.S_ISREG(st.st_mode)): continue if uid is not None and st.st_uid != uid: continue if max(st.st_mtime, st.st_ctime) < cutoff or _owner_is_gone(name): - os.unlink(p) + if is_dir: + _remove_objects_dir(p) + else: + os.unlink(p) if time.monotonic() > deadline: return except OSError: @@ -531,6 +577,24 @@ def _copy_slot(tmpdir, index_bytes=0): os.close(held) +def _remove_objects_dir(path): + """Remove a private object directory. git writes objects read-only, which + stops Windows from deleting them.""" + import shutil + import stat + + def writable_then_retry(func, p, _exc): + # Not a link: chmod would follow it to whatever it points at. + if func in (os.unlink, os.rmdir) and not os.path.islink(p): + os.chmod(p, stat.S_IWRITE) + func(p) + + try: + shutil.rmtree(path, onerror=writable_then_retry) + except OSError: + pass + + def _remove_copy(tmp_index): """Remove an index copy and the files git wrote next to it.""" import glob @@ -539,6 +603,7 @@ def _remove_copy(tmp_index): os.unlink(p) except OSError: pass + _remove_objects_dir(tmp_index + _OBJECTS_DIR_SUFFIX) def remove_copies_on_termination(): @@ -597,6 +662,75 @@ def _hook_tmpdir(): def _note_add_failure(kind, paths): _add_failed["code"] = kind * 100000 + min(len(paths), 99999) + _add_failed["left_out"] = kind != 4 + + +def _env_with_private_objects(env, cwd, objects_dir): + """`env` for a git that writes objects to `objects_dir` and still reads + the repository's own, wherever git says they are (a linked worktree shares + them). A path holding the list separator is left out, since git would + split it; the add then fails only if it has to read an object.""" + out = {**env, "GIT_OBJECT_DIRECTORY": objects_dir} + try: + r = subprocess.run([*GIT_CMD, "rev-parse", "--git-path", "objects"], + cwd=cwd, capture_output=True, timeout=5, env=env) + except (subprocess.TimeoutExpired, OSError): + return out + own = os.path.join(cwd, os.fsdecode(r.stdout).strip()) + if r.returncode == 0 and os.pathsep not in own: + out["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = os.pathsep.join( + p for p in (own, env.get("GIT_ALTERNATE_OBJECT_DIRECTORIES")) if p) + return out + + +def _add_new_files(cwd, paths, env, tmp_index): + """`git add --intent-to-add` the untracked `paths` to the index copy `env` + names, so the diff shows them. The add has to store the empty blob, so a + user who cannot write the object store gets a second try that stores it in + a private directory next to the copy. Nothing needs that blob afterwards: + `git diff` reads these files from the work tree. `git stash create` would + fail on such an index, and only runs on a copy with nothing added. + + No stdout used here (only returncode matters), but text=True still spawns + reader threads that decode stderr — git error messages can reference + non-ASCII filenames and crash on cp1252. See #2099. Drop text=True so bytes + stay raw.""" + # The paths are file names, not patterns, for this git add only: an + # untracked file named `:(glob)**` must add only itself. git refuses that + # together with a glob or icase setting from the user's environment. + env = {k: v for k, v in env.items() + if k not in ("GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS")} + env["GIT_LITERAL_PATHSPECS"] = "1" + + def add(add_env): + results = _run_git_on_review_paths( + ["add", "--intent-to-add"], paths, timeout=10, cwd=cwd, env=add_env) + return next((r for r in results if r.returncode != 0), None) + + try: + failed = add(env) + except subprocess.TimeoutExpired: + # No retry: git is slow here, not refused. The diff goes on for the + # tracked files, so a timeout on every turn cannot stop their reviews. + _note_add_failure(3, paths) + return + if not failed: + return + debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") + # Whatever happens to the retry, the diff goes on for the tracked files. + try: + objects_dir = tmp_index + _OBJECTS_DIR_SUFFIX + os.mkdir(objects_dir, 0o700) + retry_failed = add(_env_with_private_objects(env, cwd, objects_dir)) + if retry_failed: + debug_log(f"git add -N retry failed: {retry_failed.stderr[:200].decode('utf-8', errors='replace')}") + except (subprocess.TimeoutExpired, OSError) as e: + debug_log(f"git add -N retry failed: {e}") + retry_failed = True + if retry_failed: + _note_add_failure(1 if b"empty blob" in failed.stderr else 2, paths) + else: + _note_add_failure(4, paths) @contextlib.contextmanager @@ -685,24 +819,7 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths): else: add_args = None if add_args: - # No stdout used here (only returncode matters), but text=True - # still spawns reader threads that decode stderr — git error - # messages can reference non-ASCII filenames and crash on - # cp1252. See #2099. Drop text=True so bytes stay raw. - try: - results = _run_git_on_review_paths( - ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd, - # The paths are file names, not patterns, for this git add - # only: an untracked file named `:(glob)**` must add only - # itself. - env={**env, "GIT_LITERAL_PATHSPECS": "1"}) - except subprocess.TimeoutExpired: - _note_add_failure(3, add_args) - raise - failed = next((r for r in results if r.returncode != 0), None) - if failed: - _note_add_failure(1 if b"empty blob" in failed.stderr else 2, add_args) - debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}") + _add_new_files(cwd, add_args, env, tmp_index) # A whole-tree add puts a nested repository back. if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index): yield None @@ -794,26 +911,33 @@ def _gitlink_paths(top, env): return found +# True when the last _drop_gitlinks call removed at least one gitlink, so the +# index copy and HEAD can no longer have the same tree even on a clean tree. +last_dropped_gitlinks = False + + def _drop_gitlinks(top, env, tmp_index): """Remove the gitlink (mode 160000) entry of every nested repository from the index copy that `env` names, never from the real index, before anything else runs on the copy. A gitlink marks a directory that is, or can be, another repository (see diff.ignoreSubmodules in GIT_CMD): `git stash create` takes no flag like IGNORE_SUBMODULES, and `git add` - reads the gitlinks its paths cover. An entry whose directory has no - `.git` stays: git starts nothing there, and without the entry an older - `git stash create` fails on the empty directory. `top` is the work - tree's top directory. Returns True on success, False on any failure; the - copy must not be used then.""" + reads the gitlinks its paths cover. Every gitlink goes, including one + whose directory has no `.git` now: whether git starts something there is + decided when git runs, not here. Without the entry, `git stash create` on + git older than 2.34 fails on a submodule that is not checked out, and the + baseline falls back to HEAD. `top` is the work tree's top directory. + Returns True on success, False on any failure; the copy must not be used + then.""" + global last_dropped_gitlinks + last_dropped_gitlinks = False try: if not _may_have_gitlinks(tmp_index): return True gitlinks = _gitlink_paths(top, env) if gitlinks is None: return False - top_b = os.fsencode(top) - nested = sorted(p for p in gitlinks - if os.path.lexists(os.path.join(top_b, p, b".git"))) + nested = sorted(gitlinks) if not nested: return True mtime_ns = os.stat(tmp_index).st_mtime_ns @@ -829,6 +953,7 @@ def _drop_gitlinks(top, env, tmp_index): return False # Keep the mtime the copy came with; see _copied_index. os.utime(tmp_index, ns=(mtime_ns, mtime_ns)) + last_dropped_gitlinks = True debug_log(f"gitlink entries (nested repositories) removed from the " f"index copy: {len(nested)}; their contents are not reviewed") return True @@ -1058,6 +1183,18 @@ def _git_reflog_recent_commits(repo_root, max_age_s=120, max_n=5): return fresh, stale +# New name -> secret-shaped old name, for the renames and copies git reported +# during this hook run. The Stop review limits its diff to a list of paths: +# with only the new name in it, git shows the secret's content as a new file, +# and the diff parsers cannot tell it came from a name they leave out. +_secret_rename_origins = {} + + +def _note_rename(old_path, new_path): + if _is_secret_shaped(old_path): + _secret_rename_origins[new_path] = old_path + + def _git_name_only(cwd, base, include_untracked=False): """Return the set of repo-root-relative paths that differ from `base`, or None if git failed (unresolvable ref, not a repo, timeout). Callers @@ -1077,7 +1214,7 @@ def _git_name_only(cwd, base, include_untracked=False): def _run(env): # core.quotePath=false comes from GIT_CMD globally (see definition). result = subprocess.run( - [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base], + [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-status", "-z", base], cwd=cwd, capture_output=True, timeout=30, env=env, ) @@ -1086,7 +1223,18 @@ def _git_name_only(cwd, base, include_untracked=False): debug_log(f"_git_name_only({base!r}) rc={result.returncode}: {stderr_str[:200]}") return None stdout = (result.stdout or b"").decode("utf-8", errors="replace") - return {p for p in stdout.split("\0") if p} + # Fields are `status\0path\0`, or `R<score>\0old\0new\0` for a rename + # or copy, which is listed by its new name only. + fields = stdout.split("\0") + names = set() + i = 0 + while i + 1 < len(fields): + if fields[i][:1] in ("R", "C") and i + 2 < len(fields): + _note_rename(fields[i + 1], fields[i + 2]) + i += 1 + names.add(fields[i + 1]) + i += 2 + return names try: # The diff only reads the index (diff.autoRefreshIndex is off in @@ -1147,6 +1295,8 @@ def _git_status_porcelain(cwd): # 2-char-status entry. if "R" in xy or "C" in xy: i += 1 + if i < len(entries): + _note_rename(entries[i], path) i += 1 return tracked, untracked except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: @@ -1453,6 +1603,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa MAX_FILE_DIFF_BYTES is cut down to its added lines. """ _path_list_too_long.clear() + _add_failed["left_out"] = False pathspec = _diff_pathspec(cwd, paths) if paths and not pathspec: # Caller restricted to specific paths but none are inside this repo diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 468d9e6d..ee9ad2be 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -17,6 +17,7 @@ Two reassignable globals here are read by handlers in ``_last_review_truncated_bytes``. Handlers reference them as ``llm.X`` (not via ``from``-import) so they observe reassignment. """ +import contextlib import hashlib import json import logging @@ -39,7 +40,7 @@ except ImportError: # a Python built without TLS import extensibility import review_api -from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs # noqa: F401 +from _base import debug_log, _record_usage, _record_http_error, _record_net_error, _clear_net_error, _PV, PROVENANCE_TAG, state_dir as _resolve_state_dir, agent_sdk_site_dirs, make_state_dir # noqa: F401 from session_state import load_state, with_locked_state from gitutil import git_config_env, SAFE_GIT_CONFIG @@ -195,10 +196,13 @@ def _anthropic_base_url() -> str: Honors ANTHROPIC_BASE_URL (the convention the Anthropic SDK and CC itself use) so customers behind an LLM gateway (LiteLLM, Bifrost, self-hosted Anthropic-compatible proxy) can route the plugin's reviews through their - gateway. Defaults to https://api.anthropic.com. Always returns a string - with no trailing slash so callers can safely append /v1/messages etc. + gateway. Defaults to https://api.anthropic.com, also when the variable is + set but blank, which is how the SDK and CC read it. Always returns a + string with no trailing slash so callers can safely append /v1/messages + etc. """ - return os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com").rstrip("/") + base = os.environ.get("ANTHROPIC_BASE_URL", "").strip() + return (base or "https://api.anthropic.com").rstrip("/") # ── Windows certificate store with an entry OpenSSL cannot read ────────── @@ -282,6 +286,10 @@ def _urlopen(request, timeout): return urllib.request.urlopen(request, timeout=timeout, context=_store_tls_context) +def _is_remote_session() -> bool: + return os.environ.get("CLAUDE_CODE_REMOTE", "").lower() in ("1", "true", "yes", "on") + + def _probe_anthropic(timeout: float = 5.0) -> bool: req = urllib.request.Request(_anthropic_base_url() + "/", method="HEAD") try: @@ -420,7 +428,7 @@ def ensure_anthropic_reachable() -> bool: global _anthropic_reachable if _anthropic_reachable is not None: return _anthropic_reachable - if os.environ.get("CLAUDE_CODE_REMOTE", "").lower() not in ("1", "true", "yes", "on"): + if not _is_remote_session(): _anthropic_reachable = True return True if _probe_anthropic(): @@ -429,7 +437,9 @@ def ensure_anthropic_reachable() -> bool: debug_log("Remote env: api.anthropic.com unreachable, stripping anthropic.com from NO_PROXY") _strip_anthropic_from_no_proxy() _anthropic_reachable = _probe_anthropic() - if not _anthropic_reachable: + if _anthropic_reachable: + _clear_net_error() # the first probe's failure; this one got through + else: debug_log("Remote env: api.anthropic.com still unreachable after NO_PROXY scrub") return _anthropic_reachable @@ -735,7 +745,7 @@ def _read_review_model_cache(path, endpoint_key, now): def _write_review_model_cache(path, endpoint_key, model, now): tmp = None try: - os.makedirs(os.path.dirname(path), exist_ok=True) + make_state_dir(os.path.dirname(path)) fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".review_model.") with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump({"endpoint": endpoint_key, "model": model, "at": now}, f) @@ -805,11 +815,12 @@ _gateway_check_unanswered = False # depend on the model, so the Sonnet attempt is not made after it. _gateway_review_timed_out = False +_WINDOWS = os.name == "nt" + def _user_cli_path() -> Optional[str]: - """The user's own `claude`: SG_AGENTIC_CLI_PATH if set ("" selects the - SDK's bundled CLI), else the first of the absolute paths below that - exists, else None.""" + """The user's own `claude`: SG_AGENTIC_CLI_PATH if set ("" names none), else + the first of the absolute paths below that exists, else None.""" cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") if cli_path is not None: return cli_path @@ -821,18 +832,71 @@ def _user_cli_path() -> Optional[str]: # user's (potentially attacker-supplied) repo, and Windows shutil.which # searches cwd first — a checked-in ./claude.exe would get spawned. # Absolute-path probes only. - for p in ( - os.environ.get("CLAUDE_CODE_EXECPATH"), - os.path.expanduser("~/.local/bin/claude"), - "/root/.local/bin/claude", - # Claude Code Remote container install path. - "/opt/claude-code/bin/claude", - ): + probes = [os.environ.get("CLAUDE_CODE_EXECPATH")] + if not _WINDOWS: + # Where Claude Code is installed on macOS and Linux. + probes += [ + os.path.expanduser("~/.local/bin/claude"), + "/root/.local/bin/claude", + # Claude Code Remote container install path. + "/opt/claude-code/bin/claude", + ] + for p in probes: if p and os.path.isfile(p): return p return None +def _windows_user_cli() -> Optional[str]: + """Windows: the full path of the user's claude.exe, from the native + installer's folder, else from PATH; None when neither has one. Skips any + folder that is not given as a full path, and the working directory and + project root, and any folder inside them (unless that root holds the home + folder, and with it the user's own tools).""" + skipped = [d for d in (os.getcwd(), os.environ.get("CLAUDE_PROJECT_DIR")) if d and os.path.isdir(d)] + home = os.path.expanduser("~") + real_home = os.path.normcase(os.path.realpath(home)).rstrip(os.sep) + os.sep + roots = [r.rstrip(os.sep) + os.sep for r in (os.path.normcase(os.path.realpath(d)) for d in skipped)] + roots = [r for r in roots if not real_home.startswith(r)] + home_bin = os.path.join(home, ".local", "bin") + for folder in [home_bin] + os.environ.get("PATH", "").split(os.pathsep): + folder = folder.strip().strip('"') + cli = os.path.join(folder, "claude.exe") + try: + real = os.path.normcase(os.path.realpath(folder)) + # A full path is one that abspath leaves as it is. + if (os.path.normcase(os.path.abspath(folder)) == os.path.normcase(os.path.normpath(folder)) + and os.path.isfile(cli) + and not any(os.path.samefile(folder, d) for d in skipped) + and not any(real.startswith(r) for r in roots)): + return cli + except OSError: + pass + return None + + +def _cli_for_sdk(cli_path: Optional[str]) -> Optional[str]: + """What to pass the Agent SDK as `cli_path`: a given one as it is. With none + given, the SDK chooses, except on Windows. There this names the CLI bundled + with the SDK, else the user's own, by its full path, and when neither exists + the bundled path anyway, so that the start fails.""" + if cli_path or not _WINDOWS: + return cli_path or None + # When the SDK module has no file, any full path at which nothing exists will do. + sdk_file = getattr(sys.modules.get("claude_agent_sdk"), "__file__", None) or __file__ + bundled = os.path.join(os.path.dirname(os.path.abspath(sdk_file)), "_bundled", "claude.exe") + if os.path.isfile(bundled): + return bundled + cli_path = _windows_user_cli() + if not cli_path: + debug_log("no Claude Code for the Agent SDK: none is bundled with it, and there is no claude.exe " + "in ~\\.local\\bin or on PATH outside this project (SG_AGENTIC_CLI_PATH can name one)") + return bundled + debug_log(f"the Agent SDK has no bundled Claude Code; using {cli_path}") + _tolerate_unknown_sdk_messages() + return cli_path + + def _tolerate_unknown_sdk_messages() -> None: """Make the SDK's message parser pass unknown message types through instead of raising: a CLI newer than the SDK emits types the SDK does not @@ -932,6 +996,14 @@ def can_review(session_id) -> bool: return HAS_API_CREDENTIALS or gateway_review_cli(session_id) is not None +def _forget_failed_call(): + """A review got its answer from another call running beside the one that + failed, so the row should not report that failure.""" + global _last_call_claude_http_error + _last_call_claude_http_error = None + _clear_net_error() + + def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, cli_path=None): """Single-turn SDK call as a substitute for the HTTP _call_claude path on @@ -980,7 +1052,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, if cli_path: _tolerate_unknown_sdk_messages() else: - cli_path = os.environ.get("SG_AGENTIC_CLI_PATH") or None + cli_path = _cli_for_sdk(os.environ.get("SG_AGENTIC_CLI_PATH") or None) default_model = default_review_model() chosen_model = model or default_model @@ -996,7 +1068,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, system_prompt=CLAUDE_CODE_SYSTEM_PROMPT, cli_path=cli_path, allowed_tools=[], - extra_args=_only_tools_args(), + extra_args={**_only_tools_args(), **_reviewer_session_args()}, setting_sources=[], max_turns=2, model=chosen_model, @@ -1023,9 +1095,8 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, _record_usage(getattr(msg, "usage", None) or {}, chosen_model, cost_usd=getattr(msg, "total_cost_usd", None)) elif getattr(msg, "subtype", None) == "api_retry": - data = getattr(msg, "data", None) - status = data.get("error_status") if isinstance(data, dict) else None - _retried_after.add(str(status) if isinstance(status, int) else "no response") + status = _api_retry_status(msg) + _retried_after.add(str(status) if status is not None else "no response") return structured # 60s ceiling: a single review request on a healthy 3P endpoint completes @@ -1323,6 +1394,7 @@ def _call_claude_dual_or(prompt, output_schema, *, bool_key: str, list_key: str, merged.append(item) elif item not in merged: merged.append(item) + _forget_failed_call() # one leg got through; the other may have failed return {bool_key: bool(merged) or bool((ra or {}).get(bool_key)) or bool((rb or {}).get(bool_key)), list_key: merged} @@ -1786,6 +1858,32 @@ def _send_sdk_logs_to_debug_log() -> None: sdk_logger.propagate = False +# Claude Code older than 2.0.63 exits at startup with "unknown option" when +# given --no-session-persistence. The flag is sent until an inner CLI +# refuses it. +_SESSION_FLAG = "no-session-persistence" +_send_session_flag = True + + +def _reviewer_session_args() -> Dict[str, Optional[str]]: + """Extra CLI flags for the SDK-spawned inner `claude`. + + Review runs are one-shot and never resumed, so by default the inner CLI + is told not to save them as session transcripts (they hold the full + review prompt, including diff hunks). SECURITY_GUIDANCE_PERSIST_SESSIONS=1 + keeps the transcripts, e.g. to debug a review. + """ + keep = os.environ.get("SECURITY_GUIDANCE_PERSIST_SESSIONS", "").strip().lower() + if not _send_session_flag or keep in ("1", "on", "true", "yes"): + return {} + return {_SESSION_FLAG: None} + + +def _names_session_flag(stderr_line: Any) -> bool: + text = str(stderr_line) + return _SESSION_FLAG in text and "unknown option" in text.lower() + + # The agentic reviewer reads a diff it must not trust, so it gets # file-reading tools and nothing else. _REVIEWER_TOOLS = ("Read", "Grep", "Glob") @@ -1820,22 +1918,57 @@ def _names_strict_mcp_flag(stderr_line: Any) -> bool: return "--strict-mcp-config" in str(stderr_line) +def _refused_flags(stderr_lines: List[Any]) -> List[str]: + """Which of the flags this plugin can leave out the lines refuse.""" + refused = [] + if any(_names_strict_mcp_flag(l) for l in stderr_lines): + refused.append("--strict-mcp-config") + if any(_names_session_flag(l) for l in stderr_lines): + refused.append("--" + _SESSION_FLAG) + return refused + + def _run_inner_cli(start: Callable[[], Any], stderr_lines: List[str]) -> Any: """start() runs one inner CLI to its result; stderr_lines receives what that CLI writes to stderr. A start the CLI refused over - --strict-mcp-config is made once more without the flag, and the flag is - left out for the rest of this process.""" - global _send_strict_mcp - del stderr_lines[:] - try: - return start() - except Exception: - if not any(_names_strict_mcp_flag(l) for l in stderr_lines): - raise - _send_strict_mcp = False - debug_log("inner CLI refused --strict-mcp-config; starting it again without the flag") + --strict-mcp-config or --no-session-persistence is made again without + that flag, and the flag is left out for the rest of this process. A CLI + names one flag per start, so one that refuses both is started three + times.""" + global _send_strict_mcp, _send_session_flag + left_out: List[str] = [] + while True: del stderr_lines[:] - return start() + try: + return start() + except Exception: + refused = [f for f in _refused_flags(stderr_lines) if f not in left_out] + if not refused: + raise + if "--strict-mcp-config" in refused: + _send_strict_mcp = False + if "--" + _SESSION_FLAG in refused: + _send_session_flag = False + left_out += refused + debug_log(f"inner CLI refused {' and '.join(refused)}; " + "starting it again without") + + +class _ReviewerAuthFailed(Exception): + """The agentic reviewer's credentials were refused; retrying cannot help.""" + + +# Retry notices in a row, each after a 401, at which the review stops. One is +# normal: the CLI renews a stored login after a 401 and tries again. Not used +# in a remote session, where the CLI waits out a short sign-in outage on purpose. +_AGENTIC_MAX_401_RETRIES = 3 + + +def _api_retry_status(msg: Any) -> Optional[int]: + """The HTTP status of the CLI's api_retry notice, if it gives one.""" + data = getattr(msg, "data", None) + status = data.get("error_status") if isinstance(data, dict) else None + return status if isinstance(status, int) else None def _agentic_spawn_env() -> Dict[str, str]: @@ -2009,7 +2142,7 @@ def _agentic_review( "the findings list." ) - # Always prefer the user's installed `claude` over the SDK's bundled CLI. + # Prefer the `claude` that _user_cli_path finds over the SDK's bundled CLI. # The bundled CLI is whatever shipped with the pip-installed SDK version # and can lag the user's CLI by months — protocol skew between them is a # top cause of agentic_fallback=2 in production (the SDK reads @@ -2019,19 +2152,21 @@ def _agentic_review( cli_path = _gateway_cli or _user_cli_path() if cli_path: _tolerate_unknown_sdk_messages() + else: + cli_path = _cli_for_sdk(cli_path) # Without a callback the inner CLI writes to this hook's stderr, which # Claude Code shows Claude as the review notice. Log it instead. child_stderr_lines = [0] - # Lines of the current start that name --strict-mcp-config (_run_inner_cli). + # Lines of the current start that refuse a flag (_run_inner_cli). flag_refusals: List[str] = [] def _child_stderr_metric() -> Dict[str, int]: return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {} def _on_child_stderr(line: str) -> None: - if _names_strict_mcp_flag(line): - # Not counted: where the flag is refused, every review gets this + if _refused_flags([line]): + # Not counted: where a flag is refused, every review gets this # line once, from the start that is then made again. flag_refusals.append(str(line)) debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}") @@ -2057,7 +2192,8 @@ def _agentic_review( # Pre-approved, and the only tools the reviewer has: no # permission mode can then let it write, run or fetch anything. allowed_tools=list(_REVIEWER_TOOLS), - extra_args=_only_tools_args(_REVIEWER_TOOLS), + extra_args={**_only_tools_args(_REVIEWER_TOOLS), + **_reviewer_session_args()}, setting_sources=[], max_turns=turns if turns is not None else max_turns, model=model, @@ -2116,39 +2252,54 @@ def _agentic_review( # Blocks are matched by shape so older SDK builds need no extra import. file_tool_ids = set() - async for msg in query(prompt=_once(), options=opts): - if isinstance(msg, AssistantMessage): - n += 1 - for b in getattr(msg, "content", None) or []: - if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS - and getattr(b, "id", None)): - file_tool_ids.add(b.id) - ctx["rv_tool_calls"] += 1 - elif isinstance(msg, ResultMessage): - subtype = msg.subtype - if msg.structured_output is not None: - structured = msg.structured_output - # SDK ResultMessage carries aggregate usage + cache-aware - # cost across the whole multi-turn run; prefer its cost over - # the price-table estimate. getattr guards older SDK builds. - _record_usage(getattr(msg, "usage", None) or {}, model, - cost_usd=getattr(msg, "total_cost_usd", None)) - for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): - value = getattr(msg, attr, None) - # Counting must never fail the review: anything that - # is not a positive finite number adds nothing. - if (isinstance(value, (int, float)) and not isinstance(value, bool) - and 0 < value < float("inf")): - ctx[key] += int(value) - else: - # Tool results come back as user messages. - content = getattr(msg, "content", None) - if isinstance(content, list): - ctx["rv_tool_err"] += sum( - 1 for b in content - if getattr(b, "is_error", None) is True - and getattr(b, "tool_use_id", None) in file_tool_ids - ) + auth_retries = 0 + # Closed on the way out, also on a raise, so the CLI stops with the review. + async with contextlib.aclosing(query(prompt=_once(), options=opts)) as messages: + async for msg in messages: + if isinstance(msg, AssistantMessage): + # Old CLIs answer each refused request by asking the model + # again, hundreds of times; the message is the same on all. + if getattr(msg, "error", None) == "authentication_failed": + raise _ReviewerAuthFailed("authentication_failed") + auth_retries = 0 + n += 1 + for b in getattr(msg, "content", None) or []: + if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS + and getattr(b, "id", None)): + file_tool_ids.add(b.id) + ctx["rv_tool_calls"] += 1 + elif isinstance(msg, ResultMessage): + subtype = msg.subtype + if msg.structured_output is not None: + structured = msg.structured_output + # SDK ResultMessage carries aggregate usage + cache-aware + # cost across the whole multi-turn run; prefer its cost over + # the price-table estimate. getattr guards older SDK builds. + _record_usage(getattr(msg, "usage", None) or {}, model, + cost_usd=getattr(msg, "total_cost_usd", None)) + for key, attr in (("rv_turns", "num_turns"), ("rv_api_ms", "duration_api_ms")): + value = getattr(msg, attr, None) + # Counting must never fail the review: anything that + # is not a positive finite number adds nothing. + if (isinstance(value, (int, float)) and not isinstance(value, bool) + and 0 < value < float("inf")): + ctx[key] += int(value) + elif getattr(msg, "subtype", None) == "api_retry": + # A gateway's 401 without the API's x-should-retry: false + # keeps the CLI retrying for about three minutes. + auth_retries = auth_retries + 1 if _api_retry_status(msg) == 401 else 0 + if (auth_retries >= _AGENTIC_MAX_401_RETRIES + and not _is_remote_session()): + raise _ReviewerAuthFailed(f"{auth_retries} retries after HTTP 401") + else: + # Tool results come back as user messages. + content = getattr(msg, "content", None) + if isinstance(content, list): + ctx["rv_tool_err"] += sum( + 1 for b in content + if getattr(b, "is_error", None) is True + and getattr(b, "tool_use_id", None) in file_tool_ids + ) return structured, n, subtype def _run(system: str, prompt: str, *, schema: Dict[str, Any] diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 3efe344e..47a992aa 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 @@ -68,6 +68,7 @@ import re import subprocess import sys import threading +import time import urllib.request from datetime import datetime from enum import IntEnum @@ -86,9 +87,9 @@ from _base import ( # noqa: E402,F401 _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, _net_error_metric, _USAGE_CONTEXT, _log_usage, - launcher_probe_metrics, state_dir as _resolve_state_dir, + 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, + llm_reviews_switched_off, agent_sdk_installed, make_state_dir, ) import extensibility # noqa: E402 from patterns import ( # noqa: E402,F401 @@ -219,6 +220,9 @@ 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 @@ -228,6 +232,8 @@ _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") @@ -324,6 +330,10 @@ def emit_metrics( # 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 @@ -357,6 +367,8 @@ def emit_metrics( 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: @@ -422,7 +434,7 @@ def _no_credentials_notice(file_path, session_id): pass if not _git_toplevel(os.path.dirname(os.path.abspath(file_path))): return None - os.makedirs(os.path.dirname(marker), exist_ok=True) + 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, @@ -760,7 +772,7 @@ def handle_user_prompt_submit(input_data): # 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 stash baseline (still read by the Write pattern + # 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} @@ -775,15 +787,15 @@ def handle_user_prompt_submit(input_data): def _capture(repo_cwd): if not snapshot_untracked: return _timed("baseline", capture_git_baseline, repo_cwd), None - # stash-create and ls-files both walk the worktree (~2-5s each in a + # 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 stash produced a SHA. `git stash - # create` returns empty when there are no TRACKED changes, but + # 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 @@ -851,7 +863,7 @@ def handle_user_prompt_submit(input_data): # 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 stash produced + # 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 @@ -1056,6 +1068,47 @@ try: 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. @@ -1266,18 +1319,68 @@ def is_commit_review_enabled(): COMMIT_REVIEW_ENABLED = is_commit_review_enabled() -# Seconds from the start of a commit or push review's race after which -# neither side waits for the other any longer; well inside Claude Code's -# 10-minute hook timeout. +_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. @@ -1289,10 +1392,13 @@ def _agentic_review_with_race( 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 and push-sweep handlers call this — external @@ -1306,13 +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() + _RACE_MAX_WAIT_S + 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: @@ -1330,33 +1439,26 @@ def _agentic_review_with_race( if agentic_done.is_set(): return # agentic finished within the delay — never start fallback fallback_started.set() - result = (None, [], {"agentic": False, "review_failed": True, "api_error": None}) + 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 - ) - # Read on this thread: the outcome is per thread. - failed = llm.last_review_failed() - result = (g, v, {"agentic": False, "review_failed": failed, - "api_error": llm.last_review_status() if failed else None}) - except Exception: # pragma: no cover + q.put_nowait(("fallback", result)) + except _queue.Full: pass - finally: - 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: - 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() + 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 = ( @@ -1369,8 +1471,11 @@ def _agentic_review_with_race( 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", (None, [], { - "agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) + winner, (g, v, m) = "fallback", timed_out + if winner == "agentic" and not m.get("agentic_fallback"): + # The agentic run reached the model; any failure on record is the + # fallback's, which lost. + llm._forget_failed_call() 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 @@ -1385,7 +1490,7 @@ def _review_failure_reason(status): _RACE_TIMED_OUT. """ gateway = (", or an LLM gateway may need its key in ANTHROPIC_CUSTOM_HEADERS" - if os.environ.get("ANTHROPIC_BASE_URL") else "") + 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(): @@ -1416,6 +1521,44 @@ def _review_failure_reason(status): 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. @@ -1845,7 +1988,7 @@ def handle_commit_review_posttooluse(input_data): 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"): @@ -1859,17 +2002,13 @@ def handle_commit_review_posttooluse(input_data): # 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 ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() 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 ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() review_ms = int((_time.time() - review_start) * 1000) # `survived` is the raw self-refute count BEFORE the high/critical-only @@ -2286,7 +2425,7 @@ 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"] @@ -2294,24 +2433,20 @@ def handle_push_sweep_posttooluse(input_data): 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 ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() 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 ) - review_failed = llm.last_review_failed() - api_status = llm.last_review_status() 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, "pushed": len(push_range), "unreviewed": len(tail), + **_base, **_wait_m, "pushed": len(push_range), "unreviewed": len(tail), "files_reviewed": len(diff_files), "review_ms": review_ms, }, api_status) @@ -2485,10 +2620,29 @@ def handle_stop_hook(input_data): _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. @@ -2500,8 +2654,8 @@ def handle_stop_hook(input_data): if gitutil._unparsed_diff_headers else {}), **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), - }) - sys.exit(0) + }, **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 @@ -2615,13 +2769,13 @@ def handle_stop_hook(input_data): 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) @@ -2644,6 +2798,15 @@ def handle_stop_hook(input_data): 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") @@ -2652,7 +2815,7 @@ def handle_stop_hook(input_data): 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: @@ -2663,7 +2826,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 @@ -2787,6 +2950,7 @@ 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"} + 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. @@ -2808,8 +2972,9 @@ def handle_stop_hook(input_data): **({"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) @@ -2817,11 +2982,12 @@ def handle_stop_hook(input_data): 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, touched_paths, snap_baseline) + 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) + 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 @@ -2843,8 +3009,8 @@ def handle_stop_hook(input_data): if gitutil._unparsed_diff_headers else {}), **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} if gitutil._secret_shaped_skipped else {}), - }) - sys.exit(0) + }, **wake) + sys.exit(2 if wake else 0) _SDK_BOOTSTRAP_THROTTLE = os.path.join(_resolve_state_dir(), ".sdk_bootstrap_spawned") @@ -2877,7 +3043,7 @@ def _maybe_bootstrap_agent_sdk_async(): 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() @@ -2977,12 +3143,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. - _write_hook_output({"metrics": {"bash_hook_dedup": 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) diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py index c8045532..330abd28 100644 --- a/plugins/security-guidance/hooks/session_state.py +++ b/plugins/security-guidance/hooks/session_state.py @@ -20,7 +20,7 @@ import re import tempfile from datetime import datetime -from _base import debug_log, state_dir as _state_dir +from _base import debug_log, make_state_dir, state_dir as _state_dir def _state_key(session_id): @@ -139,6 +139,18 @@ def _write_then_rename(state_file, state): raise +def _write_in_place(state_file, state): + """The fallback (Windows, or a folder that refuses the rename) writes the + state file itself. As with the rename, a link there is replaced, not + followed, and a new file is the user's only, as the temporary file is.""" + if os.path.islink(state_file): + os.unlink(state_file) + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(state_file, flags, 0o600) + with os.fdopen(fd, "w") as f: + json.dump(state, f) + + def save_state(session_id, state): """Save the full state dict to file. @@ -152,12 +164,11 @@ def save_state(session_id, state): try: state_dir = os.path.dirname(state_file) if state_dir: - os.makedirs(state_dir, exist_ok=True) + make_state_dir(state_dir) if _RENAME_INTO_PLACE and _write_then_rename(state_file, state): return - with open(state_file, "w") as f: - json.dump(state, f) + _write_in_place(state_file, state) except (IOError, OSError) as e: debug_log(f"Failed to save state file {state_file}: {e}") @@ -181,7 +192,7 @@ def with_locked_state(session_id, callback): state_dir = os.path.dirname(lock_file) try: - os.makedirs(state_dir, exist_ok=True) + make_state_dir(state_dir) except OSError: pass diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh index e0c2730e..b1a5d5b9 100755 --- a/plugins/security-guidance/hooks/sg-python.sh +++ b/plugins/security-guidance/hooks/sg-python.sh @@ -100,10 +100,12 @@ probe() { # the model, whose reply runs the Stop hook again: an endless loop that # never reviewed anything. See #6251, #5781. # + # On Windows a second line carries sys.executable (see sg_own_path). + # # Only for `$(probe ...)`: the `exec` replaces that subshell instead of # forking a second process from it. [ "${BASH_SUBSHELL:-0}" -gt 0 ] || return 1 - exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}")' "$SG_TARGET" 2>/dev/null + exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}"); sys.platform == "win32" and sys.version_info >= (3, 10) and print(sys.executable)' "$SG_TARGET" 2>/dev/null } # Use as `ask ... || { note_unreadable "<name>"; continue; }` (see ask below). @@ -142,11 +144,17 @@ sg_clock() { esac } ask() { - # Sets $v; same exit status as probe. + # Sets $v and $sg_exe; same exit status as probe. local rc=0 t0 ms sg_clock; t0=$sg_now [ -n "$sg_probe_first" ] || sg_probe_first=$t0 v=$(probe "$@") || rc=$? + sg_exe="" + case "$v" in + *$'\n'*) + sg_exe=${v#*$'\n'}; sg_exe=${sg_exe%$'\r'} + v=${v%%$'\n'*} ;; + esac sg_clock; ms=$((sg_now - t0)) if [ -n "$sg_coarse" ]; then [ "$ms" -ge 2000 ] || ms=0 @@ -175,6 +183,145 @@ is_sdk_compatible() { esac } +# Packaged launcher aliases on Windows (python, python3 and py under +# ...\Microsoft\WindowsApps): starting one starts more than Python. The +# Python Install Manager's aliases make Windows check the package for an +# update on each start, and the launcher started the chosen name twice per +# hook, on every Edit, prompt and Stop. See anthropics/claude-code#98929. +# +# So when the name that answers is such an alias and its interpreter is a +# regular file elsewhere, the hook runs with that file instead, and its path +# is kept in the plugin's state folder (`launcher-python`) for a day. Later +# hooks start it directly: one process, and none through the alias. The +# remembered path is used only while PATH and the hook folder are what they +# were when it was checked and the file is still there; anything else is the +# full search below, which writes the entry again. A hook that fails on the +# remembered path empties the entry, so the next one searches again; deleting +# the file does the same by hand. One entry: sessions with different PATHs +# take turns checking, which is still one alias start per hook instead of two. +# +# Not while a virtual environment is active: the alias may be answering for +# that environment's interpreter, which other sessions should not inherit. +# +# Builtins only: nothing here starts a process on the remembered route. +unset SG_LAUNCHER_DIRECT +sg_args=("$@") +sg_exe="" # sys.executable from the last `ask` (Windows, Python 3.10+) +sg_own="" # set by sg_recall and sg_own_path +sg_memo="" # the entry's file; empty where none of this applies +sg_target_dir="" +case "${OSTYPE:-}" in + msys*|cygwin*) + if [ "${BASH_VERSINFO[0]:-0}" -ge 5 ] && [ -n "$SG_TARGET" ] && [ -z "${VIRTUAL_ENV:-}" ]; then + # The folder _base.state_dir() resolves to. + sg_home="${USERPROFILE:-${HOME:-}}" + sg_memo="${SECURITY_WARNINGS_STATE_DIR:-}" + if [ -z "$sg_memo" ] && [ -n "${CLAUDE_CONFIG_DIR:-}" ]; then + sg_memo="$CLAUDE_CONFIG_DIR/security" + fi + [ -n "$sg_memo" ] || sg_memo="~/.claude/security" + case "$sg_memo" in + "~"|"~"[\\/]*) + if [ -n "$sg_home" ]; then sg_memo="$sg_home${sg_memo:1}"; else sg_memo=""; fi ;; + esac + [ -z "$sg_memo" ] || sg_memo="$sg_memo/launcher-python" + sg_target_dir="${SG_TARGET%[\\/]*}" + fi ;; +esac + +sg_is_alias_path() { + case "${1,,}" in + */microsoft/windowsapps/*|*\\microsoft\\windowsapps\\*) return 0 ;; + esac + return 1 +} + +# An interpreter the remembered route may start: python*.exe by absolute +# path, a regular file, and not an alias itself. +sg_startable() { + local name="${1##*/}" + case "$1" in + /*) ;; + *) return 1 ;; + esac + case "${name,,}" in + python*.exe) ;; + *) return 1 ;; + esac + ! sg_is_alias_path "$1" || return 1 + [ -f "$1" ] && [ -x "$1" ] +} + +sg_recall() { + # Sets $sg_own to the remembered interpreter iff it may run this hook. + local tag saved path exe dir end age + [ -n "$sg_memo" ] && [ -r "$sg_memo" ] || return 1 + { + IFS= read -r tag && IFS= read -r saved && IFS= read -r path && + IFS= read -r exe && IFS= read -r dir && IFS= read -r end + } 2>/dev/null < "$sg_memo" || return 1 + [ "$tag" = "sg-launcher-python 1" ] && [ "$end" = "end" ] || return 1 + case "$saved" in + ""|*[!0-9]*|????????????*) return 1 ;; + esac + age=$((EPOCHSECONDS - 10#$saved)) + [ "$age" -ge 0 ] && [ "$age" -lt 86400 ] || return 1 + [ "$path" = "$PATH" ] && [ "$dir" = "$sg_target_dir" ] || return 1 + sg_startable "$exe" && [ -r "$SG_TARGET" ] || return 1 + sg_own="$exe" +} + +sg_own_path() { + # $1: the name that just answered `ask` with version $v. Succeeds, with + # $sg_own set, iff that name is a packaged alias whose interpreter is a + # regular file elsewhere that reads the hook script when started by + # itself and is the same version. Remembers it for the next hooks. + local alias="" own="$sg_exe" want="$v" drive + [ -n "$sg_memo" ] && [ -n "$own" ] || return 1 + hash "$1" 2>/dev/null && alias="${BASH_CMDS[$1]:-}" + sg_is_alias_path "$alias" || return 1 + case "$own" in + [A-Za-z]:[\\/]*) + if [ -n "${sg_drive_mounts:-}" ]; then + drive="${own:0:1}"; own="/${drive,,}/${own:3}"; own="${own//\\//}" + else + own=$(cygpath -u "$own" 2>/dev/null) || return 1 + fi ;; + esac + sg_startable "$own" || return 1 + ask "$own" || { v=$want; return 1; } + v=${v%$'\r'} + [ "$v" = "$want" ] || { v=$want; return 1; } + sg_own="$own" + if [ -d "${sg_memo%/*}" ]; then + { printf '%s\n' "sg-launcher-python 1" "$EPOCHSECONDS" "$PATH" "$own" "$sg_target_dir" "end"; } \ + 2>/dev/null > "$sg_memo" || true + fi + return 0 +} + +# Use right before `exec <name> "$@"`: runs the hook with the interpreter +# behind <name> instead when sg_own_path finds one, else returns. +sg_direct() { + if sg_own_path "$@"; then + export SG_LAUNCHER_DIRECT=2 + exec "$sg_own" "${sg_args[@]}" + fi + return 0 +} + +if sg_recall; then + export SG_LAUNCHER_DIRECT=1 + # Not exec'd, so a failure can empty the entry: no probe checked this + # interpreter today, and a broken one must not fail every hook for a day. + sg_rc=0 + "$sg_own" "$@" || sg_rc=$? + if [ "$sg_rc" -ne 0 ]; then + { : > "$sg_memo"; } 2>/dev/null || true + fi + exit "$sg_rc" +fi + # Pass 1 — try minor-versioned binaries in descending order. These are only # present if the user explicitly installed them (Homebrew / python.org / pyenv), # so picking one here always upgrades over the system `python3`. Highest @@ -185,6 +332,7 @@ for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do ask "$cmd" || { note_unreadable "$cmd"; continue; } v=${v%$'\r'} if is_sdk_compatible "$v"; then + sg_direct "$cmd" exec "$cmd" "$@" fi done @@ -201,6 +349,8 @@ for cmd in "python3" "python" "py -3"; do v=${v%$'\r'} if is_sdk_compatible "$v"; then # shellcheck disable=SC2086 + sg_direct $cmd + # shellcheck disable=SC2086 exec $cmd "$@" fi # Anything that successfully reported a "M.m" string. @@ -219,6 +369,7 @@ done for cmd in "python3.14" "python3.15" "python3.16" "python3.17" "python3.18" "python3.19"; do on_path "$cmd" || continue v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + v=${v%%$'\n'*} v=${v%$'\r'} if is_sdk_compatible "$v"; then exec "$cmd" "$@" |
