diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-19 16:51:24 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-19 16:51:24 +0000 |
| commit | 307800f0aaa7b285390bd1702055881f48098b2d (patch) | |
| tree | 68accc3bb6e2be1f34f8a319c7e25d7fb7668bef /plugins | |
| parent | ea10b213686c90bb1984b2016937310e05336cf3 (diff) | |
security-guidance: do not review against a baseline from another checkoutmhegazy/sg-stop-baseline-checkout
The turn baseline (stash SHA, HEAD, untracked snapshot) is kept per
session, and the Stop review used it in whatever checkout the turn ended
in. After the session entered another worktree, that worktree's older
commits looked like commits made this turn and its files were diffed
against the first checkout's, so code committed long before was reviewed
and reported again (anthropics/claude-code#102567).
The prompt hook now stores the repo root and the prompt time beside the
baseline. When the Stop review runs in a different checkout it leaves the
baseline out and uses what that checkout can say for itself: its own HEAD
when the turn began (from its reflog) for the commit range, HEAD for file
contents, and file times to leave out uncommitted files last written
before the turn. A baseline taken after a finding records the checkout it
was taken in.
A prompt in a folder that is not a repo no longer replaces the untracked
snapshot of the kept baseline with an empty one, which made every
untracked file in the repo look new at the next Stop.
Stop rows carry `bl_origin`: 0 same checkout, 1 another worktree, 2
another repository, 3 a folder that is gone, 4 no baseline; plus 10 or 20
when the baseline is an earlier turn's.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 67 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 35 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 79 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_stop_baseline_checkout.py | 282 |
4 files changed, 458 insertions, 5 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index f2d9dbe4..02b073e8 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -17,6 +17,7 @@ from gitutil import ( _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, ) from session_state import with_locked_state +from extensibility import _same_dir # ===================================================================== @@ -96,6 +97,10 @@ def consume_stop_state(session_id, clear=True): "touched_paths": list(state.get("touched_paths", [])), "baseline_sha": state.get("baseline_sha"), "head_at_capture": state.get("head_at_capture"), + # Where and when the prompt hook captured it; see baseline_origin. + "baseline_root": state.get("baseline_root"), + "prompt_at": state.get("prompt_at"), + "baseline_kept": state.get("baseline_kept") or 0, "untracked_at_baseline": ( dict(state["untracked_at_baseline"]) if isinstance(state.get("untracked_at_baseline"), dict) else {} @@ -117,7 +122,8 @@ def consume_stop_state(session_id, clear=True): return with_locked_state(session_id, _snap) or { "touched_paths": [], "baseline_sha": None, "head_at_capture": None, - "untracked_at_baseline": {}, + "untracked_at_baseline": {}, "baseline_root": None, "prompt_at": None, + "baseline_kept": 0, "fire_count": 0, "fire_count_expired": False, "previous_findings": [], "reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0, } @@ -153,6 +159,48 @@ def restore_unreviewed_stop_state(session_id, paths, baseline_sha): with_locked_state(session_id, _restore) +# state["baseline_kept"]: why a prompt left an earlier turn's baseline in +# place. Only telemetry reads it. +KEPT_NO_CAPTURE = 1 # it could not capture one (not a repo, or git failed) +KEPT_UNREVIEWED = 2 # the previous turn's edits were never reviewed + +# baseline_origin() values that mean "captured in another checkout". +FOREIGN_ORIGINS = (1, 2, 3) + + +def baseline_origin(repo_root, baseline_sha, baseline_root): + """Where the session's baseline was captured, relative to the checkout a + Stop review is about to read (`repo_root`): + + 0 that checkout (or the origin was not recorded) + 1 another worktree of the same repository + 2 another repository + 3 another folder, which is gone or cannot be read as a checkout + 4 there is no baseline + + `baseline_root` is the repo root the prompt hook stored beside the SHA.""" + if not baseline_sha: + return 4 + if not baseline_root or not isinstance(baseline_root, str): + return 0 + if _same_dir(baseline_root, repo_root): + return 0 + if not os.path.isdir(baseline_root): + return 3 + here, there = _git_dir(repo_root), _git_dir(baseline_root) + if not here or not there: + return 3 + return 1 if _same_dir(here, there) else 2 + + +def baseline_origin_metric(origin, kept): + """The `bl_origin` number on Stop rows: baseline_origin, plus 10 or 20 + (KEPT_*) when the baseline is an earlier turn's.""" + if origin == 4 or kept not in (KEPT_NO_CAPTURE, KEPT_UNREVIEWED): + return origin + return origin + 10 * kept + + def get_baseline_file_content(session_id, file_path, cwd): """Get the content of a file at the baseline SHA. Returns None if unavailable. @@ -605,7 +653,8 @@ def _list_untracked(cwd): debug_log(f"_list_untracked error: {e}") return {} -def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_baseline=None): +def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_baseline=None, + since_ns=None): """v2 diff strategy: derive the review set from git state alone. review_set = (files dirty vs current HEAD, plus files committed this turn @@ -620,6 +669,10 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel 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. + since_ns: for a checkout the prompt hook took no baseline or snapshot of + (the turn moved into it), the time the turn began. A dirty or untracked + file last written before then was already that way and is left out. + Known limitation: a Bash-only turn that's interrupted before Stop fires leaves touched_paths empty, so the next UPS re-baselines past those edits. v1 never reviews Bash-only turns at all, so v2 is no worse there. @@ -662,6 +715,16 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel return max(st.st_mtime_ns, st.st_ctime_ns) < capped_at_ns - _CAPPED_BASELINE_SLACK_NS preexisting_unchanged = {p for p in untracked if _unchanged_since_baseline(p)} + if since_ns: + def _written_before_turn(p): + try: + st = os.stat(os.path.join(repo, p)) + except OSError: + return False + return max(st.st_mtime_ns, st.st_ctime_ns) < since_ns - _CAPPED_BASELINE_SLACK_NS + + preexisting_unchanged |= {p for p in untracked if _written_before_turn(p)} + tracked_dirty = {p for p in tracked_dirty if not _written_before_turn(p)} new_untracked = untracked - preexisting_unchanged dirty_now = tracked_dirty | new_untracked diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index bc4d753b..0ffb2cdf 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -487,6 +487,41 @@ def _git_toplevel(cwd): return None +def _git_toplevel_and_head(cwd): + """(repo root, HEAD SHA) for `cwd` from one git call, or (None, None) + when git cannot give both (not a work tree, no commits).""" + try: + r = subprocess.run( + [*GIT_CMD, "rev-parse", "--show-toplevel", "HEAD"], + cwd=cwd, capture_output=True, timeout=5, + ) + except (subprocess.TimeoutExpired, FileNotFoundError, OSError): + return None, None + if r.returncode != 0: + return None, None + # See #2099: the first line is a PATH, so decode the bytes manually. + top, _, head = r.stdout.decode("utf-8", errors="replace").strip().rpartition("\n") + return (top.strip() or None), (head.strip() or None) + + +def _git_head_at(cwd, epoch): + """The SHA this checkout's HEAD pointed at just before `epoch` (seconds), + read from its own reflog. A checkout created after `epoch` answers with + the commit it was created at. None when git cannot say (no reflog).""" + try: + # Reflog times are whole seconds: ask for the second before, so a + # commit made in the same second as `epoch` counts as after it. + r = subprocess.run( + [*GIT_CMD, "rev-parse", "--verify", "-q", f"HEAD@{{@{int(epoch) - 1}}}"], + cwd=cwd, capture_output=True, timeout=5, + ) + except (subprocess.TimeoutExpired, FileNotFoundError, OSError, + TypeError, ValueError, OverflowError): + return None + sha = r.stdout.decode("utf-8", errors="replace").strip() + return sha if r.returncode == 0 and sha else None + + def _git_dir(repo_root): """Absolute shared `.git` directory for repo_root. diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index ea5bab18..2c77379a 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -102,6 +102,7 @@ from gitutil import ( # noqa: E402,F401 GIT_CMD, apply_safe_git_env, remove_copies_on_termination, _git_rev_parse_head, _find_git_index, _diff_pathspec, _temp_index, _git_toplevel, _git_dir, _git_rev_list_range, _git_diff_range, + _git_toplevel_and_head, _git_head_at, _detect_main_branch, _git_reflog_recent_commits, _git_name_only, _git_status_porcelain, _is_ancestor, get_git_diff, SOURCE_CODE_EXTENSIONS, SOURCE_CODE_BASENAMES, @@ -121,6 +122,8 @@ from diffstate import ( # noqa: E402,F401 _reviewed_shas_path, _load_reviewed_shas, _append_reviewed_shas, _full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight, UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set, + baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS, + KEPT_NO_CAPTURE, KEPT_UNREVIEWED, ) from reporesolve import ( # noqa: E402,F401 RES_NONE, RES_CWD, RES_COMMAND, RES_SHA_SCAN, RES_TOUCHED_PATHS, RES_HINT, @@ -575,14 +578,24 @@ def handle_user_prompt_submit(input_data): # something tracked is dirtied. return _f_sha.result(), _f_ut.result() or {} + import time as _time + captured_at = _time.time() sha, untracked_now = _capture(cwd) + # No repo here and none remembered: the listing above failed, it did not + # come back empty. + no_repo = False if not sha and not _git_toplevel(cwd): hint = load_repo_hint(session_id) if hint: debug_log(f"UPS: cwd is not a git repo; using repo hint {hint!r}") cwd = hint sha, untracked_now = _capture(cwd) - head = _git_rev_parse_head(cwd) + else: + no_repo = True + # The repo root rides on the same git call as HEAD. + root, head = (None, None) if no_repo else _git_toplevel_and_head(cwd) + if sha and not head: + head = _git_rev_parse_head(cwd) # If the previous turn's Stop hook never ran (user interrupt, follow-up # during work, tool-reject, model crash, maxTurns, PostToolUse block…), @@ -605,10 +618,25 @@ def handle_user_prompt_submit(input_data): # untracked file in the tree as written this turn. if untracked_now is not None and "untracked_at_baseline" not in state: state["untracked_at_baseline"] = untracked_now + # Once a prompt failed to capture, the baseline is old whatever + # later prompts did. + state["baseline_kept"] = ( + KEPT_NO_CAPTURE + if not sha or state.get("baseline_kept") == KEPT_NO_CAPTURE + else KEPT_UNREVIEWED) return if sha: state["baseline_sha"] = sha state["head_at_capture"] = head + # A Stop review that ends up in another checkout does not use + # this baseline. + state["baseline_root"] = root + state.pop("baseline_kept", None) + elif state.get("baseline_sha"): + state["baseline_kept"] = KEPT_NO_CAPTURE + # 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 # a SHA, so compute_v2_review_set's preexisting-untracked exclusion # works in untracked-only trees. None means no snapshot was taken @@ -616,7 +644,10 @@ def handle_user_prompt_submit(input_data): # baseline. if untracked_now is None: state.pop("untracked_at_baseline", None) - else: + elif not no_repo: + # no_repo: the earlier baseline stays (above), and so does the + # snapshot that belongs to it. An empty one in its place would + # make every untracked file in that repo look new. state["untracked_at_baseline"] = untracked_now with_locked_state(session_id, _save) @@ -2259,9 +2290,40 @@ def handle_stop_hook(input_data): save_repo_hint(session_id, repo_cwd) cwd = repo_cwd + # The baseline belongs to the checkout the prompt hook captured it in. + # When the turn ends in another one (the session entered a worktree, or + # the edits were in a different repo), it says nothing about what changed + # here: this checkout's older commits would look like commits made this + # turn, and its files would be diffed against the other checkout's. Use + # what this checkout can say for itself instead: its own HEAD when the + # turn began (from its reflog) for commits, HEAD for file contents, and + # file times for which uncommitted files were already there. + origin = None + if repo_cwd: + try: + origin = baseline_origin(repo_cwd, snap_baseline, snap["baseline_root"]) + except Exception as e: + debug_log(f"Stop hook: baseline origin check failed: {e}") + foreign_baseline = origin in FOREIGN_ORIGINS + since_ns = None + if foreign_baseline: + at = snap["prompt_at"] + at = at if isinstance(at, (int, float)) and 0 < at < 1e11 else None + baseline_sha = None + head_at_capture = _git_head_at(repo_cwd, at) if at else None + untracked_at_baseline = {} + since_ns = int(at * 1e9) if at else None + debug_log(f"Stop hook: baseline {str(snap_baseline)[:12]} is from another " + f"checkout (origin {origin}); this one was at " + f"{str(head_at_capture)[:12]} when the turn began") + review_paths, diff_base, repo_root, untracked, v2_metrics = compute_v2_review_set( - cwd, baseline_sha, head_at_capture, untracked_at_baseline + cwd, baseline_sha, head_at_capture, untracked_at_baseline, since_ns=since_ns ) + # Sent even when 0, once git status has worked. + if origin is not None and v2_metrics.get("dirty_now_count", -1) >= 0: + _TAIL_METRICS["bl_origin"] = baseline_origin_metric(origin, snap["baseline_kept"]) + v2_metrics = {**res_metrics, **v2_metrics} if not review_paths: debug_log("Stop hook: empty review set") @@ -2368,6 +2430,10 @@ def handle_stop_hook(input_data): # Update baseline so next stop hook iteration only sees new changes new_sha = None if is_subagent else capture_git_baseline(cwd) new_untracked_baseline = _list_untracked(cwd) if new_sha else None + # After a baseline from another checkout, the rest of it is replaced + # too, below. + new_head = (_git_rev_parse_head(cwd) + if new_sha and foreign_baseline and not head_at_capture else None) def _record_fire(state): if is_subagent: @@ -2392,6 +2458,13 @@ def handle_stop_hook(input_data): if new_sha: state["baseline_sha"] = new_sha state["untracked_at_baseline"] = new_untracked_baseline + state["baseline_root"] = repo_root + state.pop("baseline_kept", None) + if foreign_baseline: + # The stored HEAD is the other checkout's. Keep the one + # this review used, so a later Stop this turn still sees + # commits made (or amended) here since the prompt. + state["head_at_capture"] = head_at_capture or new_head with_locked_state(session_id, _record_fire) if new_sha: 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 |
