diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-27 20:03:52 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-27 20:03:52 +0000 |
| commit | 3654d346b45836e43e013b849be19233ff0efbc3 (patch) | |
| tree | 080cdfdff1e1f3df67ca9517251bbe8052890724 /plugins/security-guidance/hooks | |
| parent | 45bb3d5c14f7c20c9bdc9a30e798cf0d77467e2e (diff) | |
| parent | f8c5e7a1dcb71b10cb74586224b5401f3de5db28 (diff) | |
Merge remote-tracking branch 'origin/main' into mhegazy/sg-secret-rename-pairingmhegazy/sg-secret-rename-pairing
# Conflicts:
# plugins/security-guidance/hooks/diffstate.py
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 28 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 296 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 77 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 136 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 113 |
5 files changed, 598 insertions, 52 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index e5959e68..28b189a4 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -212,6 +212,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 # 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": [], @@ -300,6 +301,33 @@ def _record_http_error(status): _USAGE["http_err_count"] += 1 +def _record_net_error(code): + """Record why an LLM API call got no HTTP response: the packed code from + llm._net_error_code. `api_error` -1 cannot tell a certificate failure + from a refused connection or a timeout, and a failure the HTTP client + 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.""" + try: + c = int(code) + except (TypeError, ValueError): + return + if c > 0: + with _USAGE_LOCK: + _USAGE["net_err"] = c + + +def _clear_net_error(): + with _USAGE_LOCK: + _USAGE["net_err"] = 0 + + +def _net_error_metric(): + with _USAGE_LOCK: + return _USAGE.get("net_err", 0) + + # Set by main() and the review handlers: which review this invocation runs # and for which Claude Code session, so the usage log line can be attributed. _USAGE_CONTEXT = {"session_id": "", "review": "stop"} diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index fc42f8c1..5f65ac7f 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -6,17 +6,18 @@ there so callers keep resolving bare names through the hook module's globals — tests that ``monkeypatch.setattr(hook, "<fn>", …)`` continue to work without retargeting. """ +import hashlib import os import subprocess import sys import time -from _base import debug_log, _PV +from _base import debug_log, portable_output, _PV from gitutil import ( GIT_CMD, _git_dir, _git_toplevel, _git_status_porcelain, _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, - _secret_rename_origins, + _secret_rename_origins, index_entry_count, ) from session_state import with_locked_state from extensibility import _same_dir @@ -323,6 +324,8 @@ def get_baseline_file_content(session_id, file_path, cwd): # from uncommitted work that was already there. Stored with baseline_sha. # Telemetry only. last_baseline_fail = 0 +# Entries in the index the last capture copied, None if unknown. Telemetry only. +last_index_entries = None def capture_git_baseline(cwd): @@ -351,8 +354,9 @@ def capture_git_baseline(cwd): # 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. - global last_baseline_fail + global last_baseline_fail, last_index_entries last_baseline_fail = 0 + last_index_entries = None try: # Check if HEAD exists (i.e., repo has at least one commit) head_check = subprocess.run( @@ -370,6 +374,7 @@ def capture_git_baseline(cwd): # env is None when no usable index copy could be made: fall # 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 @@ -504,6 +509,164 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0): pass +# ─── repeated-diff count ──────────────────────────────────────────────────── +# +# Count only. A change that comes back under a new commit (undo and re-commit, +# rebase before the first push) is unknown to the reviewed-shas record and is +# reviewed again. These helpers say how often that happens, by remembering a +# hash of each reviewed hunk next to the reviewed-shas file. Nothing here +# decides whether a review runs, and nothing here waits on another process +# for more than a moment. + +_SEEN_DIFFS_BASENAME = "sg-reviewed-diffs" +_SEEN_DIFFS_TTL_S = 7 * 24 * 3600 +# Past this size the record is cut back to its newest half. +_SEEN_DIFFS_TRIM_BYTES = 1024 * 1024 +_SEEN_DIFFS_MAX_KEYS = 500 +_SEEN_DIFFS_LOCK_TRIES = 10 + +# `diff_seen` values, weakest first. A review reports the weakest of its +# hunks: 3 means every hunk already had a finished review in this clone. +DIFF_SEEN_ERROR = -1 # the record could not be read or written +DIFF_SEEN_NO = 0 # some hunk was never reviewed +DIFF_SEEN_UNFINISHED = 1 # a review of it started and has no verdict (yet) +DIFF_SEEN_OTHER_TREE = 2 # finished, on different repo contents +DIFF_SEEN_SAME_TREE = 3 # finished, on the same tree + + +def _hunk_keys(diff_files): + """One hash per hunk: the path plus the hunk's lines, context included. + + The `@@` line is left out, so a hunk keeps its key when a rebase only + moves it; the same edit next to different code gets a different key. + """ + keys = {} + for path, content in diff_files: + hunks, cur = [], [] + for ln in content.split("\n"): + if ln.startswith("@@"): + hunks.append(cur) + cur = [] + else: + cur.append(ln) + hunks.append(cur) + for body in hunks: + # A file's last hunk ends with the diff's trailing blank line. + while body and not body[-1]: + body.pop() + if not body: + continue + h = hashlib.sha256(path.encode("utf-8", "replace")) + h.update(b"\0") + h.update("\n".join(body).encode("utf-8", "replace")) + keys[h.hexdigest()[:16]] = None + keys = list(keys) + if len(keys) > _SEEN_DIFFS_MAX_KEYS: + # Keep the record small: the hunks past the cap share one key, so + # they only match the same set of hunks again. + rest = hashlib.sha256(" ".join(keys[_SEEN_DIFFS_MAX_KEYS - 1:]).encode("ascii")) + keys = keys[:_SEEN_DIFFS_MAX_KEYS - 1] + [rest.hexdigest()[:16]] + return keys + + +def _seen_lock(fd): + """True: locked. False: another process kept it. None: no flock here.""" + for _ in range(_SEEN_DIFFS_LOCK_TRIES): + try: + if _flock_nb(fd, exclusive=True): + return True + except (ImportError, OSError): + return None + time.sleep(0.05) + return False + + +def _append_diff_row(f, locked, token, done): + """Append one record for the review to `f`, the record opened "a+b".""" + _, keys, tree = token + row = f"{int(time.time())}\t{tree}\t{int(done)}\t{' '.join(keys)}\n".encode("ascii") + size = f.seek(0, os.SEEK_END) + if size: + f.seek(size - 1) + if f.read(1) != b"\n": + row = b"\n" + row # a torn last record must not swallow this one + # Cutting the record back rewrites it: not while another process holds + # the lock. Without flock at all, bounded beats exact. + if locked is not False and size + len(row) > _SEEN_DIFFS_TRIM_BYTES: + f.seek(0) + keep, room = [], _SEEN_DIFFS_TRIM_BYTES // 2 + for ln in reversed(f.read().splitlines(keepends=True)): + room -= len(ln) + if room < 0: + break + keep.append(ln) + f.seek(0) + f.truncate() + row = b"".join(reversed(keep)) + row + f.write(row) + f.flush() + + +def _diff_review_started(repo_root, diff_files, tip="HEAD"): + """Note that a review of `diff_files`, a diff ending at `tip`, is starting. + + Returns (token, metrics). `metrics` is {"diff_seen": <DIFF_SEEN_* code>}: + whether this clone already reviewed every hunk of this diff. `token` goes + to `_diff_review_done` once the review has a verdict. Never raises. + """ + if portable_output() or not diff_files: + # No metrics leave the hook in portable mode, so nothing to count. + return None, {} + try: + gd = _git_dir(repo_root) + keys = _hunk_keys(diff_files) + if not gd or not keys: + raise ValueError("no git dir" if not gd else "no hunks") + token = (os.path.join(gd, _SEEN_DIFFS_BASENAME), keys, + "".join(_full_shas(repo_root, [tip + "^{tree}"])[:1])) + tree = token[2] + now = time.time() + best = dict.fromkeys(keys, DIFF_SEEN_NO) + # Read and note under one lock, so two reviews of one diff that start + # together cannot both miss each other. + with open(token[0], "a+b") as f: + locked = _seen_lock(f.fileno()) + if locked is False: + raise OSError("record is locked") + f.seek(0) + for ln in f.read().decode("ascii", "replace").splitlines(): + row = ln.split("\t") + if len(row) != 4 or not row[0].isdigit() or len(row[0]) > 12: + continue + if now - int(row[0]) > _SEEN_DIFFS_TTL_S: + continue + if row[2] != "1": + seen = DIFF_SEEN_UNFINISHED + elif tree and row[1] == tree: + seen = DIFF_SEEN_SAME_TREE + else: + seen = DIFF_SEEN_OTHER_TREE + for k in row[3].split(" "): + if best.get(k, seen) < seen: + best[k] = seen + _append_diff_row(f, locked, token, done=False) + return token, {"diff_seen": min(best.values())} + except Exception as e: + debug_log(f"Repeated-diff count: not counted ({type(e).__name__}: {e})") + return None, {"diff_seen": DIFF_SEEN_ERROR} + + +def _diff_review_done(token): + """Note that the review `token` came from got a verdict. Never raises.""" + if not token: + return + try: + with open(token[0], "a+b") as f: + _append_diff_row(f, _seen_lock(f.fileno()), token, done=True) + except Exception as e: + debug_log(f"Repeated-diff count: verdict not noted ({type(e).__name__}: {e})") + + # ─── in-flight review markers ─────────────────────────────────────────────── # # A commit or push review records its shas only once it has a verdict, which @@ -512,14 +675,19 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0): # through a second full review. So a review first takes an exclusive flock on # `sg-inflight-<sha>`, next to the reviewed-shas file, and holds it until its # process ends; other reviews leave a locked commit to it. The kernel drops -# the lock however the holder dies, so a killed review blocks nobody. Without -# flock (native Windows Python, some network filesystems) there are no +# the lock however the holder dies, so a killed review blocks nobody. Native +# Windows Python has no flock; there the same lock is taken with LockFileEx. +# Where files cannot be locked (some network filesystems) there are no # markers and nothing changes. _INFLIGHT_PREFIX = "sg-inflight-" # A marker file nobody holds (a killed review's) is removed once this old. _INFLIGHT_GC_AGE_S = 3600 _inflight_held = {} +# Windows refuses to delete a file that is open, so a marker is closed first +# there. Elsewhere it is deleted while still locked, so nobody can lock a +# file that is about to go. +_UNLINK_BEFORE_CLOSE = os.name != "nt" def _full_shas(repo_root, shas): @@ -538,11 +706,60 @@ def _full_shas(repo_root, shas): return out +_win_lock_file_ex = None + + +def _win_lock_nb(fd, exclusive): + """`_flock_nb` for native Windows Python, with LockFileEx. + + Shared and exclusive as with flock, never waits, and Windows drops the + lock when the handle is closed or the holder's process ends. Windows + locks stop other processes reading the locked bytes, so the byte locked + is one far past the end of the (empty) marker: copying a repository while + a review runs still reads the marker. + """ + global _win_lock_file_ex + import errno + try: + import ctypes + import msvcrt + if _win_lock_file_ex is None: + from ctypes import wintypes + + class _Overlapped(ctypes.Structure): + _fields_ = [("Internal", ctypes.c_void_p), ("InternalHigh", ctypes.c_void_p), + ("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD), + ("hEvent", wintypes.HANDLE)] + + fn = ctypes.WinDLL("kernel32", use_last_error=True).LockFileEx + fn.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, + wintypes.DWORD, ctypes.POINTER(_Overlapped)] + fn.restype = wintypes.BOOL + _win_lock_file_ex = (fn, _Overlapped) + except (ImportError, AttributeError, OSError) as e: + raise OSError(errno.ENOLCK, f"no file locking in this Python ({e})") + fn, _Overlapped = _win_lock_file_ex + fail_immediately, exclusive_lock = 0x1, 0x2 + where = _Overlapped(Offset=0, OffsetHigh=0x7FFFFFFF) + if fn(msvcrt.get_osfhandle(fd), fail_immediately | (exclusive_lock if exclusive else 0), + 0, 1, 0, ctypes.byref(where)): + return True + err = ctypes.get_last_error() + if err == 33: # ERROR_LOCK_VIOLATION: another handle holds it + return False + raise OSError(errno.ENOLCK, f"LockFileEx failed (WinError {err})") + + def _flock_nb(fd, exclusive): """True when the lock was taken, False when another process holds it. Raises OSError when the file cannot be locked at all.""" import errno - import fcntl + if os.name == "nt": + return _win_lock_nb(fd, exclusive) + try: + import fcntl + except ImportError as e: + raise OSError(errno.ENOLCK, f"no file locking in this Python ({e})") try: fcntl.flock(fd, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB) return True @@ -552,16 +769,36 @@ def _flock_nb(fd, exclusive): raise -def _release_inflight(): - for p, fd in list(_inflight_held.items()): +def _again_if_refused(op, *args): + """`op(*args)`, tried a few times where another process having the file + open for a moment refuses it (Windows). Raises the last OSError.""" + import time as _time + tries = 1 if _UNLINK_BEFORE_CLOSE else 3 + for attempt in range(tries): try: - os.unlink(p) - except OSError: - pass + return op(*args) + except PermissionError: + if attempt == tries - 1: + raise + _time.sleep(0.01) + + +def _drop_marker(p, fd, unlink=True): + """Close a marker this process has open and, with `unlink`, delete it, in + the order this platform needs. Never raises. A delete that stays refused + leaves an unlocked file, which is swept once old.""" + steps = [(_again_if_refused, os.unlink, p)] if unlink else [] + steps.insert(len(steps) if _UNLINK_BEFORE_CLOSE else 0, (os.close, fd)) + for step, *args in steps: try: - os.close(fd) + step(*args) except OSError: pass + + +def _release_inflight(): + for p, fd in list(_inflight_held.items()): + _drop_marker(p, fd) _inflight_held.clear() @@ -580,11 +817,10 @@ def _sweep_inflight(gd): except OSError: continue try: - if _flock_nb(fd, exclusive=True): - os.unlink(p) + unheld = _flock_nb(fd, exclusive=True) except OSError: - pass - os.close(fd) + unheld = False + _drop_marker(p, fd, unlink=unheld) def _mark_inflight(repo_root, shas): @@ -592,7 +828,6 @@ def _mark_inflight(repo_root, shas): run, until the process ends. Best-effort; never raises. A commit another live review holds stays with that review.""" try: - import fcntl # noqa: F401 gd = _git_dir(repo_root) if not gd: return @@ -601,17 +836,26 @@ def _mark_inflight(repo_root, shas): p = os.path.join(gd, _INFLIGHT_PREFIX + sha) if not _is_full_sha(sha) or p in _inflight_held: continue - fd = os.open(p, os.O_RDWR | os.O_CREAT, 0o600) try: - # The inode check: a holder unlinks its marker when it ends, - # and a lock on that unlinked file would claim nothing. - held = (_flock_nb(fd, exclusive=True) - and os.fstat(fd).st_ino == os.stat(p).st_ino) + fd = _again_if_refused(os.open, p, os.O_RDWR | os.O_CREAT, 0o600) + except OSError: + # One marker that cannot be opened does not cost the others + # their claim. + continue + try: + held = _flock_nb(fd, exclusive=True) except OSError: # Cannot lock here at all: leave no file that reads as held. - os.close(fd) - os.unlink(p) + _drop_marker(p, fd) return + if held and _UNLINK_BEFORE_CLOSE: + # The inode check: a holder unlinks its marker when it ends, + # and a lock on that unlinked file would claim nothing. Not + # where an open file cannot be unlinked in the first place. + try: + held = os.fstat(fd).st_ino == os.stat(p).st_ino + except OSError: + held = False if not held: os.close(fd) continue @@ -627,10 +871,6 @@ def _mark_inflight(repo_root, shas): def _load_inflight_shas(repo_root, shas, _gd=None): """Which of `shas` another live review in this clone holds right now.""" out = set() - try: - import fcntl # noqa: F401 - except ImportError: - return out gd = _gd or _git_dir(repo_root) if not gd: return out diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 67fec34d..6410c1c7 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -103,6 +103,50 @@ def apply_safe_git_env(): os.environ.update(SAFE_GIT_ENV) +def index_entry_count(path): + """The entry count in an index file's header (signature, version, count), + or None if it cannot be read. A split or sparse index holds fewer entries + than the repository has tracked files.""" + try: + with open(path, "rb") as f: + header = f.read(12) + except OSError: + return None + if header[:4] == b"DIRC" and len(header) == 12: + return int.from_bytes(header[8:12], "big") + return None + + +def windows_drive_mount(path, mountinfo): + """Whether `path` is on a Windows drive mounted into WSL, given the text + of /proc/self/mountinfo. Every file status there is a round trip to the + Windows host.""" + best, best_type = "", "" + for line in mountinfo.splitlines(): + # id parent dev root mountpoint options [tags] - fstype source options + before, _, after = line.partition(" - ") + fields, tail = before.split(), after.split() + if len(fields) < 5 or not tail: + continue + point = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields[4]) + inside = path == point or path.startswith(point.rstrip("/") + "/") + if inside and len(point) >= len(best): + best, best_type = point, tail[0] + return best_type in ("9p", "drvfs", "virtiofs") + + +def on_windows_drive(path): + """windows_drive_mount for this machine. False anywhere but WSL.""" + try: + with open("/proc/sys/kernel/osrelease") as f: + if "microsoft" not in f.read().lower(): + return False + with open("/proc/self/mountinfo") as f: + return windows_drive_mount(os.path.realpath(path), f.read()) + except (OSError, ValueError): + return False + + def _git_rev_parse_head(cwd): """Return the current HEAD SHA, or None if not a git repo / no commits.""" try: @@ -249,6 +293,15 @@ def _path_batches(paths, budget=None): # long once cut down) or "none_reviewable". _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} + def _too_many_args(e): """The OS refused to start the command because its arguments are too @@ -542,6 +595,10 @@ def _hook_tmpdir(): return d +def _note_add_failure(kind, paths): + _add_failed["code"] = kind * 100000 + min(len(paths), 99999) + + @contextlib.contextmanager def _temp_index(cwd, untracked_paths=None): """Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the @@ -632,12 +689,20 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths): # 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. - _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"}) + 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')}") # A whole-tree add puts a nested repository back. if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index): yield None diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index f4562bb4..468d9e6d 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -39,7 +39,7 @@ except ImportError: # a Python built without TLS import extensibility import review_api -from _base import debug_log, _record_usage, _record_http_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 # noqa: F401 from session_state import load_state, with_locked_state from gitutil import git_config_env, SAFE_GIT_CONFIG @@ -289,10 +289,120 @@ def _probe_anthropic(timeout: float = 5.0) -> bool: return True except urllib.error.HTTPError: return True # got a status code → connected - except (urllib.error.URLError, TimeoutError, OSError): + except (urllib.error.URLError, TimeoutError, OSError) as e: + _record_net_error(_net_error_code(e)) return False +# ===================================================================== +# Why a call got no HTTP response +# ===================================================================== +# Classes for the `net_err` metric. Measure only: nothing reads these to +# decide what the plugin does. +NET_ERR_CERT_VERIFY = 1 # the server certificate did not verify +NET_ERR_TLS = 2 # any other TLS failure, including a default context that cannot be built +NET_ERR_DNS = 3 # the host name did not resolve +NET_ERR_CONNECT = 4 # refused, reset, closed early or unreachable +NET_ERR_TIMEOUT = 5 +NET_ERR_PROXY = 6 # the proxy refused the tunnel +NET_ERR_OTHER = 7 # another failure from the HTTP client +NET_ERR_INNER_CLI = 9 # the review ran through a CLI, which failed +NET_ERR_INNER_CLI_TIMEOUT = 10 +NET_ERR_NO_SDK = 11 # the review needed the agent SDK, which could not be imported + +_NET_FLAG_NO_CA_ON_DISK = 1 # Python's default CA file and directory are missing or empty +_NET_FLAG_PROXY = 2 # the request would go through a proxy +_NET_FLAG_NODE_EXTRA_CA = 4 # NODE_EXTRA_CA_CERTS is set (Python does not read it) +_NET_FLAG_SSL_CERT_ENV = 8 # SSL_CERT_FILE or SSL_CERT_DIR is set + + +def _net_error_class(exc) -> Tuple[int, int]: + """(class, X.509 verify code) for an exception from an API call; class 0 + for one that is not a network failure. The verify code is OpenSSL's + (20 = issuer not found locally, 19 = self-signed certificate in the + chain, 10 = expired), 0 when the class is not NET_ERR_CERT_VERIFY.""" + import errno + import http.client + import socket + try: + import ssl + cert_error, tls_error = ssl.SSLCertVerificationError, ssl.SSLError + except ImportError: + cert_error = tls_error = () + reason = getattr(exc, "reason", None) + err = reason if isinstance(reason, BaseException) else exc + if isinstance(err, cert_error): + code = getattr(err, "verify_code", 0) + return NET_ERR_CERT_VERIFY, code if isinstance(code, int) and 0 < code < 100 else 0 + if isinstance(err, tls_error): + return NET_ERR_TLS, 0 + if isinstance(err, socket.gaierror): + return NET_ERR_DNS, 0 + if isinstance(err, OSError): + text = str(err).lower() + if "tunnel connection failed" in text: + return NET_ERR_PROXY, 0 + if isinstance(err, TimeoutError) or "timed out" in text: + return NET_ERR_TIMEOUT, 0 + if isinstance(err, ConnectionError) or err.errno in ( + errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, + errno.EHOSTDOWN, errno.EADDRNOTAVAIL): + return NET_ERR_CONNECT, 0 + return NET_ERR_OTHER, 0 + if isinstance(err, http.client.HTTPException) or isinstance(exc, urllib.error.URLError): + return NET_ERR_OTHER, 0 + return 0, 0 + + +def _net_error_flags(tls: bool) -> int: + """What the machine's setup says about a failed call. Each check is + best effort: one that cannot be made leaves its flag off.""" + flags = 0 + if tls: + try: + import ssl + paths = ssl.get_default_verify_paths() + has_file = bool(paths.cafile) and os.path.getsize(paths.cafile) > 0 + has_dir = False + if paths.capath: + with os.scandir(paths.capath) as it: + has_dir = any(True for _ in it) + # Windows also reads the system store, which this cannot see. + if not has_file and not has_dir and sys.platform != "win32": + flags |= _NET_FLAG_NO_CA_ON_DISK + except Exception: + pass + if os.environ.get("NODE_EXTRA_CA_CERTS"): + flags |= _NET_FLAG_NODE_EXTRA_CA + if os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR"): + flags |= _NET_FLAG_SSL_CERT_ENV + try: + url = urllib.parse.urlsplit(_anthropic_base_url()) + # As urllib chooses: the proxy for the URL's scheme, bypass by host:port. + if (urllib.request.getproxies().get(url.scheme) + and not urllib.request.proxy_bypass(url.netloc.rpartition("@")[2])): + flags |= _NET_FLAG_PROXY + except Exception: + pass + return flags + + +def _net_error_code(exc) -> int: + """`net_err` for an exception: class + 100 * verify code + 10000 * flags, + or 0 for an exception that is not a network failure.""" + try: + cls, verify = _net_error_class(exc) + except Exception: + return 0 + if not cls: + return 0 + try: + flags = _net_error_flags(cls in (NET_ERR_CERT_VERIFY, NET_ERR_TLS)) + except Exception: + flags = 0 + return cls + 100 * verify + 10000 * flags + + def _strip_anthropic_from_no_proxy() -> None: for var in ("NO_PROXY", "no_proxy"): val = os.environ.get(var) @@ -834,6 +944,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, """ global _last_call_claude_http_error, _gateway_review_timed_out _last_call_claude_http_error = None + _clear_net_error() route = "gateway" if cli_path else "3P" try: @@ -862,6 +973,7 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, debug_log(f"{route} sdk-single-turn: SDK unavailable ({e})") _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_NO_SDK) return None _send_sdk_logs_to_debug_log() @@ -946,12 +1058,14 @@ def _call_claude_via_sdk(prompt, output_schema, *, max_tokens=16000, model=None, _gateway_review_timed_out = True _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_INNER_CLI_TIMEOUT) return None except Exception as e: debug_log(f"{route} sdk-single-turn: query failed ({e})") _log_child_stderr() _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(NET_ERR_INNER_CLI) return None @@ -974,6 +1088,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, """ global _last_call_claude_http_error _last_call_claude_http_error = None + _clear_net_error() if _is_3p_provider(): # On Bedrock/Vertex/Foundry/Mantle the api.anthropic.com path below @@ -1092,6 +1207,7 @@ def _call_claude(prompt, output_schema, thinking_budget=10000, max_tokens=16000, debug_log(f"Request failed after retries: {e}") _last_call_claude_http_error = -1 _record_http_error(-1) + _record_net_error(_net_error_code(e)) return None if not response_data: @@ -1590,6 +1706,7 @@ Respond with a JSON object. If vulnerabilities are found, set hasVulnerabilities cacheable_prefix=_CODE_REVIEW_RUBRIC) except Exception as e: debug_log(f"LLM code review: call raised {type(e).__name__}: {e}") + _record_net_error(_net_error_code(e)) analysis = None # A reply without the schema's required flag is not a verdict either. if not isinstance(analysis, dict) or "hasVulnerabilities" not in analysis: @@ -1791,11 +1908,15 @@ def agentic_review( before the review, 2 = it went missing during it rv_tool_err Read/Grep/Glob calls that came back as errors rv_tool_calls Read/Grep/Glob calls made + rv_turns turns the reviewer took, as the CLI counts them + rv_api_ms time the reviewer spent waiting on the model, in ms - The counts cover all stages of the review. Keys are left out when 0.""" + The counts cover all stages of the review. Keys are left out when 0. + rv_turns and rv_api_ms come from each stage's result message, so a stage + that ends without one (the CLI exits early) adds nothing to them.""" context_dir = _agentic_context_dir(repo_dir) gone = 0 if os.path.isdir(context_dir) else 1 - ctx = {"rv_tool_err": 0, "rv_tool_calls": 0} + ctx = {"rv_tool_err": 0, "rv_tool_calls": 0, "rv_turns": 0, "rv_api_ms": 0} guidance, vulns, metrics = _agentic_review(repo_dir, diff_files, touched_paths, ctx) if not gone and not os.path.isdir(context_dir): gone = 2 @@ -2012,6 +2133,13 @@ def _agentic_review( # 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) diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 0cae917d..3efe344e 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -84,10 +84,10 @@ from _base import ( # noqa: E402,F401 DEBUG_LOG_FILE, DEBUG_LOG_MAX_BYTES, debug_log, PROVENANCE_TAG, PROVENANCE_BANNER, _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, - _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, + _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, - write_hook_output as _write_hook_output, + write_hook_output as _write_hook_output, portable_output, llm_reviews_switched_off, agent_sdk_installed, ) import extensibility # noqa: E402 @@ -103,6 +103,7 @@ from session_state import ( # noqa: E402,F401 ) from gitutil import ( # noqa: E402,F401 GIT_CMD, apply_safe_git_env, remove_copies_on_termination, + on_windows_drive, _git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index, _git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range, _git_toplevel_and_head, _git_head_at, @@ -124,6 +125,7 @@ from diffstate import ( # noqa: E402,F401 _REVIEWED_SHAS_BASENAME, _REVIEWED_SHAS_CAP, _reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas, _full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight, + _diff_review_started, _diff_review_done, UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set, touched_scope, review_scope_code, baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS, @@ -219,19 +221,39 @@ CONTINUATION_SUFFIX = ( # Extra keys emit_metrics appends to every row this invocation emits. _TAIL_METRICS: Dict[str, Any] = {} +# Of those, the ones that go after the others whenever they were set: a row +# over CC's key cap loses them before any older review key. Only the launcher +# keys below come later; those are also on every smaller row of the session. +_LAST_METRIC_KEYS = ("diff_seen",) -# The launcher's slow interpreter probes, if any. After everything else. +# The launcher's slow interpreter probes, if any. After the keys above. _LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics() # Reviewer context diagnostics from llm.agentic_review, most useful first. _REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls") +# How much work the agentic reviewer did, from llm.agentic_review: turns, and +# time waiting on the model. They tell more turns from slower turns when +# review_ms moves. +_REVIEWER_EFFORT_KEYS = ("rv_turns", "rv_api_ms") +# A clean commit review row has one free key under CC's key cap once +# rv_tool_calls is on it, so the two are sent as one number: +# rv_effort = rv_turns * _EFFORT_TURNS_UNIT + rv_api_ms (capped below the unit) +_EFFORT_TURNS_UNIT = 10_000_000 +# The packed value queued for this row. Emitted after every other key, the +# launcher's included, so it never displaces one at the cap. +_REVIEWER_EFFORT_METRICS: Dict[str, Any] = {} def _note_reviewer_context(agentic_metrics): - """Queue the agentic reviewer's context diagnostics for this row.""" + """Queue the agentic reviewer's context and effort diagnostics for this row.""" for key in _REVIEWER_CONTEXT_KEYS: if agentic_metrics.get(key): _TAIL_METRICS[key] = agentic_metrics[key] + turns = agentic_metrics.get("rv_turns") or 0 + api_ms = agentic_metrics.get("rv_api_ms") or 0 + if turns or api_ms: + _REVIEWER_EFFORT_METRICS["rv_effort"] = ( + turns * _EFFORT_TURNS_UNIT + min(api_ms, _EFFORT_TURNS_UNIT - 1)) def emit_metrics( @@ -304,6 +326,12 @@ def emit_metrics( head["launcher_fallback"] = 1 usage = _usage_metrics() head.update(usage) + # Why the last call got no HTTP response (api_error -1 says only that it + # did not). Ahead of the row's own keys: on a failed review this is the + # key that says what failed, so it is not the one to lose to the key cap. + net_err = _net_error_metric() + if net_err: + head["net_err"] = net_err if head: metrics = {**head, **metrics} # Diagnostic keys go last, so they are the first dropped when a row is @@ -324,7 +352,11 @@ def emit_metrics( # managed-mcp.json) and the review was started again without it. tail["strict_mcp_off"] = 1 tail.update(_TAIL_METRICS) + for k in _LAST_METRIC_KEYS: + if k in tail: + tail[k] = tail.pop(k) tail.update(_LAUNCHER_METRICS) + tail.update(_REVIEWER_EFFORT_METRICS) metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} if rewake_summary: @@ -680,6 +712,31 @@ def _store_baseline_fail(state, fail): state.pop("baseline_fail", None) +# A prompt waits for this hook, so one this slow is worth a metrics row. Faster +# prompts send none: the row would be one more event per prompt for every user. +SLOW_PROMPT_MS = 1000 + + +def _slow_prompt_metrics(cwd, total, baseline, untracked, captured, baseline_fail): + """The metrics row for a slow prompt. Times are seconds, spent in + handle_user_prompt_submit (the launcher reports its own). Counts and flags + only, never a path. Telemetry only.""" + metrics = { + "ups_ms": int(total * 1000), + "ups_baseline_ms": int(baseline * 1000), + "ups_untracked_ms": int(untracked * 1000), + } + if diffstate.last_index_entries is not None: + metrics["ups_index_entries"] = diffstate.last_index_entries + if on_windows_drive(cwd): + metrics["ups_wsl_drive"] = 1 + if not captured: + metrics["ups_no_baseline"] = 1 + if baseline_fail: + metrics["ups_baseline_fail"] = baseline_fail + return metrics + + def handle_user_prompt_submit(input_data): """ Handle UserPromptSubmit — capture git baseline SHA. @@ -692,6 +749,8 @@ def handle_user_prompt_submit(input_data): to be lost when the wipe landed before Stop's state read. """ + import time as _time + started = _time.monotonic() cwd = input_data.get("cwd", "") if not cwd: debug_log("UPS: no cwd, skipping baseline capture") @@ -704,17 +763,25 @@ def handle_user_prompt_submit(input_data): # nothing, so only the stash baseline (still read by the Write pattern # filter) is captured. snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW + spent = {"baseline": 0.0, "untracked": 0.0} + + def _timed(key, fn, repo_cwd): + began = _time.monotonic() + try: + return fn(repo_cwd) + finally: + spent[key] += _time.monotonic() - began def _capture(repo_cwd): if not snapshot_untracked: - return capture_git_baseline(repo_cwd), None + return _timed("baseline", capture_git_baseline, repo_cwd), None # stash-create and ls-files both walk the worktree (~2-5s each in a # very large repo). Run them concurrently so UPS latency stays # ≈ max(both). import concurrent.futures as _cf with _cf.ThreadPoolExecutor(max_workers=2) as _ex: - _f_sha = _ex.submit(capture_git_baseline, repo_cwd) - _f_ut = _ex.submit(_list_untracked, repo_cwd) + _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 # pre-existing untracked files still need to be excluded from the @@ -723,7 +790,6 @@ def handle_user_prompt_submit(input_data): # something tracked is dirtied. return _f_sha.result(), _f_ut.result() or {} - import time as _time captured_at = _time.time() sha, untracked_now = _capture(cwd) # No repo here and none remembered: the listing above failed, it did not @@ -813,6 +879,13 @@ def handle_user_prompt_submit(input_data): debug_log(f"Failed to capture git baseline (cwd={cwd!r}) — not a git repo, " f"or git invocation failed (check log entries above)") + total = _time.monotonic() - started + debug_log(f"UPS: took {total:.2f}s (baseline {spent['baseline']:.2f}s, " + f"untracked {spent['untracked']:.2f}s)") + if (total * 1000 >= SLOW_PROMPT_MS or _LAUNCHER_METRICS) and not portable_output(): + emit_metrics(_slow_prompt_metrics( + cwd, total, spent["baseline"], spent["untracked"], bool(sha), baseline_fail)) + sys.exit(0) def _resolve_amend_pre_sha(repo_root, expected_post_sha=None): @@ -1284,10 +1357,11 @@ def _agentic_review_with_race( _th.Thread(target=_fallback, daemon=True).start() winner, (g, v, m) = q.get() - # What the agentic run saw of its directory is kept when the fallback's - # result replaces it below. + # What the agentic run saw of its directory, and how much work it did, + # is kept when the fallback's result replaces it below. reviewer_context = ( - {k: m[k] for k in _REVIEWER_CONTEXT_KEYS if k in m} if winner == "agentic" else {} + {k: m[k] for k in _REVIEWER_CONTEXT_KEYS + _REVIEWER_EFFORT_KEYS if k in m} + if winner == "agentic" else {} ) if winner == "agentic" and m.get("agentic_fallback") and fallback_started.is_set(): # The caller would rerun the single-shot review the fallback has @@ -1760,6 +1834,10 @@ def handle_commit_review_posttooluse(input_data): # Tell a push review (or the next commit's reflog scan) that these commits # are being reviewed, so it does not start a second review of them. _mark_inflight(repo_root, _full_shas(repo_root, shas)) + # Count only: keyed on what the reviewer is sent, after the byte caps. + _diff_token, _seen_m = _diff_review_started( + repo_root, _cap_files_for_prompt(diff_files), tip=shas[0]) + _TAIL_METRICS.update(_seen_m) review_start = _time.time() @@ -1863,6 +1941,7 @@ def handle_commit_review_posttooluse(input_data): _append_reviewed_shas(repo_root, full_shas, vulns_found=len(vulns or [])) except Exception: pass + _diff_review_done(_diff_token) if not concrete_guidance: debug_log("Commit review: no security issues found") @@ -2190,6 +2269,9 @@ def handle_push_sweep_posttooluse(input_data): sys.exit(0) _mark_inflight(repo_root, tail) + _diff_token, _seen_m = _diff_review_started( + repo_root, _cap_files_for_prompt(diff_files)) + _TAIL_METRICS.update(_seen_m) import time as _time now = _time.time() @@ -2235,6 +2317,7 @@ def handle_push_sweep_posttooluse(input_data): # The tail is now covered by this net-diff review. _append_reviewed_shas(repo_root, tail, vulns_found=len(vulns or [])) + _diff_review_done(_diff_token) new_vulns, n_deduped = _dedup_against_state( session_id, vulns or [], prompted=_finding_keys(previous_findings) @@ -2547,9 +2630,11 @@ def handle_stop_hook(input_data): debug_log(f"Stop hook: diff against {content_base[:12]} failed — falling back to {diff_base}") diff_output = get_git_diff(repo_root, diff_base, full_context=False, paths=review_paths, untracked_paths=untracked) - # Only when it happened: MiB of git diff output read, reviewable files - # whose diff was cut while reading it, diffs that hit the timeout. - for _k, _v in (("diff_mb", gitutil._diff_read["bytes"] >> 20), + # Only when it happened: a failed `git add -N` (first, so a row at CC's key + # cap keeps it), MiB of git diff output read, reviewable files whose diff + # was cut while reading it, diffs that hit the timeout. + for _k, _v in (("add_fail", gitutil._add_failed["code"]), + ("diff_mb", gitutil._diff_read["bytes"] >> 20), ("diff_cut_files", gitutil._diff_read["cut_files"]), ("diff_timeout", gitutil._diff_read["timeouts"])): if _v: |
