Files
ai-agent/scripts/ab/_mirror_worker.py
gabrielvidalandClaude Opus 5.5 c3945fe965 refactor: retire core runner/ — pi's runner lives in the harness-pi plugin
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>
2026-11-27 11:44:54 +01:00

641 lines
28 KiB
Python

#!/usr/bin/env python3
"""Runs inside ONE tree for ``mirror-replay.py``: replays each source through
that tree's converters and prints what they wrote, as JSON on stdout.
python _mirror_worker.py --tree T --harness opencode,agy,pi \\
--modes oneshot,stepwise,chunked,restart [--real-snapshot DIR] [--chunks 8] [--seed 1]
The fixtures always come from this script's own directory (the working
tree's ``scripts/ab/mirror_fixtures``), so both sides of an A/B replay the
same input. The product code comes from ``--tree``: ``<tree>/sidecar`` on
``sys.path`` for the two Python mirrors, ``node <tree>/runner/cli.mjs`` for
pi in a tree from before 2026-11-27, else the harness-pi plugin's runner
(``AB_PI_RUNNER``, default ``~/projects/ai-agent-plugins/plugins/harness-pi/
runner/cli.mjs``) — the core ``runner/`` is retired.
Modes (opencode, agy):
oneshot the whole source written, then one poll (+ the settle polls)
stepwise a poll after every op
chunked a poll at ``--chunks`` seeded cut points; for agy a cut may fall
inside a line (half of it written before the poll)
restart stepwise (fixtures) / chunked (real data), a fresh mirror object
for every poll: what a sidecar restart sees
Every mode ends with the same settle polls (the clock moved 5 s, 30 s, 1 h:
quiet windows and dead runs close their turns). What is frozen and how: see
``freeze()`` and the README.
"""
from __future__ import annotations
import argparse
import datetime as _dt
import heapq
import json
import os
import pathlib
import random
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import time as _time
import types
HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from mirror_fixtures import FROZEN_NOW # noqa: E402
from mirror_fixtures import agy as FX_AGY # noqa: E402
from mirror_fixtures import opencode as FX_OC # noqa: E402
from mirror_fixtures import pi as FX_PI # noqa: E402
SETTLE = (5.0, 30.0, 3600.0)
STEPWISE_MAX_OPS = 400 # real data: a poll per op only below this
# ── the frozen clock ─────────────────────────────────────────────────────────
class _Clock:
t = FROZEN_NOW
CLOCK = _Clock()
def _fake_time() -> types.ModuleType:
m = types.ModuleType("time")
m.__dict__.update(_time.__dict__)
m.time = lambda: CLOCK.t
return m
def _fake_datetime() -> types.ModuleType:
class FrozenDateTime(_dt.datetime):
@classmethod
def now(cls, tz=None):
return _dt.datetime.fromtimestamp(CLOCK.t, tz)
m = types.ModuleType("datetime")
m.__dict__.update(_dt.__dict__)
m.datetime = FrozenDateTime
return m
def plugin_mirrors():
"""The harness-opencode and harness-agy plugins' ``mirror`` modules,
loaded as the sidecar loads them (``harness_loader``, a live index naming
the plugin dirs of ``SIDECAR_SEED_PLUGINS_DIR`` in place)."""
import json
import tempfile
plugins = pathlib.Path(os.path.expanduser(
os.environ.get("SIDECAR_SEED_PLUGINS_DIR") or "~/projects/ai-agent-plugins/plugins"))
live = pathlib.Path(tempfile.mkdtemp(prefix="ab-mirror-live-"))
items = {}
for pid, hid in (("harness-opencode", "opencode"), ("harness-agy", "agy")):
if not (plugins / pid / "plugin.json").is_file():
raise SystemExit(f"no {pid} plugin under {plugins} (SIDECAR_SEED_PLUGINS_DIR)")
items[hid] = {"pluginId": pid, "dir": str(plugins / pid), "entry": "driver.py"}
(live / "index.json").write_text(json.dumps({"version": 1, "harnesses": items}))
os.environ["SIDECAR_LIVE_HARNESSES_DIR"] = str(live)
os.environ["SIDECAR_LIVE_PROVIDERS_DIR"] = str(live / "no-providers")
import harness_loader
out = harness_loader.LOADER.reload(start=False)
if not out.get("ok") or not {"opencode", "agy"} <= set(harness_loader.ids()):
raise SystemExit(f"the harness plugins didn't load: {out}")
return (sys.modules["sidecar_ext.harness.harness_opencode.mirror"],
sys.modules["sidecar_ext.harness.harness_agy.mirror"])
def freeze(tree: pathlib.Path):
"""Import the tree's mirrors with every run-dependent input pinned:
- ``SIDECAR_AGY_DIR`` / ``SIDECAR_AGY_ACCOUNTS`` / ``SIDECAR_LOG_DIR`` are
RELATIVE paths (``runner``, ``home``, ``logs``) resolved in the replay's
own directory: the mirrors' uuid5 of the output path is then the same on
every run (no absolute temp path in it);
- ``time.time`` and ``datetime.now`` of both mirror modules read ``CLOCK``;
- ``_git_branch`` of both mirror modules answers ``replay-branch`` (it is
only called for a cwd that exists: real data names the lab's repos,
whose branch moves);
- ``pids._live_record`` (is the agy run still going?) answers from the
replay's ``alive`` ops.
"""
os.environ["SIDECAR_AGY_DIR"] = "runner"
os.environ["SIDECAR_AGY_ACCOUNTS"] = f"{FX_AGY.ACCOUNT}=home"
os.environ["SIDECAR_LOG_DIR"] = "logs"
sys.path.insert(0, str(tree / "sidecar"))
if (tree / "sidecar" / "opencode_mirror.py").is_file():
# a tree from before the harnesses moved into plugins
import agy_mirror
import opencode_mirror
else:
opencode_mirror, agy_mirror = plugin_mirrors()
import pids
for mod in (opencode_mirror, agy_mirror):
mod.time = _fake_time()
mod.datetime = _fake_datetime()
mod._git_branch = lambda cwd: "replay-branch"
return opencode_mirror, agy_mirror, pids
# ── helpers ──────────────────────────────────────────────────────────────────
def collect(root: pathlib.Path) -> dict[str, list[str]]:
out: dict[str, list[str]] = {}
if not root.is_dir():
return out
for p in sorted(root.rglob("*")):
if p.is_file():
out[str(p.relative_to(root))] = p.read_bytes().decode("utf-8", "replace").split("\n")
return out
def groups(ops: list, cuts: list[int]) -> list[tuple[int, int]]:
"""[start, end) index ranges of ops between polls."""
bounds = [0, *sorted(set(c for c in cuts if 0 < c < len(ops))), len(ops)]
return [(a, b) for a, b in zip(bounds, bounds[1:])]
def cuts_for(mode: str, n: int, chunks: int, rng: random.Random) -> list[int]:
if mode == "oneshot":
return []
if mode == "stepwise" or (mode == "restart" and n <= STEPWISE_MAX_OPS):
return list(range(1, n))
return sorted(rng.sample(range(1, n), min(max(chunks - 1, 0), max(n - 1, 0))))
class Run:
"""A fresh directory to replay in (the process chdirs into it)."""
def __init__(self, work: pathlib.Path, name: str):
self.dir = pathlib.Path(tempfile.mkdtemp(prefix=f"{name}-", dir=work))
os.chdir(self.dir)
# ── opencode ─────────────────────────────────────────────────────────────────
OC_SCHEMA = """
CREATE TABLE session_v2 (id TEXT PRIMARY KEY, parent_id TEXT, fork_session_id TEXT,
directory TEXT, title TEXT, agent TEXT, version TEXT, time_created INTEGER);
CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER,
time_created INTEGER, data TEXT);
CREATE TABLE event_sequence (aggregate_id TEXT PRIMARY KEY, seq INTEGER);
"""
class OcWriter:
"""Writes the ops into a database with the three tables the mirror reads."""
def __init__(self, path: pathlib.Path):
self.db = sqlite3.connect(path, isolation_level=None)
self.db.executescript(OC_SCHEMA)
self.seq: dict[str, int] = {}
def _bump(self, sid: str) -> int:
self.seq[sid] = self.seq.get(sid, 0) + 1
self.db.execute("INSERT OR REPLACE INTO event_sequence VALUES (?,?)", (sid, self.seq[sid]))
return self.seq[sid]
def apply(self, op: dict) -> None:
k = op["op"]
if k == "session":
self.db.execute("INSERT INTO session_v2 VALUES (?,?,?,?,?,?,?,?)",
(op["id"], op.get("parent"), op.get("fork_of"), op.get("directory"),
op.get("title"), op.get("agent"), op.get("version", "2.0.32"),
op.get("t")))
self._bump(op["id"])
elif k == "title":
self.db.execute("UPDATE session_v2 SET title=? WHERE id=?", (op["title"], op["id"]))
self._bump(op["id"])
elif k == "put":
seq = self._bump(op["sid"])
data = op["data"] if isinstance(op["data"], str) else json.dumps(op["data"])
if self.db.execute("SELECT 1 FROM session_message WHERE id=?",
(op["mid"],)).fetchone():
self.db.execute("UPDATE session_message SET data=? WHERE id=?", (data, op["mid"]))
else:
created = op.get("t")
if created is None:
created = ((op["data"].get("time") or {}).get("created")
if isinstance(op["data"], dict) else 0) or 0
self.db.execute("INSERT INTO session_message VALUES (?,?,?,?,?,?)",
(op["mid"], op["sid"], op["type"], seq, created, data))
elif k == "forks":
pathlib.Path("runner").mkdir(exist_ok=True)
pathlib.Path("runner/ids.json").write_text(json.dumps(op["map"]))
else:
raise ValueError(f"unknown opencode op {k!r}")
def close(self) -> None:
self.db.close()
def oc_real_ops(db_path: pathlib.Path, forks: dict) -> list[dict]:
"""A real database's final state as ops: each session when it was created,
its messages in seq order, the sessions merged by creation time. A row
appears once, already in its final state (opencode rewrote it in place —
the intermediate states are gone)."""
db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
db.row_factory = sqlite3.Row
ses = db.execute("SELECT id, parent_id, fork_session_id, directory, title, agent, version,"
" time_created FROM session_v2").fetchall()
per: dict[str, list[dict]] = {}
for r in db.execute("SELECT id, session_id, type, seq, time_created, data"
" FROM session_message ORDER BY session_id, seq"):
per.setdefault(r["session_id"], []).append(
{"op": "put", "sid": r["session_id"], "mid": r["id"], "type": r["type"],
"data": r["data"], "t": r["time_created"] or 0})
db.close()
streams = []
for r in sorted(ses, key=lambda r: (r["time_created"] or 0, r["id"])):
first = {"op": "session", "id": r["id"], "parent": r["parent_id"],
"fork_of": r["fork_session_id"], "directory": r["directory"],
"title": r["title"], "agent": r["agent"], "version": r["version"],
"t": r["time_created"] or 0}
streams.append([first, *per.get(r["id"], [])])
ops: list[dict] = [{"op": "forks", "map": forks}] if forks else []
ops += list(heapq.merge(*streams, key=lambda o: o["t"] or 0))
return ops
def oc_replay(om, work: pathlib.Path, name: str, account: str, ops: list[dict], mode: str,
cuts: list[int], real: pathlib.Path | None = None,
forks: dict | None = None) -> dict:
Run(work, f"oc-{name}-{mode}")
pathlib.Path("runner").mkdir()
db_path = pathlib.Path("opencode.db")
writer = None
if real is not None and mode == "oneshot":
shutil.copyfile(real, db_path) # the real schema, as opencode wrote it
if forks:
pathlib.Path("runner/ids.json").write_text(json.dumps(forks))
rng_ops: list[dict] = []
else:
writer = OcWriter(db_path)
rng_ops = ops
def mirror():
return om.AccountMirror(account, db_path, pathlib.Path("runner/transcripts") / account,
pathlib.Path("runner/state"), pathlib.Path("runner/ids.json"))
CLOCK.t = FROZEN_NOW
m = mirror()
polls = 0
for a, b in groups(rng_ops, cuts) or [(0, 0)]:
for op in rng_ops[a:b]:
writer.apply(op)
if mode == "restart":
m.close()
m = mirror()
m.tick()
polls += 1
for dt in SETTLE:
CLOCK.t += dt
m.tick()
m.close()
if writer:
writer.close()
return {"files": collect(pathlib.Path("runner/transcripts")), "polls": polls}
# ── agy ──────────────────────────────────────────────────────────────────────
APP = pathlib.Path("home/.gemini/antigravity-cli")
class AgyWriter:
def __init__(self, alive: set[str]):
self.alive = alive
self.partial: dict[int, int] = {} # op index → bytes of its line already written
for d in (APP / "brain", pathlib.Path("logs"), pathlib.Path("runner")):
d.mkdir(parents=True, exist_ok=True)
@staticmethod
def _line(op: dict) -> bytes:
if "raw" in op:
return (op["raw"] + "\n").encode("utf-8", "surrogateescape")
return (json.dumps(op["line"]) + "\n").encode()
@staticmethod
def _target(op: dict) -> pathlib.Path:
if op["op"] == "log":
return pathlib.Path("logs") / f"{op['sid']}.log"
return APP / op["file"]
def apply(self, i: int, op: dict, upto: int | None = None) -> None:
"""Write op ``i`` (``upto``: only that many bytes of its line, for now)."""
k = op["op"]
if k in ("append", "log"):
data = self._line(op)
done = self.partial.get(i, 0)
end = len(data) if upto is None else upto
p = self._target(op)
p.parent.mkdir(parents=True, exist_ok=True)
with p.open("ab") as fh:
fh.write(data[done:end])
self.partial[i] = end
elif k == "write":
p = APP / op["file"]
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(op["text"] if "text" in op else json.dumps(op["json"]))
elif k == "record":
ids = pathlib.Path("runner/ids.json")
d = json.loads(ids.read_text()) if ids.exists() else {}
d[op["sid"]] = {**d.get(op["sid"], {}), **op["fields"]}
ids.write_text(json.dumps(d, indent=1))
elif k == "alive":
(self.alive.add if op["alive"] else self.alive.discard)(op["sid"])
elif k == "log_reset":
(pathlib.Path("logs") / f"{op['sid']}.log").write_bytes(b"")
elif k == "copy":
src = pathlib.Path(op["src"])
dst = APP / op["file"]
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dst)
else:
raise ValueError(f"unknown agy op {k!r}")
def agy_real_ops(snap: pathlib.Path) -> list[dict]:
"""The snapshot's final state as ops, conversation by conversation (oldest
first): its run's record and log (``init`` first, ``result`` events last),
its transcript lines in order (rotated ``chunks/`` first), each subagent's
link and lines right after the parent step that spawned it."""
app = snap / "home/.gemini/antigravity-cli"
ops: list[dict] = []
for rel in ("cache", "conversations"):
for p in sorted((app / rel).rglob("*")) if (app / rel).is_dir() else []:
if p.is_file():
ops.append({"op": "copy", "src": str(p), "file": str(p.relative_to(app))})
ids_path = snap / "runner/ids.json"
ids = json.loads(ids_path.read_text()) if ids_path.exists() else {}
by_conv = {r.get("agy"): sid for sid, r in ids.items() if isinstance(r, dict) and r.get("agy")}
children: dict[str, list[tuple[str, pathlib.Path]]] = {}
child_ids = set()
for f in sorted(app.glob("brain/*/.system_generated/subagents/*.json")):
try:
d = json.loads(f.read_text())
except ValueError:
continue
child = d.get("conversationId") or f.stem
child_ids.add(child)
children.setdefault(f.parent.parent.parent.name, []).append((child, f))
def lines_of(conv: str) -> list[str]:
"""The lines agy wrote, in order. ``chunks/transcript_full/*.jsonl``
are fixed-size byte slices of the transcript (lines cut across them);
like ``read_steps``, they count only when the main file no longer
starts at step 0."""
logs = app / "brain" / conv / ".system_generated/logs"
main = logs / "transcript_full.jsonl"
data = main.read_bytes() if main.is_file() else b""
first = None
for raw in data.split(b"\n"):
try:
first = json.loads(raw).get("step_index")
break
except (ValueError, AttributeError):
continue
if isinstance(first, int) and first > 0:
chunks = b"".join(p.read_bytes() for p in
sorted((logs / "chunks/transcript_full").glob("*.jsonl")))
if chunks and not chunks.endswith(b"\n"):
chunks += b"\n"
data = chunks + data
return [ln for ln in data.decode("utf-8", "surrogateescape").split("\n") if ln]
def tf(conv: str) -> str:
return f"brain/{conv}/.system_generated/logs/transcript_full.jsonl"
def conv_ops(conv: str) -> list[dict]:
out: list[dict] = []
kids = {}
for child, link in children.get(conv, []):
try:
kids.setdefault(json.loads(link.read_text()).get("spawnStepIndex"), []).append(
(child, link))
except ValueError:
pass
pending = dict(kids)
for ln in lines_of(conv):
out.append({"op": "append", "file": tf(conv), "raw": ln})
try:
idx = json.loads(ln).get("step_index")
except (ValueError, AttributeError):
idx = None
for child, link in pending.pop(idx, []):
out.append({"op": "write", "file": str(link.relative_to(app)),
"text": link.read_text()})
out += conv_ops(child)
for rest in pending.values():
for child, link in rest:
out.append({"op": "write", "file": str(link.relative_to(app)),
"text": link.read_text()})
out += conv_ops(child)
return out
convs = [d.name for d in (app / "brain").iterdir() if d.is_dir() and d.name not in child_ids]
convs.sort(key=lambda c: ((app / "brain" / c).stat().st_mtime, c))
for conv in convs:
sid = by_conv.get(conv)
head, tail = [], []
if sid:
ops.append({"op": "record", "sid": sid, "fields": ids[sid]})
ops.append({"op": "alive", "sid": sid, "alive": True})
log = snap / "logs" / f"{sid}.log"
if log.is_file():
for ln in log.read_bytes().decode("utf-8", "surrogateescape").split("\n"):
if not ln:
continue
try:
is_result = json.loads(ln).get("event") == "result"
except (ValueError, AttributeError):
is_result = False
(tail if is_result else head).append({"op": "log", "sid": sid, "raw": ln})
ops += head + conv_ops(conv) + tail
if sid:
ops.append({"op": "alive", "sid": sid, "alive": False})
for sid, r in ids.items(): # records of runs whose conversation is gone
if isinstance(r, dict) and r.get("agy") not in convs:
ops.insert(0, {"op": "record", "sid": sid, "fields": r})
return ops
def agy_replay(am, pids, work: pathlib.Path, name: str, ops: list[dict], mode: str,
cuts: list[int], rng: random.Random, real: pathlib.Path | None = None) -> dict:
Run(work, f"agy-{name}-{mode}")
alive: set[str] = set()
pids._live_record = lambda sid: {"pid": 0} if sid in alive else None
if real is not None and mode == "oneshot":
shutil.copytree(real / "home", "home")
shutil.copytree(real / "logs", "logs")
shutil.copytree(real / "runner", "runner")
todo: list[dict] = []
else:
todo = ops
writer = AgyWriter(alive)
CLOCK.t = FROZEN_NOW
m = am.mirrors()[0]
polls = 0
for a, b in groups(todo, cuts) or [(0, 0)]:
for i in range(a, b):
writer.apply(i, todo[i])
# a cut inside a line: half of the next line is on disk at the poll
if mode in ("chunked", "restart") and b < len(todo) \
and todo[b]["op"] in ("append", "log") and rng.random() < 0.5:
n = len(AgyWriter._line(todo[b]))
if n > 1:
writer.apply(b, todo[b], upto=rng.randrange(1, n))
if mode == "restart":
m = am.mirrors()[0]
m.tick()
polls += 1
for dt in SETTLE:
CLOCK.t += dt
m.tick()
return {"files": collect(pathlib.Path("runner/transcripts")), "polls": polls}
# ── pi ───────────────────────────────────────────────────────────────────────
def pi_runner(tree: pathlib.Path) -> pathlib.Path:
"""The tree's own ``runner/cli.mjs`` (refs before 2026-11-27), else the
harness-pi plugin's (``AB_PI_RUNNER``)."""
own = tree / "runner" / "cli.mjs"
if own.is_file():
return own
p = pathlib.Path(os.path.expanduser(os.environ.get(
"AB_PI_RUNNER", "~/projects/ai-agent-plugins/plugins/harness-pi/runner/cli.mjs")))
if not p.is_file():
raise SystemExit(f"error: no pi runner in {tree} nor at {p} (set AB_PI_RUNNER)")
return p
def pi_replay(tree: pathlib.Path, work: pathlib.Path) -> dict:
"""Each scenario: ``node <runner> <argv>`` (``pi_runner``) with a stub pi
on ``PI_BIN`` and the runner's dirs in a throw-away directory."""
node = os.environ.get("REPLAY_NODE") or shutil.which("node")
if not node:
raise SystemExit("error: node not found (set REPLAY_NODE)")
runner = pi_runner(tree)
# The dir holding runner/ stands for <TREE> either way: the plugin's
# harness-pi/ like a tree's root, so both sides' dumps compare.
home = runner.parent.parent.resolve()
files: dict[str, list[str]] = {}
for sc in FX_PI.SCENARIOS:
run = pathlib.Path(tempfile.mkdtemp(prefix=f"pi-{sc['name']}-", dir=work)).resolve()
cwd = run / "cwd"
cwd.mkdir()
genv = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(run),
"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null"}
subprocess.run(["git", "init", "-q", "-b", "replay"], cwd=cwd, env=genv, check=True)
subprocess.run(["git", "-c", "user.name=replay", "-c", "user.email=replay@localhost",
"commit", "-q", "--allow-empty", "-m", "replay"],
cwd=cwd, env=genv, check=True)
(run / "events.jsonl").write_text("".join(json.dumps(e) + "\n" for e in sc["events"]))
(run / "models.json").write_text(json.dumps(FX_PI.MODELS_JSON))
env = {
"PATH": f"{pathlib.Path(node).parent}:{os.environ.get('PATH', '/usr/bin:/bin')}",
"HOME": str(run / "home"), "TZ": "UTC", "LANG": "C.UTF-8",
"PI_BIN": str(HERE / "mirror_fixtures" / "pi-stub.sh"),
"PI_RUNNER_ROOT": str(run / "pi-root"),
"RUNNER_ENV_FILE": str(run / "no-env-file"),
"PI_MODELS_FILE": str(run / "models.json"),
"PI_REPLAY_ARGV": str(run / "argv"),
"PI_REPLAY_EVENTS": str(run / "events.jsonl"),
"PI_REPLAY_EXIT": str(sc["exit"]),
"NODE_OPTIONS": f"--import={(HERE / 'mirror_fixtures' / 'freeze-clock.mjs').as_uri()}",
"REPLAY_NOW": _dt.datetime.fromtimestamp(FROZEN_NOW, _dt.timezone.utc)
.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null",
}
p = subprocess.run([node, str(runner), *sc["argv"]], cwd=cwd,
env=env, capture_output=True, timeout=120)
def norm(s: str) -> str:
for real, tag in ((str(run), "<RUN>"), (str(run).replace("/", "-"), "<RUN-ENC>"),
(str(home), "<TREE>"),
(str(home).replace("/", "-"), "<TREE-ENC>")):
s = s.replace(real, tag)
return s
for rel, lines in collect(run / "pi-root" / "transcripts").items():
files[norm(f"{sc['name']}/{rel}")] = [norm(ln) for ln in lines]
argv = (run / "argv").read_bytes().decode() if (run / "argv").exists() else ""
files[f"{sc['name']}/pi-argv"] = [norm(a) for a in argv.split("\0")]
files[f"{sc['name']}/exit"] = [str(p.returncode)]
files[f"{sc['name']}/stderr"] = [norm(ln) for ln in
p.stderr.decode("utf-8", "replace").split("\n")]
return {"files": files, "polls": 0}
# ── main ─────────────────────────────────────────────────────────────────────
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--tree", required=True, type=pathlib.Path)
ap.add_argument("--harness", default="opencode,agy,pi")
ap.add_argument("--modes", default="oneshot")
ap.add_argument("--real-snapshot", type=pathlib.Path)
ap.add_argument("--chunks", type=int, default=8)
ap.add_argument("--seed", type=int, default=1)
args = ap.parse_args()
tree = args.tree.resolve()
harnesses = args.harness.split(",")
modes = args.modes.split(",")
work = pathlib.Path(tempfile.mkdtemp(prefix="mirror-replay-"))
out: dict = {"sources": {}}
om, am, pids = freeze(tree)
try:
sources: list[tuple[str, str, list, dict]] = []
if "opencode" in harnesses:
sources.append(("opencode", "fixture", FX_OC.OPS, {"account": FX_OC.ACCOUNT}))
if "agy" in harnesses:
sources.append(("agy", "fixture", FX_AGY.OPS, {}))
snap = args.real_snapshot
if snap:
for d in sorted((snap / "opencode").glob("*")) if (snap / "opencode").is_dir() else []:
if "opencode" in harnesses and (d / "opencode.db").is_file():
forks = json.loads((d / "ids.json").read_text()) \
if (d / "ids.json").is_file() else {}
sources.append(("opencode", f"real-{d.name}",
oc_real_ops(d / "opencode.db", forks),
{"account": d.name, "real": d / "opencode.db",
"forks": forks}))
if "agy" in harnesses and (snap / "agy").is_dir():
sources.append(("agy", "real", agy_real_ops(snap / "agy"),
{"real": snap / "agy"}))
for harness, name, ops, extra in sources:
key = f"{harness}:{name}"
res = {"ops": len(ops), "modes": {}}
for mode in modes:
if mode == "stepwise" and extra.get("real") and len(ops) > STEPWISE_MAX_OPS:
continue
rng = random.Random(f"{args.seed}:{key}:{mode}")
cuts = cuts_for(mode, len(ops), args.chunks, rng)
t0 = _time.time()
if harness == "opencode":
r = oc_replay(om, work, name, extra["account"], ops, mode, cuts,
extra.get("real"), extra.get("forks"))
else:
r = agy_replay(am, pids, work, name, ops, mode, cuts, rng, extra.get("real"))
r["seconds"] = round(_time.time() - t0, 2)
res["modes"][mode] = r
out["sources"][key] = res
if "pi" in harnesses:
t0 = _time.time()
r = pi_replay(tree, work)
r["seconds"] = round(_time.time() - t0, 2)
out["sources"]["pi:fixture"] = {"ops": len(FX_PI.SCENARIOS), "modes": {"oneshot": r}}
finally:
os.chdir("/")
shutil.rmtree(work, ignore_errors=True)
json.dump(out, sys.stdout, ensure_ascii=False)
return 0
if __name__ == "__main__":
sys.exit(main())