diff options
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 53 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 19 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_reviewer_context_metrics.py | 178 |
3 files changed, 247 insertions, 3 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 3f7607c6..21279426 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -1452,13 +1452,46 @@ def _agentic_spawn_env() -> Dict[str, str]: return env +# The tools the agentic reviewer is given to look around the repo. +_REVIEWER_FILE_TOOLS = ("Read", "Grep", "Glob") + + +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 + + def agentic_review( repo_dir: str, diff_files: List[Tuple[str, str]], touched_paths: List[str], ) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: + """Run the two-stage agentic review (_agentic_review) and add reviewer + context diagnostics to its metrics. Counts only, no paths: + + rv_cwd_gone 1 = the directory the reviewer runs in was missing + 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 + + The counts cover all stages of the review. Keys are left out when 0.""" + 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} + guidance, vulns, metrics = _agentic_review(repo_dir, diff_files, touched_paths, ctx) + if not gone and not os.path.isdir(context_dir): + gone = 2 + ctx_m = {"rv_cwd_gone": gone, **ctx} + return guidance, vulns, {**metrics, **{k: v for k, v in ctx_m.items() if v}} + + +def _agentic_review( + repo_dir: str, diff_files: List[Tuple[str, str]], touched_paths: List[str], + ctx: Dict[str, int], +) -> Tuple[Optional[str], List[Dict[str, Any]], Dict[str, Any]]: """Two-stage Agent-SDK review: investigate (Read/Grep/Glob over the repo) then a self-refute filter pass. Returns (guidance_or_None, vulns, metrics). On SDK unavailability returns (None, [], {"agentic_fallback": - reason}) so the caller can fall back to the single-shot path.""" + reason}) so the caller can fall back to the single-shot path. Adds to + the `ctx` counters (see agentic_review) as the reviewer makes tool calls.""" import time as _t # Note: do NOT pop ANTHROPIC_AUTH_TOKEN from os.environ here. The race @@ -1510,7 +1543,7 @@ def agentic_review( # eval harness it's a temp dir with ONLY touched_paths — the agent can't # trace cross-file data flow. The harness sets SG_AGENTIC_CONTEXT_DIR to a # full repo (worktree at the commit, or the live clone at HEAD). - context_dir = os.environ.get("SG_AGENTIC_CONTEXT_DIR") or repo_dir + context_dir = _agentic_context_dir(repo_dir) context_note = "" if context_dir != repo_dir: context_note = ( @@ -1675,9 +1708,16 @@ def agentic_review( yield {"type": "user", "message": {"role": "user", "content": prompt}} + # Blocks are matched by shape so older SDK builds need no extra import. + file_tool_ids = set() async for msg in query(prompt=_once(), options=opts): if isinstance(msg, AssistantMessage): n += 1 + for b in getattr(msg, "content", None) or []: + if (getattr(b, "name", None) in _REVIEWER_FILE_TOOLS + and getattr(b, "id", None)): + file_tool_ids.add(b.id) + ctx["rv_tool_calls"] += 1 elif isinstance(msg, ResultMessage): subtype = msg.subtype if msg.structured_output is not None: @@ -1687,6 +1727,15 @@ def agentic_review( # the price-table estimate. getattr guards older SDK builds. _record_usage(getattr(msg, "usage", None) or {}, model, cost_usd=getattr(msg, "total_cost_usd", None)) + else: + # Tool results come back as user messages. + content = getattr(msg, "content", None) + if isinstance(content, list): + ctx["rv_tool_err"] += sum( + 1 for b in content + if getattr(b, "is_error", None) is True + and getattr(b, "tool_use_id", None) in file_tool_ids + ) 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 3608ec1d..49bef273 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -202,6 +202,16 @@ CONTINUATION_SUFFIX = ( # Extra keys emit_metrics appends to every row this invocation emits. _TAIL_METRICS: Dict[str, Any] = {} +# Reviewer context diagnostics from llm.agentic_review, most useful first. +_REVIEWER_CONTEXT_KEYS = ("rv_cwd_gone", "rv_tool_err", "rv_tool_calls") + + +def _note_reviewer_context(agentic_metrics): + """Queue the agentic reviewer's context diagnostics for this row.""" + for key in _REVIEWER_CONTEXT_KEYS: + if agentic_metrics.get(key): + _TAIL_METRICS[key] = agentic_metrics[key] + def emit_metrics( metrics, @@ -1056,6 +1066,11 @@ def _agentic_review_with_race( _th.Thread(target=_fallback, daemon=True).start() winner, (g, v, m) = q.get() + # What the agentic run saw of its directory is kept when the fallback's + # result replaces it below. + reviewer_context = ( + {k: m[k] for k in _REVIEWER_CONTEXT_KEYS if k in m} if winner == "agentic" else {} + ) if winner == "agentic" and m.get("agentic_fallback") and fallback_started.is_set(): # The caller would rerun the single-shot review the fallback has # already started; use its result instead. @@ -1064,7 +1079,7 @@ def _agentic_review_with_race( else: winner, (g, v, m) = "fallback", (None, [], { "agentic": False, "review_failed": True, "api_error": _RACE_TIMED_OUT}) - m = dict(m) # don't mutate the callee's metrics dict + m = {**m, **reviewer_context} # a copy: don't mutate the callee's metrics dict m["race_winner"] = 1 if winner == "agentic" else 2 m["race_delay_s"] = delay_s m["race_started"] = 1 if fallback_started.is_set() else 0 @@ -1523,6 +1538,7 @@ def handle_commit_review_posttooluse(input_data): # the condition that used to replace the findings body occurs. Not # counted when the single-shot fallback wins the race. _TAIL_METRICS["child_stderr"] = _am["child_stderr"] + _note_reviewer_context(agentic_metrics) review_failed = bool(agentic_metrics.get("review_failed")) api_status = agentic_metrics.get("api_error") # Fall back to single-shot only on agentic FAILURE (SDK/investigate @@ -1938,6 +1954,7 @@ def handle_push_sweep_posttooluse(input_data): ) if agentic_metrics.get("child_stderr"): _TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"] + _note_reviewer_context(agentic_metrics) review_failed = bool(agentic_metrics.get("review_failed")) api_status = agentic_metrics.get("api_error") if agentic_metrics.get("agentic_fallback"): diff --git a/plugins/security-guidance/tests/test_reviewer_context_metrics.py b/plugins/security-guidance/tests/test_reviewer_context_metrics.py new file mode 100644 index 00000000..c0dfb491 --- /dev/null +++ b/plugins/security-guidance/tests/test_reviewer_context_metrics.py @@ -0,0 +1,178 @@ +"""The agentic reviewer reports, as counts only, how its Read/Grep/Glob calls +went and whether the directory it ran in was still there.""" +import json +import os +import shutil +import sys +import types + +import pytest + +import llm +import security_reminder_hook as hook + + +class _ToolUse: + def __init__(self, id, name): + self.id, self.name, self.input = id, name, {} + + +class _ToolResult: + def __init__(self, tool_use_id, is_error=None): + self.tool_use_id, self.is_error, self.content = tool_use_id, is_error, "" + + +@pytest.fixture +def sdk(monkeypatch, tmp_path): + """Stand-in for claude_agent_sdk whose reviewer replays `script.messages` + and then returns no findings. Like the SDK, it cannot start in a + directory that does not exist.""" + script = types.SimpleNamespace(messages=[], before_result=lambda: None) + + class ClaudeAgentOptions: + def __init__(self, **kwargs): + self.kwargs = kwargs + + class AssistantMessage: + def __init__(self, *content): + self.content = list(content) + + class UserMessage: + def __init__(self, content): + self.content = content + + class ResultMessage: + subtype, usage, total_cost_usd = "success", {}, 0.0 + structured_output = {"findings": []} + + async def query(prompt, options): + if not os.path.isdir(options.kwargs["cwd"]): + raise RuntimeError("Working directory does not exist") + for m in script.messages: + yield m + script.before_result() + yield ResultMessage() + + mod = types.ModuleType("claude_agent_sdk") + mod.ClaudeAgentOptions, mod.ResultMessage, mod.query = ClaudeAgentOptions, ResultMessage, query + mod.AssistantMessage = AssistantMessage + monkeypatch.setitem(sys.modules, "claude_agent_sdk", mod) + monkeypatch.setenv("SG_AGENTIC_CLI_PATH", "") + monkeypatch.setenv("SECURITY_WARNINGS_STATE_DIR", str(tmp_path / "state")) + for var in ("SG_AGENTIC_CONTEXT_DIR", "SG_AGENTIC_DEBUG_DIR", "SG_AGENTIC_MODEL"): + monkeypatch.delenv(var, raising=False) + script.assistant, script.user = AssistantMessage, UserMessage + return script + + +def _review(repo): + return llm.agentic_review(str(repo), [("a.py", "+x = 1\n")], ["a.py"])[2] + + +class TestAgenticReview: + def test_clean_review_counts_calls_and_no_errors(self, sdk, tmp_path): + sdk.messages = [sdk.assistant(_ToolUse("t1", "Read")), + sdk.user([_ToolResult("t1", is_error=False)])] + m = _review(tmp_path) + assert m["rv_tool_calls"] == 1 + assert "rv_tool_err" not in m and "rv_cwd_gone" not in m + + def test_errored_file_tool_results_are_counted(self, sdk, tmp_path): + sdk.messages = [ + sdk.assistant(_ToolUse("t1", "Read")), + sdk.user([_ToolResult("t1", is_error=True)]), + sdk.assistant(_ToolUse("t2", "Glob"), _ToolUse("t3", "Grep")), + sdk.user([_ToolResult("t2", is_error=True), _ToolResult("t3", is_error=False)]), + sdk.user("plain text"), + ] + m = _review(tmp_path) + assert (m["rv_tool_calls"], m["rv_tool_err"]) == (3, 2) + + def test_other_tools_are_not_counted(self, sdk, tmp_path): + # A rejected structured-output attempt or a denied tool is not a + # sign of missing context. + sdk.messages = [ + sdk.assistant(_ToolUse("t1", "StructuredOutput"), _ToolUse("t2", "Bash")), + sdk.user([_ToolResult("t1", is_error=True), _ToolResult("t2", is_error=True)]), + ] + m = _review(tmp_path) + assert "rv_tool_calls" not in m and "rv_tool_err" not in m + + def test_directory_missing_before_the_review(self, sdk, tmp_path): + m = _review(tmp_path / "removed") + assert m["agentic_fallback"].startswith("investigate:") + assert m["rv_cwd_gone"] == 1 + + def test_directory_removed_during_the_review(self, sdk, tmp_path): + repo = tmp_path / "wt" + repo.mkdir() + sdk.messages = [sdk.assistant(_ToolUse("t1", "Read")), + sdk.user([_ToolResult("t1", is_error=True)])] + sdk.before_result = lambda: shutil.rmtree(repo) + m = _review(repo) + assert (m["rv_cwd_gone"], m["rv_tool_err"]) == (2, 1) + + def test_counts_survive_a_failed_investigate(self, sdk, tmp_path, monkeypatch): + async def query(prompt, options): + yield sdk.assistant(_ToolUse("t1", "Read")) + yield sdk.user([_ToolResult("t1", is_error=True)]) + raise RuntimeError("inner CLI exited") + + monkeypatch.setattr(sys.modules["claude_agent_sdk"], "query", query) + m = _review(tmp_path) + assert m["agentic_fallback"].startswith("investigate:") + assert (m["rv_tool_calls"], m["rv_tool_err"]) == (1, 1) + + +class TestEmittedRow: + @pytest.fixture(autouse=True) + def _clean_tail(self, monkeypatch): + monkeypatch.setattr(hook, "_TAIL_METRICS", {}) + + def _row(self, capsys): + return json.loads(capsys.readouterr().out)["metrics"] + + def test_context_keys_come_last_in_priority_order(self, capsys): + hook._note_reviewer_context( + {"rv_tool_calls": 4, "rv_tool_err": 2, "rv_cwd_gone": 2, "investigate_turns": 5}) + hook.emit_metrics({"vulns_found": 0, "review_ms": 10}) + keys = list(self._row(capsys)) + assert keys[-5:] == ["vulns_found", "review_ms", "rv_cwd_gone", "rv_tool_err", "rv_tool_calls"] + + 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}) + row = self._row(capsys) + assert row["rv_tool_calls"] == 3 + assert "rv_tool_err" not in row and "rv_cwd_gone" not in row + + def test_failed_review_row_keeps_vulns_found_ahead_of_context_keys(self, capsys): + hook._note_reviewer_context({"rv_cwd_gone": 1}) + with pytest.raises(SystemExit): + hook._exit_review_failed("Commit", "s1", {"files_reviewed": 1}, 500) + keys = list(self._row(capsys)) + assert keys.index("vulns_found") < keys.index("rv_cwd_gone") == len(keys) - 1 + + +class TestRace: + def test_context_kept_when_the_fallback_result_replaces_a_failed_agentic_run(self, monkeypatch): + import time + + def agentic(*a): + 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} + + monkeypatch.setenv("SG_AGENTIC_RACE_DELAY_S", "0") + monkeypatch.delenv("SG_AGENTIC_NO_RACE", raising=False) + monkeypatch.setattr(hook, "agentic_review", agentic) + + def single_shot(*a, **k): + time.sleep(0.6) + return None, [] + + monkeypatch.setattr(hook, "analyze_code_security", single_shot) + monkeypatch.setattr(hook.llm, "last_review_failed", lambda: False) + _, _, m = hook._agentic_review_with_race("/nonexistent", [("a.py", "+x")], ["a.py"], []) + 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) |
