summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-10-20 21:46:32 +0000
committerClaude <noreply@anthropic.com>2026-10-20 21:46:32 +0000
commitc5bfe80e88f7ae781597b1368eb9dc90f0933d38 (patch)
treecd2c333d642a351313c7568bade355001b425cb8 /plugins
parent03bab72cbdce7039f452b15417de84989858b9e0 (diff)
parentc1785e2e56643aec21c99b3d879e9aef39e37d33 (diff)
Merge branch 'main' into mhegazy/sg-sdk-bootstrap-switchesmhegazy/sg-sdk-bootstrap-switches
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py81
-rw-r--r--plugins/security-guidance/hooks/gitutil.py316
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py58
-rw-r--r--plugins/security-guidance/tests/test_secret_named_metric.py94
-rw-r--r--plugins/security-guidance/tests/test_stop_diff_memory.py349
-rw-r--r--plugins/security-guidance/tests/test_stop_scope_metrics.py181
6 files changed, 1071 insertions, 8 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 02b073e8..d3dd2a51 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -8,6 +8,7 @@ to work without retargeting.
"""
import os
import subprocess
+import sys
import time
from _base import debug_log, _PV
@@ -112,8 +113,17 @@ def consume_stop_state(session_id, clear=True):
# State lost or overwritten since the last Stop (session_state).
"state_resets": state.get("state_resets", 0),
"state_overwrites": state.get("state_overwrites", 0),
+ "baseline_fail": state.get("baseline_fail") or 0,
}
+ # touched_paths is cleared per Stop, but one baseline can be
+ # reviewed by several Stops (rewakes). turn_touched keeps every path
+ # recorded since the baseline; only telemetry reads it.
+ turn = list(dict.fromkeys(
+ [p for p in state.get("turn_touched", []) if isinstance(p, str)]
+ + snap["touched_paths"]))[-200:]
+ snap["turn_touched"] = turn
if clear:
+ state["turn_touched"] = turn
state["touched_paths"] = []
state.pop("reviewed_diff_hash", None)
state.pop("state_resets", None)
@@ -126,9 +136,66 @@ def consume_stop_state(session_id, clear=True):
"baseline_kept": 0,
"fire_count": 0, "fire_count_expired": False, "previous_findings": [],
"reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0,
+ "baseline_fail": 0, "turn_touched": [],
}
+# Path names compare without case where the filesystem usually does.
+_FOLD_CASE = os.name == "nt" or sys.platform == "darwin"
+
+
+def _rel_in_repo(real_root, path):
+ """`path` relative to the repo root (a real path), or None when it lies
+ outside the repo."""
+ real = os.path.realpath(path)
+ try:
+ rel = os.path.relpath(real, real_root)
+ except ValueError: # another drive
+ return None
+ if rel == os.pardir or rel.startswith(os.pardir + os.sep):
+ return None
+ return rel.casefold() if _FOLD_CASE else rel
+
+
+def touched_scope(repo_root, cwd, touched_paths):
+ """Where the paths the session's edit tools wrote since the baseline lie:
+ (scope, repo-relative paths inside the repo). scope: 0 none recorded,
+ 1 all inside the reviewed repo, 2 some outside, 3 all outside. Relative
+ paths are read against `cwd`. The list holds the newest 200 paths, so
+ this is approximate past that. Telemetry only."""
+ root = os.path.realpath(repo_root)
+ inside, outside = set(), 0
+ for p in touched_paths:
+ rel = _rel_in_repo(root, os.path.join(cwd or root, p))
+ if rel is None:
+ outside += 1
+ else:
+ inside.add(rel)
+ if not touched_paths:
+ return 0, inside
+ if not outside:
+ return 1, inside
+ return (2 if inside else 3), inside
+
+
+def review_scope_code(repo_root, scope, inside, files, base_fail):
+ """One number, for telemetry only, saying how a Stop review relates to
+ what the session's edit tools wrote since the baseline:
+
+ base_fail * 100000 + scope * 10000 + min(untouched, 9999)
+
+ scope and inside: from touched_scope. untouched: how many of `files`
+ (repo-root-relative or absolute) no edit tool wrote. base_fail: 0 the
+ review diffed against a real turn-start snapshot, 1 and 2 see
+ last_baseline_fail, 3 there was no usable snapshot. Packed into one key
+ and sent even when 0, so a row without it was cut by the metrics key cap
+ or had no repo."""
+ root = os.path.realpath(repo_root)
+ untouched = sum(1 for f in files
+ if _rel_in_repo(root, os.path.join(root, f)) not in inside)
+ return int(base_fail or 0) * 100000 + scope * 10000 + min(untouched, 9999)
+
+
def record_reviewed_diff(session_id, diff_hash):
def _save(state):
state["reviewed_diff_hash"] = diff_hash
@@ -234,6 +301,14 @@ def get_baseline_file_content(session_id, file_path, cwd):
return None
+# 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
+# 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.
+last_baseline_fail = 0
+
+
def capture_git_baseline(cwd):
"""
Capture a git ref representing the current working tree state.
@@ -260,6 +335,8 @@ 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
+ last_baseline_fail = 0
try:
# Check if HEAD exists (i.e., repo has at least one commit)
head_check = subprocess.run(
@@ -281,6 +358,10 @@ def capture_git_baseline(cwd):
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:
+ last_baseline_fail = 1
+ else:
+ last_baseline_fail = 2
if sha:
return sha
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 8702e4da..4177a573 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -18,6 +18,9 @@ import contextlib
import os
import re
import subprocess
+import tempfile
+import threading
+import time
from _base import debug_log
@@ -823,6 +826,264 @@ def _is_ancestor(cwd, maybe_ancestor, descendant):
return False
+_DEFAULT_FILE_DIFF_BYTES = 4 * 1024 * 1024
+_LATE_FILE_DIFF_BYTES = 256 * 1024
+_LAST_FILE_DIFF_BYTES = 96 * 1024
+
+
+def _file_diff_cap():
+ """SG_MAX_FILE_DIFF_BYTES, or the default when it is unset, not a number
+ or not positive. Never below what a late file keeps, which is well above
+ what the review prompt takes of one file."""
+ try:
+ n = int(os.environ.get("SG_MAX_FILE_DIFF_BYTES", ""))
+ except ValueError:
+ return _DEFAULT_FILE_DIFF_BYTES
+ if n <= 0:
+ return _DEFAULT_FILE_DIFF_BYTES
+ return max(n, _LATE_FILE_DIFF_BYTES)
+
+
+# How much of one file's diff the Stop review keeps while it reads git's
+# output: this much from the start of the file's section, and as much again
+# of the added lines after that. The review prompt takes far less of a file
+# (DIFF_PER_FILE_BYTES); the rest is for filter_preexisting_from_diff, which
+# needs the removed and the added side of a rewritten file.
+MAX_FILE_DIFF_BYTES = _file_diff_cap()
+# Past this much kept in total, a further file keeps _LATE_FILE_DIFF_BYTES
+# the same two ways; past four times as much, _LAST_FILE_DIFF_BYTES from its
+# start, which is still more than the review prompt takes of one file.
+MAX_KEPT_DIFF_BYTES = 4 * MAX_FILE_DIFF_BYTES
+_SECTION_MARK = b"\ndiff --git "
+_MAX_HEADER_BYTES = 64 * 1024
+_CUT_MARK = b"\\ [cut by security-guidance: the rest of this file's diff was not read]\n"
+
+# What the last get_git_diff read, for the Stop hook's metrics: bytes of git
+# output, reviewable files whose diff was cut and the bytes cut from them,
+# and diffs that hit the timeout during this hook run.
+_diff_read = {"bytes": 0, "cut_files": 0, "cut_bytes": 0, "timeouts": 0}
+
+
+class _DiffKeeper:
+ """Takes `git diff` output as it arrives and keeps only what the review
+ can use: the header line of every file, and a bounded part of each file
+ parse_diff_into_files would keep. A turn that wrote large data files no
+ longer puts their whole diff in memory."""
+
+ def __init__(self):
+ self.parts = []
+ self.kept = 0
+ self.seen = 0
+ self.cut_files = 0
+ self.cut_bytes = 0
+ # Unhandled input. Starts as a newline that is not git's, so a header
+ # at the very start of the output is found like any other.
+ self._pending = b"\n"
+ self._at_start = True
+ self._reviewable = True
+ self._room = self._added_room = MAX_FILE_DIFF_BYTES
+ self._cut = False
+ self._ends_nl = True
+ # Past the cut: whether the next byte starts a line, and whether the
+ # line being read is an added one.
+ self._bol = True
+ self._in_added = False
+
+ def feed(self, data):
+ buf = self._pending + data
+ pos = 0
+ while True:
+ i = buf.find(_SECTION_MARK, pos)
+ if i < 0:
+ # Hold back a tail that could be the start of a header.
+ end = max(pos, len(buf) - len(_SECTION_MARK) + 1)
+ self._keep(buf, pos, end)
+ self._pending = buf[end:]
+ return
+ j = buf.find(b"\n", i + 1)
+ if j < 0 and len(buf) - i <= _MAX_HEADER_BYTES:
+ # The header line is not complete yet.
+ self._keep(buf, pos, i)
+ self._pending = buf[i:]
+ return
+ self._keep(buf, pos, i + 1)
+ if j >= 0:
+ self._begin(buf[i + 1:j])
+ pos = i + 1
+
+ def _begin(self, header):
+ """A new file's section starts with this `diff --git ` line."""
+ self._end_section()
+ text = header[len(_SECTION_MARK) - 1:].decode("utf-8", errors="replace")
+ paths = _parse_diff_header(text)
+ # A section the parser drops, or whose header it cannot read and only
+ # counts, keeps its header line.
+ self._reviewable = bool(paths) and _section_is_reviewable(
+ paths[1] or paths[0], paths[0])
+ if not self._reviewable:
+ self._room, self._added_room = len(header) + 1, 0
+ elif self.kept > 4 * MAX_KEPT_DIFF_BYTES:
+ self._room, self._added_room = max(len(header) + 1, _LAST_FILE_DIFF_BYTES), 0
+ elif self.kept > MAX_KEPT_DIFF_BYTES:
+ self._room = self._added_room = max(len(header) + 1, _LATE_FILE_DIFF_BYTES)
+ else:
+ self._room = self._added_room = MAX_FILE_DIFF_BYTES
+ self._cut = False
+
+ def _end_section(self):
+ if not self._ends_nl:
+ # Cut inside a line: end it, so what follows starts a line.
+ self._append(b"\n")
+ if self._cut:
+ self._append(_CUT_MARK)
+
+ def _append(self, piece):
+ self.parts.append(piece)
+ self.kept += len(piece)
+ self._ends_nl = piece.endswith(b"\n")
+
+ def _keep(self, buf, start, end):
+ if self._at_start and end > start:
+ self._at_start = False
+ start += 1
+ n = end - start
+ if n <= 0:
+ return
+ self.seen += n
+ take = min(n, self._room)
+ if take:
+ self._append(buf[start:start + take])
+ self._room -= take
+ if take == n or not self._reviewable:
+ return
+ if not self._cut:
+ self._cut = True
+ self.cut_files += 1
+ self._bol = self._ends_nl
+ self._in_added = False
+ self.cut_bytes += n - take - self._keep_added(buf, start + take, end)
+
+ def _keep_added(self, buf, pos, end):
+ """Past a file's cut, keep its added lines only, up to as much again.
+ A rewritten file lists every removed line before the first added one,
+ and the review is about the added ones. Returns the bytes kept."""
+ kept = 0
+ run = -1 # where a run of added lines not yet appended starts
+ while pos < end and self._added_room > 0:
+ if self._bol:
+ self._bol = False
+ self._in_added = buf.startswith(b"+", pos)
+ if self._in_added and run < 0 and not self._ends_nl:
+ self._append(b"\n")
+ if not self._in_added:
+ if run >= 0:
+ self._append(buf[run:pos])
+ run = -1
+ nxt = buf.find(b"\n+", pos, end)
+ if nxt < 0:
+ self._bol = buf.endswith(b"\n", pos, end)
+ break
+ pos = nxt + 1
+ self._bol = True
+ continue
+ nl = buf.find(b"\n", pos, end)
+ stop = end if nl < 0 else nl + 1
+ take = min(stop - pos, self._added_room)
+ if run < 0:
+ run = pos
+ self._added_room -= take
+ kept += take
+ self._bol = nl >= 0
+ if pos + take < stop:
+ self._append(buf[run:pos + take])
+ run = -1
+ pos = stop
+ if run >= 0:
+ self._append(buf[run:pos])
+ return kept
+
+ def result(self):
+ self._keep(self._pending, 0, len(self._pending))
+ self._pending = b""
+ self._end_section()
+ self._cut = False
+ return b"".join(self.parts)
+
+
+def _run_diff_bounded(cmd, timeout, **kwargs):
+ """subprocess.run(cmd, capture_output=True, timeout=timeout) for a
+ `git diff`, except that stdout goes through _DiffKeeper instead of being
+ held whole."""
+ keeper = _DiffKeeper()
+ deadline = time.monotonic() + timeout
+ try:
+ err = tempfile.TemporaryFile()
+ except OSError:
+ err = None
+ try:
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+ stderr=err if err is not None else subprocess.DEVNULL,
+ **kwargs)
+ failed = []
+ given_up = []
+
+ def _read():
+ try:
+ while not given_up:
+ chunk = p.stdout.read1(65536)
+ if not chunk or given_up:
+ break
+ keeper.feed(chunk)
+ except BaseException as e:
+ failed.append(e)
+
+ # Read on a thread, so the timeout holds even while something git
+ # started still has the pipe open after git itself is gone.
+ reader = threading.Thread(target=_read, daemon=True)
+ timed_out = False
+ try:
+ try:
+ reader.start()
+ except RuntimeError as e:
+ failed.append(e)
+ else:
+ reader.join(timeout)
+ timed_out = reader.is_alive()
+ if timed_out or failed:
+ p.kill()
+ try:
+ returncode = p.wait(max(deadline - time.monotonic(), 0.1))
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ finally:
+ if timed_out or failed or p.returncode is None:
+ # The reader may be left waiting on a pipe something else
+ # holds: it keeps nothing more, and the pipe stays its.
+ given_up.append(True)
+ p.kill()
+ p.wait()
+ if reader.ident is not None:
+ reader.join(1)
+ if not reader.is_alive():
+ p.stdout.close()
+ _diff_read["bytes"] += keeper.seen
+ if timed_out:
+ _diff_read["timeouts"] += 1
+ raise subprocess.TimeoutExpired(cmd, timeout)
+ if failed:
+ raise OSError(f"reading the diff failed: {failed[0]!r}")
+ stdout = keeper.result()
+ _diff_read["cut_files"] += keeper.cut_files
+ _diff_read["cut_bytes"] += keeper.cut_bytes
+ stderr = b""
+ if err is not None:
+ err.seek(0)
+ stderr = err.read(4096)
+ return subprocess.CompletedProcess(cmd, returncode, stdout, stderr)
+ finally:
+ if err is not None:
+ err.close()
+
def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_paths=None):
"""
@@ -838,6 +1099,9 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
cwd; absolute paths are converted, paths outside cwd are dropped).
`untracked_paths` (repo-root-relative) is forwarded to _temp_index so it
can add only those files instead of scanning the whole worktree.
+ The output is read through _DiffKeeper: files the review would drop come
+ back as their header line only, and a file's diff past
+ MAX_FILE_DIFF_BYTES is cut down to its added lines.
"""
pathspec = _diff_pathspec(cwd, paths)
if paths and not pathspec:
@@ -849,16 +1113,17 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
# core.quotePath=false comes from GIT_CMD globally (see definition).
cmd = [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
+ _diff_read.update(bytes=0, cut_files=0, cut_bytes=0)
try:
if untracked_paths is not None and not untracked_paths:
# Nothing to `add -N`, and the diff only reads the index.
- result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30)
+ result = _run_diff_bounded(cmd, 30, cwd=cwd)
else:
with _temp_index(cwd, untracked_paths) as env:
# env is None when there is no index (bare repo / not a repo)
# or no copy slot — diff still runs, just without
# untracked-file support.
- result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30, env=env)
+ result = _run_diff_bounded(cmd, 30, cwd=cwd, env=env)
if result.returncode != 0:
debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}")
return None
@@ -994,6 +1259,42 @@ def _is_secret_shaped(file_path):
return False
+# Data files whose name says they hold secrets (`secrets.yml`,
+# `client_secret.json`). They are reviewed like any other data file; the Stop
+# hook only counts how many are in its review set (never the names), to show
+# how common they are.
+_SECRET_NAMED_STEMS = frozenset((
+ 'secret', 'secrets', 'credential', 'credentials',
+ 'client_secret', 'client_secrets', 'client-secret', 'client-secrets',
+ 'service-account', 'service_account', 'serviceaccount',
+ 'service-account-key', 'service_account_key', 'serviceaccountkey',
+))
+_SECRET_NAMED_DATA_EXTENSIONS = frozenset((
+ '.json', '.yaml', '.yml', '.toml', '.properties', '.tfvars',
+))
+# `secrets.example.yml` is a placeholder and `secrets.enc.yaml` is ciphertext.
+_NOT_SECRET_NAME_PARTS = frozenset((
+ 'example', 'sample', 'template', 'tmpl', 'dist', 'schema',
+ 'enc', 'encrypted', 'sops',
+))
+
+
+def _is_secret_named(file_path):
+ base = os.path.basename(file_path.replace("\\", "/")).lower()
+ parts = base.lstrip('.').split('.')
+ if len(parts) < 2 or '.' + parts[-1] not in _SECRET_NAMED_DATA_EXTENSIONS:
+ return False
+ if _NOT_SECRET_NAME_PARTS.intersection(parts[1:-1]):
+ return False
+ stem = parts[0]
+ # Google's OAuth download is `client_secret_<client id>.json`.
+ return stem in _SECRET_NAMED_STEMS or stem.startswith('client_secret_')
+
+
+def count_secret_named(diff_files):
+ return sum(1 for file_path, _ in diff_files if _is_secret_named(file_path))
+
+
# Path tokens that bump a file's review priority when a commit exceeds
# MAX_DIFF_FILES and we have to pick a subset. These are exactly the surfaces
# single-shot and agentic reviews disagree on most (auth, routing, IPC,
@@ -1176,6 +1477,13 @@ def _parse_diff_header(header):
_unparsed_diff_headers = set()
+def _section_is_reviewable(file_path, old_path):
+ """Whether a diff section is sent for review: a source file, and not one
+ renamed away from a secret-shaped name, which still carries the secret's
+ content."""
+ return _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path)
+
+
def _iter_diff_sections(diff_output):
"""Yield (new_path, old_path, lines after the header line) per file section."""
for section in _DIFF_SECTION_RE.split(diff_output)[1:]:
@@ -1197,7 +1505,7 @@ def extract_file_paths_from_diff(diff_output):
return [
file_path for file_path, old_path, _ in _iter_diff_sections(diff_output)
- if _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path)
+ if _section_is_reviewable(file_path, old_path)
]
@@ -1213,7 +1521,7 @@ def parse_diff_into_files(diff_output):
for file_path, old_path, lines in _iter_diff_sections(diff_output):
# Filter to source code files only. A rename away from a secret-shaped
# name still carries the secret's content, so the old name counts too.
- if not _is_reviewable_source(file_path) or _skip_secret_shaped(old_path):
+ if not _section_is_reviewable(file_path, old_path):
continue
# Extract the diff content (from first @@ onwards)
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 3c38e664..99b00ce0 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -125,6 +125,7 @@ from diffstate import ( # noqa: E402,F401
_reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas,
_full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight,
UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set,
+ touched_scope, review_scope_code,
baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS,
KEPT_NO_CAPTURE, KEPT_UNREVIEWED,
)
@@ -134,6 +135,7 @@ from reporesolve import ( # noqa: E402,F401
toplevel_from_command, repo_containing_commit, scan_roots,
resolve_repo_root, save_repo_hint, load_repo_hint,
)
+import diffstate # noqa: E402 module ref for last_baseline_fail
import gitutil # noqa: E402 module ref for per-run counters
import llm # noqa: E402 module ref for reassignable globals (_last_call_claude_http_error etc.)
from llm import ( # noqa: E402,F401
@@ -645,6 +647,14 @@ def extract_content_from_input(tool_name, tool_input, tool_response=None):
# Hook handlers
# =====================================================================
+def _store_baseline_fail(state, fail):
+ """Keep diffstate.last_baseline_fail next to the baseline_sha it describes."""
+ if fail:
+ state["baseline_fail"] = fail
+ else:
+ state.pop("baseline_fail", None)
+
+
def handle_user_prompt_submit(input_data):
"""
Handle UserPromptSubmit — capture git baseline SHA.
@@ -702,6 +712,7 @@ def handle_user_prompt_submit(input_data):
sha, untracked_now = _capture(cwd)
else:
no_repo = True
+ baseline_fail = diffstate.last_baseline_fail
# The repo root rides on the same git call as HEAD.
root, head = (None, None) if no_repo else _git_toplevel_and_head(cwd)
if sha and not head:
@@ -738,6 +749,8 @@ def handle_user_prompt_submit(input_data):
if sha:
state["baseline_sha"] = sha
state["head_at_capture"] = head
+ state.pop("turn_touched", None)
+ _store_baseline_fail(state, baseline_fail)
# A Stop review that ends up in another checkout does not use
# this baseline.
state["baseline_root"] = root
@@ -2285,6 +2298,14 @@ def handle_push_sweep_posttooluse(input_data):
hook_event_name="PostToolUse")
sys.exit(2)
+def _stop_diff_truncated():
+ """Bytes of reviewable diff the Stop review did not send: cut while
+ reading git's output, plus what the prompt caps dropped after that.
+ As the metric to emit, or nothing when there were none."""
+ n = llm._last_review_truncated_bytes + gitutil._diff_read["cut_bytes"]
+ return {"diff_truncated": n} if n else {}
+
+
def handle_stop_hook(input_data):
"""
Handle the Stop hook — final security check using git diff.
@@ -2446,6 +2467,23 @@ def handle_stop_hook(input_data):
_TAIL_METRICS["bl_origin"] = baseline_origin_metric(origin, snap["baseline_kept"])
v2_metrics = {**res_metrics, **v2_metrics}
+ # Count-only view of how the review set relates to what the session's
+ # edit tools wrote. Only when a repo was read; never fails the review.
+ def _note_scope(files):
+ try:
+ if "scope" not in _scope:
+ _scope["scope"] = touched_scope(
+ repo_root, input_data.get("cwd", ""), snap["turn_touched"])
+ # -1: the stored baseline could not be used in this repo.
+ fail = (3 if v2_metrics.get("changed_since_count") == -1
+ else snap.get("baseline_fail"))
+ _TAIL_METRICS["review_scope"] = review_scope_code(
+ repo_root, *_scope["scope"], files, fail)
+ except Exception as e:
+ debug_log(f"review scope telemetry skipped: {e}")
+ _scope = {}
+ if v2_metrics.get("dirty_now_count", -1) >= 0:
+ _note_scope(review_paths)
if not review_paths:
debug_log("Stop hook: empty review set")
_skip(9, touched_paths_count=len(touched_paths))
@@ -2465,6 +2503,13 @@ 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),
+ ("diff_cut_files", gitutil._diff_read["cut_files"]),
+ ("diff_timeout", gitutil._diff_read["timeouts"])):
+ if _v:
+ _TAIL_METRICS[_k] = _v
# filter_preexisting_from_diff needs a resolvable pre-turn ref; fall
# back to HEAD when UPS never captured a baseline (print mode).
if not baseline_sha:
@@ -2504,8 +2549,13 @@ def handle_stop_hook(input_data):
# Filter out pre-existing content from file rewrites
diff_files = filter_preexisting_from_diff(diff_files, cwd, baseline_sha)
+ if "scope" in _scope:
+ _note_scope([fp for fp, _ in diff_files])
debug_log(f"Stop hook: reviewing {len(diff_files)} changed files (standard diff)")
+ secret_named = gitutil.count_secret_named(diff_files)
+ if secret_named:
+ _TAIL_METRICS["secret_named_reviewed"] = secret_named
import time as _time
stop_review_start = _time.time()
@@ -2550,6 +2600,7 @@ def handle_stop_hook(input_data):
]
# Update baseline so next stop hook iteration only sees new changes
new_sha = None if is_subagent else capture_git_baseline(cwd)
+ new_base_fail = diffstate.last_baseline_fail
new_untracked_baseline = _list_untracked(cwd) if new_sha else None
# After a baseline from another checkout, the rest of it is replaced
# too, below.
@@ -2579,6 +2630,7 @@ def handle_stop_hook(input_data):
if new_sha:
state["baseline_sha"] = new_sha
state["untracked_at_baseline"] = new_untracked_baseline
+ _store_baseline_fail(state, new_base_fail)
state["baseline_root"] = repo_root
state.pop("baseline_kept", None)
if foreign_baseline:
@@ -2613,8 +2665,7 @@ def handle_stop_hook(input_data):
"touched_paths_count": len(touched_paths),
"review_ms": review_ms,
"fire_index": fire_index,
- **({"diff_truncated": llm._last_review_truncated_bytes}
- if llm._last_review_truncated_bytes else {}),
+ **_stop_diff_truncated(),
**({"repo_resolution": repo_res} if res_metrics else {}),
**sweep_trimmed,
**({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)}
@@ -2651,8 +2702,7 @@ def handle_stop_hook(input_data):
"review_ms": review_ms,
"fire_index": fire_index,
**({"api_error": llm._last_call_claude_http_error} if llm._last_call_claude_http_error is not None else {}),
- **({"diff_truncated": llm._last_review_truncated_bytes}
- if llm._last_review_truncated_bytes else {}),
+ **_stop_diff_truncated(),
**v2_metrics,
**({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)}
if gitutil._unparsed_diff_headers else {}),
diff --git a/plugins/security-guidance/tests/test_secret_named_metric.py b/plugins/security-guidance/tests/test_secret_named_metric.py
new file mode 100644
index 00000000..14d71923
--- /dev/null
+++ b/plugins/security-guidance/tests/test_secret_named_metric.py
@@ -0,0 +1,94 @@
+"""The Stop review counts the data files it sends whose name says they hold
+secrets. Measurement only: the files are reviewed as before."""
+import pytest
+
+from conftest import (
+ STUB_VULN, VULN_PY, make_repo, metrics_of, run_hook, stop_payload, ups_payload,
+)
+
+import gitutil
+
+
+@pytest.mark.parametrize("path", [
+ "secrets.yml",
+ "config/secrets.yaml",
+ "secrets.prod.json",
+ ".secrets.toml",
+ "Secrets.YML",
+ "credentials.json",
+ "client_secret.json",
+ "keys/service-account.json",
+ "service_account.json",
+ "terraform/secrets.tfvars",
+ "client-secret.json",
+ "client_secret_1234-abc.apps.googleusercontent.com.json",
+ "serviceAccountKey.json",
+])
+def test_secret_named_data_files(path):
+ assert gitutil._is_secret_named(path)
+
+
+@pytest.mark.parametrize("path", [
+ "secrets.py",
+ "src/credentials.ts",
+ "secrets_manager.yaml",
+ "app-secrets.json",
+ "docs/secrets.md",
+ "secrets",
+ "config.yaml",
+ "package.json",
+ "secrets/config.yaml",
+ "secrets.example.yml",
+ "credentials.sample.json",
+ "secrets.schema.json",
+ "secrets.enc.yaml",
+ "secrets.sops.yaml",
+ ".json",
+])
+def test_other_files_are_not_counted(path):
+ assert not gitutil._is_secret_named(path)
+
+
+def _review(tmp_path, hook_env, files):
+ repo = make_repo(tmp_path / "repo")
+ run_hook(ups_payload(repo), hook_env)
+ for name, body in files.items():
+ (repo / name).write_text(body)
+ return run_hook(stop_payload(repo), hook_env)
+
+
+def test_stop_hook_counts_secret_named_files_and_still_reviews_them(tmp_path, hook_env, stub_api):
+ _rc, stdout, _err = _review(tmp_path, hook_env, {
+ "secrets.yml": "db:\n password: example\n",
+ "credentials.json": '{"token": "example"}\n',
+ "app.py": "print(1)\n",
+ })
+ m = metrics_of(stdout)
+ assert m.get("secret_named_reviewed") == 2
+ assert m.get("files_reviewed") == 3
+ assert "/v1/messages" in stub_api.calls
+
+
+def test_count_is_on_the_findings_row_too(tmp_path, hook_env, stub_api):
+ stub_api.vulns = [STUB_VULN]
+ rc, stdout, _err = _review(tmp_path, hook_env, {
+ "secrets.yml": "db:\n password: example\n",
+ "app.py": VULN_PY,
+ })
+ assert rc == 2
+ assert metrics_of(stdout).get("secret_named_reviewed") == 1
+
+
+def test_no_key_when_no_such_file_is_reviewed(tmp_path, hook_env, stub_api):
+ _rc, stdout, _err = _review(tmp_path, hook_env, {"app.py": "print(1)\n"})
+ m = metrics_of(stdout)
+ assert m.get("files_reviewed") == 1
+ assert "secret_named_reviewed" not in m
+
+
+def test_count_is_on_the_failed_review_row(tmp_path, hook_env, stub_api):
+ stub_api.status = 500
+ _rc, stdout, _err = _review(tmp_path, hook_env, {"secrets.yml": "a: b\n"})
+ m = metrics_of(stdout)
+ assert m.get("review_failed") is True
+ assert m.get("secret_named_reviewed") == 1
diff --git a/plugins/security-guidance/tests/test_stop_diff_memory.py b/plugins/security-guidance/tests/test_stop_diff_memory.py
new file mode 100644
index 00000000..31a524f9
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_diff_memory.py
@@ -0,0 +1,349 @@
+"""The Stop review reads `git diff` output without holding all of it: files it
+would drop come back as a header line, and one file's diff is cut at a cap."""
+import random
+import subprocess
+import sys
+import tempfile
+import time
+import tracemalloc
+
+import pytest
+
+from conftest import (
+ GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload,
+ ups_payload,
+)
+
+import gitutil
+
+
+@pytest.fixture(autouse=True)
+def _fresh_read_state():
+ yield
+ gitutil._unparsed_diff_headers.clear()
+ gitutil._diff_read.update(bytes=0, cut_files=0, cut_bytes=0, timeouts=0)
+
+
+def _rewrite(path, removed, added):
+ return (f"diff --git a/{path} b/{path}\n"
+ "index 1111111..2222222 100644\n"
+ f"--- a/{path}\n+++ b/{path}\n"
+ f"@@ -1,{len(removed)} +1,{len(added)} @@\n"
+ + "".join(f"-{ln}\n" for ln in removed)
+ + "".join(f"+{ln}\n" for ln in added))
+
+
+@pytest.fixture
+def git_env(tmp_path, monkeypatch):
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ for k, v in GIT_ENV.items():
+ monkeypatch.setenv(k, v)
+
+
+def _section(path, body_lines, old=None):
+ return (f"diff --git a/{old or path} b/{path}\n"
+ "index 1111111..2222222 100644\n"
+ f"--- a/{old or path}\n+++ b/{path}\n"
+ f"@@ -1,2 +1,{len(body_lines)} @@\n"
+ + "".join(f"+{ln}\n" for ln in body_lines))
+
+
+def _keep(raw, chunk_sizes):
+ keeper = gitutil._DiffKeeper()
+ pos = 0
+ while pos < len(raw):
+ n = next(chunk_sizes)
+ keeper.feed(raw[pos:pos + n])
+ pos += n
+ return keeper, keeper.result()
+
+
+def _sizes(*cycle):
+ while True:
+ yield from cycle
+
+
+MIXED = (
+ _section("app.py", ["import os", "os.system(cmd)"])
+ + _section("notes.txt", ["plain text", "diff --git a/fake.py b/fake.py is only text here"])
+ + _section("web/café.js", ["eval(x)"])
+ + 'diff --git "a/we\\"ird.py" "b/we\\"ird.py"\n--- "a/we\\"ird.py"\n+++ "b/we\\"ird.py"\n@@ -1 +1 @@\n+x = 1\n'
+ + "diff --git nonsense header\n@@ -1 +1 @@\n+y\n"
+ + _section("new_name.py", ["z = 2"], old="old_name.txt")
+ + _section("data.csv", ["1,2,3"] * 50)
+ + _section("last.sh", ["rm -rf $1"])
+).encode()
+
+
+class TestDiffKeeper:
+ @pytest.mark.parametrize("seed", range(40))
+ def test_same_files_as_reading_it_whole_at_any_chunking(self, seed):
+ rng = random.Random(seed)
+ sizes = iter(lambda: rng.choice([1, 2, 3, 7, 11, 12, 13, 64, 500]), None)
+ gitutil._unparsed_diff_headers.clear()
+ want = gitutil.parse_diff_into_files(MIXED.decode())
+ want_unparsed = set(gitutil._unparsed_diff_headers)
+ gitutil._unparsed_diff_headers.clear()
+ keeper, kept = _keep(MIXED, sizes)
+ assert gitutil.parse_diff_into_files(kept.decode()) == want
+ assert gitutil._unparsed_diff_headers == want_unparsed
+ assert [p for p, _ in want] == ["app.py", "web/café.js", 'we"ird.py', "new_name.py", "last.sh"]
+ assert keeper.seen == len(MIXED)
+ assert keeper.cut_files == 0
+
+ def test_dropped_file_keeps_its_header_line_only(self):
+ _, kept = _keep(MIXED, _sizes(4096))
+ text = kept.decode()
+ assert "diff --git a/notes.txt b/notes.txt\n" in text
+ assert "plain text" not in text and "1,2,3" not in text
+ assert len(kept) < len(MIXED)
+
+ def test_untouched_when_every_file_is_reviewable_and_small(self):
+ raw = (_section("a.py", ["x"]) + _section("b.js", ["y"])).encode()
+ assert _keep(raw, _sizes(5))[1] == raw
+
+ @pytest.mark.parametrize("chunk", [1, 17, 4096])
+ def test_large_file_is_cut_and_the_next_file_survives(self, monkeypatch, chunk):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300)
+ big = _section("big.json", ["k" * 37] * 100)
+ raw = (big + _section("after.py", ["import os"])).encode()
+ keeper, kept = _keep(raw, _sizes(chunk))
+ files = dict(gitutil.parse_diff_into_files(kept.decode()))
+ assert set(files) == {"big.json", "after.py"}
+ assert files["after.py"] == dict(gitutil.parse_diff_into_files(raw.decode()))["after.py"]
+ # The start of the section, then as much again of its added lines.
+ assert 300 < len(files["big.json"]) <= 2 * 300 + len(gitutil._CUT_MARK) + 2
+ assert keeper.cut_files == 1
+ assert keeper.cut_bytes == len(big) - 2 * 300
+
+ def test_cut_file_says_so_on_its_last_line(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300)
+ raw = (_section("big.json", ["k" * 37] * 100) + _section("after.py", ["x"])).encode()
+ _, kept = _keep(raw, _sizes(64))
+ files = dict(gitutil.parse_diff_into_files(kept.decode()))
+ assert files["big.json"].endswith(gitutil._CUT_MARK.decode())
+ assert "cut by security-guidance" not in files["after.py"]
+ assert kept.count(gitutil._CUT_MARK) == 1
+
+ @pytest.mark.parametrize("chunk", [1, 23, 4096])
+ def test_rewrite_past_the_cap_keeps_its_added_lines(self, monkeypatch, chunk):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 400)
+ raw = (_rewrite("views.py", ["old line %03d" % i for i in range(200)],
+ ["os.system(cmd)"] + ["new line %03d" % i for i in range(200)])
+ + _section("after.py", ["x"])).encode()
+ keeper, kept = _keep(raw, _sizes(chunk))
+ body = dict(gitutil.parse_diff_into_files(kept.decode()))["views.py"]
+ assert "+os.system(cmd)\n" in body
+ assert "-old line 199" not in body
+ past = body[400:]
+ assert all(ln.startswith(("+", "\\")) for ln in past.splitlines()[1:])
+ assert len(body) <= 2 * 400 + len(gitutil._CUT_MARK) + 2
+ assert keeper.cut_files == 1
+
+ def test_dropped_large_file_is_not_counted_as_cut(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300)
+ raw = (_section("big.log", ["k" * 37] * 100) + _section("after.py", ["x"])).encode()
+ keeper, kept = _keep(raw, _sizes(64))
+ assert keeper.cut_files == 0 and keeper.cut_bytes == 0
+ assert [p for p, _ in gitutil.parse_diff_into_files(kept.decode())] == ["after.py"]
+
+ def test_renamed_from_a_secret_shaped_name_keeps_its_header_only(self):
+ raw = (_section("config.py", ["TOKEN = 'abc'"], old=".env")
+ + _section("after.py", ["x"])).encode()
+ want = gitutil.parse_diff_into_files(raw.decode())
+ _, kept = _keep(raw, _sizes(64))
+ assert gitutil.parse_diff_into_files(kept.decode()) == want
+ assert [p for p, _ in want] == ["after.py"]
+ assert b"TOKEN" not in kept
+
+ def test_past_the_total_later_files_keep_less_and_less(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 2000)
+ monkeypatch.setattr(gitutil, "MAX_KEPT_DIFF_BYTES", 3000)
+ monkeypatch.setattr(gitutil, "_LATE_FILE_DIFF_BYTES", 200)
+ monkeypatch.setattr(gitutil, "_LAST_FILE_DIFF_BYTES", 120)
+ raw = "".join(_section(f"f{i}.py", ["v" * 30] * 400) for i in range(40)).encode()
+ keeper, kept = _keep(raw, _sizes(333))
+ files = gitutil.parse_diff_into_files(kept.decode())
+ assert [p for p, _ in files] == [f"f{i}.py" for i in range(40)]
+ sizes = [len(body) for _, body in files]
+ mark = len(gitutil._CUT_MARK) + 2
+ assert sizes[0] > 2000 and sizes[0] <= 4000 + mark
+ assert 200 < sizes[5] <= 400 + mark
+ assert sizes[-1] <= 120 + mark
+ assert sizes[0] > sizes[5] > sizes[-1]
+ assert keeper.cut_files == 40
+ # Everything not kept is counted; a cut may add a newline or two.
+ from_git = len(kept) - 40 * len(gitutil._CUT_MARK)
+ assert from_git - 80 <= len(raw) - keeper.cut_bytes <= from_git
+
+ def test_output_cut_inside_a_line_ends_with_a_newline(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300)
+ raw = _rewrite("big.json", ["k" * 37] * 100, []).encode()
+ keeper, kept = _keep(raw, _sizes(64))
+ assert kept == raw[:300] + b"\n" + gitutil._CUT_MARK
+ assert keeper.cut_bytes == len(raw) - 300
+ both = kept + _section("next.py", ["x"]).encode()
+ assert [p for p, _ in gitutil.parse_diff_into_files(both.decode())] == ["big.json", "next.py"]
+
+ def test_empty_output(self):
+ keeper, kept = _keep(b"", _sizes(1))
+ assert kept == b"" and keeper.seen == 0
+
+
+class TestRunDiffBounded:
+ def test_returns_what_run_would(self):
+ code = ("import sys; sys.stdout.buffer.write(b'diff --git a/a.py b/a.py\\n@@ -1 +1 @@\\n+x\\n'); "
+ "sys.stderr.write('warn'); sys.exit(3)")
+ r = gitutil._run_diff_bounded([sys.executable, "-c", code], 30)
+ assert r.returncode == 3
+ assert r.stdout == b"diff --git a/a.py b/a.py\n@@ -1 +1 @@\n+x\n"
+ assert r.stderr == b"warn"
+
+ def test_timeout_kills_and_raises(self):
+ code = "import sys, time; sys.stdout.write('x' * 100000); sys.stdout.flush(); time.sleep(60)"
+ before = gitutil._diff_read["timeouts"]
+ with pytest.raises(subprocess.TimeoutExpired):
+ gitutil._run_diff_bounded([sys.executable, "-c", code], 0.5)
+ assert gitutil._diff_read["timeouts"] == before + 1
+
+ def test_timeout_holds_while_another_process_keeps_the_pipe_open(self):
+ # What a `git diff` that started a fetch looks like: the program is
+ # gone, something it started still holds its stdout.
+ code = ("import subprocess, sys; "
+ "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(8)']); "
+ "sys.stdout.write('x'); sys.stdout.flush()")
+ before = gitutil._diff_read["timeouts"]
+ t0 = time.monotonic()
+ with pytest.raises(subprocess.TimeoutExpired):
+ gitutil._run_diff_bounded([sys.executable, "-c", code], 1)
+ assert time.monotonic() - t0 < 5
+ assert gitutil._diff_read["timeouts"] == before + 1
+
+ def test_a_timed_out_read_still_reports_its_size(self):
+ code = "import sys, time; sys.stdout.write('x' * 300000); sys.stdout.flush(); time.sleep(60)"
+ with pytest.raises(subprocess.TimeoutExpired):
+ gitutil._run_diff_bounded([sys.executable, "-c", code], 1)
+ assert gitutil._diff_read["bytes"] >= 200000
+
+ def test_a_read_that_breaks_is_an_error_not_a_short_diff(self, monkeypatch):
+ def broken(self, data):
+ raise MemoryError("no room")
+ monkeypatch.setattr(gitutil._DiffKeeper, "feed", broken)
+ code = "import sys; sys.stdout.write('diff --git a/a.py b/a.py\\n' * 50000)"
+ t0 = time.monotonic()
+ with pytest.raises(OSError):
+ gitutil._run_diff_bounded([sys.executable, "-c", code], 30)
+ assert time.monotonic() - t0 < 10
+
+ def test_no_thread_to_read_with_is_an_error(self, monkeypatch):
+ def refuse(self):
+ raise RuntimeError("can't start new thread")
+ monkeypatch.setattr(gitutil.threading.Thread, "start", refuse)
+ with pytest.raises(OSError):
+ gitutil._run_diff_bounded([sys.executable, "-c", "print('x')"], 30)
+
+ def test_missing_program_raises_like_run(self):
+ with pytest.raises(FileNotFoundError):
+ gitutil._run_diff_bounded(["sg-no-such-program"], 5)
+
+
+class TestGetGitDiff:
+ def test_large_data_file_is_not_held(self, tmp_path, git_env):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ (repo / "app.py").write_text(VULN_PY)
+ line = "generated text line that is about eighty bytes long once the number is on it %07d\n"
+ (repo / "gen.txt").write_text("".join(line % i for i in range(250000)))
+ paths = [str(repo / "app.py"), str(repo / "gen.txt")]
+ tracemalloc.start()
+ try:
+ diff = gitutil.get_git_diff(str(repo), "HEAD", paths=paths, untracked_paths=["gen.txt"])
+ peak = tracemalloc.get_traced_memory()[1]
+ finally:
+ tracemalloc.stop()
+ assert [p for p, _ in gitutil.parse_diff_into_files(diff)] == ["app.py"]
+ assert "diff --git a/gen.txt b/gen.txt\n" in diff and "generated text" not in diff
+ assert gitutil._diff_read["bytes"] > 20 * 1024 * 1024
+ assert gitutil._diff_read["cut_files"] == 0
+ # Reading it whole took several times the 20 MB of output.
+ assert peak < 8 * 1024 * 1024
+
+ def test_timeout_is_none(self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+
+ def slow(cmd, timeout, **kwargs):
+ raise subprocess.TimeoutExpired(cmd, timeout)
+
+ monkeypatch.setattr(gitutil, "_run_diff_bounded", slow)
+ assert gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "app.py")],
+ untracked_paths=[]) is None
+
+ @pytest.mark.parametrize("value, want", [
+ ("", 4 * 1024 * 1024), ("junk", 4 * 1024 * 1024), ("0", 4 * 1024 * 1024),
+ ("-5", 4 * 1024 * 1024), ("1000", 256 * 1024), ("1000000", 1000000)])
+ def test_cap_setting_cannot_break_the_read(self, monkeypatch, value, want):
+ monkeypatch.setenv("SG_MAX_FILE_DIFF_BYTES", value)
+ assert gitutil._file_diff_cap() == want
+
+ def test_rewritten_large_file_still_shows_what_is_new(self, tmp_path, git_env):
+ body = "".join(f"def handler_{i}(request):\n return render(request, 'page_{i}.html')\n"
+ for i in range(18000))
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "views.py").write_bytes(body.replace("\n", "\r\n").encode())
+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True)
+ subprocess.run(["git", "commit", "-q", "-m", "views"], cwd=repo, check=True)
+ assert (repo / "views.py").stat().st_size > 1200000
+ (repo / "views.py").write_bytes(("import os\nos.system(request.GET['cmd'])\n" + body).encode())
+ diff = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "views.py")], untracked_paths=[])
+ assert gitutil._diff_read["cut_files"] == 0
+ files = gitutil.filter_preexisting_from_diff(
+ gitutil.parse_diff_into_files(diff), str(repo), "HEAD")
+ assert "+os.system(request.GET['cmd'])" in files[0][1][:2000]
+
+ def test_rewrite_past_the_cap_still_shows_what_is_new(self, tmp_path, git_env, monkeypatch):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 200000)
+ body = "".join(f"def handler_{i}(request):\n return render(request, 'page_{i}.html')\n"
+ for i in range(18000))
+ repo = make_repo(tmp_path / "repo", {"views.py": body.replace("\n", "\r\n")})
+ (repo / "views.py").write_bytes(("import os\nos.system(request.GET['cmd'])\n" + body).encode())
+ diff = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "views.py")], untracked_paths=[])
+ assert gitutil._diff_read["cut_files"] == 1
+ assert len(diff) < 2 * 200000 + 1000
+ files = gitutil.filter_preexisting_from_diff(
+ gitutil.parse_diff_into_files(diff), str(repo), "HEAD")
+ assert "+os.system(request.GET['cmd'])" in files[0][1][:2000]
+
+ def test_failed_diff_is_still_none(self, tmp_path, git_env):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ assert gitutil.get_git_diff(str(repo), "0" * 40, paths=[str(repo / "app.py")],
+ untracked_paths=[]) is None
+
+
+class TestStopHook:
+ def test_reports_what_it_read_and_reviews_the_source(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "gen.txt").write_text("some generated text\n" * 150000)
+ (repo / "big.json").write_text('"k": "some generated value",\n' * 20000)
+ env = {**hook_env, "SG_MAX_FILE_DIFF_BYTES": "1000"}
+ rc, so, se = run_hook(stop_payload(repo), env)
+ m = metrics_of(so)
+ assert not m.get("skipped"), m
+ assert m["files_reviewed"] == 2
+ assert m["diff_mb"] == 3
+ assert m["diff_cut_files"] == 1
+ # 256 KiB from the start and as much again of added lines were read;
+ # the prompt took 80,000 bytes of that.
+ assert m["diff_truncated"] > 20000 * 29 - 80000 - 1000
+ assert "diff_timeout" not in m
+ assert stub_api.calls
+
+ def test_small_turn_reports_nothing_new(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ m = metrics_of(run_hook(stop_payload(repo), hook_env)[1])
+ assert m["files_reviewed"] == 1
+ assert not {"diff_mb", "diff_cut_files", "diff_timeout"} & set(m)
diff --git a/plugins/security-guidance/tests/test_stop_scope_metrics.py b/plugins/security-guidance/tests/test_stop_scope_metrics.py
new file mode 100644
index 00000000..c65103b6
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_scope_metrics.py
@@ -0,0 +1,181 @@
+"""Stop rows carry one count-only number, `review_scope`, saying how the
+reviewed files relate to what the session's edit tools wrote and whether the
+turn-start snapshot was a real one."""
+import os
+import shutil
+
+import pytest
+
+from conftest import (
+ STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload,
+ ups_payload,
+)
+
+import diffstate
+
+needs_sh = pytest.mark.skipif(os.name == "nt", reason="uses a /bin/sh git shim")
+
+
+def _stop(repo, env):
+ return metrics_of(run_hook(stop_payload(repo), env)[1])
+
+
+def _turn(repo, env, edits=(), during=None):
+ run_hook(ups_payload(repo), env)
+ for path in edits:
+ run_hook(edit_payload(repo, path), env)
+ if during:
+ during()
+ return _stop(repo, env)
+
+
+def _no_stash_env(tmp_path, hook_env):
+ """An env whose `git stash` fails, like a snapshot that could not be taken."""
+ bindir = tmp_path / "bin"
+ bindir.mkdir()
+ shim = bindir / "git"
+ shim.write_text(
+ '#!/bin/sh\nfor a in "$@"; do [ "$a" = stash ] && exit 1; done\n'
+ f'exec "{shutil.which("git")}" "$@"\n')
+ shim.chmod(0o755)
+ return {**hook_env, "PATH": f"{bindir}{os.pathsep}{hook_env['PATH']}"}
+
+
+class TestScope:
+ def test_edits_outside_repo_review_of_a_file_they_did_not_write(self, hook_env, workspace):
+ ws, repo = workspace
+ m = _turn(repo, hook_env, edits=[ws / "notes.md"],
+ during=lambda: (repo / "other.py").write_text(VULN_PY))
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 30001
+
+ def test_edit_inside_repo(self, hook_env, workspace):
+ _, repo = workspace
+ m = _turn(repo, hook_env, edits=[repo / "app.py"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 10000
+
+ def test_relative_edit_path_is_read_against_the_session_cwd(self, hook_env, workspace):
+ _, repo = workspace
+ m = _turn(repo, hook_env, edits=["app.py"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 10000
+
+ def test_mixed_edits_and_a_file_changed_by_other_means(self, hook_env, workspace):
+ ws, repo = workspace
+
+ def during():
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "gen.py").write_text(VULN_PY)
+ m = _turn(repo, hook_env, edits=[ws / "notes.md", repo / "app.py"], during=during)
+ assert m["files_reviewed"] == 2 and m["review_scope"] == 20001
+
+ def test_no_edit_tool_paths(self, hook_env, workspace):
+ _, repo = workspace
+ m = _turn(repo, hook_env, during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 1
+
+ def test_outside_only_turn_with_nothing_to_review(self, hook_env, workspace):
+ ws, repo = workspace
+ m = _turn(repo, hook_env, edits=[ws / "notes.md"])
+ assert m["skipped"] is True and m["review_scope"] == 30000
+
+ def test_skipped_review_counts_over_the_review_set(self, hook_env, workspace):
+ _, repo = workspace
+ m = _turn(repo, hook_env, during=lambda: (repo / "notes.txt").write_text("x\n"))
+ assert m["skipped"] is True and m["review_scope"] == 1
+
+ def test_second_review_of_the_same_turn_still_knows_the_edits(self, hook_env, workspace):
+ _, repo = workspace
+ m = _turn(repo, hook_env, edits=[repo / "app.py"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert m["review_scope"] == 10000
+ m = _stop(repo, hook_env) # a rewake: no new prompt, same baseline
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 10000
+ # The next prompt starts a new count.
+ m = _turn(repo, hook_env, during=lambda: (repo / "gen.py").write_text(VULN_PY))
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 1
+
+ def test_no_key_outside_a_repo(self, hook_env, tmp_path):
+ plain = tmp_path / "plain"
+ plain.mkdir()
+ m = _turn(plain, hook_env, edits=[plain / "a.py"],
+ during=lambda: (plain / "a.py").write_text(VULN_PY))
+ assert m["skipped"] is True and "review_scope" not in m
+
+ def test_unreadable_path_does_not_stop_the_review(self, hook_env, workspace):
+ _, repo = workspace
+ m = _turn(repo, hook_env, edits=[str(repo / "a\ud800b.py"), repo / "app.py"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert m["files_reviewed"] == 1
+ if os.name == "nt":
+ # Windows paths can hold a lone surrogate: it is one more file
+ # in the repo.
+ assert m["review_scope"] == 10000
+ else:
+ assert "review_scope" not in m
+
+
+class TestSnapshot:
+ def test_no_prompt_hook_means_no_snapshot(self, hook_env, workspace):
+ _, repo = workspace
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py"), hook_env)
+ m = _stop(repo, hook_env)
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 310000
+
+ @needs_sh
+ def test_failed_snapshot_is_counted(self, hook_env, workspace, tmp_path):
+ ws, repo = workspace
+ (repo / "app.py").write_text(VULN_PY) # uncommitted work from before the turn
+ m = _turn(repo, _no_stash_env(tmp_path, hook_env), edits=[ws / "notes.md"])
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 130001
+ # The next prompt takes a real snapshot and the flag is gone.
+ m = _turn(repo, hook_env, edits=[repo / "app.py"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY + "# more\n"))
+ assert m["files_reviewed"] == 1 and m["review_scope"] == 10000
+
+ @needs_sh
+ def test_flag_follows_the_snapshot_taken_after_a_finding(self, hook_env, stub_api,
+ workspace, tmp_path):
+ _, repo = workspace
+ broken = _no_stash_env(tmp_path, hook_env)
+ stub_api.vulns = [STUB_VULN]
+ # Good snapshot at the prompt; the one taken after the finding fails.
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py"), hook_env)
+ m = _stop(repo, broken)
+ assert m["vulns_found"] == 1 and m["review_scope"] == 10000
+ (repo / "app.py").write_text(VULN_PY + "# fix\n")
+ run_hook(edit_payload(repo, repo / "app.py"), hook_env)
+ m = _stop(repo, hook_env)
+ assert m["review_scope"] == 110000
+ # That Stop took a real one again.
+ (repo / "app.py").write_text(VULN_PY + "# fix 2\n")
+ run_hook(edit_payload(repo, repo / "app.py"), hook_env)
+ m = _stop(repo, hook_env)
+ assert m["review_scope"] == 10000
+
+
+class TestCode:
+ def _code(self, root, cwd, touched, files, fail=0):
+ scope, inside = diffstate.touched_scope(root, cwd, touched)
+ return diffstate.review_scope_code(root, scope, inside, files, fail)
+
+ def test_repo_at_the_filesystem_root(self):
+ root = os.path.abspath(os.sep)
+ assert self._code(root, root, [os.path.join(root, "x.py")], ["x.py", "y.py"]) == 10001
+
+ def test_names_that_only_start_like_a_parent_dir(self, tmp_path):
+ root = str(tmp_path)
+ assert self._code(root, root, [str(tmp_path / "..hidden.py")], ["..hidden.py"], 2) == 210000
+
+ def test_untouched_count_is_capped(self, tmp_path):
+ files = [f"f{i}.py" for i in range(12000)]
+ assert self._code(str(tmp_path), "", [], files) == 9999
+
+ def test_absolute_and_relative_file_names_count_the_same(self, tmp_path):
+ root = str(tmp_path)
+ touched = [str(tmp_path / "a.py")]
+ assert self._code(root, root, touched, ["a.py", "b.py"]) == 10001
+ assert self._code(root, root, touched, [str(tmp_path / "a.py"), str(tmp_path / "b.py")]) == 10001