runner/ (cli.mjs, extensions/folder-permissions.ts, test, README) was a byte-for-byte duplicate of the harness-pi plugin's runner/, kept only as the driver's fallback through the sidecar's config.RUNNER_BIN. - delete runner/ and sidecar config.RUNNER_BIN - scripts/test.py: drop the `runner` suite (it runs in ai-agent-plugins now) - scripts/ab: the pi mirror replay uses a tree's runner/ when it has one (refs before this), else the plugin's (AB_PI_RUNNER) - CLAUDE.md / docs / comments point at harness-pi's runner - sidecar/local-model.md stays (harness-opencode's LOCAL_MODEL_GUIDE) Merge only after harness-pi 1.1.0 is installed on the lab: harness-pi 1.0.x reads config.RUNNER_BIN and would fail every pi run on this core. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
548 lines
26 KiB
Python
Executable File
548 lines
26 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Replay native harness data through the three transcript converters and
|
||
compare what they write: opencode (``sidecar/opencode_mirror.py``), agy
|
||
(``sidecar/agy_mirror.py``) and pi (the harness-pi runner ``cli.mjs``'s ``TranscriptWriter`` — see
|
||
``_mirror_worker.pi_runner``).
|
||
|
||
scripts/ab/mirror-replay.py # print the working tree's dump
|
||
scripts/ab/mirror-replay.py --base HEAD # base ref vs working tree, byte for byte
|
||
scripts/ab/mirror-replay.py --incremental # growing source == one-shot (hub parse)
|
||
scripts/ab/mirror-replay.py --base main --incremental --real # + the lab's own data
|
||
scripts/ab/mirror-replay.py --base main --parse [--real] # same hub parse, any format
|
||
|
||
Sources: the committed synthetic fixtures (``mirror_fixtures/``) always;
|
||
with ``--real`` also read-only snapshots of the lab's opencode database(s)
|
||
and agy ``brain/`` (copied to a temp dir first, never printed in full).
|
||
|
||
Each tree runs ``_mirror_worker.py`` under ``uv run --with-requirements
|
||
<tree>/sidecar/requirements.txt``. Exit codes: 0 identical, 1 a difference,
|
||
2 usage or setup error.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import pathlib
|
||
import shutil
|
||
import sqlite3
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
|
||
HERE = pathlib.Path(__file__).resolve().parent
|
||
sys.path.insert(0, str(HERE))
|
||
import _common as ab # noqa: E402
|
||
|
||
WORKER = HERE / "_mirror_worker.py"
|
||
PARSE_WORKER = HERE / "_parse_worker.py"
|
||
HOME = pathlib.Path.home()
|
||
# mirror_fixtures.FROZEN_NOW, as the mirrors write it (the old format, v1)
|
||
CLOCK_STAMPS = ('"timestamp": "2099-', '"at":"2099-')
|
||
INCREMENTAL_MODES = ("stepwise", "chunked", "restart")
|
||
|
||
# The lab's live data (read-only; snapshotted by --real). Overridable.
|
||
OPENCODE_DBS = os.environ.get(
|
||
"AB_OPENCODE_DBS", f"opencode-lab={HOME}/.local/share/opencode/opencode.db")
|
||
OPENCODE_FORKS = pathlib.Path(os.environ.get(
|
||
"AB_OPENCODE_FORKS", HOME / ".opencode-runner/ids.json"))
|
||
AGY_APP = pathlib.Path(os.environ.get("AB_AGY_APP", HOME / ".gemini/antigravity-cli"))
|
||
AGY_IDS = pathlib.Path(os.environ.get("AB_AGY_IDS", HOME / ".agy-runner/ids.json"))
|
||
AGY_LOGS = pathlib.Path(os.environ.get(
|
||
"AB_AGY_LOG_DIR", HOME / "projects/ai-agent/sidecar/logs"))
|
||
AGY_ACCOUNT = "google-personal"
|
||
|
||
|
||
def runner(tree: pathlib.Path) -> list[str]:
|
||
return ["uv", "run", "--quiet", "--no-project",
|
||
"--with-requirements", str(tree / "sidecar" / "requirements.txt"), "python"]
|
||
|
||
|
||
# ── real-data snapshot ───────────────────────────────────────────────────────
|
||
|
||
def snapshot(dest: pathlib.Path, harnesses: list[str], min_age: float) -> dict:
|
||
"""Read-only copies of the lab's data into ``dest`` (counts returned)."""
|
||
counts: dict = {}
|
||
if "opencode" in harnesses:
|
||
for spec in OPENCODE_DBS.split(","):
|
||
acct, _, path = spec.partition("=")
|
||
src = pathlib.Path(os.path.expanduser(path))
|
||
if not src.is_file():
|
||
print(f"note: no opencode db at {src}", file=sys.stderr)
|
||
continue
|
||
d = dest / "opencode" / acct
|
||
d.mkdir(parents=True)
|
||
con = sqlite3.connect(f"file:{src}?mode=ro", uri=True)
|
||
out = sqlite3.connect(d / "opencode.db")
|
||
con.backup(out) # a consistent copy, WAL included
|
||
n = out.execute("SELECT (SELECT count(*) FROM session_v2),"
|
||
" (SELECT count(*) FROM session_message)").fetchone()
|
||
out.close()
|
||
con.close()
|
||
if OPENCODE_FORKS.is_file():
|
||
shutil.copyfile(OPENCODE_FORKS, d / "ids.json")
|
||
counts[f"opencode:real-{acct}"] = {"sessions": n[0], "messages": n[1]}
|
||
if "agy" in harnesses and (AGY_APP / "brain").is_dir():
|
||
d = dest / "agy"
|
||
app = d / "home/.gemini/antigravity-cli"
|
||
now = time.time()
|
||
convs, lines = 0, 0
|
||
for conv in sorted((AGY_APP / "brain").iterdir()):
|
||
gen = conv / ".system_generated"
|
||
t = gen / "logs/transcript_full.jsonl"
|
||
if not t.is_file() or now - t.stat().st_mtime < min_age:
|
||
continue # no transcript, or a live run still writing it
|
||
convs += 1
|
||
for p in [t, *sorted((gen / "logs/chunks/transcript_full").glob("*.jsonl")),
|
||
*sorted((gen / "subagents").glob("*.json"))]:
|
||
q = app / p.relative_to(AGY_APP)
|
||
q.parent.mkdir(parents=True, exist_ok=True)
|
||
shutil.copyfile(p, q)
|
||
if p.suffix == ".jsonl":
|
||
lines += p.read_bytes().count(b"\n")
|
||
# keep the dir's age order (agy_real_ops sorts conversations by it)
|
||
st = conv.stat()
|
||
os.utime(app / "brain" / conv.name, ns=(st.st_atime_ns, st.st_mtime_ns))
|
||
cache = AGY_APP / "cache/last_conversations.json"
|
||
if cache.is_file():
|
||
(app / "cache").mkdir(parents=True, exist_ok=True)
|
||
shutil.copyfile(cache, app / "cache/last_conversations.json")
|
||
ids = {}
|
||
if AGY_IDS.is_file():
|
||
ids = {k: v for k, v in json.loads(AGY_IDS.read_text()).items()
|
||
if isinstance(v, dict) and (v.get("account") or AGY_ACCOUNT) == AGY_ACCOUNT}
|
||
(d / "runner").mkdir(parents=True)
|
||
(d / "runner/ids.json").write_text(json.dumps(ids, indent=1))
|
||
(d / "logs").mkdir()
|
||
bound = {r.get("agy") for r in ids.values()}
|
||
for sid in ids:
|
||
if (AGY_LOGS / f"{sid}.log").is_file():
|
||
shutil.copyfile(AGY_LOGS / f"{sid}.log", d / "logs" / f"{sid}.log")
|
||
# what _workspace() reads of a terminal conversation's database: its head
|
||
for db in sorted((AGY_APP / "conversations").glob("*.db")):
|
||
if db.stem in bound or not (app / "brain" / db.stem).is_dir():
|
||
continue
|
||
(app / "conversations").mkdir(parents=True, exist_ok=True)
|
||
with db.open("rb") as fh:
|
||
(app / "conversations" / db.name).write_bytes(fh.read(4 * 1024 * 1024))
|
||
counts["agy:real"] = {"conversations": convs, "transcript lines": lines,
|
||
"hub runs": len(ids)}
|
||
return counts
|
||
|
||
|
||
# ── running a tree ───────────────────────────────────────────────────────────
|
||
|
||
def run_tree(tree: pathlib.Path, work: pathlib.Path, label: str, args, modes: list[str],
|
||
snap: pathlib.Path | None) -> dict:
|
||
out = work / f"{label}.json"
|
||
argv = [*runner(tree), str(WORKER), "--tree", str(tree), "--harness", args.harness,
|
||
"--modes", ",".join(modes), "--chunks", str(args.chunks), "--seed", str(args.seed)]
|
||
if snap:
|
||
argv += ["--real-snapshot", str(snap)]
|
||
t0 = time.time()
|
||
ab.run_pool([(argv, ab.frozen_env(work), out)], 1)
|
||
res = json.loads(out.read_text())
|
||
took = ", ".join(f"{k} {sum(m['seconds'] for m in v['modes'].values()):.1f}s"
|
||
for k, v in res["sources"].items())
|
||
print(f"{label}: {time.time() - t0:.1f}s ({took})", file=sys.stderr)
|
||
return res
|
||
|
||
|
||
def is_real(source: str) -> bool:
|
||
return ":real" in source
|
||
|
||
|
||
# ── rendering ────────────────────────────────────────────────────────────────
|
||
|
||
def sha(lines: list[str]) -> str:
|
||
return hashlib.sha256("\n".join(lines).encode("utf-8", "replace")).hexdigest()[:12]
|
||
|
||
|
||
def dump_text(res: dict) -> str:
|
||
out = []
|
||
for src, v in res["sources"].items():
|
||
files = v["modes"]["oneshot"]["files"]
|
||
out.append(f"### {src} ({v['ops']} op(s), {len(files)} file(s))")
|
||
for f, lines in files.items():
|
||
n = len([ln for ln in lines if ln])
|
||
if is_real(src):
|
||
out.append(f"== {f} ({n} line(s), sha256 {sha(lines)})")
|
||
else:
|
||
out.append(f"== {f}")
|
||
out += lines
|
||
return "\n".join(out) + "\n"
|
||
|
||
|
||
def _key(line: str) -> str:
|
||
try:
|
||
o = json.loads(line)
|
||
except ValueError:
|
||
return line[:40]
|
||
return str(o.get("ocKey") or o.get("agyKey") or o.get("type") or o.get("t"))
|
||
|
||
|
||
def file_diff(src: str, f: str, a: list[str] | None, b: list[str] | None,
|
||
name_a: str, name_b: str, show: int, brief: bool = False) -> list[str]:
|
||
"""The lines saying how one output file differs: by default (``brief``)
|
||
the record keys (``ocKey`` / ``agyKey``) and the JSON paths that changed,
|
||
values cut short; a unified diff of a fixture's lines (cut at 300 chars)
|
||
otherwise. Real data is always shown the short way."""
|
||
if a is None or b is None:
|
||
return [f" {f}: only in {name_b if a is None else name_a}"]
|
||
if not brief and not is_real(src):
|
||
return [f" {f}:"] + [" " + (ln if len(ln) <= 300 else ln[:299] + "…")
|
||
for ln in ab.text_diff("\n".join(a), "\n".join(b), name_a,
|
||
name_b, max_lines=show * 10)]
|
||
out = [f" {f}: {len(a)} → {len(b)} line(s)"]
|
||
ka, kb = [_key(x) for x in a], [_key(x) for x in b]
|
||
if ka != kb:
|
||
i = next((k for k, (x, y) in enumerate(zip(ka, kb)) if x != y), min(len(ka), len(kb)))
|
||
how = "same records, other order" if sorted(ka) == sorted(kb) else (
|
||
f"only in {name_a}: {sorted(set(ka) - set(kb))[:6]}; "
|
||
f"only in {name_b}: {sorted(set(kb) - set(ka))[:6]}")
|
||
out.append(f" records from #{i + 1}: {name_a} {ka[i:i + 4]} vs {name_b} "
|
||
f"{kb[i:i + 4]} ({how})")
|
||
return out
|
||
shown = 0
|
||
for i, (x, y) in enumerate(zip(a, b)):
|
||
if x == y:
|
||
continue
|
||
try:
|
||
paths = ab.diff_paths(json.loads(x), json.loads(y), "$", limit=8)
|
||
out.append(f" line {i + 1} [{_key(x)}]: " + "; ".join(paths))
|
||
except ValueError: # pi-argv, exit, stderr: plain text
|
||
out.append(f" line {i + 1}: {ab._short(x, 120)} → {ab._short(y, 120)}")
|
||
shown += 1
|
||
if shown >= show:
|
||
break
|
||
return out
|
||
|
||
|
||
def compare(a: dict, b: dict, src: str, name_a: str, name_b: str, show: int,
|
||
brief: bool = False) -> list[str]:
|
||
out = []
|
||
for f in sorted(set(a) | set(b)):
|
||
if a.get(f) != b.get(f):
|
||
out += file_diff(src, f, a.get(f), b.get(f), name_a, name_b, show, brief)
|
||
return out
|
||
|
||
|
||
def clock_notes(res: dict) -> list[str]:
|
||
"""Records stamped with the mirror's own clock rather than a time the
|
||
source gave: their timestamp says when the mirror ran."""
|
||
out = []
|
||
for src, v in res["sources"].items():
|
||
if src.startswith("pi:"):
|
||
continue # pi's runner has no other clock: its events are live
|
||
n, kinds = 0, {}
|
||
for lines in v["modes"]["oneshot"]["files"].values():
|
||
for ln in lines:
|
||
if any(c in ln for c in CLOCK_STAMPS):
|
||
n += 1
|
||
k = _key(ln).split(":")[0]
|
||
kinds[k] = kinds.get(k, 0) + 1
|
||
if n:
|
||
out.append(f" {src}: {n} record(s) stamped with the mirror's clock — "
|
||
+ ", ".join(f"{k} ×{c}" for k, c in sorted(kinds.items())))
|
||
return out
|
||
|
||
|
||
# ── hub parse (incremental equivalence) ──────────────────────────────────────
|
||
|
||
def hub_parse(files: dict[str, list[str]], work: pathlib.Path, label: str,
|
||
subagents: bool = False) -> dict[str, str]:
|
||
"""Write a mode's output and parse each transcript with the working
|
||
tree's backend parser (``_parse_worker.py --mode dump``): {file: summary}
|
||
(``subagents``: the sidechains too)."""
|
||
root = work / "parse" / label
|
||
items = []
|
||
for f, lines in files.items():
|
||
p = root / f
|
||
p.parent.mkdir(parents=True, exist_ok=True)
|
||
p.write_text("\n".join(lines), encoding="utf-8")
|
||
if f.endswith(".jsonl") and (subagents or "/subagents/" not in f):
|
||
items.append((f, p))
|
||
lst = work / "parse" / f"{label}.list.json"
|
||
lst.write_text(json.dumps([{"path": str(p)} for _f, p in items]))
|
||
out = work / "parse" / f"{label}.out"
|
||
ab.run_pool([([sys.executable, str(PARSE_WORKER), "--tree", str(ab.REPO), "--mode", "dump",
|
||
"--list", str(lst), "--out", str(out)], ab.frozen_env(work), None)], 1)
|
||
res = {}
|
||
for i, (f, _p) in enumerate(items):
|
||
res[f] = {name: (out / f"{i}.{name}.json").read_text().replace(str(root), "<ROOT>")
|
||
for name in ("short", "full")}
|
||
return res
|
||
|
||
|
||
def incremental(res: dict, work: pathlib.Path, show: int) -> int:
|
||
print("incremental == one-shot (opencode, agy):")
|
||
failed = 0
|
||
parsed_one: dict[str, dict] = {}
|
||
for src, v in res["sources"].items():
|
||
one = v["modes"]["oneshot"]["files"]
|
||
for mode in INCREMENTAL_MODES:
|
||
r = v["modes"].get(mode)
|
||
if r is None:
|
||
continue
|
||
tag = f"{src} {mode} ({r['polls']} poll(s))"
|
||
if r["files"] == one:
|
||
print(f" OK {tag}: byte-identical")
|
||
continue
|
||
if src not in parsed_one:
|
||
parsed_one[src] = hub_parse(one, work, f"{src}-oneshot".replace(":", "_"))
|
||
pa = parsed_one[src]
|
||
pb = hub_parse(r["files"], work, f"{src}-{mode}".replace(":", "_"))
|
||
bad = []
|
||
for f in sorted(set(pa) | set(pb)):
|
||
for name in ("short", "full"):
|
||
x, y = (pa.get(f) or {}).get(name), (pb.get(f) or {}).get(name)
|
||
if x != y:
|
||
paths = ab.diff_paths(json.loads(x) if x else None,
|
||
json.loads(y) if y else None, "$", limit=show)
|
||
bad.append(f" {f} full={name == 'full'} (base = oneshot, new = {mode}): "
|
||
+ "; ".join(paths))
|
||
bytes_diff = compare(one, r["files"], src, "oneshot", mode, show, brief=True)
|
||
if bad:
|
||
failed += 1
|
||
print(f" DIFF {tag}: the hub parses it differently")
|
||
for ln in bad[:show]:
|
||
print(ln)
|
||
else:
|
||
print(f" OK {tag}: same hub parse; bytes differ (below)")
|
||
for ln in bytes_diff[:show * 4]:
|
||
print(" " + ln)
|
||
return 1 if failed else 0
|
||
|
||
|
||
# ── hub parse A/B (a format change) ──────────────────────────────────────────
|
||
|
||
# What the working tree's converters change *on purpose* in the hub's parse of
|
||
# their output beyond the rewrite's fixes (``rewrite_v1.FIXES``, applied to the
|
||
# base side's old-format output before it is parsed): JSON path patterns
|
||
# (indexes folded to [*]) → the reason. Any other differing path fails.
|
||
INTENDED = {
|
||
"native": (r"^\$\.thread\[\*\]\.native$",
|
||
"a tool's `native` is the harness's own name (the old format only had "
|
||
"Claude Code's)"),
|
||
}
|
||
|
||
|
||
def _intended(path: str) -> str | None:
|
||
import re
|
||
g = re.sub(r"\[\d+\]", "[*]", path)
|
||
for kind, (rx, _why) in INTENDED.items():
|
||
if re.match(rx, g):
|
||
return kind
|
||
return None
|
||
|
||
|
||
def _rewrite(files: dict[str, list[str]], work: pathlib.Path, label: str,
|
||
fixes: list[str]) -> dict[str, list[str]]:
|
||
"""The old-format transcripts of ``files`` rewritten to v1 by the working
|
||
tree (``_parse_worker.py --mode v1``), with ``fixes``; other files as is."""
|
||
src = work / "rw" / label / "in"
|
||
dst = work / "rw" / label / "out"
|
||
items = []
|
||
for f, lines in files.items():
|
||
if not f.endswith(".jsonl"):
|
||
continue
|
||
p, q = src / f, dst / f
|
||
p.parent.mkdir(parents=True, exist_ok=True)
|
||
q.parent.mkdir(parents=True, exist_ok=True)
|
||
p.write_text("\n".join(lines), encoding="utf-8")
|
||
items.append({"path": str(p), "out": str(q), "fixes": fixes})
|
||
lst = work / "rw" / f"{label}.list.json"
|
||
lst.write_text(json.dumps(items))
|
||
out = work / "rw" / f"{label}.out"
|
||
ab.run_pool([([sys.executable, str(PARSE_WORKER), "--tree", str(ab.REPO), "--mode", "v1",
|
||
"--list", str(lst), "--out", str(out)], ab.frozen_env(work), None)], 1)
|
||
res = dict(files)
|
||
for f in files:
|
||
q = dst / f
|
||
if f.endswith(".jsonl") and q.is_file():
|
||
res[f] = q.read_text(encoding="utf-8").rstrip("\n").split("\n")
|
||
return res
|
||
|
||
|
||
def _compare(pa: dict, pb: dict, show: int, intended=_intended):
|
||
kinds: dict[str, int] = {}
|
||
bad: list[str] = []
|
||
for f in sorted(set(pa) | set(pb)):
|
||
if f not in pa or f not in pb:
|
||
bad.append(f" {f}: only in {'base' if f in pa else 'working tree'}")
|
||
continue
|
||
for name in ("short", "full"):
|
||
x, y = json.loads(pa[f][name]), json.loads(pb[f][name])
|
||
for path in ab.json_paths(x, y):
|
||
k = intended(path)
|
||
if k:
|
||
kinds[k] = kinds.get(k, 0) + 1
|
||
else:
|
||
bad.append(f" {f} full={name == 'full'}: "
|
||
+ "; ".join(ab.diff_paths(x, y, "$", limit=show)))
|
||
break
|
||
return kinds, bad
|
||
|
||
|
||
def parse_ab(base: dict, new: dict, work: pathlib.Path, show: int, chunks: int,
|
||
seed: int) -> int:
|
||
"""The base tree's one-shot output (the old format) and the working
|
||
tree's (v1), parsed by the working tree's hub parser, summary and full:
|
||
|
||
1. the old format rewritten to v1 with no fix parses exactly like itself
|
||
(the rewrite is faithful);
|
||
2. the working tree's output parses like the old format rewritten with
|
||
every fix (``rewrite_v1.FIXES``), up to ``INTENDED``; what each fix
|
||
changes in the old format's parse is listed;
|
||
3. the working tree's output fed in chunks parses like it does in one go."""
|
||
print("hub parse — base output (old format) vs working tree output (v1), one-shot:")
|
||
failed = 0
|
||
fixes = ["whole_steps", "source_times", "harness", "no_pi_fallback"]
|
||
for src in sorted(set(base["sources"]) | set(new["sources"])):
|
||
a = (base["sources"].get(src) or {}).get("modes", {}).get("oneshot", {}).get("files", {})
|
||
b = (new["sources"].get(src) or {}).get("modes", {}).get("oneshot", {}).get("files", {})
|
||
tag = src.replace(":", "_")
|
||
pa = hub_parse(a, work, f"ab-base-{tag}", subagents=True)
|
||
same = hub_parse(_rewrite(a, work, f"{tag}-faithful", []), work, f"ab-faithful-{tag}",
|
||
subagents=True)
|
||
k0, bad0 = _compare(pa, same, show, intended=lambda p: None)
|
||
by_fix = {}
|
||
for fx in fixes:
|
||
pf = hub_parse(_rewrite(a, work, f"{tag}-{fx}", [fx]), work, f"ab-{fx}-{tag}",
|
||
subagents=True)
|
||
kf, badf = _compare(pa, pf, show, intended=lambda p: None)
|
||
n = sum(1 for ln in badf)
|
||
if n:
|
||
by_fix[fx] = n
|
||
pr = hub_parse(_rewrite(a, work, f"{tag}-fixed", fixes), work, f"ab-fixed-{tag}",
|
||
subagents=True)
|
||
pb = hub_parse(b, work, f"ab-new-{tag}", subagents=True)
|
||
kinds, bad = _compare(pr, pb, show)
|
||
fixed = ", ".join(f"{k} in {n} parse(s)" for k, n in sorted(by_fix.items())) or "nothing"
|
||
got = ", ".join(f"{k} ×{n}" for k, n in sorted(kinds.items())) or "none"
|
||
if bad0:
|
||
failed += 1
|
||
print(f" DIFF {src}: the faithful rewrite parses differently from the old format")
|
||
for ln in bad0[:show]:
|
||
print(ln)
|
||
if bad:
|
||
failed += 1
|
||
print(f" DIFF {src}: {len(pb)} transcript(s); intended: {got}")
|
||
for ln in bad[:show]:
|
||
print(ln)
|
||
if not bad0 and not bad:
|
||
print(f" OK {src}: {len(pb)} transcript(s) — the v1 output parses like the old "
|
||
f"one (fixes: {fixed}; intended: {got})")
|
||
# the byte-offset contract on the working tree's output
|
||
lst = work / "parse" / f"ab-chunk-{tag}.list.json"
|
||
root = work / "parse" / f"ab-new-{tag}"
|
||
items = [{"path": str(root / f), "size": (root / f).stat().st_size} for f in pb]
|
||
lst.write_text(json.dumps(items))
|
||
out = work / "parse" / f"ab-chunk-{tag}.out"
|
||
ab.run_pool([([sys.executable, str(PARSE_WORKER), "--tree", str(ab.REPO), "--mode",
|
||
"chunked", "--list", str(lst), "--out", str(out), "--chunks", str(chunks),
|
||
"--seed", str(seed)], ab.frozen_env(work), None)], 1)
|
||
nbad = 0
|
||
for ln in out.read_text().splitlines():
|
||
row = json.loads(ln)
|
||
for name in ("short", "full"):
|
||
r = row.get(name) or {}
|
||
if not (r.get("equal") and r.get("pure")):
|
||
nbad += 1
|
||
print(f" chunked ≠ one-shot: {row['path']} full={name == 'full'} "
|
||
f"{r.get('error') or '; '.join(r.get('paths') or [])}")
|
||
if nbad:
|
||
failed += 1
|
||
else:
|
||
print(f" chunked == one-shot on all {len(items)} ({chunks} cuts each)")
|
||
return 1 if failed else 0
|
||
|
||
|
||
# ── main ─────────────────────────────────────────────────────────────────────
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
ap.add_argument("--base", metavar="REF", help="diff this git ref against the working tree")
|
||
ap.add_argument("--incremental", action="store_true",
|
||
help="replay each opencode / agy source in steps too; the hub must parse "
|
||
"the result like the one-shot output")
|
||
ap.add_argument("--harness", default="opencode,agy,pi",
|
||
help="comma list (default opencode,agy,pi)")
|
||
ap.add_argument("--real", action="store_true",
|
||
help="also the lab's opencode db(s) and agy brain/ (read-only copies)")
|
||
ap.add_argument("--min-age", type=float, default=300.0, metavar="SECONDS",
|
||
help="--real: skip agy conversations written in the last N s (default 300)")
|
||
ap.add_argument("--chunks", type=int, default=8, help="polls of the chunked mode (default 8)")
|
||
ap.add_argument("--seed", type=int, default=1)
|
||
ap.add_argument("--show", type=int, default=6, help="differences shown per file (default 6)")
|
||
ap.add_argument("--parse", action="store_true",
|
||
help="--base: compare the hub's parse of both outputs (a format change) "
|
||
"instead of their bytes, chunked too")
|
||
ap.add_argument("--text-diff", action="store_true",
|
||
help="--base: a unified diff of the fixtures' lines instead of JSON paths")
|
||
ap.add_argument("--keep", action="store_true", help="keep the scratch dir")
|
||
args = ap.parse_args()
|
||
bad = set(args.harness.split(",")) - {"opencode", "agy", "pi"}
|
||
if bad:
|
||
print(f"error: unknown harness {sorted(bad)}", file=sys.stderr)
|
||
return 2
|
||
|
||
with ab.workdir(args.keep) as work:
|
||
snap = None
|
||
if args.real:
|
||
snap = work / "real"
|
||
counts = snapshot(snap, args.harness.split(","), args.min_age)
|
||
for k, c in counts.items():
|
||
print(f"{k}: " + ", ".join(f"{n} {what}" for what, n in c.items()),
|
||
file=sys.stderr)
|
||
modes = ["oneshot", *(INCREMENTAL_MODES if args.incremental else ())]
|
||
new = run_tree(ab.REPO, work, "new", args, modes, snap)
|
||
rc = 0
|
||
if args.parse and not args.base:
|
||
print("error: --parse needs --base", file=sys.stderr)
|
||
return 2
|
||
if args.base and args.parse:
|
||
base_tree, sha_ = ab.materialise(args.base, work / "base")
|
||
base = run_tree(base_tree, work, "base", args, ["oneshot"], snap)
|
||
rc = parse_ab(base, new, work, args.show, args.chunks, args.seed)
|
||
print(("OK" if rc == 0 else "DIFF") + f": hub parse against {args.base} "
|
||
f"({sha_[:8]})")
|
||
elif args.base:
|
||
base_tree, sha_ = ab.materialise(args.base, work / "base")
|
||
base = run_tree(base_tree, work, "base", args, ["oneshot"], snap)
|
||
diffs = []
|
||
for src in sorted(set(base["sources"]) | set(new["sources"])):
|
||
a = (base["sources"].get(src) or {}).get("modes", {}).get("oneshot", {})
|
||
b = (new["sources"].get(src) or {}).get("modes", {}).get("oneshot", {})
|
||
d = compare(a.get("files", {}), b.get("files", {}), src,
|
||
f"base {sha_[:8]}", "working tree", args.show,
|
||
brief=not args.text_diff)
|
||
if d:
|
||
diffs.append(f"✗ {src}")
|
||
diffs += d
|
||
total = sum(len(f) for s in new["sources"].values()
|
||
for f in s["modes"]["oneshot"]["files"].values())
|
||
if diffs:
|
||
print(f"DIFF against {args.base} ({sha_[:8]}):")
|
||
print("\n".join(diffs))
|
||
rc = 1
|
||
else:
|
||
print(f"OK: identical to {args.base} ({sha_[:8]}) — "
|
||
f"{len(new['sources'])} source(s), {total} line(s)")
|
||
if args.incremental:
|
||
rc = max(rc, incremental(new, work, args.show))
|
||
if not args.base and not args.incremental:
|
||
sys.stdout.write(dump_text(new))
|
||
notes = clock_notes(new)
|
||
if notes:
|
||
print("note: timestamps from the mirror's clock (2099 = the frozen clock):")
|
||
print("\n".join(notes))
|
||
return rc
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|