Files
ai-agent/scripts/ab/README.md
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

347 lines
21 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# scripts/ab — proving a refactor changes nothing
Tools that compare a **base git ref** with the **working tree** and exit 1 on
any difference. They are the safety net for the provider-registry /
`parse.py` split / unified-transcript work: the parser, the price book, the
model catalogue and the sidecar's launch code may be restructured freely as
long as every command below still says `OK`.
There is **no stored baseline**. Each tool materialises the base ref
(`git archive <ref> backend cli sidecar` — plus `runner` in a ref from before
2026-11-27 — into a temp dir), runs the same
helper once per tree in separate processes, back to back, with one frozen
environment, and diffs the two outputs. What depends on the day — the price
book, the OpenRouter catalogue, the clock — is the same on both sides and
cancels out.
```bash
scripts/ab/parse-ab.py --base HEAD # parser, A/B over real transcripts
scripts/ab/parse-ab.py --chunked # incremental feed == one-shot parse
scripts/ab/parse-ab.py --base main --rename tools-v45 # a planned rename, and nothing else
scripts/ab/pricing-dump.py --base HEAD # price book
scripts/ab/catalog-dump.py --base HEAD # GET /api/models, owner + guests
scripts/ab/launch-dump.py --base HEAD # what the sidecar would launch
scripts/ab/mirror-replay.py --base HEAD [--real] # the three converters, native source → JSONL
scripts/ab/mirror-replay.py --base REF --parse [--real] # a format change: same hub parse
scripts/ab/mirror-replay.py --incremental [--real] # opencode / agy fed in steps == one-shot
cd backend && python3 -m unittest test_parse_fixtures # chunked == one-shot, v1 == legacy, readers; no corpus needed
cd sidecar && uv run --quiet --with pytest --with httpx --with-requirements requirements.txt \
python -m pytest -q test_mirror_replay.py # the converters' fixtures, no lab data needed
```
`--base` takes any ref (`HEAD`, `main`, a sha). Without `--base` the three
dump tools print the working tree's dump. Exit codes everywhere: `0` identical,
`1` a difference, `2` usage or setup error (a helper that crashed proved
nothing).
Before a refactor commit: all of them with `--base main` (or the commit before).
A zero diff also means `PARSER_VERSION` (`backend/indexer.py`) stays as it is.
A step that *means* to change the output by a rename (and bumps
`PARSER_VERSION`) proves that is all it changes with `--rename`, below.
## The corpus
`parse-ab.py` and `pricing-dump.py` read the lab's **real transcripts in
place**. Nothing is copied into the repo, and a differing value is only
printed cut to 70 characters. The default sources are the dirs the hub's
compose file mounts (`backend/core/config.py` `SOURCE_DIRS`):
| Category | Directory |
|---|---|
| `claude`, `claude/subagents` | `~/.claude/projects` |
| `claude-work`, `…/subagents` | `~/.claude-work/projects` |
| `pi` | `~/.pi-runner/transcripts` |
| `opencode` | `~/.opencode-runner/transcripts` |
| `agy`, `agy/subagents` | `~/.agy-runner/transcripts` |
| `workers`, `workers/subagents` | `~/homelab/services/ai-agent/data/workers/transcripts` (`AB_WORKERS_DIR`) |
A guest's `~/.claude-guests/<id>/projects` is a symlink to the first one. The
hub's archive (`services/ai-agent/data/transcripts`, a superset that keeps what
Claude Code pruned) is not in the default — pass it with `--corpus`.
Selection, same flags on both tools:
| Flag | Default | Meaning |
|---|---|---|
| `--corpus [LABEL=]DIR` | the table above | a dir or a file, repeatable; replaces the defaults |
| `--days N` | 60 | files modified in the last N days… |
| `--sample-per-harness N` | 40 | …plus the newest N of each category, whatever their age |
| `--max-files N` | 500 | cap: the per-category sample, then a seeded random draw of the rest |
| `--all` | off | no cap |
| `--min-age SECONDS` | 300 | skip files written in the last 5 min (live runs) |
| `--seed N` | 1 | seed of the draw and of the chunk offsets |
Measured on the lab on 2026-11-23, `--jobs 2`, the box busy (load 25):
| Run | Corpus | Wall clock |
|---|---|---|
| `parse-ab.py --base HEAD` | default: 500 files, 825 MB | 1 min 40 s |
| `parse-ab.py --chunked` | default | 1 min 45 s |
| `parse-ab.py --base HEAD --all` | 3,410 files, 7.4 GB | 24 min |
| `parse-ab.py --chunked --all` | 3,410 files, 7.4 GB | 11 min |
| `pricing-dump.py --base HEAD` | default (model scan) | 18 s |
| `catalog-dump.py --base HEAD` | — | 14 s |
| `launch-dump.py --base HEAD` | — | 8 s |
| `test_parse_fixtures` | 8 fixtures (5 legacy-format, 3 v1) + reader unit tests | 3 s |
| `mirror-replay.py --base HEAD` | fixtures | 7 s |
| `mirror-replay.py --base HEAD --real` | + 8 opencode sessions (99 rows), 38 agy conversations (4,364 lines) | 9 s |
| `mirror-replay.py --incremental` | fixtures | 22 s |
| `mirror-replay.py --incremental --real` | default `--chunks 8` | 45 s |
| `mirror-replay.py --incremental --real --chunks 300` | | 3 min 10 s |
| `mirror-replay.py --base 8981fe28 --parse --real` (2026-11-25) | fixtures + 9 opencode sessions, 43 agy conversations | 25 s |
| `test_mirror_replay.py` | fixtures, replayed twice | 5 s |
The default keeps every category's newest 40 files (so every pi, opencode,
agy and work-account transcript the lab has) and a seeded random seventh of
the claude and worker ones. Run `--all` once before a risky step, the default
on every commit.
A file that changes while the tool runs (a live conversation) is detected by
its size and mtime before and after each parse and left out of the verdict
(`N skipped`).
## `parse-ab.py --base REF`
Both trees run `parse_conversation(p, full=False)` and `full=True` on every
file (`_parse_worker.py`, `--jobs` processes at a time, default 2). Each
summary is turned into canonical JSON (sorted keys) and hashed; the driver
compares the hashes, then re-parses only the first `--show` (10) differing
files on both sides and prints the **JSON paths** that differ (`--paths`, 20
per file):
```
✗ /home/…/1f0e….jsonl [claude]
full=False: 3 path(s)
$.cost: 4.3125 → 4.4170
$.byModel.claude-opus-4-8.cost: 4.3125 → 4.4170
$.title: differ at char 80 (lengths 90 → 80): …"s accents in the café names and" → …"s accents in the café"
```
An exception raised by a parse is a result too (`EXC TypeError: …`): both
sides must fail alike.
## `parse-ab.py --base REF --rename NAME`
For a step whose whole point is a rename of the output — the neutral tool
names of parser v45 (`tools-v45`): the base side's summaries go through
`renames.TRANSFORMS[NAME]` before they are hashed, so the diff must still be
**zero**. The transform restates the rename on its own (`renames.py` imports
no product code): a slip in the product's table shows up as a difference
instead of being copied into the expectation. `tools-v45` renames the tool
cards' `name` (adding `native` = the old name), `taskRef.name`, the orphan
results' `name`, the buckets `bash` → `shell` and `task` → `todo` in `byTool`,
`byToolSub` and `turnBucket`, and byToolSub's tool sub-keys; it moves
TaskOutput / TaskStop out of the catch-all `tool` bucket into `shell` (sub-key
`?`), TaskGet / TaskList into `todo`.
The `byTool` / `byToolSub` **costs** are compared apart from the rest of the
summary: exactly, except at the paths the transform re-summed (two old cells
merged into one — `TaskCreate` + `TaskUpdate` → `todo/todo` — or a cell moved
out of a bucket's total), where the new parser adds the same terms in another
order; there they must agree to a relative 1e-9 and the run says how many did:
```
parse A/B: 296 file(s) compared × 2 modes, 0 differing, 0 skipped (changed during the run) — 70s
re-summed costs equal to rounding only: 34 in 14 file(s) (relative 1e-09); every other value identical
OK: the parser output is identical once the tools-v45 rename is applied to the base
```
A differing file is shown as usual, its base side transformed. Checked both
ways on 2026-11-24: without `--rename` every file differs; with a wrong entry
in the transform (`Read` → `reed`) the files with a Read card do.
## `parse-ab.py --chunked`
The byte-offset contract, on the working tree alone: each file is fed through
`conversations.feed_lines` as a growing temp copy, cut at `--chunks` (8) seeded
random byte offsets — most of them in the middle of a line — with `summary()`
called after every chunk. The last summary must equal the one-shot
`parse_conversation`, for both `full` modes; `summary()` called twice must
give the same thing; the offset `feed_lines` returns must stay inside the
bytes written. `--tmp-dir` moves the temp copy (one file at a time per job)
off the default temp dir.
`--base REF --chunked` runs both checks.
## `pricing-dump.py`
For every model id the corpus names (a byte regex over the same selection;
`--no-corpus` skips it), every catalogue model and a fixed list of edge ids
(dated, Bedrock-prefixed and unknown Claude ids, every GPT tier, Gemini ids
with their effort suffix, local ids and their opencode twins, OpenRouter ids,
junk) × speed (none, `standard`, `fast`, plus any other the corpus uses) × 15
usage shapes (empty, small, flat and split cache writes, cache-heavy, exactly
at and over the 100K / 200K / 272K prompt tiers, 900K, reasoning tokens,
output only, nulls): `rates_for`, `usage_cost`, `usage_cache_cost`,
`plan_units`; per model also `local_call` over 7 durations × 5 dates,
`models.is_local` and `models.context_window`. Floats are printed with `repr`.
## `catalog-dump.py`
`models.list_models()` and the payload of the real `GET /api/models` handler
for 48 scenarios: owner / guest with no extra model / a few / every key ×
OpenRouter key fine / refused / sidecar silent × agy hosted or not × the
default presets / a tuned preset file. No Anthropic key (the `FALLBACK` list),
`urlopen` raises, the sidecar probe answers from the scenario. Runs under
`uv run --with-requirements backend/requirements.txt` (the web deps are not on
the host).
## `launch-dump.py`
82 `POST /spawn`, `/resume` and `/fork` bodies — claude, pi, opencode, agy;
model, effort, thinking, account, scope (with and without `noBash`), lean,
extras, Chrome, Code Mode, compact, and the refusals — through the real route
handlers (`routes_runs.spawn` / `resume`, `fork.fork`), so `_claude_args`, the
inline pi branch, `_opencode_launch`, `_agy_launch` and `launch._launch` all
run. Per request: the answer (or the HTTP error) and every process it would
start — argv, cwd, the sorted environment **keys**, stdin.
Nothing is launched and nothing of the machine is read: `subprocess.Popen` and
`subprocess.run` are recorders, the network is off, and the sidecar runs with
a synthetic environment in a throw-away `HOME` (a work Claude login, three
opencode accounts — one keyless, one signed out — an agy account, sessions to
resume and fork). Only two product functions are replaced, both
fire-and-forget: `local_room.make_room_async` and `agy_mirror.kick` (their
calls are listed). Environment **values are never printed**: a key the sidecar
set or changed shows as `KEY#<8 hex>`, a hash of its value. Paths are
normalised (`<TREE>`, `<HOME>`, `<PYTHON>`). Runs under
`uv run --with-requirements sidecar/requirements.txt`.
## `mirror-replay.py`
The three converters that turn another harness's native data into the v1
transcripts the hub parses (Claude-Code-shaped JSONL before step 1c):
`sidecar/opencode_mirror.py` (opencode's SQLite),
`sidecar/agy_mirror.py` (agy's `brain/…/transcript_full.jsonl` + the run log)
and pi's runner `cli.mjs` (`TranscriptWriter`, fed by `pi --mode json`; the
tree's `runner/` before 2026-11-27, else the harness-pi plugin's — `AB_PI_RUNNER`,
default `~/projects/ai-agent-plugins/plugins/harness-pi/runner/cli.mjs`). Each tree
runs `_mirror_worker.py` (under `uv run --with-requirements
<tree>/sidecar/requirements.txt`) on the **same** sources — always the working
tree's `mirror_fixtures/` — and the driver compares the files written
(transcripts, subagent sidechains, `.meta.json`; not the mirrors' private
`state/`). `--base REF` is byte for byte; a difference is shown as the
records' keys and JSON paths (`--text-diff`: a unified diff of the fixtures).
| Source | How it is replayed |
|---|---|
| `opencode:fixture` | `mirror_fixtures/opencode.py`: an ordered list of the writes opencode makes (`session`, `title`, `put` = insert or rewrite a message row, `forks` = the fork route's `ids.json`) into a fresh database with the three tables the mirror reads; `AccountMirror.tick()` |
| `agy:fixture` | `mirror_fixtures/agy.py`: transcript lines, subagent links, run-log lines (`init`, `result`), a resume rewriting the log, `ids.json` records, run liveness; the sidecar's own `agy_mirror.mirrors()` |
| `pi:fixture` | `mirror_fixtures/pi.py`: 5 scenarios (argv, events, exit code) run as `node <runner>/cli.mjs …` (the tree's, else `AB_PI_RUNNER`) with `PI_BIN` = `pi-stub.sh` (prints the events, records its argv), `PI_RUNNER_ROOT`, `PI_MODELS_FILE`, `RUNNER_ENV_FILE` in a temp dir. The dump holds the transcript, the argv pi got, the exit code and stderr |
| `opencode:real-<account>` (`--real`) | a `sqlite3` backup of `~/.local/share/opencode/opencode.db` (`AB_OPENCODE_DBS=acct=path,…`) + `~/.opencode-runner/ids.json` |
| `agy:real` (`--real`) | copies of `~/.gemini/antigravity-cli/brain/*/.system_generated/{logs,subagents}`, `cache/last_conversations.json`, the head of each terminal conversation's `conversations/<id>.db`, `~/.agy-runner/ids.json` and those runs' logs (`AB_AGY_LOG_DIR`, default the canonical checkout's `sidecar/logs`); conversations written in the last `--min-age` (300) s are left out |
Real data is copied to the temp dir first and never printed whole: the plain
dump shows each real file's line count and hash, a diff shows JSON paths
with values cut to 70 characters.
**`--incremental`** replays each opencode / agy source again, growing:
`stepwise` (a poll after every op), `chunked` (`--chunks` seeded cut points;
for agy a cut can fall inside a line, half of it on disk at the poll) and
`restart` (a fresh mirror object for every poll — a sidecar restart). Every
mode ends with the same settle polls (the clock moved 5 s, 30 s, 1 h). A real
source is replayed from its final state (each opencode row once; each agy
conversation's lines in order, its subagents' right after the step that
spawned them, the run's `result` events last). Byte-identical output is
`OK`; otherwise each transcript is parsed by the working tree's backend
(`_parse_worker.py --mode dump`) and the summaries must match — a mismatch
is `DIFF` (exit 1), and the byte differences are listed either way.
**`--base REF --parse`** is for a change of the format itself (step 1c: the
converters went from Claude Code's records to v1), where bytes can't match.
Each tree's one-shot output is parsed by the working tree's backend, summary
and full, subagent sidechains included:
1. the base output (old format) rewritten to v1 with no fix
(`conversations/parse/rewrite_v1.py`, `_parse_worker.py --mode v1`) must
parse exactly like itself — the rewrite is faithful;
2. the working tree's output must parse like the base output rewritten with
every fix (`whole_steps`, `source_times`, `harness`, `no_pi_fallback`),
up to `INTENDED` — a tool's `native` is the harness's own name in v1, the
old format only had Claude Code's; the run says how many parses each fix
changed;
3. the working tree's output fed through `feed_lines` at seeded cuts must
parse like it does in one go.
```
OK agy:real: 43 transcript(s) — the v1 output parses like the old one (fixes: source_times in 66 parse(s); intended: native ×1773)
chunked == one-shot on all 43 (8 cuts each)
```
What it found on 2026-11-23 (reported then; fixed by step 1c on 2026-11-25 —
the converters write a step whole, agy's closes carry a source time):
- **opencode, by design not byte-identical**: a step first seen while it
streams goes out as its content, then a content-less `usage:<id>` record
(with `stop_reason`); a step already over goes out as one. The title record
lands where it was first seen. **The hub parses the two differently**
(`full=True` only, totals equal): the split step's thread item loses `out`
(its output tokens), and `durationMs` / `turnBucket` / `turnCacheCost`
shift — `DIFF` on `opencode:fixture` in every incremental mode.
- **agy, by design not byte-identical**: a background tool's result
(`RUNNING`, then `DONE` for the same step) goes out when it finishes, not in
step order; same hub parse. The lab's real agy data (38 conversations) was
byte-identical at 8 and at 300 polls.
- **Records stamped with the mirror's clock** (the trailing note): agy's
`turn_end`, interrupt marker, interrupted tool results and API-error turns
carry the time the mirror wrote them, not a source time — a replay sees
2099.
Since step 1c: opencode's incremental replays end on the one-shot output's
groups of events (only the title may land elsewhere) and the hub parses them
alike; agy's background results still go out when they finish; no agy
record carries the frozen clock. pi's runner has no other clock than its
own (its events are live), so the note leaves it out.
## What is frozen for both sides
| What | How | Why |
|---|---|---|
| OpenRouter catalogue | `OPENROUTER_CACHE_PATH` = a snapshot of the lab's `openrouter-models.json` taken once per run (`AB_OPENROUTER_CACHE`) | `rates_for` prices pi/OpenRouter models from it |
| Timezone | `TZ` (default `Europe/Paris`) | `limit_resets_at` falls back to it when a limit message names no zone |
| Anthropic key | removed | `models.list_models()` then serves `FALLBACK` instead of calling the API |
| Presets file | `MODEL_PRESETS_PATH` → a path that doesn't exist | the lab's presets must not leak into the catalogue dump |
| Date in a lean run's system prompt | `time.strftime` frozen in `launch-dump.py` | `launch.lean_prompt` writes "now" into argv |
| The converters' clock | `mirror-replay.py`: `time.time` / `datetime.now` of both Python mirrors, and node's `Date` in the runner (`freeze-clock.mjs`, `NODE_OPTIONS=--import`) = 2099-01-01T00:00:00Z | every pi timestamp, agy's `turn_end` / interrupt / API-error records, opencode's fallback stamp, agy's quiet windows, opencode's fork wait |
| Output paths | the mirrors run with **relative** dirs (`runner/`, `home/`, `logs/` via `SIDECAR_AGY_DIR`, `SIDECAR_AGY_ACCOUNTS`, `SIDECAR_LOG_DIR`) inside their temp dir | the record uuids are `uuid5(<output path>:<key>)` |
| Git branch | `_git_branch` of both mirrors → `replay-branch`; pi's cwd is a fresh repo on branch `replay` | real cwds are the lab's repos, whose branch moves |
| Temp paths (pi) | `<RUN>`, `<RUN-ENC>` (the `/`→`-` transcript dir), `<TREE>` replaced in the dump | the runner writes its cwd, and pi's argv names `<tree>/runner/extensions` (the plugin's `harness-pi/` stands for `<tree>`) |
| Is an agy run alive | `pids._live_record` answers from the replay's `alive` ops | a dead run closes its turn |
The parser's summary itself reads no clock: nothing had to be frozen in
the parser (`conversations/parse/`). `PYTHONHASHSEED` is deliberately **not** pinned — the two sides
hash strings differently, so an output that depended on set order would show
up as a diff.
## Not covered
- The frontend, `projects/costs.py`, the usage readers and plan labels.
- The sidecar as a **worker** (no `SIDECAR_TOKEN`: outbox env, proxied
accounts, a guest computer's own login), `routes_accounts.py`, `/interrupt`,
`/message`, `_stop_run` on a forced resume, and what the launched process
does — only that it would be started.
- In `mirror-replay.py`: pi's `--fork-from` / `--resume` without `--model`
(they read pi's session files), an interrupted pi (SIGINT), the EVOX2
wake; opencode's `MirrorThread` / proxied accounts and the deferred-fork
wait for `ids.json` without a new database write; agy's binding of a run
still pending (`pendingSince` in the last 120 s), the `chunks/` rotation as
agy writes it (replayed as one file), and `ABANDONED_S`. Real data is only
replayed in its final state (opencode rewrites rows in place: their
streaming states are gone), so a live run's step/usage split is covered by
the fixtures only.
- `find_cut_line`, `limit_resets_at` on their own, the indexer, the archive
import, and every API route other than `/api/models`.
- `pricing-dump.py` prices models with the catalogue each tree declares: a
model added to one tree shows as added lines (a real difference, as wanted).
## Files
| File | Role |
|---|---|
| `_common.py` | base-ref materialisation, corpus selection, the frozen env, JSON path diff, the `--base` runner of the dump tools |
| `_parse_worker.py` | runs inside one tree: `digest`, `dump`, `chunked` (`--transform`, `--split-costs` for `--rename`), `v1` (the rewrite, for `mirror-replay.py --parse`) |
| `renames.py` | the renames a step is meant to make (`tools-v45`), applied to the base output by `--rename` |
| `backend/fixtures/transcripts/` + `backend/test_parse_fixtures.py` | synthetic transcripts, one per harness (+ a v1 twin of pi / opencode / agy), the chunked == one-shot test that needs no corpus, v1 == legacy, the readers' unit tests |
| `mirror-replay.py`, `_mirror_worker.py` | the converters' replay: driver (snapshot, A/B, incremental, hub parse) and the per-tree helper |
| `mirror_fixtures/` + `sidecar/test_mirror_replay.py` | the synthetic opencode / agy / pi sources (ops, events, the stub `pi`, the frozen node clock) and their test |