summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-05 14:25:21 -0800
committerGitHub <noreply@github.com>2026-11-05 14:25:21 -0800
commitd2061194e0d13fe4532e9bb14d01887df8284dc2 (patch)
tree643bfcc60211194cd9a3ec985a463e24cae241f8 /plugins
parent9b1aab5d9b97b5f920454642d3b9671f53eb0d13 (diff)
parentd9c752cc4e05ffb761ac0fbdd7f13ec7fe2b2861 (diff)
Merge pull request #6919 from anthropics/mhegazy/sg-add-failure-fix
security-guidance: keep new files in the Stop review when git add -N fails
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/gitutil.py138
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py92
-rw-r--r--plugins/security-guidance/tests/test_add_failure_metric.py370
3 files changed, 542 insertions, 58 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 75d08298..041778b3 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -331,12 +331,17 @@ _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}
+# review row is near CC's key cap. kind: 1 git could not write the empty blob
+# to the object store and the retry failed too, 2 any other git error, 3
+# timeout, 4 the retry with a private object directory worked. A git that
+# speaks another language reports a failed retry as 2. With 1 to 3 the new
+# files are not in the diff, so a turn that only added files looks like a turn
+# with no changes. `left_out` says so for the last get_git_diff alone: the code
+# stays set through a fallback diff that worked.
+_add_failed = {"code": 0, "left_out": False}
+
+# Next to an index copy: where a retried `git add -N` stores the empty blob.
+_OBJECTS_DIR_SUFFIX = ".objects"
def _too_many_args(e):
@@ -434,8 +439,9 @@ def _owner_is_gone(name):
def _sweep_stale_indexes(dirpath, uid):
- """Delete index copies in `dirpath` that a killed run left behind. Only
- regular files owned by `uid` (None: no ownership check) are touched.
+ """Delete index copies in `dirpath` that a killed run left behind, and
+ their private object directories. Only regular files and directories owned
+ by `uid` (None: no ownership check) are touched.
A copy goes as soon as the hook that made it is gone: a killed hook can
leave one per run, and index-sized files fill a disk long before the age
@@ -458,12 +464,16 @@ def _sweep_stale_indexes(dirpath, uid):
p = os.path.join(dirpath, name)
try:
st = os.lstat(p)
- if not stat.S_ISREG(st.st_mode):
+ is_dir = stat.S_ISDIR(st.st_mode) and name.endswith(_OBJECTS_DIR_SUFFIX)
+ if not (is_dir or stat.S_ISREG(st.st_mode)):
continue
if uid is not None and st.st_uid != uid:
continue
if max(st.st_mtime, st.st_ctime) < cutoff or _owner_is_gone(name):
- os.unlink(p)
+ if is_dir:
+ _remove_objects_dir(p)
+ else:
+ os.unlink(p)
if time.monotonic() > deadline:
return
except OSError:
@@ -567,6 +577,24 @@ def _copy_slot(tmpdir, index_bytes=0):
os.close(held)
+def _remove_objects_dir(path):
+ """Remove a private object directory. git writes objects read-only, which
+ stops Windows from deleting them."""
+ import shutil
+ import stat
+
+ def writable_then_retry(func, p, _exc):
+ # Not a link: chmod would follow it to whatever it points at.
+ if func in (os.unlink, os.rmdir) and not os.path.islink(p):
+ os.chmod(p, stat.S_IWRITE)
+ func(p)
+
+ try:
+ shutil.rmtree(path, onerror=writable_then_retry)
+ except OSError:
+ pass
+
+
def _remove_copy(tmp_index):
"""Remove an index copy and the files git wrote next to it."""
import glob
@@ -575,6 +603,7 @@ def _remove_copy(tmp_index):
os.unlink(p)
except OSError:
pass
+ _remove_objects_dir(tmp_index + _OBJECTS_DIR_SUFFIX)
def remove_copies_on_termination():
@@ -633,6 +662,75 @@ def _hook_tmpdir():
def _note_add_failure(kind, paths):
_add_failed["code"] = kind * 100000 + min(len(paths), 99999)
+ _add_failed["left_out"] = kind != 4
+
+
+def _env_with_private_objects(env, cwd, objects_dir):
+ """`env` for a git that writes objects to `objects_dir` and still reads
+ the repository's own, wherever git says they are (a linked worktree shares
+ them). A path holding the list separator is left out, since git would
+ split it; the add then fails only if it has to read an object."""
+ out = {**env, "GIT_OBJECT_DIRECTORY": objects_dir}
+ try:
+ r = subprocess.run([*GIT_CMD, "rev-parse", "--git-path", "objects"],
+ cwd=cwd, capture_output=True, timeout=5, env=env)
+ except (subprocess.TimeoutExpired, OSError):
+ return out
+ own = os.path.join(cwd, os.fsdecode(r.stdout).strip())
+ if r.returncode == 0 and os.pathsep not in own:
+ out["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = os.pathsep.join(
+ p for p in (own, env.get("GIT_ALTERNATE_OBJECT_DIRECTORIES")) if p)
+ return out
+
+
+def _add_new_files(cwd, paths, env, tmp_index):
+ """`git add --intent-to-add` the untracked `paths` to the index copy `env`
+ names, so the diff shows them. The add has to store the empty blob, so a
+ user who cannot write the object store gets a second try that stores it in
+ a private directory next to the copy. Nothing needs that blob afterwards:
+ `git diff` reads these files from the work tree. `git stash create` would
+ fail on such an index, and only runs on a copy with nothing added.
+
+ No stdout used here (only returncode matters), but text=True 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."""
+ # The paths are file names, not patterns, for this git add only: an
+ # untracked file named `:(glob)**` must add only itself. git refuses that
+ # together with a glob or icase setting from the user's environment.
+ env = {k: v for k, v in env.items()
+ if k not in ("GIT_GLOB_PATHSPECS", "GIT_ICASE_PATHSPECS")}
+ env["GIT_LITERAL_PATHSPECS"] = "1"
+
+ def add(add_env):
+ results = _run_git_on_review_paths(
+ ["add", "--intent-to-add"], paths, timeout=10, cwd=cwd, env=add_env)
+ return next((r for r in results if r.returncode != 0), None)
+
+ try:
+ failed = add(env)
+ except subprocess.TimeoutExpired:
+ # No retry: git is slow here, not refused. The diff goes on for the
+ # tracked files, so a timeout on every turn cannot stop their reviews.
+ _note_add_failure(3, paths)
+ return
+ if not failed:
+ return
+ debug_log(f"git add -N failed: {failed.stderr[:200].decode('utf-8', errors='replace')}")
+ # Whatever happens to the retry, the diff goes on for the tracked files.
+ try:
+ objects_dir = tmp_index + _OBJECTS_DIR_SUFFIX
+ os.mkdir(objects_dir, 0o700)
+ retry_failed = add(_env_with_private_objects(env, cwd, objects_dir))
+ if retry_failed:
+ debug_log(f"git add -N retry failed: {retry_failed.stderr[:200].decode('utf-8', errors='replace')}")
+ except (subprocess.TimeoutExpired, OSError) as e:
+ debug_log(f"git add -N retry failed: {e}")
+ retry_failed = True
+ if retry_failed:
+ _note_add_failure(1 if b"empty blob" in failed.stderr else 2, paths)
+ else:
+ _note_add_failure(4, paths)
@contextlib.contextmanager
@@ -721,24 +819,7 @@ def _copied_index(cwd, top, real_index, tmpdir, untracked_paths):
else:
add_args = None
if add_args:
- # No stdout used here (only returncode matters), but text=True
- # 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.
- 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')}")
+ _add_new_files(cwd, add_args, env, tmp_index)
# A whole-tree add puts a nested repository back.
if untracked_paths is None and not _drop_gitlinks(top, env, tmp_index):
yield None
@@ -1489,6 +1570,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
MAX_FILE_DIFF_BYTES is cut down to its added lines.
"""
_path_list_too_long.clear()
+ _add_failed["left_out"] = False
pathspec = _diff_pathspec(cwd, paths)
if paths and not pathspec:
# Caller restricted to specific paths but none are inside this repo
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 950b03a7..1623e1c2 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -219,6 +219,9 @@ CONTINUATION_SUFFIX = (
"response."
)
+# New files named in the notice for a failed `git add -N`.
+_LEFT_OUT_NAMES_SHOWN = 5
+
# 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
@@ -1420,6 +1423,44 @@ def _review_failure_reason(status):
return ("reply", "the model's reply could not be read", "")
+def _left_out_files_notice(session_id, repo_root, untracked, diff_output):
+ """(one line for the terminal, text for Claude) naming the source files a
+ failed `git add -N` kept out of this Stop review, or None.
+
+ Each set of files gets one notice a session: the wake ends in another Stop
+ that fails the same way, and a notice there would wake Claude for ever. So
+ no notice unless the mark is saved. Paths are JSON quoted in ASCII: a file
+ name can hold a line break.
+ """
+ in_diff = set(extract_file_paths_from_diff(diff_output or ""))
+
+ def has_content(p):
+ try:
+ return os.path.getsize(os.path.join(repo_root, p)) > 0
+ except OSError:
+ return False
+
+ names = sorted(p for p in untracked or ()
+ if p not in in_diff and _is_reviewable_source(p) and has_content(p))
+ if not names:
+ return None
+ key = "new_files_left_out:" + hashlib.sha256(
+ "\0".join(names).encode("utf-8", "replace")).hexdigest()[:16]
+ if not atomic_check_and_mark_warning(session_id, key):
+ return None
+ if key not in load_state(session_id).get("shown_warnings", ()):
+ return None
+ _TAIL_METRICS["add_fail_told"] = len(names)
+ shown = ", ".join(json.dumps(p) for p in names[:_LEFT_OUT_NAMES_SHOWN])
+ if len(names) > _LEFT_OUT_NAMES_SHOWN:
+ shown += f" and {len(names) - _LEFT_OUT_NAMES_SHOWN} more"
+ return (f"Security review left out new files: {shown}. Log: {DEBUG_LOG_FILE}",
+ f"The security review did not see these new files, so it did not "
+ f"review them: {shown}. git could not add them to the review's "
+ f"diff. Tell the user this in one sentence, and that details are "
+ f"in {DEBUG_LOG_FILE}.")
+
+
def _exit_review_failed(kind, session_id, metrics, status, pushed="no"):
"""End a commit ("Commit") or push ("Push") review that got no verdict.
@@ -2489,10 +2530,29 @@ def handle_stop_hook(input_data):
_TAIL_METRICS["warn_fired_mask"] = warn_fired_mask
v2_metrics = {}
+ left_out = False
+ restore_paths = touched_paths
+
+ def _left_out_notice():
+ # Asked for as the row goes out: the mark must not outlive a hook
+ # killed during the review.
+ if not left_out:
+ return None
+ return _left_out_files_notice(session_id, repo_root, untracked, diff_output)
+
+ def _left_out_wake():
+ """emit_metrics arguments that wake Claude to say new files were left out."""
+ notice = _left_out_notice()
+ if not notice:
+ return {}
+ return {"rewake_summary": notice[0], "hook_event_name": hook_event_name,
+ "additional_context": (PROVENANCE_BANNER + "\n\n" + notice[1]
+ + CONTINUATION_SUFFIX + "\n")}
def _skip(reason, restore=False, **extra):
if restore:
- restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline)
+ restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline)
+ wake = _left_out_wake()
# CC truncates metrics to 10 keys by
# insertion order. v2_metrics (3) must precede sweep (3) so the v2
# diagnostics survive when extra adds touched_paths_count + ip_* keys.
@@ -2504,8 +2564,8 @@ def handle_stop_hook(input_data):
if gitutil._unparsed_diff_headers else {}),
**({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)}
if gitutil._secret_shaped_skipped else {}),
- })
- sys.exit(0)
+ }, **wake)
+ sys.exit(2 if wake else 0)
# Limit stop hook firings per asyncRewake loop to prevent infinite loops.
# fire_count auto-expires after STOP_LOOP_STATE_TTL_SEC so a stale count
@@ -2648,6 +2708,15 @@ def handle_stop_hook(input_data):
if not baseline_sha:
baseline_sha = "HEAD"
+ # New files a failed `git add -N` hid: when nothing gets reviewed they are
+ # put back, listed as touched so the next prompt keeps this baseline even
+ # if an edit tool never wrote them. A review of the tracked files goes on
+ # without them, rather than repeating that review every turn.
+ left_out = gitutil._add_failed["left_out"]
+ if left_out:
+ restore_paths = list(touched_paths) + [
+ os.path.join(repo_root, p) for p in untracked or ()]
+
if not diff_output or not diff_output.strip():
if "gave_up" in gitutil._path_list_too_long:
debug_log("Stop hook: changed paths do not fit the git commands, skipping")
@@ -2656,7 +2725,7 @@ def handle_stop_hook(input_data):
debug_log("Stop hook: no source code files among the changed paths")
_skip(7)
debug_log("Stop hook: no changes since baseline")
- _skip(6)
+ _skip(6, restore=left_out)
diff_hash = hashlib.sha256(diff_output.encode("utf-8", "replace")).hexdigest()
if snap.get("reviewed_diff_hash") == diff_hash:
@@ -2667,7 +2736,7 @@ def handle_stop_hook(input_data):
diff_files = parse_diff_into_files(diff_output)
if not diff_files:
debug_log("Stop hook: no source code files in diff")
- _skip(7)
+ _skip(7, restore=left_out)
# Mirror commit-review: hard-bail only on pathological diffs (>300 files,
# usually a bad baseline), otherwise prioritize by security-risk path
@@ -2791,6 +2860,7 @@ def handle_stop_hook(input_data):
# untracked_baseline_n is the signal for whether the UPS-time
# untracked-snapshot capture actually ran.
sweep_trimmed = {k: v for k, v in sweep.items() if k != "warn_unresolved_mask"}
+ left_out_notice = _left_out_notice()
# Guidance goes to stderr plus top-level decision/reason (see
# emit_metrics). exit(2) preserved as the asyncRewake "force fix"
# signal — that's the documented mechanism.
@@ -2812,8 +2882,9 @@ def handle_stop_hook(input_data):
**({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)}
if gitutil._secret_shaped_skipped else {}),
}, rewake_summary=_format_vulns_summary(vulns),
- additional_context=(PROVENANCE_BANNER + "\n\n"
- + concrete_guidance + CONTINUATION_SUFFIX + "\n"),
+ additional_context=(PROVENANCE_BANNER + "\n\n" + concrete_guidance
+ + ("\n\n" + left_out_notice[1] if left_out_notice else "")
+ + CONTINUATION_SUFFIX + "\n"),
hook_event_name=hook_event_name)
sys.exit(2)
@@ -2821,11 +2892,12 @@ def handle_stop_hook(input_data):
if stop_review_failed:
debug_log(f"Stop hook: review got no verdict "
f"({_review_failure_reason(llm.last_review_status())[1]})")
- restore_unreviewed_stop_state(session_id, touched_paths, snap_baseline)
+ restore_unreviewed_stop_state(session_id, restore_paths, snap_baseline)
else:
debug_log("Stop hook: no security issues found")
if is_subagent:
record_reviewed_diff(session_id, diff_hash)
+ wake = _left_out_wake()
# CC keeps the first 20 metric keys (10 in older versions), in insertion
# order, after the pv and usage keys emit_metrics puts first. The previous
# **sweep,**v2_metrics tail meant the 3 v2_metrics keys were always sliced
@@ -2847,8 +2919,8 @@ def handle_stop_hook(input_data):
if gitutil._unparsed_diff_headers else {}),
**({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)}
if gitutil._secret_shaped_skipped else {}),
- })
- sys.exit(0)
+ }, **wake)
+ sys.exit(2 if wake else 0)
_SDK_BOOTSTRAP_THROTTLE = os.path.join(_resolve_state_dir(), ".sdk_bootstrap_spawned")
diff --git a/plugins/security-guidance/tests/test_add_failure_metric.py b/plugins/security-guidance/tests/test_add_failure_metric.py
index 3a86a8ac..228b68b7 100644
--- a/plugins/security-guidance/tests/test_add_failure_metric.py
+++ b/plugins/security-guidance/tests/test_add_failure_metric.py
@@ -1,6 +1,11 @@
-"""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."""
+"""`git add --intent-to-add` puts new files in the Stop review's diff. A user
+who cannot write the object store gets a retry with a private object directory;
+a failure that stays leaves the new files for a later review, unless the turn's
+tracked files were reviewed, and tells Claude which files were left out. The
+Stop row says what happened."""
+import json
import os
+import shutil
import subprocess
import tempfile
from types import SimpleNamespace
@@ -8,11 +13,12 @@ from types import SimpleNamespace
import pytest
from conftest import (
- GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload,
- ups_payload,
+ GIT_ENV, STUB_VULN, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook,
+ stop_payload, ups_payload, write_cli,
)
import gitutil
+import security_reminder_hook as hook
def _cannot_write_read_only_dirs():
@@ -43,15 +49,16 @@ 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)
+ before = sorted(p for p in (repo / ".git" / "objects").rglob("*"))
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
+ assert m["files_reviewed"] == 1, m
+ assert m["add_fail"] == 400001
+ assert stub_api.calls
+ assert sorted(p for p in (repo / ".git" / "objects").rglob("*")) == before
- def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api, read_only_objects):
+ def test_tracked_edit_and_new_files(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)
@@ -60,21 +67,247 @@ class TestObjectStoreNotWritable:
(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
+ assert m["files_reviewed"] == 3
+ assert m["add_fail"] == 400002
+ def test_linked_worktree_and_packed_repo(self, tmp_path, hook_env, stub_api, read_only_objects):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ git(repo, "repack", "-adq")
+ wt = tmp_path / "wt"
+ git(repo, "worktree", "add", "-q", "-b", "side", str(wt))
+ read_only_objects(repo)
+ run_hook(ups_payload(wt), hook_env)
+ (wt / "handlers.py").write_text(VULN_PY)
+ m = metrics_of(run_hook(stop_payload(wt), hook_env)[1])
+ assert m["files_reviewed"] == 1, m
+ assert m["add_fail"] == 400001
-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.
+ def test_private_directory_is_gone_afterwards(self, tmp_path, monkeypatch, read_only_objects):
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ for k, v in GIT_ENV.items():
+ monkeypatch.setenv(k, v)
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ read_only_objects(repo)
+ (repo / "new.py").write_text("print('new')\n")
+ out = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")],
+ untracked_paths=["new.py"])
+ gitutil._add_failed["code"] = 0
+ assert "new.py" in out
+ assert not [p for p in d.rglob("*") if gitutil._TEMP_INDEX_PREFIX in p.name]
+
+
+class TestPathspecSettings:
+ @pytest.mark.parametrize("name", ["GIT_ICASE_PATHSPECS", "GIT_GLOB_PATHSPECS"])
+ def test_new_file_is_reviewed(self, tmp_path, hook_env, stub_api, name):
+ # git refuses --literal-pathspecs together with these two.
repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
- env = {**hook_env, "GIT_ICASE_PATHSPECS": "1"}
+ env = {**hook_env, name: "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["files_reviewed"] == 1, m
+ assert "add_fail" not in m
+
+
+@pytest.mark.skipif(os.name == "nt", reason="the stand-in git is a shell script")
+def _env_refusing_add(tmp_path, hook_env, unless_set=None):
+ """`hook_env` with a git that fails `add -N`, unless `unless_set` is in its
+ environment."""
+ d = tmp_path / "shim"
+ d.mkdir()
+ write_cli(d, "git", (
+ "import os, subprocess, sys\n"
+ f"if '--intent-to-add' in sys.argv and not os.environ.get({unless_set!r}):\n"
+ " sys.stderr.write('fatal: refused\\n')\n"
+ " sys.exit(128)\n"
+ f"sys.exit(subprocess.call([{shutil.which('git')!r}, *sys.argv[1:]]))\n"))
+ return {**hook_env, "PATH": f"{d}{os.pathsep}{hook_env['PATH']}"}
+
+
+class TestAddThatKeepsFailing:
+ def test_new_file_is_reviewed_once_git_works(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ bad = _env_refusing_add(tmp_path, hook_env)
+ run_hook(ups_payload(repo), bad)
+ (repo / "handlers.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, str(repo / "handlers.py")), bad)
+ m = metrics_of(run_hook(stop_payload(repo), bad)[1])
assert m["skip_reason"] == 6, m
assert m["add_fail"] == 200001
+ assert not stub_api.calls
+
+ run_hook(ups_payload(repo), hook_env)
+ m = metrics_of(run_hook(stop_payload(repo), hook_env)[1])
+ assert m["files_reviewed"] == 1, m
+ assert stub_api.calls
+
+ def test_file_no_edit_tool_wrote(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ bad = _env_refusing_add(tmp_path, hook_env)
+ run_hook(ups_payload(repo), bad)
+ (repo / "handlers.py").write_text(VULN_PY)
+ m = metrics_of(run_hook(stop_payload(repo), bad)[1])
+ assert m["skip_reason"] == 6, m
+
+ run_hook(ups_payload(repo), hook_env)
+ m = metrics_of(run_hook(stop_payload(repo), hook_env)[1])
+ assert m["files_reviewed"] == 1, m
+
+ def test_tracked_edit_is_still_reviewed(self, tmp_path, hook_env, stub_api):
+ repo = make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+ bad = _env_refusing_add(tmp_path, hook_env)
+ run_hook(ups_payload(repo), bad)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "a.py").write_text("print('a')\n")
+ m = metrics_of(run_hook(stop_payload(repo), bad)[1])
+ assert m["files_reviewed"] == 1, m
+ assert m["add_fail"] == 200001
+
+
+class TestNoticeForLeftOutFiles:
+ """A failure that stays is said once per set of files: Claude is woken with
+ their names, and the Stop that wake ends in stays quiet."""
+
+ @pytest.fixture
+ def bad(self, tmp_path, hook_env):
+ return _env_refusing_add(tmp_path, hook_env)
+
+ @pytest.fixture
+ def repo(self, tmp_path):
+ return make_repo(tmp_path / "repo", {"app.py": "print('hi')\n"})
+
+ def test_turn_that_only_adds_a_file(self, repo, bad, stub_api):
+ run_hook(ups_payload(repo), bad)
+ (repo / "handlers.py").write_text(VULN_PY)
+ code, out, err = run_hook(stop_payload(repo), bad)
+ assert code == 2
+ assert '"handlers.py"' in err
+ assert "Tell the user" in err
+ line = json.loads(next(x for x in out.splitlines() if x.startswith("{")))
+ assert '"handlers.py"' in line["rewakeSummary"]
+ assert line["metrics"]["skip_reason"] == 6
+ assert line["metrics"]["add_fail_told"] == 1
+ assert line["decision"] == "block"
+
+ # The Stop after the wake: same files, same failure, nothing more.
+ code, out, err = run_hook(stop_payload(repo), bad)
+ assert code == 0, err
+ assert err == ""
+ m = metrics_of(out)
+ assert m["skip_reason"] == 6
+ assert "add_fail_told" not in m
+
+ def test_new_set_of_files_gets_its_own_notice(self, repo, bad, stub_api):
+ run_hook(ups_payload(repo), bad)
+ (repo / "a.py").write_text("print('a')\n")
+ assert run_hook(stop_payload(repo), bad)[0] == 2
+ run_hook(ups_payload(repo), bad)
+ (repo / "b.py").write_text("print('b')\n")
+ code, _, err = run_hook(stop_payload(repo), bad)
+ assert code == 2
+ assert '"a.py"' in err and '"b.py"' in err
+
+ def test_tracked_edit_with_no_finding(self, repo, bad, stub_api):
+ run_hook(ups_payload(repo), bad)
+ (repo / "app.py").write_text("print('changed')\n")
+ (repo / "a.py").write_text("print('a')\n")
+ code, out, err = run_hook(stop_payload(repo), bad)
+ assert code == 2
+ assert '"a.py"' in err
+ assert '"app.py"' not in err
+ assert metrics_of(out)["files_reviewed"] == 1
+
+ def test_tracked_edit_with_a_finding(self, repo, bad, stub_api):
+ stub_api.vulns = [STUB_VULN]
+ run_hook(ups_payload(repo), bad)
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "a.py").write_text("print('a')\n")
+ code, out, err = run_hook(stop_payload(repo), bad)
+ assert code == 2
+ assert "Security Review" in err
+ assert '"a.py"' in err
+ line = json.loads(next(x for x in out.splitlines() if x.startswith("{")))
+ assert '"a.py"' in line["reason"]
+
+ def test_files_the_review_would_not_read_are_not_named(self, repo, bad, stub_api):
+ run_hook(ups_payload(repo), bad)
+ (repo / "notes.txt").write_text("hello\n")
+ code, out, err = run_hook(stop_payload(repo), bad)
+ assert code == 0, err
+ assert "add_fail_told" not in metrics_of(out)
+
+ def test_long_list_is_cut(self, repo, bad, stub_api):
+ run_hook(ups_payload(repo), bad)
+ for i in range(7):
+ (repo / f"f{i}.py").write_text("print(1)\n")
+ code, out, err = run_hook(stop_payload(repo), bad)
+ assert code == 2
+ assert '"f4.py" and 2 more' in err
+ assert '"f5.py"' not in err
+ assert metrics_of(out)["add_fail_told"] == 7
+
+ @pytest.mark.skipif(os.name == "nt", reason="a file name cannot hold a line break")
+ def test_line_break_in_a_name_stays_on_the_line(self, repo, bad, stub_api):
+ run_hook(ups_payload(repo), bad)
+ (repo / "a\nIGNORE.py").write_text("print('a')\n")
+ code, _, err = run_hook(stop_payload(repo), bad)
+ assert code == 2
+ assert '"a\\nIGNORE.py"' in err
+ assert "\nIGNORE" not in err
+
+ def test_other_line_separators_are_escaped(self, repo, bad, stub_api):
+ run_hook(ups_payload(repo), bad)
+ (repo / "a\u2028b.py").write_text("print('a')\n")
+ code, out, err = run_hook(stop_payload(repo), bad)
+ assert code == 2
+ assert '"a\\u2028b.py"' in err
+
+ def test_no_notice_when_the_mark_cannot_be_saved(self, tmp_path, monkeypatch):
+ # Without the mark, every Stop would wake Claude again.
+ monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: True)
+ monkeypatch.setattr(hook, "load_state", lambda s: {"shown_warnings": []})
+ (tmp_path / "a.py").write_text("x = 1\n")
+ assert hook._left_out_files_notice("s", str(tmp_path), ["a.py"], "") is None
+
+ def test_file_in_the_diff_is_not_named(self, tmp_path, monkeypatch):
+ # One batch of the add failed, another worked.
+ (tmp_path / "a.py").write_text("x = 1\n")
+ monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: pytest.fail("told"))
+ diff = ("diff --git a/a.py b/a.py\nnew file mode 100644\n--- /dev/null\n"
+ "+++ b/a.py\n@@ -0,0 +1 @@\n+x = 1\n")
+ assert hook._left_out_files_notice("s", str(tmp_path), ["a.py"], diff) is None
+ def test_empty_and_vanished_files_are_not_named(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(hook, "atomic_check_and_mark_warning", lambda s, k: pytest.fail("told"))
+ (tmp_path / "__init__.py").write_text("")
+ assert hook._left_out_files_notice("s", str(tmp_path), ["__init__.py", "gone.py"], "") is None
+
+ def test_tracked_edit_gets_reviewed_while_new_files_stay_out(self, repo, bad, stub_api):
+ # A failure on every turn must not stop later reviews of tracked files.
+ run_hook(ups_payload(repo), bad)
+ (repo / "a.py").write_text("print('a')\n")
+ assert run_hook(stop_payload(repo), bad)[0] == 2
+ run_hook(ups_payload(repo), bad)
+ (repo / "app.py").write_text(VULN_PY)
+ code, out, _ = run_hook(stop_payload(repo), bad)
+ assert code == 0
+ assert metrics_of(out)["files_reviewed"] == 1
+ assert stub_api.calls
+
+ def test_retry_that_works_says_nothing(self, repo, tmp_path, hook_env, stub_api):
+ env = _env_refusing_add(tmp_path, hook_env, unless_set="GIT_OBJECT_DIRECTORY")
+ run_hook(ups_payload(repo), env)
+ (repo / "handlers.py").write_text(VULN_PY)
+ code, out, err = run_hook(stop_payload(repo), env)
+ assert code == 0, err
+ m = metrics_of(out)
+ assert m["add_fail"] == 400001
+ assert "add_fail_told" not in m
+
+
+class TestStopRow:
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)
@@ -122,13 +355,26 @@ class TestGetGitDiff:
untracked_paths=["new.py"])
assert gitutil._add_failed["code"] == 200001
- def test_timeout_counts_and_still_gives_no_diff(self, repo, monkeypatch):
+ def test_timeout_counts_and_keeps_the_tracked_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
+ (repo / "app.py").write_text("print('edited')\n")
+ out = gitutil.get_git_diff(str(repo), "HEAD",
+ paths=[str(repo / "new.py"), str(repo / "app.py")],
+ untracked_paths=["new.py"])
+ assert "app.py" in out
+ assert "new.py" not in out
+ assert gitutil._add_failed == {"code": 300001, "left_out": True}
- def test_object_store_refusal(self, repo, monkeypatch):
+ def test_a_fallback_diff_that_works_clears_left_out(self, repo, monkeypatch):
+ self._adds_fail_with(monkeypatch, subprocess.TimeoutExpired("git", 10))
+ gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")],
+ untracked_paths=["new.py"])
+ monkeypatch.undo()
+ assert "new.py" in gitutil.get_git_diff(
+ str(repo), "HEAD", paths=[str(repo / "new.py")], untracked_paths=["new.py"])
+ assert gitutil._add_failed == {"code": 300001, "left_out": False}
+
+ def test_object_store_refusal_on_both_tries(self, repo, monkeypatch):
self._adds_fail_with(monkeypatch, [SimpleNamespace(
returncode=128,
stderr=b"fatal: cannot create an empty blob in the object database")])
@@ -136,8 +382,92 @@ class TestGetGitDiff:
untracked_paths=["new.py"])
assert gitutil._add_failed["code"] == 100001
+ def test_retry_reads_the_repositorys_objects_and_writes_elsewhere(self, repo, monkeypatch):
+ seen = []
+ real = gitutil._run_git_on_review_paths
+
+ def run(args, paths, timeout, **kwargs):
+ if args[0] != "add":
+ return real(args, paths, timeout, **kwargs)
+ seen.append(kwargs["env"])
+ return real(args, paths, timeout, **kwargs) if len(seen) > 1 else [
+ SimpleNamespace(returncode=128, stderr=b"nope")]
+
+ monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run)
+ out = gitutil.get_git_diff(str(repo), "HEAD", paths=[str(repo / "new.py")],
+ untracked_paths=["new.py"])
+ assert "new.py" in out
+ assert "GIT_OBJECT_DIRECTORY" not in seen[0]
+ assert seen[1]["GIT_OBJECT_DIRECTORY"].endswith(".objects")
+ assert os.path.samefile(seen[1]["GIT_ALTERNATE_OBJECT_DIRECTORIES"],
+ repo / ".git" / "objects")
+ assert gitutil._add_failed["code"] == 400001
+
+ def test_retry_timeout_keeps_the_tracked_diff(self, repo, monkeypatch):
+ (repo / "app.py").write_text("print('changed')\n")
+ real = gitutil._run_git_on_review_paths
+ adds = []
+
+ def run(args, paths, timeout, **kwargs):
+ if args[0] != "add":
+ return real(args, paths, timeout, **kwargs)
+ adds.append(args)
+ if len(adds) > 1:
+ raise subprocess.TimeoutExpired("git", 10)
+ return [SimpleNamespace(returncode=128, stderr=b"fatal: nope")]
+
+ monkeypatch.setattr(gitutil, "_run_git_on_review_paths", run)
+ out = gitutil.get_git_diff(str(repo), "HEAD", untracked_paths=["new.py"])
+ assert "app.py" in out
+ assert gitutil._add_failed["code"] == 200001
+
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
+
+
+class TestLeftovers:
+ def _private_dir(self, parent, name):
+ d = parent / name
+ (d / "e6").mkdir(parents=True)
+ blob = d / "e6" / "9de29"
+ blob.write_bytes(b"x")
+ blob.chmod(0o444)
+ return d
+
+ def test_removed_with_its_copy(self, tmp_path):
+ copy = tmp_path / "security_hook_idx_pid1_abcdefgh"
+ copy.write_bytes(b"i")
+ self._private_dir(tmp_path, copy.name + ".objects")
+ gitutil._remove_copy(str(copy))
+ assert not list(tmp_path.iterdir())
+
+ @pytest.mark.skipif(os.name == "nt", reason="no pid check on Windows")
+ def test_killed_hooks_directory_is_swept(self, tmp_path):
+ p = subprocess.Popen(["git", "--version"], stdout=subprocess.DEVNULL)
+ p.wait()
+ self._private_dir(tmp_path, f"security_hook_idx_pid{p.pid}_abcdefgh.objects")
+ gitutil._sweep_stale_indexes(str(tmp_path), None)
+ assert not list(tmp_path.iterdir())
+
+ def test_live_hooks_directory_stays(self, tmp_path):
+ self._private_dir(tmp_path, f"security_hook_idx_pid{os.getpid()}_abcdefgh.objects")
+ gitutil._sweep_stale_indexes(str(tmp_path), None)
+ assert list(tmp_path.iterdir())
+
+ def test_other_directories_stay(self, tmp_path):
+ (tmp_path / "security_hook_idx_pid1_abcdefgh.other").mkdir()
+ gitutil._sweep_stale_indexes(str(tmp_path), None)
+ assert list(tmp_path.iterdir())
+
+ @pytest.mark.skipif(os.name == "nt", reason="needs symlinks")
+ def test_link_at_the_private_directory_is_not_followed(self, tmp_path):
+ victim = tmp_path / "victim"
+ victim.mkdir()
+ (victim / "keep").write_text("x")
+ copy = tmp_path / "security_hook_idx_pid1_abcdefgh"
+ (tmp_path / (copy.name + ".objects")).symlink_to(victim)
+ gitutil._remove_copy(str(copy))
+ assert (victim / "keep").exists()