summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-26 16:02:51 -0700
committerGitHub <noreply@github.com>2026-10-26 16:02:51 -0700
commitced0aa953bf0689e48308de3405bf276421dce63 (patch)
treec12d71065fa03cf65b5810dbae876d07d53c232c /plugins
parent3cb00e4a01a0256535ccd8555a286da190625e0f (diff)
parentde9e075c828f2c4438d26571dc6046472381a085 (diff)
Merge pull request #6836 from anthropics/mhegazy/sg-diff-seen-count
security-guidance: count reviews of a diff that was already reviewed
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py161
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py17
-rw-r--r--plugins/security-guidance/tests/test_repeated_diff_count.py268
3 files changed, 445 insertions, 1 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 063b0604..1544ccfe 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -6,12 +6,13 @@ 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,
@@ -508,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
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index cb1b51d9..f8122f89 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_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,
@@ -220,6 +221,10 @@ 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.
_LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics()
@@ -325,6 +330,9 @@ 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)
metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}}
out = {"metrics": metrics}
@@ -1802,6 +1810,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()
@@ -1905,6 +1917,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")
@@ -2232,6 +2245,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()
@@ -2277,6 +2293,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)
diff --git a/plugins/security-guidance/tests/test_repeated_diff_count.py b/plugins/security-guidance/tests/test_repeated_diff_count.py
new file mode 100644
index 00000000..ede4fdcb
--- /dev/null
+++ b/plugins/security-guidance/tests/test_repeated_diff_count.py
@@ -0,0 +1,268 @@
+"""Reviews report whether their diff was reviewed before; nothing is skipped."""
+from conftest import bash_payload, commit_file, git, make_repo, metrics_of, run_hook
+
+import diffstate
+
+import pytest
+
+DIFF = [("handlers.py", "@@ -0,0 +1,2 @@\n+def h(x):\n+ return x")]
+
+
+@pytest.fixture(autouse=True)
+def _claude_code_output(monkeypatch):
+ # diffstate reads the output mode from the test runner's environment.
+ monkeypatch.setattr(diffstate, "portable_output", lambda: False)
+
+
+def _reviews(stub_api):
+ return [c for c in stub_api.calls if c.endswith("/v1/messages")]
+
+
+def _records(repo):
+ p = repo / ".git" / "sg-reviewed-diffs"
+ return p.read_text().splitlines() if p.exists() else []
+
+
+def _recommit(repo, msg):
+ git(repo, "reset", "-q", "--soft", "HEAD~1")
+ out = git(repo, "commit", "-m", msg)
+ return git(repo, "rev-parse", "HEAD").strip(), out
+
+
+def _seen(repo, diff=DIFF):
+ return diffstate._diff_review_started(str(repo), diff)
+
+
+def _finished(repo, diff=DIFF):
+ token, _ = _seen(repo, diff)
+ diffstate._diff_review_done(token)
+
+
+def _hunk(start, context, added):
+ return f"@@ -{start},2 +{start},3 @@ def f():\n {context}\n+{added}\n pass"
+
+
+def test_first_review_of_a_diff_is_not_seen(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ token, m = _seen(repo)
+ assert m == {"diff_seen": diffstate.DIFF_SEEN_NO}
+ assert token and len(_records(repo)) == 1
+
+
+def test_unfinished_then_finished_on_same_then_other_tree(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ token, _ = _seen(repo)
+ assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_UNFINISHED}
+ diffstate._diff_review_done(token)
+ assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_SAME_TREE}
+ commit_file(repo, "other.py", "x = 1\n")
+ assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_OTHER_TREE}
+
+
+def test_tree_is_the_reviewed_commits_not_where_head_went(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ sha, _ = commit_file(repo, "handlers.py", "def h(x):\n return x\n")
+ token, _ = diffstate._diff_review_started(str(repo), DIFF, tip=sha)
+ diffstate._diff_review_done(token)
+ git(repo, "reset", "-q", "--hard", "HEAD~1")
+ assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_OTHER_TREE}
+ assert diffstate._diff_review_started(str(repo), DIFF, tip=sha)[1] == {
+ "diff_seen": diffstate.DIFF_SEEN_SAME_TREE}
+
+
+def test_a_different_change_path_or_place_is_not_seen(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ one = [("auth.py", _hunk(3, "def login():", "return True"))]
+ _finished(repo, one)
+ for other in ([("auth.py", _hunk(3, "def login():", "return False"))],
+ [("other.py", one[0][1])],
+ # The same added line next to different code.
+ [("auth.py", _hunk(3, "def is_admin():", "return True"))],
+ one + [("b.py", "@@ -0,0 +1 @@\n+1")]):
+ assert _seen(repo, other)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO}
+
+
+def test_a_moved_hunk_keeps_its_key(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ _finished(repo, [("auth.py", _hunk(3, "def login():", "return True"))])
+ moved = "@@ -40,2 +44,3 @@ class A:\n def login():\n+return True\n pass"
+ assert _seen(repo, [("auth.py", moved)])[1] == {"diff_seen": diffstate.DIFF_SEEN_SAME_TREE}
+
+
+def test_real_diffs_of_two_commits_match_their_net_diff(tmp_path):
+ from gitutil import parse_diff_into_files
+ body = "".join(f"line {i}\n" for i in range(60))
+ repo = make_repo(tmp_path / "repo", {"app.py": body})
+ base = git(repo, "rev-parse", "HEAD").strip()
+ commit_file(repo, "app.py", body.replace("line 5\n", "line 5\nx = 1\n"))
+ _finished(repo, parse_diff_into_files(git(repo, "show", "-p", "HEAD")))
+ commit_file(repo, "app.py", body.replace("line 5\n", "line 5\nx = 1\n")
+ .replace("line 50\n", "line 50\ny = 2\n"))
+ _finished(repo, parse_diff_into_files(git(repo, "show", "-p", "HEAD")))
+ net = parse_diff_into_files(git(repo, "diff", base, "HEAD"))
+ assert len(diffstate._hunk_keys(net)) == 2
+ # Both hunks had a finished review; the first one on an older tree.
+ assert _seen(repo, net)[1] == {"diff_seen": diffstate.DIFF_SEEN_OTHER_TREE}
+
+
+def test_hunks_past_the_key_cap_are_not_dropped(tmp_path, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ monkeypatch.setattr(diffstate, "_SEEN_DIFFS_MAX_KEYS", 3)
+ hunks = [_hunk(10 * i, f"def f{i}():", f"x = {i}") for i in range(6)]
+ _finished(repo, [("app.py", "\n".join(hunks[:5]))])
+ assert len(_records(repo)[0].split("\t")[3].split(" ")) == 3
+ assert _seen(repo, [("app.py", "\n".join(hunks))])[1] == {"diff_seen": diffstate.DIFF_SEEN_NO}
+ assert _seen(repo, [("app.py", "\n".join(hunks[:5]))])[1] == {
+ "diff_seen": diffstate.DIFF_SEEN_SAME_TREE}
+
+
+def test_removed_sql_comment_lines_tell_diffs_apart(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ _finished(repo, [("q.sql", "@@ -1,2 +1 @@\n--- drop table users;\n select 1;")])
+ other = [("q.sql", "@@ -1,2 +1 @@\n--- drop table orders;\n select 1;")]
+ assert _seen(repo, other)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO}
+
+
+def test_commits_reviewed_one_by_one_then_as_one_net_diff(tmp_path):
+ # Two commit reviews of the same file, then a push review of their net diff.
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ h1, h2 = _hunk(3, "def a():", "x = 1"), _hunk(90, "def z():", "y = 2")
+ _finished(repo, [("app.py", h1)])
+ net = [("app.py", h1 + "\n" + h2), ("b.py", "@@ -0,0 +1 @@\n+b = 2")]
+ assert _seen(repo, net)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO}
+ _finished(repo, [("app.py", h2)])
+ _finished(repo, [net[1]])
+ assert _seen(repo, net)[1] == {"diff_seen": diffstate.DIFF_SEEN_SAME_TREE}
+
+
+def test_old_records_do_not_count(tmp_path, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ _finished(repo)
+ monkeypatch.setattr(diffstate, "_SEEN_DIFFS_TTL_S", -1)
+ assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO}
+
+
+@pytest.mark.parametrize("flock", [True, False])
+def test_record_is_cut_back_to_its_newest_rows(tmp_path, monkeypatch, flock):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ if not flock:
+ def no_flock(fd, exclusive):
+ raise ImportError("fcntl")
+ monkeypatch.setattr(diffstate, "_flock_nb", no_flock)
+ _finished(repo)
+ row = len(_records(repo)[0]) + 1
+ monkeypatch.setattr(diffstate, "_SEEN_DIFFS_TRIM_BYTES", 6 * row)
+ for i in range(12):
+ _finished(repo, [("f.py", f"@@ -0,0 +1 @@\n+{i}")])
+ rows = _records(repo)
+ assert 3 <= len(rows) <= 6
+ assert rows[-1].split("\t")[2:] == ["1", diffstate._hunk_keys([("f.py", "@@ -0,0 +1 @@\n+11")])[0]]
+ assert _seen(repo, [("f.py", "@@ -0,0 +1 @@\n+11")])[1]["diff_seen"] == diffstate.DIFF_SEEN_SAME_TREE
+ assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_NO}
+
+
+def test_damaged_record_is_read_around_and_shrinks(tmp_path, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ p = repo / ".git" / "sg-reviewed-diffs"
+ p.write_bytes(b"\xff\xfe garbage\nshort\tline\n" + b"9" * 5000 + b"\tt\t1\tk\n"
+ + b"x" * 5000)
+ monkeypatch.setattr(diffstate, "_SEEN_DIFFS_TRIM_BYTES", 2000)
+ token, m = _seen(repo)
+ assert m == {"diff_seen": diffstate.DIFF_SEEN_NO}
+ diffstate._diff_review_done(token)
+ assert p.stat().st_size < 2000
+ assert _seen(repo)[1] == {"diff_seen": diffstate.DIFF_SEEN_SAME_TREE}
+
+
+def test_a_lock_another_process_keeps_is_not_waited_on(tmp_path, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ token, _ = _seen(repo)
+ monkeypatch.setattr(diffstate, "_flock_nb", lambda fd, exclusive: False)
+ monkeypatch.setattr(diffstate, "_SEEN_DIFFS_LOCK_TRIES", 2)
+ monkeypatch.setattr(diffstate, "_SEEN_DIFFS_TRIM_BYTES", 0)
+ # A start that cannot read the record under the lock does not guess.
+ assert _seen(repo) == (None, {"diff_seen": diffstate.DIFF_SEEN_ERROR})
+ # A verdict is still noted, and the record is not cut back without the lock.
+ diffstate._diff_review_done(token)
+ assert [r.split("\t")[2] for r in _records(repo)] == ["0", "1"]
+
+
+def test_failures_are_reported_and_never_raise(tmp_path):
+ assert _seen(tmp_path / "nope") == (None, {"diff_seen": diffstate.DIFF_SEEN_ERROR})
+ diffstate._diff_review_done(None)
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ (repo / ".git" / "sg-reviewed-diffs").mkdir()
+ assert _seen(repo) == (None, {"diff_seen": diffstate.DIFF_SEEN_ERROR})
+ diffstate._diff_review_done((str(repo / ".git" / "sg-reviewed-diffs"), ["k"], "t"))
+
+
+def test_a_record_that_cannot_be_written_is_an_error_not_unseen(tmp_path, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ def full_disk(f, locked, token, done):
+ raise OSError(28, "No space left on device")
+ monkeypatch.setattr(diffstate, "_append_diff_row", full_disk)
+ assert _seen(repo) == (None, {"diff_seen": diffstate.DIFF_SEEN_ERROR})
+
+
+def test_nothing_is_recorded_in_portable_output_mode(tmp_path, monkeypatch):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ monkeypatch.setattr(diffstate, "portable_output", lambda: True)
+ assert _seen(repo) == (None, {})
+ assert _records(repo) == []
+
+
+def test_recommit_of_the_same_change_is_reviewed_again_and_counted(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ sha, out = commit_file(repo, "handlers.py", "def h(x):\n return x\n")
+ rc, so, _ = run_hook(bash_payload(repo, "git commit -m change", out), hook_env)
+ first = metrics_of(so)
+ assert rc == 0 and first["diff_seen"] == diffstate.DIFF_SEEN_NO
+
+ sha2, out2 = _recommit(repo, "same change again")
+ assert sha2 != sha
+ rc, so, _ = run_hook(bash_payload(repo, "git commit -m 'same change again'", out2), hook_env)
+ second = metrics_of(so)
+ assert rc == 0 and second["diff_seen"] == diffstate.DIFF_SEEN_SAME_TREE
+ # Last in the row, so a row over the key cap loses this and nothing older.
+ assert list(second)[-1] == "diff_seen"
+ # Count only: both commits were reviewed and recorded.
+ assert len(_reviews(stub_api)) == 2
+ assert {sha, sha2} <= diffstate._load_reviewed_shas(str(repo))
+
+
+def test_push_of_a_rebased_reviewed_commit_is_counted(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ remote = tmp_path / "remote.git"
+ git(tmp_path, "init", "-q", "--bare", str(remote))
+ git(repo, "remote", "add", "origin", str(remote))
+ git(repo, "push", "-q", "-u", "origin", "main")
+ git(repo, "checkout", "-q", "-b", "feat")
+ sha, out = commit_file(repo, "handlers.py", "def h(x):\n return x\n")
+ run_hook(bash_payload(repo, "git commit -m change", out), hook_env)
+
+ git(repo, "checkout", "-q", "main")
+ commit_file(repo, "notes.md", "notes\n")
+ git(repo, "push", "-q", "origin", "main")
+ git(repo, "checkout", "-q", "feat")
+ git(repo, "rebase", "-q", "main")
+ git(repo, "push", "-q", "-u", "origin", "feat")
+ push_out = f"To {remote}\n * [new branch] feat -> feat\n"
+ rc, so, _ = run_hook(bash_payload(repo, "git push -u origin feat", push_out), hook_env)
+ m = metrics_of(so)
+ assert rc == 0 and m["push_sweep"] is True and m["unreviewed"] == 1
+ assert m["diff_seen"] == diffstate.DIFF_SEEN_OTHER_TREE and list(m)[-1] == "diff_seen"
+ assert len(_reviews(stub_api)) == 2
+
+
+def test_failed_review_leaves_the_diff_unfinished(tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ sha, out = commit_file(repo, "handlers.py", "def h(x):\n return x\n")
+ stub_api.status = 500
+ rc, so, _ = run_hook(bash_payload(repo, "git commit -m change", out), hook_env)
+ failed = metrics_of(so)
+ assert failed["review_failed"] is True and failed["diff_seen"] == diffstate.DIFF_SEEN_NO
+
+ stub_api.status = 200
+ sha2, out2 = _recommit(repo, "same change again")
+ rc, so, _ = run_hook(bash_payload(repo, "git commit -m 'same change again'", out2), hook_env)
+ assert metrics_of(so)["diff_seen"] == diffstate.DIFF_SEEN_UNFINISHED