Files
ai-agent/scripts/transcripts-v1.py
gabrielvidalandClaude Opus 5.5 e5021e27c2 feat(scripts): transcripts-v1.py — the one-off rewrite of the past pi / opencode / agy transcripts
--verify (read-only, the default) rewrites every lab transcript and its hub
archive copy in a temp dir and parses both with this tree's backend: with no
fix the copy must parse exactly like the original (summary, full, chunked);
each fix alone lists the parse paths it changes. --dry-run, --apply (skips a
session with a live run, a file modified in the last 10 min or one that
changes meanwhile; originals to ~/.cache/ai-agent/transcript-backups/
v1-rewrite-<date>/ with a manifest; mtime + 1 s), --restore (a file a run
appended to since keeps its v1 tail behind a header), --prune (30 days).
The workers' synced copies are left in the old format and counted: the
FeedMirror syncs them by size, a rewrite here would be undone or corrupted.

The v1 reader no longer times a call from a session event (a fact that
changed, not what unblocked the call), so a session event keeps its time
(the resource miner dates a worktree's branch with it); a converter's header
takes the first moment it writes. A mirror that loaded a file in the old
format re-checks its head before appending (it may have been rewritten).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:34:34 +01:00

524 lines
22 KiB
Python
Executable File

#!/usr/bin/env python3
"""One-off: rewrite every past pi / opencode / agy transcript to v1, in place
(the unified transcript format, step 1c — docs/transcript-format.md).
scripts/transcripts-v1.py --verify # read-only proof over every file (the default)
scripts/transcripts-v1.py --dry-run # what --apply would do, nothing written
scripts/transcripts-v1.py --apply # rewrite, originals backed up
scripts/transcripts-v1.py --restore [DIR] # put the originals back (the newest backup)
scripts/transcripts-v1.py --prune # delete backups past their 30 days
What it covers — every place the hub reads these transcripts from:
- the lab's converter dirs, which the hub mounts and imports:
``~/.pi-runner/transcripts``, ``~/.opencode-runner/transcripts/<account>``,
``~/.agy-runner/transcripts/<account>`` (subagent sidechains included);
- the hub's archive copies (``services/ai-agent/data/transcripts``, what the
hub actually parses), rewritten from their own bytes next to their source —
and the archive copies whose source is gone;
- **not** the workers' synced copies (``data/workers/transcripts``, and their
archive copies): the FeedMirror re-downloads or appends to them by size,
without checking the head, so a rewrite here would be undone or corrupted
by the next sync. They stay in the old format, which the hub keeps
reading; ``--verify`` and ``--dry-run`` count them.
``--verify`` parses each original and its rewritten copy (in a temp dir)
with this tree's backend, summary and full: the rewrite with **no fix** must
parse identically (the translation is exact), fed in chunks too; then each
fix alone (``rewrite_v1.FIXES``) is applied and the JSON paths it changes are
listed by kind — the only differences ``--apply`` makes.
``--apply`` skips a file a run is writing (its session's pid record in the
sidecar's ``logs/`` is a live process) or that changed in the last 10 min,
and a file that changes while it is rewritten. Each original goes to
``~/.cache/ai-agent/transcript-backups/v1-rewrite-<date>/`` (outside every
directory the hub scans) with a ``manifest.jsonl``; the new file keeps the
original's mode and takes its mtime + 1 s (so the hub sees it changed but no
run looks recent). Backups are kept 30 days (``--prune``).
``--restore`` puts each original back whose file is still what the rewrite
wrote; a file a run appended to since keeps what it appended, behind a v1
header line (the hub reads the old part, then the v1 part). A file changed
any other way is left and listed.
The hub keeps a parser state per transcript at a byte offset: after
``--apply`` (or ``--restore``) it must re-parse the rewritten files from the
top — the indexer's head fingerprint does that; without it, redeploy with
``services/ai-agent/deploy.sh --force``.
"""
from __future__ import annotations
import argparse
import datetime
import hashlib
import json
import os
import pathlib
import random
import shutil
import sys
import tempfile
import time
HERE = pathlib.Path(__file__).resolve().parent
REPO = HERE.parent
sys.path.insert(0, str(REPO / "backend"))
sys.path.insert(0, str(HERE / "ab"))
import conversations # noqa: E402
from conversations.parse import rewrite_v1 # noqa: E402
from _common import canonical, json_paths # noqa: E402
HOME = pathlib.Path.home()
HUB_DATA = pathlib.Path(os.environ.get("AI_AGENT_DATA", HOME / "homelab/services/ai-agent/data"))
LOG_DIR = pathlib.Path(os.environ.get("SIDECAR_LOG_DIR", HOME / "projects/ai-agent/sidecar/logs"))
BACKUPS = pathlib.Path(os.environ.get("TRANSCRIPT_BACKUPS",
HOME / ".cache/ai-agent/transcript-backups"))
KEEP_DAYS = 30
RECENT_S = 600.0
# (category, harness, source dir) — the hub imports each dir's files under
# their path relative to it (core/config.py SOURCE_DIRS, accounts.transcripts_dirs).
def _sources() -> list[tuple[str, str, pathlib.Path]]:
out = [("pi", "pi", HOME / ".pi-runner/transcripts")]
for harness, root in (("opencode", HOME / ".opencode-runner/transcripts"),
("agy", HOME / ".agy-runner/transcripts")):
if root.is_dir():
out += [(f"{harness}/{d.name}", harness, d) for d in sorted(root.iterdir())
if d.is_dir()]
return out
ARCHIVE = HUB_DATA / "transcripts"
WORKERS = HUB_DATA / "workers" / "transcripts"
# ── files ────────────────────────────────────────────────────────────────────
def _read_lines(p: pathlib.Path) -> list[str]:
return p.read_text(encoding="utf-8", errors="ignore").splitlines()
def _head(p: pathlib.Path, size: int = 256 * 1024) -> list[str]:
"""A file's first lines (its first ``size`` bytes, the last partial line
dropped) — enough to tell which converter wrote it."""
try:
with p.open("rb") as fh:
data = fh.read(size)
except OSError:
return []
lines = data.decode("utf-8", "ignore").split("\n")
return lines[:-1] if len(data) == size else lines
def _records(lines: list[str]) -> list[dict]:
out = []
for ln in lines:
s = ln.strip()
if s.startswith("{"):
try:
out.append(json.loads(s))
except ValueError:
pass
return out
def _is_v1(lines: list[str]) -> bool:
recs = _records(lines[:1])
return bool(recs) and rewrite_v1.is_v1_header(recs[0])
def _sha(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def _session_of(rel: pathlib.PurePath) -> str:
"""The hub session a transcript belongs to: its stem, or for a subagent
sidechain (``<sid>/subagents/agent-x.jsonl``) its parent's."""
parts = rel.parts
if "subagents" in parts:
return parts[parts.index("subagents") - 1]
return rel.stem
def _live(sid: str) -> bool:
"""A sidecar run of ``sid`` is still going (``pids._alive``'s test: the
recorded pid exists, isn't a zombie, and started when it was recorded)."""
try:
rec = json.loads((LOG_DIR / f"{sid}.pid").read_text())
except (OSError, ValueError):
return False
pid = rec.get("pid") if isinstance(rec, dict) else rec
if not isinstance(pid, int):
return False
try:
stat = pathlib.Path(f"/proc/{pid}/stat").read_text()
except OSError:
return False
after = stat[stat.rindex(")") + 1:].split()
if after[0] == "Z":
return False
want = rec.get("starttime") if isinstance(rec, dict) else None
return want is None or str(after[19]) == str(want)
class Target:
"""A transcript to rewrite: where it is, what it is (``kind``: a lab
``source``, its ``archive`` copy — ``of`` the source, rewritten or skipped
with it — or an ``archive-only`` copy whose source is gone)."""
def __init__(self, category: str, harness: str | None, path: pathlib.Path,
rel: pathlib.PurePath, kind: str, of: "Target | None" = None):
self.category, self.harness, self.path, self.rel, self.kind, self.of = \
category, harness, path, rel, kind, of
self.skipped = False
def discover() -> tuple[list[Target], dict]:
"""Every transcript to rewrite, and what is left alone (counts)."""
targets: list[Target] = []
seen_rel: set[str] = set()
left = {"workers": {}, "workers-archive": 0, "v1 already": 0, "claude": 0}
for category, harness, root in _sources():
if not root.is_dir():
continue
for p in sorted(root.rglob("*.jsonl")):
rel = p.relative_to(root)
src = Target(category, harness, p, rel, "source")
targets.append(src)
a = ARCHIVE / rel
if a.is_file():
targets.append(Target(category, harness, a, rel, "archive", of=src))
seen_rel.add(str(rel))
workers_rel = set()
if WORKERS.is_dir():
for p in WORKERS.rglob("*.jsonl"):
rel = str(p.relative_to(WORKERS))
h = rewrite_v1.detect_harness(_records(_head(p)))
if h:
workers_rel.add(rel)
left["workers"][h] = left["workers"].get(h, 0) + 1
if ARCHIVE.is_dir():
for p in ARCHIVE.rglob("*.jsonl"):
rel = str(p.relative_to(ARCHIVE))
if rel in seen_rel:
continue
if rel in workers_rel:
left["workers-archive"] += 1
continue
h = rewrite_v1.detect_harness(_records(_head(p)))
if not h:
continue
targets.append(Target(f"{h}/archive-only", h, p, pathlib.PurePath(rel),
"archive-only"))
return targets, left
# ── verify ───────────────────────────────────────────────────────────────────
def _parse(path: pathlib.Path, full: bool):
try:
return json.loads(canonical(conversations.parse_conversation(path, full=full)))
except Exception as e: # noqa: BLE001 — a crash is a result too
return {"__exception__": f"{type(e).__name__}: {e}"}
def _chunked(path: pathlib.Path, full: bool, seed: str, n: int = 8):
data = path.read_bytes()
rng = random.Random(seed)
cuts = sorted({rng.randrange(1, len(data)) for _ in range(n)} if len(data) > 1 else set())
cuts.append(len(data))
with tempfile.NamedTemporaryFile(suffix=".jsonl", delete=False) as tf:
tmp = pathlib.Path(tf.name)
try:
st = conversations.ParserState(path, full=full)
off, prev = 0, 0
with open(tmp, "ab") as grow:
for cut in cuts:
grow.write(data[prev:cut])
grow.flush()
prev = cut
off = conversations.feed_lines(st, tmp, off)
return json.loads(canonical(st.summary()))
finally:
tmp.unlink(missing_ok=True)
def _generic(path: str) -> str:
import re
return re.sub(r"\[\d+\]", "[*]", path)
def verify(targets: list[Target], show: int) -> int:
print(f"verify: {len(targets)} transcript(s) (read-only; each rewritten copy in a temp dir)")
tmpd = pathlib.Path(tempfile.mkdtemp(prefix="transcripts-v1-"))
per: dict[str, dict] = {}
kinds: dict[str, dict[str, set]] = {} # fix → generic path → files
failed: list[str] = []
skipped = 0
now = time.time()
try:
for i, t in enumerate(targets):
try:
st = t.path.stat()
except OSError:
continue
if now - st.st_mtime < RECENT_S:
skipped += 1
continue
lines = _read_lines(t.path)
if _is_v1(lines):
continue
h = t.harness or rewrite_v1.detect_harness(_records(lines))
if h is None:
continue
c = per.setdefault(f"{h} ({t.kind})", {"files": 0, "identical": 0, "fixed": {}})
c["files"] += 1
# the original under its own name: the parse names a project after the path
name = t.path.name
work = tmpd / str(i)
work.mkdir()
orig = work / "orig" / name
orig.parent.mkdir()
shutil.copyfile(t.path, orig)
base = {full: _parse(orig, full) for full in (False, True)}
def rewritten(fixes, tag):
q = work / tag / name
q.parent.mkdir(exist_ok=True)
q.write_text("\n".join(rewrite_v1.to_v1(lines, h, fixes)) + "\n", encoding="utf-8")
return q
q = rewritten((), "faithful")
ok = True
for full in (False, True):
got = _parse(q, full)
if got != base[full]:
ok = False
failed.append(f" ✗ {t.path} full={full}: the faithful rewrite parses "
f"differently: {json_paths(base[full], got)[:show]}")
if _chunked(q, full, str(t.path)) != got:
ok = False
failed.append(f" ✗ {t.path} full={full}: chunked ≠ one-shot")
if ok:
c["identical"] += 1
for fx in rewrite_v1.FIXES:
q = rewritten((fx,), fx)
changed = False
for full in (False, True):
for p in json_paths(base[full], _parse(q, full)):
kinds.setdefault(fx, {}).setdefault(_generic(p), set()).add(str(t.path))
changed = True
if changed:
c["fixed"][fx] = c["fixed"].get(fx, 0) + 1
shutil.rmtree(work, ignore_errors=True)
finally:
shutil.rmtree(tmpd, ignore_errors=True)
print("\nper harness (where): files · faithful rewrite identical · files each fix changes")
for k in sorted(per):
c = per[k]
fixed = ", ".join(f"{f} {n}" for f, n in sorted(c["fixed"].items())) or "none"
print(f" {k:28} {c['files']:5} · {c['identical']:5} identical · {fixed}")
if skipped:
print(f" ({skipped} file(s) written in the last {int(RECENT_S // 60)} min left out)")
print("\nwhat each fix changes (JSON paths of the parse, list indexes folded; files):")
for fx in rewrite_v1.FIXES:
paths = kinds.get(fx) or {}
nfiles = len(set().union(*paths.values())) if paths else 0
print(f" {fx}: {nfiles} file(s)")
for p, fs in sorted(paths.items(), key=lambda kv: (-len(kv[1]), kv[0]))[:show * 3]:
print(f" {p} ({len(fs)})")
if failed:
print(f"\nFAIL: {len(failed)} difference(s) the rewrite should not make")
print("\n".join(failed[:show * 4]))
return 1
print("\nOK: with no fix every rewritten copy parses exactly like its original "
"(summary and full, chunked too)")
return 0
# ── apply ────────────────────────────────────────────────────────────────────
def _backup_dir(stamp: str) -> pathlib.Path:
return BACKUPS / f"v1-rewrite-{stamp}"
def _write_atomic(path: pathlib.Path, data: bytes, mode: int, mtime: float) -> None:
tmp = path.with_name(f".{path.name}.v1tmp")
with open(tmp, "wb") as fh:
fh.write(data)
fh.flush()
os.fsync(fh.fileno())
os.chmod(tmp, mode)
os.utime(tmp, (mtime, mtime))
os.replace(tmp, path)
def apply(targets: list[Target], dry: bool) -> int:
stamp = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
bdir = _backup_dir(stamp)
manifest = bdir / "manifest.jsonl"
now = time.time()
counts: dict[str, dict] = {}
rows = []
for t in targets:
c = counts.setdefault(f"{t.harness} ({t.kind})", {"rewritten": 0, "v1 already": 0,
"live run": 0, "recent": 0,
"changed": 0, "bytes": [0, 0],
"grow": 0})
try:
st = t.path.stat()
data = t.path.read_bytes()
except OSError:
continue
lines = data.decode("utf-8", "ignore").splitlines()
if _is_v1(lines):
c["v1 already"] += 1
continue
if t.of is not None and t.of.skipped:
c["its source skipped"] = c.get("its source skipped", 0) + 1
continue
if _live(_session_of(t.rel)):
c["live run"] += 1
t.skipped = True
continue
if now - st.st_mtime < RECENT_S:
c["recent"] += 1
t.skipped = True
continue
h = t.harness or rewrite_v1.detect_harness(_records(lines))
new = ("\n".join(rewrite_v1.to_v1(lines, h)) + "\n").encode("utf-8")
c["bytes"][0] += len(data)
c["bytes"][1] += len(new)
c["grow"] += len(new) >= len(data)
if dry:
c["rewritten"] += 1
continue
back = bdir / t.category.replace("/archive-only", "") / t.kind / t.rel
back.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(t.path, back)
st2 = t.path.stat()
if (st2.st_size, st2.st_mtime_ns) != (st.st_size, st.st_mtime_ns):
c["changed"] += 1 # a writer got there first: left as it is now
t.skipped = True
back.unlink()
continue
_write_atomic(t.path, new, st.st_mode & 0o7777, st.st_mtime + 1.0)
row = {"path": str(t.path), "backup": str(back), "harness": h, "kind": t.kind,
"origSize": len(data), "origSha": _sha(data), "origMtime": st.st_mtime,
"newSize": len(new), "newSha": _sha(new), "at": time.time()}
rows.append(row)
with open(manifest, "a", encoding="utf-8") as fh:
fh.write(json.dumps(row) + "\n")
c["rewritten"] += 1
if rows:
(bdir / "README.txt").write_text(
f"Originals of the transcripts scripts/transcripts-v1.py rewrote to v1 on {stamp}.\n"
f"Keep until {(datetime.date.today() + datetime.timedelta(days=KEEP_DAYS)).isoformat()}"
f" (scripts/transcripts-v1.py --prune). Restore: scripts/transcripts-v1.py "
f"--restore {bdir}\n")
verb = "would rewrite" if dry else "rewrote"
print(f"{'dry run' if dry else 'apply'}: {verb} per harness (where):")
for k in sorted(counts):
c = counts[k]
o, n = c["bytes"]
size = f", {o / 1e6:.1f} MB → {n / 1e6:.1f} MB" if o else ""
rest = ", ".join(f"{n} {what}" for what, n in c.items()
if what not in ("rewritten", "bytes", "grow") and n)
grow = f" ({c['grow']} not smaller)" if c["grow"] else ""
print(f" {k:28} {c['rewritten']:5}{size}{grow}{' · skipped: ' + rest if rest else ''}")
if not dry and rows:
print(f"originals: {bdir} (manifest.jsonl; keep {KEEP_DAYS} days)")
return 0
# ── restore / prune ──────────────────────────────────────────────────────────
def restore(bdir: pathlib.Path | None) -> int:
if bdir is None:
dirs = sorted(BACKUPS.glob("v1-rewrite-*"))
if not dirs:
print(f"error: no backup under {BACKUPS}", file=sys.stderr)
return 2
bdir = dirs[-1]
manifest = bdir / "manifest.jsonl"
rows = [json.loads(ln) for ln in manifest.read_text().splitlines() if ln.strip()]
done = grown = changed = 0
for r in rows:
p, back = pathlib.Path(r["path"]), pathlib.Path(r["backup"])
try:
cur = p.read_bytes()
orig = back.read_bytes()
except OSError as e:
print(f" ✗ {p}: {e}")
changed += 1
continue
if _sha(cur) == r["origSha"]:
continue # already the original
st = p.stat()
if _sha(cur) == r["newSha"]:
data = orig
elif len(cur) > r["newSize"] and _sha(cur[:r["newSize"]]) == r["newSha"]:
# a run appended since: what it wrote is v1, behind a header
head = json.loads(cur.split(b"\n", 1)[0])
sw = {k: head[k] for k in ("t", "v", "id", "harness", "cwd", "branch", "sidechain",
"agent") if k in head}
data = orig + (b"" if orig.endswith(b"\n") else b"\n") + \
json.dumps(sw, separators=(",", ":")).encode() + b"\n" + cur[r["newSize"]:]
grown += 1
else:
print(f" ✗ {p}: changed since the rewrite — left as it is")
changed += 1
continue
_write_atomic(p, data, st.st_mode & 0o7777, max(st.st_mtime, r["origMtime"]) + 1.0)
done += 1
print(f"restore from {bdir}: {done} file(s) put back ({grown} keep what a run appended "
f"since, behind a v1 header), {changed} left")
return 1 if changed else 0
def prune() -> int:
cutoff = time.time() - KEEP_DAYS * 86400
gone = 0
for d in sorted(BACKUPS.glob("v1-rewrite-*")):
if d.stat().st_mtime < cutoff:
shutil.rmtree(d)
gone += 1
print(f" deleted {d}")
print(f"prune: {gone} backup(s) older than {KEEP_DAYS} days deleted")
return 0
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
g = ap.add_mutually_exclusive_group()
g.add_argument("--verify", action="store_true", help="read-only proof (the default)")
g.add_argument("--dry-run", action="store_true", help="what --apply would do")
g.add_argument("--apply", action="store_true", help="rewrite in place, originals backed up")
g.add_argument("--restore", nargs="?", const="", metavar="DIR",
help="put the originals back (default: the newest backup)")
g.add_argument("--prune", action="store_true", help=f"delete backups older than {KEEP_DAYS} days")
ap.add_argument("--show", type=int, default=6, help="paths shown per fix (default 6)")
ap.add_argument("--only", action="append", metavar="PATH",
help="only these files (repeatable; for a trial)")
args = ap.parse_args()
if args.restore is not None:
return restore(pathlib.Path(args.restore) if args.restore else None)
if args.prune:
return prune()
targets, left = discover()
if args.only:
want = {str(pathlib.Path(p).resolve()) for p in args.only}
targets = [t for t in targets if str(t.path.resolve()) in want]
w = ", ".join(f"{n} {h}" for h, n in sorted(left["workers"].items())) or "none"
print(f"left in the old format (the hub reads it): workers' synced copies: {w} "
f"(+ {left['workers-archive']} archive copies of them)")
if args.apply or args.dry_run:
return apply(targets, dry=args.dry_run)
return verify(targets, args.show)
if __name__ == "__main__":
sys.exit(main())