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>
403 lines
17 KiB
Python
Executable File
403 lines
17 KiB
Python
Executable File
"""Shared plumbing of the A/B tools (see README.md): materialise a git ref,
|
|
pick the transcript corpus, run a helper in each tree, diff the results.
|
|
|
|
Nothing here imports the product code — the helpers that do run in their own
|
|
subprocess with ``<tree>/backend`` (or ``<tree>/sidecar``) on ``sys.path``, so
|
|
the base ref and the working tree never share an interpreter.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import difflib
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import random
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
|
|
HERE = pathlib.Path(__file__).resolve().parent
|
|
REPO = HERE.parent.parent
|
|
HOME = pathlib.Path.home()
|
|
|
|
# What a base tree needs: backend/ imports cli/resource_urls.py by path
|
|
# (conversations/resources.py). ``runner`` (pi's runner) only exists in refs
|
|
# before 2026-11-27 — it lives in the harness-pi plugin since (missing paths
|
|
# are skipped).
|
|
TREE_PATHS = ("backend", "cli", "sidecar", "runner")
|
|
|
|
# The lab's live transcript sources, as the hub's compose file mounts them
|
|
# (services/ai-agent/docker-compose.yml → core/config.py SOURCE_DIRS,
|
|
# accounts/profiles.py transcripts_dirs). Read in place, never copied.
|
|
# A guest's ~/.claude-guests/<id>/projects is a symlink to the first one.
|
|
DEFAULT_SOURCES: list[tuple[str, pathlib.Path]] = [
|
|
("claude", HOME / ".claude" / "projects"),
|
|
("claude-work", HOME / ".claude-work" / "projects"),
|
|
("pi", HOME / ".pi-runner" / "transcripts"),
|
|
("opencode", HOME / ".opencode-runner" / "transcripts"),
|
|
("agy", HOME / ".agy-runner" / "transcripts"),
|
|
# remote workers' transcripts, pulled by the hub's FeedMirror
|
|
("workers", pathlib.Path(os.environ.get(
|
|
"AB_WORKERS_DIR",
|
|
HOME / "homelab/services/ai-agent/data/workers/transcripts"))),
|
|
]
|
|
# The default corpus cap: about 1 GB of the lab's transcripts, a few minutes.
|
|
DEFAULT_MAX_FILES = 500
|
|
# The lab's OpenRouter catalogue cache (OPENROUTER_CACHE_PATH, plugins/providers.legacy_appe_payload, in the
|
|
# container). Snapshotted once per run so both sides price pi runs alike.
|
|
OPENROUTER_CACHE = pathlib.Path(os.environ.get(
|
|
"AB_OPENROUTER_CACHE",
|
|
HOME / "homelab/services/ai-agent/data/openrouter-models.json"))
|
|
|
|
|
|
# ── trees ────────────────────────────────────────────────────────────────────
|
|
|
|
def git(*args: str) -> str:
|
|
return subprocess.run(["git", "-C", str(REPO), *args], check=True,
|
|
capture_output=True, text=True).stdout.strip()
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def workdir(keep: bool = False):
|
|
"""A scratch dir for this run (base tree, lists, digests)."""
|
|
d = pathlib.Path(tempfile.mkdtemp(prefix="ai-agent-ab-"))
|
|
try:
|
|
yield d
|
|
finally:
|
|
if keep:
|
|
print(f"(kept {d})", file=sys.stderr)
|
|
else:
|
|
shutil.rmtree(d, ignore_errors=True)
|
|
|
|
|
|
def materialise(ref: str, dest: pathlib.Path) -> tuple[pathlib.Path, str]:
|
|
"""``git archive <ref>`` of the product dirs into ``dest``; (tree, sha)."""
|
|
sha = git("rev-parse", "--verify", f"{ref}^{{commit}}")
|
|
present = [p for p in TREE_PATHS
|
|
if git("ls-tree", "--name-only", sha, p)]
|
|
dest.mkdir(parents=True, exist_ok=True)
|
|
ar = subprocess.Popen(["git", "-C", str(REPO), "archive", sha, "--", *present],
|
|
stdout=subprocess.PIPE)
|
|
subprocess.run(["tar", "-x", "-C", str(dest)], stdin=ar.stdout, check=True)
|
|
if ar.wait() != 0:
|
|
raise SystemExit(f"error: git archive {ref} failed")
|
|
return dest, sha
|
|
|
|
|
|
def frozen_env(work: pathlib.Path) -> dict[str, str]:
|
|
"""The environment both sides run with. What is pinned, and why:
|
|
|
|
- ``OPENROUTER_CACHE_PATH``: a snapshot of the lab's OpenRouter catalogue
|
|
(taken once per run), so ``rates_for`` prices pi/OpenRouter models from
|
|
the same file on both sides and never from a half-written one.
|
|
- ``TZ``: ``limit_resets_at`` falls back to it for a limit message that
|
|
names no zone.
|
|
- ``ANTHROPIC_API_KEY`` removed: ``models.list_models`` then serves its
|
|
``FALLBACK`` list instead of calling the API.
|
|
- the catalogue overrides (``PI_MODELS_JSON``, ``OPENCODE_MODELS_JSON``,
|
|
``AGY_MODELS_JSON``, ``SPAWN_DEFAULT_MODEL``…) are passed through
|
|
unchanged — the same value for both sides.
|
|
"""
|
|
env = dict(os.environ)
|
|
snap = work / "openrouter-models.json"
|
|
if not snap.exists():
|
|
try:
|
|
shutil.copyfile(OPENROUTER_CACHE, snap)
|
|
except OSError:
|
|
snap.write_text("{}") # no catalogue: both sides price the flat estimate
|
|
env["OPENROUTER_CACHE_PATH"] = str(snap)
|
|
env["APPE_OPENROUTER_URL"] = "file:///nonexistent/ab-tools-never-fetch"
|
|
env.setdefault("TZ", "Europe/Paris")
|
|
env.pop("ANTHROPIC_API_KEY", None)
|
|
env["MODEL_PRESETS_PATH"] = str(work / "no-model-presets.json")
|
|
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
|
return env
|
|
|
|
|
|
# ── corpus ───────────────────────────────────────────────────────────────────
|
|
|
|
def parse_sources(specs: list[str] | None) -> list[tuple[str, pathlib.Path]]:
|
|
"""``--corpus LABEL=DIR`` (or a bare DIR / FILE) → [(label, path)]."""
|
|
if not specs:
|
|
return DEFAULT_SOURCES
|
|
out = []
|
|
for s in specs:
|
|
label, sep, p = s.partition("=")
|
|
if not sep:
|
|
label, p = pathlib.Path(s).name, s
|
|
out.append((label, pathlib.Path(p).expanduser()))
|
|
return out
|
|
|
|
|
|
def _walk(label: str, root: pathlib.Path):
|
|
if root.is_file():
|
|
yield label, root
|
|
return
|
|
for d, _dirs, names in os.walk(root):
|
|
sub = "subagents" in pathlib.Path(d).parts
|
|
for n in names:
|
|
if n.endswith(".jsonl"):
|
|
yield (f"{label}/subagents" if sub else label), pathlib.Path(d) / n
|
|
|
|
|
|
def pick_corpus(sources: list[tuple[str, pathlib.Path]], days: float,
|
|
max_files: int | None, sample_per_harness: int,
|
|
min_age_s: float, seed: int) -> list[dict]:
|
|
"""The files to compare: everything modified in the last ``days`` plus the
|
|
newest ``sample_per_harness`` of each category (a source, with its
|
|
``subagents/`` apart), whatever their age. ``max_files`` then keeps that
|
|
per-category sample and fills up with a seeded random draw of the rest.
|
|
|
|
A file touched in the last ``min_age_s`` seconds is a live run still being
|
|
written — left out, since the two sides would read different bytes."""
|
|
now = time.time()
|
|
by_cat: dict[str, list[dict]] = {}
|
|
for label, root in sources:
|
|
if not root.exists():
|
|
continue
|
|
for cat, p in _walk(label, root):
|
|
try:
|
|
st = p.stat()
|
|
except OSError:
|
|
continue
|
|
if now - st.st_mtime < min_age_s:
|
|
continue
|
|
by_cat.setdefault(cat, []).append({
|
|
"path": str(p), "cat": cat, "size": st.st_size,
|
|
"mtime_ns": st.st_mtime_ns, "mtime": st.st_mtime})
|
|
cutoff = now - days * 86400
|
|
sample: list[dict] = []
|
|
rest: list[dict] = []
|
|
for cat in sorted(by_cat):
|
|
files = sorted(by_cat[cat], key=lambda f: (-f["mtime"], f["path"]))
|
|
sample += files[:sample_per_harness]
|
|
rest += [f for f in files[sample_per_harness:] if f["mtime"] >= cutoff]
|
|
if max_files is not None and len(sample) + len(rest) > max_files:
|
|
rest.sort(key=lambda f: f["path"])
|
|
random.Random(seed).shuffle(rest)
|
|
rest = rest[:max(0, max_files - len(sample))]
|
|
picked = sorted(sample + rest, key=lambda f: f["path"])
|
|
return picked
|
|
|
|
|
|
def corpus_report(files: list[dict]) -> str:
|
|
cats: dict[str, list[int]] = {}
|
|
for f in files:
|
|
c = cats.setdefault(f["cat"], [0, 0])
|
|
c[0] += 1
|
|
c[1] += f["size"]
|
|
lines = [f"corpus: {len(files)} file(s), "
|
|
f"{sum(f['size'] for f in files) / 1e6:.0f} MB"]
|
|
for cat in sorted(cats):
|
|
n, size = cats[cat]
|
|
lines.append(f" {cat:<22} {n:>6} file(s) {size / 1e6:>8.0f} MB")
|
|
return "\n".join(lines)
|
|
|
|
|
|
def shards(files: list[dict], n: int) -> list[list[dict]]:
|
|
"""``n`` lists of about the same total size (biggest files dealt first)."""
|
|
out: list[list[dict]] = [[] for _ in range(max(1, n))]
|
|
load = [0] * len(out)
|
|
for f in sorted(files, key=lambda f: -f["size"]):
|
|
i = load.index(min(load))
|
|
out[i].append(f)
|
|
load[i] += f["size"] + 4096
|
|
return [s for s in out if s]
|
|
|
|
|
|
def add_corpus_args(ap) -> None:
|
|
ap.add_argument("--corpus", action="append", metavar="[LABEL=]DIR",
|
|
help="transcript dir or file, repeatable (default: the lab's "
|
|
"live sources — claude, claude-work, pi, opencode, agy, "
|
|
"workers)")
|
|
ap.add_argument("--days", type=float, default=60.0,
|
|
help="files modified in the last N days (default 60)")
|
|
ap.add_argument("--max-files", type=int, default=DEFAULT_MAX_FILES,
|
|
help="cap the corpus: the per-category sample, then a seeded "
|
|
f"random draw of the rest (default {DEFAULT_MAX_FILES})")
|
|
ap.add_argument("--all", action="store_true",
|
|
help="no cap: every file of the last --days (the lab's 60 "
|
|
"days are ~7 GB — about 35 min for A/B + chunked)")
|
|
ap.add_argument("--sample-per-harness", type=int, default=40,
|
|
help="always keep the newest N files of each category, "
|
|
"whatever their age (default 40)")
|
|
ap.add_argument("--min-age", type=float, default=300.0, metavar="SECONDS",
|
|
help="skip files modified in the last N seconds — live runs "
|
|
"(default 300)")
|
|
ap.add_argument("--seed", type=int, default=1,
|
|
help="seed of every random draw (default 1)")
|
|
|
|
|
|
def corpus_from_args(args) -> list[dict]:
|
|
files = pick_corpus(parse_sources(args.corpus), args.days,
|
|
None if args.all else args.max_files,
|
|
args.sample_per_harness, args.min_age, args.seed)
|
|
if not files:
|
|
raise SystemExit("error: no transcript found (see --corpus)")
|
|
return files
|
|
|
|
|
|
# ── running helpers ──────────────────────────────────────────────────────────
|
|
|
|
def run_pool(cmds: list[tuple[list[str], dict, pathlib.Path | None]], jobs: int,
|
|
cwd: pathlib.Path | None = None) -> None:
|
|
"""Run commands ``jobs`` at a time; ``(argv, env, stdout file)``. Any
|
|
non-zero exit aborts the tool (exit 2): a helper that crashed proved
|
|
nothing."""
|
|
pending = list(cmds)
|
|
running: list[tuple[subprocess.Popen, list[str], object]] = []
|
|
failed = False
|
|
while pending or running:
|
|
while pending and len(running) < max(1, jobs):
|
|
argv, env, out = pending.pop(0)
|
|
fh = open(out, "wb") if out else None
|
|
running.append((subprocess.Popen(argv, env=env, stdout=fh, cwd=cwd), argv, fh))
|
|
time.sleep(0.05)
|
|
for item in list(running):
|
|
proc, argv, fh = item
|
|
if proc.poll() is None:
|
|
continue
|
|
running.remove(item)
|
|
if fh:
|
|
fh.close()
|
|
if proc.returncode != 0:
|
|
failed = True
|
|
print(f"error: helper exited {proc.returncode}: {' '.join(argv)}",
|
|
file=sys.stderr)
|
|
if failed:
|
|
raise SystemExit(2)
|
|
|
|
|
|
# ── diffs ────────────────────────────────────────────────────────────────────
|
|
|
|
def canonical(obj) -> str:
|
|
"""One stable text for a JSON-able value (sorted keys; a set would be a
|
|
bug in an API payload, so it is rendered, marked, in sorted order)."""
|
|
def default(o):
|
|
if isinstance(o, (set, frozenset)):
|
|
return {"__set__": sorted(o, key=repr)}
|
|
if isinstance(o, tuple):
|
|
return list(o)
|
|
return {"__repr__": repr(o)}
|
|
return json.dumps(obj, sort_keys=True, ensure_ascii=False,
|
|
separators=(",", ":"), default=default)
|
|
|
|
|
|
def digest(obj) -> str:
|
|
return hashlib.sha256(canonical(obj).encode("utf-8", "replace")).hexdigest()
|
|
|
|
|
|
def _short(v, n: int = 70) -> str:
|
|
s = json.dumps(v, ensure_ascii=False, sort_keys=True, default=repr)
|
|
return s if len(s) <= n else s[:n - 1] + "…"
|
|
|
|
|
|
def diff_paths(a, b, path: str = "$", out: list[str] | None = None,
|
|
limit: int = 20) -> list[str]:
|
|
"""The JSON paths where ``a`` (base) and ``b`` (working tree) differ, as
|
|
readable lines — values cut short, at most ``limit`` lines."""
|
|
out = [] if out is None else out
|
|
if len(out) >= limit:
|
|
return out
|
|
if isinstance(a, dict) and isinstance(b, dict):
|
|
for k in sorted(set(a) | set(b), key=str):
|
|
if len(out) >= limit:
|
|
break
|
|
p = f"{path}.{k}"
|
|
if k not in a:
|
|
out.append(f"{p}: only in new = {_short(b[k])}")
|
|
elif k not in b:
|
|
out.append(f"{p}: only in base = {_short(a[k])}")
|
|
else:
|
|
diff_paths(a[k], b[k], p, out, limit)
|
|
elif isinstance(a, list) and isinstance(b, list):
|
|
if len(a) != len(b):
|
|
out.append(f"{path}: length {len(a)} → {len(b)}")
|
|
for i, (x, y) in enumerate(zip(a, b)):
|
|
if len(out) >= limit:
|
|
break
|
|
diff_paths(x, y, f"{path}[{i}]", out, limit)
|
|
elif isinstance(a, str) and isinstance(b, str) and a != b:
|
|
# two long strings: show where they part, not two identical-looking heads
|
|
i = next((k for k, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b)))
|
|
lo = max(0, i - 25)
|
|
head = "…" if lo else ""
|
|
out.append(f"{path}: differ at char {i} (lengths {len(a)} → {len(b)}): "
|
|
f"{head}{_short(a[lo:i + 35], 62)} → {head}{_short(b[lo:i + 35], 62)}")
|
|
elif a != b or type(a) is not type(b):
|
|
out.append(f"{path}: {_short(a)} → {_short(b)}")
|
|
return out
|
|
|
|
|
|
def json_paths(a, b, path: str = "$") -> list[str]:
|
|
"""Every JSON path where ``a`` and ``b`` differ (no values, no limit): a
|
|
key on one side only, a list's length, or a leaf."""
|
|
out: list[str] = []
|
|
if isinstance(a, dict) and isinstance(b, dict):
|
|
for k in sorted(set(a) | set(b), key=str):
|
|
p = f"{path}.{k}"
|
|
if k not in a or k not in b:
|
|
out.append(p)
|
|
else:
|
|
out += json_paths(a[k], b[k], p)
|
|
elif isinstance(a, list) and isinstance(b, list):
|
|
if len(a) != len(b):
|
|
out.append(f"{path}.length")
|
|
for i, (x, y) in enumerate(zip(a, b)):
|
|
out += json_paths(x, y, f"{path}[{i}]")
|
|
elif a != b or type(a) is not type(b):
|
|
out.append(path)
|
|
return out
|
|
|
|
|
|
def generic_path(line: str) -> str:
|
|
"""A diff line's path with its list indexes folded (``$.thread[12].cost`` →
|
|
``$.thread[*].cost``) — to count which fields differ across files."""
|
|
import re
|
|
return re.sub(r"\[\d+\]", "[*]", line.split(": ", 1)[0])
|
|
|
|
|
|
def text_diff(base: str, new: str, base_name: str, new_name: str,
|
|
max_lines: int = 200) -> list[str]:
|
|
lines = list(difflib.unified_diff(
|
|
base.splitlines(), new.splitlines(), base_name, new_name,
|
|
lineterm="", n=1))
|
|
if len(lines) > max_lines:
|
|
lines = lines[:max_lines] + [f"… {len(lines) - max_lines} more diff line(s)"]
|
|
return lines
|
|
|
|
|
|
def dump_ab(script: pathlib.Path, base_ref: str, extra: list[str],
|
|
runner=None, keep: bool = False, cwd=None) -> int:
|
|
"""The ``--base`` mode of a dump tool: run ``script --tree T`` for the base
|
|
ref and for the working tree, back to back with one environment, and diff
|
|
the two texts. 0 = identical, 1 = they differ. ``runner(tree)`` is the
|
|
interpreter argv for a tree (default: this python); ``cwd(tree)`` where it
|
|
runs."""
|
|
runner = runner or (lambda tree: [sys.executable])
|
|
with workdir(keep) as work:
|
|
base, sha = materialise(base_ref, work / "base")
|
|
env = frozen_env(work)
|
|
outs = []
|
|
for name, tree in (("base", base), ("new", REPO)):
|
|
out = work / f"{name}.txt"
|
|
t0 = time.time()
|
|
run_pool([([*runner(tree), str(script), "--tree", str(tree), *extra], env, out)],
|
|
1, cwd=cwd(tree) if cwd else None)
|
|
outs.append(out.read_text())
|
|
print(f"{name}: {len(outs[-1].splitlines())} line(s) in "
|
|
f"{time.time() - t0:.1f}s", file=sys.stderr)
|
|
if outs[0] == outs[1]:
|
|
print(f"OK: identical to {base_ref} ({sha[:8]}) — "
|
|
f"{len(outs[0].splitlines())} line(s)")
|
|
return 0
|
|
print(f"DIFF against {base_ref} ({sha[:8]}):")
|
|
for line in text_diff(outs[0], outs[1], f"base {sha[:8]}", "working tree"):
|
|
print(line)
|
|
return 1
|