summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-19 16:25:48 +0000
committerClaude <noreply@anthropic.com>2026-10-19 16:25:48 +0000
commitaf95e28036dec718066ef0c3b684dccb4f23cd39 (patch)
treeb9a43c6901686d466e41c51c23edaaeac5a64cac /plugins
parentea10b213686c90bb1984b2016937310e05336cf3 (diff)
security-guidance: read the Stop review's git diff without holding it whole
The Stop review captured the whole diff of the turn before its per-file caps applied, so a turn that wrote large text files cost the hook several times their size in memory. The output is now read as it arrives: files the review drops keep only their header line, and one file's diff is cut at 4 MiB (SG_MAX_FILE_DIFF_BYTES). The git command is unchanged. Adds count-only metrics, nonzero only: diff_mb, diff_cut_files, diff_timeout.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/gitutil.py185
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py21
-rw-r--r--plugins/security-guidance/tests/test_stop_diff_memory.py250
3 files changed, 450 insertions, 6 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index bc4d753b..cf606337 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -18,6 +18,8 @@ import contextlib
import os
import re
import subprocess
+import tempfile
+import threading
from _base import debug_log
@@ -767,6 +769,181 @@ def _is_ancestor(cwd, maybe_ancestor, descendant):
+def _file_diff_cap():
+ try:
+ n = int(os.environ.get("SG_MAX_FILE_DIFF_BYTES", ""))
+ except ValueError:
+ return 4 * 1024 * 1024
+ return max(n, _LATE_FILE_DIFF_BYTES)
+
+
+_LATE_FILE_DIFF_BYTES = 64 * 1024
+# How much of one file's diff the Stop review keeps while it reads git's
+# output. The review prompt takes far less of a file (DIFF_PER_FILE_BYTES);
+# the rest is room for filter_preexisting_from_diff, which needs the removed
+# and the added side of a rewritten file, so a rewrite keeps both sides for
+# files up to about half of this.
+MAX_FILE_DIFF_BYTES = _file_diff_cap()
+# Past this much kept in total, each further file keeps only its start.
+MAX_KEPT_DIFF_BYTES = 4 * MAX_FILE_DIFF_BYTES
+_SECTION_MARK = b"\ndiff --git "
+_MAX_HEADER_BYTES = 64 * 1024
+
+# 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 up to MAX_FILE_DIFF_BYTES 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._room = MAX_FILE_DIFF_BYTES
+ self._reviewable = True
+ self._cut = False
+ self._ends_nl = True
+
+ 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."""
+ text = header[len(_SECTION_MARK) - 1:].decode("utf-8", errors="replace")
+ paths = _parse_diff_header(text)
+ # Same test as parse_diff_into_files. An unparsed header is passed on
+ # so the parser still counts it.
+ self._reviewable = not paths or _is_reviewable_source(paths[1] or paths[0])
+ if not self._reviewable:
+ self._room = len(header) + 1
+ elif self.kept > MAX_KEPT_DIFF_BYTES:
+ self._room = max(len(header) + 1, _LATE_FILE_DIFF_BYTES)
+ else:
+ self._room = MAX_FILE_DIFF_BYTES
+ self._cut = False
+ if not self._ends_nl:
+ # The previous file was cut inside a line.
+ self.parts.append(b"\n")
+ self._ends_nl = True
+
+ def _keep(self, data):
+ if self._at_start and data:
+ self._at_start = False
+ data = data[1:]
+ if not data:
+ return
+ self.seen += len(data)
+ take = data[:self._room]
+ if take:
+ self.parts.append(take)
+ self.kept += len(take)
+ self._room -= len(take)
+ self._ends_nl = take.endswith(b"\n")
+ if len(take) < len(data) and self._reviewable:
+ self.cut_bytes += len(data) - len(take)
+ if not self._cut:
+ self._cut = True
+ self.cut_files += 1
+
+ def result(self):
+ self._keep(self._pending)
+ self._pending = b""
+ if not self._ends_nl:
+ # Cut inside a line: end it, so anything joined after this
+ # output starts on a line of its own.
+ self.parts.append(b"\n")
+ self._ends_nl = True
+ 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()
+ 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)
+ expired = threading.Event()
+
+ def _expire():
+ expired.set()
+ p.kill()
+
+ timer = threading.Timer(timeout, _expire)
+ timer.daemon = True
+ try:
+ try:
+ timer.start()
+ except RuntimeError as e:
+ raise OSError(f"no thread for the diff timeout: {e}")
+ while True:
+ chunk = p.stdout.read1(1024 * 1024)
+ if not chunk:
+ break
+ keeper.feed(chunk)
+ returncode = p.wait()
+ except BaseException:
+ p.kill()
+ p.wait()
+ raise
+ finally:
+ timer.cancel()
+ p.stdout.close()
+ stdout = keeper.result()
+ _diff_read["bytes"] += keeper.seen
+ _diff_read["cut_files"] += keeper.cut_files
+ _diff_read["cut_bytes"] += keeper.cut_bytes
+ # A diff that finished as the timer fired is still a finished diff.
+ if expired.is_set() and returncode != 0:
+ _diff_read["timeouts"] += 1
+ raise subprocess.TimeoutExpired(cmd, timeout)
+ 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):
"""
Get the git diff between the baseline SHA and the current working tree,
@@ -781,6 +958,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.
"""
pathspec = _diff_pathspec(cwd, paths)
if paths and not pathspec:
@@ -792,16 +972,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", "--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
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index ea5bab18..72edf794 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -2136,6 +2136,12 @@ 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."""
+ return llm._last_review_truncated_bytes + gitutil._diff_read["cut_bytes"]
+
+
def handle_stop_hook(input_data):
"""
Handle the Stop hook — final security check using git diff.
@@ -2282,6 +2288,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:
@@ -2419,8 +2432,8 @@ 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 {}),
+ **({"diff_truncated": _stop_diff_truncated()}
+ if _stop_diff_truncated() else {}),
**({"repo_resolution": repo_res} if res_metrics else {}),
**sweep_trimmed,
**({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)}
@@ -2457,8 +2470,8 @@ 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 {}),
+ **({"diff_truncated": _stop_diff_truncated()}
+ if _stop_diff_truncated() else {}),
**v2_metrics,
**({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)}
if gitutil._unparsed_diff_headers else {}),
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..e95d94ec
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_diff_memory.py
@@ -0,0 +1,250 @@
+"""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 tracemalloc
+
+import pytest
+
+from conftest import (
+ GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload,
+ ups_payload,
+)
+
+import gitutil
+
+
+@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"]
+ assert files["big.json"] and len(files["big.json"]) < 300
+ assert keeper.cut_files == 1
+ assert keeper.kept <= 300 + len(_section("after.py", ["import os"])) + 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
+ assert [p for p, _ in gitutil.parse_diff_into_files(kept.decode())] == ["after.py"]
+
+ def test_past_the_total_each_file_keeps_only_its_start(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)
+ raw = "".join(_section(f"f{i}.py", ["v" * 30] * 60) for i in range(6)).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(6)]
+ assert len(kept) <= 2 * 2000 + 4 * 200 + 6
+ assert keeper.cut_files == 6
+
+ def test_output_cut_inside_a_line_ends_with_a_newline(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "MAX_FILE_DIFF_BYTES", 300)
+ raw = _section("big.json", ["k" * 37] * 100).encode()
+ keeper, kept = _keep(raw, _sizes(64))
+ assert kept.endswith(b"\n") and not raw.startswith(kept)
+ assert keeper.cut_bytes == len(raw) - (len(kept) - 1)
+ 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.write('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_finished_as_the_timer_fired_is_not_a_timeout(self, monkeypatch):
+ class Fired:
+ def __init__(self, timeout, fn):
+ self.fn = fn
+ daemon = False
+ def start(self):
+ pass
+ def cancel(self):
+ self.fn()
+ monkeypatch.setattr(gitutil.threading, "Timer", Fired)
+ r = gitutil._run_diff_bounded([sys.executable, "-c", "print('ok')"], 30)
+ assert r.returncode == 0 and r.stdout.strip() == b"ok"
+
+ 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", 64 * 1024),
+ ("-5", 64 * 1024), ("100000", 100000)])
+ 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_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' * 9000)
+ env = {**hook_env, "SG_MAX_FILE_DIFF_BYTES": "100000"}
+ 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
+ assert m["diff_truncated"] > 9000 * 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)