summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-09 14:59:22 -0800
committerGitHub <noreply@github.com>2026-11-09 14:59:22 -0800
commit97c32530afada4841fca83fde0d470812a3dcfab (patch)
treed1a9d75a5a70f3839f428ae1e54cf8b3a55dd401 /plugins/security-guidance/hooks
parent0412be76f50ab4f4f8abff3753efa9269fbbca5b (diff)
parenta8fa1532035ddf875c8594dd4407cbe38ffbe99a (diff)
Merge pull request #6838 from anthropics/mhegazy/sg-stop-finding-names-unwritten
security-guidance: say when a Stop finding is in a file the session has no record of editing
Diffstat (limited to 'plugins/security-guidance/hooks')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py95
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py56
2 files changed, 141 insertions, 10 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index 34655335..9ca56774 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -10,6 +10,7 @@ import hashlib
import os
import subprocess
import sys
+import unicodedata
import time
from _base import debug_log, portable_output, _PV
@@ -20,7 +21,7 @@ from gitutil import (
_git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index,
_secret_rename_origins, index_entry_count,
)
-from session_state import with_locked_state
+from session_state import load_state, with_locked_state
from extensibility import _same_dir
@@ -72,8 +73,8 @@ def record_touched_path(session_id, file_path):
paths = state.setdefault("touched_paths", [])
if file_path not in paths:
paths.append(file_path)
- if len(paths) > 200:
- del paths[:len(paths) - 200]
+ if len(paths) > TOUCHED_PATHS_CAP:
+ del paths[:len(paths) - TOUCHED_PATHS_CAP]
with_locked_state(session_id, _record)
@@ -120,12 +121,16 @@ def consume_stop_state(session_id, clear=True):
}
# 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.
+ # recorded since the prompt hook's baseline. Read by the scope
+ # metric and, through touched_since_prompt, by the no-edit-record note.
turn = list(dict.fromkeys(
[p for p in state.get("turn_touched", []) if isinstance(p, str)]
- + snap["touched_paths"]))[-200:]
+ + snap["touched_paths"]))[-TOUCHED_PATHS_CAP:]
snap["turn_touched"] = turn
if clear:
+ if snap["state_resets"] or snap["state_overwrites"]:
+ # turn_touched outlives this Stop, and so does its gap.
+ state["turn_touched_lost"] = True
state["turn_touched"] = turn
state["touched_paths"] = []
state.pop("reviewed_diff_hash", None)
@@ -143,6 +148,32 @@ def consume_stop_state(session_id, clear=True):
}
+# record_touched_path and turn_touched keep the newest paths only.
+TOUCHED_PATHS_CAP = 200
+
+
+def touched_since_prompt(session_id):
+ """(paths, complete): every path the session's edit tools recorded since
+ the prompt hook's baseline, read now and without consuming or writing
+ anything, so edits recorded while a Stop review runs are in it.
+ `complete` is False when the list is known to be missing paths: the
+ state was lost or overwritten since the prompt, it could not be read, or
+ the prompt hook's own save is not in it. Callers check the length
+ against TOUCHED_PATHS_CAP."""
+ try:
+ state = load_state(session_id)
+ except Exception:
+ return [], False
+ if not isinstance(state, dict):
+ return [], False
+ paths = list(dict.fromkeys(
+ [p for p in state.get("turn_touched", []) if isinstance(p, str)]
+ + [p for p in state.get("touched_paths", []) if isinstance(p, str)]))
+ lost = (state.get("state_resets") or state.get("state_overwrites")
+ or state.get("turn_touched_lost"))
+ return paths, not lost and state.get("prompt_at") is not None
+
+
# Path names compare without case where the filesystem usually does.
_FOLD_CASE = os.name == "nt" or sys.platform == "darwin"
@@ -151,13 +182,21 @@ 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)
+ if sys.platform == "darwin":
+ # git and the file system can spell one name composed and decomposed.
+ real = unicodedata.normalize("NFC", real)
+ real_root = unicodedata.normalize("NFC", real_root)
+ if _FOLD_CASE:
+ # Fold before comparing: realpath keeps the case a path was typed in,
+ # so the repo folder itself can be spelled differently too.
+ real, real_root = real.casefold(), real_root.casefold()
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
+ return rel
def touched_scope(repo_root, cwd, touched_paths):
@@ -165,7 +204,7 @@ def touched_scope(repo_root, cwd, touched_paths):
(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."""
+ this is approximate past that."""
root = os.path.realpath(repo_root)
inside, outside = set(), 0
for p in touched_paths:
@@ -199,6 +238,44 @@ def review_scope_code(repo_root, scope, inside, files, base_fail):
return int(base_fail or 0) * 100000 + scope * 10000 + min(untouched, 9999)
+def findings_without_edit_record(session_id, at_stop_start, repo_root, cwd,
+ finding_paths, reviewed):
+ """Which findings are in a reviewed file for which there is no record of
+ this session's edit tools writing it since the prompt: (those files as
+ the review named them, in order and without repeats; how many findings
+ they hold). The count is -1, with no files, when the record is known to
+ be incomplete: lost state, or more paths than the list keeps.
+
+ `at_stop_start`: turn_touched as the Stop began; a prompt that arrives
+ while the review runs resets the stored list. A finding path that is not
+ one of the `reviewed` files, or that cannot be resolved, is left out."""
+ since, complete = touched_since_prompt(session_id)
+ touched = list(dict.fromkeys(list(at_stop_start) + since))
+ if not complete or len(touched) >= TOUCHED_PATHS_CAP:
+ return [], -1
+ _, inside = touched_scope(repo_root, cwd, touched)
+ root = os.path.realpath(repo_root)
+
+ def rel(f):
+ try:
+ return _rel_in_repo(root, os.path.join(root, f))
+ except (ValueError, OSError): # NUL, or a name the OS cannot encode
+ return None
+ candidates = {}
+ for f in reviewed:
+ r = rel(f)
+ if r is not None and r not in inside:
+ candidates.setdefault(r, f)
+ names, count = [], 0
+ for f in finding_paths:
+ r = rel(f) if isinstance(f, str) and f else None
+ if r in candidates:
+ count += 1
+ if candidates[r] not in names:
+ names.append(candidates[r])
+ return names, count
+
+
def record_reviewed_diff(session_id, diff_hash):
def _save(state):
state["reviewed_diff_hash"] = diff_hash
@@ -221,8 +298,8 @@ def restore_unreviewed_stop_state(session_id, paths, baseline_sha):
def _restore(state):
existing = state.get("touched_paths", [])
merged = list(dict.fromkeys(list(paths) + list(existing)))
- if len(merged) > 200:
- merged = merged[:200]
+ if len(merged) > TOUCHED_PATHS_CAP:
+ merged = merged[:TOUCHED_PATHS_CAP]
state["touched_paths"] = merged
if baseline_sha and not state.get("baseline_sha"):
state["baseline_sha"] = baseline_sha
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 47a992aa..e9ee4421 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -129,6 +129,7 @@ from diffstate import ( # noqa: E402,F401
_diff_review_started, _diff_review_done,
UNTRACKED_BASELINE_CAP, _list_untracked, compute_v2_review_set,
touched_scope, review_scope_code,
+ findings_without_edit_record,
baseline_origin, baseline_origin_metric, FOREIGN_ORIGINS,
KEPT_NO_CAPTURE, KEPT_UNREVIEWED,
)
@@ -220,6 +221,36 @@ CONTINUATION_SUFFIX = (
"response."
)
+# Added to a Stop finding in a file with no record of this session's edit
+# tools writing it since the prompt. The review set comes from git, so it can
+# hold another session's or process's work in the same checkout, and without
+# a turn-start snapshot also earlier work. The record is not proof (a shell
+# command leaves none, and a record can be lost), so the note states only
+# what is known and leaves the decision to the session.
+NO_EDIT_RECORD_NOTE = (
+ "\n\nNote: this review has no record of this session's edit tools "
+ "writing {files} since the last prompt. It reviews every change it "
+ "finds in the checkout, so that change may have been made another way: "
+ "by a shell command, in an earlier turn, or by another process or "
+ "session working in this checkout. If it is not your change, leave the "
+ "file as it is and tell the user about the finding instead of fixing "
+ "it. If it is your change, handle the finding as usual."
+)
+NO_EDIT_RECORD_NOTE_MAX_FILES = 10
+
+
+def _no_edit_record_note(names):
+ """The note for `names` (from findings_without_edit_record), or "".
+ Quoted as JSON: a file name can hold a line break."""
+ if not names:
+ return ""
+ shown = ", ".join(json.dumps(n) for n in names[:NO_EDIT_RECORD_NOTE_MAX_FILES])
+ if len(names) > NO_EDIT_RECORD_NOTE_MAX_FILES:
+ shown += (f" and {len(names) - NO_EDIT_RECORD_NOTE_MAX_FILES} more of "
+ "the files above")
+ return NO_EDIT_RECORD_NOTE.format(files=shown)
+
+
# New files named in the notice for a failed `git add -N`.
_LEFT_OUT_NAMES_SHOWN = 5
@@ -853,6 +884,7 @@ def handle_user_prompt_submit(input_data):
state["baseline_sha"] = sha
state["head_at_capture"] = head
state.pop("turn_touched", None)
+ state.pop("turn_touched_lost", None)
_store_baseline_fail(state, baseline_fail)
# A Stop review that ends up in another checkout does not use
# this baseline.
@@ -2941,6 +2973,27 @@ def handle_stop_hook(input_data):
if new_sha:
debug_log(f"Updated git baseline after stop hook: {new_sha[:12]}")
+ # Say so when a finding is in a file with no record of the session's
+ # edit tools writing it. Not when the state file was already found
+ # lost at the start of this Stop. Never fails the delivery.
+ no_record_note = ""
+ try:
+ if v2_metrics.get("dirty_now_count", -1) >= 0:
+ names, n_no_record = [], -1
+ if not (snap.get("state_resets") or snap.get("state_overwrites")):
+ names, n_no_record = findings_without_edit_record(
+ session_id, snap["turn_touched"], repo_root,
+ input_data.get("cwd", ""),
+ [v.get("filePath") for v in vulns],
+ [fp for fp, _ in diff_files])
+ no_record_note = _no_edit_record_note(names)
+ # Findings in such files; -1 when the record was incomplete
+ # and no note was added. Sent even when 0 and after the review
+ # keys, so a row without it was cut by the key cap.
+ _TAIL_METRICS["finding_no_edit_record"] = n_no_record
+ except Exception as e:
+ debug_log(f"no-edit-record note skipped: {e}")
+
sev = {"critical": 0, "high": 0, "medium": 0}
for v in vulns:
s = v.get("severity", "medium")
@@ -2972,7 +3025,8 @@ def handle_stop_hook(input_data):
**({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)}
if gitutil._secret_shaped_skipped else {}),
}, rewake_summary=_format_vulns_summary(vulns),
- additional_context=(PROVENANCE_BANNER + "\n\n" + concrete_guidance
+ additional_context=(PROVENANCE_BANNER + "\n\n"
+ + concrete_guidance + no_record_note
+ ("\n\n" + left_out_notice[1] if left_out_notice else "")
+ CONTINUATION_SUFFIX + "\n"),
hook_event_name=hook_event_name)