diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-10-20 13:55:54 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-20 13:55:54 -0700 |
| commit | 62e145efc6d95799a58d6dcc4a65febcaeeaa898 (patch) | |
| tree | 940e40dd56155a8c2cf7f37656cb887786c1f1c1 /plugins | |
| parent | 2e8b30fa811b35586b1cc1a727be0a587c0af817 (diff) | |
| parent | 3b1114ffc69b73ef80f64d8647e3ad632141801c (diff) | |
Merge pull request #6628 from anthropics/mhegazy/sg-stop-scope-telemetry
security-guidance: report how Stop reviews relate to the session's own edits
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 81 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 34 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_stop_scope_metrics.py | 181 |
3 files changed, 296 insertions, 0 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 02b073e8..d3dd2a51 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -8,6 +8,7 @@ to work without retargeting. """ import os import subprocess +import sys import time from _base import debug_log, _PV @@ -112,8 +113,17 @@ def consume_stop_state(session_id, clear=True): # State lost or overwritten since the last Stop (session_state). "state_resets": state.get("state_resets", 0), "state_overwrites": state.get("state_overwrites", 0), + "baseline_fail": state.get("baseline_fail") or 0, } + # touched_paths is cleared per Stop, but one baseline can be + # reviewed by several Stops (rewakes). turn_touched keeps every path + # recorded since the baseline; only telemetry reads it. + turn = list(dict.fromkeys( + [p for p in state.get("turn_touched", []) if isinstance(p, str)] + + snap["touched_paths"]))[-200:] + snap["turn_touched"] = turn if clear: + state["turn_touched"] = turn state["touched_paths"] = [] state.pop("reviewed_diff_hash", None) state.pop("state_resets", None) @@ -126,9 +136,66 @@ def consume_stop_state(session_id, clear=True): "baseline_kept": 0, "fire_count": 0, "fire_count_expired": False, "previous_findings": [], "reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0, + "baseline_fail": 0, "turn_touched": [], } +# Path names compare without case where the filesystem usually does. +_FOLD_CASE = os.name == "nt" or sys.platform == "darwin" + + +def _rel_in_repo(real_root, path): + """`path` relative to the repo root (a real path), or None when it lies + outside the repo.""" + real = os.path.realpath(path) + try: + rel = os.path.relpath(real, real_root) + except ValueError: # another drive + return None + if rel == os.pardir or rel.startswith(os.pardir + os.sep): + return None + return rel.casefold() if _FOLD_CASE else rel + + +def touched_scope(repo_root, cwd, touched_paths): + """Where the paths the session's edit tools wrote since the baseline lie: + (scope, repo-relative paths inside the repo). scope: 0 none recorded, + 1 all inside the reviewed repo, 2 some outside, 3 all outside. Relative + paths are read against `cwd`. The list holds the newest 200 paths, so + this is approximate past that. Telemetry only.""" + root = os.path.realpath(repo_root) + inside, outside = set(), 0 + for p in touched_paths: + rel = _rel_in_repo(root, os.path.join(cwd or root, p)) + if rel is None: + outside += 1 + else: + inside.add(rel) + if not touched_paths: + return 0, inside + if not outside: + return 1, inside + return (2 if inside else 3), inside + + +def review_scope_code(repo_root, scope, inside, files, base_fail): + """One number, for telemetry only, saying how a Stop review relates to + what the session's edit tools wrote since the baseline: + + base_fail * 100000 + scope * 10000 + min(untouched, 9999) + + scope and inside: from touched_scope. untouched: how many of `files` + (repo-root-relative or absolute) no edit tool wrote. base_fail: 0 the + review diffed against a real turn-start snapshot, 1 and 2 see + last_baseline_fail, 3 there was no usable snapshot. Packed into one key + and sent even when 0, so a row without it was cut by the metrics key cap + or had no repo.""" + root = os.path.realpath(repo_root) + untouched = sum(1 for f in files + if _rel_in_repo(root, os.path.join(root, f)) not in inside) + return int(base_fail or 0) * 100000 + scope * 10000 + min(untouched, 9999) + + def record_reviewed_diff(session_id, diff_hash): def _save(state): state["reviewed_diff_hash"] = diff_hash @@ -234,6 +301,14 @@ def get_baseline_file_content(session_id, file_path, cwd): return None +# 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 +# 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. +last_baseline_fail = 0 + + def capture_git_baseline(cwd): """ Capture a git ref representing the current working tree state. @@ -260,6 +335,8 @@ def capture_git_baseline(cwd): # 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. + global last_baseline_fail + last_baseline_fail = 0 try: # Check if HEAD exists (i.e., repo has at least one commit) head_check = subprocess.run( @@ -281,6 +358,10 @@ def capture_git_baseline(cwd): 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: + last_baseline_fail = 1 + else: + last_baseline_fail = 2 if sha: return sha diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index eb132c50..a526e471 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -124,6 +124,7 @@ 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, + touched_scope, review_scope_code, baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS, KEPT_NO_CAPTURE, KEPT_UNREVIEWED, ) @@ -133,6 +134,7 @@ from reporesolve import ( # noqa: E402,F401 toplevel_from_command, repo_containing_commit, scan_roots, resolve_repo_root, save_repo_hint, load_repo_hint, ) +import diffstate # noqa: E402 module ref for last_baseline_fail import gitutil # noqa: E402 module ref for per-run counters import llm # noqa: E402 module ref for reassignable globals (_last_call_claude_http_error etc.) from llm import ( # noqa: E402,F401 @@ -644,6 +646,14 @@ def extract_content_from_input(tool_name, tool_input, tool_response=None): # Hook handlers # ===================================================================== +def _store_baseline_fail(state, fail): + """Keep diffstate.last_baseline_fail next to the baseline_sha it describes.""" + if fail: + state["baseline_fail"] = fail + else: + state.pop("baseline_fail", None) + + def handle_user_prompt_submit(input_data): """ Handle UserPromptSubmit — capture git baseline SHA. @@ -701,6 +711,7 @@ def handle_user_prompt_submit(input_data): sha, untracked_now = _capture(cwd) else: no_repo = True + baseline_fail = diffstate.last_baseline_fail # 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: @@ -737,6 +748,8 @@ def handle_user_prompt_submit(input_data): if sha: state["baseline_sha"] = sha state["head_at_capture"] = head + state.pop("turn_touched", None) + _store_baseline_fail(state, baseline_fail) # A Stop review that ends up in another checkout does not use # this baseline. state["baseline_root"] = root @@ -2445,6 +2458,23 @@ def handle_stop_hook(input_data): _TAIL_METRICS["bl_origin"] = baseline_origin_metric(origin, snap["baseline_kept"]) v2_metrics = {**res_metrics, **v2_metrics} + # Count-only view of how the review set relates to what the session's + # edit tools wrote. Only when a repo was read; never fails the review. + def _note_scope(files): + try: + if "scope" not in _scope: + _scope["scope"] = touched_scope( + repo_root, input_data.get("cwd", ""), snap["turn_touched"]) + # -1: the stored baseline could not be used in this repo. + fail = (3 if v2_metrics.get("changed_since_count") == -1 + else snap.get("baseline_fail")) + _TAIL_METRICS["review_scope"] = review_scope_code( + repo_root, *_scope["scope"], files, fail) + except Exception as e: + debug_log(f"review scope telemetry skipped: {e}") + _scope = {} + if v2_metrics.get("dirty_now_count", -1) >= 0: + _note_scope(review_paths) if not review_paths: debug_log("Stop hook: empty review set") _skip(9, touched_paths_count=len(touched_paths)) @@ -2503,6 +2533,8 @@ def handle_stop_hook(input_data): # Filter out pre-existing content from file rewrites diff_files = filter_preexisting_from_diff(diff_files, cwd, baseline_sha) + if "scope" in _scope: + _note_scope([fp for fp, _ in diff_files]) debug_log(f"Stop hook: reviewing {len(diff_files)} changed files (standard diff)") @@ -2549,6 +2581,7 @@ 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_base_fail = diffstate.last_baseline_fail 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. @@ -2578,6 +2611,7 @@ def handle_stop_hook(input_data): if new_sha: state["baseline_sha"] = new_sha state["untracked_at_baseline"] = new_untracked_baseline + _store_baseline_fail(state, new_base_fail) state["baseline_root"] = repo_root state.pop("baseline_kept", None) if foreign_baseline: diff --git a/plugins/security-guidance/tests/test_stop_scope_metrics.py b/plugins/security-guidance/tests/test_stop_scope_metrics.py new file mode 100644 index 00000000..c65103b6 --- /dev/null +++ b/plugins/security-guidance/tests/test_stop_scope_metrics.py @@ -0,0 +1,181 @@ +"""Stop rows carry one count-only number, `review_scope`, saying how the +reviewed files relate to what the session's edit tools wrote and whether the +turn-start snapshot was a real one.""" +import os +import shutil + +import pytest + +from conftest import ( + STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, + ups_payload, +) + +import diffstate + +needs_sh = pytest.mark.skipif(os.name == "nt", reason="uses a /bin/sh git shim") + + +def _stop(repo, env): + return metrics_of(run_hook(stop_payload(repo), env)[1]) + + +def _turn(repo, env, edits=(), during=None): + run_hook(ups_payload(repo), env) + for path in edits: + run_hook(edit_payload(repo, path), env) + if during: + during() + 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.""" + bindir = tmp_path / "bin" + bindir.mkdir() + shim = bindir / "git" + shim.write_text( + '#!/bin/sh\nfor a in "$@"; do [ "$a" = stash ] && exit 1; done\n' + f'exec "{shutil.which("git")}" "$@"\n') + shim.chmod(0o755) + return {**hook_env, "PATH": f"{bindir}{os.pathsep}{hook_env['PATH']}"} + + +class TestScope: + def test_edits_outside_repo_review_of_a_file_they_did_not_write(self, hook_env, workspace): + ws, repo = workspace + m = _turn(repo, hook_env, edits=[ws / "notes.md"], + during=lambda: (repo / "other.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 30001 + + def test_edit_inside_repo(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, edits=[repo / "app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 10000 + + def test_relative_edit_path_is_read_against_the_session_cwd(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, edits=["app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 10000 + + def test_mixed_edits_and_a_file_changed_by_other_means(self, hook_env, workspace): + ws, repo = workspace + + def during(): + (repo / "app.py").write_text(VULN_PY) + (repo / "gen.py").write_text(VULN_PY) + m = _turn(repo, hook_env, edits=[ws / "notes.md", repo / "app.py"], during=during) + assert m["files_reviewed"] == 2 and m["review_scope"] == 20001 + + def test_no_edit_tool_paths(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 1 + + def test_outside_only_turn_with_nothing_to_review(self, hook_env, workspace): + ws, repo = workspace + m = _turn(repo, hook_env, edits=[ws / "notes.md"]) + assert m["skipped"] is True and m["review_scope"] == 30000 + + def test_skipped_review_counts_over_the_review_set(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, during=lambda: (repo / "notes.txt").write_text("x\n")) + assert m["skipped"] is True and m["review_scope"] == 1 + + def test_second_review_of_the_same_turn_still_knows_the_edits(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, edits=[repo / "app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["review_scope"] == 10000 + m = _stop(repo, hook_env) # a rewake: no new prompt, same baseline + assert m["files_reviewed"] == 1 and m["review_scope"] == 10000 + # The next prompt starts a new count. + m = _turn(repo, hook_env, during=lambda: (repo / "gen.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 and m["review_scope"] == 1 + + def test_no_key_outside_a_repo(self, hook_env, tmp_path): + plain = tmp_path / "plain" + plain.mkdir() + m = _turn(plain, hook_env, edits=[plain / "a.py"], + during=lambda: (plain / "a.py").write_text(VULN_PY)) + assert m["skipped"] is True and "review_scope" not in m + + def test_unreadable_path_does_not_stop_the_review(self, hook_env, workspace): + _, repo = workspace + m = _turn(repo, hook_env, edits=[str(repo / "a\ud800b.py"), repo / "app.py"], + during=lambda: (repo / "app.py").write_text(VULN_PY)) + assert m["files_reviewed"] == 1 + if os.name == "nt": + # Windows paths can hold a lone surrogate: it is one more file + # in the repo. + assert m["review_scope"] == 10000 + else: + assert "review_scope" not in m + + +class TestSnapshot: + def test_no_prompt_hook_means_no_snapshot(self, hook_env, workspace): + _, repo = workspace + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py"), hook_env) + m = _stop(repo, hook_env) + assert m["files_reviewed"] == 1 and m["review_scope"] == 310000 + + @needs_sh + 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"]) + 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"], + during=lambda: (repo / "app.py").write_text(VULN_PY + "# more\n")) + assert m["files_reviewed"] == 1 and m["review_scope"] == 10000 + + @needs_sh + 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) + stub_api.vulns = [STUB_VULN] + # Good snapshot at the prompt; the one taken after the finding fails. + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + run_hook(edit_payload(repo, repo / "app.py"), hook_env) + m = _stop(repo, broken) + assert m["vulns_found"] == 1 and m["review_scope"] == 10000 + (repo / "app.py").write_text(VULN_PY + "# fix\n") + run_hook(edit_payload(repo, repo / "app.py"), hook_env) + m = _stop(repo, hook_env) + assert m["review_scope"] == 110000 + # That Stop took a real one again. + (repo / "app.py").write_text(VULN_PY + "# fix 2\n") + run_hook(edit_payload(repo, repo / "app.py"), hook_env) + m = _stop(repo, hook_env) + assert m["review_scope"] == 10000 + + +class TestCode: + def _code(self, root, cwd, touched, files, fail=0): + scope, inside = diffstate.touched_scope(root, cwd, touched) + return diffstate.review_scope_code(root, scope, inside, files, fail) + + def test_repo_at_the_filesystem_root(self): + root = os.path.abspath(os.sep) + assert self._code(root, root, [os.path.join(root, "x.py")], ["x.py", "y.py"]) == 10001 + + def test_names_that_only_start_like_a_parent_dir(self, tmp_path): + root = str(tmp_path) + assert self._code(root, root, [str(tmp_path / "..hidden.py")], ["..hidden.py"], 2) == 210000 + + def test_untouched_count_is_capped(self, tmp_path): + files = [f"f{i}.py" for i in range(12000)] + assert self._code(str(tmp_path), "", [], files) == 9999 + + def test_absolute_and_relative_file_names_count_the_same(self, tmp_path): + root = str(tmp_path) + touched = [str(tmp_path / "a.py")] + assert self._code(root, root, touched, ["a.py", "b.py"]) == 10001 + assert self._code(root, root, touched, [str(tmp_path / "a.py"), str(tmp_path / "b.py")]) == 10001 |
