diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-11-09 14:59:32 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-09 14:59:32 -0800 |
| commit | ea686bae367e20a4092b2fd4327ffd299bb60f24 (patch) | |
| tree | cd64a87ba776838a0941e6e43d1b05d480ec8af5 /plugins/security-guidance/hooks | |
| parent | fa5015cff6782d33feeeb31dd2753eea3be83568 (diff) | |
| parent | 5d1c0f596415311a60adc55d0c0fa1d5f4ac27d8 (diff) | |
Merge pull request #7033 from anthropics/mhegazy/sg-unseen-commit-count
security-guidance: count commits that no commit hook saw
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 92 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 45 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 56 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/session_state.py | 27 |
4 files changed, 217 insertions, 3 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 9ca56774..174207f7 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -13,7 +13,7 @@ import sys import unicodedata import time -from _base import debug_log, portable_output, _PV +from _base import debug_log, make_state_dir, portable_output, _PV import gitutil from gitutil import ( GIT_CMD, @@ -23,6 +23,8 @@ from gitutil import ( ) from session_state import load_state, with_locked_state from extensibility import _same_dir +from gitutil import turn_commit_shas +from session_state import commit_log_files, get_commit_log_file # ===================================================================== @@ -105,6 +107,7 @@ def consume_stop_state(session_id, clear=True): # Where and when the prompt hook captured it; see baseline_origin. "baseline_root": state.get("baseline_root"), "prompt_at": state.get("prompt_at"), + "turn_started": state.get("turn_started"), "baseline_kept": state.get("baseline_kept") or 0, "untracked_at_baseline": ( dict(state["untracked_at_baseline"]) @@ -141,7 +144,7 @@ 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": {}, "baseline_root": None, "prompt_at": None, - "baseline_kept": 0, + "baseline_kept": 0, "turn_started": None, "fire_count": 0, "fire_count_expired": False, "previous_findings": [], "reviewed_diff_hash": None, "state_resets": 0, "state_overwrites": 0, "baseline_fail": 0, "turn_touched": [], @@ -661,6 +664,91 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0): pass +# ─── commits of a turn, count only ────────────────────────────────────────── +# +# A commit review starts from a hook on the Bash tool. A commit made another +# way (the PowerShell tool, a script, the user's own terminal) starts none. +# The Stop row says how many commits a turn made and how many of them no +# commit hook saw. Nothing reads these to decide whether a review runs. +# +# Kept in a file of its own per session, append-only: saving the session state +# from one more background hook could drop another hook's change where there +# is no state lock (Windows). Lines: `seen <sha prefix>` from commit hooks, +# `counted <sha>` from the Stop hook. Every session's are read, so a commit +# is seen by any of them and counted once on this machine. + +TURN_COMMITS_ERROR = -1 + + +def _note_commits(session_id, kind, shas): + """Never raises.""" + if not shas or portable_output(): + return + try: + path = get_commit_log_file(session_id) + make_state_dir(os.path.dirname(path)) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND + | getattr(os, "O_NOFOLLOW", 0), 0o600) + with os.fdopen(fd, "a") as f: + f.write("".join(f"{kind} {sha}\n" for sha in shas)) + except Exception as e: + debug_log(f"{kind} commits not noted: {e}") + + +def note_seen_commits(session_id, shas): + """A commit hook saw these commits.""" + _note_commits(session_id, "seen", shas) + + +def note_counted_commits(session_id, shas): + """These commits went out in a Stop row.""" + _note_commits(session_id, "counted", shas) + + +def turn_commits_code(repo_root, prompt_at, until, head_before=None): + """(code, shas) for the commits made in this checkout from the prompt to + `until` that no Stop row has counted yet: + + made * 10000 + no_review * 100 + unseen (each capped at 99) + + no_review: no finished or running review in this clone, for whatever + reason. unseen: of those, the ones no commit hook saw. The code is None + when nothing was committed or the start of the turn is not known, + TURN_COMMITS_ERROR when git could not say.""" + if not isinstance(prompt_at, (int, float)) or not 0 < prompt_at < 1e11: + return None, [] + shas = turn_commit_shas(repo_root, prompt_at, until, head_before) + if not shas: + return (TURN_COMMITS_ERROR if shas is None else None), [] + noted = {"seen": set(), "counted": set()} + for path in commit_log_files(newer_than=prompt_at): + try: + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + kind, _, value = line.strip().partition(" ") + if value and kind in noted: + noted[kind].add(value) + except OSError: + return TURN_COMMITS_ERROR, [] + new = [s for s in shas if s not in noted["counted"]] + if not new: + return None, [] + gd = _git_dir(repo_root) + if not gd: + return TURN_COMMITS_ERROR, [] + # The marker file, not its lock: taking the lock for a moment could make + # the review that is about to claim the commit leave it alone. Markers + # first: a review that ends in between then reads as finished. + missed = [s for s in new + if not os.path.exists(os.path.join(gd, _INFLIGHT_PREFIX + s))] + reviewed = _load_reviewed_shas(repo_root, _gd=gd) + missed = [s for s in missed if s not in reviewed] + seen = tuple(noted["seen"]) + unseen = sum(1 for s in missed if not s.startswith(seen)) + code = min(len(new), 99) * 10000 + min(len(missed), 99) * 100 + min(unseen, 99) + return code, new + + # ─── repeated-diff count ──────────────────────────────────────────────────── # # Count only. A change that comes back under a new commit (undo and re-commit, diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 4c363ef4..9b1e2c91 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -1097,6 +1097,51 @@ def _detect_main_branch(repo_root): return None +# Commits turn_commit_shas reads. +TURN_COMMITS_MAX = 100 + + +def turn_commit_shas(repo_root, since, until, head_before=None): + """SHAs that `git commit` made in this checkout from `since` to `until` + (epoch seconds), newest first, from its HEAD reflog. None when git cannot + say. Not merges, picks, reverts or rebases: no review hook waits for + those. + + Goes by the time of the reflog entry, so checking out or pulling + somebody's recent commit does not count as making one (a commit made + with GIT_COMMITTER_DATE set is dated by that). Those times are whole + seconds; `head_before`, what HEAD was at `since`, leaves out the commits + made earlier in that second.""" + try: + # --date=unix makes %gd `HEAD@{<seconds>}`; %gs is free text, so last. + r = subprocess.run( + [*GIT_CMD, "log", "-g", "--no-show-signature", "--date=unix", + "--basic-regexp", "--grep-reflog=^commit", "-n", str(TURN_COMMITS_MAX), + "--format=%H %gd %gs", "HEAD", "--"], + cwd=repo_root, capture_output=True, timeout=5, + ) + except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError): + return None + if r.returncode != 0: + # A repository without a commit has nothing to count. + return None if _git_rev_parse_head(repo_root) or not _git_toplevel(repo_root) else [] + since = int(since) + entries = [] + for line in r.stdout.decode("utf-8", errors="replace").splitlines(): + # 40 digits only: the reviewed record knows no SHA-256 ids. + m = re.match(r"([0-9a-f]{40}) HEAD@\{(\d+)\} commit(?! \((?:merge|cherry-pick)\))", line) + if m and since <= int(m.group(2)) <= until: + entries.append((m.group(1), int(m.group(2)))) + # Oldest match, as the turn itself can come back to where it started. + for i in range(len(entries) - 1, -1, -1): + if entries[i][1] > since: + break + if entries[i][0] == head_before: + del entries[i:] + break + return list(dict.fromkeys(sha for sha, _ in entries)) + + def _git_reflog_recent_commits(repo_root, max_age_s=120, max_n=5): """Return (fresh_commit_shas, stale_count) from the HEAD reflog. diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index e9ee4421..e87afe55 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -261,6 +261,13 @@ _TAIL_METRICS: Dict[str, Any] = {} # keys below come later; those are also on every smaller row of the session. _LAST_METRIC_KEYS = ("diff_seen",) +# CC keeps this many keys of a row. +_METRIC_KEY_CAP = 20 +# How long a Stop row waits for its commit count. +_TURN_COMMITS_WAIT_S = 2.0 +# Set by the Stop hook: queues the commit count for the row being emitted. +_turn_commits_request = None + # The launcher's slow interpreter probes, if any. After the keys above. _LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics() # Whether the launcher skipped a packaged alias. Only on rows sent anyway. @@ -293,6 +300,47 @@ def _note_reviewer_context(agentic_metrics): turns * _EFFORT_TURNS_UNIT + min(api_ms, _EFFORT_TURNS_UNIT - 1)) +def _request_turn_commits(session_id, cwd, turn_started): + """Count the commits from the prompt to now on this Stop row.""" + global _turn_commits_request + import time as _time + try: + started_at, head_before = turn_started + except (TypeError, ValueError): + return + _turn_commits_request = (session_id, cwd, started_at, head_before, _time.time()) + + +def _add_turn_commits(metrics): + """Append `turn_commits` to a Stop row that has room for it. Computed + here, once the row is ready, so the turn's commit hooks have had the + length of the review to start. On a thread with a short limit: findings + wait for this row. Commits that find no room are left for a later Stop + row of the turn. Never raises.""" + if not _turn_commits_request or len(metrics) >= _METRIC_KEY_CAP: + return + session_id, cwd, started_at, head_before, until = _turn_commits_request + result = [] + + def _count(): + try: + repo_root = _git_toplevel(cwd) if cwd else None + result.append(diffstate.turn_commits_code( + repo_root, started_at, until, head_before) if repo_root else (None, [])) + except Exception as e: + debug_log(f"turn commit count failed: {e}") + try: + counter = threading.Thread(target=_count, daemon=True) + counter.start() + counter.join(_TURN_COMMITS_WAIT_S) + except RuntimeError as e: # no thread to be had + debug_log(f"turn commit count failed: {e}") + code, shas = result[0] if result else (diffstate.TURN_COMMITS_ERROR, []) + if code is not None: + metrics["turn_commits"] = code + diffstate.note_counted_commits(session_id, shas) + + def emit_metrics( metrics, rewake_summary=None, @@ -401,6 +449,7 @@ def emit_metrics( # Last of all: the first key a full row loses. tail.update(_LAUNCHER_DIRECT) metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} + _add_turn_commits(metrics) out = {"metrics": metrics} if rewake_summary: out["rewakeSummary"] = rewake_summary @@ -862,6 +911,9 @@ def handle_user_prompt_submit(input_data): preserved = {"value": False} def _save(state): + # Where this turn's own commits start, also when the baseline below + # stays an earlier turn's. Telemetry only. + state["turn_started"] = [captured_at, head] # Only preserve if there's actually an old baseline to preserve. # First UPS of a session can have touched_paths if PostToolUse # somehow ran first (print mode, odd harnesses) — in that case @@ -1678,6 +1730,7 @@ def handle_commit_review_posttooluse(input_data): # `git commit || git log --stat` where `N files changed` appears in output # even though the commit itself failed. all_shas = _COMMIT_SHA_RE.findall(bash_output) + diffstate.note_seen_commits(session_id, all_shas) commit_succeeded = ( not interrupted and bool(all_shas) @@ -1724,6 +1777,7 @@ def handle_commit_review_posttooluse(input_data): _base["repo_resolution"] = repo_res _root = repo_root _fresh, _stale = _git_reflog_recent_commits(_root) + diffstate.note_seen_commits(session_id, _fresh) if _fresh: # Commits an earlier call's review is still working on are that # review's: it records them when it has a verdict. (Read before @@ -2620,6 +2674,8 @@ def handle_stop_hook(input_data): head_at_capture = snap["head_at_capture"] untracked_at_baseline = snap.get("untracked_at_baseline") or {} previous_findings = snap["previous_findings"] + if not is_subagent and not portable_output(): + _request_turn_commits(session_id, cwd, snap["turn_started"]) # Only when it happened: state lost to an unreadable file, and saves that # overwrote another hook's (possible only without locking). SubagentStop # does not clear them, so it does not report them either. diff --git a/plugins/security-guidance/hooks/session_state.py b/plugins/security-guidance/hooks/session_state.py index 330abd28..14a72a42 100644 --- a/plugins/security-guidance/hooks/session_state.py +++ b/plugins/security-guidance/hooks/session_state.py @@ -47,6 +47,31 @@ def get_lock_file(session_id): return os.path.join(state_dir, f"security_warnings_state_{_state_key(session_id)}.lock") +def get_commit_log_file(session_id): + """Where diffstate notes the commits a session's hooks saw and counted.""" + state_dir = _state_dir() + return os.path.join(state_dir, f"security_warnings_state_{_state_key(session_id)}.commits") + + +def commit_log_files(newer_than): + """Those files of all sessions, written to since `newer_than` (epoch + seconds, with some slack for coarse file times).""" + state_dir = _state_dir() + out = [] + try: + for name in os.listdir(state_dir): + if name.startswith("security_warnings_state_") and name.endswith(".commits"): + path = os.path.join(state_dir, name) + try: + if os.path.getmtime(path) >= newer_than - 5: + out.append(path) + except OSError: + pass + except OSError: + pass + return out + + def cleanup_old_state_files(): """Remove state files, lock files and leftover temporary files older than 30 days.""" try: @@ -59,7 +84,7 @@ def cleanup_old_state_files(): for filename in os.listdir(state_dir): if filename.startswith("security_warnings_state_") and ( - filename.endswith((".json", ".lock", ".tmp")) + filename.endswith((".json", ".lock", ".tmp", ".commits")) ): file_path = os.path.join(state_dir, filename) try: |
