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/security-guidance/hooks | |
| 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/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 81 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 34 |
2 files changed, 115 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: |
