77import argparse
88import json
99import os
10+ import re
1011from pathlib import Path
1112
1213import yaml
1718from benchmark .verify import count_bugs , verify
1819
1920CONFIG_FILE = Path (__file__ ).parent / "config.yaml"
21+ REPO_CONFIG_FILE = Path (__file__ ).parent / "config_repo.yaml"
2022SKIP_RULES = {"mod" , "traits" , "graph_helpers" , "analysis" , "cost" , "registry" , "graph" }
2123
2224# Rough average cost per 1K tokens (used as fallback when model doesn't report usage)
@@ -31,12 +33,13 @@ def list_rules(repo_dir: str) -> list[str]:
3133 return [f .stem for f in sorted (rules_dir .glob ("*.rs" )) if f .stem not in SKIP_RULES ]
3234
3335
36+ _CERT_RE = re .compile (r"CERTIFICATE_START\s*\n(.*?)CERTIFICATE_END" , re .DOTALL )
37+
38+
3439def parse_certificate (messages : list ) -> dict | None :
35- """Extract structured certificate JSON from agent message history."""
36- import re
40+ """Extract the last structured certificate JSON from agent message history."""
3741 for msg in reversed (messages ):
38- content = msg .get ("content" , "" )
39- block = re .search (r"CERTIFICATE_START\s*\n(.*?)CERTIFICATE_END" , content , re .DOTALL )
42+ block = _CERT_RE .search (msg .get ("content" , "" ) or "" )
4043 if block :
4144 try :
4245 return json .loads (block .group (1 ).strip ())
@@ -45,6 +48,24 @@ def parse_certificate(messages: list) -> dict | None:
4548 return None
4649
4750
51+ def parse_all_certificates (messages : list ) -> list [dict ]:
52+ """Every certificate block in the trajectory (a whole-repo run emits many), de-duplicated
53+ by (rule, source) in first-seen order. Unparseable blocks are skipped."""
54+ seen , out = set (), []
55+ for msg in messages :
56+ for block in _CERT_RE .finditer (msg .get ("content" , "" ) or "" ):
57+ try :
58+ cert = json .loads (block .group (1 ).strip ())
59+ except json .JSONDecodeError :
60+ continue
61+ key = (cert .get ("rule" ), json .dumps (cert .get ("source" ), sort_keys = True ))
62+ if key in seen :
63+ continue
64+ seen .add (key )
65+ out .append (cert )
66+ return out
67+
68+
4869def extract_total_tokens (messages : list ) -> int :
4970 total = 0
5071 for msg in messages :
@@ -62,6 +83,22 @@ def save_trajectory(messages: list, path: Path) -> None:
6283 f .write (json .dumps ({"role" : msg .get ("role" , "" ), "content" : msg .get ("content" , "" )}) + "\n " )
6384
6485
86+ def _session_cost (agent , price ):
87+ """Authoritative session spend from the trajectory. ``agent.cost`` is already our
88+ token×price figure (see _build_model); cross-check against a fresh recompute and take
89+ the max — never under-count for the budget guard. Returns (cost, tokens_k, usage)."""
90+ usage = extract_usage (agent .messages )
91+ cost = max (agent .cost , price .cost (usage ) if price is not None else 0.0 )
92+ total_tokens = usage .total_tokens or extract_total_tokens (agent .messages )
93+ tokens_k = round (total_tokens / 1000 , 2 ) if total_tokens else round (cost / AVG_COST_PER_KTOK * 1000 , 2 )
94+ return cost , tokens_k , usage
95+
96+
97+ def _trajectory (agent ) -> list [dict ]:
98+ """The agent's own message history — provenance proof carried on cert-bearing rows."""
99+ return [{"role" : m .get ("role" , "" ), "content" : m .get ("content" , "" )} for m in agent .messages ]
100+
101+
65102def _build_model (model_name : str , api_base : str | None , max_tokens : int , price : Price | None ,
66103 model_kwargs : dict | None = None , api_key : str | None = None ):
67104 """A LitellmModel whose cost is OUR token×price figure, so mini-swe-agent's own
@@ -148,23 +185,11 @@ def run_one(
148185 cert = None
149186 try :
150187 agent .run (task = rule_name )
151- # agent.cost is already our token×price figure (see _build_model), which is what
152- # mini-swe-agent's per-step cost_limit enforced. Cross-check it against a fresh
153- # recompute over the whole trajectory and take the max — never under-count.
154- usage = extract_usage (agent .messages )
155- agent_cost = agent .cost
156- recomputed = price .cost (usage ) if price is not None else 0.0
157- cost = max (agent_cost , recomputed )
158- total_tokens = usage .total_tokens or extract_total_tokens (agent .messages )
159- tokens_k = round (total_tokens / 1000 , 2 ) if total_tokens else round (cost / AVG_COST_PER_KTOK * 1000 , 2 )
188+ cost , tokens_k , usage = _session_cost (agent , price )
160189 usage_row = {"input" : usage .input_tokens , "output" : usage .output_tokens ,
161190 "cache_read" : usage .cache_read_tokens , "cache_write" : usage .cache_write_tokens ,
162- "accounted_cost_usd" : round (agent_cost , 6 )}
163- # Provenance record: the agent's own message history. The backend requires this on a
164- # bug_found row and checks the certificate was emitted here (not pasted from a public
165- # answer key), so we carry it on every cert-bearing row.
166- trajectory = [{"role" : m .get ("role" , "" ), "content" : m .get ("content" , "" )}
167- for m in agent .messages ]
191+ "accounted_cost_usd" : round (agent .cost , 6 )}
192+ trajectory = _trajectory (agent )
168193 cert = parse_certificate (agent .messages )
169194 if trajectory_dir is not None :
170195 safe_model = model_name .replace ("/" , "_" ).replace (":" , "_" )
@@ -221,6 +246,88 @@ def run_one(
221246 }
222247
223248
249+ def run_repo_session (
250+ model_name : str ,
251+ ctx : EnvContext ,
252+ cost_limit : float ,
253+ * ,
254+ api_base : str | None = None ,
255+ trajectory_dir : Path | None = None ,
256+ price : Price | None = None ,
257+ max_tokens : int = DEFAULT_MAX_TOKENS ,
258+ step_limit : int | None = None ,
259+ config_path : str | Path | None = None ,
260+ strategy : str | None = None ,
261+ model_kwargs : dict | None = None ,
262+ api_key : str | None = None ,
263+ ) -> dict :
264+ """One WHOLE-REPO bug-hunting session: the agent gets the entire library + pred and the
265+ full budget as its ``cost_limit``, chooses which rules to probe, and emits a certificate
266+ per bug. Returns ``{"rows": [...], "cost": float, "tokens_k": float}`` — one result row
267+ per distinct emitted certificate, each re-verified with pred and carrying the shared
268+ session trajectory for provenance. Contrast with ``run_one`` (one isolated rule/session).
269+ """
270+ from minisweagent .agents .default import DefaultAgent
271+ from minisweagent .environments .local import LocalEnvironment
272+
273+ cfg_file = Path (config_path ) if config_path else REPO_CONFIG_FILE
274+ config = yaml .safe_load (cfg_file .read_text (encoding = "utf-8" ))
275+ if strategy is None :
276+ strat_file = os .environ .get ("AGENT_STRATEGY_FILE" )
277+ strategy = Path (strat_file ).read_text (encoding = "utf-8" ) if strat_file else ""
278+ agent_cfg = config .get ("agent" , {})
279+ agent_cfg ["cost_limit" ] = cost_limit
280+ if step_limit is not None :
281+ agent_cfg ["step_limit" ] = step_limit
282+
283+ agent = DefaultAgent (
284+ _build_model (model_name , api_base , max_tokens , price ,
285+ model_kwargs = model_kwargs , api_key = api_key ),
286+ LocalEnvironment (),
287+ ** agent_cfg ,
288+ )
289+ agent .extra_template_vars = {
290+ "repo_dir" : str (ctx .repo_path ),
291+ "commit_hash" : ctx .commit_hash [:7 ],
292+ "cost_limit" : cost_limit ,
293+ "strategy" : strategy ,
294+ }
295+
296+ agent .run (task = "find-bugs" )
297+ cost , tokens_k , _usage = _session_cost (agent , price )
298+ trajectory = _trajectory (agent )
299+ if trajectory_dir is not None :
300+ safe_model = model_name .replace ("/" , "_" ).replace (":" , "_" )
301+ save_trajectory (agent .messages , Path (trajectory_dir ) / f"{ safe_model } _whole-repo.jsonl" )
302+
303+ rows = _rows_from_certificates (parse_all_certificates (agent .messages ))
304+ # The whole session is ONE trajectory shared by every bug — return it once for the
305+ # envelope (build_submission) instead of copying it onto each row.
306+ return {"rows" : rows , "cost" : cost , "tokens_k" : tokens_k , "trajectory" : trajectory }
307+
308+
309+ def _rows_from_certificates (certs : list [dict ]) -> list [dict ]:
310+ """Verify each certificate with pred and build one result row per cert. bug_found when
311+ pred confirms, else rejected. No per-row trajectory — a whole-repo run's provenance
312+ trajectory lives once at the envelope level (submission["trajectory"])."""
313+ rows = []
314+ for cert in certs :
315+ verdict = verify (cert )
316+ row = {
317+ "rule" : cert .get ("rule" ),
318+ "result" : "bug_found" if verdict .accepted else "rejected" ,
319+ "cost" : 0.0 , # session cost/tokens live on the submission envelope, not per row
320+ "tokens_k" : 0.0 ,
321+ "certificate" : cert ,
322+ }
323+ if verdict .accepted :
324+ row ["verify_details" ] = verdict .details
325+ else :
326+ row ["reject_reason" ] = verdict .reason
327+ rows .append (row )
328+ return rows
329+
330+
224331def main () -> None :
225332 parser = argparse .ArgumentParser (description = "pred-based bug-finding benchmark" )
226333 parser .add_argument ("--model" , default = "anthropic/claude-sonnet-4-6" , help = "LiteLLM model name" )
0 commit comments