summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/tests
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-10-20 20:29:41 +0000
committerClaude <noreply@anthropic.com>2026-10-20 20:35:31 +0000
commitf15240feee15b8fe020d38fd46ab5becc97c80a0 (patch)
tree750e7516e8ca33fb39c959f54e4414acac15edd5 /plugins/security-guidance/tests
parent8680640bffd91d9a7fc33ad1ede46a031d36abef (diff)
parentf61e6d15fc03feb474d6df219e37b46f9c14565b (diff)
Merge branch 'main' into mhegazy/sg-gateway-loginmhegazy/sg-gateway-login
Diffstat (limited to 'plugins/security-guidance/tests')
-rw-r--r--plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py75
-rw-r--r--plugins/security-guidance/tests/test_launcher_newer_python.py55
-rw-r--r--plugins/security-guidance/tests/test_nested_repos.py162
-rw-r--r--plugins/security-guidance/tests/test_secret_shaped_paths.py20
-rw-r--r--plugins/security-guidance/tests/test_stop_baseline_checkout.py282
5 files changed, 594 insertions, 0 deletions
diff --git a/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py
new file mode 100644
index 00000000..2325cd9b
--- /dev/null
+++ b/plugins/security-guidance/tests/test_bootstrap_spawn_cwd.py
@@ -0,0 +1,75 @@
+"""The SDK bootstrap's Python subprocesses must not import from the repository.
+
+`python -c` and `python -m` put the working directory first on the import
+path, and hooks run in the user's repository, so every interpreter the
+bootstrap starts runs from a directory the plugin owns.
+"""
+import ast
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+import ensure_agent_sdk
+
+from conftest import HOOKS_DIR, make_repo
+
+
+def _spawns(tree):
+ for node in ast.walk(tree):
+ if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ and node.func.attr in ("run", "Popen", "call", "check_call", "check_output")
+ and isinstance(node.func.value, ast.Name) and node.func.value.id == "subprocess"):
+ yield node
+
+
+def test_every_spawn_sets_a_plugin_owned_cwd():
+ tree = ast.parse((HOOKS_DIR / "ensure_agent_sdk.py").read_text())
+ calls = list(_spawns(tree))
+ assert len(calls) >= 6
+ for call in calls:
+ cwd = [k for k in call.keywords if k.arg == "cwd"]
+ assert cwd, f"subprocess call on line {call.lineno} inherits the hook's working directory"
+ assert ast.unparse(cwd[0].value) == "_spawn_cwd()", call.lineno
+
+
+def test_spawn_cwd_is_the_state_dir(tmp_path, monkeypatch):
+ state = tmp_path / "state"
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state))
+ assert ensure_agent_sdk._spawn_cwd() == str(state)
+ assert state.is_dir()
+
+
+def test_relative_state_dir_is_made_absolute(tmp_path, monkeypatch):
+ # Children run in the state dir, so a relative one would be resolved twice.
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", "rel")
+ assert ensure_agent_sdk._spawn_cwd() == str(tmp_path / "rel")
+
+
+@pytest.mark.skipif(sys.platform == "win32", reason="symlinked interpreter")
+@pytest.mark.skipif(sys.version_info < (3, 10), reason="bootstrap stops before the probe")
+def test_health_check_ignores_module_in_repo(tmp_path, monkeypatch):
+ repo = tmp_path / "repo"
+ make_repo(repo)
+ marker = tmp_path / "imported-from-repo"
+ (repo / "claude_agent_sdk.py").write_text(
+ f"open({str(marker)!r}, 'w').write('x')\n")
+
+ state = tmp_path / "state"
+ venv_bin = state / "agent-sdk-venv" / ("Scripts" if sys.platform == "win32" else "bin")
+ venv_bin.mkdir(parents=True)
+ venv_py = venv_bin / ("python.exe" if sys.platform == "win32" else "python")
+ os.symlink(sys.executable, venv_py)
+
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(state))
+ monkeypatch.chdir(repo)
+ monkeypatch.setattr(ensure_agent_sdk, "_sdk_on_syspath", lambda: False)
+ # No rebuild if the probe fails: this test only covers the probe.
+ ensure_agent_sdk._write_cooldown(state)
+
+ outcome, _, _ = ensure_agent_sdk.main()
+
+ assert outcome in (ensure_agent_sdk.NOOP_VENV, ensure_agent_sdk.SKIP_COOLDOWN)
+ assert not marker.exists()
diff --git a/plugins/security-guidance/tests/test_launcher_newer_python.py b/plugins/security-guidance/tests/test_launcher_newer_python.py
new file mode 100644
index 00000000..fc152b73
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_newer_python.py
@@ -0,0 +1,55 @@
+"""sg-python.sh finds Python releases newer than its versioned list.
+
+The versioned names it prefers stop at python3.13. A machine whose `python3`
+is below 3.10 (stock macOS: 3.9) and whose only newer interpreter is
+python3.14 used to end up on 3.9, which cannot load the agent SDK, so the
+commit reviewer was off without a word. See #4907, #5024.
+
+Interpreters are emulated with shell scripts, so these tests need a POSIX
+shell.
+"""
+import sys
+
+import pytest
+
+from test_launcher_process_count import PYTHON, _add, _run, _starts, box # noqa: F401
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+
+
+def test_newer_release_beats_a_python3_below_3_10(box):
+ _add(box, "python3", PYTHON, version="3.9")
+ _add(box, "python3.14", PYTHON, version="3.14")
+ r = _run(box, "hook.py")
+ assert "ran:python3.14" in r.stdout, r.stdout + r.stderr
+ assert _starts(box) == ["python3 probe", "python3.14 probe", "python3.14 hook.py"]
+
+
+def test_newer_release_is_found_when_it_is_the_only_python(box):
+ _add(box, "python3.15", PYTHON, version="3.15")
+ r = _run(box, "hook.py")
+ assert "ran:python3.15" in r.stdout, r.stdout + r.stderr
+ assert _starts(box) == ["python3.15 probe", "python3.15 hook.py"]
+
+
+@pytest.mark.parametrize("working", ["python3.12", "python3", "python"])
+def test_an_interpreter_that_already_works_is_kept(box, working):
+ _add(box, working, PYTHON, version="3.12")
+ _add(box, "python3.14", PYTHON, version="3.14")
+ r = _run(box, "hook.py")
+ assert f"ran:{working}" in r.stdout, r.stdout + r.stderr
+ assert "python3.14 probe" not in _starts(box)
+
+
+def test_oldest_of_the_newer_releases_is_tried_first(box):
+ _add(box, "python3.16", PYTHON, version="3.16")
+ _add(box, "python3.14", PYTHON, version="3.14")
+ r = _run(box, "hook.py")
+ assert "ran:python3.14" in r.stdout, r.stdout + r.stderr
+
+
+def test_no_python_at_all_still_starts_nothing(box):
+ r = _run(box, "hook.py")
+ assert r.returncode == 1
+ assert "python3.14" in r.stderr
+ assert _starts(box) == []
diff --git a/plugins/security-guidance/tests/test_nested_repos.py b/plugins/security-guidance/tests/test_nested_repos.py
new file mode 100644
index 00000000..cb010018
--- /dev/null
+++ b/plugins/security-guidance/tests/test_nested_repos.py
@@ -0,0 +1,162 @@
+import os
+import subprocess
+import tempfile
+
+import pytest
+
+from conftest import (
+ GIT_ENV, STUB_VULN, VULN_PY, git, make_repo, metrics_of, run_hook,
+ stop_payload, ups_payload,
+)
+
+import gitutil
+
+
+def _add_nested_repo(parent, rel, marker):
+ """A directory with its own `.git` whose config names a filter command,
+ the way an unpacked archive or a vendored checkout can. The command leaves
+ a line in `marker` each time git runs it."""
+ nested = make_repo(parent / rel, {
+ "lib.py": "print('one')\n",
+ ".gitattributes": "* filter=probe\n",
+ })
+ git(nested, "config", "filter.probe.clean",
+ f"sh -c 'echo ran >> \"{marker.as_posix()}\"; cat'")
+ # Same size, so git has to read the file to tell whether it changed.
+ (nested / "lib.py").write_text("print('two')\n")
+ old = os.stat(nested / ".git" / "index").st_mtime - 3600
+ os.utime(nested / ".git" / "index", (old, old))
+ return nested
+
+
+@pytest.fixture
+def outer(tmp_path):
+ return make_repo(tmp_path / "outer", {"app.py": "print('hi')\n"})
+
+
+@pytest.fixture
+def marker(tmp_path):
+ return tmp_path / "filter-ran"
+
+
+def _turn(repo, hook_env, stub_api, during):
+ stub_api.vulns = [STUB_VULN]
+ assert run_hook(ups_payload(repo), hook_env)[0] == 0
+ during()
+ return run_hook(stop_payload(repo), hook_env)
+
+
+def test_untracked_nested_repo_filter_not_run(outer, marker, hook_env, stub_api):
+ def during():
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "app.py").write_text(VULN_PY)
+
+ rc, out, err = _turn(outer, hook_env, stub_api, during)
+
+ assert not marker.exists(), marker.read_text()
+ # The turn's own edit is still reviewed.
+ assert stub_api.calls, (rc, out, err)
+ assert "app.py" in out + err
+
+
+def test_untracked_nested_repo_alone_is_not_reviewed(outer, marker, hook_env, stub_api):
+ rc, out, err = _turn(
+ outer, hook_env, stub_api,
+ lambda: _add_nested_repo(outer, "vendor/pkg", marker))
+
+ assert not marker.exists(), marker.read_text()
+ assert not stub_api.calls
+ assert (metrics_of(out) or {}).get("skipped") is True
+
+
+@pytest.fixture
+def git_env(tmp_path, monkeypatch):
+ """For calling gitutil in this process: a temp dir of our own, and the
+ environment restored afterwards."""
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ saved = dict(os.environ)
+ os.environ.update(GIT_ENV)
+ yield
+ os.environ.clear()
+ os.environ.update(saved)
+
+
+def _record_nested_repo(outer, marker, gitmodules=None):
+ nested = _add_nested_repo(outer, "vendor/pkg", marker)
+ if gitmodules:
+ (outer / ".gitmodules").write_text(gitmodules)
+ git(outer, "add", "-A")
+ git(outer, "commit", "-q", "-m", "add vendor/pkg")
+ if marker.exists():
+ marker.unlink()
+ return nested
+
+
+def test_untracked_nested_repo_is_not_a_changed_file(outer, marker, git_env):
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "new.py").write_text("x = 1\n")
+
+ tracked, untracked = gitutil._git_status_porcelain(str(outer))
+
+ assert (tracked, untracked) == (set(), {"new.py"})
+
+
+def test_intent_to_add_skips_nested_repos(outer, marker, git_env):
+ _add_nested_repo(outer, "vendor/pkg", marker)
+ (outer / "new.py").write_text("x = 1\n")
+
+ with gitutil._temp_index(str(outer), ["new.py", "vendor/pkg/"]) as env:
+ assert env is not None
+ listed = subprocess.run(
+ ["git", "ls-files", "-s"], cwd=outer, capture_output=True,
+ text=True, env=env,
+ ).stdout
+
+ assert "new.py" in listed
+ assert "160000" not in listed
+ assert not marker.exists()
+
+
+# A repository can ask for one submodule to be checked whatever the default.
+GITMODULES_IGNORE_NONE = (
+ '[submodule "pkg"]\n\tpath = vendor/pkg\n\turl = ./vendor/pkg\n\tignore = none\n'
+)
+
+
+@pytest.mark.parametrize("gitmodules", [None, GITMODULES_IGNORE_NONE])
+def test_status_and_diff_leave_out_recorded_nested_repo(outer, marker, git_env, gitmodules):
+ nested = _record_nested_repo(outer, marker, gitmodules)
+ (nested / "lib.py").write_text("print('abc')\n")
+ (outer / "app.py").write_text(VULN_PY)
+
+ tracked, untracked = gitutil._git_status_porcelain(str(outer))
+ diff = gitutil.get_git_diff(str(outer), "HEAD", untracked_paths=[])
+ names = gitutil._git_name_only(str(outer), "HEAD")
+
+ assert tracked == {"app.py"}
+ assert names == {"app.py"}
+ assert "app.py" in diff and "vendor/pkg" not in diff
+ assert not marker.exists()
+
+
+def test_commit_range_diff_does_not_enter_nested_repo(outer, marker, git_env, tmp_path):
+ nested = _record_nested_repo(outer, marker, GITMODULES_IGNORE_NONE)
+ ext_marker = tmp_path / "ext-diff-ran"
+ git(nested, "config", "diff.external",
+ f"sh -c 'echo ran >> \"{ext_marker.as_posix()}\"'")
+ base = git(outer, "rev-parse", "HEAD").strip()
+ git(nested, "commit", "-q", "-am", "two")
+ git(outer, "commit", "-q", "-am", "move vendor/pkg")
+ for m in (marker, ext_marker):
+ if m.exists():
+ m.unlink()
+ # The user's own setting asks for a submodule's changes inline.
+ os.environ.update({"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "diff.submodule",
+ "GIT_CONFIG_VALUE_0": "diff"})
+
+ out = gitutil._git_diff_range(str(outer), base, "HEAD")
+
+ assert not ext_marker.exists() and not marker.exists()
+ assert "lib.py" not in (out or "")
diff --git a/plugins/security-guidance/tests/test_secret_shaped_paths.py b/plugins/security-guidance/tests/test_secret_shaped_paths.py
index bfd5180d..b20beef3 100644
--- a/plugins/security-guidance/tests/test_secret_shaped_paths.py
+++ b/plugins/security-guidance/tests/test_secret_shaped_paths.py
@@ -25,6 +25,11 @@ import gitutil
"private_dot_netrc",
"dot_aws/credentials",
"Deploy_RSA",
+ ".credentials.json",
+ ".claude/.credentials.json",
+ "private_dot_claude/private_dot_credentials.json",
+ ".claude.json",
+ "dot_claude.json",
])
def test_secret_shaped_names_are_not_reviewable(path):
assert gitutil._is_secret_shaped(path)
@@ -44,6 +49,8 @@ def test_secret_shaped_names_are_not_reviewable(path):
"bin/deploy",
"Dockerfile.dev",
"executable_backup.sh",
+ "config/credentials.json",
+ "src/claude.json",
])
def test_ordinary_source_stays_reviewable(path):
assert not gitutil._is_secret_shaped(path)
@@ -93,3 +100,16 @@ def test_stop_hook_reports_how_many_files_it_left_out(tmp_path, hook_env, stub_a
_rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
assert metrics_of(stdout).get("secret_shaped_skipped") == 2
assert stub_api.calls == []
+
+
+@pytest.mark.parametrize("name", [".credentials.json", ".claude.json"])
+def test_claude_code_files_rewritten_during_the_turn_are_not_sent(tmp_path, hook_env, stub_api, name):
+ repo = make_repo(tmp_path / "repo")
+ (repo / name).write_text('{"accessToken": "old"}\n')
+ run_hook(ups_payload(repo), hook_env)
+ (repo / name).write_text('{"accessToken": "new-and-longer"}\n')
+ later = (repo / name).stat().st_mtime + 5
+ os.utime(repo / name, (later, later))
+ _rc, stdout, _err = run_hook(stop_payload(repo), hook_env)
+ assert metrics_of(stdout).get("secret_shaped_skipped") == 1
+ assert stub_api.calls == []
diff --git a/plugins/security-guidance/tests/test_stop_baseline_checkout.py b/plugins/security-guidance/tests/test_stop_baseline_checkout.py
new file mode 100644
index 00000000..97c20ab3
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_baseline_checkout.py
@@ -0,0 +1,282 @@
+"""The turn baseline belongs to the checkout the prompt hook captured it in.
+A Stop review in another checkout (the session entered a worktree, or edited
+another repo) does not use it: commits count from that checkout's own HEAD at
+the time of the prompt, files are diffed against HEAD, and uncommitted files
+last written before the prompt are left out. Stop rows carry `bl_origin`,
+saying which case the row was."""
+import json
+import os
+import shutil
+import time
+
+import pytest
+
+from conftest import (
+ STUB_VULN, VULN_PY, edit_payload, git, make_repo, metrics_of, run_hook,
+ stop_payload, ups_payload,
+)
+
+
+@pytest.fixture
+def checkouts(tmp_path, monkeypatch):
+ """a: a repo's primary checkout. b: a linked worktree of it whose branch
+ already holds a committed file that a's branch lacks. Both were last
+ committed to an hour ago."""
+ monkeypatch.setenv("GIT_COMMITTER_DATE", f"@{int(time.time()) - 3600} +0000")
+ a = make_repo(tmp_path / "ws" / "a", {"app.py": "print('hi')\n"})
+ b = tmp_path / "ws" / "b"
+ git(a, "worktree", "add", "-q", "-b", "feature", str(b))
+ (b / "old.py").write_text(VULN_PY)
+ git(b, "add", "-A")
+ git(b, "commit", "-q", "-m", "earlier work")
+ monkeypatch.delenv("GIT_COMMITTER_DATE")
+ return a, b
+
+
+def _stop(cwd, hook_env):
+ return metrics_of(run_hook(stop_payload(cwd), hook_env)[1])
+
+
+def _state(hook_env):
+ d = hook_env["SECURITY_WARNINGS_STATE_DIR"]
+ for e in os.scandir(d):
+ if e.name.endswith(".json"):
+ with open(e.path) as f:
+ state = json.load(f)
+ if "baseline_sha" in state:
+ return state
+ raise AssertionError(os.listdir(d))
+
+
+def test_baseline_from_the_reviewed_checkout(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ m = _stop(a, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 0
+
+
+def test_sent_on_a_skipped_review_too(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ m = _stop(a, hook_env)
+ assert m["skipped"] is True and m["bl_origin"] == 0
+
+
+def test_prompt_in_a_subdirectory_is_the_same_checkout(hook_env, checkouts):
+ a, _ = checkouts
+ (a / "pkg").mkdir()
+ run_hook(ups_payload(a / "pkg"), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 0
+
+
+def test_turn_that_only_enters_another_worktree_reviews_nothing(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ m = _stop(b, hook_env)
+ # b's earlier commit is not a commit made this turn.
+ assert m["skipped"] is True and m["bl_origin"] == 1
+ assert not stub_api.calls
+
+
+def test_edit_after_entering_another_worktree_is_reviewed(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ (b / "new.py").write_text(VULN_PY)
+ run_hook(edit_payload(b, b / "new.py"), hook_env)
+ m = _stop(b, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 1
+ assert stub_api.calls.count("/v1/messages") == 1
+
+
+def test_commit_made_after_entering_another_worktree_is_reviewed(
+ hook_env, checkouts):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ (b / "new.py").write_text(VULN_PY)
+ git(b, "add", "-A")
+ git(b, "commit", "-q", "-m", "this turn")
+ m = _stop(b, hook_env)
+ # new.py, not old.py from the earlier commit.
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 1
+
+
+def test_commit_in_a_worktree_created_this_turn_is_reviewed(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ c = a.parent / "c"
+ git(a, "worktree", "add", "-q", "-b", "fresh", str(c))
+ (c / "new.py").write_text(VULN_PY)
+ git(c, "add", "-A")
+ git(c, "commit", "-q", "-m", "this turn")
+ (c / "more.py").write_text(VULN_PY)
+ m = _stop(c, hook_env)
+ assert m["files_reviewed"] == 2 and m["bl_origin"] == 1
+
+
+def test_uncommitted_work_already_in_the_other_worktree_is_left_out(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ (b / "scratch.py").write_text(VULN_PY) # untracked
+ (b / "old.py").write_text(VULN_PY + "# todo\n") # tracked, edited
+ time.sleep(2.2) # past the slack allowed around the prompt time
+ run_hook(ups_payload(a), hook_env)
+ m = _stop(b, hook_env)
+ assert m["skipped"] is True and m["bl_origin"] == 1
+ assert not stub_api.calls
+ # Both are reviewed once the turn writes to them.
+ (b / "scratch.py").write_text(VULN_PY + "x = 1\n")
+ (b / "old.py").write_text(VULN_PY + "# done\n")
+ m = _stop(b, hook_env)
+ assert m["files_reviewed"] == 2 and m["bl_origin"] == 1
+
+
+def test_baseline_kept_from_an_interrupted_turn_in_another_worktree(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ run_hook(edit_payload(a, a / "app.py"), hook_env)
+ run_hook(ups_payload(b), hook_env)
+ m = _stop(b, hook_env)
+ assert m["skipped"] is True and m["bl_origin"] == 21
+ assert not stub_api.calls
+
+
+def test_baseline_kept_from_an_interrupted_turn_in_the_same_checkout(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ run_hook(edit_payload(a, a / "app.py"), hook_env)
+ run_hook(ups_payload(a), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 20
+
+
+def test_interrupted_turn_then_a_prompt_that_cannot_capture(hook_env, checkouts):
+ a, _ = checkouts
+ run_hook(ups_payload(a), hook_env)
+ run_hook(edit_payload(a, a / "app.py"), hook_env)
+ run_hook(ups_payload(a), hook_env)
+ run_hook(ups_payload(a.parent), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 10
+
+
+def test_baseline_from_another_repository(hook_env, checkouts, tmp_path):
+ a, _ = checkouts
+ other = make_repo(tmp_path / "ws" / "other", {"lib.py": "x = 1\n"})
+ run_hook(ups_payload(a), hook_env)
+ (other / "lib.py").write_text(VULN_PY)
+ m = _stop(other, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 2
+
+
+def test_baseline_from_a_checkout_that_is_gone(hook_env, checkouts):
+ a, b = checkouts
+ run_hook(ups_payload(b), hook_env)
+ git(a, "worktree", "remove", "--force", str(b))
+ shutil.rmtree(b, ignore_errors=True)
+ (a / "app.py").write_text(VULN_PY)
+ m = _stop(a, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 3
+
+
+def test_prompt_in_a_folder_that_is_not_a_repo_keeps_the_untracked_snapshot(
+ hook_env, checkouts):
+ a, _ = checkouts
+ ws = a.parent
+ (a / "notes.py").write_text("n = 0\n") # untracked since before the session
+ run_hook(ups_payload(a), hook_env)
+ (a / "first.py").write_text("x = 1\n")
+ assert _stop(a, hook_env)["bl_origin"] == 0
+ run_hook(ups_payload(ws), hook_env)
+ (a / "second.py").write_text("y = 2\n")
+ run_hook(edit_payload(ws, a / "second.py"), hook_env)
+ m = _stop(ws, hook_env)
+ # The earlier baseline is kept, so the first turn's file is reviewed
+ # again. notes.py is not: the snapshot that goes with it is kept too.
+ assert m["files_reviewed"] == 2 and m["bl_origin"] == 10
+ # The next prompt in the repo captures a fresh baseline there.
+ run_hook(ups_payload(a), hook_env)
+ (a / "third.py").write_text("z = 3\n")
+ m = _stop(a, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 0
+
+
+def test_baseline_taken_after_a_finding_belongs_to_the_reviewed_checkout(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ run_hook(ups_payload(a), hook_env)
+ (b / "new.py").write_text(VULN_PY)
+ stub_api.vulns = [dict(STUB_VULN, filePath="new.py")]
+ assert _stop(b, hook_env)["bl_origin"] == 1
+ st = _state(hook_env)
+ assert os.path.samefile(st["baseline_root"], b)
+ # b's HEAD at the prompt, not a's.
+ assert st["head_at_capture"] == git(b, "rev-parse", "HEAD").strip()
+ # Same turn, next Stop: only what changed since the finding.
+ stub_api.vulns = []
+ (b / "newer.py").write_text("v = 1\n")
+ m = _stop(b, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 0
+
+
+def test_baseline_taken_after_a_finding_keeps_the_turns_first_commit(
+ hook_env, checkouts, stub_api):
+ a, _ = checkouts
+ head = git(a, "rev-parse", "HEAD").strip()
+ run_hook(ups_payload(a), hook_env)
+ (a / "app.py").write_text(VULN_PY)
+ git(a, "commit", "-q", "-am", "this turn")
+ stub_api.vulns = [dict(STUB_VULN, filePath="app.py")]
+ assert _stop(a, hook_env)["bl_origin"] == 0
+ assert _state(hook_env)["head_at_capture"] == head
+ # A fix folded into the commit is still inside the turn's range.
+ (a / "app.py").write_text(VULN_PY + "x = 1\n")
+ git(a, "commit", "-q", "-a", "--amend", "-m", "this turn")
+ assert _stop(a, hook_env)["files_reviewed"] == 1
+
+
+def test_first_baseline_taken_after_a_finding_records_its_checkout(
+ hook_env, checkouts, stub_api):
+ a, b = checkouts
+ ws = a.parent
+ run_hook(ups_payload(ws), hook_env)
+ (a / "new.py").write_text(VULN_PY)
+ run_hook(edit_payload(ws, a / "new.py"), hook_env)
+ stub_api.vulns = [dict(STUB_VULN, filePath="new.py")]
+ assert _stop(ws, hook_env)["bl_origin"] == 4
+ assert os.path.samefile(_state(hook_env)["baseline_root"], a)
+ stub_api.vulns = []
+ assert _stop(b, hook_env)["bl_origin"] == 1
+
+
+def test_no_baseline_at_all(hook_env, checkouts):
+ a, _ = checkouts
+ ws = a.parent
+ run_hook(ups_payload(ws), hook_env)
+ (a / "new.py").write_text("v = 1\n")
+ run_hook(edit_payload(ws, a / "new.py"), hook_env)
+ m = _stop(ws, hook_env)
+ assert m["files_reviewed"] == 1 and m["bl_origin"] == 4
+
+
+def test_prompt_subdirectory_removed_during_the_turn(hook_env, checkouts):
+ a, _ = checkouts
+ (a / "pkg").mkdir()
+ run_hook(ups_payload(a / "pkg"), hook_env)
+ (a / "pkg").rmdir()
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 0
+
+
+def test_nested_worktree_removed_during_the_turn(hook_env, checkouts):
+ a, _ = checkouts
+ nested = a / ".claude" / "worktrees" / "wt"
+ git(a, "worktree", "add", "-q", "-b", "nested", str(nested))
+ run_hook(ups_payload(nested), hook_env)
+ git(a, "worktree", "remove", "--force", str(nested))
+ (a / "app.py").write_text(VULN_PY)
+ assert _stop(a, hook_env)["bl_origin"] == 3