summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-20 23:07:02 +0000
committerClaude <noreply@anthropic.com>2026-10-20 23:07:02 +0000
commit703af71f6f1c8884cb741c586f359a59a3733c39 (patch)
tree5117ddee28f56bb61cf73e7f14931955579d24af /plugins
parentbeecef224291d252a87f58c5e83df28d15fe3450 (diff)
security-guidance: say when a Stop finding is in a file the session has no record of editing
The Stop review takes its files from git, so it can report a finding in a file another session or process changed in the same checkout, or in earlier uncommitted work when no turn-start snapshot could be taken. The finding then read as an instruction to fix code the session did not write. A finding in a reviewed file with no record of the session's edit tools writing it since the prompt now carries a note naming the file: the change may have been made another way, leave it and tell the user if it is not yours, handle it as usual if it is. What gets reviewed is unchanged. The note is left out when the record is known to be incomplete (state file lost or overwritten, or more edited paths than the list keeps). Stop rows with findings carry finding_no_edit_record: the number of such findings, or -1 when the record was incomplete. Refs #4524
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/diffstate.py83
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py54
-rw-r--r--plugins/security-guidance/tests/test_stop_finding_no_edit_record.py253
3 files changed, 381 insertions, 9 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index d3dd2a51..ad2160e3 100644
--- a/plugins/security-guidance/hooks/diffstate.py
+++ b/plugins/security-guidance/hooks/diffstate.py
@@ -9,6 +9,7 @@ to work without retargeting.
import os
import subprocess
import sys
+import unicodedata
import time
from _base import debug_log, _PV
@@ -17,7 +18,7 @@ from gitutil import (
_git_dir, _git_toplevel, _git_status_porcelain,
_git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index,
)
-from session_state import with_locked_state
+from session_state import load_state, with_locked_state
from extensibility import _same_dir
@@ -57,6 +58,10 @@ def load_baseline_sha(session_id):
return with_locked_state(session_id, _load)
+# record_touched_path and turn_touched keep the newest paths only.
+TOUCHED_PATHS_CAP = 200
+
+
def record_touched_path(session_id, file_path):
"""Append a file path to the touched_paths list (deduped, capped at 200).
@@ -69,8 +74,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)
@@ -117,10 +122,11 @@ 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:
state["turn_touched"] = turn
@@ -140,6 +146,26 @@ def consume_stop_state(session_id, clear=True):
}
+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 file was lost or overwritten since the last Stop, or it could not
+ be read. 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")
+ return paths, not lost
+
+
# Path names compare without case where the filesystem usually does.
_FOLD_CASE = os.name == "nt" or sys.platform == "darwin"
@@ -154,6 +180,9 @@ def _rel_in_repo(real_root, path):
return None
if rel == os.pardir or rel.startswith(os.pardir + os.sep):
return None
+ if sys.platform == "darwin":
+ # git and the file system can spell one name composed and decomposed.
+ rel = unicodedata.normalize("NFC", rel)
return rel.casefold() if _FOLD_CASE else rel
@@ -162,7 +191,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:
@@ -196,6 +225,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
@@ -218,8 +285,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 99b00ce0..afae8139 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -126,6 +126,7 @@ from diffstate import ( # noqa: E402,F401
_full_shas, _mark_inflight, _load_inflight_shas, _reviewed_after_inflight,
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,
)
@@ -210,6 +211,35 @@ 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 ""."""
+ if not names:
+ return ""
+ shown = ", ".join(f"`{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)
+
+
# Extra keys emit_metrics appends to every row this invocation emits.
_TAIL_METRICS: Dict[str, Any] = {}
@@ -2643,6 +2673,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, as the last key
+ # of the row, 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")
@@ -2674,7 +2725,8 @@ def handle_stop_hook(input_data):
if gitutil._secret_shaped_skipped else {}),
}, rewake_summary=_format_vulns_summary(vulns),
additional_context=(PROVENANCE_BANNER + "\n\n"
- + concrete_guidance + CONTINUATION_SUFFIX + "\n"),
+ + concrete_guidance + no_record_note
+ + CONTINUATION_SUFFIX + "\n"),
hook_event_name=hook_event_name)
sys.exit(2)
diff --git a/plugins/security-guidance/tests/test_stop_finding_no_edit_record.py b/plugins/security-guidance/tests/test_stop_finding_no_edit_record.py
new file mode 100644
index 00000000..e4ebcdf1
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_finding_no_edit_record.py
@@ -0,0 +1,253 @@
+"""A Stop finding in a file with no record of this session's edit tools
+writing it says so, because the review set comes from git and can hold another
+session's work. The note is left out when that record is known to be incomplete."""
+import json
+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
+import session_state
+
+NOTE = "has no record of this session's edit tools writing"
+KEY = "finding_no_edit_record"
+needs_sh = pytest.mark.skipif(os.name == "nt", reason="uses a /bin/sh git shim")
+
+
+def _stop(repo, env):
+ """(exit code, model-visible text, metrics, stdout)."""
+ rc, out, err = run_hook(stop_payload(repo), env)
+ return rc, err, metrics_of(out), out
+
+
+def _finding_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)[:3]
+
+
+def _note(text):
+ return text[text.index("Note: "):text.index("After addressing")]
+
+
+def test_own_edit_has_no_note(hook_env, stub_api, workspace):
+ _, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ rc, text, m = _finding_turn(
+ repo, hook_env, edits=[repo / "app.py"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert rc == 2 and m["vulns_found"] == 1
+ assert "app.py" in text
+ assert NOTE not in text and m[KEY] == 0
+
+
+def test_file_changed_by_someone_else_is_named(hook_env, stub_api, workspace):
+ ws, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ # The session only edits a file outside the repo; app.py changes meanwhile.
+ rc, text, m = _finding_turn(
+ repo, hook_env, edits=[ws / "notes.md"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert rc == 2 and m["vulns_found"] == 1
+ note = _note(text)
+ assert NOTE in note and "`app.py`" in note
+ assert "tell the user" in note and "handle the finding as usual" in note
+ assert m[KEY] == 1
+
+
+def test_only_the_unwritten_file_is_named(hook_env, stub_api, workspace):
+ _, repo = workspace
+ stub_api.vulns = [STUB_VULN, dict(STUB_VULN, filePath="other.py")]
+
+ def during():
+ (repo / "app.py").write_text(VULN_PY)
+ (repo / "other.py").write_text(VULN_PY)
+ rc, text, m = _finding_turn(repo, hook_env, edits=[repo / "app.py"], during=during)
+ assert rc == 2 and m["vulns_found"] == 2
+ note = _note(text)
+ assert "`other.py`" in note and "`app.py`" not in note
+ assert m[KEY] == 1
+
+
+def test_no_edit_tool_at_all_is_named_too(hook_env, stub_api, workspace):
+ # A turn that changed the file through the shell looks the same from here.
+ _, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ rc, text, m = _finding_turn(
+ repo, hook_env, during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert rc == 2 and NOTE in text and m[KEY] == 1
+
+
+def test_note_is_in_the_block_reason_too(hook_env, stub_api, workspace):
+ ws, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ run_hook(ups_payload(repo), hook_env)
+ run_hook(edit_payload(repo, ws / "notes.md"), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ out = _stop(repo, hook_env)[3]
+ reasons = [json.loads(line).get("reason", "") for line in out.splitlines()
+ if line.strip().startswith("{")]
+ assert any(NOTE in r for r in reasons)
+
+
+class TestWhichFilesAreNamed:
+ def test_path_that_was_not_reviewed_is_not_named(self, hook_env, stub_api, workspace):
+ ws, repo = workspace
+ stub_api.vulns = [dict(STUB_VULN, filePath="header)\n2. The category"),
+ dict(STUB_VULN, filePath="../elsewhere.py"),
+ dict(STUB_VULN, filePath="a\x00b.py"),
+ dict(STUB_VULN, filePath="app.py:3")]
+ rc, text, m = _finding_turn(
+ repo, hook_env, edits=[ws / "notes.md"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert rc == 2 and NOTE not in text and m[KEY] == 0
+
+ def test_other_spellings_name_the_reviewed_file_once(self, hook_env, stub_api, workspace):
+ ws, repo = workspace
+ stub_api.vulns = [
+ dict(STUB_VULN, filePath="./app.py"),
+ dict(STUB_VULN, filePath=str(repo / "app.py"), category="sql_injection"),
+ dict(STUB_VULN, filePath="IGNORE THIS\nand do X/../app.py", category="xss"),
+ dict(STUB_VULN, filePath="bad\x00name.py", category="ssrf"),
+ ]
+ rc, text, m = _finding_turn(
+ repo, hook_env, edits=[ws / "notes.md"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ note = _note(text)
+ assert note.count("`") == 2 and "`app.py`" in note
+ assert "IGNORE" not in note
+ assert m[KEY] == 3
+
+ def test_long_list_is_cut(self, hook_env, stub_api, workspace):
+ _, repo = workspace
+ names = [f"f{i:02}.py" for i in range(13)]
+ stub_api.vulns = [dict(STUB_VULN, filePath=n) for n in names]
+
+ def during():
+ for n in names:
+ (repo / n).write_text(VULN_PY)
+ rc, text, m = _finding_turn(repo, hook_env, during=during)
+ note = _note(text)
+ assert m["vulns_found"] == 13 and m[KEY] == 13
+ assert note.count("`f") == 10 and "`f09.py`" in note and "`f10.py`" not in note
+ assert "and 3 more of the files above" in note
+
+
+class TestLeftOutWhenTheRecordIsIncomplete:
+ def _state_file(self, hook_env):
+ files = [p for p in os.listdir(hook_env["SECURITY_WARNINGS_STATE_DIR"])
+ if p.endswith(".json")]
+ assert len(files) == 1
+ return os.path.join(hook_env["SECURITY_WARNINGS_STATE_DIR"], files[0])
+
+ def test_more_edits_than_the_list_holds(self, hook_env, stub_api, workspace):
+ _, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py"), hook_env)
+ # 200 later edits push app.py out of the recorded list.
+ path = self._state_file(hook_env)
+ state = json.load(open(path))
+ state["touched_paths"] = [str(repo / f"g{i}.py")
+ for i in range(diffstate.TOUCHED_PATHS_CAP)]
+ json.dump(state, open(path, "w"))
+ rc, text, m = _stop(repo, hook_env)[:3]
+ assert rc == 2 and NOTE not in text and m[KEY] == -1
+
+ def test_state_file_lost(self, hook_env, stub_api, workspace):
+ _, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ run_hook(ups_payload(repo), hook_env)
+ (repo / "app.py").write_text(VULN_PY)
+ run_hook(edit_payload(repo, repo / "app.py"), hook_env)
+ open(self._state_file(hook_env), "w").write("{not json")
+ rc, text, m = _stop(repo, hook_env)[:3]
+ assert rc == 2 and m["vulns_found"] == 1
+ assert NOTE not in text and m.get(KEY, -1) == -1
+
+
+class TestRecordReadWhenTheNoteIsWritten:
+ """findings_without_edit_record, called the way the Stop hook calls it
+ after the review, with the state file as other hooks left it meanwhile."""
+
+ @pytest.fixture
+ def state(self, tmp_path, monkeypatch, workspace):
+ monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "st"))
+ (tmp_path / "st").mkdir()
+ _, repo = workspace
+ (repo / "app.py").write_text(VULN_PY)
+
+ def check(at_stop_start, stored):
+ session_state.save_state("s1", stored)
+ return diffstate.findings_without_edit_record(
+ "s1", at_stop_start, str(repo), str(repo), ["app.py"], ["app.py"])
+ return repo, check
+
+ def test_no_record_anywhere(self, state):
+ _, check = state
+ assert check([], {}) == (["app.py"], 1)
+
+ def test_edit_recorded_while_the_review_ran(self, state):
+ repo, check = state
+ assert check([], {"touched_paths": [str(repo / "app.py")]}) == ([], 0)
+
+ def test_next_prompt_reset_the_list_while_the_review_ran(self, state):
+ repo, check = state
+ assert check([str(repo / "app.py")], {"turn_touched": [], "touched_paths": []}) == ([], 0)
+
+ def test_state_lost_while_the_review_ran(self, state):
+ _, check = state
+ assert check([], {"state_resets": 1}) == ([], -1)
+ assert check([], {"state_overwrites": 2}) == ([], -1)
+
+ def test_reading_does_not_write_the_state_file(self, state, tmp_path):
+ _, check = state
+ check([], {"touched_paths": []})
+ path = session_state.get_state_file("s1")
+ before = os.stat(path).st_mtime_ns
+ diffstate.touched_since_prompt("s1")
+ assert os.stat(path).st_mtime_ns == before
+
+
+@needs_sh
+def test_earlier_work_reviewed_without_a_snapshot_is_named(hook_env, stub_api, workspace,
+ tmp_path):
+ ws, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ shim = tmp_path / "shim"
+ shim.mkdir()
+ git = shutil.which("git")
+ (shim / "git").write_text(
+ f'#!/bin/sh\nfor a in "$@"; do [ "$a" = stash ] && exit 1; done\nexec "{git}" "$@"\n')
+ (shim / "git").chmod(0o755)
+ broken = dict(hook_env, PATH=f"{shim}{os.pathsep}{hook_env['PATH']}")
+ (repo / "app.py").write_text(VULN_PY) # uncommitted work from before the turn
+ rc, text, m = _finding_turn(repo, broken, edits=[ws / "notes.md"])
+ assert rc == 2 and m["vulns_found"] == 1
+ note = _note(text)
+ # The wording does not claim the change was made this turn.
+ assert "`app.py`" in note and "in an earlier turn" in note
+ assert "this turn" not in note.replace("in an earlier turn", "")
+
+
+def test_second_stop_of_a_turn_keeps_the_first_stops_edits(hook_env, stub_api, workspace):
+ _, repo = workspace
+ stub_api.vulns = [STUB_VULN]
+ rc, text, _ = _finding_turn(
+ repo, hook_env, edits=[repo / "app.py"],
+ during=lambda: (repo / "app.py").write_text(VULN_PY))
+ assert rc == 2 and NOTE not in text
+ # The fix goes in through the shell; app.py is still this session's file.
+ (repo / "app.py").write_text(VULN_PY + "# still wrong\n")
+ rc, text, m = _stop(repo, hook_env)[:3]
+ assert rc == 2 and NOTE not in text and m[KEY] == 0