mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-10-14 04:08: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>
687 lines
26 KiB
Python
687 lines
26 KiB
Python
"""Workspace, patch, and verifier evidence for workflow benchmark runs."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import os
|
|
import re
|
|
import shlex
|
|
import shutil
|
|
import stat
|
|
import sys
|
|
import tempfile
|
|
from dataclasses import dataclass
|
|
from pathlib import Path, PurePosixPath
|
|
from typing import Any, Iterator, Sequence
|
|
|
|
from .evolution import skill_fingerprint
|
|
from .process_control import ManagedProcessError, ManagedProcessResult, run_checked, run_managed
|
|
from .proposer_sandbox import SANDBOX_WORKSPACE, SandboxSession, build_sandbox_environment
|
|
|
|
MAX_PATCH_BYTES = 300_000
|
|
MAX_WORKSPACE_SNAPSHOT_ENTRIES = 100_000
|
|
MAX_WORKSPACE_SNAPSHOT_PATH_BYTES = 16 * 1024 * 1024
|
|
MAX_WORKSPACE_SNAPSHOT_FILE_BYTES = 1024 * 1024 * 1024
|
|
|
|
# Claude Code's own enableWeakerNestedSandbox bootstrap creates these paths on
|
|
# EVERY session regardless of task or model output -- reproduced empirically
|
|
# with a trivial "say OK" prompt: a synthetic package.json/lockfiles/
|
|
# node_modules, a full set of .env variants, and .claude/agents,
|
|
# .claude/commands, .claude/.cc-writes. None of this is something the model
|
|
# decided to write, so it must not count as an "unauthorized" workspace
|
|
# change during the planning-phase boundary check (the one thing this
|
|
# snapshot is used for -- see workspace_snapshot's callers). Mirrors the
|
|
# pre-existing .git exclusion below, which is the same kind of harness/tool
|
|
# noise rather than substantive diff.
|
|
WORKSPACE_SNAPSHOT_BOOTSTRAP_NOISE = frozenset(
|
|
{
|
|
".claude",
|
|
".bash_profile",
|
|
".bashrc",
|
|
".env",
|
|
".env.development",
|
|
".env.development.local",
|
|
".env.local",
|
|
".env.production",
|
|
".env.production.local",
|
|
".env.test",
|
|
".env.test.local",
|
|
".gitmodules",
|
|
".gitconfig",
|
|
".idea",
|
|
".npmrc",
|
|
".profile",
|
|
".ripgreprc",
|
|
".vscode",
|
|
".yarnrc",
|
|
".yarnrc.yml",
|
|
".zprofile",
|
|
".zshrc",
|
|
"bunfig.toml",
|
|
"node_modules",
|
|
"package-lock.json",
|
|
"package.json",
|
|
"pnpm-lock.yaml",
|
|
"yarn.lock",
|
|
}
|
|
)
|
|
# Claude Code may drop a workspace-root `scripts` *file* during bootstrap.
|
|
# Only that exact entry is noise — a `scripts/` directory is real workspace.
|
|
WORKSPACE_SNAPSHOT_ROOT_FILE_NOISE = frozenset({"scripts"})
|
|
|
|
# The set above is matched at the workspace ROOT only, because most of its
|
|
# entries (package.json, node_modules, the .env family) are also legitimate
|
|
# repository content further down the tree -- gitnexus/package.json and
|
|
# gitnexus/.claude/settings.local.json are both tracked files whose edits must
|
|
# still be caught. But Claude Code bootstraps into whatever directory it is
|
|
# running in, so a task whose prompt cd's into a subdirectory gets the same
|
|
# noise one level down. Observed in skill-evolution run 29861768554: 13 of 18
|
|
# sessions failed with "phase changed unauthorized workspace path(s):
|
|
# gitnexus/.claude/.cc-writes". That entry is matched at ANY depth -- never
|
|
# ".claude" itself, which holds real configuration.
|
|
#
|
|
# Deliberately only .cc-writes. Every excluded name is a blind spot: once a
|
|
# .claude directory already exists (gitnexus/.claude/settings.local.json is
|
|
# tracked), anything a phase writes underneath an excluded entry becomes
|
|
# invisible to this check, and Claude Code loads .claude/agents relative to
|
|
# its cwd -- which these tasks point at gitnexus/. Adding "agents" and
|
|
# "commands" here on the theory that they might also appear nested would let a
|
|
# planning phase plant a definition that the later work phase reads, with no
|
|
# evidence in the boundary check. Only .cc-writes was ever observed nested, so
|
|
# only .cc-writes is excluded; extend this set from an observed failure, never
|
|
# pre-emptively.
|
|
CLAUDE_BOOTSTRAP_DIR = ".claude"
|
|
CLAUDE_BOOTSTRAP_ENTRIES = frozenset({".cc-writes"})
|
|
|
|
IMPLEMENTATION_ARMS = frozenset(
|
|
{
|
|
"workflow",
|
|
"workflow_direct",
|
|
"ce_workflow",
|
|
"ce_workflow_direct",
|
|
"baseline",
|
|
"baseline_nomcp",
|
|
}
|
|
)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class VerificationResult:
|
|
"""Verifier output that preserves infrastructure terminal state."""
|
|
|
|
command: Sequence[str] | str
|
|
process: ManagedProcessResult
|
|
output: str
|
|
|
|
@property
|
|
def passed(self) -> bool:
|
|
return self.process.ok
|
|
|
|
def __iter__(self) -> Iterator[bool | str]:
|
|
# Preserve the historical two-value unpacking API for standalone
|
|
# callers while runner.py inspects ``process.state`` explicitly.
|
|
yield self.passed
|
|
yield self.output
|
|
|
|
|
|
def _is_bootstrap_noise(
|
|
relative: PurePosixPath,
|
|
*,
|
|
is_dir: bool = False,
|
|
is_file: bool = False,
|
|
) -> bool:
|
|
"""Report whether a walked entry is harness noise rather than workspace change."""
|
|
|
|
parts = relative.parts
|
|
if parts[0] == ".git" or parts[0] in WORKSPACE_SNAPSHOT_BOOTSTRAP_NOISE:
|
|
return True
|
|
if (
|
|
is_file
|
|
and not is_dir
|
|
and len(parts) == 1
|
|
and parts[0] in WORKSPACE_SNAPSHOT_ROOT_FILE_NOISE
|
|
):
|
|
return True
|
|
return len(parts) >= 2 and parts[-2] == CLAUDE_BOOTSTRAP_DIR and parts[-1] in CLAUDE_BOOTSTRAP_ENTRIES
|
|
|
|
|
|
def workspace_snapshot(worktree: Path) -> dict[str, str]:
|
|
"""Hash the workspace without following links, excluding Git internals
|
|
and Claude Code's own sandbox-bootstrap noise (see
|
|
WORKSPACE_SNAPSHOT_BOOTSTRAP_NOISE)."""
|
|
|
|
root = worktree.expanduser().absolute()
|
|
mode = root.lstat().st_mode
|
|
if stat.S_ISLNK(mode) or not stat.S_ISDIR(mode) or root.resolve(strict=True) != root:
|
|
raise ValueError(f"workspace snapshot root must be a real directory: {root}")
|
|
|
|
snapshot: dict[str, str] = {}
|
|
pending: list[tuple[Path, PurePosixPath]] = [(root, PurePosixPath())]
|
|
entry_count = 0
|
|
path_bytes = 0
|
|
file_bytes = 0
|
|
nofollow = getattr(os, "O_NOFOLLOW", 0)
|
|
while pending:
|
|
directory, relative_dir = pending.pop()
|
|
try:
|
|
children = sorted(os.scandir(directory), key=lambda entry: entry.name, reverse=True)
|
|
except OSError as exc:
|
|
raise ValueError(f"workspace snapshot directory is unreadable: {directory}: {exc}") from exc
|
|
for entry in children:
|
|
relative = relative_dir / entry.name
|
|
if _is_bootstrap_noise(
|
|
relative,
|
|
is_dir=entry.is_dir(follow_symlinks=False),
|
|
is_file=entry.is_file(follow_symlinks=False),
|
|
):
|
|
continue
|
|
entry_count += 1
|
|
path_bytes += len(relative.as_posix().encode())
|
|
if entry_count > MAX_WORKSPACE_SNAPSHOT_ENTRIES or path_bytes > MAX_WORKSPACE_SNAPSHOT_PATH_BYTES:
|
|
raise ValueError("workspace snapshot exceeds its bounded entry or path limit")
|
|
metadata = entry.stat(follow_symlinks=False)
|
|
permissions = stat.S_IMODE(metadata.st_mode)
|
|
if stat.S_ISDIR(metadata.st_mode):
|
|
snapshot[relative.as_posix()] = f"d:{permissions:o}"
|
|
pending.append((Path(entry.path), relative))
|
|
continue
|
|
if stat.S_ISLNK(metadata.st_mode):
|
|
snapshot[relative.as_posix()] = f"l:{permissions:o}:{os.readlink(entry.path)}"
|
|
continue
|
|
if not stat.S_ISREG(metadata.st_mode):
|
|
snapshot[relative.as_posix()] = f"s:{metadata.st_mode}"
|
|
continue
|
|
file_bytes += metadata.st_size
|
|
if file_bytes > MAX_WORKSPACE_SNAPSHOT_FILE_BYTES:
|
|
raise ValueError("workspace snapshot exceeds its bounded file-byte limit")
|
|
descriptor = os.open(entry.path, os.O_RDONLY | nofollow)
|
|
try:
|
|
opened = os.fstat(descriptor)
|
|
if (
|
|
not stat.S_ISREG(opened.st_mode)
|
|
or opened.st_dev != metadata.st_dev
|
|
or opened.st_ino != metadata.st_ino
|
|
):
|
|
raise ValueError(f"workspace file changed while opening: {entry.path}")
|
|
digest = hashlib.sha256()
|
|
while chunk := os.read(descriptor, 64 * 1024):
|
|
digest.update(chunk)
|
|
after = os.fstat(descriptor)
|
|
if (opened.st_size, opened.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
|
raise ValueError(f"workspace file changed while hashing: {entry.path}")
|
|
finally:
|
|
os.close(descriptor)
|
|
snapshot[relative.as_posix()] = f"f:{permissions:o}:{metadata.st_size}:{digest.hexdigest()}"
|
|
return snapshot
|
|
|
|
|
|
def enforce_phase_workspace(
|
|
worktree: Path,
|
|
before: dict[str, str],
|
|
*,
|
|
allowed_artifact: Path | None,
|
|
) -> None:
|
|
"""Require a phase to change only its one explicit workspace artifact.
|
|
|
|
``allowed_artifact=None`` is the stricter contract: the phase must leave
|
|
the workspace byte-identical. That is what a review phase whose artifact
|
|
lives outside the workspace has to satisfy — there is nothing in there it
|
|
is entitled to touch.
|
|
"""
|
|
|
|
root = worktree.expanduser().absolute()
|
|
if allowed_artifact is None:
|
|
after = workspace_snapshot(root)
|
|
changed = sorted(
|
|
path for path in before.keys() | after.keys() if before.get(path) != after.get(path)
|
|
)
|
|
if changed:
|
|
raise ValueError(f"phase changed the read-only workspace: {', '.join(changed[:5])}")
|
|
return
|
|
artifact = allowed_artifact.expanduser().absolute()
|
|
try:
|
|
relative = PurePosixPath(artifact.relative_to(root).as_posix())
|
|
except ValueError as exc:
|
|
raise ValueError(f"phase artifact escapes the workspace: {allowed_artifact}") from exc
|
|
after = workspace_snapshot(root)
|
|
changed = {path for path in before.keys() | after.keys() if before.get(path) != after.get(path)}
|
|
artifact_key = relative.as_posix()
|
|
artifact_state = after.get(artifact_key)
|
|
if before.get(artifact_key) == artifact_state:
|
|
raise ValueError(f"phase did not create or change its required artifact: {relative}")
|
|
if artifact_state is None or not artifact_state.startswith("f:"):
|
|
raise ValueError(f"phase artifact must be a regular non-symlink file: {relative}")
|
|
|
|
try:
|
|
metadata = artifact.lstat()
|
|
descriptor = os.open(artifact, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
|
except OSError as exc:
|
|
raise ValueError(f"phase artifact must be a readable regular non-symlink file: {relative}") from exc
|
|
try:
|
|
opened = os.fstat(descriptor)
|
|
if (
|
|
stat.S_ISLNK(metadata.st_mode)
|
|
or not stat.S_ISREG(metadata.st_mode)
|
|
or not stat.S_ISREG(opened.st_mode)
|
|
or metadata.st_dev != opened.st_dev
|
|
or metadata.st_ino != opened.st_ino
|
|
):
|
|
raise ValueError(f"phase artifact must be a regular non-symlink file: {relative}")
|
|
finally:
|
|
os.close(descriptor)
|
|
|
|
allowed = {artifact_key}
|
|
parent = relative.parent
|
|
while parent.parts:
|
|
parent_key = parent.as_posix()
|
|
if parent_key not in before and after.get(parent_key, "").startswith("d:"):
|
|
allowed.add(parent_key)
|
|
parent = parent.parent
|
|
unauthorized = sorted(changed - allowed)
|
|
if unauthorized:
|
|
preview = ", ".join(unauthorized[:8])
|
|
suffix = " …" if len(unauthorized) > 8 else ""
|
|
raise ValueError(f"phase changed unauthorized workspace path(s): {preview}{suffix}")
|
|
|
|
|
|
def require_skill_fingerprint(worktree: Path, arm: str, expected: str | None, *, phase: str) -> None:
|
|
"""Fail closed when a bounded phase changes the evaluated prompt roots."""
|
|
|
|
try:
|
|
observed = skill_fingerprint(worktree, arm)
|
|
except (OSError, ValueError) as exc:
|
|
raise ValueError(f"{phase} changed the evaluated skill fingerprint") from exc
|
|
if observed != expected:
|
|
raise ValueError(f"{phase} changed the evaluated skill fingerprint")
|
|
|
|
|
|
def snapshot_plan_docs(worktree: Path) -> dict[Path, str]:
|
|
"""Hash direct, regular plan artifacts without following links."""
|
|
|
|
plans = worktree / "docs" / "plans"
|
|
if not plans.exists():
|
|
return {}
|
|
if plans.is_symlink() or not plans.is_dir():
|
|
raise ValueError(f"plan directory must be a real directory: {plans}")
|
|
|
|
snapshot: dict[Path, str] = {}
|
|
for path in sorted(plans.iterdir()):
|
|
if path.suffix.lower() not in {".md", ".html"}:
|
|
continue
|
|
metadata = path.lstat()
|
|
if stat.S_ISLNK(metadata.st_mode):
|
|
raise ValueError(f"plan artifact cannot be a symlink: {path}")
|
|
if not stat.S_ISREG(metadata.st_mode):
|
|
raise ValueError(f"plan artifact must be a regular file: {path}")
|
|
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
|
try:
|
|
opened = os.fstat(descriptor)
|
|
if not stat.S_ISREG(opened.st_mode) or opened.st_dev != metadata.st_dev or opened.st_ino != metadata.st_ino:
|
|
raise ValueError(f"plan artifact changed while opening: {path}")
|
|
with os.fdopen(descriptor, "rb", closefd=False) as handle:
|
|
snapshot[path] = hashlib.file_digest(handle, "sha256").hexdigest()
|
|
after = os.fstat(descriptor)
|
|
if (opened.st_size, opened.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
|
raise ValueError(f"plan artifact changed while hashing: {path}")
|
|
finally:
|
|
os.close(descriptor)
|
|
return snapshot
|
|
|
|
|
|
def new_plan_doc(worktree: Path, before: dict[Path, str]) -> Path:
|
|
"""Return the sole new or modified plan, rejecting ambiguous evidence."""
|
|
|
|
after = snapshot_plan_docs(worktree)
|
|
deleted = sorted(path for path in before if path not in after)
|
|
if deleted:
|
|
raise ValueError("planning deleted existing plan artifact(s): " + ", ".join(str(path) for path in deleted))
|
|
changed = sorted(path for path, digest in after.items() if before.get(path) != digest)
|
|
if len(changed) != 1:
|
|
raise ValueError(f"planning must create or modify exactly one plan artifact; observed {len(changed)}")
|
|
return changed[0]
|
|
|
|
|
|
def _assert_self_contained_git_objects(clone: Path) -> None:
|
|
"""Refuse clones that share pack/object bytes with another repository."""
|
|
|
|
alternates = clone / ".git" / "objects" / "info" / "alternates"
|
|
if alternates.exists():
|
|
raise RuntimeError(f"clone unexpectedly has an external object alternate: {alternates}")
|
|
objects = clone / ".git" / "objects"
|
|
if not objects.is_dir():
|
|
raise RuntimeError(f"clone is missing a git object store: {clone}")
|
|
for obj in objects.rglob("*"):
|
|
if obj.is_file() and obj.stat().st_nlink > 1:
|
|
raise RuntimeError(f"clone object is hardlinked to host storage: {obj}")
|
|
|
|
|
|
def copy_isolated_tree(source: Path, parent: Path) -> Path:
|
|
"""Copy a sanitized clone without sharing git objects or a ref namespace.
|
|
|
|
``git clone --no-local`` of GitNexus plus ``sanitize_clone_for_hidden_oracles``
|
|
(repack/prune/fsck) is minutes per cell. After sanitization the snapshot is
|
|
one parentless commit; copying that tree is the isolation boundary the
|
|
contamination bug actually required (a private ``.git``), not a second
|
|
fetch of full history. Prefer ``cp --reflink=auto`` so XFS/btrfs pay COW;
|
|
fall back to a full copy on filesystems that cannot reflink.
|
|
"""
|
|
|
|
try:
|
|
source_meta = source.expanduser().lstat()
|
|
except OSError as exc:
|
|
raise RuntimeError(f"clone template is unavailable: {source}: {exc}") from exc
|
|
if stat.S_ISLNK(source_meta.st_mode) or not stat.S_ISDIR(source_meta.st_mode):
|
|
raise RuntimeError(f"clone template must be a real directory: {source}")
|
|
source = source.expanduser().resolve()
|
|
target = Path(tempfile.mkdtemp(prefix="wfbench-", dir=parent))
|
|
target.rmdir()
|
|
try:
|
|
copied = run_managed(
|
|
["cp", "-a", "--reflink=auto", str(source), str(target)],
|
|
timeout=600,
|
|
)
|
|
if not copied.ok:
|
|
# The fallback is for a filesystem that cannot reflink, which shows
|
|
# up as a normal nonzero exit. A cancellation or timeout is reported
|
|
# the same way (run_managed returns it rather than raising), and
|
|
# copytree cannot be cancelled — so falling back there makes the
|
|
# outage breaker wait out the full copy it set the event to avoid.
|
|
if copied.state != "exited":
|
|
raise ManagedProcessError(["cp", "-a", "--reflink=auto", str(source), str(target)], copied)
|
|
shutil.copytree(source, target, symlinks=True, copy_function=shutil.copy2)
|
|
_assert_self_contained_git_objects(target)
|
|
return target
|
|
except BaseException as primary:
|
|
if target.exists():
|
|
try:
|
|
shutil.rmtree(target)
|
|
except OSError as cleanup:
|
|
primary.add_note(f"clone copy cleanup also failed: {type(cleanup).__name__}: {cleanup}")
|
|
raise
|
|
|
|
|
|
def make_worktree(repo: Path, ref: str, parent: Path) -> Path:
|
|
"""Create a self-contained clone per benchmark arm."""
|
|
|
|
target = Path(tempfile.mkdtemp(prefix="wfbench-", dir=parent))
|
|
target.rmdir()
|
|
try:
|
|
run_checked(
|
|
[
|
|
"git",
|
|
"clone",
|
|
"--no-local",
|
|
"--no-hardlinks",
|
|
"--no-tags",
|
|
"--quiet",
|
|
str(repo),
|
|
str(target),
|
|
],
|
|
timeout=600,
|
|
)
|
|
_assert_self_contained_git_objects(target)
|
|
for candidate in (ref, f"origin/{ref}"):
|
|
proc = run_managed(
|
|
["git", "-C", str(target), "checkout", "--detach", "--quiet", candidate],
|
|
timeout=60,
|
|
)
|
|
if proc.ok:
|
|
return target
|
|
raise RuntimeError(f"ref {ref!r} not found in clone of {repo}")
|
|
except BaseException as primary:
|
|
if target.exists():
|
|
try:
|
|
shutil.rmtree(target)
|
|
except OSError as cleanup:
|
|
primary.add_note(f"clone cleanup also failed: {type(cleanup).__name__}: {cleanup}")
|
|
raise
|
|
|
|
|
|
def remove_clone(clone: Path) -> None:
|
|
"""Delete one throwaway arm clone (created by make_worktree)."""
|
|
|
|
shutil.rmtree(clone)
|
|
|
|
|
|
def parse_shortstat(text: str) -> dict[str, int]:
|
|
"""Parse `git diff --shortstat` output into churn counters."""
|
|
|
|
keys = {
|
|
"file": "diff_files",
|
|
"insertion": "diff_insertions",
|
|
"deletion": "diff_deletions",
|
|
}
|
|
out = dict.fromkeys(keys.values(), 0)
|
|
for count, word in re.findall(r"(\d+) (file|insertion|deletion)", text):
|
|
out[keys[word]] = int(count)
|
|
return out
|
|
|
|
|
|
def _sandbox_git(sandbox: SandboxSession, args: list[str], *, timeout: int = 60) -> str:
|
|
command = ["/usr/bin/git", "-c", "core.fsmonitor=false", *args]
|
|
result = sandbox.run(command, timeout=timeout, env=build_sandbox_environment())
|
|
if not result.ok:
|
|
raise ManagedProcessError(command, result)
|
|
return result.stdout_tail
|
|
|
|
|
|
def _prepare_untracked_for_diff(sandbox: SandboxSession) -> None:
|
|
_sandbox_git(sandbox, ["add", "--intent-to-add", "-A"])
|
|
|
|
|
|
def _synthetic_guidance_exclusions(sandbox: SandboxSession) -> list[str]:
|
|
return [f":(exclude,literal){path}" for path in sandbox.synthetic_guidance_paths]
|
|
|
|
|
|
def implementation_diff_digest(
|
|
sandbox: SandboxSession,
|
|
orig_sha: str,
|
|
*,
|
|
prepare_untracked: bool = True,
|
|
) -> str:
|
|
"""Digest non-plan final work entirely inside the containment boundary."""
|
|
|
|
if not re.fullmatch(r"[0-9a-fA-F]{40,64}", orig_sha):
|
|
raise ValueError(f"unsafe git object id: {orig_sha!r}")
|
|
if prepare_untracked:
|
|
_prepare_untracked_for_diff(sandbox)
|
|
exclusions = " ".join(shlex.quote(path) for path in _synthetic_guidance_exclusions(sandbox))
|
|
command = (
|
|
"/usr/bin/git -c core.fsmonitor=false diff --no-ext-diff --no-textconv --binary "
|
|
f"{orig_sha} -- . ':(exclude)docs/plans' ':(exclude).claude/skills' "
|
|
f"{exclusions} | /usr/bin/sha256sum"
|
|
)
|
|
result = sandbox.run(
|
|
["/bin/sh", "-c", command],
|
|
timeout=60,
|
|
env=build_sandbox_environment(),
|
|
)
|
|
if not result.ok:
|
|
raise ManagedProcessError(command, result)
|
|
digest = result.stdout_tail.strip().split()[0] if result.stdout_tail.strip() else ""
|
|
if not re.fullmatch(r"[0-9a-f]{64}", digest):
|
|
raise RuntimeError("sandboxed git diff did not produce a SHA-256 digest")
|
|
return digest
|
|
|
|
|
|
def diff_churn(
|
|
sandbox: SandboxSession,
|
|
orig_sha: str,
|
|
*,
|
|
prepare_untracked: bool = True,
|
|
) -> dict[str, int]:
|
|
"""Return code churn versus the arm's starting SHA."""
|
|
|
|
if prepare_untracked:
|
|
_prepare_untracked_for_diff(sandbox)
|
|
output = _sandbox_git(
|
|
sandbox,
|
|
[
|
|
"diff",
|
|
"--no-ext-diff",
|
|
"--no-textconv",
|
|
"--shortstat",
|
|
orig_sha,
|
|
"--",
|
|
".",
|
|
":(exclude)docs/plans",
|
|
":(exclude).claude/skills",
|
|
*_synthetic_guidance_exclusions(sandbox),
|
|
],
|
|
)
|
|
return parse_shortstat(output)
|
|
|
|
|
|
def _bounded_regular_bytes(path: Path, *, limit: int) -> bytes:
|
|
"""Read at most ``limit`` bytes without following a generated link."""
|
|
|
|
metadata = path.lstat()
|
|
if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode):
|
|
raise RuntimeError(f"generated artifact is not a regular non-symlink file: {path}")
|
|
nofollow = getattr(os, "O_NOFOLLOW", 0)
|
|
descriptor = os.open(path, os.O_RDONLY | nofollow)
|
|
try:
|
|
opened = os.fstat(descriptor)
|
|
if not stat.S_ISREG(opened.st_mode):
|
|
raise RuntimeError(f"generated artifact changed type while opening: {path}")
|
|
chunks: list[bytes] = []
|
|
remaining = limit
|
|
while remaining > 0:
|
|
chunk = os.read(descriptor, min(64 * 1024, remaining))
|
|
if not chunk:
|
|
break
|
|
chunks.append(chunk)
|
|
remaining -= len(chunk)
|
|
return b"".join(chunks)
|
|
finally:
|
|
os.close(descriptor)
|
|
|
|
|
|
def capture_patch(sandbox: SandboxSession, worktree: Path, orig_sha: str) -> bytes:
|
|
"""Stream a final patch inside the sandbox while retaining a bounded prefix."""
|
|
|
|
artifact_dir = Path(tempfile.mkdtemp(prefix=".wfbench-artifact-", dir=worktree))
|
|
artifact_dir.chmod(0o700)
|
|
patch = artifact_dir / "final.patch"
|
|
sandbox_path = f"{SANDBOX_WORKSPACE}/{artifact_dir.relative_to(worktree).as_posix()}/final.patch"
|
|
sink = """\
|
|
import subprocess
|
|
import sys
|
|
|
|
limit = int(sys.argv[1])
|
|
output = sys.argv[2]
|
|
command = sys.argv[3:]
|
|
with open(output, "xb") as handle:
|
|
process = subprocess.Popen(command, stdout=subprocess.PIPE)
|
|
assert process.stdout is not None
|
|
remaining = limit
|
|
for chunk in iter(lambda: process.stdout.read(65536), b""):
|
|
if remaining:
|
|
retained = chunk[:remaining]
|
|
handle.write(retained)
|
|
remaining -= len(retained)
|
|
process.stdout.close()
|
|
returncode = process.wait()
|
|
if returncode:
|
|
raise SystemExit(returncode)
|
|
"""
|
|
command = [
|
|
"/usr/bin/python3",
|
|
"-I",
|
|
"-c",
|
|
sink,
|
|
str(MAX_PATCH_BYTES),
|
|
sandbox_path,
|
|
"/usr/bin/git",
|
|
"-c",
|
|
"core.fsmonitor=false",
|
|
"diff",
|
|
"--no-ext-diff",
|
|
"--no-textconv",
|
|
"--binary",
|
|
orig_sha,
|
|
"--",
|
|
".",
|
|
":(exclude).wfbench-artifact-*",
|
|
*_synthetic_guidance_exclusions(sandbox),
|
|
]
|
|
primary: BaseException | None = None
|
|
try:
|
|
result = sandbox.run(command, timeout=60, env=build_sandbox_environment())
|
|
if not result.ok:
|
|
raise ManagedProcessError(command, result)
|
|
return _bounded_regular_bytes(patch, limit=MAX_PATCH_BYTES)
|
|
except BaseException as exc:
|
|
primary = exc
|
|
raise
|
|
finally:
|
|
# The returned bytes are the evidence; this temporary sink must not
|
|
# become an agent edit in later Git diffs or repeated captures.
|
|
try:
|
|
shutil.rmtree(artifact_dir)
|
|
except OSError as cleanup:
|
|
# A failed removal must neither discard the patch already read nor
|
|
# replace the real failure. The leftover directory is excluded from
|
|
# the patch pathspec above and dies with the disposable clone, so
|
|
# it cannot corrupt the evidence; still report it rather than hide it.
|
|
detail = f"patch artifact cleanup failed: {artifact_dir}: {type(cleanup).__name__}: {cleanup}"
|
|
if primary is not None:
|
|
primary.add_note(detail)
|
|
else:
|
|
print(f"warning: {detail}", file=sys.stderr, flush=True)
|
|
|
|
|
|
def enforce_work_evidence(
|
|
record: dict[str, Any],
|
|
*,
|
|
arm: str,
|
|
before_digest: str,
|
|
after_digest: str,
|
|
) -> None:
|
|
if arm not in IMPLEMENTATION_ARMS or not record.get("resolved"):
|
|
return
|
|
if before_digest != after_digest:
|
|
return
|
|
record["resolved"] = False
|
|
record["error_kind"] = "no-work-produced"
|
|
record["error_detail"] = "verifier passed but the implementation arm produced no non-plan repository change"
|
|
|
|
|
|
def run_verify(
|
|
command: str,
|
|
cwd: Path,
|
|
timeout: int,
|
|
*,
|
|
command_prefix: list[str] | None = None,
|
|
env: dict[str, str] | None = None,
|
|
require_pid_namespace: bool = False,
|
|
) -> VerificationResult:
|
|
"""Run the task's verify command; keep its output tail for diagnosis."""
|
|
|
|
if command_prefix:
|
|
# HOME is writable during model execution. A non-login shell prevents
|
|
# candidate-created profile files from running inside trusted evidence
|
|
# collection or either verifier.
|
|
managed_command: list[str] | str = [*command_prefix, "/bin/sh", "-c", command]
|
|
shell = False
|
|
managed_cwd: Path | None = None
|
|
else:
|
|
managed_command = command
|
|
shell = True
|
|
managed_cwd = cwd
|
|
proc = run_managed(
|
|
managed_command,
|
|
shell=shell,
|
|
cwd=managed_cwd,
|
|
env=env,
|
|
timeout=timeout,
|
|
require_pid_namespace=require_pid_namespace,
|
|
)
|
|
output = proc.stdout_tail + "\n" + proc.stderr_tail
|
|
if proc.detail:
|
|
output += f"\n[{proc.state}] {proc.detail}"
|
|
return VerificationResult(
|
|
command=managed_command,
|
|
process=proc,
|
|
output=output[-4000:],
|
|
)
|