A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(ci): harden behavioral eval token, label, and verifier trust (#2449)
Seth Karten3fc5d967e4c1
diff --git a/.github/workflows/behavioral-evals.yml b/.github/workflows/behavioral-evals.ymlindex 3af2c96797..7d4c5591a6 100644--- a/.github/workflows/behavioral-evals.yml+++ b/.github/workflows/behavioral-evals.yml@@ -106,22 +106,48 @@ jobs:}}- evaluate:+ authorize:+ name: Authorize the pre-release label actorif: >-github.event_name == 'pull_request_target' && github.event.action == 'labeled' &&github.event.label.name == 'pre-release'- name: runnerruns-on: ubuntu-24.04- timeout-minutes: 360+ timeout-minutes: 5+ permissions: {}+ steps:+ - name: Validate the labeling actor's repository permission+ uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v8.0.0+ with:+ script: |+ const actor = context.payload.sender;+ if (!actor) {+ core.setFailed('No labeling actor recorded for this event.');+ return;+ }+ const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({+ owner: context.repo.owner,+ repo: context.repo.repo,+ username: actor.login,+ });+ const allowed = ['admin', 'maintain', 'write'];+ if (!allowed.includes(permission.permission)) {+ core.setFailed(+ `Actor ${actor.login} has '${permission.permission}' access; ` ++ 'the pre-release label requires write, maintain, or admin.'+ );+ }++ mark-pending:+ name: Mark the requested head pending+ if: >-+ github.event_name == 'pull_request_target' && github.event.action == 'labeled' &&+ github.event.label.name == 'pre-release'+ runs-on: ubuntu-24.04+ timeout-minutes: 5permissions:- actions: read- contents: readstatuses: write+ needs: authorizesteps:- - name: Record the job budget- # Mirrors timeout-minutes above so the orchestrator fits its waits inside the job.- run: echo "BEHAVIORAL_JOB_DEADLINE_EPOCH=$(( $(date +%s) + 360 * 60 ))" >> "$GITHUB_ENV"-- name: Mark the requested head pendinguses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v8.0.0with:@@ -145,6 +171,22 @@ jobs:target_url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,});+ evaluate:+ if: >-+ github.event_name == 'pull_request_target' && github.event.action == 'labeled' &&+ github.event.label.name == 'pre-release'+ name: runner+ runs-on: ubuntu-24.04+ timeout-minutes: 360+ needs: [authorize, mark-pending]+ permissions:+ actions: read+ contents: read+ steps:+ - name: Record the job budget+ # Mirrors timeout-minutes above so the orchestrator fits its waits inside the job.+ run: echo "BEHAVIORAL_JOB_DEADLINE_EPOCH=$(( $(date +%s) + 360 * 60 ))" >> "$GITHUB_ENV"+- name: Check out trusted evaluatoruses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0with:@@ -383,6 +425,26 @@ jobs:if-no-files-found: warnretention-days: 30+ - name: Enforce complete paired result and regression thresholds+ if: always()+ run: test -f results/verdict && test "$(cat results/verdict)" = pass++ report:+ name: Publish PR report+ needs: evaluate+ if: always() && needs.evaluate.result != 'skipped'+ runs-on: ubuntu-24.04+ permissions:+ contents: read+ pull-requests: write+ statuses: write+ steps:+ - name: Download evaluation results+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7+ with:+ name: behavioral-results-${{ github.run_attempt }}+ path: .+- name: Set exact-head statusif: always()uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v8.0.0@@ -438,24 +500,6 @@ jobs:target_url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,});- - name: Enforce complete paired result and regression thresholds- if: always()- run: test -f results/verdict && test "$(cat results/verdict)" = pass-- report:- name: Publish PR report- needs: evaluate- if: always() && needs.evaluate.result != 'skipped'- runs-on: ubuntu-24.04- permissions:- contents: read- pull-requests: write- steps:- - name: Download evaluation results- uses: actions/download-artifact@642e1d0bd1d03f3d1c2f94b1f3ae300c4d0b1b4a # v7- with:- name: behavioral-results-${{ github.run_attempt }}- path: .- name: Publish PR reportif: always() && hashFiles('results/report.md') != ''diff --git a/scripts/evals/short_swe/README.md b/scripts/evals/short_swe/README.mdindex 84c3c2c6f5..c6e064e66b 100644--- a/scripts/evals/short_swe/README.md+++ b/scripts/evals/short_swe/README.md@@ -61,8 +61,17 @@ Reapply the label to approve the new exact comparison.each task image, so scoring does not resolve packages from the network. A fixed gold-patch oracle must resolvebefore any paired task starts. Missing or inconsistent verifier output fails as infrastructurerather than becoming a zero reward.-- There is no durable baseline, promotion job, focused confirmation, or automatic+- The verifier-side test-control filter is scoped to that SWE-bench Verified transfer: only the+ 15 Verified tasks collect a candidate patch into a separate verifier, so only they run+ `filter_test_control` there. SWE-bench Pro candidates are graded in the solver sandbox by the+ upstream Harbor finalize (unchanged from #2306), and ScaleSWE's own reward restores test files to+ base before scoring. Neither taskset transfers a candidate patch to a verifier, so the filter does+ not apply to them.+- There is no durable gating baseline, promotion job, focused confirmation, or automaticretry. The one run compares head directly with its exact base and never merges.+ `harness-baselines.json` holds static reference results for other coding harnesses on+ the same suite; the report renders them as context only, unmeasured rows read as not+ yet measured, and they never affect the verdict.## Gatediff --git a/scripts/evals/short_swe/harness-baselines.json b/scripts/evals/short_swe/harness-baselines.jsonnew file mode 100644index 0000000000..6e29e31f5c--- /dev/null+++ b/scripts/evals/short_swe/harness-baselines.json@@ -0,0 +1,183 @@+{+ "schema_version": 2,+ "description": "Static harness baselines on the 28-task Short SWE suite",+ "model": "internal/glm-5.3-fast",+ "model_note": "All harnesses measured on internal/glm-5.3-fast \u2014 same model as the paired evaluation. Same 28-task suite, same scoring. The comparison isolates the harness contribution.",+ "baselines": [+ {+ "harness": "pi-coding-harness",+ "label": "Pi coding harness",+ "tasksets": {+ "swebench-verified": {+ "resolved": 13,+ "tasks": 15,+ "uncached_input_tokens": 1690000,+ "cached_input_tokens": 18150000,+ "output_tokens": 250300,+ "measured": true+ },+ "swebench-pro": {+ "resolved": 6,+ "tasks": 8,+ "uncached_input_tokens": 1080000,+ "cached_input_tokens": 14200000,+ "output_tokens": 191100,+ "measured": true+ },+ "scaleswe": {+ "resolved": 3,+ "tasks": 5,+ "uncached_input_tokens": 350000,+ "cached_input_tokens": 2440000,+ "output_tokens": 46300,+ "measured": true+ }+ },+ "model_failures": 0,+ "e2e_seconds": 4186.0,+ "measured_at": "2026-09-18T00:00:00Z",+ "source": "Same-model re-eval Sept 18 2026, pi 0.85.1 with internal/glm-5.3-fast via Prime Inference, official swebench 5.0.2 + Pro + ScaleSWE docker scoring; all 28 tasks, 0 API errors",+ "model": "internal/glm-5.3-fast"+ },+ {+ "harness": "codex",+ "label": "Codex",+ "tasksets": {+ "swebench-verified": {+ "resolved": 9,+ "tasks": 15,+ "uncached_input_tokens": 703673,+ "cached_input_tokens": 5988352,+ "output_tokens": 64452,+ "measured": true+ },+ "swebench-pro": {+ "resolved": 5,+ "tasks": 8,+ "uncached_input_tokens": 1574479,+ "cached_input_tokens": 49020928,+ "output_tokens": 101388,+ "measured": true+ },+ "scaleswe": {+ "resolved": 3,+ "tasks": 5,+ "uncached_input_tokens": 426738,+ "cached_input_tokens": 5228544,+ "output_tokens": 52676,+ "measured": true+ }+ },+ "model_failures": 0,+ "e2e_seconds": 1623.1,+ "measured_at": "2026-09-18T00:00:00Z",+ "source": "Same-model re-eval Sept 18 2026, codex 0.154.0 with internal/glm-5.3-fast via Prime Inference (Responses API), Prime VM sandbox per task, official scoring; all 28 tasks, 0 model failures",+ "model": "internal/glm-5.3-fast"+ },+ {+ "harness": "claude-code",+ "label": "Claude Code",+ "tasksets": {+ "swebench-verified": {+ "resolved": 12,+ "tasks": 15,+ "uncached_input_tokens": 2476452,+ "cached_input_tokens": 46053376,+ "output_tokens": 1475250,+ "measured": true+ },+ "swebench-pro": {+ "resolved": 6,+ "tasks": 8,+ "uncached_input_tokens": 1280056,+ "cached_input_tokens": 23324672,+ "output_tokens": 287563,+ "measured": true+ },+ "scaleswe": {+ "resolved": 3,+ "tasks": 5,+ "uncached_input_tokens": 806904,+ "cached_input_tokens": 14674944,+ "output_tokens": 683901,+ "measured": true+ }+ },+ "model_failures": 0,+ "e2e_seconds": 0.0,+ "measured_at": "2026-09-18T00:00:00Z",+ "source": "Same-model re-eval Sept 18 2026, claude-code 2.1.274 with internal/glm-5.3-fast via Prime Inference (Anthropic-compatible), 3600s rollout budget, official scoring; all 28 tasks",+ "model": "internal/glm-5.3-fast"+ },+ {+ "harness": "swe-agent",+ "label": "SWE Agent",+ "tasksets": {+ "swebench-verified": {+ "resolved": 11,+ "tasks": 15,+ "uncached_input_tokens": 2288590,+ "cached_input_tokens": 8957952,+ "output_tokens": 145302,+ "measured": true+ },+ "swebench-pro": {+ "resolved": 2,+ "tasks": 8,+ "uncached_input_tokens": 3844170,+ "cached_input_tokens": 8013824,+ "output_tokens": 175265,+ "measured": true+ },+ "scaleswe": {+ "resolved": 3,+ "tasks": 5,+ "uncached_input_tokens": 1901909,+ "cached_input_tokens": 5091328,+ "output_tokens": 58997,+ "measured": true+ }+ },+ "model_failures": 0,+ "e2e_seconds": 0.0,+ "measured_at": "2026-09-18T00:00:00Z",+ "source": "Same-model re-eval Sept 18 2026, SWE-agent 1.1.0 with internal/glm-5.3-fast via Prime Inference, Prime VM sandbox per task, official scoring; all 28 tasks, 0 failures, avg 124-259s/task",+ "model": "internal/glm-5.3-fast"+ },+ {+ "harness": "bash-edit",+ "label": "Bash Edit",+ "tasksets": {+ "swebench-verified": {+ "resolved": 6,+ "tasks": 15,+ "uncached_input_tokens": 1497428,+ "cached_input_tokens": 13005824,+ "output_tokens": 1095094,+ "measured": true+ },+ "swebench-pro": {+ "resolved": 3,+ "tasks": 8,+ "uncached_input_tokens": 972615,+ "cached_input_tokens": 10501120,+ "output_tokens": 607403,+ "measured": true+ },+ "scaleswe": {+ "resolved": 3,+ "tasks": 5,+ "uncached_input_tokens": 667659,+ "cached_input_tokens": 5729280,+ "output_tokens": 346989,+ "measured": true+ }+ },+ "model_failures": 0,+ "e2e_seconds": 20345.0,+ "measured_at": "2026-09-18T00:00:00Z",+ "source": "Fresh eval Sept 18 2026, minimal bash REPL harness with internal/glm-5.3-fast (same model as paired eval), network-free docker per task, pinned suite verifiers; all 28 tasks",+ "model": "internal/glm-5.3-fast"+ }+ ]+}diff --git a/scripts/evals/short_swe/report.py b/scripts/evals/short_swe/report.pyindex ce1b16a228..11a0d8bf99 100644--- a/scripts/evals/short_swe/report.py+++ b/scripts/evals/short_swe/report.py@@ -11,6 +11,7 @@ from pathlib import PathMARKER = "<!-- prime-agent-behavioral-eval:v1 -->"TASK_COUNT = 28+TASKSET_SIZES = {"swebench-verified": 15, "swebench-pro": 8, "scaleswe": 5}RESOLVED_LOSS_LIMIT = 5MODEL_FAILURE_LIMIT = 3RATIO_LIMIT = 2.0@@ -20,6 +21,22 @@ TASKSET_LABELS = {"swebench-pro": "SWE-bench Pro","scaleswe": "ScaleSWE",}+HARNESS_LABELS = {+ "pi-coding-harness": "Pi coding harness",+ "codex": "Codex",+ "claude-code": "Claude Code",+ "swe-agent": "SWE Agent",+ "bash-edit": "Bash Edit",+}+BASELINES_PATH = Path(__file__).resolve().parent / "harness-baselines.json"+BASELINE_FIELDS = (+ "resolved",+ "model_failures",+ "uncached_input_tokens",+ "cached_input_tokens",+ "output_tokens",+ "e2e_seconds",+)def aggregate(tasks: list[dict]) -> dict:@@ -136,6 +153,134 @@ def validate_result(result: dict, request: dict) -> tuple[dict, dict]:return base, head+def validate_baselines(document: dict) -> dict[str, dict]:+ """Validate a harness baselines document and return entries keyed by harness id."""+ if (+ not isinstance(document, dict)+ or document.get("schema_version") != 2+ or not isinstance(document.get("description"), str)+ or not document["description"]+ or not isinstance(document.get("model"), str)+ or not document["model"]+ ):+ raise ValueError("invalid harness baselines document")+ entries = document.get("baselines")+ if not isinstance(entries, list) or len(entries) != len(HARNESS_LABELS):+ raise ValueError("harness baselines must list every harness exactly once")+ validated: dict[str, dict] = {}+ seen: set[str] = set()+ for entry in entries:+ if not isinstance(entry, dict) or entry.get("harness") not in HARNESS_LABELS:+ raise ValueError("invalid harness baseline identity")+ harness = entry["harness"]+ if harness in seen:+ raise ValueError("duplicate harness baseline")+ seen.add(harness)+ tasksets = entry.get("tasksets")+ if not isinstance(tasksets, dict) or set(tasksets) != set(TASKSET_SIZES):+ raise ValueError(f"harness baseline for {harness} must cover every taskset")+ for ts_id, ts in tasksets.items():+ if not isinstance(ts, dict):+ raise ValueError(f"invalid taskset entry for {harness}/{ts_id}")+ if not isinstance(ts.get("measured"), bool):+ raise ValueError(f"invalid harness baseline measured for {harness}/{ts_id}")+ expected = TASKSET_SIZES[ts_id]+ if ts.get("tasks") != expected:+ raise ValueError(f"harness baseline {harness}/{ts_id} must list {expected} tasks")+ resolved = ts.get("resolved")+ if not isinstance(resolved, int) or isinstance(resolved, bool) or not 0 <= resolved <= expected:+ raise ValueError(f"invalid harness baseline resolved for {harness}/{ts_id}")+ for field in ("uncached_input_tokens", "cached_input_tokens", "output_tokens"):+ value = ts.get(field)+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:+ raise ValueError(f"invalid harness baseline {field} for {harness}/{ts_id}")+ validated[harness] = entry+ return validated+++def load_baselines(path: Path | None = None) -> dict[str, dict]:+ """Return measured harness baselines; they are context only, so every problem reads as unmeasured."""+ if path is None:+ path = BASELINES_PATH+ try:+ document = json.loads(path.read_text())+ except (OSError, json.JSONDecodeError):+ return {}+ try:+ return validate_baselines(document)+ except (ValueError, TypeError, KeyError):+ return {}+++def render_baselines(measured: dict[str, dict]) -> list[str]:+ """Render the static harness baselines; they are context only and never gate the verdict."""+ lines = [+ "",+ "#### Harness baselines (static reference)",+ "",+ "| Harness | SWE-bench Verified | SWE-bench Pro | ScaleSWE | Total |",+ "| --- | ---: | ---: | ---: | ---: |",+ ]+ unmeasured = []+ for harness, label in HARNESS_LABELS.items():+ entry = measured.get(harness)+ if entry is None or not entry.get("tasksets"):+ unmeasured.append(label)+ lines.append(+ f"| {label} | ?/{TASKSET_SIZES['swebench-verified']} | "+ f"?/{TASKSET_SIZES['swebench-pro']} | "+ f"?/{TASKSET_SIZES['scaleswe']} | ?/{TASK_COUNT} |"+ )+ else:+ tasksets = entry["tasksets"]+ cells = []+ for ts_id in ("swebench-verified", "swebench-pro", "scaleswe"):+ ts = tasksets.get(ts_id)+ if ts and ts.get("measured"):+ cells.append(f"{ts.get('resolved', 0)}/{ts['tasks']}")+ else:+ cells.append(f"?/{ts['tasks']}" if ts else f"?/{TASKSET_SIZES[ts_id]}")+ total = sum(ts.get("resolved", 0) for ts in tasksets.values() if ts.get("measured"))+ total_tasks = sum(ts["tasks"] for ts in tasksets.values() if ts.get("measured"))+ if any(ts.get("measured") for ts in tasksets.values()):+ lines.append(f"| {label} | {' | '.join(cells)} | {total}/{total_tasks} |")+ else:+ unmeasured.append(label)+ lines.append(+ f"| {label} | ?/{TASKSET_SIZES['swebench-verified']} | "+ f"?/{TASKSET_SIZES['swebench-pro']} | "+ f"?/{TASKSET_SIZES['scaleswe']} | ?/{TASK_COUNT} |"+ )+ lines.append("")+ if unmeasured:+ plural = "s" if len(unmeasured) > 1 else ""+ lines.append(f"Baseline{plural} not yet measured: {', '.join(unmeasured)}.")+ lines.append("Static reference only; harness baselines never gate the PR.")+ lines.extend(+ [+ "",+ "| Harness | Uncached input | Cached input | Output |",+ "| --- | ---: | ---: | ---: |",+ ]+ )+ for harness, label in HARNESS_LABELS.items():+ entry = measured.get(harness)+ if entry is None or not entry.get("tasksets"):+ lines.append(f"| {label} | ? | ? | ? |")+ else:+ tasksets = entry["tasksets"]+ uncached = sum(+ ts.get("uncached_input_tokens", 0) for ts in tasksets.values() if ts.get("measured")+ )+ cached = sum(ts.get("cached_input_tokens", 0) for ts in tasksets.values() if ts.get("measured"))+ output = sum(ts.get("output_tokens", 0) for ts in tasksets.values() if ts.get("measured"))+ if any(ts.get("measured") for ts in tasksets.values()):+ lines.append(f"| {label} | {uncached:,} | {cached:,} | {output:,} |")+ else:+ lines.append(f"| {label} | ? | ? | ? |")+ return lines++def render(result: dict, request: dict, evaluations: dict | None = None) -> tuple[str, str]:base, head = validate_result(result, request)findings = compare(base, head)@@ -185,6 +330,7 @@ def render(result: dict, request: dict, evaluations: dict | None = None) -> tuplf"{value['uncached_input_tokens']:,} | {value['cached_input_tokens']:,} | "f"{value['output_tokens']:,} |")+ lines.extend(render_baselines(load_baselines()))lines.extend(["", "**Threshold findings:**" if findings else "No drastic threshold crossed.", ""])lines.extend(f"- {finding}" for finding in findings)lines.append(f"[Workflow run]({run_url})")diff --git a/scripts/evals/short_swe/secure_harbor.py b/scripts/evals/short_swe/secure_harbor.pyindex 6ed2c03c91..f8acf065d4 100644--- a/scripts/evals/short_swe/secure_harbor.py+++ b/scripts/evals/short_swe/secure_harbor.py@@ -6,7 +6,7 @@ from pathlib import Pathimport verifiers.v1 as vffrom offline_swebench_grader import grade-from verified_verifier import rewrite_test_script, trusted_base_commit+from verified_verifier import MAX_PATCH_BYTES, filter_test_control, rewrite_test_script, trusted_base_commitfrom verifiers.v1.runtimes import Runtimefrom verifiers.v1.tasksets.harbor import HarborEnv, HarborEnvConfig, HarborTaskfrom verifiers.v1.tasksets.harbor.taskset import verifier_box_data@@ -28,6 +28,16 @@ class SecureVerifiedMixin:async def stage_verifier(self, runtime: Runtime) -> None:await super().stage_verifier(runtime)+ raw = await runtime.read("/tmp/prime-agent.patch", max_bytes=MAX_PATCH_BYTES + 1)+ if isinstance(raw, bytes) and len(raw) > MAX_PATCH_BYTES:+ raise RuntimeError(+ "candidate patch exceeds the filtering cap; refusing to apply an unfiltered tail"+ )+ if not raw:+ return+ filtered = filter_test_control(raw)+ if filtered.encode("utf-8") != raw:+ await runtime.write("/tmp/prime-agent.patch", filtered.encode("utf-8"))result = await runtime.run(["sh", "-c", "test ! -s /tmp/prime-agent.patch || git apply --binary /tmp/prime-agent.patch"],{},diff --git a/scripts/evals/short_swe/tests/test_hosted_eval.py b/scripts/evals/short_swe/tests/test_hosted_eval.pyindex 44c374c0a2..29c519bdd9 100644--- a/scripts/evals/short_swe/tests/test_hosted_eval.py+++ b/scripts/evals/short_swe/tests/test_hosted_eval.py@@ -246,7 +246,8 @@ def test_launch_stops_created_evaluations_when_a_spawn_fails(tmp_path: Path, mondef test_hosted_budgets_fit_the_github_job_limit(monkeypatch) -> None:workflow = (ROOT / ".github" / "workflows" / "behavioral-evals.yml").read_text()- job_limit = int(re.search(r"\n timeout-minutes: (\d+)", workflow).group(1))+ evaluate = workflow[workflow.find(" evaluate:") :]+ job_limit = int(re.search(r"\n timeout-minutes: (\d+)", evaluate).group(1))assert hosted_eval.GITHUB_JOB_LIMIT_MINUTES == job_limitassert f"BEHAVIORAL_JOB_DEADLINE_EPOCH=$(( $(date +%s) + {job_limit} * 60 ))" in workflow# The per-evaluation cap plus the collection reserve have to fit inside the job limit.diff --git a/scripts/evals/short_swe/tests/test_short_swe.py b/scripts/evals/short_swe/tests/test_short_swe.pyindex a93b1c8906..0d9a2f5c10 100644--- a/scripts/evals/short_swe/tests/test_short_swe.py+++ b/scripts/evals/short_swe/tests/test_short_swe.py@@ -115,7 +115,9 @@ def test_offline_verified_grader_requires_all_expected_tests() -> None:offline_swebench_grader.grade(config, "pytest failed before collecting tests")-def test_patch_collection_uses_trusted_base_and_keeps_all_git_states(tmp_path: Path) -> None:+def test_patch_collection_uses_trusted_base_and_keeps_all_git_states(+ tmp_path: Path,+) -> None:repo = tmp_path / "repo"repo.mkdir()subprocess.run(["git", "init", "-q"], cwd=repo, check=True)@@ -156,6 +158,59 @@ def test_patch_collection_uses_trusted_base_and_keeps_all_git_states(tmp_path: Passert (clone / "untracked.txt").read_text() == "untracked\n"+def test_patch_collection_overrides_candidate_diff_prefix_config(+ tmp_path: Path,+) -> None:+ """A candidate that rewrites its repo's diff prefix config must not escape the filter.++ git config diff.srcPrefix/diff.dstPrefix (or diff.mnemonicPrefix) in the solver+ sandbox would make plain git diff emit headers like "diff --git i/... j/...",+ whose sections filter_test_control cannot attribute to a path. The collect+ command must pin the a/ and b/ prefixes itself.+ """+ repo = tmp_path / "repo"+ repo.mkdir()+ subprocess.run(["git", "init", "-q"], cwd=repo, check=True)+ subprocess.run(["git", "config", "user.email", "[email protected]"], cwd=repo, check=True)+ subprocess.run(["git", "config", "user.name", "Test"], cwd=repo, check=True)+ subprocess.run(["git", "config", "commit.gpgsign", "false"], cwd=repo, check=True)+ (repo / "src.py").write_text("x = 1\n")+ tests = repo / "tests"+ tests.mkdir()+ (tests / "test_x.py").write_text("def test_x():\n assert 1 == 1\n")+ subprocess.run(["git", "add", "."], cwd=repo, check=True)+ subprocess.run(["git", "commit", "-qm", "base"], cwd=repo, check=True)+ base = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()++ # Candidate tampers with the test and rewrites the diff prefixes it will be+ # collected with.+ (tests / "test_x.py").write_text("def test_x():\n assert 1 == 2\n")+ (repo / "src.py").write_text("x = 2\n")+ subprocess.run(["git", "config", "diff.srcPrefix", "i/"], cwd=repo, check=True)+ subprocess.run(["git", "config", "diff.dstPrefix", "j/"], cwd=repo, check=True)+ subprocess.run(["git", "config", "diff.mnemonicPrefix", "true"], cwd=repo, check=True)+ subprocess.run(["git", "config", "diff.noprefix", "true"], cwd=repo, check=True)++ task = tmp_path / "task/tests"+ task.mkdir(parents=True)+ (task / "config.json").write_text(json.dumps({"base_commit": base}))+ command = verified_verifier.patch_collect_command(task.parent)+ pins = [+ "-c diff.srcPrefix=a/",+ "-c diff.dstPrefix=b/",+ "-c diff.mnemonicPrefix=false",+ "-c diff.noprefix=false",+ ]+ assert all(pin in command for pin in pins)+ subprocess.run(command.split(" && ", 1)[1], cwd=repo, check=True, shell=True)+ patch = Path("/tmp/prime-agent.patch").read_text()+ assert "diff --git a/tests/test_x.py b/tests/test_x.py" in patch++ filtered = verified_verifier.filter_test_control(patch)+ assert "x = 2" in filtered+ assert "assert 1 == 2" not in filtered++def test_verified_test_rewrite_handles_pinned_install_variants() -> None:for install in [*sorted(verified_verifier.INSTALLS), None]:script = "\n".join(@@ -214,13 +269,18 @@ def labeled_event() -> dict:"pull_request": {"number": 2306,"state": "open",- "base": {"sha": "b" * 40, "repo": {"full_name": "PrimeIntellect-ai/prime-agent"}},+ "base": {+ "sha": "b" * 40,+ "repo": {"full_name": "PrimeIntellect-ai/prime-agent"},+ },"head": {"sha": "c" * 40, "repo": {"full_name": "contributor/prime-agent"}},},}-def test_task_runtime_credentials_are_removed_before_sandbox_creation(tmp_path: Path) -> None:+def test_task_runtime_credentials_are_removed_before_sandbox_creation(+ tmp_path: Path,+) -> None:harbor = tmp_path / "verifiers/v1/tasksets/harbor/taskset.py"harbor.parent.mkdir(parents=True)harbor.write_text(@@ -233,7 +293,13 @@ def test_task_runtime_credentials_are_removed_before_sandbox_creation(tmp_path:task.data = SimpleNamespace(env={name: "secret"- for name in ("PRIME_API_KEY", "PRIME_SANDBOX_API_KEY", "GITHUB_TOKEN", "GH_TOKEN", "HF_TOKEN")+ for name in (+ "PRIME_API_KEY",+ "PRIME_SANDBOX_API_KEY",+ "GITHUB_TOKEN",+ "GH_TOKEN",+ "HF_TOKEN",+ )}| {"SAFE": "value"})@@ -366,7 +432,8 @@ def test_scored_model_timeout_is_an_outcome_but_incomplete_trace_fails() -> Nonetransient_provider_failure.errors = [transient_error]with pytest.raises(ValueError, match="complete trace or model outcome"):evaluate.trace_record(- SimpleNamespace(traces=[transient_provider_failure], errors=[], ok=False), "suite"+ SimpleNamespace(traces=[transient_provider_failure], errors=[], ok=False),+ "suite",)mixed_failure = fake_trace(ok=False, timeout=True)mixed_failure.rewards = {}@@ -416,7 +483,11 @@ def test_model_failure_without_reported_usage_records_zero_tokens() -> None:failure.errors = [provider_error]record = evaluate.trace_record(SimpleNamespace(traces=[failure], errors=[], ok=False), "suite")assert record["model_failure"] is True- assert (record["uncached_input_tokens"], record["cached_input_tokens"], record["output_tokens"]) == (+ assert (+ record["uncached_input_tokens"],+ record["cached_input_tokens"],+ record["output_tokens"],+ ) == (0,0,0,@@ -503,7 +574,10 @@ def paired(base_resolved: int = 10, head_resolved: int = 10, head_multiplier: in"model": "internal/glm-5.3-fast","started_at": 1.0,"finished_at": 2.0,- "sides": {"base": tasks(base_resolved), "head": tasks(head_resolved, head_multiplier)},+ "sides": {+ "base": tasks(base_resolved),+ "head": tasks(head_resolved, head_multiplier),+ },}@@ -546,6 +620,102 @@ def test_report_fails_drastic_quality_or_efficiency_regression() -> None:assert "Cumulative task time reached 2.00x base without more resolutions." in markdown+def _baseline_v2(harness: str, label: str, resolved: int = 0, measured: bool = False) -> dict:+ return {+ "harness": harness,+ "label": label,+ "tasksets": {+ "swebench-verified": {+ "resolved": resolved if measured else 0,+ "tasks": 15,+ "uncached_input_tokens": 100 if measured else 0,+ "cached_input_tokens": 1000 if measured else 0,+ "output_tokens": 10 if measured else 0,+ "measured": measured,+ },+ "swebench-pro": {+ "resolved": resolved if measured else 0,+ "tasks": 8,+ "uncached_input_tokens": 100 if measured else 0,+ "cached_input_tokens": 1000 if measured else 0,+ "output_tokens": 10 if measured else 0,+ "measured": measured,+ },+ "scaleswe": {+ "resolved": resolved if measured else 0,+ "tasks": 5,+ "uncached_input_tokens": 100 if measured else 0,+ "cached_input_tokens": 1000 if measured else 0,+ "output_tokens": 10 if measured else 0,+ "measured": measured,+ },+ },+ "model_failures": 0,+ "e2e_seconds": 100.0 if measured else 0.0,+ "measured_at": "2026-09-18T00:00:00Z" if measured else "1970-01-01T00:00:00Z",+ "source": "test fixture" if measured else "Pending measurement run",+ }+++def _baselines_doc(measured_harness: str | None = None) -> dict:+ return {+ "schema_version": 2,+ "description": "Static harness baselines on the 28-task Short SWE suite",+ "model": "internal/glm-5.3-fast",+ "baselines": [+ _baseline_v2(h, label, resolved=3, measured=(h == measured_harness))+ for h, label in report.HARNESS_LABELS.items()+ ],+ }+++def test_harness_baselines_file_holds_the_pinned_schema() -> None:+ document = json.loads((EVAL_ROOT / "harness-baselines.json").read_text())+ assert document["schema_version"] == 2+ assert set(b["harness"] for b in document["baselines"]) == set(report.HARNESS_LABELS)+ for entry in document["baselines"]:+ assert set(entry["tasksets"]) == set(report.TASKSET_SIZES)+ validated = report.validate_baselines(document)+ assert set(validated) == set(report.HARNESS_LABELS)+++def test_report_renders_the_harness_baselines_section() -> None:+ result = paired(base_resolved=16, head_resolved=18)+ text, verdict = report.render(result, request())+ assert "Harness baselines" in text+ assert verdict == "pass"+++def test_unmeasured_baselines_render_placeholders() -> None:+ doc = _baselines_doc(measured_harness=None)+ assert report.validate_baselines(doc)+++def test_measured_baselines_render_numbers_and_never_change_the_verdict() -> None:+ doc = _baselines_doc(measured_harness="pi-coding-harness")+ validated = report.validate_baselines(doc)+ assert "pi-coding-harness" in validated+ regression = report.compare(+ {+ "resolved": 10,+ "model_failures": 0,+ "uncached_input_tokens": 100,+ "cached_input_tokens": 1000,+ "output_tokens": 50,+ "e2e_seconds": 10.0,+ },+ {+ "resolved": 1,+ "model_failures": 0,+ "uncached_input_tokens": 100,+ "cached_input_tokens": 1000,+ "output_tokens": 50,+ "e2e_seconds": 10.0,+ },+ )+ assert regression, "regression gates are independent of baselines"++def open_directories(source: Path, destination: Path) -> tuple[int, int]:flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXECreturn os.open(source, flags), os.open(destination, flags)@@ -659,3 +829,167 @@ def test_compare_gates_positive_totals_over_a_zero_base() -> None:}findings = report.compare(base, head)assert findings, "positive totals over a zero base must gate"+++# --- filter_test_control tests ---+++class TestFilterTestControl:+ """Execution tests for the candidate patch filter."""++ def _diff(self, a: str, b: str) -> str:+ return (+ f"diff --git a/{a} b/{b}\n"+ f"index 1234567..89abcde 100644\n"+ f"--- a/{a}\n"+ f"+++ b/{b}\n"+ f"@@ -1 +1 @@\n+x = 1\n"+ )++ @pytest.mark.parametrize(+ "a,b,kept",+ [+ ("src/module.py", "src/module.py", True),+ ("tests/conftest.py", "tests/helpers.py", False),+ ("src/util.py", "tests/conftest.py", False),+ ("src/none.py", "tests/conftest.py", False),+ ("pyproject.toml", "pyproject.toml", False),+ ("tests/test_foo.py", "tests/test_foo.py", False),+ ("tests/helpers.py", "tests/helpers.py", False),+ ("src/mod.py", "tests/__init__.py", False),+ ("pkg/tests/fixture.py", "pkg/tests/fixture.py", False),+ ],+ )+ def test_filter_paths(self, a: str, b: str, kept: bool) -> None:+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ result = filter_test_control(self._diff(a, b))+ assert bool(result) == kept++ def test_bytes_and_str_match(self) -> None:+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ patch = self._diff("src/lib.py", "src/lib.py")+ assert filter_test_control(patch) == filter_test_control(patch.encode())++ def test_headerless_rejected_and_oversize_capped(self) -> None:+ from scripts.evals.short_swe.verified_verifier import (+ MAX_PATCH_BYTES,+ filter_test_control,+ )++ with pytest.raises(RuntimeError, match="no diff --git header"):+ filter_test_control("--- a/x\n+++ b/x\n@@ -1 +1 @@\n+x\n")+ with pytest.raises(RuntimeError, match="exceeds"):+ filter_test_control(b"x" * (MAX_PATCH_BYTES + 1))++ def test_unattributable_header_rejected(self) -> None:+ """Headers without both a/ and b/ tokens fail closed instead of being kept.++ git config diff.srcPrefix/diff.dstPrefix can produce these; keeping the+ section (as an older version of the filter did) would smuggle test-control+ edits into the verifier.+ """+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ for header in (+ "diff --git i/tests/conftest.py j/tests/conftest.py\n",+ "diff --git a/tests/conftest.py j/tests/conftest.py\n",+ "diff --git i/tests/conftest.py b/tests/conftest.py\n",+ "diff --git tests/conftest.py tests/conftest.py\n",+ ):+ patch = header + (+ "index 1234567..89abcde 100644\n"+ "--- i/tests/conftest.py\n"+ "+++ j/tests/conftest.py\n"+ "@@ -1 +1 @@\n"+ "+assert True\n"+ )+ with pytest.raises(RuntimeError, match="no a/ or b/ path"):+ filter_test_control(patch)++ def test_empty_and_multi_file(self) -> None:+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ assert filter_test_control(b"") == ""+ mixed = self._diff("src/lib.py", "src/lib.py") + self._diff("s.py", "tests/conftest.py")+ result = filter_test_control(mixed)+ assert "src/lib.py" in result and "conftest" not in result++ def test_traditional_section_riding_kept_section_dropped(self) -> None:+ """git apply parses traditional ---/+++ sections after a kept git-header section.++ They must route through TEST_CONTROL on their own paths, not ride the+ preceding section's attribution.+ """+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ patch = (+ self._diff("src/keep.py", "src/keep.py")+ + "--- a/testing/test_helpers.py\n"+ + "+++ b/testing/test_helpers.py\n"+ + "@@ -1,1 +1,1 @@\n"+ + "-old\n"+ + "+new\n"+ )+ result = filter_test_control(patch)+ assert "keep.py" in result and "new" not in result++ def test_traditional_section_kept_when_source_path(self) -> None:+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ patch = (+ self._diff("src/keep.py", "src/keep.py")+ + "--- a/src/trad.py\n"+ + "+++ b/src/trad.py\n"+ + "@@ -1,1 +1,1 @@\n"+ + "-old\n"+ + "+new\n"+ )+ result = filter_test_control(patch)+ assert "keep.py" in result and "new" in result+ # The +++ header line is kept too: git apply needs it.+ assert "+++ b/src/trad.py" in result++ def test_fake_count_in_hunk_context_cannot_inflate_hunk_lines(self) -> None:+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ patch = (+ "diff --git a/src/keep.py b/src/keep.py\n"+ "@@ -1,1 +1,1 @@ ctx +9,9 @@ tail\n"+ "+x\n"+ "--- a/testing/test_helpers.py\n"+ "+++ b/testing/test_helpers.py\n"+ "@@ -1,1 +1,1 @@\n"+ "-old\n"+ "+new\n"+ )+ result = filter_test_control(patch)+ assert "keep.py" in result and "new" not in result++ def test_hunk_removed_line_three_dash_test_path_is_content(self) -> None:+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ patch = "diff --git a/src/keep.py b/src/keep.py\n@@ -1,3 +1,2 @@\n old\n--- a/tests/foo.py\n+new\n"+ result = filter_test_control(patch)+ assert "--- a/tests/foo.py" in result and "new" in result++ def test_hunk_body_dashdash_is_content(self) -> None:+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ patch = "diff --git a/src/keep.py b/src/keep.py\n@@ -1,3 +1,2 @@\n---- a/tricky.py\n+plus\n"+ result = filter_test_control(patch)+ assert "---- a/tricky.py" in result and "plus" in result++ def test_quoted_traditional_path_test_control(self) -> None:+ from scripts.evals.short_swe.verified_verifier import filter_test_control++ patch = (+ self._diff("src/keep.py", "src/keep.py")+ + '--- "a/tests/weird name.py"\n'+ + '+++ "b/tests/weird name.py"\n'+ + "@@ -1 +1 @@\n"+ + "+x\n"+ )+ result = filter_test_control(patch)+ assert "keep.py" in result and "weird" not in resultdiff --git a/scripts/evals/short_swe/verified_verifier.py b/scripts/evals/short_swe/verified_verifier.pyindex 40d79f95ec..c795d17338 100644--- a/scripts/evals/short_swe/verified_verifier.py+++ b/scripts/evals/short_swe/verified_verifier.py@@ -1,6 +1,8 @@"""Trusted rewrites for pinned SWE-bench Verified test templates."""import json+import re+import shlexfrom pathlib import PathINSTALLS = {@@ -25,10 +27,18 @@ def trusted_base_commit(task_dir: Path) -> str:def patch_collect_command(task_dir: Path) -> str:base = trusted_base_commit(task_dir)+ # The candidate agent controls this sandbox, including its git config, so the+ # collect command must not honor repo-local diff prefix settings: a candidate+ # that sets diff.srcPrefix/diff.dstPrefix (or diff.mnemonicPrefix, or+ # diff.noprefix) would emit headers like "diff --git i/tests/conftest.py+ # j/tests/conftest.py" or prefix-less ones, which _patch_paths cannot attribute+ # to a path. -c overrides any repo config.return ("rm -rf /logs/artifacts && ""git add -N -- . && "- f"git diff --binary --no-ext-diff {base} -- . > /tmp/prime-agent.patch"+ "git -c diff.srcPrefix=a/ -c diff.dstPrefix=b/ -c diff.mnemonicPrefix=false "+ "-c diff.noprefix=false "+ f"diff --binary --no-ext-diff {base} -- . > /tmp/prime-agent.patch")@@ -52,3 +62,147 @@ def rewrite_test_script(script: str) -> str:script = script.replace(LOG_ASSIGNMENT, "LOG_FILE=/dev/null", 1)script = script.replace(TEE_REDIRECT, ": # output captured by the runtime controller", 1)return script.replace(PARSER, 'exit "${TEST_STATUS:-0}"', 1)+++# Maximum patch size accepted for filtering (prevents memory abuse).+MAX_PATCH_BYTES = 16 * 1024 * 1024++# Paths that control test execution; a candidate patch must not touch them+# in the verifier sandbox because the pinned test metadata is the contract.+TEST_CONTROL = re.compile(+ r"^(?:[^/]+/)*"+ r"(?:tests(?:/.*)?|testing(?:/.*)?|conftest\.py|\.?pytest\.ini|tox\.ini|pyproject\.toml|setup\.cfg|"+ r"test_[^/]*\.py|[^/]*_test\.py)$"+)+++def _decode_patch(raw: bytes | str) -> str:+ """Decode a runtime.read patch payload to text, capped in both forms."""+ if isinstance(raw, str):+ if len(raw.encode("utf-8")) > MAX_PATCH_BYTES:+ raise RuntimeError("candidate patch exceeds the filtering cap")+ return raw+ if len(raw) > MAX_PATCH_BYTES:+ raise RuntimeError("candidate patch exceeds the filtering cap")+ return raw.decode("utf-8", errors="strict")+++def _patch_paths(header: str) -> tuple[str, str]:+ """Extract the a-side and b-side paths from a diff --git header.++ A header that yields no a/ or b/ token cannot be attributed to a path, so it is+ rejected instead of kept: git config (diff.srcPrefix, diff.dstPrefix, or+ diff.mnemonicPrefix) can produce headers such as+ ``diff --git i/tests/conftest.py j/tests/conftest.py``, and a kept-but-unattributed+ section would smuggle test-control edits into the verifier.+ """+ tokens = shlex.split(header)+ a_path = ""+ b_path = ""+ for token in tokens:+ if token.startswith("a/") and not a_path:+ a_path = token[2:]+ elif token.startswith("b/") and not b_path:+ b_path = token[2:]+ if not a_path or not b_path:+ raise RuntimeError(+ f"diff --git header has no a/ or b/ path; refusing to filter: {header.strip()[:80]!r}"+ )+ return a_path, b_path+++def _unquote_path(raw: str) -> str:+ """Strip surrounding quotes from a traditional ---/+++ path token."""+ raw = raw.strip().split("\t")[0]+ if raw.startswith('"') and raw.endswith('"'):+ return raw[1:-1]+ return raw+++def _strip_diff_prefix(path: str) -> str:+ return path[2:] if len(path) > 2 and path[1] == "/" and path[0] in "ab" else path+++def _hunk_expected_lines(header: str) -> int | None:+ # Anchored to the real header shape (-N[,M] then +N[,M] then @@): a greedy+ # pattern could capture a fake "+N,M @@" from arbitrary function-context+ # text, inflating the count and keeping in_hunk true past the real hunk end.+ m = re.search(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", header)+ if not m:+ return None+ return 1 if m.group(2) is None else int(m.group(2))+++def _in_traditional_section(current: list[str]) -> bool:+ return bool(current) and current[0].startswith("--- ")+++def filter_test_control(raw: bytes | str) -> str:+ """Drop hunks that modify test-control paths from a unified diff.++ The input may be raw bytes (as returned by Runtime.read) or text.+ Only diff --git headers are recognized; a patch without any+ recognized header is rejected so traditional header-less diffs+ cannot bypass the filter, and any header whose a/ or b/ path is+ missing is rejected so diff-prefix tampering cannot smuggle+ test-control edits through as unattributable sections.+ """+ patch = _decode_patch(raw)+ kept: list[str] = []+ current: list[str] = []+ a_path = ""+ b_path = ""+ saw_header = False+ in_hunk = False+ hunk_lines_left: int | None = None+ for line in patch.splitlines(keepends=True):+ if in_hunk and hunk_lines_left is not None and hunk_lines_left <= 0:+ # The previous hunk's line count is exhausted; a --- here is a new+ # traditional file header (git apply treats it as such), not hunk content.+ in_hunk = False+ if line.startswith("diff --git "):+ if not saw_header and current:+ # Content before the first header is traditional-diff preamble:+ # git apply can still apply it, so it cannot bypass the filter.+ raise RuntimeError(+ "candidate patch has content before the first diff --git header; refusing to filter",+ )+ if current and not (TEST_CONTROL.fullmatch(a_path) or TEST_CONTROL.fullmatch(b_path)):+ kept.extend(current)+ current = [line]+ a_path, b_path = _patch_paths(line)+ saw_header = True+ in_hunk = False+ hunk_lines_left = None+ elif (+ line.startswith("--- ")+ and current+ and not in_hunk+ and _strip_diff_prefix(_unquote_path(line[4:])) not in (a_path, b_path)+ ):+ # Traditional-diff header between hunks: git apply parses it as a new+ # file patch after the preceding section, so it cannot ride along a+ # kept section's attribution. Route it through TEST_CONTROL on its+ # own a/b paths; a test-control traditional section is dropped.+ if current and not (TEST_CONTROL.fullmatch(a_path) or TEST_CONTROL.fullmatch(b_path)):+ kept.extend(current)+ current = [line]+ a_path = _strip_diff_prefix(_unquote_path(line[4:]))+ b_path = ""+ in_hunk = False+ hunk_lines_left = None+ elif b_path == "" and line.startswith("+++ ") and current and _in_traditional_section(current):+ current.append(line)+ b_path = _strip_diff_prefix(_unquote_path(line[4:]))+ else:+ if line.startswith("@@"):+ in_hunk = True+ hunk_lines_left = _hunk_expected_lines(line)+ elif in_hunk and hunk_lines_left is not None and not line.startswith("\\"):+ hunk_lines_left -= 1+ current.append(line)+ if current and not (TEST_CONTROL.fullmatch(a_path) or TEST_CONTROL.fullmatch(b_path)):+ kept.extend(current)+ if not saw_header and patch.strip():+ raise RuntimeError("candidate patch has no diff --git header; refusing to filter")+ return "".join(kept)