diff options
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 53 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 19 |
2 files changed, 69 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"): |
