summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-11-09 17:01:31 -0800
committerGitHub <noreply@github.com>2026-11-09 17:01:31 -0800
commit57f78907595aee8408ab919e915eb9a5b10b4098 (patch)
treefadbc10d655fb79c363f3a398b87c74d57866fa5 /plugins
parentc929527f39e8c9ea64bd168a5e9a098476d49475 (diff)
parent4708b6fd9a96ca6124b297209f16c98b0176d5d4 (diff)
Merge pull request #7032 from anthropics/mhegazy/sg-refused-verdict-count
security-guidance: count reviewer verdicts the CLI refused
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/llm.py24
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py12
-rw-r--r--plugins/security-guidance/tests/test_reviewer_context_metrics.py73
3 files changed, 104 insertions, 5 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py
index 9b542c4f..6f8c68e2 100644
--- a/plugins/security-guidance/hooks/llm.py
+++ b/plugins/security-guidance/hooks/llm.py
@@ -2091,6 +2091,14 @@ def _agentic_spawn_env() -> Dict[str, str]:
_REVIEWER_FILE_TOOLS = ("Read", "Grep", "Glob")
+def _is_wrapped_verdict(value: Any) -> bool:
+ """True for a verdict nested inside its own list key:
+ {"findings": {"findings": [...]}}."""
+ return isinstance(value, dict) and any(
+ isinstance(inner, dict) and isinstance(inner.get(key), list)
+ for key, inner in value.items())
+
+
def _agentic_context_dir(repo_dir: str) -> str:
"""The directory the agentic reviewer runs in."""
return os.environ.get("SG_AGENTIC_CONTEXT_DIR") or repo_dir
@@ -2106,6 +2114,9 @@ def agentic_review(
before the review, 2 = it went missing during it
rv_tool_err Read/Grep/Glob calls that came back as errors
rv_tool_calls Read/Grep/Glob calls made
+ rv_so_err verdicts the CLI refused, e.g. for breaking the schema
+ rv_so_wrapped of those, verdicts wrapped in their own key, as in
+ {"findings": {"findings": [...]}}
rv_turns turns the reviewer took, as the CLI counts them
rv_api_ms time the reviewer spent waiting on the model, in ms
@@ -2114,7 +2125,8 @@ def agentic_review(
that ends without one (the CLI exits early) adds nothing to them."""
context_dir = _agentic_context_dir(repo_dir)
gone = 0 if os.path.isdir(context_dir) else 1
- ctx = {"rv_tool_err": 0, "rv_tool_calls": 0, "rv_turns": 0, "rv_api_ms": 0}
+ ctx = {"rv_tool_err": 0, "rv_tool_calls": 0, "rv_turns": 0, "rv_api_ms": 0,
+ "rv_so_err": 0, "rv_so_wrapped": 0}
guidance, vulns, metrics = _agentic_review(repo_dir, diff_files, touched_paths, ctx)
if not gone and not os.path.isdir(context_dir):
gone = 2
@@ -2318,6 +2330,8 @@ def _agentic_review(
# Blocks are matched by shape so older SDK builds need no extra import.
file_tool_ids = set()
+ # StructuredOutput call id -> whether its verdict was wrapped.
+ verdicts: Dict[str, bool] = {}
auth_retries = 0
# Closed on the way out, also on a raise, so the CLI stops with the review.
async with contextlib.aclosing(query(prompt=_once(), options=opts)) as messages:
@@ -2334,6 +2348,9 @@ def _agentic_review(
and getattr(b, "id", None)):
file_tool_ids.add(b.id)
ctx["rv_tool_calls"] += 1
+ elif (getattr(b, "name", None) == "StructuredOutput"
+ and getattr(b, "id", None)):
+ verdicts[b.id] = _is_wrapped_verdict(getattr(b, "input", None))
elif isinstance(msg, ResultMessage):
subtype = msg.subtype
if msg.structured_output is not None:
@@ -2366,6 +2383,11 @@ def _agentic_review(
if getattr(b, "is_error", None) is True
and getattr(b, "tool_use_id", None) in file_tool_ids
)
+ for b in content:
+ wrapped = verdicts.get(getattr(b, "tool_use_id", None))
+ if wrapped is not None and getattr(b, "is_error", None) is True:
+ ctx["rv_so_err"] += 1
+ ctx["rv_so_wrapped"] += wrapped
return structured, n, subtype
def _run(system: str, prompt: str, *, schema: Dict[str, Any]
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 53a25583..b02dcab7 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -288,11 +288,20 @@ _EFFORT_TURNS_UNIT = 10_000_000
_REVIEWER_EFFORT_METRICS: Dict[str, Any] = {}
+# Verdicts the reviewer's CLI refused, and how many of them were wrapped in
+# their own key, sent as one number: refused * 100 + wrapped (both capped).
+_REVIEWER_VERDICT_KEYS = ("rv_so_err", "rv_so_wrapped")
+
+
def _note_reviewer_context(agentic_metrics):
"""Queue the agentic reviewer's context and effort diagnostics for this row."""
for key in _REVIEWER_CONTEXT_KEYS:
if agentic_metrics.get(key):
_TAIL_METRICS[key] = agentic_metrics[key]
+ refused, wrapped = (min(agentic_metrics.get(k) or 0, 99) for k in _REVIEWER_VERDICT_KEYS)
+ if refused:
+ # On a row at the key cap this costs that row its rv_effort.
+ _TAIL_METRICS["rv_so"] = refused * 100 + wrapped
turns = agentic_metrics.get("rv_turns") or 0
api_ms = agentic_metrics.get("rv_api_ms") or 0
if turns or api_ms:
@@ -1553,7 +1562,8 @@ def _agentic_review_with_race(
# What the agentic run saw of its directory, and how much work it did,
# is kept when the fallback's result replaces it below.
reviewer_context = (
- {k: m[k] for k in _REVIEWER_CONTEXT_KEYS + _REVIEWER_EFFORT_KEYS if k in m}
+ {k: m[k] for k in (_REVIEWER_CONTEXT_KEYS + _REVIEWER_VERDICT_KEYS
+ + _REVIEWER_EFFORT_KEYS) if k in m}
if winner == "agentic" else {}
)
if winner == "agentic" and m.get("agentic_fallback") and fallback_started.is_set():
diff --git a/plugins/security-guidance/tests/test_reviewer_context_metrics.py b/plugins/security-guidance/tests/test_reviewer_context_metrics.py
index 99e94dc7..4c0bcf43 100644
--- a/plugins/security-guidance/tests/test_reviewer_context_metrics.py
+++ b/plugins/security-guidance/tests/test_reviewer_context_metrics.py
@@ -14,8 +14,8 @@ import security_reminder_hook as hook
class _ToolUse:
- def __init__(self, id, name):
- self.id, self.name, self.input = id, name, {}
+ def __init__(self, id, name, input=None):
+ self.id, self.name, self.input = id, name, {} if input is None else input
class _ToolResult:
@@ -102,6 +102,44 @@ class TestAgenticReview:
m = _review(tmp_path)
assert "rv_tool_calls" not in m and "rv_tool_err" not in m
+ @pytest.mark.parametrize("verdict, wrapped", [
+ ({"findings": {"findings": []}}, 1),
+ ({"findings": {"findings": [{"filePath": "a.py"}]}}, 1),
+ ({"survived": {"survived": [0]}}, 1),
+ ({"findings": {}}, 0), ({"findings": None}, 0), ({"findings": "none"}, 0),
+ ({"findings": {"filePath": "a.py"}}, 0), ({"findings": {"findings": None}}, 0),
+ ({}, 0), (None, 0), ("[]", 0), ([], 0),
+ ])
+ def test_refused_verdict_is_counted_with_its_shape(self, sdk, tmp_path, verdict, wrapped):
+ call = _ToolUse("t1", "StructuredOutput")
+ call.input = verdict
+ sdk.messages = [sdk.assistant(call), sdk.user([_ToolResult("t1", is_error=True)])]
+ m = _review(tmp_path)
+ assert (m["rv_so_err"], m.get("rv_so_wrapped", 0)) == (1, wrapped)
+
+ def test_accepted_verdict_and_other_errors_are_not_counted(self, sdk, tmp_path):
+ sdk.messages = [
+ sdk.assistant(_ToolUse("t1", "StructuredOutput", {"findings": {"findings": []}}),
+ _ToolUse("t2", "Read")),
+ sdk.user([_ToolResult("t1", is_error=False), _ToolResult("t2", is_error=True),
+ _ToolResult("t9", is_error=True)]),
+ ]
+ m = _review(tmp_path)
+ assert "rv_so_err" not in m and "rv_so_wrapped" not in m
+
+ def test_refused_verdicts_are_counted_when_the_review_ends_without_one(
+ self, sdk, tmp_path, monkeypatch):
+ async def query(prompt, options):
+ for i in range(5):
+ yield sdk.assistant(_ToolUse(f"t{i}", "StructuredOutput", {"findings": {"findings": []}}))
+ yield sdk.user([_ToolResult(f"t{i}", is_error=True)])
+ raise RuntimeError("Failed to provide valid structured output after 5 attempts")
+
+ monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query)
+ m = _review(tmp_path)
+ assert m["agentic_fallback"].startswith("investigate:")
+ assert (m["rv_so_err"], m["rv_so_wrapped"]) == (5, 5)
+
def test_directory_missing_before_the_review(self, sdk, tmp_path):
m = _review(tmp_path / "removed")
assert m["agentic_fallback"].startswith("investigate:")
@@ -179,6 +217,21 @@ class TestEmittedRow:
keys = list(self._row(capsys))
assert keys[-5:] == ["vulns_found", "review_ms", "rv_cwd_gone", "rv_tool_err", "rv_tool_calls"]
+ @pytest.mark.parametrize("metrics, sent", [
+ ({"rv_so_err": 1, "rv_so_wrapped": 1}, 101),
+ ({"rv_so_err": 3}, 300),
+ ({"rv_so_err": 250, "rv_so_wrapped": 120}, 9999),
+ ({"rv_so_err": 0, "rv_so_wrapped": 0}, None),
+ ({}, None),
+ ])
+ def test_refused_verdicts_are_one_key(self, capsys, metrics, sent):
+ hook._note_reviewer_context({"rv_tool_calls": 2, "rv_turns": 3, "rv_api_ms": 9, **metrics})
+ hook.emit_metrics({"vulns_found": 0})
+ row = self._row(capsys)
+ assert row.get("rv_so") == sent
+ assert list(row)[-1] == "rv_effort"
+ assert "rv_so_err" not in row and "rv_so_wrapped" not in row
+
def test_effort_is_one_key_after_every_other_key(self, capsys, monkeypatch):
monkeypatch.setattr(hook, "_LAUNCHER_METRICS", {"launcher_probe_ms": 7000})
hook._note_reviewer_context({"rv_api_ms": 9100, "rv_turns": 5, "rv_tool_calls": 4})
@@ -223,6 +276,19 @@ class TestEmittedRow:
keys = list(self._row(capsys))
assert keys[-2:] == ["rv_tool_calls", "rv_effort"] and len(keys) <= 20
+ def test_refused_verdicts_fit_under_the_cap_on_a_clean_commit_review_row(self, capsys, monkeypatch):
+ """They take the place rv_effort has on such a row."""
+ monkeypatch.setattr(hook, "_usage_metrics", lambda: {
+ "tok_in": 1, "tok_out": 1, "tok_cache_r": 0, "tok_cache_w": 0, "cost_usd": 0.1, "api_calls": 1})
+ hook._note_reviewer_context({"rv_tool_calls": 2, "rv_so_err": 1, "rv_so_wrapped": 1,
+ "rv_turns": 3, "rv_api_ms": 9100})
+ hook.emit_metrics({
+ "vulns_found": 0, "commit_review": True, "commit_review_on": True,
+ "sha_via_reflog": True, "reflog_shas_n": 1, "rate_count": 1, "agentic": True,
+ "candidates": 0, "race_winner": 1, "files_reviewed": 1, "review_ms": 9500,
+ })
+ assert "rv_so" in list(self._row(capsys))[:20]
+
def test_zero_or_absent_keys_are_left_out(self, capsys):
hook._note_reviewer_context({"rv_tool_calls": 3, "rv_tool_err": 0})
hook.emit_metrics({"vulns_found": 0})
@@ -246,7 +312,7 @@ class TestRace:
time.sleep(0.3) # fails after the fallback has started
return None, [], {"agentic_fallback": "investigate:RuntimeError",
"rv_cwd_gone": 2, "rv_tool_err": 4, "rv_tool_calls": 5,
- "rv_turns": 18, "rv_api_ms": 60000}
+ "rv_so_err": 5, "rv_so_wrapped": 4, "rv_turns": 18, "rv_api_ms": 60000}
monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0")
monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False)
@@ -262,3 +328,4 @@ class TestRace:
assert m["race_winner"] == 2 and m["agentic"] is False
assert (m["rv_cwd_gone"], m["rv_tool_err"], m["rv_tool_calls"]) == (2, 4, 5)
assert (m["rv_turns"], m["rv_api_ms"]) == (18, 60000)
+ assert (m["rv_so_err"], m["rv_so_wrapped"]) == (5, 4)