From d71ce397a645800a91bb5ec525ddf3d4ab320525 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Sat, 7 Nov 2026 02:01:31 +0000 Subject: security-guidance: count how custom rules are written Measure only: path globs a wider reading would change, refused and counted repeats in regexes, and the slowest custom regex, on the Stop row. Which rules apply does not change. Co-authored-by: mhegazy --- plugins/security-guidance/hooks/diffstate.py | 42 +++++- plugins/security-guidance/hooks/extensibility.py | 125 ++++++++++++++- .../hooks/security_reminder_hook.py | 24 ++- .../tests/test_custom_rule_stats.py | 168 +++++++++++++++++++++ 4 files changed, 354 insertions(+), 5 deletions(-) create mode 100644 plugins/security-guidance/tests/test_custom_rule_stats.py (limited to 'plugins') diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 34655335..275709ed 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -60,7 +60,7 @@ def load_baseline_sha(session_id): return with_locked_state(session_id, _load) -def record_touched_path(session_id, file_path): +def record_touched_path(session_id, file_path, custom_rule_stats=None): """Append a file path to the touched_paths list (deduped, capped at 200). Stop is the consumer and clears under the same lock it reads with; UPS @@ -69,6 +69,9 @@ def record_touched_path(session_id, file_path): stale paths so over-retention is harmless, just wasteful. """ def _record(state): + # In the save this hook makes anyway: one more could drop another + # hook's change where there is no state lock (Windows). + _fold_custom_rule_stats(state, custom_rule_stats) paths = state.setdefault("touched_paths", []) if file_path not in paths: paths.append(file_path) @@ -77,6 +80,36 @@ def record_touched_path(session_id, file_path): with_locked_state(session_id, _record) +# Reported on the Stop row; see extensibility.edit_stats. The first three are +# kept as maximum or union over the turn's edits, the others are added up. +CUSTOM_RULE_KEYS = ("cr_rules", "cr_slow_ms", "cr_shapes", "cr_gain", "cr_loss") + + +def _fold_custom_rule_stats(state, stats): + if not stats: + return + kept = state.get("custom_rules") + if not isinstance(kept, dict): + kept = state["custom_rules"] = {} + for key in CUSTOM_RULE_KEYS: + new, old = stats.get(key, 0), kept.get(key, 0) + if not isinstance(old, int): + old = 0 + if key == "cr_shapes": + value = old | new + elif key in ("cr_rules", "cr_slow_ms"): + value = max(old, new) + else: + value = old + new + if value: + kept[key] = value + + +def record_custom_rule_stats(session_id, stats): + """Fold one edit's custom rule counts into the turn's. Telemetry only.""" + with_locked_state(session_id, lambda state: _fold_custom_rule_stats(state, stats)) + + def consume_stop_state(session_id, clear=True): """Atomically snapshot all state the Stop hook needs and clear touched_paths. @@ -117,6 +150,10 @@ def consume_stop_state(session_id, clear=True): "state_resets": state.get("state_resets", 0), "state_overwrites": state.get("state_overwrites", 0), "baseline_fail": state.get("baseline_fail") or 0, + "custom_rules": ( + dict(state["custom_rules"]) + if isinstance(state.get("custom_rules"), dict) else {} + ), } # touched_paths is cleared per Stop, but one baseline can be # reviewed by several Stops (rewakes). turn_touched keeps every path @@ -131,6 +168,7 @@ def consume_stop_state(session_id, clear=True): state.pop("reviewed_diff_hash", None) state.pop("state_resets", None) state.pop("state_overwrites", None) + state.pop("custom_rules", None) return snap return with_locked_state(session_id, _snap) or { @@ -139,7 +177,7 @@ 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": [], + "baseline_fail": 0, "turn_touched": [], "custom_rules": {}, } diff --git a/plugins/security-guidance/hooks/extensibility.py b/plugins/security-guidance/hooks/extensibility.py index d27e9173..1f42945d 100644 --- a/plugins/security-guidance/hooks/extensibility.py +++ b/plugins/security-guidance/hooks/extensibility.py @@ -58,6 +58,11 @@ PATTERNS_BASENAMES = ("security-patterns.yaml", "security-patterns.yml", "securi _guidance_block: str = "" _user_patterns: List[Dict[str, Any]] = [] +# Custom rules whose regex the slow-regex check refused. Telemetry only. +_refused_regexes = 0 +# Seconds the slowest custom regex took in this hook. Telemetry only. +slowest_regex = 0.0 + # ── public API ─────────────────────────────────────────────────────────────── @@ -68,7 +73,8 @@ def load_for_session(cwd: Optional[str]) -> None: Called from the hook's main() before dispatching. Failures are non-fatal — a malformed config file produces a debug_log entry, never a crash. """ - global _guidance_block, _user_patterns + global _guidance_block, _user_patterns, _refused_regexes + _refused_regexes = 0 try: _guidance_block = _wrap_guidance(_load_guidance(cwd)) except Exception as e: @@ -313,6 +319,8 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: rule["substrings"] = substrings if regex: if _has_redos_structure(regex): + global _refused_regexes + _refused_regexes += 1 debug_log(f"extensibility: skipping {name}: regex looks ReDoS-prone: {regex!r:.60}") return None try: @@ -328,6 +336,7 @@ def _validate_pattern(entry: Any, source: str) -> Optional[Dict[str, Any]]: if not isinstance(paths, list) or not isinstance(exclude, list): debug_log(f"extensibility: skipping {name}: paths/exclude_paths must be lists") return None + rule["_globs"] = (tuple(paths), tuple(exclude)) # read by edit_stats # Capture as defaults so the lambda doesn't share state across rules. rule["path_filter"] = ( lambda p, _inc=tuple(paths), _exc=tuple(exclude): _glob_match(p, _inc, _exc) @@ -378,3 +387,117 @@ def _has_redos_structure(regex: str) -> bool: if a.startswith(b) or b.startswith(a): return True return False + + +# ── telemetry: how custom rules are written ────────────────────────────────── +# Counts and flags only, never a glob, a regex, a rule name or a path. Nothing +# here changes which rules apply. + +# Bits of cr_shapes. +_SHAPE_PLAIN_PATHS = 1 # a `paths` glob with a folder and no leading `*` +_SHAPE_PLAIN_EXCLUDE = 2 # the same in `exclude_paths` +_SHAPE_MID_STARS = 4 # `/**/` inside a glob +_SHAPE_BRACES = 8 # `{a,b}`, which fnmatch takes literally +_SHAPE_LEADING = 16 # starts with `/` or `./` +_SHAPE_REGEX_REFUSED = 32 # a rule dropped by the slow-regex check +_SHAPE_REGEX_COUNTED = 64 # a loaded regex repeats a repeated group by count + +_COUNTED_REPEAT = re.compile(r"\((?:\?:)?[^()\[\]\\]*[+*][^()\[\]\\]*\)\{\d*(?:,\d*)?\}") + + +def _shape_bits(globs: Tuple[str, ...], plain: int) -> int: + bits = 0 + for g in globs: + if not isinstance(g, str): + continue + g = g.replace("\\", "/") + if "/" in g and not g.startswith(("*", "/", "./")): + bits |= plain + if "/**/" in g: + bits |= _SHAPE_MID_STARS + if "{" in g: + bits |= _SHAPE_BRACES + if g.startswith(("/", "./")): + bits |= _SHAPE_LEADING + return bits + + +def _zero_depth_forms(glob: str) -> List[str]: + """`glob`, and the globs left when each `**/` matches no folder.""" + forms = [glob] + for form in forms: + for m in re.finditer(r"(?:^|(?<=/))\*\*/", form): + shorter = form[:m.start()] + form[m.end():] + if shorter and shorter not in forms and len(forms) < 16: + forms.append(shorter) + return forms + + +def _wider_glob_match(path: str, rels: Tuple[str, ...], + include: Tuple[str, ...], exclude: Tuple[str, ...]) -> bool: + """What _glob_match would say if globs were also read against the path + inside the project (`rels`), and `**/` could match no folder.""" + norm = path.replace(os.sep, "/") + names = [norm, norm.lstrip("/"), os.path.basename(norm)] + for rel in rels: + names += [rel, "/" + rel, "./" + rel] + + def _hit(globs: Tuple[str, ...]) -> bool: + return any(fnmatch.fnmatch(n, f) for g in globs + for f in _zero_depth_forms(g) for n in names) + if include and not _hit(include): + return False + if exclude and _hit(exclude): + return False + return True + + +def _inside(root: Optional[str], path: str) -> Optional[str]: + if not root: + return None + try: + rel = os.path.relpath(os.path.realpath(path), os.path.realpath(root)) + except (OSError, ValueError): + return None + if rel == os.pardir or rel.startswith(os.pardir + os.sep): + return None + return rel.replace(os.sep, "/") + + +def edit_stats(file_path: str, cwd: Optional[str], project_dir: Optional[str]) -> Dict[str, int]: + """Counts for one edit; empty for a user with no custom rules. + Telemetry only.""" + stats: Dict[str, int] = {} + shapes = _SHAPE_REGEX_REFUSED if _refused_regexes else 0 + gain = loss = 0 + # From both folders: in a worktree the session's own is the one that fits. + rels = tuple(dict.fromkeys( + r for r in (_inside(d, file_path) for d in (cwd, project_dir)) if r is not None + )) if _user_patterns else () + for rule in _user_patterns: + include, exclude = rule.get("_globs", ((), ())) + if include or exclude: + shapes |= _shape_bits(include, _SHAPE_PLAIN_PATHS) + shapes |= _shape_bits(exclude, _SHAPE_PLAIN_EXCLUDE) + try: + now = _glob_match(file_path.lstrip("/"), include, exclude) + wider = _wider_glob_match(file_path, rels, include, exclude) + except Exception: + continue + gain += wider and not now + loss += now and not wider + if _COUNTED_REPEAT.search(rule.get("regex", "")): + shapes |= _SHAPE_REGEX_COUNTED + if _user_patterns: + stats["cr_rules"] = len(_user_patterns) + if shapes: + stats["cr_shapes"] = shapes + if gain: + stats["cr_gain"] = int(gain) + if loss: + stats["cr_loss"] = int(loss) + return stats + + +# A custom regex that takes at least this long is reported, in seconds. +SLOW_REGEX_S = 0.1 diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 47a992aa..e240fce1 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -228,7 +228,7 @@ _TAIL_METRICS: Dict[str, Any] = {} # Of those, the ones that go after the others whenever they were set: a row # over CC's key cap loses them before any older review key. Only the launcher # keys below come later; those are also on every smaller row of the session. -_LAST_METRIC_KEYS = ("diff_seen",) +_LAST_METRIC_KEYS = ("diff_seen", *diffstate.CUSTOM_RULE_KEYS) # The launcher's slow interpreter probes, if any. After the keys above. _LAUNCHER_METRICS: Dict[str, Any] = launcher_probe_metrics() @@ -679,11 +679,15 @@ def check_patterns(file_path, content): break if not matched and "regex" in pattern and content: + started = time.perf_counter() try: if re.search(pattern["regex"], content): matched = True except Exception: pass + if "_source" in pattern: # a custom rule + extensibility.slowest_regex = max( + extensibility.slowest_regex, time.perf_counter() - started) if matched: matches.append((pattern["ruleName"], pattern["reminder"])) @@ -2596,6 +2600,10 @@ def handle_stop_hook(input_data): if isinstance(snap.get(_k), int) and snap[_k] > 0: _TAIL_METRICS[_k] = snap[_k] + for _k in diffstate.CUSTOM_RULE_KEYS: + if snap.get("custom_rules", {}).get(_k): + _TAIL_METRICS[_k] = snap["custom_rules"][_k] + # Sweep pattern-warning outcomes (pure local work; stop_hook_active is # already guaranteed False here so no double-count guard needed). sweep = {} @@ -3182,7 +3190,15 @@ def main(): if file_path.startswith(plans_dir): sys.exit(0) - record_touched_path(session_id, file_path) + # Telemetry only: how this edit's custom rules are written. + rule_stats = None + if ENABLE_PATTERN_RULES: + try: + rule_stats = extensibility.edit_stats( + file_path, input_data.get("cwd"), os.environ.get("CLAUDE_PROJECT_DIR")) + except Exception as e: + debug_log(f"custom rule stats failed: {e}") + record_touched_path(session_id, file_path, rule_stats) content = extract_content_from_input( tool_name, tool_input, input_data.get("tool_response")) @@ -3208,6 +3224,10 @@ def main(): else: debug_log("All patterns existed in baseline, skipping") + if extensibility.slowest_regex >= extensibility.SLOW_REGEX_S: + diffstate.record_custom_rule_stats( + session_id, {"cr_slow_ms": int(extensibility.slowest_regex * 1000)}) + for rule_name, reminder in pattern_matches: warning_key = f"{file_path}-{rule_name}" if atomic_check_and_mark_warning(session_id, warning_key): diff --git a/plugins/security-guidance/tests/test_custom_rule_stats.py b/plugins/security-guidance/tests/test_custom_rule_stats.py new file mode 100644 index 00000000..9bbc87ce --- /dev/null +++ b/plugins/security-guidance/tests/test_custom_rule_stats.py @@ -0,0 +1,168 @@ +"""Counts about custom rules on the Stop row. They change no rule's outcome.""" +import json +import os + +import pytest + +import extensibility + +from conftest import edit_payload, git, metrics_of, run_hook, stop_payload, ups_payload + +GLOBS = ["*.ts", "**/*.ts", "**/src/**", "**/src/**/*.ts", "src/**", "src/*.ts", "src/**/*.ts", "/src/**", + "./src/**", "src", "*.{ts,js}", "config.ts", "[!t]*.ts", "**/[!t]*.ts", "src/?.ts"] +FILES = ["config.ts", "t.ts", "src/a.ts", "src/t.ts", "src/lib/a.ts", "src/lib/deep/t.ts", "other/a.ts"] + + +@pytest.mark.parametrize("glob", GLOBS) +def test_the_wider_reading_never_loses_an_include(glob, tmp_path): + for f in FILES: + path = str(tmp_path.joinpath(*f.split("/"))) + if extensibility._glob_match(path.lstrip("/"), (glob,), ()): + assert extensibility._wider_glob_match(path, (f,), (glob,), ()) + + +@pytest.mark.parametrize("glob,f,now,wider", [ + ("src/**", "src/a.ts", False, True), + ("src/*.ts", "src/lib/a.ts", False, True), # `*` still crosses `/` + ("src/**/*.ts", "src/a.ts", False, True), + ("**/src/**/*.ts", "src/a.ts", False, True), + ("**/src/**/*.ts", "src/lib/a.ts", True, True), + ("/src/**", "src/a.ts", False, True), + ("*.ts", "src/lib/deep/t.ts", True, True), + ("src/**", "other/a.ts", False, False), + ("*.{ts,js}", "config.ts", False, False), +]) +def test_readings(glob, f, now, wider, tmp_path): + path = str(tmp_path.joinpath(*f.split("/"))) + assert extensibility._glob_match(path.lstrip("/"), (glob,), ()) is now + assert extensibility._wider_glob_match(path, (f,), (glob,), ()) is wider + + +def _rules(repo, *rules, name="security-patterns.json"): + (repo / ".claude").mkdir(exist_ok=True) + (repo / ".claude" / name).write_text(json.dumps({"patterns": [ + dict({"rule_name": f"r{i}", "substrings": ["NEEDLE("], "reminder": "x"}, **r) + for i, r in enumerate(rules)]})) + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "rules") + + +def _stats(repo, env, files, cwd=None): + env = {**env, "CLAUDE_PROJECT_DIR": str(repo)} + run_hook(ups_payload(repo), env) + outs = [] + for name in files: + p = repo / name + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text("NEEDLE(1)\n") + outs.append(run_hook(edit_payload(cwd or repo, p, "NEEDLE(1)\n"), env)[1]) + m = metrics_of(run_hook(stop_payload(repo), env)[1]) + return {k: v for k, v in m.items() if k.startswith("cr_")}, outs + + +def test_rules_that_would_start_to_apply(env, workspace): + _, repo = workspace + _rules(repo, {"paths": ["src/**"]}, {"paths": ["*.ts"]}) + stats, outs = _stats(repo, env, ["src/a.ts", "src/b.ts"]) + assert stats == {"cr_rules": 2, "cr_shapes": 1, "cr_gain": 2} + # The rule that does not apply today still does not. + assert all("additionalContext" in o for o in outs) + + +def test_excludes_that_would_start_to_apply(env, workspace): + _, repo = workspace + _rules(repo, {"exclude_paths": ["src/**"]}) + stats, outs = _stats(repo, env, ["src/a.ts"]) + assert stats == {"cr_rules": 1, "cr_shapes": 2, "cr_loss": 1} + assert "additionalContext" in outs[0] + + +def test_no_extra_save_of_the_state(env, workspace, monkeypatch, tmp_path): + import diffstate + import session_state + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "st")) + saves = [] + real = session_state.save_state + monkeypatch.setattr(session_state, "save_state", lambda *a: saves.append(a) or real(*a)) + diffstate.record_touched_path("s9", "/a.ts", {"cr_rules": 1, "cr_gain": 1}) + assert len(saves) == 1 + assert saves[0][1]["custom_rules"] == {"cr_rules": 1, "cr_gain": 1} + assert saves[0][1]["touched_paths"] == ["/a.ts"] + + +def test_worktree_outside_the_project(env, workspace, tmp_path): + _, repo = workspace + _rules(repo, {"paths": ["src/**"]}) + tree = tmp_path / "tree" + git(repo, "worktree", "add", "-q", "-b", "side", str(tree)) + extensibility.load_for_session(str(tree)) + stats = extensibility.edit_stats(str(tree / "src" / "a.ts"), str(tree), str(repo)) + assert stats["cr_gain"] == 1 + + +def test_they_come_after_the_review_keys(env, workspace): + _, repo = workspace + _rules(repo, {"paths": ["src/**"]}) + e = {**env, "CLAUDE_PROJECT_DIR": str(repo)} + run_hook(ups_payload(repo), e) + run_hook(edit_payload(repo, repo / "src" / "a.ts", "NEEDLE("), e) + keys = list(metrics_of(run_hook(stop_payload(repo), e)[1])) + assert "cr_rules" in keys + first = min(i for i, k in enumerate(keys) if k.startswith("cr_")) + assert not [k for k in keys[first:] if not k.startswith(("cr_", "launcher"))] + + +@pytest.mark.parametrize("rule,bits", [ + ({"paths": ["**/src/**/*.ts"]}, 4), + ({"paths": ["*.{ts,js}"]}, 8), + ({"paths": ["/src/**"]}, 16), + ({"regex": "(a+)+$"}, 32), + ({"regex": "(a+){2,}$"}, 64), + ({"regex": "(a+){20}$"}, 64), + ({"regex": "([A-Za-z0-9+/]{4}){10,}"}, 0), +]) +def test_shapes(rule, bits, env, workspace): + _, repo = workspace + _rules(repo, rule) + stats, _ = _stats(repo, env, ["other/a.ts"]) + assert stats.get("cr_shapes", 0) == bits + + +def test_a_slow_regex_is_timed(env, workspace): + _, repo = workspace + _rules(repo, {"substrings": [], "regex": "(a+){2,}$"}) + env = {**env, "CLAUDE_PROJECT_DIR": str(repo)} + run_hook(ups_payload(repo), env) + run_hook(edit_payload(repo, repo / "n.txt", "a" * 23 + "!"), env) + m = metrics_of(run_hook(stop_payload(repo), env)[1]) + assert m["cr_slow_ms"] >= 100 + + +def test_no_custom_rules_no_keys(env, workspace): + _, repo = workspace + assert _stats(repo, env, ["src/a.ts"])[0] == {} + + +def test_reported_once(env, workspace): + _, repo = workspace + _rules(repo, {"paths": ["src/**"]}) + assert _stats(repo, env, ["src/a.ts"])[0] + m = metrics_of(run_hook(stop_payload(repo), env)[1]) + assert not [k for k in m if k.startswith("cr_")] + + +def test_a_subagent_stop_leaves_them_for_the_turn(env, workspace): + _, repo = workspace + _rules(repo, {"paths": ["src/**"]}) + e = {**env, "CLAUDE_PROJECT_DIR": str(repo)} + run_hook(ups_payload(repo), e) + run_hook(edit_payload(repo, repo / "src" / "a.ts", "NEEDLE("), e) + run_hook(stop_payload(repo, event="SubagentStop"), e) + m = metrics_of(run_hook(stop_payload(repo), e)[1]) + assert m["cr_gain"] == 1 + + +def test_wrong_kind_in_state_does_not_break_the_hook(env, workspace): + _, repo = workspace + _rules(repo, {"paths": [5]}, {"paths": ["src/**"]}) + assert _stats(repo, env, ["src/a.ts"])[0]["cr_rules"] == 2 -- cgit From 8b45f783efb8cc363cc4c7d90616c3608b531d91 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 9 Nov 2026 19:39:40 +0000 Subject: security-guidance: keep the user's own rules out of the custom rule tests Co-authored-by: mhegazy --- plugins/security-guidance/tests/test_custom_rule_stats.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'plugins') diff --git a/plugins/security-guidance/tests/test_custom_rule_stats.py b/plugins/security-guidance/tests/test_custom_rule_stats.py index 9bbc87ce..fcad3130 100644 --- a/plugins/security-guidance/tests/test_custom_rule_stats.py +++ b/plugins/security-guidance/tests/test_custom_rule_stats.py @@ -13,6 +13,18 @@ GLOBS = ["*.ts", "**/*.ts", "**/src/**", "**/src/**/*.ts", "src/**", "src/*.ts", FILES = ["config.ts", "t.ts", "src/a.ts", "src/t.ts", "src/lib/a.ts", "src/lib/deep/t.ts", "other/a.ts"] +@pytest.fixture(autouse=True) +def _home_without_user_rules(tmp_path, monkeypatch): + """A home directory without the user's own rules and guidance.""" + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + monkeypatch.setattr(extensibility, "_guidance_block", "") + monkeypatch.setattr(extensibility, "_user_patterns", []) + + @pytest.mark.parametrize("glob", GLOBS) def test_the_wider_reading_never_loses_an_include(glob, tmp_path): for f in FILES: -- cgit From cb66958137ed012ea742103e560738107ff53002 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Fri, 6 Nov 2026 17:49:51 +0000 Subject: security-guidance: tests read the session state file by name The test helper opened the first JSON file in the state directory, which can be the review model cache depending on directory order. Select the session state file by its prefix and require exactly one. Co-authored-by: mhegazy --- plugins/security-guidance/tests/test_repo_resolution.py | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) (limited to 'plugins') diff --git a/plugins/security-guidance/tests/test_repo_resolution.py b/plugins/security-guidance/tests/test_repo_resolution.py index 30c94a7c..bd1840f4 100644 --- a/plugins/security-guidance/tests/test_repo_resolution.py +++ b/plugins/security-guidance/tests/test_repo_resolution.py @@ -261,20 +261,15 @@ class TestHooksJson: def _read_state(env): + # The review model cache is JSON in this directory too. d = env["SECURITY_WARNINGS_STATE_DIR"] - files = [e.path for e in os.scandir(d) if e.name.endswith(".json")] - assert files, os.listdir(d) + files = [e.path for e in os.scandir(d) + if e.name.startswith("security_warnings_state_") and e.name.endswith(".json")] + assert len(files) == 1, os.listdir(d) with open(files[0]) as f: return json.load(f) -def _read_state_or_empty(env): - d = env["SECURITY_WARNINGS_STATE_DIR"] - if not any(e.name.endswith(".json") for e in os.scandir(d)): - return {} - return _read_state(env) - - class TestCommitReview: def test_cwd_is_repo_unchanged(self, workspace, hook_env, stub_api): ws, repo = workspace @@ -334,7 +329,7 @@ class TestCommitReview: m = metrics_of(so) assert m.get("skip_reason") is None, m assert m["repo_resolution"] == rr.RES_SHA_SCAN and m["files_reviewed"] == 1 - assert "repo_root_hint" not in _read_state_or_empty(hook_env) + assert "repo_root_hint" not in _read_state(hook_env) def test_workspace_cwd_sha_scan_via_project_dir(self, workspace, hook_env, tmp_path): ws, repo = workspace @@ -429,7 +424,7 @@ class TestPushSweep: m = metrics_of(so) assert m["push_sweep"] is True and m["repo_resolution"] == rr.RES_SHA_SCAN, m assert m.get("skip_reason") != 26 - assert "repo_root_hint" not in _read_state_or_empty(hook_env) + assert "repo_root_hint" not in _read_state(hook_env) def test_cwd_is_repo_dash_C_other_repo(self, workspace, hook_env, tmp_path): ws, repo = workspace -- cgit From 9ea2fbca5b6c62113e011a8f183bb336a26f9883 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 9 Nov 2026 19:39:42 +0000 Subject: security-guidance: keep the user's own rules out of the commit count tests Co-authored-by: mhegazy --- plugins/security-guidance/tests/test_turn_commits_metric.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'plugins') diff --git a/plugins/security-guidance/tests/test_turn_commits_metric.py b/plugins/security-guidance/tests/test_turn_commits_metric.py index fd74b082..cf3dc99a 100644 --- a/plugins/security-guidance/tests/test_turn_commits_metric.py +++ b/plugins/security-guidance/tests/test_turn_commits_metric.py @@ -25,6 +25,16 @@ def _session_id_from_the_payload(monkeypatch): monkeypatch.delenv("CLAUDE_CODE_REMOTE_SESSION_ID", raising=False) +@pytest.fixture(autouse=True) +def _home_without_user_rules(tmp_path, monkeypatch): + """A home directory without the user's own rules, whose keys could fill the row.""" + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + + def session_state_file(hook_env): [path] = [p for p in Path(hook_env["SECURITY_WARNINGS_STATE_DIR"]).glob("security_warnings_state_*.json")] return path @@ -358,7 +368,6 @@ def test_parts_are_capped(tmp_path, monkeypatch): def test_old_commit_records_are_removed(tmp_path, monkeypatch): monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path)) - monkeypatch.setenv("HOME", str(tmp_path)) diffstate.note_seen_commits("s1", ["abc1234"]) diffstate.note_seen_commits("s2", ["abc1234"]) os.utime(session_state.get_commit_log_file("s1"), (1, 1)) -- cgit