Official Codebase of 3DCodeVerse
Python
flywheel: export refine rounds as (brief -> diff -> delta) training pairs
Ziyao Zeng92ed4a6f68d4
diff --git a/harness/bench/refine_pairs.py b/harness/bench/refine_pairs.pynew file mode 100644index 00000000..21b8935b--- /dev/null+++ b/harness/bench/refine_pairs.py@@ -0,0 +1,421 @@+"""Refine rounds as training pairs: what the round was TOLD, what it CHANGED, what it SCORED.++``codeverse/flywheel/pairs.py`` exports whole code trees per round and never looks at+what asked for the change, so a refine round arrives as two 30 KB files with no cause.+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++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"+commit, and looking a commit up by message is ambiguous (``r01 refine`` also matches+``r01 refine: generated``).++ python bench/refine_pairs.py bench/out --out refine_pairs.jsonl --summary+ python bench/refine_pairs.py bench/out/aa_articulated --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.+"""++from __future__ import annotations++import argparse+import itertools+import json+import re+import statistics+import sys+from collections import Counter+from collections.abc import Iterator, Sequence+from dataclasses import dataclass, field+from pathlib import Path+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.flywheel import _git # noqa: E402+from codeverse.flywheel.quality import prompt_hash # noqa: E402+from codeverse.flywheel.record import ( # noqa: E402+ BATTERY_MARKERS,+ effective_judgment,+ is_run_dir,+ iter_runs,+)+from codeverse.workspace import Workspace # noqa: E402++SCHEMA_VERSION = 1++#: round kinds that are a refine transition — a round handed instructions derived from+#: the previous round's verdict, and the only three the recorded corpus holds.+#: ``baseline`` has no predecessor, and ``texture`` / ``asset:*`` rounds are driven by+#: the texture pass rather than by a judgment.+REFINE_KINDS: tuple[str, ...] = ("refine", "rewrite", "detail")++#: cap on the inlined diff. The corpus's largest transition diff is ~62 KB, so nothing+#: recorded today is truncated; the cap only stops a pathological row from eating a+#: dataset, and every row records it next to the pre-cap size.+MAX_DIFF_BYTES = 200_000++#: |Δscore| below which a round counts as ``unchanged``. Same 0.05 the flywheel's+#: preference pairs already use as "a real difference" (``flywheel/pairs.build_pairs``).+OUTCOME_THRESHOLD = 0.05++DROP_REASONS: tuple[str, ...] = (+ "empty_battery",+ "unreadable_record",+ "duplicate_run",+ "missing_predecessor",+ "missing_commit",+ "missing_prev_judgment",+ "no_instructions",+ "git_read_failed",+ "empty_diff",+)+++# --------------------------------------------------------------------------- instructions+_FILES_RE = re.compile(r"\s*\(files:\s*(?P<files>[^)]*)\)\s*$")+_HEAD_RE = re.compile(r"^\[(?P<source>[^/\]]+)/(?P<kind>[^\]]+)\]\s*(?P<rest>.*)$", re.S)+_TARGET_RE = re.compile(r"[A-Za-z0-9_.:+-]{1,64}")+_BULLET_SPLIT_RE = re.compile(r";\s+(?=\([a-z]\)\s)")+# the optional instance override is ``[Leg_1]``; the ``/`` keeps it from swallowing the+# ``[source/kind]`` head that follows it+_BULLET_RE = re.compile(r"^\((?P<letter>[a-z])\)\s*(?:\[(?P<target>[^\]/]+)\]\s*)?(?P<rest>.*)$", re.S)+++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 parse_instruction(line: str) -> list[dict[str, Any]]:+ """The task(s) encoded in one recorded instruction line.++ ``orchestrator.compact_instructions`` emits three shapes and the corpus holds all+ three: a single ``RefineTask.line()`` (``[source/kind] target: text (files: a, b)``),+ the grouped form (``target: (a) [source/kind] text; (b) …``) and — detail rounds — a+ bare sentence. A line that matches none of them still yields one task carrying its+ whole text, so no instruction is silently lost; the target prefix is only honoured+ when it is a single bare token, or a sentence's own colon would be read as one.+ """+ raw = line.strip()+ files: list[str] = []+ if (m := _FILES_RE.search(raw)) is not None:+ files = [f.strip() for f in m.group("files").split(",") if f.strip()]+ raw = raw[: m.start()].rstrip()+ if (head := _HEAD_RE.match(raw)) is not None:+ target, sep, text = head.group("rest").partition(": ")+ if not sep:+ target, text = "overall", head.group("rest")+ return [_task(head.group("source"), head.group("kind"), target, text, files)]+ target, sep, rest = raw.partition(": ")+ if not sep or _TARGET_RE.fullmatch(target) is None:+ return [_task("", "", "", raw, files)]+ bullets = _BULLET_SPLIT_RE.split(rest)+ if _BULLET_RE.match(bullets[0]) is None:+ return [_task("", "", target, rest, files)]+ out: list[dict[str, Any]] = []+ for b in bullets:+ bm = _BULLET_RE.match(b)+ if bm is None:+ out.append(_task("", "", target, b, files))+ continue+ who, inner = bm.group("target") or target, bm.group("rest")+ if (hm := _HEAD_RE.match(inner)) is not None:+ out.append(_task(hm.group("source"), hm.group("kind"), who, hm.group("rest"), files))+ else:+ out.append(_task("", "", who, inner, files))+ return out+++# --------------------------------------------------------------------------- rows+def outcome_label(delta: float | None, *, threshold: float = OUTCOME_THRESHOLD) -> str:+ """``improved`` / ``regressed`` / ``unchanged`` by ``threshold``; ``unscored`` when+ either side has no usable verdict (a degraded judge outage is *not* a 0.0)."""+ if delta is None:+ return "unscored"+ if delta > threshold:+ return "improved"+ if delta < -threshold:+ return "regressed"+ return "unchanged"+++def _gate_errors(rnd: RoundRecord) -> list[dict[str, Any]]:+ """The ERROR findings of a round's gates — the half of the refine brief the judge+ did not write. ``fix_hint`` is what ``build_refine_instructions`` copies verbatim."""+ return [{"gate": g.gate, "target": f.target or "", "message": f.message,+ "fix_hint": f.fix_hint, "data": f.data}+ for g in rnd.gates for f in g.errors]+++def _side(rnd: RoundRecord, files: list[str]) -> dict[str, Any]:+ j = effective_judgment(rnd)+ return {+ "round": rnd.index,+ "kind": rnd.kind,+ "commit": rnd.commit,+ "score": j.overall if j else None,+ "passed": j.passed if j else None,+ "build_ok": None if rnd.build is None else rnd.build.ok,+ "gate_errors": sum(len(g.errors) for g in rnd.gates),+ "files": files,+ }+++def _diff_lines(text: str) -> tuple[int, int]:+ """(added, removed) body lines of a unified diff — the ``+++``/``---`` headers are+ file markers, not content, and would otherwise count once per changed file."""+ added = removed = 0+ for ln in text.splitlines():+ if ln.startswith("+") and not ln.startswith("+++"):+ added += 1+ elif ln.startswith("-") and not ln.startswith("---"):+ removed += 1+ return added, removed+++def transition_row(+ ws: Workspace, rec: RunRecord, run_id: RunId, prev: RoundRecord, cur: RoundRecord,+ *, threshold: float = OUTCOME_THRESHOLD, max_diff_bytes: int = MAX_DIFF_BYTES,+ files_cache: dict[str, list[str]] | None = None,+) -> dict[str, Any]:+ """One training row for the transition ``prev`` → ``cur``. Raises+ :class:`~codeverse.flywheel._git.GitReadError` when either commit is unreadable."""+ cache = files_cache if files_cache is not None else {}+ for c in (prev.commit, cur.commit):+ if c not in cache:+ cache[c] = _git.list_files_at(ws, c)+ diff, diff_bytes, truncated = _git.diff_between(ws, prev.commit, cur.commit, max_bytes=max_diff_bytes)+ 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)+ return {+ "schema_version": SCHEMA_VERSION,+ "battery": run_id.battery,+ "run": run_id.slug,+ "run_dir": str(ws.root),+ "cell": run_id.cell,+ "arm": run_id.arm,+ "prompt_id": rec.spec.id,+ "prompt": rec.spec.prompt,+ "prompt_hash": prompt_hash(rec.spec.prompt),+ "track": rec.spec.track.value,+ "language": rec.spec.language.value,+ "generator": rec.spec.backends.generator,+ "agent_backend": cur.agent_backend,+ "round": cur.index,+ "round_kind": cur.kind,+ "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)],+ "diff": diff,+ "diff_bytes": diff_bytes,+ "diff_added": added,+ "diff_removed": removed,+ "diff_truncated": truncated,+ "diff_max_bytes": max_diff_bytes,+ "changed_files": _git.changed_files_between(ws, prev.commit, cur.commit),+ "before": _side(prev, cache[prev.commit]),+ "after": _side(cur, cache[cur.commit]),+ "score_before": pj.overall if pj else None,+ "score_after": cj.overall if cj else None,+ "score_delta": delta,+ "outcome": outcome_label(delta, threshold=threshold),+ "outcome_threshold": threshold,+ }+++# --------------------------------------------------------------------------- scan+@dataclass+class Report:+ """What one export saw: totals, named drops, and a digest per written row."""++ roots: list[str] = field(default_factory=list)+ runs: int = 0+ kinds: Counter[str] = field(default_factory=Counter)+ drops: Counter[str] = field(default_factory=Counter)+ stats: list[dict[str, Any]] = field(default_factory=list)++ @property+ def rows(self) -> int:+ return len(self.stats)++ @property+ def transitions(self) -> int:+ """Refine-kind rounds seen — rows plus every per-transition drop."""+ 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."""+ if is_run_dir(root) or any((root / m).is_dir() for m in BATTERY_MARKERS):+ 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]+++def iter_rows(+ root: Path, report: Report, *, threshold: float = OUTCOME_THRESHOLD,+ max_diff_bytes: int = MAX_DIFF_BYTES,+) -> Iterator[dict[str, Any]]:+ """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.+ """+ seen: set[Path] = set()+ for scan in scan_roots(root):+ 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()+ if resolved in seen:+ report.drops["duplicate_run"] += 1+ continue+ seen.add(resolved)+ report.runs += 1+ yield from _run_rows(ws, rec, run_id, report, threshold=threshold, max_diff_bytes=max_diff_bytes)+++def _run_rows(+ ws: Workspace, rec: RunRecord, run_id: RunId, report: Report, *, threshold: float, max_diff_bytes: int+) -> Iterator[dict[str, Any]]:+ by_index = {r.index: r for r in rec.rounds}+ files_cache: dict[str, list[str]] = {}+ for cur in rec.rounds:+ report.kinds[cur.kind] += 1+ if cur.kind not in REFINE_KINDS:+ continue+ prev = by_index.get(cur.index - 1)+ if prev is None:+ report.drops["missing_predecessor"] += 1+ continue+ if not prev.commit or not cur.commit:+ report.drops["missing_commit"] += 1+ continue+ if effective_judgment(prev) is None:+ report.drops["missing_prev_judgment"] += 1+ continue+ if not cur.instructions:+ report.drops["no_instructions"] += 1+ continue+ try:+ row = transition_row(ws, rec, run_id, prev, cur, threshold=threshold,+ max_diff_bytes=max_diff_bytes, files_cache=files_cache)+ except _git.GitReadError:+ report.drops["git_read_failed"] += 1+ continue+ if not row["diff"].strip():+ report.drops["empty_diff"] += 1+ continue+ report.stats.append({"battery": row["battery"], "track": row["track"], "outcome": row["outcome"],+ "diff_bytes": row["diff_bytes"], "diff_added": row["diff_added"],+ "diff_removed": row["diff_removed"]})+ yield row+++def export(+ root: Path, out: Path | None, *, threshold: float = OUTCOME_THRESHOLD,+ max_diff_bytes: int = MAX_DIFF_BYTES,+) -> Report:+ """Write the rows under ``root`` as JSONL to ``out`` (``None`` = count only)."""+ report = Report()+ rows = iter_rows(root, report, threshold=threshold, max_diff_bytes=max_diff_bytes)+ if out is None:+ for _ in rows:+ pass+ return report+ out.parent.mkdir(parents=True, exist_ok=True)+ tmp = out.with_suffix(out.suffix + ".tmp")+ with tmp.open("w") as fh:+ for row in rows:+ fh.write(json.dumps(row, ensure_ascii=False) + "\n")+ tmp.replace(out)+ return report+++# --------------------------------------------------------------------------- report+def _table(title: str, counts: Counter[str], *, by_count: bool = True) -> list[str]:+ if not counts:+ return []+ items = counts.most_common() if by_count else sorted(counts.items())+ width = max(len(k) for k, _ in items)+ return [f"{title}:"] + [f" {k:<{width}} {n:>5}" for k, n in items]+++def scan_report(report: Report) -> str:+ """Totals + every drop reason. Printed always: a truncated export must never look+ like a small corpus."""+ by_kind = ", ".join(f"{n} {k}" for k, n in sorted(report.kinds.items())) or "none"+ lines = [f"{report.rows} row(s) from {report.runs} run(s) in {len(report.roots)} root(s)",+ 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"]+ return "\n".join(lines)+++def summary_report(report: Report, *, threshold: float = OUTCOME_THRESHOLD) -> str:+ """Counts per battery / track / outcome, and how big the diffs are."""+ if not report.stats:+ return "no rows to summarise"+ lines = _table("rows per battery", Counter(s["battery"] for s in report.stats))+ lines += [""] + _table("rows per track", Counter(s["track"] for s in report.stats))+ lines += [""] + _table(f"rows per outcome (|delta| > {threshold})",+ Counter(s["outcome"] for s in report.stats))+ sizes = sorted(s["diff_bytes"] for s in report.stats)+ churn = sorted(s["diff_added"] + s["diff_removed"] for s in report.stats)+ lines += ["", f"diff size: median {int(statistics.median(sizes))} bytes "+ f"(min {sizes[0]}, max {sizes[-1]}); "+ f"median {int(statistics.median(churn))} changed lines"]+ return "\n".join(lines)+++def main(argv: Sequence[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("root", type=Path, help="directory of batteries, a battery, a runs dir or one run")+ ap.add_argument("--out", type=Path, help="write the rows here as JSONL")+ ap.add_argument("--summary", action="store_true", help="also print per-battery/track/outcome counts")+ ap.add_argument("--threshold", type=float, default=OUTCOME_THRESHOLD,+ help=f"|delta| above which a round improved/regressed (default {OUTCOME_THRESHOLD})")+ ap.add_argument("--max-diff-bytes", type=int, default=MAX_DIFF_BYTES,+ help=f"cap on the inlined diff, recorded on every row (default {MAX_DIFF_BYTES})")+ args = ap.parse_args(argv)++ if not args.root.is_dir():+ ap.error(f"{args.root} is not a directory")+ if args.out is None and not args.summary:+ ap.error("nothing to do: pass --out to write rows, --summary to print counts, or both")++ report = export(args.root, args.out, threshold=args.threshold, max_diff_bytes=args.max_diff_bytes)+ if args.out is not None:+ print(f"wrote {args.out}")+ print(scan_report(report))+ if args.summary:+ print()+ print(summary_report(report, threshold=args.threshold))+ return 0 if report.rows else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/harness/codeverse/flywheel/_git.py b/harness/codeverse/flywheel/_git.pyindex 39ab28e7..b4fe3ee0 100644--- a/harness/codeverse/flywheel/_git.py+++ b/harness/codeverse/flywheel/_git.py@@ -93,6 +93,32 @@ def read_tree_at(ws: Workspace, commit: str) -> dict[str, bytes]:return files+def diff_between(ws: Workspace, before: str, after: str, *, max_bytes: int | None = None) -> tuple[str, int, bool]:+ """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.+ """+ 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+ total = len(raw)+ if max_bytes is not None and total > max_bytes:+ head = raw[:max_bytes].decode("utf-8", errors="replace")+ return f"{head}\n... [truncated {total - max_bytes} bytes]\n", total, True+ return raw.decode("utf-8", errors="replace"), total, False+++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+ return sorted(p for p in out.decode("utf-8", errors="replace").split("\0") if p and _keep(p))++def read_working_tree(ws: Workspace) -> dict[str, bytes]:"""Fallback when a round has no commit: the current ``src/`` + ``public/``."""files: dict[str, bytes] = {}diff --git a/harness/tests/flywheel_cli/test_refine_pairs.py b/harness/tests/flywheel_cli/test_refine_pairs.pynew file mode 100644index 00000000..481954af--- /dev/null+++ b/harness/tests/flywheel_cli/test_refine_pairs.py@@ -0,0 +1,305 @@+"""``bench/refine_pairs.py``: refine transitions exported as (brief -> diff -> delta) rows.++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.+"""++from __future__ import annotations++import json+from collections.abc import Callable+from pathlib import Path++import pytest++from bench.refine_pairs import (+ DROP_REASONS,+ Report,+ export,+ iter_rows,+ main,+ outcome_label,+ parse_instruction,+ scan_roots,+ transition_row,+)+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity+from codeverse.contracts.run import RunRecord+from codeverse.flywheel.record import load_record, run_id_for+from codeverse.workspace import Workspace+from tests.flywheel_cli.conftest import make_fake_run+++def _corpus(root: Path, *, battery: str = "batt", slug: str = "chair") -> Workspace:+ """One battery holding one run: two judged rounds, ``src/`` committed twice."""+ ws, _ = make_fake_run(root / battery / "runs", slug)+ return ws+++def _patch(ws: Workspace, edit: Callable[[RunRecord], None]) -> RunRecord:+ rec = load_record(ws)+ edit(rec)+ ws.write_json(ws.record_path, rec)+ return rec+++def _rows(root: Path, **kw) -> tuple[list[dict], Report]:+ report = Report()+ return list(iter_rows(root, report, **kw)), report+++# --------------------------------------------------------------------------- pure functions+def test_parse_instruction_refine_task_line():+ tasks = parse_instruction("[gate/gate:connectivity] Leg_0: weld the leg to the seat (files: src/model.py, src/parts/leg.py)")+ assert tasks == [{"source": "gate", "kind": "gate:connectivity", "target": "Leg_0",+ "instruction": "weld the leg to the seat",+ "files": ["src/model.py", "src/parts/leg.py"]}]+++def test_parse_instruction_grouped_bullets():+ """``compact_instructions`` folds ``Leg_0``/``Leg_1`` into one ``Leg:`` line; each+ bullet is its own task and may name the instance it came from."""+ tasks = parse_instruction(+ "Leg: (a) [gate/gate:contract] too thin; (b) [Leg_1] [judge/geometry] add a fillet (files: src/model.py)")+ assert [(t["source"], t["kind"], t["target"], t["instruction"]) for t in tasks] == [+ ("gate", "gate:contract", "Leg", "too thin"),+ ("judge", "geometry", "Leg_1", "add a fillet"),+ ]+ assert all(t["files"] == ["src/model.py"] for t in tasks)+++def test_parse_instruction_bare_sentence_keeps_its_colon():+ """Detail rounds send prose. A sentence's own colon is not a target: only a single+ bare token before ``: `` is, or the whole instruction would be cut in half."""+ prose = "Add the panel lines where the shells meet (lids, trays): 1-2 mm wide insets."+ assert parse_instruction(prose) == [+ {"source": "", "kind": "", "target": "", "instruction": prose, "files": []}]+ assert parse_instruction("window_frame: Slope the exterior sill.") == [+ {"source": "", "kind": "", "target": "window_frame", "instruction": "Slope the exterior sill.", "files": []}]+++def test_outcome_label():+ assert outcome_label(0.2) == "improved"+ assert outcome_label(-0.2) == "regressed"+ assert outcome_label(0.01) == "unchanged"+ assert outcome_label(0.2, threshold=0.5) == "unchanged"+ assert outcome_label(None) == "unscored"+++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"]+++# --------------------------------------------------------------------------- rows+def test_row_carries_brief_diff_and_delta(tmp_path):+ root = tmp_path / "out"+ ws = _corpus(root)+ rows, report = _rows(root)+ (row,) = rows+ assert (row["battery"], row["run"], row["round"], row["round_kind"]) == ("batt", "chair", 1, "refine")+ assert row["prompt_id"] == "chair" and row["prompt"] == "a wooden dining chair"+ assert (row["track"], row["language"]) == ("static_object", "blender")+ # 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["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"]+ assert "--- a/src/model.py" in row["diff"] and "+++ b/src/parts/leg.py" in row["diff"]+ assert row["diff_bytes"] == len(row["diff"].encode()) and not row["diff_truncated"]+ assert row["diff_added"] > 0 and row["diff_removed"] > 0+ assert (row["score_before"], row["score_after"], row["score_delta"]) == (0.55, 0.8, 0.25)+ assert row["before"]["build_ok"] is True and row["after"]["build_ok"] is True+ assert row["outcome"] == "improved"+ assert report.rows == 1 and not report.drops+ assert report.kinds == {"baseline": 1, "refine": 1}+ assert ws.root.name == "chair"+++def test_outcome_threshold_is_recorded_on_the_row(tmp_path):+ root = tmp_path / "out"+ _corpus(root)+ (row,), _ = _rows(root, threshold=0.5)+ assert row["outcome"] == "unchanged" and row["outcome_threshold"] == 0.5+++def test_gate_error_findings_carry_fix_hints(tmp_path):+ """The refine brief is half judge, half gate: ``build_refine_instructions`` copies a+ finding's ``fix_hint`` verbatim, and only ERROR findings become tasks."""+ root = tmp_path / "out"+ ws = _corpus(root)+ _patch(ws, lambda rec: rec.rounds[0].gates.append(GateReport(gate="connectivity", passed=False, findings=[+ GateFinding(gate="connectivity", severity=Severity.ERROR, target="Leg_0",+ message="Leg_0 is not connected", fix_hint="move Leg_0 up by 3 mm"),+ GateFinding(gate="connectivity", severity=Severity.WARN, target="Seat", message="1.2 mm overlap")])))+ (row,), _ = _rows(root)+ assert row["gate_findings"] == [{"gate": "connectivity", "target": "Leg_0",+ "message": "Leg_0 is not connected",+ "fix_hint": "move Leg_0 up by 3 mm", "data": {}}]+ assert row["before"]["gate_errors"] == 1+++def test_diff_is_capped_and_says_so(tmp_path):+ 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"]+++def test_diff_uses_the_recorded_shas_not_head(tmp_path):+ """152 of the 239 recorded runs end on a "restore best round rNN" commit and only 54+ have HEAD at their last round, so the recorded sha is the only usable handle."""+ root = tmp_path / "out"+ ws = _corpus(root)+ rec = load_record(ws)+ (ws.src / "model.py").write_text("# restored baseline\n")+ ws.commit("restore best round r00")+ (row,), _ = _rows(root)+ assert row["after"]["commit"] == rec.rounds[1].commit+ assert "restored baseline" not in row["diff"]+++def test_nested_battery_layout_keeps_battery_cell_and_arm(tmp_path):+ root = tmp_path / "out"+ make_fake_run(root / "cmp" / "cells" / "chair_cell", "harness_arm")+ (row,), report = _rows(root)+ assert (row["battery"], row["cell"], row["arm"]) == ("cmp", "chair_cell", "harness_arm")+ assert row["run"] == "chair_cell__harness_arm"+ assert report.roots == [str(root / "cmp")]+++def test_transition_row_is_callable_on_one_run(tmp_path):+ """The row builder is usable without the scanner (one run, two rounds in hand)."""+ ws, rec = make_fake_run(tmp_path / "runs")+ run_id = run_id_for(tmp_path / "runs", ws.root)+ row = transition_row(ws, rec, run_id, rec.rounds[0], rec.rounds[1])+ assert row["run"] == ws.root.name and row["score_delta"] == 0.25+++# --------------------------------------------------------------------------- drops+def _drop_empty_battery(root: Path) -> None:+ (root / "batt" / "cells").mkdir(parents=True)+++def _drop_unreadable_record(root: Path) -> None:+ _corpus(root)+ broken = root / "batt" / "runs" / "broken"+ broken.mkdir()+ (broken / "record.json").write_text("{not json")+++def _drop_duplicate_run(root: Path) -> None:+ ws = _corpus(root)+ (root / "batt" / "runs" / "chair_link").symlink_to(ws.root, target_is_directory=True)+++def _drop_missing_predecessor(root: Path) -> None:+ _patch(_corpus(root), lambda rec: setattr(rec.rounds[1], "index", 5))+++def _drop_missing_commit(root: Path) -> None:+ _patch(_corpus(root), lambda rec: setattr(rec.rounds[1], "commit", ""))+++def _drop_missing_prev_judgment(root: Path) -> None:+ _patch(_corpus(root), lambda rec: setattr(rec.rounds[0], "judgment", None))+++def _drop_no_instructions(root: Path) -> None:+ _patch(_corpus(root), lambda rec: setattr(rec.rounds[1], "instructions", []))+++def _drop_git_read_failed(root: Path) -> None:+ _patch(_corpus(root), lambda rec: setattr(rec.rounds[1], "commit", "0" * 40))+++def _drop_empty_diff(root: Path) -> None:+ _patch(_corpus(root), lambda rec: setattr(rec.rounds[1], "commit", rec.rounds[0].commit))+++#: one corpus per reason; the parametrisation below fails loudly if a reason has none+DROP_CORPUS: dict[str, Callable[[Path], None]] = {+ "empty_battery": _drop_empty_battery,+ "unreadable_record": _drop_unreadable_record,+ "duplicate_run": _drop_duplicate_run,+ "missing_predecessor": _drop_missing_predecessor,+ "missing_commit": _drop_missing_commit,+ "missing_prev_judgment": _drop_missing_prev_judgment,+ "no_instructions": _drop_no_instructions,+ "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"}++[email protected]("reason", DROP_REASONS)+def test_every_drop_reason_is_counted(tmp_path, reason):+ root = tmp_path / "out"+ DROP_CORPUS[reason](root)+ rows, report = _rows(root)+ assert dict(report.drops) == {reason: 1}+ assert len(rows) == report.rows == (1 if reason in KEEPS_ROW else 0)+++def test_drop_corpus_covers_every_declared_reason():+ assert set(DROP_CORPUS) == set(DROP_REASONS)+++# --------------------------------------------------------------------------- cli+def test_main_writes_jsonl_and_prints_the_summary(tmp_path, capsys):+ root = tmp_path / "out"+ _corpus(root, battery="batt_a", slug="chair")+ _corpus(root, battery="batt_b", slug="stool")+ out = tmp_path / "pairs" / "refine.jsonl"++ assert main([str(root), "--out", str(out), "--summary"]) == 0+ printed = capsys.readouterr().out+ rows = [json.loads(line) for line in out.read_text().splitlines()]++ assert len(rows) == 2 and {r["battery"] for r in rows} == {"batt_a", "batt_b"}+ assert "2 row(s) from 2 run(s) in 2 root(s)" in printed+ assert "dropped: none" in printed+ assert "rows per battery" in printed and "batt_a" in printed+ assert "rows per track" in printed and "static_object" in printed+ assert "rows per outcome" in printed and "improved" in printed+ assert "diff size: median" in printed+++def test_main_reports_drops_without_writing(tmp_path, capsys):+ root = tmp_path / "out"+ _drop_no_instructions(root)+ assert main([str(root), "--summary"]) == 1+ printed = capsys.readouterr().out+ assert "0 row(s) from 1 run(s)" in printed+ assert "no_instructions" in printed+ assert "no rows to summarise" in printed+++def test_main_needs_somewhere_to_put_the_result(tmp_path):+ root = tmp_path / "out"+ _corpus(root)+ with pytest.raises(SystemExit):+ main([str(root)])+ with pytest.raises(SystemExit):+ main([str(tmp_path / "nope"), "--summary"])+++def test_export_replaces_the_target_atomically(tmp_path):+ root = tmp_path / "out"+ _corpus(root)+ out = tmp_path / "refine.jsonl"+ out.write_text("stale\n")+ report = export(root, out)+ assert report.rows == 1 and json.loads(out.read_text())["run"] == "chair"+ assert not list(tmp_path.glob("*.tmp"))