Skip to content

Official Codebase of 3DCodeVerse

Python

flywheel: the refine-pairs review sweep — textconv RCE, the real brief, the physical battery

ziyaoc0b84f16f849
diff --git a/harness/bench/refine_pairs.py b/harness/bench/refine_pairs.py
index 21b8935b..278a6120 100644
--- a/harness/bench/refine_pairs.py
+++ b/harness/bench/refine_pairs.py
@@ -5,7 +5,7 @@ what asked for the change, so a refine round arrives as two 30 KB files with no
This exports the transition instead — one row per refine round::
(previous round's judge issues + improvement plan + gate ERROR findings
- + the instruction lines actually sent) -> the src/ diff -> score delta
+ + the instruction lines the agent sessions were handed) -> src/ diff -> score delta
Both sides come from the round's OWN recorded commit, never from ``HEAD``: only 54 of the
239 recorded runs have HEAD at their last round, 152 end on a "restore best round rNN"
@@ -14,12 +14,24 @@ commit, and looking a commit up by message is ambiguous (``r01 refine`` also mat
python bench/refine_pairs.py bench/out --out refine_pairs.jsonl --summary
python bench/refine_pairs.py bench/out/aa_articulated --summary
+ python bench/refine_pairs.py bench/out/aa_articulated/arms/control/cells/art_med_tool_chest/\\
+ harness_gemini-cli_gemini-3.7-flash/run --summary
``root`` is a directory OF batteries (``bench/out``), one battery, a runs directory or a
-single run — every layout the flywheel scanner knows. Runs reachable twice through the
-symlinked cells of a battery are exported once (identity is the resolved path), and every
-transition that cannot be exported is counted under a named reason: the scan report is
-printed whether or not rows were written.
+single run — every layout the flywheel scanner knows, and a single run reports the same
+identity a whole-tree scan gives it. A run reachable through more than one path (54 of
+the 239) is exported once, labelled with the battery it PHYSICALLY lives in: ``bench/out``'s
+aliases are cross-battery symlinks (``compare_v4_calm/cells/*`` points into ``compare_v4``
+and ``compare_v4_harness_calm``), so labelling by the first path scanned credited 54 of the
+205 rows to a battery they never ran in. Every run and round that cannot be exported is
+counted under a named reason; the scan report is printed whether or not rows were written.
+
+Two instruction fields, because they are not the same list. ``refine_tasks`` is
+``RoundRecord.instructions`` — every task ``build_refine_instructions`` compiled, before
+grouping. ``instruction_lines`` is what the agents actually read: the per-group output of
+``orchestrator.compact_instructions``, folded by target and capped at
+``policy.max_instructions_per_task``, recovered from the round's own prompt files. They
+differ for 167 of the corpus's 205 transitions.
"""
from __future__ import annotations
@@ -38,14 +50,19 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from codeverse.contracts.run import RoundRecord, RunId, RunRecord # noqa: E402
+from codeverse.contracts.run import RUN_PATH_NOISE, RoundRecord, RunId, RunRecord # noqa: E402
from codeverse.flywheel import _git # noqa: E402
from codeverse.flywheel.quality import prompt_hash # noqa: E402
from codeverse.flywheel.record import ( # noqa: E402
BATTERY_MARKERS,
+ RUN_SEARCH_DEPTH,
+ FoundRun,
+ RecordError,
effective_judgment,
is_run_dir,
iter_runs,
+ load_record,
+ run_id_for,
)
from codeverse.workspace import Workspace # noqa: E402
@@ -67,6 +84,7 @@ MAX_DIFF_BYTES = 200_000
OUTCOME_THRESHOLD = 0.05
DROP_REASONS: tuple[str, ...] = (
+ "not_a_battery",
"empty_battery",
"unreadable_record",
"duplicate_run",
@@ -89,11 +107,74 @@ _BULLET_SPLIT_RE = re.compile(r";\s+(?=\([a-z]\)\s)")
_BULLET_RE = re.compile(r"^\((?P<letter>[a-z])\)\s*(?:\[(?P<target>[^\]/]+)\]\s*)?(?P<rest>.*)$", re.S)
+#: heading every refine template renders ``compact_instructions``' output under
+#: (``prompts/tracks/refine_object.j2``, ``refine_graphics.j2``, ``scene_refine.j2``)
+_CHANGES_HEADING = "## Changes to make"
+#: what follows the numbered list in those templates
+_CHANGES_END = ("## ", "Targets:", "Files in scope:", "EDIT ONLY THESE FILES")
+_NUMBERED_RE = re.compile(r"^\s*\d+\.\s+(?P<line>.*)$")
+
+
def _task(source: str, kind: str, target: str, instruction: str, files: list[str]) -> dict[str, Any]:
return {"source": source, "kind": kind, "target": target.strip(),
"instruction": instruction.strip(), "files": files}
+def changes_block(prompt: str) -> list[str]:
+ """The instruction lines of one rendered refine prompt.
+
+ The templates number the lines (``{{ loop.index }}. {{ t }}``), so the numbering is
+ stripped back off; a line wrapped over several lines of markdown is rejoined onto the
+ entry it belongs to. A prompt without the heading (a rebuild, a texture pass, a
+ baseline) yields nothing.
+ """
+ out: list[str] = []
+ started = False
+ for ln in prompt.splitlines():
+ if not started:
+ started = ln.startswith(_CHANGES_HEADING)
+ continue
+ if ln.startswith(_CHANGES_END):
+ break
+ if (m := _NUMBERED_RE.match(ln)) is not None:
+ out.append(m.group("line").strip())
+ elif ln.strip() and out:
+ out[-1] += " " + ln.strip()
+ return out
+
+
+def sent_instructions(ws: Workspace, round_index: int) -> list[dict[str, Any]]:
+ """What each of the round's agent sessions was actually handed, per session.
+
+ A refine round fans out over file-disjoint groups, and each group's session gets its
+ OWN ``compact_instructions`` output — folded by target, capped at
+ ``policy.max_instructions_per_task``. ``RoundRecord.instructions`` keeps none of
+ that: it is the flat pre-grouping task list. The prompt files the sessions were
+ started with (``trajectories/<label>_rNN/prompt.md``) do, so they are the only record
+ of the real brief; 195 of the corpus's 205 transitions still have theirs on disk.
+ A ``<label>.a<n>`` retry re-sends the same brief, so identical blocks are kept once.
+ """
+ traj = ws.root / "trajectories"
+ suffix = f"_r{round_index:02d}"
+ dirs = sorted(traj.glob(f"*{suffix}")) if traj.is_dir() else []
+ out: list[dict[str, Any]] = []
+ seen: set[tuple[str, ...]] = set()
+ # sorted by LABEL, not by directory name: `.` sorts before `_`, so sorting the names
+ # puts `refine.a2_r01` in front of the `refine_r01` whose retry it is, and the retry
+ # would then be the session the brief is credited to
+ for label in sorted(d.name[: -len(suffix)] for d in dirs):
+ try:
+ text = (traj / f"{label}{suffix}" / "prompt.md").read_text(errors="replace")
+ except OSError:
+ continue
+ lines = changes_block(text)
+ if not lines or tuple(lines) in seen:
+ continue
+ seen.add(tuple(lines))
+ out.append({"session": label, "lines": lines})
+ return out
+
+
def parse_instruction(line: str) -> list[dict[str, Any]]:
"""The task(s) encoded in one recorded instruction line.
@@ -196,6 +277,8 @@ def transition_row(
added, removed = _diff_lines(diff)
pj, cj = effective_judgment(prev), effective_judgment(cur)
delta = None if pj is None or cj is None else round(cj.overall - pj.overall, 4)
+ sent = sent_instructions(ws, cur.index)
+ lines = [ln for s in sent for ln in s["lines"]] or list(cur.instructions)
return {
"schema_version": SCHEMA_VERSION,
"battery": run_id.battery,
@@ -215,8 +298,13 @@ def transition_row(
"issues": [i.model_dump(mode="json") for i in pj.issues] if pj else [],
"improvement_plan": [i.model_dump(mode="json") for i in pj.improvement_plan] if pj else [],
"gate_findings": _gate_errors(prev),
- "instructions": list(cur.instructions),
- "instruction_tasks": [t for line in cur.instructions for t in parse_instruction(line)],
+ # what was COMPILED (RoundRecord.instructions) vs what was SENT (the per-group
+ # compacted prompts). Neither is the other: see the module docstring.
+ "refine_tasks": list(cur.instructions),
+ "sent_instructions": sent,
+ "instruction_source": "prompt" if sent else "record",
+ "instruction_lines": lines,
+ "instruction_tasks": [t for line in lines for t in parse_instruction(line)],
"diff": diff,
"diff_bytes": diff_bytes,
"diff_added": added,
@@ -240,9 +328,11 @@ class Report:
"""What one export saw: totals, named drops, and a digest per written row."""
roots: list[str] = field(default_factory=list)
+ skipped: list[str] = field(default_factory=list)
runs: int = 0
kinds: Counter[str] = field(default_factory=Counter)
drops: Counter[str] = field(default_factory=Counter)
+ aliases: Counter[str] = field(default_factory=Counter)
stats: list[dict[str, Any]] = field(default_factory=list)
@property
@@ -255,16 +345,82 @@ class Report:
return sum(self.kinds[k] for k in REFINE_KINDS)
-def scan_roots(root: Path) -> list[Path]:
- """The scan roots under ``root`` — one per battery, so ``RunId.battery`` stays a
- battery name. ``bench/out`` holds runs 5 levels down, and scanning it whole would
- label every run ``out`` and collapse the per-battery summary."""
+def scan_roots(root: Path) -> tuple[list[Path], list[Path]]:
+ """``(scan roots, skipped children)`` for ``root``.
+
+ One scan root per battery, so ``RunId.battery`` stays a battery name: ``bench/out``
+ holds runs 5 levels down, and scanning it whole would label every run ``out`` and
+ collapse the per-battery summary. A child that is neither a run nor a battery is
+ RETURNED as skipped rather than dropped in silence — ``bench/out`` holds three of
+ them (report-only merge directories with no cells of their own).
+ """
if is_run_dir(root) or any((root / m).is_dir() for m in BATTERY_MARKERS):
- return [root]
+ return [root], []
kids = sorted(p for p in root.iterdir() if p.is_dir())
if any(is_run_dir(k) for k in kids):
- return [root]
- return [k for k in kids if is_run_dir(k) or any((k / m).is_dir() for m in BATTERY_MARKERS)] or [root]
+ return [root], []
+ roots = [k for k in kids if is_run_dir(k) or any((k / m).is_dir() for m in BATTERY_MARKERS)]
+ if not roots:
+ return [root], []
+ return roots, [k for k in kids if k not in roots]
+
+
+def battery_root_for(run_dir: Path) -> Path:
+ """The root that gives ``run_dir`` its battery label when no scan root claims it.
+
+ The OUTERMOST ancestor (within :data:`RUN_SEARCH_DEPTH`) whose path down to the run
+ begins with a battery marker — ``bench/out/<battery>/arms/<arm>/cells/…/run`` reports
+ ``<battery>``, the same label a whole-``bench/out`` scan mints for it, so pointing the
+ exporter at one run and finding it in a full scan produce the same identity. A layout
+ with no marker at all (``<dir>/<slug>``) falls back to the run's parent.
+ """
+ root = run_dir.parent
+ for p in run_dir.parents[:RUN_SEARCH_DEPTH]:
+ parts = run_dir.relative_to(p).parts
+ if parts[0] in RUN_PATH_NOISE:
+ root = p
+ return root
+
+
+def physical_run_id(resolved: Path, roots: Sequence[Path], found: RunId) -> RunId:
+ """``found`` re-minted against the battery the run PHYSICALLY lives in.
+
+ ``found`` names the root the scan REACHED the run through, and in ``bench/out`` that
+ is not always where it ran: 54 runs are reachable through a symlink in another
+ battery's cells. The deepest scan root containing the resolved path wins; a run
+ linked in from outside the scanned tree keeps its own :func:`battery_root_for`.
+ """
+ owners = [r for r in roots if resolved.is_relative_to(r)]
+ if owners:
+ return run_id_for(max(owners, key=lambda r: len(r.parts)), resolved)
+ return run_id_for(battery_root_for(resolved), resolved)
+
+
+def _found_runs(scan: Path, report: Report) -> Iterator[FoundRun]:
+ """Every run under one scan root — or ``scan`` itself when it IS a run directory.
+
+ ``iter_runs`` searches strictly BELOW its argument, so a lone run directory (the
+ documented single-run input) yields nothing there and the export silently reported
+ zero rows. It is read here instead, against the battery root its path sits in.
+ """
+ if is_run_dir(scan):
+ ws = Workspace(scan)
+ try:
+ rec = load_record(ws)
+ except RecordError:
+ report.drops["unreadable_record"] += 1
+ return
+ yield FoundRun(ws, rec, run_id_for(battery_root_for(ws.root), ws.root))
+ return
+ found = iter_runs(scan, on_error=lambda _p, _e: report.drops.update(["unreadable_record"]))
+ try: # iter_runs is a generator: it raises for an empty battery on the first step
+ found = itertools.chain([next(found)], found)
+ except FileNotFoundError:
+ report.drops["empty_battery"] += 1
+ return
+ except StopIteration:
+ return
+ yield from found
def iter_rows(
@@ -274,26 +430,27 @@ def iter_rows(
"""Yield one row per exportable refine transition under ``root``, filling ``report``.
Every run and every round is accounted for: a run is exported once per resolved path
- (the symlinked cells of the recorded batteries make 54 runs reachable twice) and a
- transition that cannot be exported increments a named reason instead of vanishing.
+ (``bench/out``'s cross-battery symlinks make runs reachable twice), it is labelled
+ with the battery it physically lives in, and a child directory or transition that
+ cannot be exported increments a named reason instead of vanishing.
"""
+ roots, skipped = scan_roots(root)
+ report.skipped = [str(p) for p in skipped]
+ if skipped: # a Counter records a zero once touched, and "dropped: none" must stay true
+ report.drops["not_a_battery"] += len(skipped)
+ batteries = [r.resolve() for r in roots if not is_run_dir(r)]
seen: set[Path] = set()
- for scan in scan_roots(root):
+ for scan in roots:
report.roots.append(str(scan))
- found = iter_runs(scan, on_error=lambda _p, _e: report.drops.update(["unreadable_record"]))
- try: # iter_runs is a generator: it raises for an empty battery on the first step
- found = itertools.chain([next(found)], found)
- except FileNotFoundError:
- report.drops["empty_battery"] += 1
- continue
- except StopIteration:
- continue
- for ws, rec, run_id in found:
- resolved = ws.root.resolve()
+ for ws, rec, found_id in _found_runs(scan, report):
+ resolved = ws.root # Workspace resolves its root on construction
if resolved in seen:
report.drops["duplicate_run"] += 1
continue
seen.add(resolved)
+ run_id = physical_run_id(resolved, batteries, found_id)
+ if run_id.battery != found_id.battery:
+ report.aliases[f"{found_id.battery} -> {run_id.battery}"] += 1
report.runs += 1
yield from _run_rows(ws, rec, run_id, report, threshold=threshold, max_diff_bytes=max_diff_bytes)
@@ -317,6 +474,9 @@ def _run_rows(
if effective_judgment(prev) is None:
report.drops["missing_prev_judgment"] += 1
continue
+ # the RECORD's task list decides exportability: a round with no compiled task was
+ # never given a brief, while a missing prompt file only costs the row its
+ # per-session breakdown (transition_row then falls back to this same list)
if not cur.instructions:
report.drops["no_instructions"] += 1
continue
@@ -372,6 +532,10 @@ def scan_report(report: Report) -> str:
f"rounds seen: {sum(report.kinds.values())} "
f"({report.transitions} refine-kind; {by_kind})"]
lines += _table("dropped", report.drops, by_count=False) or ["dropped: none"]
+ if report.skipped:
+ lines += ["skipped (neither a run nor a battery):"] + [f" {p}" for p in report.skipped]
+ # not a drop: the run WAS exported, under the battery it physically lives in
+ lines += _table("reached through another battery's symlink", report.aliases, by_count=False)
return "\n".join(lines)
diff --git a/harness/codeverse/flywheel/_git.py b/harness/codeverse/flywheel/_git.py
index b4fe3ee0..5efd1103 100644
--- a/harness/codeverse/flywheel/_git.py
+++ b/harness/codeverse/flywheel/_git.py
@@ -3,6 +3,13 @@
The exporter / pairs builder must never touch the working tree of a run
(another process may be resuming it), so everything here goes through
``git archive`` / ``git ls-tree`` on the run's repository.
+
+Read-only is not the same as safe: a run's ``.git/config`` and ``.gitattributes``
+were writable by the agent, and git config can name a program to RUN. Every
+invocation therefore goes through the same sanitised argv + environment the
+workspace's own git uses (:data:`~codeverse.workspace.GIT_SAFE_FLAGS`,
+:func:`~codeverse.workspace.git_safe_env`), and every content-rendering command
+adds :data:`~codeverse.workspace.GIT_SAFE_DIFF_FLAGS`.
"""
from __future__ import annotations
@@ -12,10 +19,9 @@ import subprocess
import tarfile
from pathlib import Path
-from codeverse.workspace import Workspace
+from codeverse.workspace import GIT_SAFE_DIFF_FLAGS, GIT_SAFE_FLAGS, Workspace, git_safe_env
_GIT_TIMEOUT_S = 60
-_ENV = {"PATH": "/usr/bin:/bin:/usr/local/bin", "GIT_TERMINAL_PROMPT": "0"}
#: directories of a workspace that hold agent-authored code
CODE_ROOTS: tuple[str, ...] = ("src", "public")
@@ -29,7 +35,8 @@ class GitReadError(RuntimeError):
def _run(ws: Workspace, *args: str) -> subprocess.CompletedProcess[bytes]:
try:
proc = subprocess.run(
- ["git", *args], cwd=ws.root, capture_output=True, check=False, env=_ENV, timeout=_GIT_TIMEOUT_S
+ ["git", *GIT_SAFE_FLAGS, *args], cwd=ws.root, capture_output=True, check=False,
+ env=git_safe_env(), timeout=_GIT_TIMEOUT_S,
)
except subprocess.TimeoutExpired as e: # pragma: no cover - defensive
raise GitReadError(f"git {' '.join(args)} timed out in {ws.root}") from e
@@ -97,15 +104,12 @@ def diff_between(ws: Workspace, before: str, after: str, *, max_bytes: int | Non
"""Unified diff of the code roots between two commits: ``(text, total_bytes, truncated)``.
``total_bytes`` is what git actually produced, so a capped row still records the
- size it was capped from. Both commits are checked first because the useful shas
- are the ones recorded on the rounds, never ``HEAD`` — a finished run ends on a
- "restore best round rNN" commit — and a sha the repository no longer holds must
- fail loudly rather than diff against an empty tree.
+ size it was capped from. The useful shas are the ones recorded on the rounds,
+ never ``HEAD`` — a finished run ends on a "restore best round rNN" commit — and a
+ sha the repository no longer holds raises rather than diffing against an empty
+ tree: ``git diff`` itself refuses an unknown object, so no pre-check is needed.
"""
- for c in (before, after):
- if not commit_exists(ws, c):
- raise GitReadError(f"commit {c!r} not found in {ws.root}")
- raw = _run(ws, "diff", "--no-ext-diff", before, after, "--", *CODE_ROOTS).stdout
+ raw = _run(ws, "diff", *GIT_SAFE_DIFF_FLAGS, before, after, "--", *CODE_ROOTS).stdout
total = len(raw)
if max_bytes is not None and total > max_bytes:
head = raw[:max_bytes].decode("utf-8", errors="replace")
@@ -115,7 +119,7 @@ def diff_between(ws: Workspace, before: str, after: str, *, max_bytes: int | Non
def changed_files_between(ws: Workspace, before: str, after: str) -> list[str]:
"""Sorted code-root paths that differ between two commits."""
- out = _run(ws, "diff", "--no-ext-diff", "--name-only", "-z", before, after, "--", *CODE_ROOTS).stdout
+ out = _run(ws, "diff", *GIT_SAFE_DIFF_FLAGS, "--name-only", "-z", before, after, "--", *CODE_ROOTS).stdout
return sorted(p for p in out.decode("utf-8", errors="replace").split("\0") if p and _keep(p))
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.py
index ad553bc6..5b945a0e 100644
--- a/harness/codeverse/workspace.py
+++ b/harness/codeverse/workspace.py
@@ -56,8 +56,17 @@ _GITIGNORE_LINES = (
)
-#: prepended to every workspace git argv: an agent-planted hook / fsmonitor never runs.
-_GIT_SAFE_FLAGS = ("-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false")
+#: prepended to every git argv run against a run workspace: an agent-planted hook,
+#: fsmonitor or unnamed external diff driver never runs, and the GLOBAL attributes file
+#: cannot name one either. ``-c`` outranks ``.git/config``, so these hold even in a
+#: repository the agent has written to.
+GIT_SAFE_FLAGS = ("-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false",
+ "-c", "core.attributesFile=/dev/null", "-c", "diff.external=")
+#: added to every git command that RENDERS file content (diff / show / log -p). A
+#: NAMED driver — ``.gitattributes`` "*.bin diff=x" plus ``[diff "x"] textconv``/``command``
+#: in .git/config, both agent-writable — is not reachable by ``-c``, and ``--no-ext-diff``
+#: alone does not disable textconv: without ``--no-textconv`` that driver EXECUTES.
+GIT_SAFE_DIFF_FLAGS = ("--no-ext-diff", "--no-textconv")
#: local (.git/config) config that makes git EXECUTE a program. ``-c`` cannot override a
#: local ``filter.*`` / ``diff.*`` driver, so these are unset in place before every commit.
_GIT_EXEC_SECTIONS = ("filter", "diff", "alias", "gpg", "credential")
@@ -74,6 +83,15 @@ def _git_home() -> str:
return str(d)
+def git_safe_env(**extra: str) -> dict[str, str]:
+ """Environment for git in an agent-writable repository: no system or global config
+ (``.gitconfig`` written into the workspace is git's GLOBAL config when HOME is the
+ workspace), a fixed PATH, and no credential prompt. ``extra`` adds identity."""
+ return {"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": _git_home(),
+ "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1",
+ "GIT_TERMINAL_PROMPT": "0", **extra}
+
+
class WorkspaceGitError(subprocess.CalledProcessError):
"""A git command in a run workspace failed, carrying git's own explanation.
@@ -305,11 +323,9 @@ class Workspace:
with self._lock:
for attempt in range(4):
proc = subprocess.run(
- ["git", *_GIT_SAFE_FLAGS, *args], cwd=self.root, text=True, capture_output=True, check=False,
- env={"GIT_AUTHOR_NAME": "3dcv", "GIT_AUTHOR_EMAIL": "3dcv@local",
- "GIT_COMMITTER_NAME": "3dcv", "GIT_COMMITTER_EMAIL": "3dcv@local",
- "PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": _git_home(),
- "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"},
+ ["git", *GIT_SAFE_FLAGS, *args], cwd=self.root, text=True, capture_output=True, check=False,
+ env=git_safe_env(GIT_AUTHOR_NAME="3dcv", GIT_AUTHOR_EMAIL="3dcv@local",
+ GIT_COMMITTER_NAME="3dcv", GIT_COMMITTER_EMAIL="3dcv@local"),
)
if proc.returncode == 0 or "index.lock" not in (proc.stderr or ""):
break
@@ -379,12 +395,12 @@ class Workspace:
def changed_files(self, since: str | None = None) -> list[FileChange]:
"""Files changed vs ``since`` (a commit) or vs HEAD (uncommitted work)."""
with self._lock: # add -N + two diffs are one unit: a sibling commit between them mislabels a status
- self._sanitise_git_config() # `add`/`diff` apply clean + textconv drivers
+ self._sanitise_git_config() # `add` applies clean filters; -c cannot unset a local one
self._git("add", "-A", "-N") # register untracked so they show up in diff
- args = ["diff", "--numstat", "--diff-filter=ADM"] + ([since] if since else ["HEAD"])
+ args = ["diff", *GIT_SAFE_DIFF_FLAGS, "--numstat", "--diff-filter=ADM"] + ([since] if since else ["HEAD"])
out = self._git(*args).stdout
status = {}
- for line in self._git("diff", "--name-status", since or "HEAD").stdout.splitlines():
+ for line in self._git("diff", *GIT_SAFE_DIFF_FLAGS, "--name-status", since or "HEAD").stdout.splitlines():
if "\t" in line:
st, path = line.split("\t", 1)
status[path] = {"A": "added", "D": "deleted"}.get(st[0], "modified")
diff --git a/harness/tests/flywheel_cli/test_flywheel.py b/harness/tests/flywheel_cli/test_flywheel.py
index 56083e7f..6275f65c 100644
--- a/harness/tests/flywheel_cli/test_flywheel.py
+++ b/harness/tests/flywheel_cli/test_flywheel.py
@@ -86,6 +86,48 @@ def test_git_tree_at_commit(fake_run):
_git.read_tree_at(ws, "deadbeef")
+def test_a_planted_diff_driver_never_runs(fake_run, tmp_path):
+ """``.git/config`` and ``.gitattributes`` in a run workspace were writable by the
+ agent, and a git diff driver is a program git RUNS.
+
+ ``--no-ext-diff`` does not cover textconv: with only that flag, a ``.gitattributes``
+ entry ``*.bin diff=evil`` plus ``[diff "evil"] textconv = sh -c …`` executes the
+ command while the exporter merely reads the repository (reproduced on git 2.34).
+ ``-c`` cannot unset a LOCAL named driver, so the flag is the fix, not the config.
+ """
+ ws, _rec = fake_run
+ fired = tmp_path / "fired"
+ payload = f"sh -c 'echo pwned >> {fired}; cat'"
+ (ws.src / "blob.bin").write_bytes(b"\x00\x01before\n")
+ before = ws.commit("binary before")
+ (ws.src / "blob.bin").write_bytes(b"\x00\x01after\n")
+ after = ws.commit("binary after")
+ # planted AFTER the last commit: ws.commit() sanitises .git/config on the way past
+ (ws.root / ".gitattributes").write_text("*.bin diff=evil\n*.py diff=evil\n")
+ for key in ("textconv", "command"):
+ ws._git("config", "--local", f"diff.evil.{key}", payload)
+ ws._git("config", "--local", "diff.external", payload)
+
+ text, _total, _truncated = _git.diff_between(ws, before, after)
+ files = _git.changed_files_between(ws, before, after)
+
+ assert not fired.exists(), f"a planted diff driver ran: {fired.read_text()!r}"
+ assert files == ["src/blob.bin"] and "src/blob.bin" in text
+
+
+def test_diff_between_refuses_a_sha_the_repo_does_not_have(fake_run):
+ """The recorded round shas are the only usable handles, and one the repository no
+ longer holds must raise rather than diff against an empty tree."""
+ ws, rec = fake_run
+ good = rec.rounds[1].commit
+ with pytest.raises(_git.GitReadError):
+ _git.diff_between(ws, "0" * 40, good)
+ with pytest.raises(_git.GitReadError):
+ _git.diff_between(ws, good, "0" * 40)
+ with pytest.raises(_git.GitReadError):
+ _git.changed_files_between(ws, good, "0" * 40)
+
+
# --------------------------------------------------------------------------- export + pack
diff --git a/harness/tests/flywheel_cli/test_refine_pairs.py b/harness/tests/flywheel_cli/test_refine_pairs.py
index 481954af..b776d539 100644
--- a/harness/tests/flywheel_cli/test_refine_pairs.py
+++ b/harness/tests/flywheel_cli/test_refine_pairs.py
@@ -3,9 +3,10 @@
Every case builds a corpus in the real on-disk layout — ``<root>/<battery>/runs/<slug>``,
a git repo with two commits and two round records — because the exporter's whole job is
to survive that layout: the recorded round shas rather than ``HEAD`` (a finished run ends
-on a "restore best round rNN" commit), one row per resolved run path (a battery's
-symlinked cells make runs reachable twice), and a named reason for every transition it
-cannot export.
+on a "restore best round rNN" commit), one row per resolved run path labelled with the
+battery it physically lives in (``bench/out``'s cell symlinks point ACROSS batteries), the
+brief the agent sessions were really handed rather than the pre-grouping task list, and a
+named reason for every run and transition it cannot export.
"""
from __future__ import annotations
@@ -19,6 +20,7 @@ import pytest
from bench.refine_pairs import (
DROP_REASONS,
Report,
+ changes_block,
export,
iter_rows,
main,
@@ -27,9 +29,10 @@ from bench.refine_pairs import (
scan_roots,
transition_row,
)
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.contracts.run import RunRecord
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Judgment, Severity
+from codeverse.contracts.run import RoundRecord, RunRecord
from codeverse.flywheel.record import load_record, run_id_for
+from codeverse.judges.rubrics import is_degraded
from codeverse.workspace import Workspace
from tests.flywheel_cli.conftest import make_fake_run
@@ -40,6 +43,28 @@ def _corpus(root: Path, *, battery: str = "batt", slug: str = "chair") -> Worksp
return ws
+def _degraded() -> Judgment:
+ """What ``judges.rubrics.degraded_judgment`` writes when the judge call fails: a
+ 0.0 verdict flagged both ways. ``is_degraded`` below keeps this honest."""
+ return Judgment(rubric="static_object_v1", judge_backend="gemini:gemini-3.1-pro-preview",
+ scores={"fidelity": 0.0}, overall=0.0, passed=False,
+ summary="judge_error: 503 from the judge", n_samples=0,
+ raw=json.dumps({"status": "degraded", "error": "503"}))
+
+
+def _prompt(ws: Workspace, session: str, round_index: int, lines: list[str]) -> None:
+ """One session's prompt file, in the shape ``agents.cli_common.begin_session`` writes
+ and ``prompts/tracks/refine_object.j2`` renders."""
+ d = ws.root / "trajectories" / f"{session}_r{round_index:02d}"
+ d.mkdir(parents=True, exist_ok=True)
+ numbered = "\n".join(f"{i}. {ln}" for i, ln in enumerate(lines, 1))
+ (d / "prompt.md").write_text(
+ f"<!-- system -->\nYou are a Blender author\n\n<!-- prompt -->\n"
+ f"# Refine `Chair` — round {round_index}\n\nThe object already builds.\n\n"
+ f"## Changes to make (in priority order; `[gate/...]` items are hard failures — fix them first)\n\n"
+ f"{numbered}\n\nTargets: Leg\n\n## What the judge saw\n1. not an instruction\n")
+
+
def _patch(ws: Workspace, edit: Callable[[RunRecord], None]) -> RunRecord:
rec = load_record(ws)
edit(rec)
@@ -94,8 +119,21 @@ def test_scan_roots_picks_batteries_not_the_parent(tmp_path):
root = tmp_path / "out"
_corpus(root, battery="batt_a")
_corpus(root, battery="batt_b")
- assert scan_roots(root) == [root / "batt_a", root / "batt_b"]
- assert scan_roots(root / "batt_a") == [root / "batt_a"]
+ (root / "merged_report").mkdir() # neither a run nor a battery: reported, not silent
+ assert scan_roots(root) == ([root / "batt_a", root / "batt_b"], [root / "merged_report"])
+ assert scan_roots(root / "batt_a") == ([root / "batt_a"], [])
+
+
+def test_changes_block_reads_the_numbered_list_and_stops_at_the_next_section():
+ """The refine templates number ``compact_instructions``' lines and follow them with
+ ``Targets:``; a numbered line in a LATER section is not an instruction."""
+ prompt = ("# Refine `Chair` — round 1\n\n"
+ "## Changes to make (in priority order)\n\n"
+ "1. Leg: (a) [judge/geometry] thicken\n\n2. [judge/material] Seat: oak,\n quarter-sawn\n\n"
+ "Targets: Leg, Seat\n\n## What the judge saw\n1. legs too thin\n")
+ assert changes_block(prompt) == ["Leg: (a) [judge/geometry] thicken",
+ "[judge/material] Seat: oak, quarter-sawn"]
+ assert changes_block("# Rebuild `Chair`\n\n1. fix the syntax error\n") == []
# --------------------------------------------------------------------------- rows
@@ -110,7 +148,7 @@ def test_row_carries_brief_diff_and_delta(tmp_path):
# the brief is the PREVIOUS round's verdict, the change is this round's
assert [i["target"] for i in row["issues"]] == ["Leg"]
assert [i["instruction"] for i in row["improvement_plan"]] == ["thicken the legs", "add a back rail"]
- assert row["instructions"] == ["thicken the legs"]
+ assert row["refine_tasks"] == ["thicken the legs"]
assert row["before"]["files"] == ["src/model.py"]
assert row["after"]["files"] == ["src/model.py", "src/parts/leg.py"]
assert row["changed_files"] == ["src/model.py", "src/parts/leg.py"]
@@ -149,11 +187,197 @@ def test_gate_error_findings_carry_fix_hints(tmp_path):
def test_diff_is_capped_and_says_so(tmp_path):
+ """The cap must actually cut the text: a row that carries the WHOLE diff and merely
+ says "truncated" is the failure the cap exists to prevent."""
root = tmp_path / "out"
_corpus(root)
(row,), _ = _rows(root, max_diff_bytes=120)
assert row["diff_truncated"] and row["diff_max_bytes"] == 120
assert row["diff_bytes"] > 120 and "[truncated" in row["diff"]
+ head, marker, _rest = row["diff"].partition("\n... [truncated ")
+ assert marker and len(head.encode()) == 120, "the kept head is exactly the cap"
+ assert f"{row['diff_bytes'] - 120} bytes" in row["diff"], "and it names what it dropped"
+ (whole,), _ = _rows(root) # the same diff uncapped: same prefix, more of it
+ assert whole["diff"].startswith(head) and len(whole["diff"]) > len(head)
+ assert not whole["diff_truncated"] and whole["diff_bytes"] == row["diff_bytes"]
+
+
+def test_diff_lines_count_content_not_file_headers(tmp_path):
+ """``+++``/``---`` are one pair per changed FILE. Counting them inflates every row's
+ churn by the number of files the round touched — the label a preference model reads."""
+ root = tmp_path / "out"
+ _corpus(root)
+ (row,), _ = _rows(root)
+ # round 1 rewrites 3 of the 4 lines of src/model.py and adds the 1-line src/parts/leg.py
+ assert (row["diff_added"], row["diff_removed"]) == (4, 3)
+ naive_added = sum(1 for ln in row["diff"].splitlines() if ln.startswith("+"))
+ naive_removed = sum(1 for ln in row["diff"].splitlines() if ln.startswith("-"))
+ assert (naive_added, naive_removed) == (6, 5), "two file header pairs sit in that diff"
+
+
+def test_changed_files_are_the_ones_this_round_touched(tmp_path):
+ """Per-file attribution is the round's OWN diff, not the file list at its commit: a
+ round that edits one of two files must not be recorded as having rewritten both."""
+ root = tmp_path / "out"
+ ws = _corpus(root)
+ (ws.src / "parts" / "leg.py").write_text("LEG = 0.06\n")
+ commit = ws.commit("round 2")
+ _patch(ws, lambda rec: rec.rounds.append(RoundRecord(
+ index=2, kind="refine", commit=commit, instructions=["thicken the legs again"],
+ build=BuildResult(ok=True, language="blender"), judgment=rec.rounds[1].judgment)))
+ rows, _ = _rows(root)
+ second = rows[-1]
+ assert second["round"] == 2
+ assert second["changed_files"] == ["src/parts/leg.py"]
+ assert second["after"]["files"] == ["src/model.py", "src/parts/leg.py"], "both exist, one changed"
+ assert "src/model.py" not in second["diff"]
+
+
+def test_only_refine_kind_rounds_are_transitions(tmp_path):
+ """A texture pass edits ``src/`` and has everything a row needs — a judged
+ predecessor, a commit, instructions. It is still not a refine transition: nothing
+ derived it from a verdict, so it is a round SEEN and a row not written, with no drop
+ to explain (the drop reasons are for transitions that should have been exportable)."""
+ root = tmp_path / "out"
+ ws = _corpus(root)
+ (ws.src / "model.py").write_text("# textured\nimport bpy\n")
+ commit = ws.commit("texture pass")
+ _patch(ws, lambda rec: rec.rounds.append(RoundRecord(
+ index=2, kind="texture", commit=commit, instructions=["bake a quarter-sawn oak albedo"],
+ build=BuildResult(ok=True, language="blender"))))
+ rows, report = _rows(root)
+ assert [r["round_kind"] for r in rows] == ["refine"]
+ assert report.kinds == {"baseline": 1, "refine": 1, "texture": 1}
+ assert report.transitions == 1 and not report.drops
+
+
+def test_a_degraded_verdict_is_unscored_not_a_zero(tmp_path):
+ """A judge outage writes a 0.0 ``judge_error:`` Judgment. Read as a score it turns a
+ fine round into the corpus's worst regression (0.0 - 0.55), and the sign of that row
+ is exactly what the pairs are for."""
+ assert is_degraded(_degraded()), "the fixture must stay the real degraded shape"
+ root = tmp_path / "out"
+ ws = _corpus(root)
+ _patch(ws, lambda rec: setattr(rec.rounds[1], "judgment", _degraded()))
+ (row,), report = _rows(root)
+ assert row["score_before"] == 0.55
+ assert row["score_after"] is None and row["score_delta"] is None
+ assert row["outcome"] == "unscored"
+ assert row["after"]["score"] is None and row["after"]["passed"] is None
+ assert not report.drops
+
+
+def test_a_degraded_previous_verdict_drops_the_transition(tmp_path):
+ """The brief is the PREVIOUS round's verdict. A judge outage wrote no verdict, so
+ there is no brief — and a 0.0 one would make every issue list empty on purpose."""
+ root = tmp_path / "out"
+ ws = _corpus(root)
+ _patch(ws, lambda rec: setattr(rec.rounds[0], "judgment", _degraded()))
+ rows, report = _rows(root)
+ assert rows == [] and dict(report.drops) == {"missing_prev_judgment": 1}
+
+
+# --------------------------------------------------------------------------- instructions
+def test_instruction_lines_are_the_ones_the_sessions_were_handed(tmp_path):
+ """``RoundRecord.instructions`` is the COMPILED task list; each file-disjoint group's
+ agent session is handed its own ``compact_instructions`` output, folded by target and
+ capped. The two differ for 167 of the corpus's 205 transitions, so the row carries
+ both and says which one ``instruction_tasks`` was parsed from."""
+ root = tmp_path / "out"
+ ws = _corpus(root)
+ compiled = ["[judge/geometry] Leg_0: thicken it (files: src/parts/leg.py)",
+ "[judge/geometry] Leg_1: thicken it (files: src/parts/leg.py)",
+ "[judge/material] Seat: quarter-sawn oak (files: src/model.py)"]
+ _patch(ws, lambda rec: setattr(rec.rounds[1], "instructions", compiled))
+ leg = "Leg: (a) [judge/geometry] thicken it; (b) [Leg_1] [judge/geometry] thicken it (files: src/parts/leg.py)"
+ seat = "[judge/material] Seat: quarter-sawn oak (files: src/model.py)"
+ _prompt(ws, "refine_leg", 1, [leg])
+ _prompt(ws, "refine_seat", 1, [seat])
+
+ (row,), _ = _rows(root)
+ assert row["instruction_source"] == "prompt"
+ assert [s["session"] for s in row["sent_instructions"]] == ["refine_leg", "refine_seat"]
+ assert row["instruction_lines"] == [leg, seat]
+ assert row["refine_tasks"] == compiled
+ assert row["instruction_lines"] != row["refine_tasks"]
+ assert [t["target"] for t in row["instruction_tasks"]] == ["Leg", "Leg_1", "Seat"]
+
+
+def test_a_retry_session_is_not_a_second_brief(tmp_path):
+ """``<label>.a2`` is the SAME brief re-sent after a silent bail (``_session_label``);
+ counting it twice would double every task in the row."""
+ root = tmp_path / "out"
+ ws = _corpus(root)
+ line = "Leg: (a) [judge/geometry] thicken it (files: src/parts/leg.py)"
+ _prompt(ws, "refine", 1, [line])
+ _prompt(ws, "refine.a2", 1, [line])
+ (row,), _ = _rows(root)
+ assert row["instruction_lines"] == [line]
+ assert [s["session"] for s in row["sent_instructions"]] == ["refine"]
+
+
+def test_instruction_lines_fall_back_to_the_record_when_no_prompt_survives(tmp_path):
+ """10 of the corpus's 205 transitions have no prompt file left. The compiled task
+ list is then all there is, and the row says so rather than shipping an empty brief."""
+ root = tmp_path / "out"
+ _corpus(root)
+ (row,), _ = _rows(root)
+ assert row["sent_instructions"] == [] and row["instruction_source"] == "record"
+ assert row["instruction_lines"] == row["refine_tasks"] == ["thicken the legs"]
+
+
+# --------------------------------------------------------------------------- identity
+def test_a_cross_battery_alias_is_labelled_with_the_physical_battery(tmp_path):
+ """``bench/out``'s aliases point ACROSS batteries (``compare_v4_calm/cells/*`` is a
+ symlink into ``compare_v4`` and ``compare_v4_harness_calm``) and the alias sorts
+ FIRST, so labelling by the root that reached a run first credits it to a battery it
+ never ran in. The label is the battery the run physically lives in; the alias is
+ reported, not lost."""
+ root = tmp_path / "out"
+ ws = _corpus(root, battery="zz_physical", slug="chair")
+ alias = root / "aa_alias" / "runs"
+ alias.mkdir(parents=True)
+ (alias / "chair").symlink_to(ws.root, target_is_directory=True)
+
+ rows, report = _rows(root)
+ assert report.roots == [str(root / "aa_alias"), str(root / "zz_physical")]
+ assert [r["battery"] for r in rows] == ["zz_physical"]
+ assert rows[0]["run_dir"] == str(ws.root)
+ assert dict(report.drops) == {"duplicate_run": 1}
+ assert dict(report.aliases) == {"aa_alias -> zz_physical": 1}
+
+
+def test_a_single_run_directory_exports_with_the_identity_a_full_scan_gives_it(tmp_path):
+ """The documented one-run input. ``iter_runs`` searches strictly BELOW its argument,
+ so the run itself was invisible and the export reported zero rows as a success."""
+ root = tmp_path / "out"
+ ws = _corpus(root, battery="batt", slug="chair")
+ whole, _ = _rows(root)
+ alone, report = _rows(ws.root)
+ assert len(alone) == 1 and report.runs == 1 and not report.drops
+ assert (alone[0]["battery"], alone[0]["run"]) == ("batt", "chair")
+ assert alone[0] == whole[0]
+
+
+def test_a_single_nested_run_keeps_the_whole_battery_path(tmp_path):
+ """The same for the deepest layout, ``<battery>/arms/<arm>/cells/<cell>/<slug>``,
+ where the battery is the OUTERMOST marker on the path: stopping at the first one up
+ (``<arm>``, which owns a ``cells/``) labels the run with its arm instead."""
+ root = tmp_path / "out"
+ ws, _ = make_fake_run(root / "batt" / "arms" / "control" / "cells" / "chair_cell", "harness_arm")
+ whole, _ = _rows(root)
+ (row,), report = _rows(ws.root)
+ assert (row["battery"], row["arm"], row["cell"]) == ("batt", "control", "chair_cell")
+ assert row["run"] == "control__chair_cell__harness_arm"
+ assert report.roots == [str(ws.root)]
+ assert row == whole[0]
+
+
+def test_main_accepts_one_run_directory(tmp_path, capsys):
+ root = tmp_path / "out"
+ ws = _corpus(root)
+ assert main([str(ws.root), "--summary"]) == 0
+ assert "1 row(s) from 1 run(s) in 1 root(s)" in capsys.readouterr().out
def test_diff_uses_the_recorded_shas_not_head(tmp_path):
@@ -187,6 +411,11 @@ def test_transition_row_is_callable_on_one_run(tmp_path):
# --------------------------------------------------------------------------- drops
+def _drop_not_a_battery(root: Path) -> None:
+ _corpus(root)
+ (root / "merged_report").mkdir() # bench/out holds three of these
+
+
def _drop_empty_battery(root: Path) -> None:
(root / "batt" / "cells").mkdir(parents=True)
@@ -229,6 +458,7 @@ def _drop_empty_diff(root: Path) -> None:
#: one corpus per reason; the parametrisation below fails loudly if a reason has none
DROP_CORPUS: dict[str, Callable[[Path], None]] = {
+ "not_a_battery": _drop_not_a_battery,
"empty_battery": _drop_empty_battery,
"unreadable_record": _drop_unreadable_record,
"duplicate_run": _drop_duplicate_run,
@@ -239,8 +469,8 @@ DROP_CORPUS: dict[str, Callable[[Path], None]] = {
"git_read_failed": _drop_git_read_failed,
"empty_diff": _drop_empty_diff,
}
-#: the two run-level drops leave the run itself exportable
-KEEPS_ROW = {"unreadable_record", "duplicate_run"}
+#: the scan-level drops leave the run itself exportable
+KEEPS_ROW = {"not_a_battery", "unreadable_record", "duplicate_run"}
@pytest.mark.parametrize("reason", DROP_REASONS)
@@ -252,6 +482,19 @@ def test_every_drop_reason_is_counted(tmp_path, reason):
assert len(rows) == report.rows == (1 if reason in KEEPS_ROW else 0)
+def test_a_skipped_child_is_named_in_the_report(tmp_path, capsys):
+ """Counting it is half the job: "every drop is counted" has to say WHICH directory
+ was passed over, or a mistyped battery name reads as an empty corpus."""
+ from bench.refine_pairs import scan_report
+
+ root = tmp_path / "out"
+ _drop_not_a_battery(root)
+ _, report = _rows(root)
+ assert report.skipped == [str(root / "merged_report")]
+ assert str(root / "merged_report") in scan_report(report)
+ assert "not_a_battery" in scan_report(report)
+
+
def test_drop_corpus_covers_every_declared_reason():
assert set(DROP_CORPUS) == set(DROP_REASONS)