diff options
| author | Claude <noreply@anthropic.com> | 2026-11-10 02:52:01 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-10 02:52:01 +0000 |
| commit | fa2face5178e7c20f8d0195728056d8bdad82c2f (patch) | |
| tree | d03e5df0e15d67840cab48afd7cb449b8045a563 /plugins | |
| parent | dceb15d50832e6adf380bedc26dde03d251324b9 (diff) | |
security-guidance: pack the custom rule counts into one telemetry keymhegazy/sg-pack-custom-rule-counts
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
4 files changed, 75 insertions, 15 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index 2dac1208..6df7a5c6 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -83,9 +83,31 @@ def record_touched_path(session_id, file_path, custom_rule_stats=None): 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") +# A full Stop row lost these and the turn's commit count, so they travel as +# one decimal number, each field capped to its digits: +# rules (2) shapes (3) gain (3) loss (3) slow_ms (4) +# 15 digits at most, well inside what a JSON number holds exactly. +_CUSTOM_RULE_PACK = (("cr_rules", 99), ("cr_shapes", 999), ("cr_gain", 999), + ("cr_loss", 999), ("cr_slow_ms", 9999)) + + +# Kept in the state per turn. See extensibility.edit_stats. cr_rules, cr_shapes +# and cr_slow_ms are maximum or union over the turn's edits, the others are +# added up. +CUSTOM_RULE_KEYS = tuple(key for key, _ in _CUSTOM_RULE_PACK) + + +def custom_rule_pack(kept): + """The turn's custom rule counts as one number; 0 when there are none.""" + if not isinstance(kept, dict): + return 0 + value = 0 + for key, cap in _CUSTOM_RULE_PACK: + part = kept.get(key, 0) + if not isinstance(part, int) or isinstance(part, bool) or part < 0: + part = 0 + value = value * (10 ** len(str(cap))) + min(part, cap) + return value def _fold_custom_rule_stats(state, stats): diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index b02dcab7..6647e92a 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -259,7 +259,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", *diffstate.CUSTOM_RULE_KEYS) +_LAST_METRIC_KEYS = ("diff_seen", "cr_pack") # CC keeps this many keys of a row. _METRIC_KEY_CAP = 20 @@ -2675,7 +2675,7 @@ def handle_stop_hook(input_data): # paths the concurrent active=False fire needs. if stop_hook_active: debug_log("Stop hook: stop_hook_active=True, skipping to avoid recursion") - emit_metrics({"skipped": True, "skip_reason": 1, "diff_strategy_v2": True}) + emit_metrics({"skipped": True, "skip_reason": 1}) sys.exit(0) # Snapshot all state under one lock BEFORE any slow work (sweep file I/O, @@ -2701,9 +2701,9 @@ 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] + _cr_pack = diffstate.custom_rule_pack(snap.get("custom_rules")) + if _cr_pack: + _TAIL_METRICS["cr_pack"] = _cr_pack # Sweep pattern-warning outcomes (pure local work; stop_hook_active is # already guaranteed False here so no double-count guard needed). @@ -2757,7 +2757,6 @@ def handle_stop_hook(input_data): # diagnostics survive when extra adds touched_paths_count + ip_* keys. emit_metrics({ "skipped": True, "skip_reason": reason, "fire_index": fire_count + 1, - "diff_strategy_v2": True, **v2_metrics, **extra, **sweep, **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} if gitutil._unparsed_diff_headers else {}), @@ -3087,7 +3086,6 @@ def handle_stop_hook(input_data): emit_metrics({ "vulns_found": len(vulns), "untracked_baseline_n": len(untracked_at_baseline), - "diff_strategy_v2": True, "critical_count": sev["critical"], "high_count": sev["high"], "files_reviewed": len(diff_files), @@ -3128,7 +3126,6 @@ def handle_stop_hook(input_data): emit_metrics({ **({"review_failed": True} if stop_review_failed else {}), "vulns_found": 0, - "diff_strategy_v2": True, "files_reviewed": len(diff_files), "touched_paths_count": len(touched_paths), "review_ms": review_ms, diff --git a/plugins/security-guidance/tests/test_custom_rule_stats.py b/plugins/security-guidance/tests/test_custom_rule_stats.py index fcad3130..b48b9ba8 100644 --- a/plugins/security-guidance/tests/test_custom_rule_stats.py +++ b/plugins/security-guidance/tests/test_custom_rule_stats.py @@ -4,6 +4,7 @@ import os import pytest +import diffstate import extensibility from conftest import edit_payload, git, metrics_of, run_hook, stop_payload, ups_payload @@ -59,6 +60,14 @@ def _rules(repo, *rules, name="security-patterns.json"): git(repo, "commit", "-q", "-m", "rules") +def _unpack(metrics): + """The custom rule counts on a Stop row, by name; zeros left out.""" + digits = f"{metrics.get('cr_pack', 0):015d}" + fields = (("cr_rules", digits[:2]), ("cr_shapes", digits[2:5]), ("cr_gain", digits[5:8]), + ("cr_loss", digits[8:11]), ("cr_slow_ms", digits[11:])) + return {k: int(v) for k, v in fields if int(v)} + + def _stats(repo, env, files, cwd=None): env = {**env, "CLAUDE_PROJECT_DIR": str(repo)} run_hook(ups_payload(repo), env) @@ -69,7 +78,8 @@ def _stats(repo, env, files, cwd=None): 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 + assert not [k for k in m if k.startswith("cr_") and k != "cr_pack"] + return _unpack(m), outs def test_rules_that_would_start_to_apply(env, workspace): @@ -119,7 +129,7 @@ def test_they_come_after_the_review_keys(env, workspace): 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 + assert "cr_pack" 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"))] @@ -147,7 +157,7 @@ def test_a_slow_regex_is_timed(env, workspace): 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 + assert _unpack(m)["cr_slow_ms"] >= 100 def test_no_custom_rules_no_keys(env, workspace): @@ -171,10 +181,26 @@ def test_a_subagent_stop_leaves_them_for_the_turn(env, workspace): 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 + assert _unpack(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 + + +def test_pack_layout_and_caps(): + assert diffstate.custom_rule_pack( + {"cr_rules": 2, "cr_shapes": 65, "cr_gain": 7, "cr_loss": 3, "cr_slow_ms": 450} + ) == 2_065_007_003_0450 + biggest = diffstate.custom_rule_pack( + {"cr_rules": 500, "cr_shapes": 5000, "cr_gain": 5000, "cr_loss": 5000, "cr_slow_ms": 99999}) + assert biggest == 10 ** 15 - 1 and biggest < 2 ** 53 + assert _unpack({"cr_pack": biggest}) == { + "cr_rules": 99, "cr_shapes": 999, "cr_gain": 999, "cr_loss": 999, "cr_slow_ms": 9999} + + +@pytest.mark.parametrize("kept", [None, [], "x", {}, {"cr_rules": "2"}, {"cr_gain": -1}, {"cr_gain": True}]) +def test_pack_of_nothing_usable_is_zero(kept): + assert diffstate.custom_rule_pack(kept) == 0 diff --git a/plugins/security-guidance/tests/test_turn_commits_metric.py b/plugins/security-guidance/tests/test_turn_commits_metric.py index cf3dc99a..2aafd634 100644 --- a/plugins/security-guidance/tests/test_turn_commits_metric.py +++ b/plugins/security-guidance/tests/test_turn_commits_metric.py @@ -64,6 +64,21 @@ class TestStopRow: assert m["turn_commits"] == 10101 assert m["files_reviewed"] == 1 + def test_custom_rule_counts_take_one_place(self, repo, stop, hook_env, stub_api): + (repo / ".claude").mkdir() + (repo / ".claude" / "security-patterns.json").write_text(json.dumps({"patterns": [ + {"rule_name": "r1", "substrings": ["NEEDLE("], "reminder": "x", "paths": ["src/**"]}, + {"rule_name": "r2", "substrings": ["NEEDLE("], "reminder": "x", "exclude_paths": ["src/**"]}, + ]})) + (repo / "src").mkdir() + (repo / "src" / "a.ts").write_text("NEEDLE(1)\n") + env = {**hook_env, "CLAUDE_PROJECT_DIR": str(repo)} + run_hook(edit_payload(repo, repo / "src" / "a.ts", "NEEDLE(1)\n"), env) + commit_file(repo, "a.py", "print('a')\n") + m = stop(repo, CLAUDE_PROJECT_DIR=str(repo)) + assert [k for k in m if k.startswith("cr_")] == ["cr_pack"] + assert "turn_commits" in m + def test_commit_the_hook_reviewed(self, repo, stop, hook_env): _, out = commit_file(repo, "a.py", "print('a')\n") run_hook(bash_payload(repo, "git commit -m change", out), hook_env) |
