summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-27 20:08:34 +0000
committerClaude <noreply@anthropic.com>2026-10-27 21:23:30 +0000
commitf1b930f0368e0e0a096442eaa9c1c951b8076b71 (patch)
treeb9c2a907269897c4131ce4c64eefd5c9652e4865 /plugins
parentf8c5e7a1dcb71b10cb74586224b5401f3de5db28 (diff)
security-guidance: take the turn baseline without git stash createmhegazy/sg-prompt-snapshot
stash create checks the work tree on one thread. add -u into the throwaway index copy, write-tree and commit-tree produce the same commit and use git's index preload instead, which matters where each file status is slow. See #6854.
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py151
-rw-r--r--plugins/security-guidance/hooks/gitutil.py8
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py16
-rw-r--r--plugins/security-guidance/tests/test_baseline_snapshot.py257
-rw-r--r--plugins/security-guidance/tests/test_git_index_locks.py19
-rw-r--r--plugins/security-guidance/tests/test_slow_prompt_metrics.py14
-rw-r--r--plugins/security-guidance/tests/test_stop_scope_metrics.py10
-rw-r--r--plugins/security-guidance/tests/test_temp_index_cleanup.py4
8 files changed, 410 insertions, 69 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 9ba40385..de9719cf 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -13,6 +13,7 @@ import sys
import time
from _base import debug_log, portable_output, _PV
+import gitutil
from gitutil import (
GIT_CMD,
_git_dir, _git_toplevel, _git_status_porcelain,
@@ -319,7 +320,7 @@ def get_baseline_file_content(session_id, file_path, cwd):
# How the last capture_git_baseline call got its SHA: 0 a real snapshot,
-# 1 `stash create` failed and HEAD was returned, 2 no index copy and HEAD was
+# 1 the snapshot failed and HEAD was returned, 2 no index copy and HEAD was
# returned. With 1 or 2 the next Stop review cannot tell the turn's changes
# from uncommitted work that was already there. Stored with baseline_sha.
# Telemetry only.
@@ -328,29 +329,110 @@ last_baseline_fail = 0
last_index_entries = None
+# Who the snapshot commit is made by. Set on every commit-tree call, so the
+# user's own name never appears on a commit they did not make and a repo with
+# no identity configured still works. The commit object does land in
+# `.git/objects`, but nothing refers to it, like the one `git stash create`
+# used to make here: it is prunable from the moment it is written.
+_SNAPSHOT_IDENT = {
+ "GIT_AUTHOR_NAME": "security-guidance", "GIT_AUTHOR_EMAIL": "security-guidance@localhost",
+ "GIT_COMMITTER_NAME": "security-guidance", "GIT_COMMITTER_EMAIL": "security-guidance@localhost",
+}
+
+# The whole snapshot, not one command: `stash create` was capped at 15 s and a
+# per-command cap would let a slow filesystem hold the prompt for far longer.
+_SNAPSHOT_BUDGET_S = 15
+
+
+def _snapshot_commit(cwd, env, head_tree):
+ """A commit of every tracked change, on the index copy `env` names.
+
+ Returns its SHA, "" when nothing tracked has changed (so the caller uses
+ HEAD, `head_tree` being HEAD's tree), or None when git refused or the
+ time budget ran out.
+
+ No `--missing-ok`: git counts a partial clone's promisor blobs as
+ present, so write-tree neither fetches nor fails on one, and the
+ existence check it would turn off is worth keeping.
+ """
+ deadline = time.monotonic() + _SNAPSHOT_BUDGET_S
+
+ def run(args, extra=None):
+ left = deadline - time.monotonic()
+ if left <= 0:
+ raise subprocess.TimeoutExpired(args, _SNAPSHOT_BUDGET_S)
+ return subprocess.run(
+ [*GIT_CMD, *args], cwd=cwd, capture_output=True, timeout=left,
+ env={**env, **(extra or {})},
+ )
+
+ # No pathspec: `add -u` has staged the whole work tree, whatever directory
+ # of it `cwd` is, since git 2.0. `-- :/` would say the same but fails
+ # outright under a user's GIT_LITERAL_PATHSPECS.
+ add = run(["add", "-u"])
+ if add.returncode != 0:
+ debug_log(f"Snapshot: add -u failed: {_stderr_of(add)}")
+ return None
+ tree = run(["write-tree"])
+ sha = (tree.stdout or b"").decode("utf-8", errors="replace").strip()
+ if tree.returncode != 0 or not sha:
+ debug_log(f"Snapshot: write-tree failed: {_stderr_of(tree)}")
+ return None
+ if sha == head_tree:
+ return ""
+ if gitutil.last_dropped_gitlinks:
+ # A nested repository's entry is gone from the index copy, so the
+ # tree cannot equal HEAD's even on a clean work tree. Ask whether
+ # anything but those entries differs, rather than writing a commit
+ # object on every prompt in a repo with submodules.
+ same = run(["diff-tree", "--quiet", "--ignore-submodules=all", head_tree, sha])
+ if same.returncode == 0:
+ return ""
+ commit = run(["-c", "commit.gpgsign=false", "commit-tree", sha, "-p", "HEAD",
+ "-m", "security-guidance turn baseline"], _SNAPSHOT_IDENT)
+ out = (commit.stdout or b"").decode("utf-8", errors="replace").strip()
+ if commit.returncode != 0 or not out:
+ debug_log(f"Snapshot: commit-tree failed: {_stderr_of(commit)}")
+ return None
+ return out
+
+
+def _stderr_of(result):
+ return (result.stderr or b"").decode("utf-8", errors="replace").strip()[:200]
+
+
def capture_git_baseline(cwd):
"""
Capture a git ref representing the current working tree state.
- Uses `git stash create` which creates a commit object for the current state
- (HEAD + uncommitted changes) without modifying the stash list or working tree.
+ Builds a commit object for the current state (HEAD + uncommitted changes)
+ without touching the stash list or the working tree: `add -u` stages every
+ tracked change into a throwaway index copy, `write-tree` turns that into a
+ tree, and `commit-tree` hangs it off HEAD.
Falls back to HEAD if the working tree is clean.
Returns the SHA string, or None if not in a git repo or if the repo has no commits.
- `stash create` runs on a throwaway copy of the index (GIT_INDEX_FILE), so
- its `index.lock` and `index.stash.<pid>` files land next to the copy, not
- in `.git`: it cannot collide with a concurrent git command, and a timeout
- kill cannot leave a lock that blocks the user's next one.
- GIT_OPTIONAL_LOCKS does not cover stash. Copying the real index without a
- lock is safe: git replaces it by atomic rename.
-
- NOTE: `git stash create` does NOT capture untracked files. UPS pairs this
+ This was `git stash create`, which does the same thing in one command but
+ checks the work tree on a single thread, while `add -u` uses git's index
+ preload (one thread per 500 entries, up to 20). On a filesystem where each
+ file status is slow — a WSL repository on a Windows drive, a network mount
+ — that is the whole cost of the prompt: see #6854, where `stash create`
+ took 4 s on 1,424 files and never finished on 10,000.
+
+ The commands run on a throwaway copy of the index (GIT_INDEX_FILE), so
+ their `index.lock` lands next to the copy, not in `.git`: they cannot
+ collide with a concurrent git command, and a timeout kill cannot leave a
+ lock that blocks the user's next one. GIT_OPTIONAL_LOCKS does not cover
+ these. Copying the real index without a lock is safe: git replaces it by
+ atomic rename.
+
+ NOTE: the snapshot does NOT capture untracked files. UPS pairs this
SHA with a `_list_untracked()` snapshot stored as `untracked_at_baseline`,
and `compute_v2_review_set` subtracts that set so pre-existing untracked
files are not reviewed as Claude-authored. UPS takes no snapshot while the
Stop review, its only reader, is switched off.
"""
# stdout is a SHA so text=True is safe on stdout, but a non-ASCII
- # filename in `git stash create`'s STDERR warning (e.g. a worktree
+ # filename in git's STDERR warning (e.g. a worktree
# with `Ávila_report.txt` triggers a quotePath/locale warning) would
# trip the stderr reader thread on Windows cp1252. Decode both streams
# leniently for symmetry with _list_untracked. See #2056.
@@ -358,15 +440,19 @@ def capture_git_baseline(cwd):
last_baseline_fail = 0
last_index_entries = None
try:
- # Check if HEAD exists (i.e., repo has at least one commit)
+ # HEAD's commit and its tree in one call: the commit is the answer
+ # for a clean tree, the tree is what the snapshot is compared with.
+ # A failure here means the repo has no commits — skip the review
+ # rather than create commits in the user's repo.
head_check = subprocess.run(
- [*GIT_CMD, "rev-parse", "HEAD"],
+ [*GIT_CMD, "rev-parse", "HEAD", "HEAD^{tree}"],
cwd=cwd, capture_output=True, timeout=5
)
- if head_check.returncode != 0:
- # No commits yet — skip review rather than creating commits in the user's repo
+ head_out = (head_check.stdout or b"").decode("utf-8", errors="replace").split()
+ if head_check.returncode != 0 or len(head_out) != 2:
debug_log("No commits in repo, skipping baseline capture")
return None
+ head_sha, head_tree = head_out
sha = ""
# untracked_paths=[]: a plain copy of the index, no `add -N` pass.
@@ -375,25 +461,14 @@ def capture_git_baseline(cwd):
# back to HEAD.
if env is not None:
last_index_entries = index_entry_count(env["GIT_INDEX_FILE"])
- result = subprocess.run(
- [*GIT_CMD, "stash", "create"],
- cwd=cwd, capture_output=True, timeout=15, env=env
- )
- sha = (result.stdout or b"").decode("utf-8", errors="replace").strip()
- if not sha and result.returncode != 0:
+ sha = _snapshot_commit(cwd, env, head_tree)
+ if sha is None:
last_baseline_fail = 1
+ sha = ""
else:
last_baseline_fail = 2
- if sha:
- return sha
-
- # Working tree is clean — stash create returns empty. Use HEAD.
- result = subprocess.run(
- [*GIT_CMD, "rev-parse", "HEAD"],
- cwd=cwd, capture_output=True, timeout=5
- )
- sha = (result.stdout or b"").decode("utf-8", errors="replace").strip()
- return sha if sha else None
+ # No snapshot: nothing tracked has changed, or it could not be taken.
+ return sha or head_sha
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
debug_log(f"Failed to capture git baseline: {e}")
return None
@@ -997,12 +1072,12 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
review_set = (files dirty vs current HEAD, plus files committed this turn
when HEAD advanced linearly) ∩ (files whose content differs from the
- pre-turn stash baseline). The first term is immune to checkout/pull
+ pre-turn baseline). The first term is immune to checkout/pull
ballooning; the second filters out the user's untouched pre-turn WIP.
Falls back to dirty_now alone when no baseline is available.
untracked_at_baseline: {repo-root-relative path: mtime_ns} captured at
- UPS. `git stash create` doesn't include untracked files, so without this
+ UPS. The baseline snapshot doesn't include untracked files, so without this
snapshot a pre-existing untracked file looks "new since baseline" forever.
A file is excluded only if it was untracked at baseline AND its mtime is
unchanged — an in-place edit during the turn is still reviewed.
@@ -1073,11 +1148,11 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
dirty_now |= _git_name_only(repo, f"{head_at_capture}..HEAD") or set()
diff_base = head_at_capture
- # changed_since: tracked files vs the stash baseline (no `add -N` — the
- # stash never contained untracked files anyway), then union with
+ # changed_since: tracked files vs the turn baseline (no `add -N` — the
+ # baseline never contained untracked files anyway), then union with
# currently-untracked. The previous `include_untracked=True` arm cost a
# full `git add -N .` (slow in large repos) per call to surface
- # untracked files in the diff output — but `git diff <stash>` already
+ # untracked files in the diff output — but `git diff <baseline>` already
# lists them as "only in worktree" without that, and we have the explicit
# set from status regardless.
if baseline_sha:
@@ -1087,7 +1162,7 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel
else:
changed_since = None
# changed_since is None on missing baseline OR on git error (e.g. the
- # dangling stash SHA was pruned). Either way, don't intersect with ∅ —
+ # dangling baseline SHA was pruned). Either way, don't intersect with ∅ —
# that would silently zero the review set. Fall back to dirty_now.
review_set = (dirty_now & changed_since) if changed_since is not None else dirty_now
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index ec51e3c6..de764d57 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -794,6 +794,11 @@ def _gitlink_paths(top, env):
return found
+# True when the last _drop_gitlinks call removed at least one gitlink, so the
+# index copy and HEAD can no longer have the same tree even on a clean tree.
+last_dropped_gitlinks = False
+
+
def _drop_gitlinks(top, env, tmp_index):
"""Remove the gitlink (mode 160000) entry of every nested repository from
the index copy that `env` names, never from the real index, before
@@ -805,6 +810,8 @@ def _drop_gitlinks(top, env, tmp_index):
`git stash create` fails on the empty directory. `top` is the work
tree's top directory. Returns True on success, False on any failure; the
copy must not be used then."""
+ global last_dropped_gitlinks
+ last_dropped_gitlinks = False
try:
if not _may_have_gitlinks(tmp_index):
return True
@@ -829,6 +836,7 @@ def _drop_gitlinks(top, env, tmp_index):
return False
# Keep the mtime the copy came with; see _copied_index.
os.utime(tmp_index, ns=(mtime_ns, mtime_ns))
+ last_dropped_gitlinks = True
debug_log(f"gitlink entries (nested repositories) removed from the "
f"index copy: {len(nested)}; their contents are not reviewed")
return True
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 3efe344e..a4dee788 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -23,7 +23,7 @@ The plugin has two layers:
## How the git baseline works
-On each UserPromptSubmit, the plugin runs `git stash create` to get a SHA representing
+On each UserPromptSubmit, the plugin takes a snapshot commit to get a SHA representing
the current working tree state (HEAD + any uncommitted changes). This SHA is saved to
the session state file. When the Stop hook fires, it runs `git diff <baseline_sha>` to
get only the changes made since that snapshot. After analysis, the baseline is updated
@@ -760,7 +760,7 @@ def handle_user_prompt_submit(input_data):
# The untracked snapshot has one reader: the Stop-hook diff review, which
# skips before reading it when either of these switches is off (see
# handle_stop_hook). Listing the worktree on every prompt then buys
- # nothing, so only the stash baseline (still read by the Write pattern
+ # nothing, so only the turn baseline (still read by the Write pattern
# filter) is captured.
snapshot_untracked = ENABLE_STOP_REVIEW and ENABLE_CODE_SECURITY_REVIEW
spent = {"baseline": 0.0, "untracked": 0.0}
@@ -775,15 +775,15 @@ def handle_user_prompt_submit(input_data):
def _capture(repo_cwd):
if not snapshot_untracked:
return _timed("baseline", capture_git_baseline, repo_cwd), None
- # stash-create and ls-files both walk the worktree (~2-5s each in a
+ # the baseline snapshot and ls-files both walk the worktree (~2-5s each in a
# very large repo). Run them concurrently so UPS latency stays
# ≈ max(both).
import concurrent.futures as _cf
with _cf.ThreadPoolExecutor(max_workers=2) as _ex:
_f_sha = _ex.submit(_timed, "baseline", capture_git_baseline, repo_cwd)
_f_ut = _ex.submit(_timed, "untracked", _list_untracked, repo_cwd)
- # Taken whether or not the stash produced a SHA. `git stash
- # create` returns empty when there are no TRACKED changes, but
+ # Taken whether or not the snapshot produced a SHA. The baseline
+ # falls back to HEAD when there are no TRACKED changes, but
# pre-existing untracked files still need to be excluded from the
# next Stop's review_set — otherwise an untracked-only working
# tree gets every untracked file reviewed on every turn until
@@ -851,7 +851,7 @@ def handle_user_prompt_submit(input_data):
# When the turn began: what a Stop review in another checkout has
# to go on.
state["prompt_at"] = captured_at
- # untracked_at_baseline is independent of whether the stash produced
+ # untracked_at_baseline is independent of whether the snapshot produced
# a SHA, so compute_v2_review_set's preexisting-untracked exclusion
# works in untracked-only trees. None means no snapshot was taken
# (Stop review off): drop the previous one, which belongs to an older
@@ -2615,13 +2615,13 @@ def handle_stop_hook(input_data):
f"{MAX_REVIEW_SET_PATHS} paths), skipping")
_skip(8)
# Run from repo_root so the toplevel-relative review_paths resolve.
- # Diff CONTENT against the turn-start stash (baseline_sha) so the LLM
+ # Diff CONTENT against the turn-start snapshot (baseline_sha) so the LLM
# sees only this-turn edits — diffing against HEAD includes the user's
# pre-turn uncommitted WIP, which inflates review_ms and can re-flag
# the same pre-existing pattern every turn. The file LIST still comes
# from git state (compute_v2_review_set), so Bash/subagent edits are
# caught either way. Fall back to diff_base (HEAD/head_at_capture)
- # when the stash is missing or pruned.
+ # when the baseline commit is missing or pruned.
content_base = baseline_sha or diff_base
diff_output = get_git_diff(repo_root, content_base, full_context=False,
paths=review_paths, untracked_paths=untracked)
diff --git a/plugins/security-guidance/tests/test_baseline_snapshot.py b/plugins/security-guidance/tests/test_baseline_snapshot.py
new file mode 100644
index 00000000..eaa0e5c2
--- /dev/null
+++ b/plugins/security-guidance/tests/test_baseline_snapshot.py
@@ -0,0 +1,257 @@
+"""The turn baseline is a commit of the tracked changes (#6854), where it used
+to be `git stash create`. These pin the states where the two could differ."""
+import os
+import subprocess
+
+import pytest
+
+import diffstate
+import gitutil
+from conftest import GIT_ENV, git, make_repo
+
+
+@pytest.fixture(autouse=True)
+def safe_env(monkeypatch):
+ for k, v in gitutil.git_config_env(gitutil.SAFE_GIT_CONFIG).items():
+ monkeypatch.setenv(k, v)
+
+
+def _tree(repo, sha):
+ return git(repo, "rev-parse", f"{sha}^{{tree}}").strip()
+
+
+def _plain_stash_tree(repo):
+ """What `git stash create` would have produced, on the real index."""
+ out = subprocess.run(["git", "stash", "create"], cwd=repo, capture_output=True,
+ text=True, env={**os.environ, **GIT_ENV})
+ sha = out.stdout.strip()
+ return _tree(repo, sha) if sha else _tree(repo, "HEAD")
+
+
+def _capture(repo):
+ sha = diffstate.capture_git_baseline(str(repo))
+ return sha, diffstate.last_baseline_fail
+
+
+def _repo(tmp_path, name="r"):
+ return make_repo(tmp_path / name, {"a.txt": "a\n", "b.txt": "b\n", "d/c.txt": "c\n"})
+
+
+def test_unstaged_and_staged_changes_are_in_the_snapshot(tmp_path):
+ repo = _repo(tmp_path)
+ (repo / "a.txt").write_text("staged\n")
+ git(repo, "add", "a.txt")
+ (repo / "a.txt").write_text("staged\nunstaged\n")
+ (repo / "b.txt").write_text("also dirty\n")
+ sha, fail = _capture(repo)
+ assert fail == 0
+ assert git(repo, "show", f"{sha}:a.txt") == "staged\nunstaged\n"
+ assert git(repo, "show", f"{sha}:b.txt") == "also dirty\n"
+ assert git(repo, "rev-parse", f"{sha}^").strip() == git(repo, "rev-parse", "HEAD").strip()
+
+
+@pytest.mark.parametrize("state", [
+ "unstaged", "staged", "staged-plus-unstaged", "worktree-delete", "staged-delete",
+ "staged-rename", "staged-new", "mode-change", "symlink", "untracked-only", "stale-stat",
+])
+def test_same_tree_as_stash_create(tmp_path, state):
+ repo = _repo(tmp_path, state)
+ if state == "unstaged":
+ (repo / "a.txt").write_text("x\n")
+ elif state == "staged":
+ (repo / "a.txt").write_text("x\n"); git(repo, "add", "a.txt")
+ elif state == "staged-plus-unstaged":
+ (repo / "a.txt").write_text("x\n"); git(repo, "add", "a.txt")
+ (repo / "a.txt").write_text("y\n")
+ elif state == "worktree-delete":
+ (repo / "a.txt").unlink()
+ elif state == "staged-delete":
+ git(repo, "rm", "-q", "a.txt")
+ elif state == "staged-rename":
+ git(repo, "mv", "a.txt", "z.txt")
+ elif state == "staged-new":
+ (repo / "n.txt").write_text("n\n"); git(repo, "add", "n.txt")
+ elif state == "mode-change":
+ os.chmod(repo / "a.txt", 0o755)
+ elif state == "symlink":
+ (repo / "a.txt").unlink(); os.symlink("b.txt", repo / "a.txt")
+ elif state == "untracked-only":
+ (repo / "u.txt").write_text("u\n")
+ elif state == "stale-stat":
+ t = os.stat(repo / "a.txt").st_mtime + 2
+ os.utime(repo / "a.txt", (t, t))
+ # Capture FIRST: `git stash create` refreshes the real index, which would
+ # cancel the stale stat entry the last state is about.
+ sha, fail = _capture(repo)
+ assert fail == 0
+ assert _tree(repo, sha) == _plain_stash_tree(repo)
+
+
+def test_clean_tree_is_head(tmp_path):
+ repo = _repo(tmp_path)
+ assert _capture(repo) == (git(repo, "rev-parse", "HEAD").strip(), 0)
+
+
+def test_conflicted_merge_snapshots_the_conflicted_files(tmp_path):
+ """`stash create` refused here and the whole conflicted file was then
+ reviewed as the turn's work. `add -u` resolves the conflict in the index
+ COPY, so the baseline holds what the work tree had, markers and all, and
+ the user's own index keeps its unmerged entries."""
+ repo = _repo(tmp_path)
+ git(repo, "checkout", "-q", "-b", "other")
+ (repo / "a.txt").write_text("theirs\n"); git(repo, "commit", "-qam", "theirs")
+ git(repo, "checkout", "-q", "main")
+ (repo / "a.txt").write_text("ours\n"); git(repo, "commit", "-qam", "ours")
+ subprocess.run(["git", "merge", "other"], cwd=repo, capture_output=True,
+ env={**os.environ, **GIT_ENV})
+ assert "UU" in git(repo, "status", "--porcelain")
+ conflicted = (repo / "a.txt").read_text()
+ sha, fail = _capture(repo)
+ assert fail == 0
+ assert git(repo, "show", f"{sha}:a.txt") == conflicted
+ assert "UU" in git(repo, "status", "--porcelain")
+ assert git(repo, "ls-files", "-u")
+
+
+def test_intent_to_add_file_is_snapshotted_with_its_content(tmp_path):
+ """`git add -N` marks a file to be committed without staging content.
+ `stash create` refused on such an index and the baseline fell back to
+ HEAD, so the file's pre-existing content was reviewed as the turn's work.
+ The snapshot holds that content, so only what the turn changes is."""
+ repo = _repo(tmp_path)
+ (repo / "n.txt").write_text("secret = 1\n")
+ git(repo, "add", "-N", "n.txt")
+ sha, fail = _capture(repo)
+ assert fail == 0
+ assert sha != git(repo, "rev-parse", "HEAD").strip()
+ assert git(repo, "show", f"{sha}:n.txt") == "secret = 1\n"
+ # The path is still named in the review set, as it was before, but its
+ # content is in the baseline now, so the reviewer is sent nothing for it
+ # where `stash create` failing sent the whole file.
+
+
+def test_subdirectory_cwd_snapshots_the_whole_tree(tmp_path):
+ repo = _repo(tmp_path)
+ (repo / "a.txt").write_text("top changed\n")
+ (repo / "d" / "c.txt").write_text("below changed\n")
+ sha, fail = _capture(repo / "d")
+ assert fail == 0
+ assert git(repo, "show", f"{sha}:a.txt") == "top changed\n"
+ assert git(repo, "show", f"{sha}:d/c.txt") == "below changed\n"
+
+
+def test_nested_repository_stays_out_of_the_snapshot(tmp_path):
+ """A directory with its own .git is another repository: #6837 keeps its
+ gitlink out of the index copy, so it must stay out of the tree too."""
+ repo = _repo(tmp_path)
+ nested = repo / "vendor"
+ make_repo(nested, {"x.txt": "x\n"})
+ git(repo, "add", "vendor")
+ git(repo, "commit", "-qm", "add nested")
+ (nested / "x.txt").write_text("changed inside\n")
+ (repo / "a.txt").write_text("changed outside\n")
+ sha, fail = _capture(repo)
+ assert fail == 0
+ assert git(repo, "show", f"{sha}:a.txt") == "changed outside\n"
+ assert "vendor" not in git(repo, "ls-tree", "--name-only", sha)
+
+
+def test_clean_tree_with_a_nested_repository_is_head(tmp_path):
+ """The index copy has no gitlink, so its tree can never equal HEAD's.
+ Without a second look that would mint a commit object on every prompt in
+ a repo with submodules, and the baseline would be a prunable dangling
+ commit instead of HEAD."""
+ repo = _repo(tmp_path)
+ make_repo(repo / "vendor", {"x.txt": "x\n"})
+ git(repo, "add", "vendor")
+ git(repo, "commit", "-qm", "add nested")
+ head = git(repo, "rev-parse", "HEAD").strip()
+ assert _capture(repo) == (head, 0)
+
+ # A change inside the nested repository is still not this repo's work.
+ (repo / "vendor" / "x.txt").write_text("changed inside\n")
+ assert _capture(repo) == (head, 0)
+
+ # A real change outside it still gets a snapshot.
+ (repo / "a.txt").write_text("changed outside\n")
+ sha, fail = _capture(repo)
+ assert fail == 0 and sha != head
+ assert git(repo, "show", f"{sha}:a.txt") == "changed outside\n"
+
+
+def test_snapshot_leaves_the_real_index_and_worktree_alone(tmp_path):
+ repo = _repo(tmp_path)
+ (repo / "a.txt").write_text("dirty\n")
+ before_index = (repo / ".git" / "index").read_bytes()
+ before_status = git(repo, "status", "--porcelain")
+ before_stash = git(repo, "stash", "list")
+ _capture(repo)
+ assert (repo / ".git" / "index").read_bytes() == before_index
+ assert git(repo, "status", "--porcelain") == before_status
+ assert git(repo, "stash", "list") == before_stash
+ assert [p for p in os.listdir(repo / ".git") if p.startswith("index.")] == []
+
+
+def test_snapshot_commit_is_unreferenced(tmp_path):
+ repo = _repo(tmp_path)
+ (repo / "a.txt").write_text("dirty\n")
+ sha, _ = _capture(repo)
+ assert sha not in git(repo, "log", "--all", "--format=%H")
+ assert git(repo, "rev-parse", "HEAD").strip() != sha
+
+
+def test_partial_clone_snapshots_without_fetching(tmp_path):
+ """A blobless clone has no blob for an unchanged file. git counts a
+ promisor object as present, so write-tree neither fetches nor fails;
+ this pins that, since the snapshot must never make a network call."""
+ origin = _repo(tmp_path, "origin")
+ git(origin, "config", "uploadpack.allowFilter", "true")
+ for i in range(3):
+ (origin / f"big{i}.txt").write_text(f"content {i}\n")
+ git(origin, "add", "-A")
+ git(origin, "commit", "-qm", "more")
+ clone = tmp_path / "clone"
+ subprocess.run(["git", "clone", "-q", "--filter=blob:none", "--no-local",
+ str(origin), str(clone)], check=True, capture_output=True,
+ env={**os.environ, **GIT_ENV})
+ # Nothing can be fetched from here on: a snapshot that tried would fail.
+ git(clone, "config", "remote.origin.url", "/nonexistent-origin")
+ (clone / "a.txt").write_text("dirty\n")
+ sha, fail = _capture(clone)
+ assert fail == 0 and sha
+ assert git(clone, "show", f"{sha}:a.txt") == "dirty\n"
+
+
+def test_literal_pathspecs_in_the_environment(tmp_path, monkeypatch):
+ """A user who exports GIT_LITERAL_PATHSPECS gets it in the hook's
+ environment, and a magic pathspec would then fail outright and drop the
+ baseline to HEAD on every prompt of the session."""
+ repo = _repo(tmp_path)
+ monkeypatch.setenv("GIT_LITERAL_PATHSPECS", "1")
+ (repo / "a.txt").write_text("dirty\n")
+ sha, fail = _capture(repo)
+ assert fail == 0
+ assert git(repo, "show", f"{sha}:a.txt") == "dirty\n"
+
+
+def test_no_identity_configured_still_snapshots(tmp_path, monkeypatch):
+ repo = _repo(tmp_path)
+ (repo / "a.txt").write_text("dirty\n")
+ for var in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL",
+ "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "EMAIL"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)
+ monkeypatch.setenv("GIT_CONFIG_SYSTEM", os.devnull)
+ sha, fail = _capture(repo)
+ assert fail == 0 and sha
+ assert "security-guidance" in git(repo, "show", "-s", "--format=%an", sha)
+
+
+def test_signing_configured_does_not_sign_the_snapshot(tmp_path):
+ repo = _repo(tmp_path)
+ git(repo, "config", "commit.gpgsign", "true")
+ git(repo, "config", "gpg.program", "/nonexistent-gpg")
+ (repo / "a.txt").write_text("dirty\n")
+ sha, fail = _capture(repo)
+ assert fail == 0 and sha
+ assert git(repo, "show", "-s", "--format=%G?", sha).strip() in ("N", "")
diff --git a/plugins/security-guidance/tests/test_git_index_locks.py b/plugins/security-guidance/tests/test_git_index_locks.py
index 17a877ff..6faaddd3 100644
--- a/plugins/security-guidance/tests/test_git_index_locks.py
+++ b/plugins/security-guidance/tests/test_git_index_locks.py
@@ -65,12 +65,13 @@ def _make_stat_stale(path):
os.utime(path, (t, t))
-def _is_stash_create(args):
- return list(args[-2:]) == ["stash", "create"]
+def _is_snapshot_add(args):
+ """The `git add -u` that stages the turn baseline's tracked changes."""
+ return list(args[-2:]) == ["add", "-u"]
class TestBaselineCapture:
- def test_stash_create_gets_a_throwaway_index(self, tmp_path, tmproot, monkeypatch):
+ def test_snapshot_gets_a_throwaway_index(self, tmp_path, tmproot, monkeypatch):
repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
(repo / "app.py").write_text("x = 2\n")
before = _index_sig(repo / ".git")
@@ -78,7 +79,7 @@ class TestBaselineCapture:
real_run = subprocess.run
def spy(args, **kw):
- if _is_stash_create(args):
+ if _is_snapshot_add(args):
seen.append(kw["env"]["GIT_INDEX_FILE"])
return real_run(args, **kw)
@@ -90,13 +91,13 @@ class TestBaselineCapture:
assert _index_litter(repo / ".git") == []
assert _leftovers(tmproot) == []
- def test_killed_stash_create_leaves_nothing(self, tmp_path, tmproot, monkeypatch):
+ def test_killed_snapshot_leaves_nothing(self, tmp_path, tmproot, monkeypatch):
repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
(repo / "app.py").write_text("x = 2\n")
real_run = subprocess.run
def killed(args, **kw):
- if _is_stash_create(args):
+ if _is_snapshot_add(args):
idx = kw["env"]["GIT_INDEX_FILE"]
for suffix in (".lock", ".stash.4242", ".stash.4242.lock"):
with open(idx + suffix, "wb") as f:
@@ -211,7 +212,7 @@ class TestReadOnlyGitLeavesTheRealIndexAlone:
assert _leftovers(tmproot) == []
def test_diffs_need_no_index_copy(self, tmp_path, tmproot, monkeypatch):
- """Every copy is index-sized, so only `add -N` and stash get one."""
+ """Every copy is index-sized, so only `add -N` and the snapshot get one."""
repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n", "b.py": "b = 1\n"})
first = git(repo, "rev-parse", "HEAD").strip()
commit_file(repo, "app.py", "x = 2\n")
@@ -293,10 +294,10 @@ class TestWholeHook:
assert m.get("skip_reason") is None and m["files_reviewed"] == 2, m
calls = read_log()
- assert {"stash", "status", "diff", "add"} <= {sub[0] for _, _, sub in calls}
+ assert {"write-tree", "status", "diff", "add"} <= {sub[0] for _, _, sub in calls}
assert [c for c in calls if c[0] != "0"] == []
for _, index_file, sub in calls:
- if sub[0] in ("stash", "add"):
+ if sub[0] in ("write-tree", "commit-tree", "add"):
assert index_file.startswith(str(tmproot)), sub
assert _index_sig(repo / ".git") == before
assert _index_litter(repo / ".git") == []
diff --git a/plugins/security-guidance/tests/test_slow_prompt_metrics.py b/plugins/security-guidance/tests/test_slow_prompt_metrics.py
index fa947507..827b4642 100644
--- a/plugins/security-guidance/tests/test_slow_prompt_metrics.py
+++ b/plugins/security-guidance/tests/test_slow_prompt_metrics.py
@@ -10,7 +10,7 @@ import gitutil
from conftest import git, make_repo, metrics_of, run_hook, ups_payload
SLOW = 1.2
-STASH = '*"stash create"*'
+SNAPSHOT = '*"add -u"*'
MOUNTS = (
"25 30 8:32 / / rw,relatime - ext4 /dev/sdc rw\n"
"60 25 0:50 / /mnt/c rw,noatime - 9p C:\\134 rw,aname=drivers\n"
@@ -42,7 +42,7 @@ def _slow(hook_env, tmp_path, match):
def test_slow_capture_reports_where_the_time_went(repo, hook_env, tmp_path):
- rc, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH))
+ rc, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, SNAPSHOT))
m = metrics_of(out)
assert rc == 0
assert m["ups_ms"] >= SLOW * 1000
@@ -60,7 +60,7 @@ def test_slow_untracked_listing_is_told_apart(repo, hook_env, tmp_path):
def test_slow_prompt_with_stop_review_off_lists_nothing(repo, hook_env, tmp_path):
- env = {**_slow(hook_env, tmp_path, STASH), "ENABLE_STOP_REVIEW": "0"}
+ env = {**_slow(hook_env, tmp_path, SNAPSHOT), "ENABLE_STOP_REVIEW": "0"}
m = metrics_of(run_hook(ups_payload(str(repo)), env)[1])
assert m["ups_baseline_ms"] >= SLOW * 1000
assert m["ups_untracked_ms"] == 0
@@ -90,7 +90,7 @@ def test_failed_snapshot_is_flagged(repo, hook_env, tmp_path):
shim = tmp_path / "bin"
shim.mkdir()
(shim / "git").write_text(
- f'#!/bin/sh\ncase "$*" in {STASH}) sleep {SLOW}; exit 1;; esac\n'
+ f'#!/bin/sh\ncase "$*" in *"write-tree"*) sleep {SLOW}; exit 1;; esac\n'
f'exec "{shutil.which("git")}" "$@"\n')
(shim / "git").chmod(0o755)
env = {**hook_env, "PATH": f"{shim}{os.pathsep}{hook_env['PATH']}"}
@@ -110,14 +110,14 @@ def test_slow_launcher_is_reported_on_a_fast_prompt(repo, hook_env):
def test_other_hosts_get_no_output(repo, hook_env, tmp_path):
- env = {k: v for k, v in _slow(hook_env, tmp_path, STASH).items()
+ env = {k: v for k, v in _slow(hook_env, tmp_path, SNAPSHOT).items()
if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "PLUGIN_ROOT")}
env["SECURITY_GUIDANCE_PORTABLE_OUTPUT"] = "1"
assert run_hook(ups_payload(str(repo)), env)[1].strip() == ""
def test_row_holds_no_path_and_valid_keys(repo, hook_env, tmp_path):
- _, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, STASH))
+ _, out, _ = run_hook(ups_payload(str(repo)), _slow(hook_env, tmp_path, SNAPSHOT))
assert str(repo) not in out and str(tmp_path) not in out
metrics = json.loads(out)["metrics"]
assert all(re.fullmatch(r"[a-z][a-z0-9_]{0,39}", k) for k in metrics)
@@ -128,7 +128,7 @@ def test_slow_capture_saves_the_same_baseline(repo, hook_env, tmp_path):
(repo / "app.py").write_text("print('changed')\n")
(repo / "new.txt").write_text("untracked\n")
states = []
- for name, env in (("fast", hook_env), ("slow", _slow(hook_env, tmp_path, STASH))):
+ for name, env in (("fast", hook_env), ("slow", _slow(hook_env, tmp_path, SNAPSHOT))):
d = tmp_path / name
d.mkdir()
env = {k: v for k, v in env.items() if k != "CLAUDE_CODE_REMOTE_SESSION_ID"}
diff --git a/plugins/security-guidance/tests/test_stop_scope_metrics.py b/plugins/security-guidance/tests/test_stop_scope_metrics.py
index c65103b6..7ae6dc64 100644
--- a/plugins/security-guidance/tests/test_stop_scope_metrics.py
+++ b/plugins/security-guidance/tests/test_stop_scope_metrics.py
@@ -29,13 +29,13 @@ def _turn(repo, env, edits=(), during=None):
return _stop(repo, env)
-def _no_stash_env(tmp_path, hook_env):
- """An env whose `git stash` fails, like a snapshot that could not be taken."""
+def _no_write_tree_env(tmp_path, hook_env):
+ """An env whose `git write-tree` fails, like a snapshot that could not be taken."""
bindir = tmp_path / "bin"
bindir.mkdir()
shim = bindir / "git"
shim.write_text(
- '#!/bin/sh\nfor a in "$@"; do [ "$a" = stash ] && exit 1; done\n'
+ '#!/bin/sh\nfor a in "$@"; do [ "$a" = write-tree ] && exit 1; done\n'
f'exec "{shutil.which("git")}" "$@"\n')
shim.chmod(0o755)
return {**hook_env, "PATH": f"{bindir}{os.pathsep}{hook_env['PATH']}"}
@@ -127,7 +127,7 @@ class TestSnapshot:
def test_failed_snapshot_is_counted(self, hook_env, workspace, tmp_path):
ws, repo = workspace
(repo / "app.py").write_text(VULN_PY) # uncommitted work from before the turn
- m = _turn(repo, _no_stash_env(tmp_path, hook_env), edits=[ws / "notes.md"])
+ m = _turn(repo, _no_write_tree_env(tmp_path, hook_env), edits=[ws / "notes.md"])
assert m["files_reviewed"] == 1 and m["review_scope"] == 130001
# The next prompt takes a real snapshot and the flag is gone.
m = _turn(repo, hook_env, edits=[repo / "app.py"],
@@ -138,7 +138,7 @@ class TestSnapshot:
def test_flag_follows_the_snapshot_taken_after_a_finding(self, hook_env, stub_api,
workspace, tmp_path):
_, repo = workspace
- broken = _no_stash_env(tmp_path, hook_env)
+ broken = _no_write_tree_env(tmp_path, hook_env)
stub_api.vulns = [STUB_VULN]
# Good snapshot at the prompt; the one taken after the finding fails.
run_hook(ups_payload(repo), hook_env)
diff --git a/plugins/security-guidance/tests/test_temp_index_cleanup.py b/plugins/security-guidance/tests/test_temp_index_cleanup.py
index 4ac19ea5..9b103a71 100644
--- a/plugins/security-guidance/tests/test_temp_index_cleanup.py
+++ b/plugins/security-guidance/tests/test_temp_index_cleanup.py
@@ -220,7 +220,7 @@ class TestOwnerGone:
@pytest.mark.skipif(os.name == "nt", reason="uses signals and a /bin/sh git shim")
class TestHookProcessKilled:
def _start_slow_hook(self, tmp_path, hook_env, repo):
- """Start a UserPromptSubmit hook whose `git stash create` hangs, and
+ """Start a UserPromptSubmit hook whose snapshot `git add -u` hangs, and
return once its index copy exists."""
import shutil
import subprocess
@@ -233,7 +233,7 @@ class TestHookProcessKilled:
shim = bindir / "git"
shim.write_text(
"#!/bin/sh\n"
- 'case "$*" in *"stash create"*) [ -n "$SLOW_GIT" ] && exec sleep 60;; esac\n'
+ 'case "$*" in *"add -u"*) [ -n "$SLOW_GIT" ] && exec sleep 60;; esac\n'
f'exec "{real_git}" "$@"\n'
)
shim.chmod(0o755)