summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-23 01:40:07 +0000
committerClaude <noreply@anthropic.com>2026-10-23 01:40:07 +0000
commitbc74a56723a0ce58935822c78e26ee93707a974b (patch)
treea6e0e677fd8b6901aaedb4571a8f9dd52cdcab7d /plugins
parent465f09344424225c25d438f2e052732c3d688d2f (diff)
security-guidance: count failed git add -N calls in the Stop reviewmhegazy/sg-add-fail-metric
A failed add leaves new files out of the diff with no sign of it. Measure only; behaviour is unchanged.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/gitutil.py33
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py8
-rw-r--r--plugins/security-guidance/tests/test_add_failure_metric.py143
3 files changed, 175 insertions, 9 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 73d7c611..1f1b4bbf 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -249,6 +249,15 @@ def _path_batches(paths, budget=None):
# long once cut down) or "none_reviewable".
_path_list_too_long = set()
+# A failed `git add --intent-to-add` during this hook run, for the Stop hook's
+# metrics: kind * 100000 + the paths the add was given. One number because a
+# review row is near CC's key cap. A failed add leaves the new files out of the
+# diff, so a turn that only added files looks like a turn with no changes; a
+# timeout loses the whole diff. kind: 1 git could not write the empty blob to
+# the object store, 2 any other git error, 3 timeout. A git that speaks another
+# language counts as 2.
+_add_failed = {"code": 0}
+
def _too_many_args(e):
"""The OS refused to start the command because its arguments are too
@@ -542,6 +551,10 @@ def _hook_tmpdir():
return d
+def _note_add_failure(kind, paths):
+ _add_failed["code"] = kind * 100000 + min(len(paths), 99999)
+
+
@contextlib.contextmanager
def _temp_index(cwd, untracked_paths=None):
"""Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the
@@ -632,12 +645,20 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths):
# still spawns reader threads that decode stderr — git error
# messages can reference non-ASCII filenames and crash on
# cp1252. See #2099. Drop text=True so bytes stay raw.
- _run_git_on_review_paths(
- ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd,
- # The paths are file names, not patterns, for this git add
- # only: an untracked file named `:(glob)**` must add only
- # itself.
- env={**env, "GIT_LITERAL_PATHSPECS": "1"})
+ try:
+ results = _run_git_on_review_paths(
+ ["add", "--intent-to-add"], add_args, timeout=10, cwd=cwd,
+ # The paths are file names, not patterns, for this git add
+ # only: an untracked file named `:(glob)**` must add only
+ # itself.
+ env={**env, "GIT_LITERAL_PATHSPECS": "1"})
+ except subprocess.TimeoutExpired:
+ _note_add_failure(3, add_args)
+ raise
+ failed = next((r for r in results if r.returncode != 0), None)
+ if failed:
+ _note_add_failure(1 if b"empty blob" in failed.stderr else 2, add_args)
+ debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}")
# A whole-tree add puts a nested repository back.
if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index):
yield None
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 0cae917d..e5fd18a9 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -2547,9 +2547,11 @@ def handle_stop_hook(input_data):
debug_log(f"Stop hook: diff against {content_base[:12]} failed — falling back to {diff_base}")
diff_output = get_git_diff(repo_root, diff_base, full_context=False,
paths=review_paths, untracked_paths=untracked)
- # Only when it happened: MiB of git diff output read, reviewable files
- # whose diff was cut while reading it, diffs that hit the timeout.
- for _k, _v in (("diff_mb", gitutil._diff_read["bytes"] >> 20),
+ # Only when it happened: a failed `git add -N` (first, so a row at CC's key
+ # cap keeps it), MiB of git diff output read, reviewable files whose diff
+ # was cut while reading it, diffs that hit the timeout.
+ for _k, _v in (("add_fail", gitutil._add_failed["code"]),
+ ("diff_mb", gitutil._diff_read["bytes"] >> 20),
("diff_cut_files", gitutil._diff_read["cut_files"]),
("diff_timeout", gitutil._diff_read["timeouts"])):
if _v:
diff --git a/plugins/security-guidance/tests/test_add_failure_metric.py b/plugins/security-guidance/tests/test_add_failure_metric.py
new file mode 100644
index 00000000..3a86a8ac
--- /dev/null
+++ b/plugins/security-guidance/tests/test_add_failure_metric.py
@@ -0,0 +1,143 @@
+"""A failed `git add --intent-to-add` leaves new files out of the Stop review's
+diff. The review goes on as before; the Stop row says that it happened."""
+import os
+import subprocess
+import tempfile
+from types import SimpleNamespace
+
+import pytest
+
+from conftest import (
+ GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload,
+ ups_payload,
+)
+
+import gitutil
+
+
+def _cannot_write_read_only_dirs():
+ with tempfile.TemporaryDirectory() as d:
+ os.chmod(d, 0o555)
+ try:
+ return not os.access(d, os.W_OK)
+ finally:
+ os.chmod(d, 0o755)
+
+
+@pytest.fixture
+def read_only_objects():
+ made = []
+
+ def lock(repo):
+ made.append(repo / ".git" / "objects")
+ subprocess.run(["chmod", "-R", "a-w", str(made[-1])], check=True)
+
+ yield lock
+ for objects in made:
+ subprocess.run(["chmod", "-R", "u+w", str(objects)], check=True)
+
+
+@pytest.mark.skipif(os.name == "nt" or not _cannot_write_read_only_dirs(),
+ reason="needs a user that file permissions apply to")
+class TestObjectStoreNotWritable:
+ def test_turn_that_only_adds_a_file(self, tmp_path, hook_env, stub_api, read_only_objects):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ read_only_objects(repo)
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "handlers.py").write_text(VULN_PY)
+ m = metrics_of(run_hook(stop_payload(repo), hook_env)[1])
+ assert m["skip_reason"] == 6, m
+ assert m["review_set_count"] == 1
+ assert m["add_fail"] == 100001
+ assert not stub_api.calls
+
+ def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api, read_only_objects):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ read_only_objects(repo)
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "a.py").write_text("print('a')\n")
+ (repo / "b.py").write_text("print('b')\n")
+ m = metrics_of(run_hook(stop_payload(repo), hook_env)[1])
+ assert not m.get("skipped"), m
+ assert m["files_reviewed"] == 1
+ assert m["add_fail"] == 100002
+
+
+class TestStopRow:
+ def test_other_git_error(self, tmp_path, hook_env, stub_api):
+ # git refuses --literal-pathspecs together with a user's icase setting.
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ env = {**hook_env, "GIT_ICASE_PATHSPECS": "1"}
+ run_hook(ups_payload(repo), env)
+ (repo / "handlers.py").write_text(VULN_PY)
+ m = metrics_of(run_hook(stop_payload(repo), env)[1])
+ assert m["skip_reason"] == 6, m
+ assert m["add_fail"] == 200001
+
+ def test_add_that_works_reports_nothing(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 / "handlers.py").write_text(VULN_PY)
+ m = metrics_of(run_hook(stop_payload(repo), hook_env)[1])
+ assert m["files_reviewed"] == 1
+ assert "add_fail" not in m
+
+
+class TestGetGitDiff:
+ @pytest.fixture(autouse=True)
+ def _env(self, 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)
+ yield
+ gitutil._add_failed["code"] = 0
+
+ @pytest.fixture
+ def repo(self, tmp_path):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ (repo / "new.py").write_text("print('new')\n")
+ return repo
+
+ def _adds_fail_with(self, monkeypatch, outcome):
+ real = gitutil._run_git_on_review_paths
+
+ def run(args, paths, timeout, **kwargs):
+ if args[0] != "add":
+ return real(args, paths, timeout, **kwargs)
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+
+ monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run)
+
+ def test_any_failed_batch_counts(self, repo, monkeypatch):
+ self._adds_fail_with(monkeypatch, [
+ SimpleNamespace(returncode=0, stderr=b""),
+ SimpleNamespace(returncode=128, stderr=b"fatal: nope"),
+ ])
+ gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")],
+ untracked_paths=["new.py"])
+ assert gitutil._add_failed["code"] == 200001
+
+ def test_timeout_counts_and_still_gives_no_diff(self, repo, monkeypatch):
+ self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10))
+ assert gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")],
+ untracked_paths=["new.py"]) is None
+ assert gitutil._add_failed["code"] == 300001
+
+ def test_object_store_refusal(self, repo, monkeypatch):
+ self._adds_fail_with(monkeypatch, [SimpleNamespace(
+ returncode=128,
+ stderr=b"fatal: cannot create an empty blob in the object database")])
+ gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")],
+ untracked_paths=["new.py"])
+ assert gitutil._add_failed["code"] == 100001
+
+ def test_a_later_add_that_works_keeps_the_failure(self, repo, monkeypatch):
+ gitutil._add_failed["code"] = 300001
+ gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")],
+ untracked_paths=["new.py"])
+ assert gitutil._add_failed["code"] == 300001