mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-10-15 04:18:05 +00:00
* test(release): add fixed-answer native tool accuracy
* fix(release): gate stable artifacts on pinned paired evaluations
Apply review findings #1-4: gate Docker publication, grade in-flight retries, preserve repository context, and execute negative controls in CI.
* fix(eval): verify native context and resolve harness security findings
Inspect Claude's first startup reminder for ordinary repository guidance.
Bound launcher-option matching and escape Markdown backslashes and pipes.
Exclude only the parsed synthetic accuracy corpus from CodeQL; keep the
benchmark harness and evaluator under security analysis.
Validated focused Python and TypeScript regressions plus core typecheck.
* fix(eval): wake the EC2 runner and prove paired evaluator execution
Bootstrap the existing dedicated instance from a protected hosted job, bound
native runner pickup, and stop only instances started by this run. Keep paid
sessions inside the fixed stop window and add a runner-only dispatch.
Require a contained six-cell prepare/session/oracle/report canary in CI,
including a failed repair that remains in the measured denominator.
* fix(ci): reuse existing configuration and disambiguate accuracy cases
Remove the new AWS credential/settings path and release opt-in variable. Bound native runner pickup with the existing GitHub token and retain private EventBridge startup until its existing mechanism can be reused. Reuse current workflow environment names and evolution schedule controls.
Name malformed-observation cases explicitly so the execution audit distinguishes null from missing and actually tests invalid arrays.
* fix(review): isolate release builds and preserve benchmark evidence
* fix(release): gate RC publication on paired quality and manage EC2 lifecycle
* fix(ci): clarify release shell redirects and build script
* fix(eval): remove temporary patch sinks after capture
* fix(bench): retire tool-accuracy allowances repaired on main
Main at 50aa4be3b repaired three #3487 route checks (#3505) and all four
#3499 Python scope checks (#3502, #3504). The ratchet correctly failed the
merged head with stale allowances, so remove them and keep the fixed answers
as release protection: 18/31 pass, 13 recorded gaps remain.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(release): gate RCs on accuracy only and keep paid runs for stable
Follow the cost split proposed in discussion #3493: fixed-answer tool
accuracy on every RC, paired agent runs before stable releases and on a
weekly schedule against the latest RC.
RC publication no longer prepares a bundle, calls release-evaluation.yml
and waits for a paid run of up to 21 hours on the shared EC2 lock. Every
release attaches this run's accuracy report; stable npm publication still
requires exact-commit paired evidence. release-evaluation.yml drops its
workflow_call path and the now-unused candidate bundle module.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(release): address PR #3503 review feedback
- Page through recent release-evaluation runs instead of reading only
the newest 50, so valid stable evidence cannot be pushed off page one.
- Bound each runner-pickup jobs request by the remaining deadline.
- Replace non-finite floats at any depth in failure receipts so the
incomplete report still serializes with allow_nan=False.
- Clarify that the summary.cap case has 501 names over 1001 sites.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(review): harden candidate build and close review gaps
- Mount the candidate checkout's .git read-only inside the build sandbox,
so lifecycle scripts cannot plant git config (e.g. core.fsmonitor) that
host git later runs in that checkout during actions/checkout cleanup.
The real-Bubblewrap canary now also attempts that write.
- Type tool-accuracy observations instead of using explicit any.
- Cover the fail-closed branches reviewers found untested: unsafe or
missing evidence artifacts, mismatched task pins, malformed repo/SHA,
an instance that stops again during bootstrap, and unbalanced GitNexus
guidance markers.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(release): describe RC accuracy gate and stable evidence step
- CONTRIBUTING now states that RCs are gated by CI (including the
fixed-answer tool-accuracy check) without a paid run, and that stable
publication needs a passing Release evaluation for the exact commit
within seven days.
- The oracle-control fixture passes tarfile's data filter only where it
exists (3.11.4+), matching the declared Python 3.11 floor.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(bench): pin tool-accuracy fixture line anchors in one place
run.ts bucketed rename edits and explain findings by line literals that
expectations.ts duplicated. Export FIXTURE_ANCHORS (file, line, pinned text)
from expectations.ts, build the fixed answers and run.ts classifiers from it,
and fail loudly (runner and unit test) when a fixture line no longer holds
the pinned text. Expected answers and observations are unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(bench): fail closed when ripgrep is missing from the tool-accuracy run
rename's text-search pass shells out to rg and only logs a degraded warning
when it is absent, so a runner without ripgrep scored a degraded rename
(homonym.ts:1 missing) and still passed. Check rg --version before indexing,
record it in accuracy.json source.externalTools, and install ripgrep in the
ci-tests tool-accuracy job and the docker release-gate (same if: condition).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(eval): split baseline guidance, share bwrap preamble, drop dead bare option, harden patch cleanup
- Move the baseline (no-GitNexus) guidance scrubbing out of proposer_sandbox.py
into baseline_guidance.py, with its unit tests.
- Expose real_directory, runtime_mount_args and bwrap_base_args publicly so
release_build no longer imports private helpers or re-assembles the shared
bubblewrap preamble; the candidate build command is byte-identical.
- Remove the unused run_claude `bare` parameter and its --bare/--tools branches.
- capture_patch: a failed temporary-directory removal no longer discards the
read patch or replaces an earlier error; it is attached as a note, or warned
on stderr when there was no earlier error.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(ec2-runner): keep stop observing through transient describe failures
- stop() treats a failed or timed-out describe-instances call as unknown
state and keeps observing until the stop deadline; a persistent failure
is still raised at the deadline with the last command error. Unusable
states and identity mismatches still fail at once (new CommandError
subclass separates command failures from semantic ones).
- Readiness CLI has one paid mode: --job-name NAME. --evolve is removed;
skill evolution passes its job name, and tests tie the watchdog command
to the paid job's actual name in both EC2 workflows.
- Jobs-API requests never get a timeout larger than the remaining pickup
budget (previously rounded up to 1s past the deadline).
- Document that the shared concurrency group keeps only one pending run,
so a queued release evaluation can be replaced and must be confirmed.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(eval): record verified EC2 lifecycle configuration
The README still described the AWS settings as assumed and unverified.
The OIDC role, environment settings and runner_only lifecycle were
configured and verified live on 2026-10-09.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(release-eval): grade both runtimes against one pinned task toolchain
Candidate and stable each staged task dependencies (node_modules,
gitnexus-shared/dist) from their own runtime checkout, so the same v1.6.12
task source was graded with different TypeScript, Vitest and LadybugDB
versions and a per-task solve delta also measured dependency drift.
- Check out and build the pinned task commit once (tasks-base) and point
every task's repo at it for both runtimes; the runtime under test reaches
sessions only through --gitnexus-root. prepare requires --task-repo at the
single pinned task commit (new task-sha subcommand resolves it).
- Retain sandbox_dependency_content_digest per measured row and make
release_gate fail when any task's cells, across candidate and stable, do not
share one recorded dependency digest.
- Move the task-pin comparison into validate_report(task_pins=...) and use
it from release_report check and release_gate.
- Cover the gate CLI with a missing and a corrupt candidate report.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(ci): warn that a pending release evaluation can be replaced
GitHub keeps one pending run per concurrency group, so a newer queued
EC2 run cancels a pending release evaluation. Operators must confirm the
startup job ran before relying on the evidence.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(eval): prove hidden oracles against the grading toolchain
Release evaluation now grades every task with dependencies built at the
pinned task commit (TypeScript 5.9.3, Vitest 4.1.11), but the oracle
controls still ran against the current checkout's toolchain. The Ubuntu
containment job now builds the pinned task toolchain and points the
controls at it. All seven controls pass locally against that build.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(ci): pin the duplicated EC2 lifecycle jobs together
Both EC2 workflows carry their own copy of the live-verified start,
check, readiness and stop jobs. A reusable workflow would change that
verified job structure, so instead a test requires the copies to stay
identical apart from the job display name and the paid-job dependency.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(release-eval): accept stable evidence only from main's current evaluator
Stable publish validated downloaded agent evidence against the release
commit's eval/ tree and never tied a report to the run that produced it.
Evidence from an older evaluator stayed acceptable for seven days after
graders changed, while task changes on main made every fresh evaluation
mismatch the tag. The first invalid artifact also hid older valid runs.
The composite action now extracts eval/ from main's head and runs the
validator there with locked base dependencies only (no dev extras or
project build). A report counts only when its harness_sha is the head_sha
of its trusted main run and the compare API shows no change under eval/,
the release-evaluation workflow or the pinned agent CLI between that
harness and the evaluator; a missing, diverged or 300-file comparison
fails closed. Runs are tried newest first, rejected runs are skipped
with a bounded reason list, every gh call has a timeout, and task pins
use validate_report's task_pins check.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(eval): break the sandbox import cycle and resolve code-scanning alerts
- baseline_guidance is now pure text handling with its own GuidanceError;
the baseline mount builder lives in proposer_sandbox again and converts
that error to SandboxError, so imports run one way only.
- task_assets uses the public real_directory name; the unused private
alias is gone.
- The oracle-control fixture always extracts with tarfile's data filter
and skips on Pythons that lack it, instead of extracting unfiltered.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(release-eval): run candidate lifecycle scripts offline; reject smuggled report fields
- build_candidate now downloads locked dependencies with --ignore-scripts,
then runs every lifecycle script (dependency installs, prepare, build)
in a fresh network namespace, so candidate code cannot reach host-local
services. Verified locally that the current head and the pinned task
commit build this way; the real-Bubblewrap canary now asserts only
loopback is visible to a lifecycle script.
- validate_report requires the evidence document to equal its
field-whitelisted rebuild, so per-run or top-level fields outside the
published schema are rejected before the publisher copies the file.
- The sandbox test suite also covers a no-GitNexus sandbox refusing
unbalanced guidance markers.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(eval): describe the offline candidate lifecycle
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(release-eval): pin downloads to the npm registry; require dependency binding
Address review feedback on PR #3503:
- The candidate's online install phase now refuses lockfile entries that
resolve outside https://registry.npmjs.org/ (other than in-checkout
workspace links) and refuses shipped .npmrc files, so a candidate
cannot steer npm at loopback, private or metadata endpoints.
- Every measured row must carry a 64-hex task-dependency digest, so a
single report cannot be accepted with its grading toolchain unbound.
- Oversized JSON integers mark a measurement untrustworthy instead of
crashing report generation.
- Baseline guidance stripping recognises headings with up to three
leading spaces (CommonMark).
- Remove a stale comment about the old private helper name.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(eval): parse CommonMark ATX headings; compare evidence by exact JSON
- Baseline guidance stripping now parses headings as CommonMark ATX
headings (0-3 leading spaces, optional closing # run, tabs), so a
GitNexus section heading like '## GitNexus rules ##' is removed too.
- Evidence validation compares the serialized rebuild with the report,
so a retyped value (true for 1, 2.0 for 2) no longer passes.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(eval): drop continuations of every CommonMark list item in baseline guidance
A removed GitNexus instruction left its indented continuation behind when
the item used '+' or an ordered marker (1. / 1)). The scrubber now
recognises every CommonMark list-item marker.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(eval): isolate candidate MCP from agent task writes (#3503)
Run MCP in a nested Bubblewrap boundary with read-only task, graph,
registry and runtime mounts, private state and isolated processes/network.
Keep task writes on the agent's built-in tools and remove mutating MCP grants.
Add startup/tool mutation canaries and preserve explicit unsafe diagnostics.
Validation: focused pytest 138 passed, 16 skipped. Full locked evaluator
996 passed, 29 skipped; real containment canaries require Ubuntu CI.
Note: eight pre-existing comparator-reuse failures reproduce on the
unchanged head due to missing os.supports_dir_fd support. One process-control
timeout failed in the full run and passed alone and on the unchanged head.
* fix(eval): close baseline mount overlap and test symlink evidence (#3503)
Reject supplied no-MCP mounts that cover forbidden GitNexus paths, including ancestor mounts and lexical aliases. Keep ordinary dependency mounts available.
Exercise evidence symlink rejection with a real valid-report target and retain dangling-link coverage.
Validation: 1026 evaluator tests passed, 29 skipped; targeted mount tests 36 passed and evidence tests 34 passed. Removing the symlink guard in memory makes the repaired regression fail. Ruff and diff checks passed.
Note: eight pre-existing comparator-reuse failures remain in this environment because os.supports_dir_fd lacks the required os.lstat support.
---------
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
348 lines
16 KiB
Python
348 lines
16 KiB
Python
"""A whole sweep, offline: real runner, real sessions, scripted model.
|
|
|
|
The layers between a model turn and a promotion decision had never been
|
|
exercised together. Unit tests covered each in isolation and the paid runs that
|
|
would have covered the composition kept dying, so the contracts BETWEEN them
|
|
went unverified - and that is where this harness has repeatedly shipped bugs.
|
|
|
|
This drives runner.main() the way the workflow does. Everything is real: task
|
|
selection, hidden-oracle capture, the sandbox, the CLI subprocess, artifact
|
|
capture, review scoring against the oracle, aggregation, the health guard, and
|
|
the promotion gate. Only the model is scripted, through MockProvider.
|
|
|
|
Two provisioning steps are stubbed because this environment cannot supply them,
|
|
and neither is harness logic: the pinned gitnexus runtime mounts (no
|
|
node_modules in a worktree) and the sanitized graph build (needs the gitnexus
|
|
CLI at a mounted path). Containment is host-unsafe here; bubblewrap stays with
|
|
the real-sandbox canary in the containment job.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import os
|
|
import shutil
|
|
|
|
import pytest
|
|
|
|
from workflow_bench import oracle_assets, runner
|
|
from workflow_bench.mock_provider import MockProvider, Reply
|
|
|
|
FAKE_CLI = Path(__file__).parent / "fixtures" / "fake_claude.py"
|
|
ARMS = ("ce_review", "review", "candidate_review")
|
|
|
|
# When set, the sweep runs with NOTHING provisioning-stubbed: real bubblewrap
|
|
# containment, the real pinned runtime mounts, and the real sanitized graph
|
|
# build. The named CI job installs all three, so a missing one there is a
|
|
# regression rather than an unsupported machine - it FAILS instead of quietly
|
|
# degrading to the stubbed path, which is the whole point of the gate.
|
|
FULL_SWEEP_ENV = "GITNEXUS_REQUIRE_FULL_SWEEP"
|
|
FULL_SWEEP = os.environ.get(FULL_SWEEP_ENV) == "1"
|
|
|
|
# The runner refuses --unsafe-no-bwrap whenever CI is set, because that mode runs
|
|
# sessions with bypassPermissions behind a boundary its own docstring calls "not
|
|
# a security boundary". Deleting CI to get past that refusal would run an
|
|
# uncontained agent sweep on the runner holding the checkout and credentials, so
|
|
# the stubbed path is skipped under CI instead. The containment job sets
|
|
# GITNEXUS_REQUIRE_FULL_SWEEP=1 and takes the real bubblewrap path, so CI keeps
|
|
# its coverage; only the uncontained convenience run is given up.
|
|
pytestmark = pytest.mark.skipif(
|
|
not FULL_SWEEP and bool(os.environ.get("CI")),
|
|
reason="an uncontained sweep must not run in CI; the containment job runs it with GITNEXUS_REQUIRE_FULL_SWEEP=1",
|
|
)
|
|
|
|
# The review output and the hidden labels are DELIBERATELY different shapes -
|
|
# the labels carry line_start/line_end and no recommendation. Only a real run
|
|
# surfaces that; it is why these are written out rather than shared.
|
|
FINDING = {
|
|
"id": "f1", "severity": "high", "category": "correctness", "path": "src/sum.js",
|
|
"line": 1, "end_line": 1, "blocking": True, "scenario": "review-defect",
|
|
"evidence": "export const total = (a, b) => a - b;", "recommendation": "use a + b",
|
|
}
|
|
LABEL = {"id": "f1", "severity": "high", "category": "correctness",
|
|
"path": "src/sum.js", "line_start": 1, "line_end": 1}
|
|
SECOND_LABEL = {"id": "f2", "severity": "high", "category": "correctness",
|
|
"path": "src/scale.js", "line_start": 1, "line_end": 1}
|
|
SECOND_FINDING = {
|
|
"id": "f2", "severity": "high", "category": "correctness", "path": "src/scale.js",
|
|
"line": 1, "end_line": 1, "blocking": True, "scenario": "review-defect",
|
|
"evidence": "export const twice = (n) => n + 2;", "recommendation": "use n * 2",
|
|
}
|
|
|
|
|
|
def _git(repo: Path, *args: str) -> str:
|
|
return subprocess.run(["git", "-C", str(repo), *args], check=True,
|
|
capture_output=True, text=True).stdout.strip()
|
|
|
|
|
|
@pytest.fixture
|
|
def bench(tmp_path: Path):
|
|
"""A self-contained corpus: one repo, one task, one hidden label."""
|
|
|
|
repo = tmp_path / "repo"
|
|
(repo / "src").mkdir(parents=True)
|
|
(repo / "src" / "sum.js").write_text("export const total = (a, b) => a - b;\n")
|
|
(repo / "src" / "scale.js").write_text("export const twice = (n) => n + 2;\n")
|
|
_git(repo, "init", "-q", ".")
|
|
_git(repo, "config", "user.email", "t@t")
|
|
_git(repo, "config", "user.name", "t")
|
|
_git(repo, "add", "-A")
|
|
_git(repo, "commit", "-q", "-m", "fixture")
|
|
sha = _git(repo, "rev-parse", "HEAD")
|
|
|
|
oracles = tmp_path / "oracles"
|
|
oracles.mkdir()
|
|
(oracles / "review-fixture-defect.labels.json").write_text(
|
|
json.dumps({"schema_version": 1, "findings": [LABEL]})
|
|
)
|
|
(oracles / "review-fixture-second.labels.json").write_text(
|
|
json.dumps({"schema_version": 1, "findings": [SECOND_LABEL]})
|
|
)
|
|
|
|
tasks = tmp_path / "tasks.yaml"
|
|
tasks.write_text(
|
|
"tasks:\n"
|
|
" - id: review-fixture-defect\n"
|
|
" class: review-defect\n"
|
|
f" repo: {repo}\n"
|
|
f" ref: {sha}\n"
|
|
" prompt: Review this change and report actionable defects.\n"
|
|
' verify: test -s "$GITNEXUS_BENCH_REVIEW_OUTPUT"\n'
|
|
" oracle:\n"
|
|
' command: test -s "$GITNEXUS_BENCH_REVIEW_OUTPUT"\n'
|
|
" files: [{ source: review-fixture-defect.labels.json, target: review-labels.json }]\n"
|
|
# A SECOND task, because the thing a cross-task scheduler changes is
|
|
# invisible with one: waves are per-task, so a single task cannot show
|
|
# ordering, packing, or a breaker that spans a task boundary.
|
|
" - id: review-fixture-second\n"
|
|
" class: review-defect\n"
|
|
f" repo: {repo}\n"
|
|
f" ref: {sha}\n"
|
|
" prompt: Review the scaling helper and report actionable defects.\n"
|
|
' verify: test -s "$GITNEXUS_BENCH_REVIEW_OUTPUT"\n'
|
|
" oracle:\n"
|
|
' command: test -s "$GITNEXUS_BENCH_REVIEW_OUTPUT"\n'
|
|
" files: [{ source: review-fixture-second.labels.json, target: review-labels.json }]\n"
|
|
)
|
|
|
|
plugin = tmp_path / "ce-plugin"
|
|
(plugin / ".claude-plugin").mkdir(parents=True)
|
|
(plugin / ".claude-plugin" / "plugin.json").write_text(
|
|
json.dumps({"name": "compound-engineering", "version": "0.0.0-fixture"})
|
|
)
|
|
for skill in ("ce-plan", "ce-work", "ce-code-review"):
|
|
directory = plugin / "skills" / skill
|
|
directory.mkdir(parents=True)
|
|
(directory / "SKILL.md").write_text(f"---\nname: {skill}\ndescription: fixture\n---\nFixture.\n")
|
|
|
|
overlay = tmp_path / "overlay" / ".claude" / "skills" / "gitnexus-review"
|
|
overlay.mkdir(parents=True)
|
|
(overlay / "SKILL.md").write_text("---\nname: gitnexus-review\ndescription: fixture\n---\nCandidate.\n")
|
|
|
|
return SimpleNamespace(tasks=tasks, oracles=oracles, plugin=plugin,
|
|
overlay=tmp_path / "overlay", out=tmp_path / "out")
|
|
|
|
|
|
def _stub_provisioning(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Replace what this machine cannot supply - and nothing else.
|
|
|
|
Under FULL_SWEEP nothing is replaced: the runtime mounts and the graph are
|
|
built for real, so the sweep exercises containment and provisioning too.
|
|
"""
|
|
|
|
if FULL_SWEEP:
|
|
if shutil.which("bwrap") is None:
|
|
pytest.fail(f"{FULL_SWEEP_ENV}=1 but bubblewrap is absent")
|
|
return
|
|
|
|
monkeypatch.setattr(runner, "trusted_gitnexus_runtime_mounts", lambda **_kwargs: ())
|
|
|
|
def materialize(worktree, *, sanitized_head=None, **_kwargs):
|
|
# The one-clone registry guard reads this before any session runs.
|
|
meta = Path(worktree) / ".gitnexus"
|
|
meta.mkdir(parents=True, exist_ok=True)
|
|
(meta / "meta.json").write_text(
|
|
json.dumps({"indexedAt": "2026-09-08T00:00:00Z", "lastCommit": sanitized_head or "0" * 40})
|
|
)
|
|
|
|
def fake_graph(**kwargs):
|
|
kwargs["env"].graph_snapshots[kwargs["graph_key"]] = SimpleNamespace(
|
|
digest="fixture-graph", manifest_digest="fixture-graph-manifest",
|
|
dependency_content_digest=None, dependency_manifest_digest=None,
|
|
materialize=materialize,
|
|
)
|
|
|
|
monkeypatch.setattr(runner, "ensure_task_graph", fake_graph)
|
|
|
|
|
|
def _sweep(bench, monkeypatch: pytest.MonkeyPatch, findings: list[dict], verdict: str, *, invoke_skill: bool = True):
|
|
"""Run the real CLI against a model scripted to return `findings`."""
|
|
|
|
_stub_provisioning(monkeypatch)
|
|
monkeypatch.setattr(
|
|
oracle_assets, "ORACLE_ROOT", bench.oracles, raising=False
|
|
)
|
|
monkeypatch.setattr(
|
|
runner, "capture_task_oracles",
|
|
lambda tasks, root=bench.oracles: oracle_assets.capture_task_oracles(tasks, root=root),
|
|
)
|
|
def review_for(body: str) -> str:
|
|
# Per task: the second task's defect is in another file, so replying
|
|
# with the first task's finding would score it wrong. A cross-task
|
|
# scheduler makes which task a request belongs to load-bearing.
|
|
chosen = findings
|
|
if findings and "scaling helper" in body:
|
|
chosen = [SECOND_FINDING if f is FINDING else f for f in findings]
|
|
return json.dumps({"schema_version": 1, "verdict": verdict, "findings": chosen})
|
|
|
|
class Scripted(MockProvider):
|
|
def next_reply(self) -> Reply:
|
|
body = json.dumps(self.requests[-1].body if self.requests else {})
|
|
target = re.search(r"(/[^\s\"']*review-output\.json)", body)
|
|
skill = re.search(r"\b(gitnexus-review|ce-code-review)\b", body)
|
|
return Reply(
|
|
text="reviewing",
|
|
tools=[
|
|
# The evidence gate needs a Skill request with a non-error
|
|
# result: a review that never invoked its skill measured the
|
|
# model, not the skill.
|
|
*([{"name": "Skill", "input": {"skill": skill.group(1) if skill else "gitnexus-review"}}]
|
|
if invoke_skill else []),
|
|
{"name": "Write", "input": {
|
|
"file_path": target.group(1) if target else str(bench.out / "unmatched-review-output.json"),
|
|
"content": review_for(body)}},
|
|
],
|
|
input_tokens=2_000, output_tokens=300,
|
|
cache_read_input_tokens=7_000, cache_creation_input_tokens=1_000,
|
|
)
|
|
|
|
with Scripted() as provider:
|
|
monkeypatch.setattr(sys, "argv", [
|
|
"runner", "--tasks", str(bench.tasks), "--arms", *ARMS,
|
|
"--runs", "1", "--workers", "1", "--out", str(bench.out),
|
|
"--base-url", provider.base_url, "--anthropic-api-key", "offline",
|
|
"--claude-bin", str(FAKE_CLI),
|
|
*([] if FULL_SWEEP else ["--unsafe-no-bwrap"]),
|
|
"--model", "mock-model",
|
|
"--ce-plugin-dir", str(bench.plugin), "--ce-plugin-version", "0.0.0-fixture",
|
|
"--candidate-overlay", str(bench.overlay),
|
|
])
|
|
|
|
try:
|
|
code = runner.main()
|
|
except SystemExit as exc:
|
|
code = exc.code
|
|
|
|
rows = [json.loads(line) for line in (bench.out / "results.jsonl").read_text().splitlines()]
|
|
return code, rows, provider
|
|
|
|
|
|
def _row(rows: list[dict], arm: str, task: str = "review-fixture-defect") -> dict:
|
|
return next(r for r in rows if r["arm"] == arm and r["task"] == task)
|
|
|
|
|
|
def test_a_correct_review_scores_and_the_sweep_exits_clean(bench, monkeypatch) -> None:
|
|
"""The whole path, green: every arm measured, scored, and accounted for."""
|
|
|
|
code, rows, provider = _sweep(bench, monkeypatch, [FINDING], "request_changes")
|
|
|
|
assert code in (None, 0), f"sweep did not succeed: {code}"
|
|
tasks = {"review-fixture-defect", "review-fixture-second"}
|
|
assert len(rows) == len(ARMS) * len(tasks)
|
|
assert len(provider.requests) == len(ARMS) * len(tasks), "each cell must reach the provider once"
|
|
assert {r["task"] for r in rows} == tasks, "both tasks must have run"
|
|
|
|
row = _row(rows, "review")
|
|
assert row["ok"] is True and row["resolved"] is True
|
|
assert row["skill_invoked"] is True
|
|
assert (row["review_true_positives"], row["review_false_positives"], row["review_false_negatives"]) == (1, 0, 0)
|
|
assert row["review_f1"] == 1.0
|
|
# The provider's own numbers survived the CLI, the parser and the row.
|
|
assert row["cache_read_input_tokens"] == 7_000
|
|
assert row["input_tokens"] == 2_000
|
|
|
|
# Each task scored against ITS OWN oracle. This is what a cross-task
|
|
# scheduler puts at risk: interleaving cells from different tasks means a
|
|
# mis-routed context or artifact scores one task against another's labels,
|
|
# and both would still look "green" per row.
|
|
second = _row(rows, "review", task="review-fixture-second")
|
|
assert second["resolved"] is True and second["review_f1"] == 1.0
|
|
assert second["review_artifact"] == "review-fixture-second-review-run0.review.json"
|
|
|
|
for name in ("results.jsonl", "report.md", "promotion.json"):
|
|
assert (bench.out / name).is_file(), f"{name} was not written"
|
|
assert (bench.out / "review-fixture-defect-review-run0.review.json").is_file()
|
|
|
|
|
|
def test_one_run_cannot_promote_a_candidate(bench, monkeypatch) -> None:
|
|
"""The gate refuses on insufficient paired runs, and says so."""
|
|
|
|
_sweep(bench, monkeypatch, [FINDING], "request_changes")
|
|
promotion = json.loads((bench.out / "promotion.json").read_text())
|
|
|
|
assert promotion["run_status"] == "complete"
|
|
decision = next(d for d in promotion["decisions"] if d["candidate_arm"] == "candidate_review")
|
|
assert decision["decision"] == "insufficient_evidence"
|
|
assert any("valid paired runs" in reason for reason in decision["reasons"])
|
|
|
|
|
|
def test_a_finding_in_the_wrong_place_scores_zero_but_stays_valid_evidence(bench, monkeypatch) -> None:
|
|
"""Being wrong is a quality result, not a broken measurement.
|
|
|
|
The negative control that makes the passing case mean something: same
|
|
harness, same well-formed artifact, only the answer changed.
|
|
"""
|
|
|
|
wrong = {**FINDING, "path": "src/WRONG.js", "line": 99, "end_line": 99}
|
|
_code, rows, _provider = _sweep(bench, monkeypatch, [wrong], "request_changes")
|
|
|
|
row = _row(rows, "review")
|
|
assert (row["review_true_positives"], row["review_false_positives"], row["review_false_negatives"]) == (0, 1, 1)
|
|
assert row["review_f1"] == 0.0
|
|
assert row["resolved"] is False
|
|
assert row["error_kind"] == "oracle-failed", "a wrong answer is not a session or evidence failure"
|
|
assert row["review_evidence_valid"] is True, "the artifact was well formed; only the answer was wrong"
|
|
|
|
|
|
def test_approving_defective_code_is_a_miss_with_no_false_positive(bench, monkeypatch) -> None:
|
|
"""The other half of the control: silence scores differently from a wrong guess."""
|
|
|
|
_code, rows, _provider = _sweep(bench, monkeypatch, [], "approve")
|
|
|
|
row = _row(rows, "review")
|
|
assert (row["review_true_positives"], row["review_false_positives"], row["review_false_negatives"]) == (0, 0, 1)
|
|
assert row["review_precision"] is None, "precision is undefined with no predictions, not zero"
|
|
assert row["review_verdict_correct"] is False, "approving defective code is the wrong verdict"
|
|
assert row["review_evidence_valid"] is True
|
|
|
|
|
|
def test_a_review_that_never_invoked_its_skill_is_not_a_measurement(bench, monkeypatch) -> None:
|
|
"""The gate that separates measuring a SKILL from measuring a model.
|
|
|
|
Added because a mutation exposed it: forcing skill_was_invoked_events to
|
|
return True left every other test here passing, so nothing pinned the gate.
|
|
The artifact is written and correct in this run - only the skill request is
|
|
missing - so a pass would mean the arm scored a review it never performed.
|
|
"""
|
|
|
|
code, rows, _provider = _sweep(bench, monkeypatch, [FINDING], "request_changes", invoke_skill=False)
|
|
|
|
row = _row(rows, "review")
|
|
assert row["skill_invoked"] is False
|
|
assert row["error_kind"] == "skill-not-invoked"
|
|
assert code not in (None, 0), "the sweep must not report success on unusable evidence"
|
|
|
|
# The row still carries its own score - the artifact was well formed - and
|
|
# aggregate() DOES count it in the arm's quality median (the KNOWN GAP noted
|
|
# above aggregate(); test_workflow_bench pins the resulting 0.5). Filtering
|
|
# it out of the median alone inverted a promotion, because valid_runs and
|
|
# excluded_runs kept counting it. It counts for cost either way: the session
|
|
# ran and was billed.
|
|
assert row["review_weighted_f1"] == 1.0
|
|
assert row["review_evidence_valid"] is True
|