summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-09 17:52:07 +0000
committerClaude <noreply@anthropic.com>2026-11-09 17:52:07 +0000
commit67f8c646e7cb50b4e28e042d13932efca6dc5f50 (patch)
treea38c9eedd041469f6c8576ac151a91304db3ea39 /plugins
parent0412be76f50ab4f4f8abff3753efa9269fbbca5b (diff)
security-guidance: push review of a merge reviews what the push added
The reviewed prefix could end on the merged-in branch, so the diff held everything the first parent has that the branch lacks. Keep the base on HEAD's first-parent line. A merge whose history is all reviewed is sent as its combined diff, so only its conflict resolutions and hand edits are read. Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/gitutil.py55
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py64
-rw-r--r--plugins/security-guidance/tests/test_push_merge_base.py245
3 files changed, 362 insertions, 2 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 4c363ef4..733762ef 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -1047,7 +1047,7 @@ def _git_rev_list_range(repo_root, base, head="HEAD"):
# See #2099: stdout is ASCII SHAs, but stderr can carry git error
# messages referencing non-ASCII filenames — keep bytes raw.
r = subprocess.run(
- [*GIT_CMD, "rev-list", "--reverse", f"{base}..{head}"],
+ [*GIT_CMD, "rev-list", "--reverse", "--topo-order", f"{base}..{head}"],
cwd=repo_root, capture_output=True, timeout=10,
)
if r.returncode != 0:
@@ -1057,6 +1057,59 @@ def _git_rev_list_range(repo_root, base, head="HEAD"):
return []
+def _git_range_parents(repo_root, base, head="HEAD"):
+ """{sha: [parent shas, first parent first]} for `base..head`.
+
+ Empty on error: the caller then treats the range as linear, which reviews
+ more, never less.
+ """
+ try:
+ r = subprocess.run(
+ [*GIT_CMD, "rev-list", "--parents", f"{base}..{head}"],
+ cwd=repo_root, capture_output=True, timeout=10,
+ )
+ if r.returncode != 0:
+ return {}
+ rows = [line.split() for line in r.stdout.decode("utf-8", errors="replace").splitlines()]
+ return {row[0]: row[1:] for row in rows if row}
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
+ return {}
+
+
+def _git_merge_resolved_files(repo_root, merge_sha):
+ """(path, combined-diff hunks) for each source file a merge changed itself,
+ or None on error.
+
+ The combined diff shows only lines that match none of the merge's parents:
+ conflict resolutions and hand edits. A clean merge has none, and neither
+ does a conflict settled by taking one side whole.
+ """
+ try:
+ r = subprocess.run(
+ [*GIT_CMD, "diff-tree", "--cc", "-M", "--no-commit-id", "-r", "--no-color",
+ "--no-ext-diff", "--no-textconv", merge_sha],
+ cwd=repo_root, capture_output=True, timeout=30,
+ )
+ if r.returncode != 0:
+ return None
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
+ return None
+ files = []
+ # Hunk lines start with one marker column per parent, so only a file
+ # header starts with "diff --cc " in the first column.
+ text = r.stdout.decode("utf-8", errors="replace")
+ for section in re.split(r"^diff --cc ", text, flags=re.M)[1:]:
+ header, _, body = section.partition("\n")
+ path = header
+ if header.startswith('"'):
+ quoted = _read_quoted_path(header, 0)
+ path = quoted[0] if quoted else None
+ at = body.find("@@@")
+ if path and at >= 0 and _section_is_reviewable(path, path):
+ files.append((path, body[at:].rstrip("\n")))
+ return files
+
+
def _git_diff_range(repo_root, base, head="HEAD"):
"""`git diff -p base head` as text on success, None on error.
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 47a992aa..cd7e0c7c 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -107,6 +107,7 @@ from gitutil import ( # noqa: E402,F401
on_windows_drive,
_git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index,
_git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range,
+ _git_range_parents, _git_merge_resolved_files,
_git_toplevel_and_head, _git_head_at,
_detect_main_branch, _git_reflog_recent_commits, _git_name_only,
_git_status_porcelain, _is_ancestor, get_git_diff,
@@ -1208,6 +1209,50 @@ def _compute_push_sweep_base(prev_upstream, push_range, reviewed):
base = push_range[i - 1] if i > 0 else prev_upstream
return base, push_range[i:]
+def _push_sweep_base_with_merges(prev_upstream, push_range, reviewed, parents):
+ """Choose the base when the range has merge commits.
+
+ The reviewed prefix can end on a merged-in branch, and a diff from there
+ holds everything the first parent has that the merged-in branch lacks:
+ code this push did not add. So the base must be on HEAD's first-parent
+ line, or be `prev_upstream`.
+
+ A merge on that line whose history in the range is all reviewed brought in
+ nothing unreviewed. Such merges are returned as `settled`: only what each
+ one resolved itself still needs a look.
+
+ Returns (base, settled). `push_range` must be in topological order, HEAD
+ last.
+ """
+ first_parent_line = set()
+ sha = push_range[-1]
+ while sha in parents:
+ first_parent_line.add(sha)
+ sha = parents[sha][0] if parents[sha] else None
+ settled = []
+ covered = 0
+ for sha in push_range:
+ if sha not in reviewed:
+ if len(parents.get(sha, ())) < 2 or sha not in first_parent_line:
+ break
+ settled.append(sha)
+ covered += 1
+ base = next((s for s in reversed(push_range[:covered]) if s in first_parent_line),
+ prev_upstream)
+ return base, settled
+
+def _merge_resolved_diff_files(repo_root, merges):
+ """{path: combined-diff hunks} of what `merges` resolved themselves, or
+ None if git failed."""
+ resolved = {}
+ for sha in merges:
+ files = _git_merge_resolved_files(repo_root, sha)
+ if files is None:
+ return None
+ for path, hunks in files:
+ resolved[path] = resolved[path] + "\n" + hunks if path in resolved else hunks
+ return resolved
+
def _push_section(bash_output):
"""Return the slice of `bash_output` that contains the push's range lines.
@@ -2163,7 +2208,8 @@ def handle_push_sweep_posttooluse(input_data):
Spec: review `git diff B..HEAD` where `B` is the newest commit such that
`prev_upstream..B` is entirely in `.git/sg-reviewed-shas`. Skip if
- `B == HEAD`. Mark `B..HEAD` reviewed afterward.
+ `B == HEAD`. Mark `B..HEAD` reviewed afterward. With merges in the range,
+ see `_push_sweep_base_with_merges`.
Diff and Read are both at HEAD (push doesn't move the working tree), so the
agentic reviewer sees a consistent view — a vuln introduced in commit A and
@@ -2345,6 +2391,19 @@ def handle_push_sweep_posttooluse(input_data):
debug_log(f"Push sweep: waited {_waited:.0f}s for a running commit review")
base, tail = _compute_push_sweep_base(prev_upstream, push_range, reviewed)
prefix_advanced = len(push_range) - len(tail)
+ _parents = _git_range_parents(repo_root, prev_upstream, "HEAD") if base else {}
+ _settled = []
+ if any(len(p) > 1 for p in _parents.values()):
+ base, _settled = _push_sweep_base_with_merges(
+ prev_upstream, push_range, reviewed, _parents)
+ _resolved = _merge_resolved_diff_files(repo_root, _settled)
+ if _resolved is None:
+ # Could not read what a merge resolved: review the whole range instead.
+ base, _settled, _resolved = prev_upstream, [], {}
+ if _settled:
+ _TAIL_METRICS["merges_settled"] = len(_settled)
+ if base == prev_upstream:
+ prefix_advanced = 0
if base is None:
debug_log("Push sweep: every pushed commit already reviewed")
emit_metrics({**_base, "pushed": len(push_range), "unreviewed": 0,
@@ -2374,6 +2433,9 @@ def handle_push_sweep_posttooluse(input_data):
"unreviewed": len(tail), "skip_reason": 45})
sys.exit(0)
diff_files = parse_diff_into_files(diff_text)
+ for _path, _hunks in diff_files:
+ _resolved[_path] = _resolved[_path] + "\n" + _hunks if _path in _resolved else _hunks
+ diff_files = list(_resolved.items())
if not diff_files:
emit_metrics({**_base, "pushed": len(push_range),
"unreviewed": len(tail), "skip_reason": 30})
diff --git a/plugins/security-guidance/tests/test_push_merge_base.py b/plugins/security-guidance/tests/test_push_merge_base.py
new file mode 100644
index 00000000..bdc337ee
--- /dev/null
+++ b/plugins/security-guidance/tests/test_push_merge_base.py
@@ -0,0 +1,245 @@
+"""A push whose tip is a merge reviews what the push added, not the rest of main."""
+import json
+import os
+import subprocess
+
+import pytest
+
+from conftest import bash_payload, commit_file, git, make_repo, metrics_of, run_hook
+
+import diffstate
+import gitutil
+import security_reminder_hook as hook
+
+
+def _record_reviewed(repo, *shas):
+ diffstate._append_reviewed_shas(str(repo), list(shas))
+
+
+def _forward_repo(tmp_path):
+ """main holds work the release branch lacks; both are on the remote."""
+ repo = make_repo(tmp_path / "repo", {"app.py": "a = 1\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, "branch", "release")
+ commit_file(repo, "future.py", "main_only = 1\n")
+ git(repo, "push", "-q", "origin", "main")
+ git(repo, "switch", "-q", "release")
+ return repo, remote
+
+
+def _on_release(repo, name):
+ sha, _ = commit_file(repo, name, f"{name[:-3]} = 1\n")
+ git(repo, "push", "-q", "origin", "release")
+ return sha
+
+
+def _merge_forward(repo):
+ git(repo, "switch", "-q", "-c", "fwd", "main")
+ git(repo, "merge", "-q", "--no-ff", "--no-edit", "origin/release")
+ return git(repo, "rev-parse", "HEAD").strip()
+
+
+def _push_fwd(repo, remote, env):
+ git(repo, "push", "-q", "-u", "origin", "fwd")
+ out = f"To {remote}\n * [new branch] fwd -> fwd\n"
+ return run_hook(bash_payload(repo, "git push -u origin fwd", out), env)
+
+
+def _reviewed_text(stub_api):
+ return [json.dumps(b) for b, c in zip(stub_api.bodies, stub_api.calls)
+ if c.endswith("/v1/messages")]
+
+
+def test_clean_forward_merge_of_reviewed_commits_needs_no_review(tmp_path, hook_env, stub_api):
+ repo, remote = _forward_repo(tmp_path)
+ fix = _on_release(repo, "fix.py")
+ _record_reviewed(repo, fix)
+ merge = _merge_forward(repo)
+
+ rc, so, _ = _push_fwd(repo, remote, hook_env)
+
+ m = metrics_of(so)
+ assert rc == 0 and m["merges_settled"] == 1 and m["skip_reason"] == 30
+ assert _reviewed_text(stub_api) == []
+ assert merge in diffstate._load_reviewed_shas(str(repo))
+
+
+def test_conflict_resolution_is_still_reviewed(tmp_path, hook_env, stub_api):
+ repo, remote = _forward_repo(tmp_path)
+ git(repo, "switch", "-q", "main")
+ commit_file(repo, "app.py", "a = 2\n")
+ git(repo, "push", "-q", "origin", "main")
+ git(repo, "switch", "-q", "release")
+ fix, _ = commit_file(repo, "app.py", "a = 3\n")
+ other, _ = commit_file(repo, "fix.py", "fix = 1\n")
+ git(repo, "push", "-q", "origin", "release")
+ _record_reviewed(repo, fix, other)
+ git(repo, "switch", "-q", "-c", "fwd", "main")
+ assert subprocess.run(["git", "merge", "--no-ff", "--no-edit", "origin/release"],
+ cwd=repo, capture_output=True).returncode != 0
+ (repo / "app.py").write_text("a = resolved_by_hand\n")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "--no-edit")
+
+ rc, so, _ = _push_fwd(repo, remote, hook_env)
+
+ m = metrics_of(so)
+ assert rc == 0 and m["merges_settled"] == 1 and m["files_reviewed"] == 1
+ sent = _reviewed_text(stub_api)
+ assert sent and all("resolved_by_hand" in t and "@@@" in t for t in sent)
+ assert not any("future.py" in t or "fix.py" in t for t in sent)
+
+
+def test_unreadable_merge_is_not_settled(tmp_path, monkeypatch):
+ monkeypatch.setattr(hook, "_git_merge_resolved_files", lambda *a: None)
+ assert hook._merge_resolved_diff_files(str(tmp_path), ["x"]) is None
+
+
+def test_edit_after_a_merge_keeps_both_diffs(tmp_path, hook_env, stub_api):
+ repo, remote = _forward_repo(tmp_path)
+ git(repo, "switch", "-q", "main")
+ commit_file(repo, "app.py", "a = 2\n")
+ git(repo, "push", "-q", "origin", "main")
+ git(repo, "switch", "-q", "release")
+ fix, _ = commit_file(repo, "app.py", "a = 3\n")
+ git(repo, "push", "-q", "origin", "release")
+ _record_reviewed(repo, fix)
+ git(repo, "switch", "-q", "-c", "fwd", "main")
+ subprocess.run(["git", "merge", "--no-ff", "--no-edit", "origin/release"],
+ cwd=repo, capture_output=True)
+ (repo / "app.py").write_text("a = resolved_by_hand\n")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "--no-edit")
+ commit_file(repo, "app.py", "a = resolved_by_hand\nb = later_edit\n")
+
+ rc, so, _ = _push_fwd(repo, remote, hook_env)
+
+ m = metrics_of(so)
+ assert rc == 0 and m["files_reviewed"] == 1
+ sent = _reviewed_text(stub_api)
+ assert sent and all("resolved_by_hand" in t and "later_edit" in t for t in sent)
+
+
+def test_hand_edit_in_a_merge_is_reviewed(tmp_path, hook_env, stub_api):
+ repo, remote = _forward_repo(tmp_path)
+ _record_reviewed(repo, _on_release(repo, "fix.py"))
+ _merge_forward(repo)
+ (repo / "extra.py").write_text("added_in_merge = 1\n")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "--amend", "--no-edit")
+
+ rc, so, _ = _push_fwd(repo, remote, hook_env)
+
+ sent = _reviewed_text(stub_api)
+ assert rc == 0 and sent and all("added_in_merge" in t for t in sent)
+ assert not any("future.py" in t for t in sent)
+
+
+def test_unreviewed_merged_side_is_reviewed(tmp_path, hook_env, stub_api):
+ repo, remote = _forward_repo(tmp_path)
+ _on_release(repo, "fix.py")
+ _merge_forward(repo)
+
+ rc, so, _ = _push_fwd(repo, remote, hook_env)
+
+ m = metrics_of(so)
+ assert rc == 0 and "merges_settled" not in m and m["files_reviewed"] == 1
+ sent = _reviewed_text(stub_api)
+ assert sent and all("fix.py" in t for t in sent)
+ assert not any("future.py" in t for t in sent)
+
+
+def test_partly_reviewed_side_does_not_pull_in_main(tmp_path, hook_env, stub_api):
+ repo, remote = _forward_repo(tmp_path)
+ _record_reviewed(repo, _on_release(repo, "fix.py"))
+ _on_release(repo, "second.py")
+ _merge_forward(repo)
+
+ rc, so, _ = _push_fwd(repo, remote, hook_env)
+
+ sent = _reviewed_text(stub_api)
+ assert rc == 0 and sent and all("second.py" in t for t in sent)
+ assert not any("future.py" in t for t in sent)
+
+
+def test_commit_after_a_settled_merge_is_reviewed_alone(tmp_path, hook_env, stub_api):
+ repo, remote = _forward_repo(tmp_path)
+ _record_reviewed(repo, _on_release(repo, "fix.py"))
+ _merge_forward(repo)
+ commit_file(repo, "after.py", "after_merge = 1\n")
+
+ rc, so, _ = _push_fwd(repo, remote, hook_env)
+
+ m = metrics_of(so)
+ assert rc == 0 and m["merges_settled"] == 1 and m["files_reviewed"] == 1
+ sent = _reviewed_text(stub_api)
+ assert sent and all("after_merge" in t for t in sent)
+ assert not any("future.py" in t or "fix.py" in t for t in sent)
+
+
+def test_linear_push_keeps_its_base(tmp_path, hook_env, stub_api):
+ repo, remote = _forward_repo(tmp_path)
+ before = git(repo, "rev-parse", "HEAD").strip()
+ first, _ = commit_file(repo, "one.py", "one = 1\n")
+ _record_reviewed(repo, first)
+ tip, _ = commit_file(repo, "two.py", "two = 1\n")
+ git(repo, "push", "-q", "origin", "release")
+ out = f"To {remote}\n {before[:7]}..{tip[:7]} release -> release\n"
+
+ rc, so, _ = run_hook(bash_payload(repo, "git push origin release", out), hook_env)
+
+ m = metrics_of(so)
+ assert rc == 0 and m["prefix_advanced"] == 1 and "merges_settled" not in m
+ sent = _reviewed_text(stub_api)
+ assert sent and all("two.py" in t and "one.py" not in t for t in sent)
+
+
+def _parents(**rows):
+ return {k: v.split() for k, v in rows.items()}
+
+
+@pytest.mark.parametrize("range_, reviewed, parents, want", [
+ # The issue's shape: the reviewed prefix ends on the merged-in branch.
+ (["r1", "r2", "M"], {"r1", "r2"}, _parents(r1="o", r2="r1", M="p r2"), ("M", ["M"])),
+ # A reviewed commit on the first-parent line is a valid base.
+ (["c", "r", "M"], {"c"}, _parents(c="p", r="o", M="c r"), ("c", [])),
+ (["c", "r", "M"], {"c", "r"}, _parents(c="p", r="o", M="c r"), ("M", ["M"])),
+ # Nothing reviewed before the merge.
+ (["r", "M"], set(), _parents(r="o", M="p r"), ("prev", [])),
+ # A merge on the merged-in side is not settled.
+ (["s", "m2", "M"], {"s"}, _parents(s="o", m2="s q", M="p m2"), ("prev", [])),
+ # Merges one after another.
+ (["r", "M1", "M2"], {"r"}, _parents(r="o", M1="p r", M2="M1 o"), ("M2", ["M1", "M2"])),
+])
+def test_base_with_merges(range_, reviewed, parents, want):
+ assert hook._push_sweep_base_with_merges("prev", range_, reviewed, parents) == want
+
+
+def test_cleanly_merged_file_is_not_called_resolved(tmp_path):
+ repo = make_repo(tmp_path / "repo", {"both.py": "".join(f"l{i}\n" for i in range(12))})
+ git(repo, "switch", "-q", "-c", "side")
+ commit_file(repo, "both.py", "first\n" + "".join(f"l{i}\n" for i in range(1, 12)))
+ git(repo, "switch", "-q", "main")
+ commit_file(repo, "both.py", "".join(f"l{i}\n" for i in range(11)) + "last\n")
+ git(repo, "merge", "-q", "--no-ff", "--no-edit", "side")
+ head = git(repo, "rev-parse", "HEAD").strip()
+ assert gitutil._git_merge_resolved_files(str(repo), head) == []
+
+
+@pytest.mark.skipif(os.name == "nt", reason='file names cannot hold " on Windows')
+def test_resolved_path_with_a_quote(tmp_path):
+ name = 'we"ird.py'
+ repo = make_repo(tmp_path / "repo", {name: "base\n"})
+ git(repo, "switch", "-q", "-c", "side")
+ commit_file(repo, name, "side\n")
+ git(repo, "switch", "-q", "main")
+ commit_file(repo, name, "main\n")
+ subprocess.run(["git", "merge", "--no-edit", "side"], cwd=repo, capture_output=True)
+ (repo / name).write_text("resolved\n")
+ git(repo, "add", "-A")
+ git(repo, "commit", "-q", "--no-edit")
+ head = git(repo, "rev-parse", "HEAD").strip()
+ assert [p for p, _ in gitutil._git_merge_resolved_files(str(repo), head)] == [name]