runner/cli.mjs (pi), sidecar/opencode_mirror.py and sidecar/agy_mirror.py write v1 events (docs/transcript-format.md) instead of Claude-Code-shaped records: a header naming the harness, each model step whole — its call, its blocks, its usage, in one append — tool calls under their neutral name with the harness's own in `native`, the hub envelopes (author tag, inbox note) unwrapped and the old text conventions said as events. Shared Python helpers in sidecar/transcript_v1.py (Out: header, moved facts, dedup keys rebuilt from the file, a v1 header before the first v1 line appended to an old-format file); backend/test_converter_tables.py keeps its copies of the hub's tables equal to the hub's. - opencode: a step goes out once it has ended (its tokens come then, after its tools ran), so a step seen while it streamed no longer splits into content + a late usage record (quirk a). A step still running when its turn ends (idle, a new turn, the next step) goes out as it stands; a step that failed or was aborted and left nothing is not written (its error, or the interrupt, says it). - agy: what closes a turn (turn_end, the interrupt, the interrupted results, the API-error call) carries the latest time agy recorded in it, never the mirror's clock (quirk c). - pi: a fork copies its source's v1 history under the new id. - gen_progress.tool_running reads v1 transcripts too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
181 lines
9.6 KiB
JavaScript
181 lines
9.6 KiB
JavaScript
// The runner against a fake `pi` that replays scripted JSON events: it writes
|
|
// v1 (a header naming pi, each step whole), compactions become the viewer's
|
|
// divider, a reply a full context cut off is continued (once per cut, at most
|
|
// RUNNER_AUTO_CONTINUES times) with one turn_end at the very end, and a
|
|
// transcript from before v1 is continued behind a v1 header.
|
|
// Run: node --test runner/test/cli.test.mjs
|
|
import { test } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { spawnSync } from "node:child_process";
|
|
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, readdirSync, chmodSync } from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "cli.mjs");
|
|
const SID = "01a2ffff-0000-7000-8000-00000000c0de";
|
|
const MODEL = "fake-model";
|
|
|
|
const usage = (input, output) => ({ input, output, cacheRead: 0, cacheWrite: 0,
|
|
cost: { total: 0 } });
|
|
const reply = (stopReason, text, input, output) => ({ type: "message_end", message: {
|
|
role: "assistant", model: MODEL, provider: "fake", stopReason,
|
|
content: text ? [{ type: "text", text }] : [], usage: usage(input, output) } });
|
|
const compaction = (tokensBefore, estimatedTokensAfter, reason = "threshold") => [
|
|
{ type: "compaction_start", reason },
|
|
{ type: "compaction_end", reason, aborted: false, willRetry: false,
|
|
result: { summary: "## Goal\nthe summary", firstKeptEntryId: "x", tokensBefore,
|
|
estimatedTokensAfter } },
|
|
];
|
|
const settled = { type: "agent_settled", aborted: false };
|
|
|
|
/** Run the runner with a fake pi whose Nth invocation prints scripts[N]
|
|
* (`before`: lines the transcript already holds). */
|
|
function run(scripts, extraEnv = {}, before = null, argv = null, setup = null) {
|
|
const dir = mkdtempSync(path.join(os.tmpdir(), "pi-runner-test-"));
|
|
if (before) {
|
|
const t = path.join(dir, "root", "transcripts", dir.replaceAll("/", "-"));
|
|
mkdirSync(t, { recursive: true });
|
|
writeFileSync(path.join(t, `${SID}.jsonl`), before.map((o) => JSON.stringify(o)).join("\n") + "\n");
|
|
}
|
|
writeFileSync(path.join(dir, "scripts.json"), JSON.stringify(scripts));
|
|
writeFileSync(path.join(dir, "models.json"),
|
|
JSON.stringify({ providers: { fake: { models: [{ id: MODEL }] } } }));
|
|
const fake = path.join(dir, "fake-pi.mjs");
|
|
writeFileSync(fake, `#!/usr/bin/env node
|
|
import { readFileSync, appendFileSync } from "node:fs";
|
|
const dir = ${JSON.stringify(dir)};
|
|
const calls = dir + "/calls.jsonl";
|
|
let n = 0; try { n = readFileSync(calls, "utf8").split("\\n").filter(Boolean).length; } catch {}
|
|
appendFileSync(calls, JSON.stringify(process.argv.slice(2)) + "\\n");
|
|
const scripts = JSON.parse(readFileSync(dir + "/scripts.json", "utf8"));
|
|
for (const e of scripts[Math.min(n, scripts.length - 1)]) process.stdout.write(JSON.stringify(e) + "\\n");
|
|
`);
|
|
chmodSync(fake, 0o755);
|
|
if (setup) setup(dir);
|
|
const r = spawnSync(process.execPath, [CLI, ...(argv ?? ["-p", "do the task", "--session-id", SID, "--model", MODEL])], {
|
|
cwd: dir, encoding: "utf8",
|
|
env: { ...process.env, PI_BIN: fake, PI_RUNNER_ROOT: path.join(dir, "root"),
|
|
PI_MODELS_FILE: path.join(dir, "models.json"), RUNNER_ENV_FILE: path.join(dir, "none"),
|
|
RUNNER_PERM_EXT: path.join(dir, "none.ts"), ...extraEnv },
|
|
});
|
|
assert.equal(r.status, 0, r.stderr);
|
|
const tdir = path.join(dir, "root", "transcripts");
|
|
const file = path.join(tdir, readdirSync(tdir)[0], `${SID}.jsonl`);
|
|
const records = readFileSync(file, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));
|
|
const calls = readFileSync(path.join(dir, "calls.jsonl"), "utf8").split("\n").filter(Boolean)
|
|
.map((l) => JSON.parse(l));
|
|
return { records, calls };
|
|
}
|
|
|
|
// What the transcript says, one word per event (a step's blocks and usage
|
|
// left out: `step` stands for its call).
|
|
const kinds = (evs) => evs
|
|
.filter((e) => !["session", "usage", "text", "thinking", "tool_call"].includes(e.t))
|
|
.map((e) => e.t === "prompt" ? "user"
|
|
: e.t === "call" ? "step"
|
|
: e.t === "inject" && e.kind === "compact_summary" ? "summary"
|
|
: e.t === "inject" && e.text.startsWith("<pi-runner-auto-continue>") ? "continue"
|
|
: e.t);
|
|
|
|
test("a mid-run compaction is the viewer's divider, and the run is not continued", () => {
|
|
const { records, calls } = run([[
|
|
reply("toolUse", "", 90000, 50), ...compaction(98500, 21000), reply("stop", "done", 22000, 10), settled,
|
|
]]);
|
|
assert.equal(calls.length, 1);
|
|
assert.deepEqual(kinds(records), ["user", "step", "compact", "summary", "step", "turn_end"]);
|
|
const b = records.find((r) => r.t === "compact");
|
|
assert.equal(b.trigger, "auto");
|
|
assert.equal(b.preTokens, 98500);
|
|
assert.equal(b.postTokens, 21000);
|
|
assert.equal(typeof b.durationMs, "number");
|
|
assert.equal(records.find((r) => r.kind === "compact_summary").text, "## Goal\nthe summary");
|
|
});
|
|
|
|
test("a reply cut off by a full context, then compacted, is continued once", () => {
|
|
const { records, calls } = run([
|
|
[reply("length", "", 127134, 1), ...compaction(127135, 24000), settled],
|
|
[reply("stop", "picked it up", 25000, 40), settled],
|
|
]);
|
|
assert.equal(calls.length, 2);
|
|
// Same session, the continue prompt in place of the user's.
|
|
assert.equal(calls[1][calls[1].indexOf("--session-id") + 1], SID);
|
|
assert.match(calls[1].at(-1), /context window filled up/);
|
|
assert.equal(calls[0].at(-1), "do the task");
|
|
assert.deepEqual(kinds(records),
|
|
["user", "step", "compact", "summary", "continue", "step", "turn_end"]);
|
|
});
|
|
|
|
test("the auto-continues stop at RUNNER_AUTO_CONTINUES", () => {
|
|
const cut = [reply("length", "", 127134, 1), ...compaction(127135, 24000), settled];
|
|
const { records, calls } = run([cut], { RUNNER_AUTO_CONTINUES: "1" });
|
|
assert.equal(calls.length, 2);
|
|
assert.equal(kinds(records).filter((k) => k === "turn_end").length, 1);
|
|
assert.equal(kinds(records).at(-1), "turn_end");
|
|
});
|
|
|
|
test("a reply cut at the output limit with no compaction after it ends the turn", () => {
|
|
const { records, calls } = run([[reply("length", "half a file", 30000, 32768), settled]]);
|
|
assert.equal(calls.length, 1);
|
|
assert.deepEqual(kinds(records), ["user", "step", "turn_end"]);
|
|
});
|
|
|
|
test("a new transcript opens on a v1 header naming pi; a step is written whole", () => {
|
|
const { records } = run([[
|
|
{ type: "message_end", message: { role: "assistant", model: MODEL, provider: "fake",
|
|
stopReason: "toolUse", usage: usage(10, 5),
|
|
content: [{ type: "text", text: "Listing." },
|
|
{ type: "toolCall", id: "c1", name: "bash", arguments: { command: "ls", timeout: 3 } }] } },
|
|
{ type: "message_end", message: { role: "toolResult", toolCallId: "c1",
|
|
content: [{ type: "text", text: "a.txt" }], isError: false } },
|
|
reply("stop", "done", 20, 3), settled,
|
|
]]);
|
|
const head = records[0];
|
|
assert.deepEqual([head.t, head.v, head.id, head.harness], ["session", 1, SID, "pi"]);
|
|
assert.deepEqual(records.slice(1, 7).map((e) => e.t),
|
|
["prompt", "call", "text", "tool_call", "usage", "tool_result"]);
|
|
const call = records.find((e) => e.t === "tool_call");
|
|
assert.deepEqual([call.tool, call.native, call.input.timeout], ["shell", "bash", 3000]);
|
|
// one step's events share one moment
|
|
assert.equal(new Set(records.slice(2, 6).map((e) => e.at)).size, 1);
|
|
});
|
|
|
|
test("a transcript from before v1 is continued behind a v1 header", () => {
|
|
const old = { type: "user", sessionId: SID, cwd: "/x", gitBranch: null,
|
|
timestamp: "2026-11-01T10:00:00.000Z", message: { role: "user", content: "first" } };
|
|
const { records } = run([[reply("stop", "again", 5, 1), settled]], {}, [old]);
|
|
assert.deepEqual(records[0], old);
|
|
assert.deepEqual([records[1].t, records[1].v, records[1].harness], ["session", 1, "pi"]);
|
|
assert.deepEqual(kinds(records.slice(1)), ["user", "step", "turn_end"]);
|
|
});
|
|
|
|
test("a fork copies its source's v1 history under the new session's id", () => {
|
|
const SRC = "01a2ffff-0000-7000-8000-00000000f0f0";
|
|
const src = [{ t: "session", v: 1, id: SRC, harness: "pi", cwd: "/x" },
|
|
{ t: "prompt", text: "one", origin: "user" },
|
|
{ t: "call", model: MODEL }, { t: "text", text: "1" }, { t: "usage", input: 1, output: 1 },
|
|
{ t: "prompt", text: "two", origin: "user" }];
|
|
const { records } = run([[reply("stop", "forked", 5, 1), settled]], {}, null,
|
|
["-p", "instead", "--session-id", SID, "--fork-from", SRC, "--cut-line", "5",
|
|
"--cut-user-ord", "1", "--model", MODEL],
|
|
(dir) => {
|
|
const t = path.join(dir, "root", "transcripts", dir.replaceAll("/", "-"));
|
|
mkdirSync(t, { recursive: true });
|
|
writeFileSync(path.join(t, `${SRC}.jsonl`), src.map((o) => JSON.stringify(o)).join("\n") + "\n");
|
|
const sessions = path.join(dir, "root", "sessions");
|
|
mkdirSync(sessions, { recursive: true });
|
|
writeFileSync(path.join(sessions, `2026-11-25T00-00-00-000Z_${SRC}.jsonl`), [
|
|
{ type: "session", id: SRC },
|
|
{ type: "message", id: "a", message: { role: "user", content: [{ type: "text", text: "one" }] } },
|
|
{ type: "message", id: "b", message: { role: "assistant", content: [] } },
|
|
{ type: "message", id: "c", message: { role: "user", content: [{ type: "text", text: "two" }] } },
|
|
].map((o) => JSON.stringify(o)).join("\n") + "\n");
|
|
});
|
|
assert.deepEqual([records[0].t, records[0].v, records[0].id], ["session", 1, SID]);
|
|
assert.deepEqual(records.slice(1, 5), src.slice(1, 5));
|
|
// the fork runs elsewhere than its source: a session event says so
|
|
assert.deepEqual([records[5].t, typeof records[5].cwd], ["session", "string"]);
|
|
assert.deepEqual(kinds(records.slice(5)), ["user", "step", "turn_end"]);
|
|
assert.equal(records[6].text, "instead");
|
|
});
|