Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

remove the faux provider and the hillclimb perf tooling (#3223)

kt583b603119e2
diff --git a/Makefile b/Makefile
index 0b87aa7276..0905902c96 100644
--- a/Makefile
+++ b/Makefile
@@ -51,14 +51,6 @@ glibc-gate:
fi \
;; esac
-# Perf wave + regression gate (benchmark.yml job, the local mirror): runs the
-# TS binary and a fresh release build side by side in a fresh Prime sandbox
-# (both sides on one quiet machine, the methodology BENCHMARKS.md requires)
-# and gates the rust medians against scripts/battery/perf-baseline.json.
-# PA_BENCH_NO_SANDBOX=1 runs it on the bare runner instead.
-perf-wave:
- scripts/battery/ci_perf_wave.sh
-
# Local mirror of the release build-job gates:
# release build against the committed lockfile, deterministic tarball assembly,
# then end-to-end verification of the host-target artifact. The vendored
@@ -180,4 +172,4 @@ shard-gates:
python3 scripts/test_ci_test_shard.py
python3 scripts/test_ci_pr_crates.py
-.PHONY: check deny windows-cross actionlint perf-wave glibc-gate release-dry-run continuous-dry-run audit-build package catalog-assets catalog-assets-fixture catalog-assets-gates fold-gates restamp-gates shard-gates
+.PHONY: check deny windows-cross actionlint glibc-gate release-dry-run continuous-dry-run audit-build package catalog-assets catalog-assets-fixture catalog-assets-gates fold-gates restamp-gates shard-gates
diff --git a/crates/pa-cli/tests/differential_cli.rs b/crates/pa-cli/tests/differential_cli.rs
index c5fc0024e7..c36e7a22f9 100644
--- a/crates/pa-cli/tests/differential_cli.rs
+++ b/crates/pa-cli/tests/differential_cli.rs
@@ -356,7 +356,7 @@ fn run(binary: &Path, args: &[&str], sandbox: &Path) -> InvocationOutput {
// through passwd rather than $HOME, so the env override is the only
// reliable isolation for both binaries.
.env("PRIME_AGENT_CODING_AGENT_DIR", sandbox.join("agent"))
- // Isolate TMPDIR too (batterylib.scrubbed_env parity): without it the
+ // Isolate TMPDIR too: without it the
// TS daemon census escapes into the box's ambient daemons and
// `shutdown --force` kills unrelated sockets (containment contract).
.env("TMPDIR", sandbox.join("tmp"))
diff --git a/crates/pa-core/src/tools/golden_replay.rs b/crates/pa-core/src/tools/golden_replay.rs
index 307de2704a..34d0b3c0cf 100644
--- a/crates/pa-core/src/tools/golden_replay.rs
+++ b/crates/pa-core/src/tools/golden_replay.rs
@@ -1,5 +1,5 @@
//! Golden differential tests: replay the corpus recorded from the REAL
-//! TypeScript tools (see `tests/golden/harness.mjs`) against the Rust port
+//! TypeScript tools (frozen in `tests/golden/corpus/`) against the Rust port
//! and assert identical model-facing output.
//!
//! Corpus cases cover fuzzy edits, file-not-found, bash timeouts and
@@ -30,7 +30,7 @@ fn corpus(name: &str) -> serde_json::Value {
serde_json::from_str(&std::fs::read_to_string(path).expect("corpus file")).expect("corpus JSON")
}
-/// Normalize temp paths the same way harness.mjs does.
+/// Normalize temp paths to the forms the recorded corpus uses.
fn norm_string(s: &str, tmp: &str) -> String {
let out = s.replace(&format!("{tmp}/"), "<TMP>/");
let re = regex_lite("golden-[A-Za-z0-9_]{6}");
@@ -127,7 +127,7 @@ async fn golden_edit_group_matches_ts() {
let mut input = case["input"].clone();
if case["applyPrepareArguments"].as_bool().unwrap_or(false) {
input = crate::tools::edit::prepare_edit_arguments(input);
- // The TS harness records the prepared input for such cases.
+ // The TS harness recorded the prepared input for such cases.
assert_json_eq(
&input.clone(),
&case["preparedInput"].clone(),
diff --git a/crates/pa-core/tests/golden/harness.mjs b/crates/pa-core/tests/golden/harness.mjs
deleted file mode 100644
index 07c940613f..0000000000
--- a/crates/pa-core/tests/golden/harness.mjs
+++ /dev/null
@@ -1,663 +0,0 @@
-#!/usr/bin/env node
-/**
- * Golden differential harness (lane core-tools).
- *
- * Runs the REAL TypeScript tools from the /tmp/pa-golden copy of prime-agent
- * and records their results as a JSON corpus, so a Rust port can assert
- * byte-identical parity.
- *
- * - cwd for execution: /tmp/pa-golden (node_modules resolution via jiti).
- * - Output: corpus/*.json next to this file.
- * - Every case sets up its fixture in a fresh mkdtemp dir; the fixture setup
- * is recorded as replayable shell commands.
- * - Normalization: os.tmpdir() prefix -> "<TMP>", random tmp ids -> "<ID>".
- * No timestamps, durations, or random ids are recorded.
- *
- * Determinism: two runs produce identical corpus files.
- */
-import { spawnSync } from "node:child_process";
-import fs from "node:fs";
-import os from "node:os";
-import path from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import { createRequire } from "node:module";
-
-const PA_ROOT = "/tmp/pa-golden";
-const __filename = fileURLToPath(import.meta.url);
-const OUT_DIR = path.dirname(__filename);
-const CORPUS = path.join(OUT_DIR, "corpus");
-
-const TMP = os.tmpdir();
-
-const req = createRequire(path.join(PA_ROOT, "package.json"));
-const { createJiti } = req("jiti");
-const jiti = createJiti(pathToFileURL(path.join(PA_ROOT, "harness-entry.mjs")).href, {
- interopDefault: true,
- alias: {
- "@earendil-works/pi-agent-core": path.join(PA_ROOT, "packages/agent/src/index.ts"),
- "@earendil-works/pi-ai": path.join(PA_ROOT, "packages/ai/src/index.ts"),
- "@earendil-works/pi-tui": path.join(PA_ROOT, "packages/tui/src/index.ts"),
- },
-});
-
-async function loadTs(rel) {
- const mod = await jiti.import(path.join(PA_ROOT, rel));
- return mod.default ?? mod;
-}
-
-// ---------------------------------------------------------------- normalizing
-function normString(s) {
- let out = s.split(TMP + "/").join("<TMP>/");
- out = out.replace(/golden-[A-Za-z0-9_]{6}/g, "golden-<ID>");
- out = out.replace(/\bpi-(?:bash|output)-[0-9a-f]+\.log/g, "pi-<ID>.log");
- out = out.replace(/tmp-stdout-[0-9A-Za-z_]+/g, "tmp-stdout-<ID>");
- return out;
-}
-
-function deepNorm(value) {
- if (typeof value === "string") return normString(value);
- if (Array.isArray(value)) return value.map(deepNorm);
- if (value && typeof value === "object") {
- const out = {};
- for (const [k, v] of Object.entries(value)) out[k] = deepNorm(v);
- return out;
- }
- return value;
-}
-
-function writeCorpus(name, cases) {
- const doc = deepNorm({ group: name, caseCount: cases.length, cases });
- fs.writeFileSync(path.join(CORPUS, name + ".json"), JSON.stringify(doc, null, 2) + "\n");
-}
-
-// ------------------------------------------------------------------- fixtures
-function makeFixture(tc) {
- const dir = fs.mkdtempSync(path.join(TMP, "golden-"));
- for (const [name, content] of Object.entries(tc.files ?? {})) {
- const abs = path.join(dir, name);
- fs.mkdirSync(path.dirname(abs), { recursive: true });
- fs.writeFileSync(abs, Buffer.from(String(content), "utf-8"));
- }
- for (const cmd of tc.fixture ?? []) {
- const r = spawnSync("/bin/bash", ["-c", cmd], { cwd: dir, encoding: "utf-8" });
- if (r.status !== 0) {
- throw new Error(`fixture command failed (${r.status}): ${cmd}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`);
- }
- }
- return dir;
-}
-
-function stripCaseRuntimeFields(tc) {
- const { files, fixture, ...rest } = tc;
- return rest;
-}
-
-// ================================================================== GROUP 1
-async function editGroup() {
- const mod = await loadTs("packages/coding-agent/src/core/tools/edit.ts");
-
- const gitless = {
- files: {
- "file.txt": "alpha\nbeta\ngamma\ndelta\n",
- },
- };
-
- const cases = [
- {
- name: "unique-replacement",
- ...gitless,
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "beta", newText: "BETA" }] },
- },
- {
- name: "two-edits",
- files: { "file.txt": "alpha\nbeta\ngamma\ndelta\n" },
- applyPrepareArguments: false,
- input: {
- path: "file.txt",
- edits: [
- { oldText: "alpha", newText: "ALPHA" },
- { oldText: "gamma", newText: "GAMMA" },
- ],
- },
- },
- {
- name: "not-found",
- ...gitless,
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "missing", newText: "x" }] },
- },
- {
- name: "ambiguous",
- files: { "file.txt": "repeat\nmiddle\nrepeat\n" },
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "repeat", newText: "x" }] },
- },
- {
- name: "overlapping-edits",
- files: { "file.txt": "abcdef\n" },
- applyPrepareArguments: false,
- input: {
- path: "file.txt",
- edits: [
- { oldText: "abcd", newText: "X" },
- { oldText: "cdef", newText: "Y" },
- ],
- },
- },
- {
- name: "file-not-found",
- applyPrepareArguments: false,
- input: { path: "missing.txt", edits: [{ oldText: "a", newText: "b" }] },
- },
- {
- name: "empty-edits",
- ...gitless,
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [] },
- },
- {
- name: "legacy-oldText-newText",
- ...gitless,
- applyPrepareArguments: true,
- input: { path: "file.txt", oldText: "beta", newText: "BETA" },
- },
- {
- name: "edits-as-json-string",
- ...gitless,
- applyPrepareArguments: true,
- input: { path: "file.txt", edits: JSON.stringify([{ oldText: "beta", newText: "BETA" }]) },
- },
- {
- name: "bom-file",
- files: { "file.txt": "hello world\nsecond line\n" },
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "world", newText: "planet" }] },
- },
- {
- name: "crlf-file",
- files: { "file.txt": "line1\r\nline2\r\nline3\r\n" },
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "line2", newText: "LINE2" }] },
- },
- {
- name: "fuzzy-trailing-whitespace",
- files: { "file.txt": "alpha \nbeta\nkeep \n" },
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "alpha\n", newText: "ALPHA\n" }] },
- },
- {
- name: "fuzzy-smart-quotes",
- files: { "file.txt": "it’s a “test” line\n" },
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "it's a \"test\" line", newText: "plain quotes" }] },
- },
- {
- name: "empty-oldtext",
- ...gitless,
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "", newText: "x" }] },
- },
- {
- name: "no-change",
- ...gitless,
- applyPrepareArguments: false,
- input: { path: "file.txt", edits: [{ oldText: "beta", newText: "beta" }] },
- },
- {
- name: "directory-path",
- fixture: ["mkdir -p adir"],
- applyPrepareArguments: false,
- input: { path: "adir", edits: [{ oldText: "a", newText: "b" }] },
- },
- ];
-
- const out = [];
- for (const tc of cases) {
- const dir = makeFixture(tc);
- const def = mod.createEditToolDefinition(dir);
- let input = structuredClone(tc.input);
- let preparedInput;
- if (tc.applyPrepareArguments) {
- input = def.prepareArguments(input);
- preparedInput = input;
- }
- let result;
- try {
- const r = await def.execute("id", input, undefined);
- result = { ok: true, text: r.content[0].text, details: r.details ?? null };
- } catch (err) {
- result = { ok: false, error: err.message };
- }
- let finalContent = null;
- try {
- finalContent = fs.readFileSync(path.resolve(dir, String(tc.input.path)), "utf-8");
- } catch {
- finalContent = null;
- }
- out.push({
- name: tc.name,
- files: tc.files ?? {},
- fixture: tc.fixture ?? [],
- applyPrepareArguments: tc.applyPrepareArguments,
- input: tc.input,
- ...(preparedInput !== undefined ? { preparedInput } : {}),
- result,
- finalContent,
- });
- }
- writeCorpus("edit", out);
- return out.length;
-}
-
-// ================================================================== GROUP 2
-// Fixed commit dates keep commit hashes (printed by `git reset --hard`)
-// deterministic across runs.
-const FIXED_DATE = "GIT_AUTHOR_DATE='2005-04-07T22:13:13' GIT_COMMITTER_DATE='2005-04-07T22:13:13'";
-
-const dirtyRepoFixture = [
- "git init -q .",
- "git config user.email t@t",
- "git config user.name t",
- "echo original > tracked.txt",
- "git add tracked.txt",
- FIXED_DATE + " git commit -qm init",
- "echo modified > tracked.txt",
- "echo untracked > untracked.txt",
-];
-
-const cleanRepoFixture = [
- "git init -q .",
- "git config user.email t@t",
- "git config user.name t",
- "echo original > tracked.txt",
- "git add tracked.txt",
- FIXED_DATE + " git commit -qm init",
-];
-
-function bashCase(name, opts) {
- return { name, ...opts };
-}
-
-async function runBashCase(tc) {
- let dir;
- if (tc.cwdIsDeleted) {
- dir = makeFixture({ files: tc.files ?? {}, fixture: tc.fixture ?? [] });
- fs.rmSync(dir, { recursive: true });
- } else {
- dir = makeFixture(tc);
- }
- const bashMod = await loadTs("packages/coding-agent/src/core/tools/bash.ts");
- const def = bashMod.createBashToolDefinition(dir, tc.options);
- const input = { command: tc.command };
- if (tc.timeout !== undefined) input.timeout = tc.timeout;
- if (tc.allowDestructiveGit !== undefined) input.allowDestructiveGit = tc.allowDestructiveGit;
- let result;
- try {
- const r = await def.execute("id", input, undefined);
- result = { ok: true, isError: false, text: r.content[0].text, details: r.details ?? null };
- } catch (err) {
- result = { ok: false, isError: true, error: err.message };
- }
- const out = {
- name: tc.name,
- files: tc.files ?? {},
- fixture: tc.fixture ?? [],
- command: tc.command,
- ...(tc.timeout !== undefined ? { timeout: tc.timeout } : {}),
- ...(tc.allowDestructiveGit !== undefined ? { allowDestructiveGit: tc.allowDestructiveGit } : {}),
- ...(tc.envBypass ? { envBypass: tc.envBypass } : {}),
- ...(tc.cwdIsDeleted ? { cwdIsDeleted: true } : {}),
- result,
- };
- // Normalize + probe details of fullOutputPath (existence is checked pre-normalization).
- const rawPath = result.ok ? result.details?.fullOutputPath : undefined;
- if (rawPath) {
- let exists = false;
- let bytes = null;
- try {
- const st = fs.statSync(rawPath);
- exists = true;
- bytes = st.size;
- } catch {
- exists = false;
- }
- result.fullOutputFile = { exists, bytes };
- }
- return out;
-}
-
-function bashCaseDefs() {
- return [
- bashCase("echo-hello", { command: "echo hello" }),
- bashCase("exit-code-3", { command: "echo out; exit 3" }),
- bashCase("no-output", { command: "true" }),
- bashCase("timeout", { command: "sleep 5", timeout: 1 }),
- bashCase("stdout-stderr-both", { command: "echo out; echo err1 1>&2; echo out2; echo err2 1>&2" }),
- bashCase("line-truncation", { command: "seq 1 2500" }),
- bashCase("byte-truncation-multiline", {
- command: "for i in $(seq 1 100); do head -c 600 /dev/zero | tr '\\0' x; echo; done",
- }),
- bashCase("single-huge-line", {
- command: "python3 -c \"print('x'*60000)\"",
- }),
- bashCase("unicode-output", {
- command:
- "python3 -c \"import sys,time; sys.stdout.write('\\u00e9\\u00e9\\u00e9'); sys.stdout.flush(); time.sleep(0.05); sys.stdout.write('\\u2713'); sys.stdout.flush()\"",
- }),
- bashCase("destructive-checkout-dirty", {
- fixture: dirtyRepoFixture,
- command: "git checkout -- .",
- }),
- bashCase("destructive-allow-bypass", {
- fixture: dirtyRepoFixture,
- command: "git checkout -- .",
- allowDestructiveGit: true,
- }),
- bashCase("destructive-reset-clean", {
- fixture: cleanRepoFixture,
- command: "git reset --hard",
- }),
- bashCase("destructive-quoted", {
- command: "echo 'git reset --hard'",
- }),
- bashCase("destructive-cd-sub", {
- fixture: [
- ...cleanRepoFixture,
- "mkdir sub",
- "cd sub && git init -q . && git config user.email t@t && git config user.name t && echo orig > subfile.txt && git add subfile.txt && " + FIXED_DATE + " git commit -qm subinit",
- "cd sub && echo dirty > subfile.txt",
- ],
- command: "cd sub && git checkout -- .",
- }),
- bashCase("destructive-comment", {
- fixture: cleanRepoFixture,
- command: "echo done # git reset --hard",
- }),
- bashCase("env-bypass", {
- fixture: dirtyRepoFixture,
- command: "git checkout -- .",
- envBypass: true,
- }),
- bashCase("cwd-missing", {
- cwdIsDeleted: true,
- command: "echo hi",
- }),
- ];
-}
-
-async function bashGroup() {
- const defs = bashCaseDefs();
- const out = [];
- // env-bypass needs PI_BASH_ALLOW_DESTRUCTIVE_GIT in process.env; run it in a
- // child node process (getShellEnv() inherits process.env).
- for (const tc of defs) {
- if (!tc.envBypass) {
- out.push(await runBashCase(tc));
- }
- }
- // Child run: only the env-bypass case.
- const envBypassDef = defs.find((d) => d.envBypass);
- const childEnv = {
- ...process.env,
- PI_BASH_ALLOW_DESTRUCTIVE_GIT: "1",
- HARNESS_ONLY_BYPASS: "1",
- HARNESS_OUT: path.join(CORPUS, "_env-bypass-part.json"),
- };
- const r = spawnSync(process.execPath, [__filename], { encoding: "utf-8", env: childEnv, cwd: process.cwd() });
- if (r.status !== 0) {
- throw new Error("env-bypass child run failed:\n" + r.stdout + "\n" + r.stderr);
- }
- const part = JSON.parse(fs.readFileSync(childEnv.HARNESS_OUT, "utf-8"));
- fs.rmSync(childEnv.HARNESS_OUT, { force: true });
- out.push(part);
-
- writeCorpus("bash", out);
- return out.length;
-}
-
-// ================================================================== GROUP 3
-async function previewGroup() {
- const cp = await loadTs("packages/coding-agent/src/core/tools/code-preview.ts");
- const inputs = [
- "npm run test -- --watch",
- "git add -A && git commit -m x",
- "python3 <<'EOF'\nprint('hello')\nEOF",
- "%%bash\ncd sub && make",
- "curl -s https://api.example.com/v1 -H 'Authorization: Bearer abc123def456'",
- "cd sub && make",
- "uv run python3 -m pytest tests/x.rs",
- "tee -a out.log",
- "API_TOKEN = \"abc123\"\nrequests.get(\"https://example.com\", headers={\"Authorization\": \"Bearer sk-live-0123456789\"})",
- "python3 -c \"import base64; print(base64.b64encode(b'0123456789'*12))\"",
- "cat data.bin",
- "echo qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM+/0987654321qazwsxedcrfvtgbyhnujmikolp",
- "for i in $(ls /very/long/path/with/many/components/here); do echo processing $i; done",
- "from pathlib import Path\nout = Path('out.txt')\nout.write_text('hello')\nimport subprocess\nsubprocess.run('git status', shell=True)",
- "print('just printing')",
- "%%bash\necho in-bash-cell",
- ];
- const out = inputs.map((input) => ({
- input,
- bash: cp.previewBashCommand(input),
- ipython: cp.previewIpythonCode(input),
- }));
- writeCorpus("preview", out);
- return out.length;
-}
-
-// ================================================================== GROUP 4
-async function truncateGroup() {
- const tr = await loadTs("packages/coding-agent/src/core/tools/truncate.ts");
- const cases = [
- { name: "exact-boundary-equal-limits", content: "a\nb\nc", maxLines: 3, maxBytes: 10 },
- { name: "one-line-over-head", content: "a\nb\nc\nd", maxLines: 3, maxBytes: 100 },
- { name: "one-line-over-tail", content: "a\nb\nc\nd", maxLines: 3, maxBytes: 100 },
- {
- name: "multibyte-at-byte-boundary",
- content: "éééééééééé\néééééééééé\néééééééééé\n",
- maxLines: 100,
- maxBytes: 24,
- },
- { name: "first-line-exceeds-bytes-head", content: "xxxxxxxxxxxxxxxxxxxxxxxx\nshort\n", maxLines: 10, maxBytes: 16 },
- { name: "first-line-exceeds-bytes-tail", content: "xxxxxxxxxxxxxxxxxxxxxxxx\nshort\n", maxLines: 10, maxBytes: 16 },
- {
- name: "tail-trailing-blank-partial-rescue",
- content: "y".repeat(100) + "\n\n\n",
- maxLines: 10,
- maxBytes: 50,
- },
- { name: "empty-string", content: "", maxLines: 5, maxBytes: 50 },
- { name: "no-trailing-newline", content: "a\nb\nc", maxLines: 2, maxBytes: 100 },
- { name: "byte-limit-tail-simple", content: Array.from({ length: 40 }, (_, i) => "line" + i).join("\n") + "\n", maxLines: 2000, maxBytes: 60 },
- ];
- const out = cases.map((tc) => ({
- name: tc.name,
- content: tc.content,
- maxLines: tc.maxLines,
- maxBytes: tc.maxBytes,
- head: tr.truncateHead(tc.content, { maxLines: tc.maxLines, maxBytes: tc.maxBytes }),
- tail: tr.truncateTail(tc.content, { maxLines: tc.maxLines, maxBytes: tc.maxBytes }),
- }));
- writeCorpus("truncate", out);
- return out.length;
-}
-
-// ================================================================== GROUP 5
-async function ipythonGroup() {
- const ip = await loadTs("packages/coding-agent/src/core/tools/ipython.ts");
- const kernelShared = await loadTs("packages/coding-agent/src/core/kernel/shared.ts");
- const BusyErr = kernelShared.KernelBusyAfterInterruptError;
-
- function makeProvisioner(executions) {
- const calls = { ensure: 0, execute: 0, kill: 0 };
- let i = 0;
- const manager = {
- execute: async (code, opts) => {
- calls.execute++;
- const item = executions[Math.min(i++, executions.length - 1)];
- if (item instanceof Error) throw item;
- return item;
- },
- };
- return {
- calls,
- ensure: async (_onProgress, _signal) => {
- calls.ensure++;
- return manager;
- },
- kill: async () => {
- calls.kill++;
- },
- };
- }
-
- const okResult = (over = {}) => ({ status: "ok", stdout: "", stderr: "", durationMs: 123, ...over });
-
- const caseDefs = [
- {
- name: "stdout-stderr-result-ordering",
- code: "print('out')",
- mockResults: [okResult({ stdout: "out\n", stderr: "err\n", result: "42" })],
- ctxMode: "none",
- },
- {
- name: "error-status-traceback",
- code: "1/0",
- mockResults: [
- {
- status: "error",
- stdout: "before\n",
- stderr: "",
- result: undefined,
- error: {
- ename: "ZeroDivisionError",
- evalue: "division by zero",
- traceback: ["Traceback (most recent call last):", " File ...: division by zero"],
- },
- durationMs: 5,
- },
- ],
- ctxMode: "none",
- },
- {
- name: "empty-output",
- code: "x = 1",
- mockResults: [okResult()],
- ctxMode: "none",
- },
- {
- name: "background-output",
- code: "import time; time.sleep(0.01)",
- mockResults: [okResult({ stdout: "x", backgroundOutput: "late output\nfrom background" })],
- ctxMode: "none",
- },
- {
- name: "aborted-status",
- code: "import time; time.sleep(10)",
- mockResults: [okResult({ status: "aborted", stdout: "partial output" })],
- ctxMode: "none",
- },
- {
- name: "busy-then-cancel-no-ui",
- code: "print('never')",
- mockResults: [new BusyErr()],
- ctxMode: "none",
- },
- {
- name: "busy-then-kill-restart-notice",
- code: "print('after restart')",
- mockResults: [new BusyErr(), okResult({ stdout: "after restart\n" })],
- ctxMode: "ui-kill",
- },
- ];
-
- const out = [];
- for (const tc of caseDefs) {
- const prov = makeProvisioner(tc.mockResults);
- const def = ip.createIpythonToolDefinition("/tmp", { provisioner: prov });
- const ctx =
- tc.ctxMode === "ui-kill"
- ? {
- hasUI: true,
- ui: {
- async select(_prompt, _choices, _opts) {
- return "Kill kernel and restart";
- },
- setWorkingMessage() {},
- },
- }
- : undefined;
- let result;
- try {
- const r = await def.execute("id", { code: tc.code }, undefined, undefined, ctx);
- result = { ok: true, isError: r.isError === true, outputText: r.content[0].text };
- } catch (err) {
- result = { ok: false, isError: true, error: err.message };
- }
- out.push({
- name: tc.name,
- code: tc.code,
- ctxMode: tc.ctxMode,
- mockResults: tc.mockResults.map((m) => (m instanceof Error ? { thrown: m.name, message: m.message } : m)),
- provisionerCalls: prov.calls,
- result,
- });
- }
- writeCorpus("ipython", out);
- return out.length;
-}
-
-// ================================================================== GROUP 6
-async function schemaGroup() {
- const edit = await loadTs("packages/coding-agent/src/core/tools/edit.ts");
- const bash = await loadTs("packages/coding-agent/src/core/tools/bash.ts");
- const ipython = await loadTs("packages/coding-agent/src/core/tools/ipython.ts");
- const defs = {
- bash: bash.createBashToolDefinition("/tmp"),
- edit: edit.createEditToolDefinition("/tmp"),
- ipython: ipython.createIpythonToolDefinition("/tmp"),
- };
- const out = [];
- for (const [tool, def] of Object.entries(defs)) {
- out.push({
- tool,
- name: def.name,
- label: def.label,
- description: def.description,
- promptSnippet: def.promptSnippet,
- ...(def.executionMode !== undefined ? { executionMode: def.executionMode } : {}),
- parameters: def.parameters,
- });
- }
- writeCorpus("schema", out);
- return out.length;
-}
-
-// ======================================================================= main
-async function main() {
- fs.mkdirSync(CORPUS, { recursive: true });
- if (process.env.HARNESS_ONLY_BYPASS === "1") {
- // Child run: execute only the env-bypass bash case, write it to HARNESS_OUT.
- const defs = bashCaseDefs().filter((d) => d.envBypass);
- const results = [];
- for (const tc of defs) results.push(await runBashCase(tc));
- fs.writeFileSync(process.env.HARNESS_OUT, JSON.stringify(deepNorm(results[0]), null, 2) + "\n");
- process.exit(0);
- }
- const counts = {};
- counts.edit = await editGroup();
- counts.bash = await bashGroup();
- counts.preview = await previewGroup();
- counts.truncate = await truncateGroup();
- counts.ipython = await ipythonGroup();
- counts.schema = await schemaGroup();
-
- const total = Object.values(counts).reduce((a, b) => a + b, 0);
- console.log("corpus written:", JSON.stringify(counts), "total", total);
-}
-
-main().catch((err) => {
- console.error(err);
- process.exit(1);
-});
diff --git a/scripts/battery/README.md b/scripts/battery/README.md
deleted file mode 100644
index e322b1a865..0000000000
--- a/scripts/battery/README.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Perf-wave battery
-
-The perf wave measures the interactive TUI against the deployed TS
-binary (the "ts" side) and a release build of this repo (the "rust"
-side), gates the rust medians against the recorded baseline, and is
-driven by the Makefile `perf-wave` target:
-
- make perf-wave
-
-`perf-wave` runs `ci_perf_wave.sh`, the CI-shaped entry: it creates an
-ephemeral Prime sandbox (4 CPU / 16 GB, the spec class the baseline was
-recorded on), installs the deployed TS binary plus a fresh release build
-of the checkout, runs the wave there, downloads the results, and gates
-them (`perf_gate.py` against `perf-baseline.json`). Every timing comes
-from the same quiet machine for both sides, which is the whole point of
-the sandbox. `PA_BENCH_NO_SANDBOX=1` runs the wave directly on the host
-instead (`run_perf_wave.sh` + `perf_wave.py`).
-
-Files:
-
-- `ci_perf_wave.sh` — the Makefile entry (sandbox lifecycle, results
- download, the gate call)
-- `run_perf_wave.sh` — the local runner (same shape as the CI entry,
- without the sandbox dance)
-- `perf_wave.py` — the driver (dimensions below; accepts --ts-bin /
- --rust-bin)
-- `sustained_cpu.py` — the sustained-CPU dimension: the interactive TUI
- driven through the faux provider — a 30s idle window, a paced plain-text
- stream, a paced markdown/code stream, and a long tool-execution turn —
- with %CPU sampled per process from /proc and ASSERTED: idle <5% and
- streaming <30% of one core, keystroke-to-render mid-stream <50ms, the
- paused viewport stable mid-stream, and a double Ctrl+C mid-scroll
- terminating the process (bug #6's no-escape invariant)
-- `stream_throughput.py` — the stream-throughput dimension (token
- throughput of the live render loop, both binaries)
-- `perf.py` — the perf measurement helpers the dimensions share:
- startup launch-to-ready, keystroke-to-render typing latency, and
- cold-resume-to-ready over the same tmux pane channel a real user
- types through (both product sides)
-- `scale_corpus.py` — the deterministic heavy-scale corpus the resume
- dimension replays (the 350-turn / 1078-row corpus perf_wave.py
- generates via scale_corpus for its resume dim)
-- `perf_gate.py` — the gate (medians vs `perf-baseline.json`, default
- threshold 1.10)
-- `perf-baseline.json` — the recorded baseline the gate compares against
-- `batterylib.py` — the shared harness (side sessions, the deterministic
- mock provider, the daemon-reap sweep every harness reuses:
- `reap_daemons(needles=[...])` sweeps any `--mode daemon` process whose
- argv references the given paths — the graceful `sd` shutdown first, then
- the SIGTERM/SIGKILL rounds until a respawned main is gone; the harness
- sandboxes pin an isolated per-side TMPDIR so a supervisor's socket lands
- under the sandbox root the sweep can name)
-- `mock_provider.py` — the deterministic mock provider batterylib drives
- (responses are session-scoped queues — a queue is selected per request
- by markers in the request's user-message text, so a parent session and
- a concurrently running spawned child each get their own scripted
- responses deterministically)
-- `ts_identity.py` — the shared ts-identity guard: every PATH-driven
- harness refuses to run when its "ts" binary is this repo's Rust product
-- `../ts_faux_extension.js` — the faux-provider driver extension the TS
- side loads (scripted responses read from PRIME_AGENT_FAUX_SCRIPT);
- verification harness only, never installed for real users
diff --git a/scripts/battery/batterylib.py b/scripts/battery/batterylib.py
deleted file mode 100644
index 55940f4765..0000000000
--- a/scripts/battery/batterylib.py
+++ /dev/null
@@ -1,715 +0,0 @@
-#!/usr/bin/env python3
-"""Shared helpers for the parity battery: isolated per-side environments,
-tmux frame capture, a JSONL daemon-wire client, and evidence-file helpers.
-
-The battery drives the TS binary (ground truth) and the Rust binary side by
-side against a deterministic mock provider (mock_provider.py). Nothing here
-is part of the product.
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import re
-import shutil
-import socket
-import subprocess
-import time
-from dataclasses import dataclass, field
-from pathlib import Path
-
-NL = chr(10)
-# Environment keys set by this box's own prime-agent session/worker; they must
-# never leak into spawned daemons, workers, or interactive sessions.
-SCRUB_ENV_PREFIXES = ("PRIME_AGENT_INTERNAL", "RLM_")
-SCRUB_ENV_KEYS = (
- "TMUX",
- "TMUX_PANE",
- "PRIME_AGENT_SESSION_DIR",
- "PRIME_AGENT_CODING_AGENT_DIR",
- "PRIME_AGENT_CODING_AGENT_SESSION_DIR",
- "PRIME_AGENT_KERNEL_OWNER_PID",
- "PI_CODING_AGENT_DIR",
- "PI_CODING_AGENT",
-)
-
-TMUX_SIZE = (120, 36)
-
-
-def scrubbed_env(agent_dir: Path, tmpdir: Path, extra: dict | None = None) -> dict:
- """A clean env: no worker/role markers, isolated agent dir + TMPDIR."""
- env = {
- k: v
- for k, v in os.environ.items()
- if not k.startswith(SCRUB_ENV_PREFIXES) and k not in SCRUB_ENV_KEYS
- }
- env["PRIME_AGENT_CODING_AGENT_DIR"] = str(agent_dir)
- env["TMPDIR"] = str(tmpdir)
- if extra:
- env.update(extra)
- return env
-
-
-def rust_binary_staleness(binary: Path, repo_root: Path) -> str | None:
- """Why a built Rust binary cannot include this checkout's current
- product code (`None` = fresh or unknown). A stale build reports false
- divergences against the TS ground truth (run 20260920: the
- compaction-abort harness "failed" on main only because the checkout's
- target/release binary predates the auto-compaction merge), so the
- harnesses fail fast instead of wasting a run. The binary's mtime must
- postdate the newest commit touching the product sources; set
- PA_BATTERY_ALLOW_STALE_RUST=1 to skip the guard (deliberate
- old-build testing).
- """
- if os.environ.get("PA_BATTERY_ALLOW_STALE_RUST") == "1":
- return None
- try:
- binary = Path(binary)
- if not binary.exists():
- return None # a missing binary is the caller's own error
- out = subprocess.run(
- ["git", "log", "-1", "--format=%ct", "--", "crates", "prime-agent-runtime"],
- cwd=repo_root,
- capture_output=True,
- text=True,
- timeout=10,
- ).stdout.strip()
- if not out:
- return None
- newest_product_commit = int(out)
- built = binary.stat().st_mtime
- # One minute of slack: a build started at the commit's timestamp
- # still includes it.
- if built + 60 < newest_product_commit:
- age_min = int((newest_product_commit - built) / 60)
- return (
- f"{binary} predates the newest product commit in {repo_root} "
- f"(binary built ~{age_min} min before the newest crates/ or "
- "prime-agent-runtime/ change): a stale build reports false "
- "divergences. Rebuild (cargo build --release -p pa-cli) or "
- "point --rust-bin/PA_PARITY_RUST at a current build; set "
- "PA_BATTERY_ALLOW_STALE_RUST=1 to override."
- )
- except Exception:
- return None
- return None
-
-
-def run_cmd(
- argv: list[str],
- env: dict,
- cwd: Path,
- timeout: float = 120.0,
- stdin_text: str | None = "",
-) -> dict:
- """Run a command, returning a record with stdout/stderr/exit/duration."""
- start = time.time()
- try:
- proc = subprocess.run(
- argv,
- env=env,
- cwd=str(cwd),
- input=stdin_text,
- capture_output=True,
- text=True,
- timeout=timeout,
- )
- return {
- "argv": argv,
- "exit_code": proc.returncode,
- "stdout": proc.stdout,
- "stderr": proc.stderr,
- "duration_s": round(time.time() - start, 2),
- "timeout": False,
- }
- except subprocess.TimeoutExpired as exc:
- return {
- "argv": argv,
- "exit_code": None,
- "stdout": exc.stdout.decode() if isinstance(exc.stdout, bytes) else (exc.stdout or ""),
- "stderr": exc.stderr.decode() if isinstance(exc.stderr, bytes) else (exc.stderr or ""),
- "duration_s": round(time.time() - start, 2),
- "timeout": True,
- }
-
-
-class MockProvider:
- """One mock-provider process per side, so request logs never interleave."""
-
- def __init__(self, battery_dir: Path, port_offset_holder: list[int]):
- self.script_path = battery_dir / "mock-script.json"
- self.requests_path = Path(str(self.script_path) + ".requests.jsonl")
- for path in (self.script_path, self.requests_path):
- if path.exists():
- path.unlink()
- self.port = None
- self._holder = port_offset_holder
- self._proc = None
-
- def set_responses(self, responses: list[dict], queues: list[dict] | None = None) -> None:
- """Write the mock script. `responses` is the default queue; each
- entry of `queues` is a session-scoped queue ({"name", "match",
- "matchModels", "responses"}) served to requests whose model id
- (matchModels) or user-message text (match markers) selects it
- (mock_provider.py picks per request). An entry may also be a
- scripted provider failure: {"error": "<message>", "status": 400}."""
- script = {"responses": responses}
- if queues:
- script["queues"] = queues
- with open(self.script_path, "w") as f:
- json.dump(script, f)
-
- def start(self) -> int:
- here = Path(__file__).parent
- for _ in range(20):
- self._proc = subprocess.Popen(
- ["python3", str(here / "mock_provider.py"), str(self.script_path)],
- stdout=subprocess.PIPE,
- stderr=subprocess.DEVNULL,
- text=True,
- )
- line = self._proc.stdout.readline()
- try:
- self.port = int(line.strip())
- return self.port
- except ValueError:
- self._proc.kill()
- time.sleep(0.1)
- raise RuntimeError("mock provider failed to start")
-
- def url(self) -> str:
- return f"http://127.0.0.1:{self.port}/v1"
-
- def requests(self) -> list[dict]:
- if not self.requests_path.exists():
- return []
- out = []
- for line in self.requests_path.read_text().splitlines():
- if line.strip():
- out.append(json.loads(line))
- return out
-
- def stop(self) -> None:
- if self._proc:
- self._proc.terminate()
- try:
- self._proc.wait(timeout=5)
- except subprocess.TimeoutExpired:
- self._proc.kill()
-
-
-@dataclass
-class Side:
- """One product side (ts or rust) with fully isolated state."""
-
- name: str
- binary: str
- root: Path # evidence/<side>
- agent_dir: Path
- work_dir: Path
- daemon_socket: Path
- mock: MockProvider
- env: dict = field(default_factory=dict)
- daemon_proc: subprocess.Popen | None = None
-
- @property
- def base_url(self) -> str:
- return self.mock.url()
-
- def write_models_json(self) -> None:
- self.agent_dir.mkdir(parents=True, exist_ok=True)
- models = {
- "providers": {
- "prime-inference": {
- "api": "openai-completions",
- "baseUrl": self.base_url,
- "apiKey": "sk-battery",
- "models": [
- {
- "id": "mock-1",
- "name": "Mock 1",
- "api": "openai-completions",
- "baseUrl": self.base_url,
- "contextWindow": 128000,
- "maxTokens": 4096,
- }
- ],
- }
- }
- }
- (self.agent_dir / "models.json").write_text(json.dumps(models, indent=1))
-
- # -- evidence helpers ---------------------------------------------------
-
- def evidence(self, flow: str, name: str, text: str) -> Path:
- path = self.root / flow / name
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(text)
- return path
-
- def evidence_json(self, flow: str, name: str, obj) -> Path:
- path = self.root / flow / name
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(obj, indent=1, sort_keys=False))
- return path
-
- def sessions_dir(self) -> Path:
- return self.agent_dir / "sessions"
-
- def session_files(self) -> list[Path]:
- d = self.sessions_dir()
- if not d.exists():
- return []
- return sorted(d.glob("*.jsonl"), key=lambda p: p.stat().st_mtime)
-
- # -- daemon --------------------------------------------------------------
-
- def start_daemon(self, timeout: float = 30.0) -> None:
- """Start the daemon on this side's socket (identical argv both sides)."""
- log = self.root / "daemon.log"
- log.parent.mkdir(parents=True, exist_ok=True)
- with open(log, "ab") as logfile:
- self.daemon_proc = subprocess.Popen(
- [self.binary, "--mode", "daemon", "--daemon-socket", str(self.daemon_socket)],
- env=self.env,
- cwd=str(self.work_dir),
- stdin=subprocess.DEVNULL,
- stdout=logfile,
- stderr=logfile,
- )
- deadline = time.time() + timeout
- while time.time() < deadline:
- if self.daemon_socket.exists():
- try:
- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
- probe.connect(str(self.daemon_socket))
- return
- except OSError:
- pass
- if self.daemon_proc.poll() is not None:
- raise RuntimeError(
- f"{self.name} daemon exited early: {log.read_text(errors='replace')[-2000:]}"
- )
- time.sleep(0.2)
- raise RuntimeError(f"{self.name} daemon socket never appeared")
-
- def stop_daemon(self) -> None:
- """Shut this side's daemon down and reap its whole tree (the
- shared `reap_daemons` sweep; see its docstring for the leak
- history). Only processes whose argv references this side's unique
- socket paths are touched, never unrelated daemons."""
- needles = [str(self.daemon_socket)]
- tmpdir = self.env.get("TMPDIR")
- if tmpdir:
- needles.append(tmpdir.rstrip("/"))
- reap_daemons(socket_paths=[self.daemon_socket], needles=needles, proc=self.daemon_proc)
-
- def own_daemon_pids(self) -> list[int]:
- """Daemon processes whose argv references this side's daemon
- socket or its TMPDIR (the supervisor's socket lives there)."""
- exclude = {self.daemon_proc.pid} if self.daemon_proc else set()
- needles = [str(self.daemon_socket)]
- tmpdir = self.env.get("TMPDIR")
- if tmpdir:
- needles.append(tmpdir.rstrip("/"))
- return daemon_pids_matching(needles, exclude_pids=exclude)
-
-
-def daemon_pids_matching(needles, exclude_pids=()) -> list[int]:
- """Live `--mode daemon` processes whose argv references any of
- `needles` (daemon socket paths, isolated TMPDIR roots, or a harness
- sandbox root containing either). Empty-string needles are dropped: a
- bare "" would match every process. The scan walks /proc on Linux and
- `ps` on macOS (a harness must reap on both)."""
- seen: list[int] = []
- live_needles = [needle for needle in needles if needle]
- if Path("/proc").is_dir():
- for proc_dir in Path("/proc").iterdir():
- if not proc_dir.name.isdigit():
- continue
- pid = int(proc_dir.name)
- if pid in (1, os.getpid()) or pid in exclude_pids:
- continue
- try:
- argv = [
- part.decode(errors="replace")
- for part in (proc_dir / "cmdline").read_bytes().split(b"\0")
- if part
- ]
- except OSError:
- continue
- if "--mode" not in argv or "daemon" not in argv:
- continue
- if any(needle in part for part in argv for needle in live_needles):
- seen.append(pid)
- return seen
- scan = subprocess.run(
- ["ps", "-axo", "pid=,command="],
- capture_output=True,
- text=True,
- env=dict(os.environ, COLUMNS="4096"),
- )
- for line in scan.stdout.splitlines():
- parts = line.strip().split(None, 1)
- if len(parts) < 2 or not parts[0].isdigit():
- continue
- pid = int(parts[0])
- if pid in (1, os.getpid()) or pid in exclude_pids:
- continue
- argv = parts[1].split()
- if "--mode" not in argv or "daemon" not in argv:
- continue
- # Needles can span argv splits (a socket, sandbox, or TMPDIR path
- # with spaces), so they match against the full rendered command
- # line, never against the fragments.
- if any(needle in parts[1] for needle in live_needles):
- seen.append(pid)
- return seen
-
-
-def worker_pids_under(cwd_roots=(), exclude_pids=()) -> list[int]:
- """Processes whose working directory sits under any of `cwd_roots`
- (normalized, trailing-separator-safe). The products' detached session
- workers run as `<binary> worker` with no sandbox path in their argv,
- but with the session's cwd (the side's work dir), so cwd is the only
- scope that reaches them. /proc-only: the macOS fallback reaps the
- daemon pair (the argv scan above) and leaves the detached workers to
- their own exit paths."""
- if not Path("/proc").is_dir():
- return []
- roots = []
- for root in cwd_roots:
- if root:
- text = str(root).rstrip("/") + "/"
- roots.append(text)
- seen: list[int] = []
- for proc_dir in Path("/proc").iterdir():
- if not proc_dir.name.isdigit():
- continue
- pid = int(proc_dir.name)
- if pid in (1, os.getpid()) or pid in exclude_pids:
- continue
- try:
- cwd = os.readlink(proc_dir / "cwd")
- except OSError:
- continue
- if any(cwd.startswith(root) for root in roots):
- seen.append(pid)
- return seen
-
-
-def reap_daemons(socket_paths=(), needles=(), proc=None, cwd_roots=()) -> None:
- """Reap a harness's daemon tree (the #221 pattern, lifted so every
- standalone harness shares it).
-
- A bare terminate() leaks: the TS product runs a per-run supervisor
- (its own `--mode daemon` process on a socket under the side's TMPDIR)
- that RESPAWNS a killed main daemon, so SIGTERM alone leaves the pair
- behind (run 20260920: every wire-harness pass leaked two daemons; the
- #223 close-out: a standalone harness rmtree'd its tempdir and left a
- daemon spinning at 74% CPU on the deleted socket). The graceful `sd` wire
- shutdown (both products implement it) goes first for every
- `socket_paths` entry; `proc` (a directly spawned daemon) is then
- terminated; then the sweep kills every `--mode daemon` process whose
- argv references any of `needles` — a respawned main or a detached
- supervisor — and finally every process whose cwd sits under any of
- `cwd_roots` (the detached session workers: `<binary> worker` carries
- no sandbox path in its argv, only in its cwd). SIGTERM first,
- escalate to SIGKILL, re-check for a respawned main until the
- supervisor is gone."""
- for socket_path in socket_paths:
- try:
- wire = Wire(Path(socket_path))
- wire.send_command("sd", {"type": "shutdown"})
- wire.close()
- time.sleep(2)
- except Exception:
- pass
- if proc and proc.poll() is None:
- proc.terminate()
- try:
- proc.wait(timeout=10)
- except subprocess.TimeoutExpired:
- proc.kill()
- exclude = {proc.pid} if proc else set()
- for _ in range(3):
- pids = daemon_pids_matching(needles, exclude_pids=exclude)
- pids += worker_pids_under(cwd_roots, exclude_pids=exclude)
- if not pids:
- return
- for pid in pids:
- try:
- os.kill(pid, 15)
- except (ProcessLookupError, PermissionError):
- pass
- time.sleep(1.0)
- for pid in daemon_pids_matching(needles, exclude_pids=exclude) + worker_pids_under(
- cwd_roots, exclude_pids=exclude
- ):
- try:
- os.kill(pid, 9)
- except (ProcessLookupError, PermissionError):
- pass
- time.sleep(0.5)
-
-
-class Wire:
- """JSONL daemon-protocol client (protocol 7, the TS wire format)."""
-
- def __init__(self, socket_path: Path):
- self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- self.sock.settimeout(90)
- self.sock.connect(str(socket_path))
- self.buf = b""
- self.events: list = []
- self.hello = self.read_line()
-
- def send_command(self, command_id: str, command: dict) -> None:
- envelope = {
- "type": "command",
- "id": command_id,
- "protocol": {"name": "prime-agent.daemon", "version": 7},
- "command": command,
- }
- self.sock.sendall((json.dumps(envelope) + chr(10)).encode())
-
- def read_line(self, timeout: float = 60.0) -> dict:
- """Read one JSON line; raises TimeoutError when nothing arrives."""
- deadline = time.time() + timeout
- while bytes([10]) not in self.buf:
- remaining = deadline - time.time()
- if remaining <= 0:
- raise TimeoutError("daemon line timeout")
- self.sock.settimeout(max(0.1, remaining))
- chunk = self.sock.recv(65536)
- if not chunk:
- raise EOFError("daemon closed the connection")
- self.buf += chunk
- line, self.buf = self.buf.split(bytes([10]), 1)
- return json.loads(line.decode())
-
- def request(self, command_id: str, command: dict, timeout: float = 60.0) -> dict:
- """Send a command; return the response carrying the matching id.
-
- Side events (non-matching lines) are recorded into `self.events`.
- """
- self.send_command(command_id, command)
- deadline = time.time() + timeout
- while True:
- remaining = deadline - time.time()
- if remaining <= 0:
- raise TimeoutError(f"no response for command {command_id}")
- line = self.read_line(timeout=remaining)
- if line.get("id") == command_id:
- return line
- self.events.append(line)
-
- def drain(self, timeout: float = 3.0) -> list:
- """Read whatever the daemon sends for up to `timeout` seconds,
- buffering side events into `self.events`; returns the new events."""
- deadline = time.time() + timeout
- fresh = []
- while True:
- remaining = deadline - time.time()
- if remaining <= 0:
- return fresh
- try:
- line = self.read_line(timeout=remaining)
- except TimeoutError:
- return fresh
- fresh.append(line)
- self.events.append(line)
-
- def close(self) -> None:
- try:
- self.sock.close()
- except OSError:
- pass
-
-
-# -- tmux ---------------------------------------------------------------------
-
-def tmux(*args: str, check: bool = True) -> subprocess.CompletedProcess:
- """Run tmux on the default socket (never the agentui socket)."""
- env = {k: v for k, v in os.environ.items() if k not in ("TMUX", "TMUX_PANE")}
- proc = subprocess.run(
- ["env", "-u", "TMUX", "-u", "TMUX_PANE", "tmux", *args],
- env=env,
- capture_output=True,
- text=True,
- )
- if check and proc.returncode != 0:
- raise RuntimeError(f"tmux {args} failed: {proc.stderr}")
- return proc
-
-
-def tmux_launch(
- session: str,
- command: list[str],
- env: dict,
- cwd: Path,
- size: tuple[int, int] = TMUX_SIZE,
- unset_keys: tuple[str, ...] = (),
-) -> None:
- """Create a detached session of `size` running `command` with `env`.
-
- tmux panes inherit the tmux server's environment, not the client's, so
- the pane command is wrapped in `env KEY=VALUE ...` (and TMUX unset) to
- guarantee isolation from the ambient agent session.
-
- `unset_keys` names keys the pane must never see even though they
- inherit from the server (dropping them from `env` is not enough: an
- inherited key is neither an assignment nor on the scrub list).
-
- The pane runs with `-c cwd` as its working directory, so a relative
- `command[0]` (e.g. `target/release/prime-agent` passed from the repo
- root) would resolve against the pane cwd and vanish instantly. Resolve
- the binary to an absolute path before it reaches the pane.
- """
- if command and not os.path.isabs(command[0]) and "/" in command[0]:
- resolved = Path(command[0]).resolve()
- if not resolved.exists():
- raise RuntimeError(f"tmux_launch: binary {command[0]} not found at {resolved}")
- command = [str(resolved), *command[1:]]
- # The pane inherits the tmux server env, so only the deltas (the scrubbed
- # overrides) need explicit assignment; everything else stays inherited.
- assignment = [
- f"{key}={value}"
- for key, value in sorted(env.items())
- if os.environ.get(key) != value or key in ("PRIME_AGENT_CODING_AGENT_DIR", "TMPDIR")
- ]
- unset = ["-u", "TMUX", "-u", "TMUX_PANE"]
- for key in SCRUB_ENV_KEYS:
- if key not in ("TMUX", "TMUX_PANE"):
- unset += ["-u", key]
- # The tmux server inherited this session's worker markers; unset every
- # one of them so pane processes never see daemon-worker identity.
- for key in list(os.environ):
- if key.startswith(SCRUB_ENV_PREFIXES):
- unset += ["-u", key]
- # The caller's keys ride the same unset (a key that only inherits from
- # the server reaches the pane unless it is named here).
- for key in unset_keys:
- unset += ["-u", key]
- # tmux runs multi-argument pane commands through its default shell, so
- # wrap explicitly: sh -c 'exec env -u ... KEY=V ... <command>'.
- words = (
- ["exec", "/usr/bin/env"]
- + unset
- + assignment
- + list(command)
- )
- import shlex
-
- shell_command = " ".join(shlex.quote(w) for w in words)
- tmux(
- "new-session",
- "-d",
- "-x",
- str(size[0]),
- "-y",
- str(size[1]),
- "-s",
- session,
- "-c",
- str(cwd),
- "/bin/sh",
- "-c",
- shell_command,
- )
-
-
-def tmux_resize(session: str, size: tuple[int, int]) -> None:
- """Resize a detached session's window (frame-parity captures at a
- second terminal size)."""
- tmux("resize-window", "-t", session, "-x", str(size[0]), "-y", str(size[1]), check=False)
-
-
-def tmux_capture(session: str, pane: str = "0") -> str:
- return tmux("capture-pane", "-p", "-t", f"{session}:{pane}").stdout
-
-
-def tmux_send(session: str, keys: str, enter: bool = True) -> None:
- tmux("send-keys", "-t", session, keys, "Enter" if enter else "")
-
-
-def children_of(pid: int) -> list[int]:
- """Live child pids of `pid` (youngest last), by /proc traversal."""
- out = []
- for proc_dir in Path("/proc").iterdir():
- if not proc_dir.name.isdigit():
- continue
- try:
- stat = (proc_dir / "stat").read_text()
- except OSError:
- continue
- # The comm field can contain spaces/parens: split after the last ')'.
- rest = stat[stat.rfind(")") + 1 :].split()
- if len(rest) >= 2 and rest[1] == str(pid):
- out.append(int(proc_dir.name))
- return sorted(out)
-
-
-def tmux_kill(session: str) -> None:
- tmux("kill-session", "-t", session, check=False)
-
-
-def tmux_wait_text(session: str, pattern: str, timeout: float = 60.0, poll: float = 0.5) -> str:
- """Poll a pane until `pattern` appears; returns the final frame."""
- deadline = time.time() + timeout
- frame = ""
- while time.time() < deadline:
- frame = tmux_capture(session)
- if re.search(pattern, frame):
- return frame
- time.sleep(poll)
- return frame
-
-
-# -- normalization + diff helpers ---------------------------------------------
-
-def normalize(value, skip_keys=("timestamp", "id", "parentId", "sessionId", "socketPath", "pid")):
- """Recursively normalize volatile keys for cross-side comparisons."""
-
- def norm(v):
- if isinstance(v, dict):
- return {k: ("<norm>" if k in skip_keys else norm(val)) for k, val in v.items()}
- if isinstance(v, list):
- return [norm(x) for x in v]
- return v
-
- return norm(value)
-
-
-def shape_of(value):
- """A structural fingerprint: dict keys / list shapes / type names."""
-
- def shp(v):
- if isinstance(v, dict):
- return {k: shp(val) for k, val in sorted(v.items())}
- if isinstance(v, list):
- return [shp(v[0])] if v else []
- return type(v).__name__
-
- return shp(value)
-
-
-def copy_dir_contents(src: Path, dst: Path) -> None:
- if not src.exists():
- return
- if dst.exists():
- shutil.rmtree(dst)
- shutil.copytree(src, dst)
-
-
-def write_report(path: Path, title: str, sections: list[dict]) -> None:
- """Write the markdown gap report."""
- lines = [f"# {title}", ""]
- for section in sections:
- lines.append(f"## {section['title']}")
- lines.append("")
- for row in section.get("rows", []):
- lines.append(f"- {row}")
- lines.append("")
- path.write_text(NL.join(lines))
diff --git a/scripts/battery/ci_perf_wave.sh b/scripts/battery/ci_perf_wave.sh
deleted file mode 100755
index 1b29a9cab9..0000000000
--- a/scripts/battery/ci_perf_wave.sh
+++ /dev/null
@@ -1,106 +0,0 @@
-#!/usr/bin/env bash
-# CI entry for the perf wave (driven by the benchmark workflow on main's tree).
-#
-# Creates an ephemeral Prime sandbox (4 CPU / 16 GB, the same spec class the
-# baseline was recorded on), installs the deployed TS binary plus a fresh
-# release build of the checkout, runs scripts/battery/run_perf_wave.sh
-# there, downloads the results, gates them against the recorded baseline,
-# and terminates the sandbox. Every timing comes from the same quiet
-# machine for both sides, which is the whole point of the sandbox.
-#
-# Requirements on the runner: the `prime` CLI, docker-image access to
-# rust:1, tmux/python3 inside the sandbox image, network access.
-#
-# Environment:
-# PA_BENCH_NO_SANDBOX=1 run the wave directly on this runner instead
-# PRIME_SANDBOX_NAME sandbox name (default build-perf-benchmark)
-# PRIME_BENCH_TRIALS trial count (default 5)
-set -euo pipefail
-cd "$(dirname "$0")/../.."
-
-SANDBOX_NAME="${PRIME_SANDBOX_NAME:-build-perf-benchmark}"
-TRIALS="${PRIME_BENCH_TRIALS:-5}"
-
-if [ -n "${PA_BENCH_NO_SANDBOX:-}" ]; then
- PRIME_BENCH_TRIALS="$TRIALS" scripts/battery/run_perf_wave.sh
- exit $?
-fi
-
-SANDBOX_ID="$(
- PRIME_DISABLE_VERSION_CHECK=1 prime sandbox --plain create \
- --name "$SANDBOX_NAME" rust:1 \
- --cpu-cores 4 --memory-gb 16 --disk-size-gb 80 \
- --timeout-minutes 300 -y |
- grep -oE '[0-9a-z]{20,}' | tail -1
-)"
-cleanup() {
- PRIME_DISABLE_VERSION_CHECK=1 prime sandbox --plain delete "$SANDBOX_ID" >/dev/null 2>&1 || true
-}
-trap cleanup EXIT
-echo "== sandbox $SANDBOX_ID"
-
-run_in_sandbox() {
- # 300s exec cap: long work runs detached with a DONE-marker poll.
- PRIME_DISABLE_VERSION_CHECK=1 prime sandbox --plain run "$SANDBOX_ID" "$1"
-}
-
-# 1. ship the checkout + the deployed TS release into the sandbox.
-git bundle create /tmp/benchmark.bundle --all
-prime sandbox --plain upload "$SANDBOX_ID" /tmp/benchmark.bundle /tmp/benchmark.bundle
-RELEASE_TREE="$(dirname "$(readlink -f "$(command -v prime-agent)")")/.."
-# shellcheck disable=SC2012
-TS_RELEASE_TAR=/tmp/ts-release.tar
-tar cf "$TS_RELEASE_TAR" -C "$RELEASE_TREE" .
-prime sandbox --plain upload "$SANDBOX_ID" "$TS_RELEASE_TAR" /tmp/ts-release.tar
-
-cat > /tmp/sb-benchmark.sh <<'EOF'
-#!/bin/bash
-set -euo pipefail
-mkdir -p /opt/repo /opt/ts-release
-cd /opt/repo
-git clone /tmp/benchmark.bundle repo
-cd repo
-git checkout "${GITHUB_HEAD_REF:-main}"
-git log --oneline -1
-tar xf /tmp/ts-release.tar -C /opt/ts-release
-TS_BIN=$(find /opt/ts-release -maxdepth 3 -name prime-agent -type f | head -1)
-ln -sf "$TS_BIN" /usr/local/bin/prime-agent
-prime-agent --version | head -1
-apt-get update -qq && apt-get install -y -qq tmux procps time
-# 2. fresh release build + the wave, detached (the 300s exec cap).
-nohup bash -c '
- cd /opt/repo/repo &&
- PRIME_BENCH_TRIALS="'"$PRIME_BENCH_TRIALS"'" \
- PA_WAVE_RUST_BIN=/opt/repo/repo/target/release/prime-agent \
- scripts/battery/run_perf_wave.sh
- echo $? > /opt/wave.exit
-' > /opt/wave.log 2>&1 &
-echo detached-started
-EOF
-prime sandbox --plain upload "$SANDBOX_ID" /tmp/sb-benchmark.sh /tmp/sb-benchmark.sh
-
-# 3. poll the detached wave to completion.
-DEADLINE=$(( $(date +%s) + 14400 ))
-while true; do
- STATUS=$(run_in_sandbox "if [ -f /opt/wave.exit ]; then cat /opt/wave.exit; else echo running; fi" | tail -1 | tr -d '[:space:]')
- [ "$STATUS" != "running" ] && break
- if [ "$(date +%s)" -gt "$DEADLINE" ]; then
- echo "FATAL: sandbox wave exceeded the 4h poll deadline" >&2
- exit 2
- fi
- sleep 60
-done
-run_in_sandbox "tail -n 40 /opt/wave.log" || true
-if [ "$STATUS" != "0" ]; then
- echo "FATAL: sandbox wave exited with $STATUS (log above)" >&2
- exit 2
-fi
-
-# 4. pull the results back and gate them on the runner.
-mkdir -p scripts/battery/runs
-RUN_DIR="scripts/battery/runs/perf-wave-$(date -u +%Y%m%dT%H%M%SZ)"
-mkdir -p "$RUN_DIR"
-RUN_IN_SANDBOX_DIR=$(run_in_sandbox "ls -1dt /opt/repo/repo/scripts/battery/runs/perf-wave-* | head -1" | grep perf-wave | head -1)
-prime sandbox --plain download "$SANDBOX_ID" "$RUN_IN_SANDBOX_DIR/results.json" "$RUN_DIR/results.json"
-python3 scripts/battery/perf_gate.py --results "$RUN_DIR/results.json"
-echo "== wave results: $RUN_DIR"
diff --git a/scripts/battery/mock_provider.py b/scripts/battery/mock_provider.py
deleted file mode 100644
index e392238012..0000000000
--- a/scripts/battery/mock_provider.py
+++ /dev/null
@@ -1,297 +0,0 @@
-#!/usr/bin/env python3
-"""Deterministic OpenAI-compatible mock provider for the parity battery.
-
-Serves `/v1/chat/completions` (SSE streaming) and `/v1/models` from a JSON
-script file, so the TS binary and the Rust binary can be driven side by side
-with identical model responses. Not part of the product; battery harness
-only.
-
-Script file format:
- {
- "responses": [
- {"text": "hello"},
- {"toolCall": {"name": "bash", "arguments": {"command": "echo hi"}}},
- {"error": "prompt is too long: 213462 tokens > 200000 maximum", "status": 400},
- {"text": "done", "delayMs": 500, "usage": {"prompt_tokens": 100, "completion_tokens": 10, "total_tokens": 110, "prompt_tokens_details": {"cached_tokens": 80}}}
- ],
- "queues": [
- {"name": "child", "match": ["child task text"], "matchModels": ["mock-1"], "responses": [{"text": "child reply"}]}
- ]
- }
-Optional per-response keys: `delayMs` (stream starts after the delay), `usage`
-(overrides the reported token usage, so a flow can push the session past a
-context/compaction threshold deterministically), and `error`/`status` (a
-scripted provider failure: the non-2xx answer carries the OpenAI error body,
-so a flow can script overflow probes identically for both binaries).
-
-Responses are SESSION-SCOPED, not global. The chat-completions wire carries
-no session id, so a queue is selected per request: the first queue whose
-`matchModels` entry equals the request's model id, or whose `match` marker
-appears in the concatenated text of the request's user-role messages, serves
-the request; a request that matches no queue falls through to the default
-`responses` queue. This keeps a parent session and a spawned child session
-(which race the provider concurrently) on independent scripted response
-cursors instead of popping one shared queue in arrival order, and keeps
-model-routed flows (a scripted turn model vs a dashboard status-line model)
-off each other's cursors. User-role text is the discriminator because a
-parent's post-tool continuation embeds the child's task text in tool-call
-arguments and tool results; matching those would misroute the parent.
-Each queue pops its next scripted response per matching request
-(round-robin when a queue runs dry: its last entry repeats). Every request,
-the raw request body, and the serving queue's name are logged to
-`<script>.requests.jsonl` for wire-level diffs.
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import sys
-import threading
-import time
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-
-
-def user_message_text(body: dict) -> str:
- """Concatenated text of the request's user-role messages (string or
- content-part form). Tool results and tool-call arguments are excluded:
- a parent's post-tool continuation embeds the child's task text there,
- so those would misroute the parent into the child's queue."""
- parts = []
- for message in body.get("messages", []):
- if message.get("role") != "user":
- continue
- content = message.get("content")
- if isinstance(content, str):
- parts.append(content)
- elif isinstance(content, list):
- for part in content:
- if isinstance(part, dict) and part.get("text"):
- parts.append(part["text"])
- return chr(10).join(parts)
-
-
-class MockState:
- def __init__(self, script_path: str):
- self.script_path = script_path
- self.script_mtime = None
- self.responses = []
- self.index = 0
- # Session-scoped queues: [{"name", "match", "responses", "index"}]
- self.queues = []
- self.request_log_path = script_path + ".requests.jsonl"
- self.lock = threading.Lock()
- self._reload_if_changed()
-
- def _reload_if_changed(self):
- """Reload the script when the file changes; a new script restarts
- every response cursor at 0, so each battery flow can swap scripts
- against one long-lived provider process."""
- mtime = os.stat(self.script_path).st_mtime
- if mtime != self.script_mtime:
- with open(self.script_path) as f:
- script = json.load(f)
- self.script_mtime = mtime
- self.responses = script["responses"]
- self.index = 0
- self.queues = []
- for queue in script.get("queues", []):
- self.queues.append(
- {
- "name": queue["name"],
- "match": queue.get("match", []),
- "matchModels": queue.get("matchModels", []),
- "responses": queue["responses"],
- "index": 0,
- }
- )
-
- def next_response(self, body: dict):
- """Pop the next scripted response for this request's session: the
- first queue whose model id or user-text markers match serves it;
- no match falls through to the default queue. Returns the serving
- queue's name and the scripted entry."""
- with self.lock:
- self._reload_if_changed()
- user_text = user_message_text(body)
- model = body.get("model", "")
- for queue in self.queues:
- matched_model = model in queue["matchModels"]
- matched_text = any(marker in user_text for marker in queue["match"])
- if matched_model or matched_text:
- entry = queue["responses"][min(queue["index"], len(queue["responses"]) - 1)]
- queue["index"] += 1
- return queue["name"], entry
- entry = self.responses[min(self.index, len(self.responses) - 1)]
- self.index += 1
- return "default", entry
-
-
-def chunk_delta(delta, finish_reason=None):
- return {
- "id": "chatcmpl-battery",
- "object": "chat.completion.chunk",
- "created": 1750000000,
- "model": "mock-1",
- "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],
- }
-
-
-class Handler(BaseHTTPRequestHandler):
- state: MockState
- protocol_version = "HTTP/1.1"
-
- def log_message(self, *args):
- pass
-
- def _json(self, status, obj):
- body = json.dumps(obj).encode()
- self.send_response(status)
- self.send_header("Content-Type", "application/json")
- self.send_header("Content-Length", str(len(body)))
- self.end_headers()
- self.wfile.write(body)
-
- def do_GET(self):
- if self.path.rstrip("/").endswith("/models"):
- self._json(
- 200,
- {"object": "list", "data": [{"id": "mock-1", "object": "model", "owned_by": "battery"}]},
- )
- else:
- self._json(404, {"error": {"message": f"unknown path {self.path}"}})
-
- def do_POST(self):
- length = int(self.headers.get("Content-Length", "0"))
- raw = self.rfile.read(length)
- try:
- body = json.loads(raw)
- except json.JSONDecodeError:
- self._json(400, {"error": {"message": "invalid json"}})
- return
- if "/chat/completions" not in self.path:
- self._json(404, {"error": {"message": f"unknown path {self.path}"}})
- return
- queue_name, entry = self.state.next_response(body)
- with open(self.state.request_log_path, "a") as f:
- f.write(
- json.dumps(
- {
- "path": self.path,
- "body": body,
- "auth": self.headers.get("Authorization", ""),
- "queue": queue_name,
- }
- )
- + "\n"
- )
- # Optional scripted provider failure: `{"error": "<message>",
- # "status": 400}` answers with a non-2xx status and the OpenAI
- # error body, so a flow can script provider failures (overflow
- # probes included) identically for both binaries.
- if "error" in entry:
- error_body = {"message": entry["error"]}
- if entry.get("errorType"):
- error_body["type"] = entry["errorType"]
- self._json(int(entry.get("status") or 400), {"error": error_body})
- return
- # Optional scripted delay: the response starts streaming after
- # `delayMs`, so a battery flow can hold a session mid-turn.
- delay_ms = float(entry.get("delayMs") or 0)
- if delay_ms > 0:
- time.sleep(delay_ms / 1000.0)
- self.send_response(200)
- self.send_header("Content-Type", "text/event-stream")
- self.send_header("Cache-Control", "no-cache")
- self.send_header("Transfer-Encoding", "chunked")
- self.end_headers()
-
- def send(obj):
- data = f"data: {json.dumps(obj)}\r\n\r\n".encode()
- # Proper HTTP chunked framing: each write is one chunk.
- self.wfile.write(f"{len(data):X}\r\n".encode() + data + b"\r\n")
-
- try:
- if "text" in entry:
- send(chunk_delta({"role": "assistant", "content": entry["text"]}))
- elif "toolCall" in entry:
- call = entry["toolCall"]
- args = json.dumps(call["arguments"])
- send(
- chunk_delta(
- {
- "role": "assistant",
- "tool_calls": [
- {
- "index": 0,
- "id": call.get("id", "call_battery_1"),
- "type": "function",
- "function": {"name": call["name"], "arguments": ""},
- }
- ],
- }
- )
- )
- # Stream the arguments JSON in two pieces like a real server.
- half = max(1, len(args) // 2)
- send(
- chunk_delta(
- {
- "tool_calls": [
- {
- "index": 0,
- "function": {"arguments": args[:half]},
- }
- ]
- }
- )
- )
- send(
- chunk_delta(
- {
- "tool_calls": [
- {
- "index": 0,
- "function": {"arguments": args[half:]},
- }
- ],
- }
- )
- )
- else:
- send(chunk_delta({"role": "assistant", "content": ""}))
- send(chunk_delta({}, "stop"))
- usage = entry.get("usage") or {
- "prompt_tokens": 100,
- "completion_tokens": 10,
- "total_tokens": 110,
- "prompt_tokens_details": {"cached_tokens": 80},
- }
- send(
- {
- "id": "chatcmpl-battery",
- "object": "chat.completion.chunk",
- "created": 1750000000,
- "model": "mock-1",
- "choices": [],
- "usage": usage,
- }
- )
- done = b"data: [DONE]\r\n\r\n"
- self.wfile.write(f"{len(done):X}\r\n".encode() + done + b"\r\n")
- # Terminal chunk: end of the chunked body.
- self.wfile.write(b"0\r\n\r\n")
- except (BrokenPipeError, ConnectionResetError):
- pass
-
-
-def main():
- script_path = sys.argv[1]
- Handler.state = MockState(script_path)
- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
- print(server.server_address[1], flush=True)
- server.serve_forever()
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/battery/perf-baseline.json b/scripts/battery/perf-baseline.json
deleted file mode 100644
index 5c9dc8a5b5..0000000000
--- a/scripts/battery/perf-baseline.json
+++ /dev/null
@@ -1,235 +0,0 @@
-{
- "run": "perf-wave-20260921",
- "recorded": "2026-09-21",
- "note": "Rust-side medians from the fresh TS-vs-Rust wave (see BENCHMARKS.md); the gate flags a fresh rust metric >10% worse than these.",
- "results": {
- "startup_typing": {
- "ts": {
- "ready_s_median": 1.539,
- "first_frame_s_median": 1.511,
- "typing_ms_median": 41.1,
- "typing_ms_p95": 63.3,
- "typing_samples": 125,
- "launches": 5
- },
- "rust": {
- "ready_s_median": 0.332,
- "first_frame_s_median": 0.332,
- "typing_ms_median": 39.5,
- "typing_ms_p95": 82.1,
- "typing_samples": 125,
- "launches": 5
- }
- },
- "idle_rss": {
- "ts": {
- "total_mb_median": 998.3,
- "by_role_kb_median": {
- "daemon": 507992,
- "interactive": 258360,
- "kernel": 41532,
- "other": 214608
- },
- "trials": 3
- },
- "rust": {
- "total_mb_median": 165.5,
- "by_role_kb_median": {
- "daemon": 32952,
- "interactive": 42548,
- "kernel": 42288,
- "worker": 43132
- },
- "trials": 3
- }
- },
- "load_rss": {
- "ts": {
- "total_mb": 2830.8,
- "by_role_kb": {
- "daemon": 1571884,
- "other": 224584,
- "interactive": 978632,
- "kernel": 123632
- },
- "panes_settled": 3
- },
- "rust": {
- "total_mb": 784.0,
- "by_role_kb": {
- "daemon": 32176,
- "other": 11792,
- "interactive": 136932,
- "worker": 516196,
- "kernel": 105756
- },
- "panes_settled": 3
- }
- },
- "resume": {
- "ts": {
- "ready_s_median": 1.45,
- "corpus_rows": 1078,
- "launches": 5
- },
- "rust": {
- "ready_s_median": 0.683,
- "corpus_rows": 1078,
- "launches": 5
- }
- },
- "kernel_spawn": {
- "ts": {
- "create_to_first_cell_s_cold_median": 0.789,
- "create_to_first_cell_s_trials": [
- {
- "create_s": 0.491,
- "first_cell_s": 7.297
- },
- {
- "create_s": 0.45,
- "first_cell_s": 0.789
- },
- {
- "create_s": 0.482,
- "first_cell_s": 0.909
- },
- {
- "create_s": 0.519,
- "first_cell_s": 0.603
- },
- {
- "create_s": 0.519,
- "first_cell_s": 0.598
- }
- ],
- "prompt_to_first_cell_s_warm_median": 0.051500000000000004,
- "warm_trials": [
- 0.224,
- 0.05,
- 0.031,
- 0.053,
- 0.053
- ]
- },
- "rust": {
- "create_to_first_cell_s_cold_median": 0.696,
- "create_to_first_cell_s_trials": [
- {
- "create_s": 0.11,
- "first_cell_s": 7.205
- },
- {
- "create_s": 0.105,
- "first_cell_s": 0.711
- },
- {
- "create_s": 0.128,
- "first_cell_s": 0.696
- },
- {
- "create_s": 0.128,
- "first_cell_s": 0.692
- },
- {
- "create_s": 0.133,
- "first_cell_s": 0.684
- }
- ],
- "prompt_to_first_cell_s_warm_median": 0.0495,
- "warm_trials": [
- 0.113,
- 0.04,
- 0.051,
- 0.061,
- 0.048
- ]
- }
- },
- "streaming": {
- "ts": {
- "settle_s_median": 1.4849999999999999,
- "tokens_per_s_est": 7668.0,
- "turns": [
- 1.15,
- 1.82
- ]
- },
- "rust": {
- "settle_s_median": 0.6900000000000001,
- "tokens_per_s_est": 16503.0,
- "turns": [
- 0.93,
- 0.45
- ]
- },
- "_exit_code": 0
- },
- "compaction": {
- "ts": {
- "compact_s_median": 0.045,
- "grown_turns": 40,
- "trials": [
- 0.045,
- 0.049,
- 0.045,
- 0.042,
- 0.044
- ]
- },
- "rust": {
- "compact_s_median": 0.054,
- "grown_turns": 40,
- "trials": [
- 0.051,
- 0.053,
- 0.061,
- 0.054,
- 0.057
- ]
- }
- },
- "export": {
- "ts": {
- "export_s_median": 0.28,
- "html_bytes_median": 866859,
- "trials": [
- 0.248,
- 0.286,
- 0.28,
- 0.308,
- 0.258
- ]
- },
- "rust": {
- "export_s_median": 0.036,
- "html_bytes_median": 866847,
- "trials": [
- 0.037,
- 0.035,
- 0.036,
- 0.039,
- 0.035
- ]
- }
- },
- "daemon_overhead": {
- "ts": {
- "delta_kb_median": 3386992,
- "per_session_kb_median": 338699,
- "trials": [
- 3367436,
- 3406548
- ]
- },
- "rust": {
- "delta_kb_median": 1039850,
- "per_session_kb_median": 103985,
- "trials": [
- 1059744,
- 1019956
- ]
- }
- }
- }
-}
\ No newline at end of file
diff --git a/scripts/battery/perf.py b/scripts/battery/perf.py
deleted file mode 100644
index aee97c1a89..0000000000
--- a/scripts/battery/perf.py
+++ /dev/null
@@ -1,250 +0,0 @@
-#!/usr/bin/env python3
-"""Perf measurement helpers for the parity battery (PERF row).
-
-Two measurements per product side, both taken over the same tmux pane
-channel a real user types through:
-
-- startup: process launch (tmux new-session) to an interactive-ready frame
- (the input prompt plus the settled status chrome). Cold: every measured
- launch uses a fresh daemon socket, so the interactive process also spawns
- and waits for its own daemon, like a real cold start.
-- typing: keystroke-to-render latency. One character at a time via tmux
- send-keys, then a capture-pane poll until the character is visible; the
- per-keystroke wall time includes the fixed tmux subprocess overhead on
- both sides, so the differential is fair.
-
-Not part of the product.
-"""
-
-from __future__ import annotations
-
-import os
-import re
-import sys
-import time
-from pathlib import Path
-
-sys.path.insert(0, str(Path(__file__).parent))
-import batterylib as B # noqa: E402
-
-
-# Interactive-ready marker, identical for both products: the input prompt
-# line, the "manage" bottom bar, and the flagged model resolved in the splash
-# (TS briefly shows "model —" while the session is still loading; keystrokes
-# sent in that window are swallowed, so the model id is part of ready).
-READY_PROMPT = re.compile(r"^\s*>\s*$", re.MULTILINE)
-READY_MODEL_ID = "mock-1"
-
-
-def is_ready(side_name: str, frame: str) -> bool:
- del side_name # the marker is product-agnostic
- return (
- bool(READY_PROMPT.search(frame))
- and "manage" in frame
- and READY_MODEL_ID in frame
- )
-
-
-# The typed string: plain alphanumerics only (no tmux key-name collisions),
-# distinctive enough that an accidental match elsewhere in a frame is
-# implausible.
-TYPING_TEXT = "zqxjvtypingfeel0123456789"
-
-# Cold-start cleanup grace: after a wire shutdown, force-kill any process
-# still holding this run's socket path in its command line.
-SHUTDOWN_GRACE_S = 10.0
-
-
-def stop_perf_daemon(socket_path: Path) -> None:
- """Shut the measured run's daemon down: wire `shutdown`, then a targeted
- kill of anything still referencing the socket path."""
- try:
- wire = B.Wire(socket_path)
- wire.send_command("sd", {"type": "shutdown"})
- wire.close()
- except (OSError, EOFError):
- pass
- deadline = time.time() + SHUTDOWN_GRACE_S
- needle = str(socket_path)
- while time.time() < deadline:
- if _pids_referencing(needle):
- time.sleep(0.2)
- else:
- return
- for pid in _pids_referencing(needle):
- try:
- os.kill(pid, 15)
- except (ProcessLookupError, PermissionError):
- pass
- time.sleep(0.5)
-
-
-def _pids_referencing(needle: str) -> list[int]:
- hits = []
- for proc_dir in Path("/proc").iterdir():
- if not proc_dir.name.isdigit():
- continue
- try:
- cmdline = (proc_dir / "cmdline").read_bytes().decode(errors="replace")
- except (OSError, PermissionError):
- continue
- if needle in cmdline:
- hits.append(int(proc_dir.name))
- return hits
-
-
-def launch_argv(side: B.Side, daemon_socket: Path) -> list[str]:
- """The interactive launch invocation every perf launch uses, onboard
- settle run included. The flagged provider/model resolve mock-1: a fresh
- install would show the first-run trace notice (both products resolve the
- startup model from settings + auth now), so the flags keep the notice
- out of the settle measurement while still exercising the readiness gate."""
- return [
- side.binary,
- "--daemon-socket",
- str(daemon_socket),
- "--provider",
- "prime-inference",
- "--model",
- "mock-1",
- "--offline",
- ]
-
-
-def measure_launch(side: B.Side, tag: str, daemon_socket: Path) -> dict:
- """One cold interactive launch: startup numbers plus the typing
- measurement taken in the same session. The record carries `session`,
- `first_frame_s`, `ready_s`, `typing_ms`, and the ready frame."""
- session = tag
- daemon_socket.parent.mkdir(parents=True, exist_ok=True)
- if daemon_socket.exists():
- daemon_socket.unlink()
- argv = launch_argv(side, daemon_socket)
- t0 = time.time()
- B.tmux_launch(session, argv, side.env, side.work_dir)
- first_frame_s = None
- ready_s = None
- ready_frame = ""
- deadline = t0 + 60.0
- while time.time() < deadline:
- frame = B.tmux_capture(session)
- if first_frame_s is None and frame.strip():
- first_frame_s = round(time.time() - t0, 3)
- if is_ready(side.name, frame):
- ready_s = round(time.time() - t0, 3)
- ready_frame = frame
- break
- time.sleep(0.01)
- typing_ms: list[float] = []
- if ready_s is not None:
- typing_ms = measure_typing(session, side.name)
- B.tmux_kill(session)
- return {
- "session": session,
- "first_frame_s": first_frame_s,
- "ready_s": ready_s,
- "typing_ms": typing_ms,
- "ready_frame": ready_frame,
- }
-
-
-def measure_typing(session: str, side_name: str, text: str = TYPING_TEXT) -> list[float]:
- """Per-keystroke keystroke-to-render latencies (ms) while typing `text`."""
- latencies: list[float] = []
- typed = ""
- for ch in text:
- typed += ch
- t0 = time.time()
- B.tmux("send-keys", "-t", session, "-l", ch)
- # Rendered = the typed prefix sits on the input prompt line (a
- # whole-frame substring match would false-positive on the cwd).
- pattern = re.compile(r"^\s*>\s*" + re.escape(typed), re.MULTILINE)
- rendered = False
- deadline = t0 + 2.0
- while time.time() < deadline:
- frame = B.tmux_capture(session)
- # `is_ready` demands an empty prompt line, which is false the
- # moment the first keystroke renders: here the prompt line
- # carrying the typed prefix plus the bottom bar is the evidence.
- if pattern.search(frame) and "manage" in frame:
- rendered = True
- break
- time.sleep(0.001)
- if not rendered:
- # Keep the sequence honest: a lost keystroke surfaces as a
- # timeout-shaped latency so medians do not silently drop it.
- latencies.append(round((time.time() - t0) * 1000, 1))
- break
- latencies.append(round((time.time() - t0) * 1000, 1))
- time.sleep(0.03)
- return latencies
-
-
-def measure_resume(
- side: B.Side,
- tag: str,
- daemon_socket: Path,
- corpus: Path,
- timeout_s: float,
-) -> dict:
- """One interactive `--resume <corpus>` launch, measured to the ready
- frame (prompt line + manage bar + resolved model id). The record
- carries `session`, `first_frame_s`, `ready_s`, and the ready frame: the
- ready time is snapshot ingest plus first full layout, the path a
- transcript-scale resume pays before the user can type."""
- session = tag
- daemon_socket.parent.mkdir(parents=True, exist_ok=True)
- if daemon_socket.exists():
- daemon_socket.unlink()
- argv = launch_argv(side, daemon_socket) + ["--resume", str(corpus)]
- t0 = time.time()
- B.tmux_launch(session, argv, side.env, side.work_dir)
- first_frame_s = None
- ready_s = None
- ready_frame = ""
- deadline = t0 + timeout_s
- while time.time() < deadline:
- frame = B.tmux_capture(session)
- if first_frame_s is None and frame.strip():
- first_frame_s = round(time.time() - t0, 3)
- if is_ready(side.name, frame):
- ready_s = round(time.time() - t0, 3)
- ready_frame = frame
- break
- time.sleep(0.05)
- B.tmux_kill(session)
- return {
- "session": session,
- "first_frame_s": first_frame_s,
- "ready_s": ready_s,
- "ready_frame_rows": len(ready_frame.splitlines()) if ready_frame else 0,
- "ready_frame_tail": ready_frame[-2000:] if ready_frame else "",
- }
-
-
-def summarize(values: list[float]) -> dict:
- ordered = sorted(values)
- if not ordered:
- return {"n": 0}
-
- def pct(p: float) -> float:
- idx = min(len(ordered) - 1, int(round(p / 100 * (len(ordered) - 1))))
- return round(ordered[idx], 1)
-
- return {
- "n": len(ordered),
- "min": round(ordered[0], 1),
- "median": pct(50),
- "p95": pct(95),
- "max": round(ordered[-1], 1),
- }
-
-
-def median(values: list[float]) -> float | None:
- if not values:
- return None
- ordered = sorted(values)
- mid = len(ordered) // 2
- if len(ordered) % 2:
- return ordered[mid]
- return (ordered[mid - 1] + ordered[mid]) / 2.0
diff --git a/scripts/battery/perf_gate.py b/scripts/battery/perf_gate.py
deleted file mode 100644
index e15fdaa89f..0000000000
--- a/scripts/battery/perf_gate.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/usr/bin/env python3
-"""Regression gate for the perf wave: compare a fresh results.json against
-the recorded baseline and flag Rust regressions beyond a threshold.
-
-The gate compares the RUST side's own medians against the baseline's rust
-medians (an absolute regression check): the TS side is the ground truth and
-its numbers move with the TS release, but a Rust metric that got >10% worse
-than the recorded baseline is a regression regardless of TS.
-
-Higher-is-worse for every metric compared here.
-
-Usage:
- python3 scripts/battery/perf_gate.py --results <run>/results.json \
- [--baseline scripts/battery/perf-baseline.json] [--threshold 1.10]
-
-Not part of the product.
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-from pathlib import Path
-
-# results[dim][side] -> the metrics the gate tracks (all lower-is-better).
-TRACKED = {
- "startup_typing": ["ready_s_median", "typing_ms_median", "typing_ms_p95"],
- "idle_rss": ["total_mb_median"],
- "load_rss": ["total_mb"],
- "resume": ["ready_s_median"],
- "kernel_spawn": [
- "create_to_first_cell_s_cold_median",
- "prompt_to_first_cell_s_warm_median",
- ],
- "streaming": ["settle_s_median"],
- "sustained_cpu": [
- "tui_idle_mean_pct",
- "tui_plain_mean_pct",
- "tui_code_mean_pct",
- "tui_tool_mean_pct",
- "typing_ms_median",
- ],
- "compaction": ["compact_s_median"],
- "export": ["export_s_median"],
- "daemon_overhead": ["delta_kb_median", "per_session_kb_median"],
-}
-
-
-def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- here = Path(__file__).resolve().parent
- parser.add_argument("--results", required=True)
- parser.add_argument("--baseline", default=str(here / "perf-baseline.json"))
- parser.add_argument("--threshold", type=float, default=1.10)
- parser.add_argument(
- "--allow-missing",
- action="store_true",
- help="dims absent from the fresh run are warnings, not failures",
- )
- args = parser.parse_args()
-
- fresh = json.loads(Path(args.results).read_text())
- baseline = json.loads(Path(args.baseline).read_text())
- fresh_results = fresh.get("results", {})
- baseline_results = baseline.get("results", {})
-
- regressions = []
- warnings = []
- checked = 0
- for dim, metrics in TRACKED.items():
- fresh_dim = fresh_results.get(dim)
- base_dim = baseline_results.get(dim)
- if not isinstance(fresh_dim, dict) or not isinstance(base_dim, dict):
- message = f"{dim}: not evaluable (missing from "
- message += "fresh run)" if base_dim else "(missing from baseline)"
- (warnings if args.allow_missing else regressions).append(message)
- continue
- for metric in metrics:
- fresh_value = fresh_dim.get("rust", {}).get(metric)
- base_value = base_dim.get("rust", {}).get(metric)
- if fresh_value is None or base_value is None:
- (warnings if args.allow_missing else regressions).append(
- f"{dim}.{metric}: not evaluable (fresh={fresh_value} baseline={base_value})"
- )
- continue
- checked += 1
- ratio = float(fresh_value) / float(base_value)
- if ratio > args.threshold:
- regressions.append(
- f"REGRESSION {dim}.{metric}: rust {fresh_value} vs baseline "
- f"{base_value} (ratio {ratio:.2f} > {args.threshold})"
- )
- else:
- print(
- f"ok {dim}.{metric}: rust {fresh_value} vs baseline "
- f"{base_value} (ratio {ratio:.2f})"
- )
-
- for message in warnings:
- print(f"WARN {message}")
- if regressions:
- for message in regressions:
- print(message, file=sys.stderr)
- print(
- f"FAIL: {len(regressions)} regression(s) beyond "
- f"{args.threshold:.2f}x the recorded baseline ({checked} metrics checked)",
- file=sys.stderr,
- )
- return 1
- print(f"PASS: no rust regression beyond {args.threshold:.2f}x ({checked} metrics checked)")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/scripts/battery/perf_wave.py b/scripts/battery/perf_wave.py
deleted file mode 100644
index 3f1ed6265c..0000000000
--- a/scripts/battery/perf_wave.py
+++ /dev/null
@@ -1,1026 +0,0 @@
-#!/usr/bin/env python3
-"""TS-vs-Rust performance wave: the f10 dimensions plus the extended set.
-
-Every dimension runs the TS binary and the Rust binary side by side through
-the same tmux pane channel / daemon wire a real user drives, against the
-same deterministic mock provider (batterylib). Medians over N interleaved
-trials; the differential is the reported number.
-
-Dimensions (each writes evidence under <run>/<dim>/<side>/):
- startup_typing cold startup to ready + keystroke-to-render (f10 rerun)
- idle_rss steady-state RSS after a cold launch (daemon + TUI tree)
- load_rss RSS with 3 attached sessions, each running a kernel cell
- resume cold resume of a 1000+ row transcript to ready
- kernel_spawn prompt -> first ipython cell output rendered (boot + warm)
- streaming unpaced ~12k-token turn settle (tokens/sec through TUI;
- reuses stream_throughput.py)
- compaction wire `compact` pipeline duration on an imported 1000+ row
- session
- export `session export` (HTML) wall time on the large corpus
- daemon_overhead daemon-tree RSS delta across 10 idle sessions
- sustained_cpu 30s idle + paced plain/code streaming + long tool turn
- %CPU of the interactive process, asserted (render-loop
- regression guard, lane cpu-spin)
-
-Runs on the mission box or in a perf sandbox; timings are only comparable
-when both sides run on the same quiet machine, so the intended execution is
-a fresh Prime sandbox (see .github/workflows/benchmark.yml and
-scripts/battery/run_perf_wave.sh).
-
-Not part of the product.
-
-Usage:
- python3 scripts/battery/perf_wave.py [--dims all] [--trials 5]
- [--runs-root scripts/battery/runs] [--ts-bin prime-agent]
- [--rust-bin target/release/prime-agent] [--run-name perf-wave]
-"""
-
-from __future__ import annotations
-
-import argparse
-import datetime
-import json
-import os
-import re
-import shutil
-import subprocess
-import sys
-import time
-from pathlib import Path
-
-sys.path.insert(0, str(Path(__file__).parent))
-import batterylib as B # noqa: E402
-import perf as P # noqa: E402
-import scale_corpus # noqa: E402
-import ts_identity # noqa: E402
-
-NL = chr(10)
-
-ALL_DIMS = [
- "startup_typing",
- "idle_rss",
- "load_rss",
- "resume",
- "kernel_spawn",
- "streaming",
- "compaction",
- "export",
- "daemon_overhead",
- "sustained_cpu",
-]
-
-# The 1000+ row resume/export corpus: 350 turns -> 1078 rows.
-CORPUS_TURNS = 350
-CORPUS_ROWS = scale_corpus.corpus_rows(CORPUS_TURNS)
-# The compaction dim grows its sessions through live turns instead (see
-# the PARITY NOTE above).
-
-KERNEL_MARKER = "KERNEL_BENCH_42"
-KERNEL_CODE = f"print('{KERNEL_MARKER}')"
-
-# RSS settling: the interactive tree must be quiet for this long before a
-# memory sample is taken.
-RSS_QUIET_S = 3.0
-
-
-class PerfWave:
- def __init__(self, run_dir: Path, ts_bin: str, rust_bin: str, dims: list[str], trials: int):
- self.run_dir = run_dir
- self.stamp = run_dir.name
- self.ts_bin = ts_bin
- self.rust_bin = rust_bin
- self.dims = dims
- self.trials = trials
- self.runid = "vwave" + self.stamp
- self.sides: dict[str, B.Side] = {}
- self.tmpdirs: dict[str, Path] = {}
-
- # -- setup / teardown ----------------------------------------------------
-
- def make_side(self, name: str, binary: str) -> B.Side:
- root = self.run_dir / name
- (root / "agent").mkdir(parents=True, exist_ok=True)
- (root / "work").mkdir(parents=True, exist_ok=True)
- mock = B.MockProvider(root, [])
- mock.set_responses([{"text": "hello"}])
- mock.start()
- tmpdir = Path("/tmp") / f"{self.runid}-{name}"
- if tmpdir.exists():
- shutil.rmtree(tmpdir)
- tmpdir.mkdir(parents=True)
- self.tmpdirs[name] = tmpdir
- side = B.Side(
- name=name,
- binary=binary,
- root=root,
- agent_dir=root / "agent",
- work_dir=root / "work",
- daemon_socket=root / "daemon.sock",
- mock=mock,
- )
- side.env = B.scrubbed_env(side.agent_dir, tmpdir)
- if name == "rust":
- # The Rust binary resolves the kernel runtime sidecar through
- # PI_PACKAGE_DIR (the checkout ships prime-agent-runtime/).
- side.env["PI_PACKAGE_DIR"] = str(Path(__file__).resolve().parents[2])
- side.env["PRIME_API_KEY"] = "sk-battery"
- side.write_models_json()
- self.sides[name] = side
- return side
-
- def teardown_sides(self) -> None:
- for side in self.sides.values():
- side.stop_daemon()
- for tmpdir in self.tmpdirs.values():
- shutil.rmtree(tmpdir, ignore_errors=True)
- for side in self.sides.values():
- side.mock.stop()
-
- def onboard(self, side: B.Side) -> None:
- """Settle first-run dialogs once (the perf.py launch gate)."""
- socket = side.root / "onboard.sock"
- socket.parent.mkdir(parents=True, exist_ok=True)
- if socket.exists():
- socket.unlink()
- session = f"{self.runid}-onboard-{side.name}"
- B.tmux_launch(session, P.launch_argv(side, socket), side.env, side.work_dir)
- deadline = time.time() + 30
- while time.time() < deadline:
- frame = B.tmux_capture(session)
- if "Share agent traces" in frame:
- B.tmux_send(session, "Down")
- time.sleep(0.5)
- B.tmux_send(session, "Enter")
- time.sleep(1.0)
- elif P.is_ready(side.name, frame):
- break
- else:
- time.sleep(0.5)
- deadline = time.time() + 30
- while time.time() < deadline:
- if P.is_ready(side.name, B.tmux_capture(session)):
- break
- time.sleep(0.5)
- B.tmux_kill(session)
- P.stop_perf_daemon(socket)
-
- # -- RSS sampling ---------------------------------------------------------
-
- def side_process_records(self, side: B.Side) -> list[dict]:
- """Every live process belonging to this side's product tree: the
- environ carries the side's isolated agent dir + TMPDIR into every
- spawned process (daemon, supervisor, TUI, workers, kernels), so the
- env is the complete, product-agnostic scope (argv-based sweeps miss
- short-argv workers)."""
- records = []
- agent_needle = str(side.agent_dir)
- tmp_needle = str(self.tmpdirs[side.name])
- socket_needle = str(side.daemon_socket)
- for proc_dir in Path("/proc").iterdir():
- if not proc_dir.name.isdigit():
- continue
- pid = int(proc_dir.name)
- if pid in (1, os.getpid()):
- continue
- try:
- argv = [
- part.decode(errors="replace")
- for part in (proc_dir / "cmdline").read_bytes().split(b"\0")
- if part
- ]
- except OSError:
- continue
- environ_text = ""
- try:
- environ_text = (proc_dir / "environ").read_bytes().decode(errors="replace")
- except OSError:
- pass
- owns = (
- agent_needle in environ_text
- or tmp_needle in environ_text
- or socket_needle in " ".join(argv)
- )
- if not owns or not argv:
- continue
- try:
- status = (proc_dir / "status").read_text()
- except OSError:
- continue
- rss_kb = 0
- for line in status.splitlines():
- if line.startswith("VmRSS:"):
- rss_kb = int(line.split()[1])
- break
- if rss_kb == 0:
- continue
- records.append(
- {
- "pid": pid,
- "role": self.role_of(argv),
- "rss_kb": rss_kb,
- "argv": argv[:6],
- }
- )
- return records
-
- @staticmethod
- def role_of(argv: list[str]) -> str:
- if "--mode" in argv and "daemon" in argv:
- return "daemon"
- if "worker" in argv:
- return "worker"
- if argv[0].endswith(("python", "python3")) or "rlm.repl" in " ".join(argv):
- return "kernel"
- if "--daemon-socket" in argv:
- return "interactive"
- return "other"
-
- def rss_sample(self, side: B.Side, quiet_s: float = RSS_QUIET_S) -> dict:
- """Take an RSS sample once the tree is quiet: no transient
- setup/install processes (the first-touch kernel-runtime provision —
- `uv pip install`, venv creation, build backends — runs in the
- background and would otherwise land in the sample; run 3 of the
- 2026-09-21 wave caught a 147 MB `uv` install on the TS side), and
- the total stable to ±2% across `quiet_s` seconds."""
- # The transient wait (kernel-runtime provisioning) is effectively
- # uncapped: a cold sandbox installs numpy/pandas-class packages and
- # `uv` can run for minutes; sampling during it reports install
- # memory as idle memory. The stability gate below still applies.
- deadline = time.time() + 600.0
- stable_since: float | None = None
- last_total = -1
- while time.time() < deadline:
- records = self.side_process_records(side)
- transient = any(
- any(
- part in ("uv", "pip", "hatchling", "virtualenv")
- or part.endswith("/uv")
- or part.endswith("/pip")
- or part.endswith("/virtualenv")
- for part in r["argv"]
- )
- for r in records
- )
- total_kb = sum(r["rss_kb"] for r in records)
- if transient:
- stable_since = None
- elif (
- last_total >= 0
- and abs(total_kb - last_total) <= max(1.0, 0.02 * last_total)
- ):
- if stable_since is None:
- stable_since = time.time()
- elif time.time() - stable_since >= quiet_s:
- break
- else:
- stable_since = None
- last_total = total_kb
- time.sleep(2.0)
- records = self.side_process_records(side)
- total_kb = sum(r["rss_kb"] for r in records)
- by_role: dict[str, int] = {}
- for r in records:
- by_role[r["role"]] = by_role.get(r["role"], 0) + r["rss_kb"]
- return {
- "total_kb": total_kb,
- "by_role_kb": by_role,
- "processes": records,
- }
-
- def evidence(self, dim: str, side_name: str, name: str, obj) -> Path:
- path = self.run_dir / dim / side_name / name
- path.parent.mkdir(parents=True, exist_ok=True)
- text = obj if isinstance(obj, str) else json.dumps(obj, indent=1)
- path.write_text(text)
- return path
-
- def median(self, values: list[float]) -> float | None:
- return P.median(values)
-
- # -- dimension: startup + typing (the f10 rerun) ---------------------------
-
- def dim_startup_typing(self) -> dict:
- out: dict[str, dict] = {}
- buckets: dict[str, dict] = {}
- for side_name in ("ts", "rust"):
- buckets[side_name] = {"ready_s": [], "first_frame_s": [], "typing_ms": []}
- for i in range(self.trials):
- for side_name in ("ts", "rust"):
- side = self.sides[side_name]
- socket = side.root / "startup" / f"sock-{i}.sock"
- rec = P.measure_launch(side, f"{self.runid}-start-{side_name}-{i}", socket)
- self.evidence("startup_typing", side_name, f"launch-{i}.json", rec)
- P.stop_perf_daemon(socket)
- if rec["ready_s"] is None:
- print(f"WARNING: {side_name} launch {i} never reached ready", file=sys.stderr)
- continue
- bucket = buckets[side_name]
- bucket["ready_s"].append(rec["ready_s"])
- bucket["first_frame_s"].append(rec["first_frame_s"] or rec["ready_s"])
- bucket["typing_ms"].extend(rec["typing_ms"])
- for side_name in ("ts", "rust"):
- bucket = buckets[side_name]
- self.evidence("startup_typing", side_name, "summary.json", bucket)
- typing = P.summarize(bucket["typing_ms"])
- out[side_name] = {
- "ready_s_median": self.median(bucket["ready_s"]),
- "first_frame_s_median": self.median(bucket["first_frame_s"]),
- "typing_ms_median": typing.get("median"),
- "typing_ms_p95": typing.get("p95"),
- "typing_samples": typing.get("n"),
- "launches": len(bucket["ready_s"]),
- }
- return out
-
- # -- dimension: idle RSS ---------------------------------------------------
-
- def dim_idle_rss(self) -> dict:
- out: dict[str, dict] = {}
- samples: dict[str, list[dict]] = {"ts": [], "rust": []}
- for i in range(max(2, self.trials // 2 + 1)):
- for side_name in ("ts", "rust"):
- side = self.sides[side_name]
- socket = side.root / "idle" / f"sock-{i}.sock"
- socket.parent.mkdir(parents=True, exist_ok=True)
- if socket.exists():
- socket.unlink()
- session = f"{self.runid}-idle-{side_name}-{i}"
- B.tmux_launch(
- session, P.launch_argv(side, socket), side.env, side.work_dir
- )
- deadline = time.time() + 60
- while time.time() < deadline:
- if P.is_ready(side_name, B.tmux_capture(session)):
- break
- time.sleep(0.05)
- sample = self.rss_sample(side)
- sample["trial"] = i
- samples[side_name].append(sample)
- B.tmux_kill(session)
- P.stop_perf_daemon(socket)
- for side_name in ("ts", "rust"):
- self.evidence("idle_rss", side_name, "samples.json", samples[side_name])
- totals = [s["total_kb"] for s in samples[side_name]]
- out[side_name] = {
- "total_mb_median": round(self.median(totals) / 1024.0, 1),
- "by_role_kb_median": self._median_by_role(samples[side_name]),
- "trials": len(totals),
- }
- return out
-
- @staticmethod
- def _median_by_role(samples: list[dict]) -> dict:
- roles: dict[str, list[int]] = {}
- for sample in samples:
- for role, kb in sample["by_role_kb"].items():
- roles.setdefault(role, []).append(kb)
- return {role: int(P.median(kbs)) for role, kbs in sorted(roles.items())}
-
- # -- dimension: load RSS (3 sessions with kernel activity) -----------------
-
- def dim_load_rss(self) -> dict:
- out: dict[str, dict] = {}
- for side_name in ("ts", "rust"):
- side = self.sides[side_name]
- self.ensure_fresh_daemon(side)
- # 3 interactive sessions on the same daemon, each running one
- # kernel cell: the mock serves one ipython tool call per pane.
- # Session-scoped mock queues: each pane's initial prompt pops a
- # per-pane ipython tool call; the post-tool continuations fall
- # through to the shared default queue (the mock excludes tool
- # results from queue matching) and get the plain done reply.
- queues = []
- for pane in range(3):
- queues.append(
- {
- "name": f"load-{pane}",
- "match": [f"load bench pane {pane}"],
- "responses": [
- {
- "toolCall": {
- "name": "ipython",
- "arguments": {"code": f"print('LOAD_DONE_{pane}')"},
- }
- }
- ],
- }
- )
- side.mock.set_responses(
- [{"text": f"load bench done {pane}"} for pane in range(3)], queues
- )
- panes = []
- for pane in range(3):
- session = f"{self.runid}-load-{side_name}-{pane}"
- argv = P.launch_argv(side, side.daemon_socket)
- B.tmux_launch(session, argv, side.env, side.work_dir)
- panes.append(session)
- deadline = time.time() + 90
- while time.time() < deadline:
- if P.is_ready(side_name, B.tmux_capture(session)):
- break
- time.sleep(0.1)
- for pane, session in enumerate(panes):
- B.tmux_send(session, f"run load bench pane {pane}", enter=True)
- settled = 0
- deadline = time.time() + 300
- while time.time() < deadline and settled < len(panes):
- settled = 0
- for pane, session in enumerate(panes):
- if f"LOAD_DONE_{pane}" in B.tmux_capture(session):
- settled += 1
- time.sleep(0.5)
- if settled < len(panes):
- print(
- f"WARNING: {side_name} load bench: only {settled}/3 panes settled",
- file=sys.stderr,
- )
- sample = self.rss_sample(side)
- self.evidence("load_rss", side_name, "sample.json", sample)
- out[side_name] = {
- "total_mb": round(sample["total_kb"] / 1024.0, 1),
- "by_role_kb": sample["by_role_kb"],
- "panes_settled": settled,
- }
- for session in panes:
- B.tmux_kill(session)
- side.stop_daemon()
- return out
-
- # -- dimension: session resume ---------------------------------------------
-
- def corpus_path(self) -> Path:
- # Header cwd = the shared run dir (the battery's f12 pattern): one
- # corpus file, identical on both sides.
- return scale_corpus.corpus_path(CORPUS_TURNS, self.run_dir, str(self.run_dir))
-
- def dim_resume(self) -> dict:
- corpus = self.corpus_path()
- out: dict[str, dict] = {}
- buckets: dict[str, list] = {"ts": [], "rust": []}
- for i in range(max(3, self.trials)):
- for side_name in ("ts", "rust"):
- side = self.sides[side_name]
- socket = side.root / "resume" / f"sock-{i}.sock"
- socket.parent.mkdir(parents=True, exist_ok=True)
- if socket.exists():
- socket.unlink()
- rec = P.measure_resume(
- side,
- f"{self.runid}-resume-{side_name}-{i}",
- socket,
- corpus,
- timeout_s=300.0,
- )
- rec["corpus_rows"] = CORPUS_ROWS
- self.evidence("resume", side_name, f"launch-{i}.json", rec)
- P.stop_perf_daemon(socket)
- if rec["ready_s"] is None:
- print(
- f"WARNING: {side_name} resume {i} never reached ready",
- file=sys.stderr,
- )
- continue
- buckets[side_name].append(rec["ready_s"])
- for side_name in ("ts", "rust"):
- self.evidence(
- "resume", side_name, "summary.json", {"ready_s": buckets[side_name]}
- )
- out[side_name] = {
- "ready_s_median": self.median(buckets[side_name]),
- "corpus_rows": CORPUS_ROWS,
- "launches": len(buckets[side_name]),
- }
- return out
-
- # -- dimension: kernel spawn -------------------------------------------------
-
- def dim_kernel_spawn(self) -> dict:
- """Two kernel measures, both product-level and identical on the two
- binaries:
-
- - cold `create -> first kernel cell ready`: daemon session create
- plus one prompt whose mock reply is an ipython tool call; the
- wire `prompt_and_wait` round trip completes only after the kernel
- booted and the first cell returned. This is the session-create
- path a user's first ipython cell pays.
- - warm `prompt -> first cell rendered`: keystroke-to-render on an
- attached interactive pane with an already-running kernel.
- """
- out: dict[str, dict] = {}
- for side_name in ("ts", "rust"):
- side = self.sides[side_name]
- self.ensure_fresh_daemon(side)
- # Cold: session create -> first kernel cell, over the wire.
- cold_trials = []
- for trial in range(max(3, self.trials)):
- side.mock.set_responses(
- [
- {
- "toolCall": {
- "name": "ipython",
- "arguments": {"code": KERNEL_CODE},
- }
- },
- {"text": f"kernel bench reply {trial}"},
- ]
- )
- wire = B.Wire(side.daemon_socket)
- t0 = time.time()
- create = wire.request(
- f"kc{trial}",
- {
- "type": "create",
- "name": f"wave-kernel-{trial}",
- "config": self.session_config(side),
- },
- timeout=120,
- )
- if create.get("success") is not True:
- print(f"WARNING: {side_name} kernel create failed: {create}", file=sys.stderr)
- wire.close()
- break
- session_id = create["data"].get("activeSessionId") or create["data"].get("id")
- create_s = time.time() - t0
- prompt = wire.request(
- f"kp{trial}",
- {
- "type": "prompt_and_wait",
- "activeSessionId": session_id,
- "message": f"kernel bench turn {trial}",
- },
- timeout=300,
- )
- total_s = round(time.time() - t0, 3)
- wire.close()
- self.evidence(
- "kernel_spawn",
- side_name,
- f"cold-{trial}.json",
- {
- "create_s": round(create_s, 3),
- "prompt_to_cell_s": round(total_s - create_s, 3),
- "create_to_first_cell_s": total_s,
- "prompt_success": prompt.get("success"),
- },
- )
- if prompt.get("success") is not True:
- print(f"WARNING: {side_name} kernel prompt failed: {prompt}", file=sys.stderr)
- continue
- cold_trials.append({"create_s": round(create_s, 3), "first_cell_s": total_s})
- # Warm: interactive pane with a booted kernel.
- session = f"{self.runid}-kernel-{side_name}"
- B.tmux_launch(
- session, P.launch_argv(side, side.daemon_socket), side.env, side.work_dir
- )
- deadline = time.time() + 90
- while time.time() < deadline:
- if P.is_ready(side_name, B.tmux_capture(session)):
- break
- time.sleep(0.1)
- latencies = []
- for trial in range(max(3, self.trials)):
- side.mock.set_responses(
- [
- {
- "toolCall": {
- "name": "ipython",
- "arguments": {"code": KERNEL_CODE},
- }
- },
- {"text": f"kernel bench reply {trial}"},
- ]
- )
- t0 = time.time()
- B.tmux_send(session, f"kernel bench turn {trial}", enter=True)
- rendered = False
- deadline = t0 + 180
- while time.time() < deadline:
- frame = B.tmux_capture(session)
- if KERNEL_MARKER in frame:
- rendered = True
- break
- time.sleep(0.05)
- if not rendered:
- print(
- f"WARNING: {side_name} kernel bench warm trial {trial} timed out",
- file=sys.stderr,
- )
- break
- latencies.append(round(time.time() - t0, 3))
- # settle so the next sample is not polluted by residual
- # rendering
- time.sleep(2.0)
- self.evidence("kernel_spawn", side_name, "warm-trials.json", latencies)
- warm = self.median(latencies[1:]) if len(latencies) > 1 else None
- out[side_name] = {
- "create_to_first_cell_s_cold_median": self.median(
- [t["first_cell_s"] for t in cold_trials]
- )
- if cold_trials
- else None,
- "create_to_first_cell_s_trials": cold_trials,
- "prompt_to_first_cell_s_warm_median": warm,
- "warm_trials": latencies,
- }
- B.tmux_kill(session)
- side.stop_daemon()
- return out
-
- # -- dimension: streaming throughput -----------------------------------------
-
- # -- dimension: sustained CPU (render-loop regression guard) ------------------
- #
- # The cpu-spin dogfood fix (frame-batch scheduler, per-block markdown
- # cache, timer-driven spinner) is guarded by absolute budgets, not a
- # TS ratio: a render loop that burns 90%+ of a core while idle or
- # while a stream renders is a bug at any TS-relative speed.
- # sustained_cpu.py drives the interactive TUI through the faux
- # provider (idle window, paced plain-text stream, paced code stream,
- # long tool-execution turn), samples %CPU per process from /proc, and
- # asserts: idle < 5%, streaming < 30%, typing mid-stream < 50ms, and
- # the double-Ctrl+C exit mid-scroll (bug #6's trapped-scroll repro).
-
- def dim_sustained_cpu(self) -> dict:
- script = Path(__file__).parent / "sustained_cpu.py"
- out_dir = self.run_dir / "sustained_cpu"
- out_dir.mkdir(parents=True, exist_ok=True)
- # NOTE: no PI_PACKAGE_DIR here either — sustained_cpu.py scopes the
- # runtime sidecar to the rust pane itself (same reason as the
- # streaming dim).
- env = dict(os.environ)
- env.pop("PI_PACKAGE_DIR", None)
- env["PA_RUST_BINARY"] = str(Path(self.rust_bin).resolve())
- proc = subprocess.run(
- ["python3", str(script), "--out", str(out_dir)],
- env=env,
- cwd=str(Path(__file__).resolve().parents[2]),
- capture_output=True,
- text=True,
- timeout=2400,
- )
- self.evidence("sustained_cpu", "shared", "sustained_cpu.log", proc.stdout + proc.stderr)
- result: dict[str, dict] = {}
- for side_name in ("ts", "rust"):
- path = out_dir / f"{side_name}-sustained-cpu.json"
- if not path.exists():
- print(f"WARNING: missing {path}", file=sys.stderr)
- continue
- data = json.loads(path.read_text())
-
- def tui_mean(dim):
- return ((data.get(dim) or {}).get("tui") or {}).get("mean_pct")
-
- result[side_name] = {
- "tui_idle_mean_pct": tui_mean("idle"),
- "tui_plain_mean_pct": tui_mean("plain"),
- "tui_code_mean_pct": tui_mean("code"),
- "tui_tool_mean_pct": tui_mean("tool"),
- "typing_ms_median": (data.get("typing_probe") or {}).get("median_ms"),
- "exit_s": (data.get("exit_probe") or {}).get("elapsed_s"),
- "passed": data.get("passed"),
- }
- result["_exit_code"] = proc.returncode
- return result
-
- def dim_streaming(self) -> dict:
- # stream_throughput.py runs both binaries itself (faux engine on
- # rust, the ts faux extension on ts) and settles two unpaced
- # ~12k-token turns per side.
- script = Path(__file__).parent / "stream_throughput.py"
- out_dir = self.run_dir / "streaming"
- out_dir.mkdir(parents=True, exist_ok=True)
- # NOTE: no PI_PACKAGE_DIR here — the TS binary resolves its own
- # package layout from that env and a non-release tree crashes it;
- # stream_throughput.py scopes PI_PACKAGE_DIR to the rust pane and
- # finds the runtime sidecar itself.
- env = dict(os.environ)
- env["PA_RUST_BINARY"] = str(Path(self.rust_bin).resolve())
- proc = subprocess.run(
- ["python3", str(script), "--out", str(out_dir)],
- env=env,
- cwd=str(Path(__file__).resolve().parents[2]),
- capture_output=True,
- text=True,
- timeout=1200,
- )
- self.evidence("streaming", "shared", "stream_throughput.log", proc.stdout + proc.stderr)
- result: dict[str, dict] = {}
- # ~12k tokens per turn (chars/4 estimate, the streaming harness's
- # own metric): SEGMENTS * SEGMENT_WORDS words plus segment markers.
- sys.path.insert(0, str(Path(__file__).parent))
- import stream_throughput # noqa: E402
-
- tokens_per_turn = len(stream_throughput.filler_text()) // 4
- for side_name in ("ts", "rust"):
- path = out_dir / f"{side_name}-throughput.json"
- if not path.exists():
- print(f"WARNING: missing {path}", file=sys.stderr)
- continue
- data = json.loads(path.read_text())
- settles = [turn["settle_seconds"] for turn in data.get("turns", [])]
- self.evidence("streaming", side_name, "throughput.json", data)
- result[side_name] = {
- "settle_s_median": self.median(settles),
- "tokens_per_s_est": round(tokens_per_turn / self.median(settles), 0)
- if settles
- else None,
- "turns": settles,
- }
- result["_exit_code"] = proc.returncode
- return result
-
- # -- dimension: compaction on a large session ---------------------------------
- #
- # PARITY NOTE (found by this wave, 2026-09-21; fixed by the
- # import-compaction lane, see crates/pa-daemon/tests/
- # import_compaction_e2e.rs): growing the session by `import_jsonl`
- # used to make the TS daemon compact it while the Rust daemon answered
- # "Session is too short to compact". Root cause: the Rust session-file
- # parse degraded whole message rows to Unknown on fields the TS loader
- # tolerates (the raw provider stopReason "tool_calls", a missing
- # toolName), so the compaction walk under-counted and found no cut with
- # history. The wire parse now keeps those rows (pa-types), and the e2e
- # locks the whole flow. The benchmark still grows both sides
- # identically through `prompt_and_wait` turns (the f7 battery pattern),
- # so the measured pipeline is comparable.
-
- COMPACT_GROW_TURNS = 40
- # ~3k tokens of deterministic text per turn -> ~120k tokens of history,
- # well past the 20k keep-recent budget so the cut has history to
- # summarize on both sides.
- COMPACT_TURN_TEXT = "Compaction bench turn payload. " * 1050
-
- def dim_compaction(self) -> dict:
- out: dict[str, dict] = {}
- for side_name in ("ts", "rust"):
- side = self.sides[side_name]
- self.ensure_fresh_daemon(side)
- durations = []
- for trial in range(max(3, self.trials)):
- wire = B.Wire(side.daemon_socket)
- create = wire.request(
- f"cc{trial}",
- {
- "type": "create",
- "name": f"wave-compact-{trial}",
- "config": self.session_config(side),
- },
- timeout=120,
- )
- if create.get("success") is not True:
- print(f"WARNING: {side_name} create failed: {create}", file=sys.stderr)
- wire.close()
- break
- session_id = create["data"].get("activeSessionId") or create["data"].get("id")
- # Grow: every turn replies with the same deterministic big
- # text (the mock round-robins the last scripted response
- # once the queue runs dry).
- side.mock.set_responses([{"text": self.COMPACT_TURN_TEXT}])
- for turn in range(self.COMPACT_GROW_TURNS):
- grown = wire.request(
- f"gp{trial}-{turn}",
- {
- "type": "prompt_and_wait",
- "activeSessionId": session_id,
- "message": f"compaction bench seed turn {turn}",
- },
- timeout=300,
- )
- if grown.get("success") is not True:
- print(
- f"WARNING: {side_name} grow turn {turn} failed: {grown}",
- file=sys.stderr,
- )
- break
- # Compact: the mock serves the summarizer reply.
- side.mock.set_responses([{"text": f"compaction summary {trial}"}])
- t0 = time.time()
- compact = wire.request(
- f"kc{trial}",
- {"type": "compact", "activeSessionId": session_id},
- timeout=600,
- )
- duration = round(time.time() - t0, 3)
- self.evidence("compaction", side_name, f"compact-{trial}.json", compact)
- wire.send_command(
- f"sp{trial}",
- {"type": "kill", "activeSessionId": session_id},
- )
- wire.close()
- if compact.get("success") is not True:
- print(f"WARNING: {side_name} compact failed: {compact}", file=sys.stderr)
- continue
- durations.append(duration)
- self.evidence(
- "compaction",
- side_name,
- f"grown-{trial}.json",
- {"turns": self.COMPACT_GROW_TURNS},
- )
- side.stop_daemon()
- out[side_name] = {
- "compact_s_median": self.median(durations),
- "grown_turns": self.COMPACT_GROW_TURNS,
- "trials": durations,
- }
- return out
-
- # -- dimension: HTML export ----------------------------------------------------
-
- def dim_export(self) -> dict:
- corpus = self.corpus_path()
- out: dict[str, dict] = {}
- for side_name in ("ts", "rust"):
- side = self.sides[side_name]
- durations = []
- sizes = []
- for trial in range(max(3, self.trials)):
- output = side.root / "export" / f"export-{trial}.html"
- output.parent.mkdir(parents=True, exist_ok=True)
- t0 = time.time()
- result = B.run_cmd(
- [side.binary, "session", "export", str(corpus), str(output)],
- env=side.env,
- cwd=side.work_dir,
- timeout=300,
- )
- duration = round(time.time() - t0, 3)
- if result["exit_code"] != 0 or not output.exists():
- print(
- f"WARNING: {side_name} export failed: {result['exit_code']} "
- f"{result['stderr'][-300:]}",
- file=sys.stderr,
- )
- self.evidence("export", side_name, f"run-{trial}.json", result)
- continue
- durations.append(duration)
- sizes.append(output.stat().st_size)
- output.unlink()
- out[side_name] = {
- "export_s_median": self.median(durations),
- "html_bytes_median": int(self.median([float(s) for s in sizes]))
- if sizes
- else None,
- "trials": durations,
- }
- return out
-
- # -- dimension: daemon per-session overhead -------------------------------------
-
- def dim_daemon_overhead(self) -> dict:
- out: dict[str, dict] = {}
- for side_name in ("ts", "rust"):
- side = self.sides[side_name]
- deltas = []
- per_session = []
- for trial in range(2):
- if side.daemon_socket.exists():
- side.daemon_socket.unlink()
- side.start_daemon()
- time.sleep(3.0)
- baseline = self.rss_sample(side, quiet_s=1.0)
- wire = B.Wire(side.daemon_socket)
- created = 0
- for i in range(10):
- create = wire.request(
- f"dc{trial}-{i}",
- {
- "type": "create",
- "name": f"wave-overhead-{trial}-{i}",
- "config": self.session_config(side),
- },
- timeout=120,
- )
- if create.get("success") is not True:
- print(
- f"WARNING: {side_name} overhead create {i} failed: {create}",
- file=sys.stderr,
- )
- break
- created += 1
- wire.close()
- time.sleep(3.0)
- loaded = self.rss_sample(side, quiet_s=1.0)
- self.evidence(
- "daemon_overhead",
- side_name,
- f"trial-{trial}.json",
- {"created": created, "baseline_kb": baseline["total_kb"], "loaded": loaded},
- )
- if created == 10:
- delta = loaded["total_kb"] - baseline["total_kb"]
- deltas.append(delta)
- per_session.append(delta / 10.0)
- side.stop_daemon()
- out[side_name] = {
- "delta_kb_median": int(self.median([float(d) for d in deltas]))
- if deltas
- else None,
- "per_session_kb_median": int(self.median([float(d) for d in per_session]))
- if per_session
- else None,
- "trials": deltas,
- }
- return out
-
- # -- config -------------------------------------------------------------------
-
- def ensure_fresh_daemon(self, side: B.Side) -> None:
- """Start a daemon on the side socket, first reaping anything that
- still holds it (a failed dimension can leave a live daemon; the TS
- daemon start aborts with ELOCKED while the old one lives)."""
- B.reap_daemons(
- socket_paths=[side.daemon_socket],
- needles=[str(side.daemon_socket), str(self.tmpdirs[side.name])],
- )
- if side.daemon_socket.exists():
- side.daemon_socket.unlink()
- side.start_daemon()
-
- def session_config(self, side: B.Side) -> dict:
- return {
- "cwd": str(side.work_dir),
- "sessionDir": str(side.agent_dir / "sessions"),
- "provider": "prime-inference",
- "model": "mock-1",
- "executionMode": "print",
- }
-
- # -- driver ---------------------------------------------------------------------
-
- def run(self) -> int:
- results: dict[str, dict] = {}
- for name in ("ts", "rust"):
- self.make_side(name, self.ts_bin if name == "ts" else self.rust_bin)
- # Settle first-run dialogs once per side before any measurement.
- for side_name in ("ts", "rust"):
- self.onboard(self.sides[side_name])
- for dim in self.dims:
- print(f"== dimension: {dim}", flush=True)
- started = time.time()
- try:
- results[dim] = getattr(self, f"dim_{dim}")()
- except Exception as exc: # keep later dimensions running
- import traceback
-
- traceback.print_exc()
- results[dim] = {"error": str(exc)}
- # A half-torn dimension can leave its daemon tree alive;
- # reap both sides so the next dimension starts clean.
- for side in self.sides.values():
- side.stop_daemon()
- print(
- f"== {dim} done in {time.time() - started:.1f}s: "
- + json.dumps(results[dim], default=str)[:400],
- flush=True,
- )
- (self.run_dir / "results.partial.json").write_text(
- json.dumps(results, indent=1, default=str)
- )
- self.teardown_sides()
- payload = {
- "run": self.stamp,
- "ts_bin": self.ts_bin,
- "rust_bin": self.rust_bin,
- "trials": self.trials,
- "corpus_rows": CORPUS_ROWS,
- "results": results,
- }
- (self.run_dir / "results.json").write_text(json.dumps(payload, indent=1, default=str))
- print(json.dumps(payload, indent=1, default=str))
- return 0
-
-
-def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- here = Path(__file__).resolve().parent
- repo = here.parent.parent
- parser.add_argument("--dims", default=",".join(ALL_DIMS))
- parser.add_argument("--trials", type=int, default=5)
- parser.add_argument("--runs-root", default=str(here / "runs"))
- parser.add_argument("--run-name", default=None)
- parser.add_argument("--ts-bin", default="prime-agent")
- parser.add_argument("--rust-bin", default=str(repo / "target" / "release" / "prime-agent"))
- args = parser.parse_args()
- dims = [d.strip() for d in args.dims.split(",") if d.strip()]
- for dim in dims:
- if dim not in ALL_DIMS:
- parser.error(f"unknown dim {dim}; valid: {ALL_DIMS}")
- # Fail fast: the ts side must be the deployed TS product.
- ts_identity.assert_ts_side_is_the_ts_product(args.ts_bin, args.rust_bin)
- stale = B.rust_binary_staleness(Path(args.rust_bin), repo)
- if stale:
- print(f"STALE RUST BINARY: {stale}", file=sys.stderr)
- return 2
- stamp = args.run_name or (
- "perf-wave-"
- + datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- )
- run_dir = Path(args.runs_root) / stamp
- run_dir.mkdir(parents=True, exist_ok=True)
- wave = PerfWave(run_dir, args.ts_bin, args.rust_bin, dims, args.trials)
- return wave.run()
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/scripts/battery/run_perf_wave.sh b/scripts/battery/run_perf_wave.sh
deleted file mode 100755
index 2551d58621..0000000000
--- a/scripts/battery/run_perf_wave.sh
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/env bash
-# Local runner for the perf wave: run it exactly the way the CI workflow
-# does (see .github/workflows/benchmark.yml), on this machine.
-#
-# scripts/battery/run_perf_wave.sh [extra perf_wave.py args]
-#
-# Environment:
-# PA_WAVE_SKIP_BUILD=1 do not rebuild the rust release binary
-# PA_WAVE_TRIALS=N trial count (default 5)
-# PA_WAVE_DIMS=... comma list (default all)
-# PA_WAVE_RUST_BIN=... rust binary (default target/release/prime-agent)
-# PA_WAVE_TS_BIN=... ts binary (default prime-agent on PATH)
-#
-# Timings are only comparable when both sides run on the same quiet machine:
-# the intended host for this script is a fresh Prime sandbox (the CI entry
-# scripts/battery/ci_perf_wave.sh drives exactly that), but it also runs
-# locally for smoke checks.
-set -euo pipefail
-cd "$(dirname "$0")/../.."
-
-TRIALS="${PA_WAVE_TRIALS:-5}"
-DIMS="${PA_WAVE_DIMS:-all}"
-RUST_BIN="${PA_WAVE_RUST_BIN:-target/release/prime-agent}"
-TS_BIN="${PA_WAVE_TS_BIN:-prime-agent}"
-
-if [ -z "${PA_WAVE_SKIP_BUILD:-}" ]; then
- echo "== building rust release binary" >&2
- cargo build --release -p pa-cli
-fi
-
-if [ "$DIMS" = "all" ]; then
- DIMS_ARG=""
-else
- DIMS_ARG="--dims $DIMS"
-fi
-
-echo "== running the perf wave (trials=$TRIALS)" >&2
-python3 scripts/battery/perf_wave.py \
- --trials "$TRIALS" $DIMS_ARG \
- --ts-bin "$TS_BIN" --rust-bin "$RUST_BIN" \
- "$@"
-
-RUN_DIR=$(ls -1dt scripts/battery/runs/perf-wave-* | head -1)
-echo "== gating against scripts/battery/perf-baseline.json" >&2
-python3 scripts/battery/perf_gate.py --results "$RUN_DIR/results.json"
-echo "== results: $RUN_DIR"
diff --git a/scripts/battery/scale_corpus.py b/scripts/battery/scale_corpus.py
deleted file mode 100644
index 670f0fd694..0000000000
--- a/scripts/battery/scale_corpus.py
+++ /dev/null
@@ -1,183 +0,0 @@
-#!/usr/bin/env python3
-"""Deterministic heavy-scale corpus for the interactive-resume gate.
-
-One session file per turn count: a turn is a user message, an assistant
-message carrying one `ipython` tool call (the code-preview path), and the
-`toolResult` — three message rows per turn. `custom_message` rows (the
-harness-digest shape) add eleven base rows plus one row per twenty turns,
-so the row counts match the heavy-scale benchmark corpus:
-5000 turns -> 15,261 transcript rows.
-
-Not part of the product.
-"""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-
-T0 = 1789584016603
-
-
-def _ts(index: int) -> str:
- return "2026-09-16T18:40:%02d.%03dZ" % (index % 60, index % 1000)
-
-
-def _ipython_code(turn: int) -> str:
- return (
- "import subprocess\n"
- f"result = subprocess.run(['echo', 'corpus {turn}'], capture_output=True, text=True)\n"
- "print(result.stdout.strip())\n"
- "files = [f for f in range(3)]\n"
- "print(sorted(files))\n"
- )
-
-
-def _usage(extra: int = 0) -> dict:
- return {
- "input": 100 + extra,
- "output": 20 + extra,
- "cacheRead": 10,
- "cacheWrite": 0,
- "totalTokens": 130 + extra,
- "cost": {"input": 0.1, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.12},
- }
-
-
-def generate(turns: int, cwd: str) -> list[dict]:
- """The corpus entries for `turns` turns (session header included)."""
- lines: list[dict] = [
- {
- "type": "session",
- "id": "scale-corpus",
- "version": 3,
- "timestamp": "2026-09-16T18:40:16.600Z",
- "cwd": cwd,
- "rlmDepth": 0,
- }
- ]
- parent = None
-
- def entry(entry_type: str, fields: dict, entry_id: str, index: int) -> dict:
- record = dict(fields)
- record["type"] = entry_type
- record["id"] = entry_id
- record["parentId"] = parent
- record["timestamp"] = _ts(index)
- return record
-
- counter = 0
-
- def next_id() -> str:
- nonlocal counter
- counter += 1
- return f"{counter:08x}"[:8]
-
- for base in range(11):
- record = entry(
- "custom_message",
- {
- "customType": "harness_digest",
- "content": (
- f"[harness-digest] base note {base}: persistent state summary for the scale corpus."
- ),
- },
- next_id(),
- counter,
- )
- lines.append(record)
- parent = record["id"]
-
- for turn in range(turns):
- record = entry(
- "message",
- {
- "message": {
- "role": "user",
- "content": [{"type": "text", "text": f"please do task number {turn}"}],
- "timestamp": T0 + turn,
- }
- },
- next_id(),
- counter,
- )
- lines.append(record)
- parent = record["id"]
-
- record = entry(
- "message",
- {
- "message": {
- "role": "assistant",
- "content": [
- {"type": "thinking", "thinking": f"task {turn}: run the corpus command"},
- {"type": "text", "text": f"Running the tool for task {turn}."},
- ],
- "toolCalls": [
- {
- "id": f"call_{turn:06d}",
- "name": "ipython",
- "arguments": {"code": _ipython_code(turn)},
- }
- ],
- "api": "openai-completions",
- "provider": "prime-inference",
- "model": "mock-1",
- "usage": _usage(),
- "stopReason": "tool_calls",
- "timestamp": T0 + turn,
- }
- },
- next_id(),
- counter,
- )
- lines.append(record)
- parent = record["id"]
-
- record = entry(
- "message",
- {
- "message": {
- "role": "toolResult",
- "toolCallId": f"call_{turn:06d}",
- "content": [{"type": "text", "text": f"corpus {turn}\n[0, 1, 2]\n"}],
- "isError": False,
- "timestamp": T0 + turn,
- }
- },
- next_id(),
- counter,
- )
- lines.append(record)
- parent = record["id"]
-
- if (turn + 1) % 20 == 0:
- record = entry(
- "custom_message",
- {
- "customType": "harness_digest",
- "content": (
- f"[harness-digest] note {turn}: persistent state summary for the scale corpus."
- ),
- },
- next_id(),
- counter,
- )
- lines.append(record)
- parent = record["id"]
-
- return lines
-
-
-def corpus_rows(turns: int) -> int:
- """Transcript rows the corpus yields (messages + custom rows)."""
- return 3 * turns + 11 + turns // 20
-
-
-def corpus_path(turns: int, run_dir: Path, cwd: str) -> Path:
- """Write (or reuse) the deterministic corpus for `turns` under `run_dir`."""
- path = run_dir / f"scale-corpus-{turns}.jsonl"
- if not path.exists():
- entries = generate(turns, cwd)
- path.write_text("\n".join(json.dumps(entry) for entry in entries) + "\n")
- return path
diff --git a/scripts/battery/stream_throughput.py b/scripts/battery/stream_throughput.py
deleted file mode 100755
index 6887ed1846..0000000000
--- a/scripts/battery/stream_throughput.py
+++ /dev/null
@@ -1,258 +0,0 @@
-#!/usr/bin/env python3
-"""Big-turn streaming-throughput verifier (lane: stream-rate).
-
-Drives the interactive TUI through an UNPACED faux provider inside tmux and
-measures how long each ~12k-token streamed turn takes to fully render, for
-BOTH binaries (the TS product is the ground truth). The acceptance
-contract: the Rust binary's per-turn render settle time stays within
-SETTLE_RATIO of the TS binary's on the same corpus. The regression this
-pins: a wire that broadcasts one frame per provider delta starves the
-client at the flusher tick rate, so a turn the engine finishes in seconds
-rendered for minutes (the compact-finish e2e diagnosis).
-
-tmux rules: default socket only (`env -u TMUX`), vplane-* session names, no
-kill-server; sessions are killed individually at the end.
-"""
-
-import argparse
-import json
-import os
-import re
-import shutil
-import subprocess
-import sys
-import tempfile
-import time
-
-import ts_identity # the shared PATH-binary identity guard (same dir)
-
-SESSION_NAME = "vplane-thru"
-SIZE = ("120", "40")
-
-# ~12k tokens per turn (chars/4 estimate), unpaced: the faux provider
-# streams ~3000 full-partial deltas as fast as it can. MARK-nn segments let
-# the pane sampler see progressive content; the tail word marks the settle.
-SEGMENTS = 24
-SEGMENT_WORDS = 250
-TAIL_ONE = "turn-one-settled"
-TAIL_TWO = "turn-two-settled"
-
-SPINNERS = "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f"
-PULSES = "\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc"
-SPINNER_CLASS = "[" + SPINNERS + PULSES + "]"
-
-# The acceptance contract: the Rust settle stays within SETTLE_RATIO of the
-# TS settle OR under SETTLE_CAP seconds, whichever is looser. TS renders an
-# unpaced faux turn in a fraction of a second on a fast machine, so a strict
-# ratio would pin constant-factor renderer differences, not the regression
-# this harness exists for (the starvation pipeline rendered one 12k-token
-# turn for 60+ seconds); the cap keeps that regression out.
-SETTLE_RATIO = 2.0
-SETTLE_CAP = 5.0
-SETTLE_TIMEOUT = 600.0
-
-
-def filler_text():
- parts = []
- for segment in range(SEGMENTS):
- parts.append(f"MARK-{segment:02d}")
- parts.append(" ".join(f"word{index}" for index in range(SEGMENT_WORDS)))
- return " ".join(parts)
-
-
-FAUX_SCRIPT = {
- "engine": "faux",
- "modelId": "faux-1",
- "modelName": "Faux Model",
- "reasoning": False,
- "contextWindow": 128000,
- "responses": [
- {"text": f"{filler_text()} {TAIL_ONE}"},
- {"text": f"{filler_text()} {TAIL_TWO}"},
- ],
-}
-
-PROMPT_ONE = "Write the first big answer."
-PROMPT_TWO = "Write the second big answer."
-
-
-def tmux(*args, check=True):
- result = subprocess.run(
- ["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True
- )
- if check and result.returncode != 0:
- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")
- return result.stdout
-
-
-def capture(session):
- return tmux("capture-pane", "-p", "-t", session)
-
-
-def find_runtime_package_dir():
- releases = os.path.expanduser("~/.local/share/prime-agent/releases")
- candidates = [
- entry
- for entry in sorted(os.listdir(releases))
- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))
- ]
- if not candidates:
- raise SystemExit("cannot find the prime-agent-runtime sidecar; set PI_PACKAGE_DIR")
- return os.path.join(releases, candidates[-1])
-
-
-TS_FAUX_EXTENSION = open(
- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "ts_faux_extension.js"),
- encoding="utf-8",
-).read()
-
-
-def wait_for(session, needle, timeout):
- deadline = time.time() + timeout
- while time.time() < deadline:
- if needle in capture(session):
- return True
- time.sleep(0.3)
- return False
-
-
-def run_turn(session, prompt, tail_word, out_dir, binary):
- """Submit `prompt` and time how long the turn takes to fully render."""
- tmux("send-keys", "-t", session, prompt)
- tmux("send-keys", "-t", session, "Enter")
- started = time.time()
- marks = set()
- deadline = time.time() + SETTLE_TIMEOUT
- while time.time() < deadline:
- pane = capture(session)
- marks.update(word for word in re.findall(r"MARK-\d\d", pane))
- settled = tail_word in pane and not re.search(SPINNER_CLASS, pane)
- if settled:
- elapsed = time.time() - started
- print(
- f"{binary}: turn with tail {tail_word!r} rendered in "
- f"{elapsed:.2f}s ({len(marks)} segment markers seen mid-turn)"
- )
- return elapsed, len(marks)
- time.sleep(0.2)
- raise AssertionError(
- f"{binary}: the turn with tail {tail_word!r} never settled within "
- f"{SETTLE_TIMEOUT}s; last pane:" "\n{capture(session)}"
- )
-
-
-def run_session(binary, sandbox, shared_cwd, script_path, out_dir):
- width, height = SIZE
- session = f"{SESSION_NAME}-{binary}"
- tmux("kill-session", "-t", session, check=False)
- tmux("new-session", "-d", "-s", session, "-x", width, "-y", height, "-c", shared_cwd)
- env = (
- f"HOME={sandbox['home']} "
- f"PRIME_AGENT_CODING_AGENT_DIR={sandbox['agent']} "
- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "
- "PRIME_AGENT_DISABLE_ANALYTICS=1"
- )
- if binary == "ts":
- command = (
- f"prime-agent --daemon-socket {sandbox['agent']}/daemon.sock "
- "--model faux-1"
- )
- else:
- rust = os.environ.get("PA_RUST_BINARY") or os.path.join(
- os.path.dirname(os.path.abspath(__file__)),
- "..",
- "..",
- "target",
- "release",
- "prime-agent",
- )
- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()
- command = (
- f"PI_PACKAGE_DIR={package_dir} "
- f"{rust} --daemon-socket {sandbox['agent']}/daemon.sock "
- "--model faux-1"
- )
- tmux("send-keys", "-t", session, f"{env} {command}", "Enter")
- if not wait_for(session, "Collapsed mode", timeout=120):
- raise AssertionError(f"{binary}: the editor never came up")
-
- turns = []
- for prompt, tail in ((PROMPT_ONE, TAIL_ONE), (PROMPT_TWO, TAIL_TWO)):
- elapsed, marks = run_turn(session, prompt, tail, out_dir, binary)
- turns.append({"prompt": prompt, "settle_seconds": round(elapsed, 2), "marks_seen": marks})
- tmux("kill-session", "-t", session, check=False)
-
- evidence_path = os.path.join(out_dir, f"{binary}-throughput.json")
- os.makedirs(out_dir, exist_ok=True)
- with open(evidence_path, "w") as f:
- json.dump({"turns": turns}, f, indent=1)
- return turns
-
-
-def main():
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")
- parser.add_argument("--out", default=None, help="captures directory")
- parser.add_argument("--only", default=None, help="run a single binary (ts|rust)")
- args = parser.parse_args()
-
- # Fail fast before any launch: a non-TS `prime-agent` on PATH plays a
- # Rust build as the "ts" side and reports false divergences.
- if args.only in (None, "ts"):
- ts_identity.assert_ts_side_is_the_ts_product()
-
- base = tempfile.mkdtemp(prefix="stream-throughput-sandbox-")
- out_dir = args.out or tempfile.mkdtemp(prefix="stream-throughput-captures-")
- shared_cwd = os.path.join(base, "shared-cwd")
- os.makedirs(shared_cwd, exist_ok=True)
- script_path = os.path.join(base, "faux-script.json")
- with open(script_path, "w") as f:
- json.dump(FAUX_SCRIPT, f, indent=2)
- sandboxes = {}
- for binary in ("ts", "rust"):
- home = os.path.join(base, binary, "home")
- agent = os.path.join(base, binary, "agent")
- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)
- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)
- with open(os.path.join(agent, "settings.json"), "w") as f:
- json.dump({"onboardingCompleted": True}, f)
- sandboxes[binary] = {"home": home, "agent": agent}
- with open(os.path.join(sandboxes["ts"]["agent"], "extensions", "stream-faux.js"), "w") as f:
- f.write(TS_FAUX_EXTENSION)
-
- try:
- if args.only:
- run_session(args.only, sandboxes[args.only], shared_cwd, script_path, out_dir)
- print(f"{args.only}: throughput run finished; captures in {out_dir}")
- return 0
- ts_turns = run_session("ts", sandboxes["ts"], shared_cwd, script_path, out_dir)
- rust_turns = run_session("rust", sandboxes["rust"], shared_cwd, script_path, out_dir)
- failures = []
- for index, (ts_turn, rust_turn) in enumerate(zip(ts_turns, rust_turns)):
- ts_seconds = ts_turn["settle_seconds"]
- rust_seconds = rust_turn["settle_seconds"]
- bound = max(ts_seconds * SETTLE_RATIO, SETTLE_CAP)
- if rust_seconds > bound:
- failures.append(
- f"turn {index + 1}: rust rendered in {rust_seconds}s, "
- f"ts in {ts_seconds}s (bound {bound:.1f}s = "
- f"max({SETTLE_RATIO}x ts, {SETTLE_CAP}s cap))"
- )
- if failures:
- print("FAIL " + "; ".join(failures))
- return 1
- print(
- "PASS rust kept up: "
- + ", ".join(
- f"turn {index + 1}: ts {ts['settle_seconds']}s vs rust {rust['settle_seconds']}s"
- for index, (ts, rust) in enumerate(zip(ts_turns, rust_turns))
- )
- )
- return 0
- finally:
- if not args.keep:
- shutil.rmtree(base, ignore_errors=True)
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/scripts/battery/sustained_cpu.py b/scripts/battery/sustained_cpu.py
deleted file mode 100644
index 2fccca7a03..0000000000
--- a/scripts/battery/sustained_cpu.py
+++ /dev/null
@@ -1,573 +0,0 @@
-#!/usr/bin/env python3
-"""Sustained-CPU regression guard (lane: cpu-spin, dogfood P0).
-
-The dogfood report: 91-99.8% sustained CPU on the interactive TUI, typing
-lag while streaming, and a trapped-scroll state no key escapes. The
-render-loop fixes (frame-batch scheduler, per-block markdown cache,
-timer-driven spinner) must keep the interactive process inside its CPU
-budgets. This harness drives the same unpaced/paced faux-provider
-streaming a real dogfood turn produces, samples %CPU per process from
-/proc, and ASSERTS the budgets:
-
- idle 30s window after ready, %CPU of the interactive process
- plain_stream a paced plain-text streaming turn
- code_stream a paced markdown/code-fence streaming turn (the dogfood
- hot payload: code blocks + ipython tool blocks)
- tool_exec a long-running tool-execution turn (bash sleep)
-
-Plus the no-escape invariant probe: mid-stream, with the viewport
-scrolled up and the detail toggled (the bug #6 repro sequence), the exit
-keys must still land — keystroke-to-render during streaming is measured,
-and a double Ctrl+C mid-scroll must terminate the process.
-
-Run for one or both binaries (the TS product is the ground truth):
-
- python3 scripts/battery/sustained_cpu.py --rust-bin target/release/prime-agent \
- [--only rust|ts] [--out DIR]
-
-Not part of the product.
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import os
-import re
-import shutil
-import subprocess
-import sys
-import tempfile
-import threading
-import time
-from pathlib import Path
-
-sys.path.insert(0, str(Path(__file__).parent))
-import ts_identity # noqa: E402 the shared PATH-binary identity guard
-
-# tmux rules: default socket only (`env -u TMUX`), vplane-free session
-# names, no kill-server; sessions are killed individually at the end.
-SESSION_PREFIX = "cpu-guard"
-SIZE = ("160", "48")
-
-CLK_TCK = os.sysconf("SC_CLK_TCK")
-
-# The budgets the fix is accountable for (percent of one core):
-# idle <5%, streaming <30% (lane targets, with the assert margin at the
-# target itself: a release build over budget fails the guard).
-IDLE_BUDGET_PCT = 5.0
-STREAM_BUDGET_PCT = 30.0
-TOOL_BUDGET_PCT = 30.0
-# Keystroke-to-render while a stream renders (lane target <50ms).
-TYPING_BUDGET_MS = 50.0
-# The exit path: a double Ctrl+C mid-scroll must terminate the process
-# within this bound (the trapped-scroll bug #6 symptom was "no key
-# escapes, killed the process").
-EXIT_BOUND_S = 10.0
-# The idle window the guard samples (the lane brief's 30s).
-IDLE_WINDOW_S = 30.0
-
-# The paced stream: ~200 tokens/s keeps a turn rendering for ~25s per
-# side (the sampling window), fast enough to expose a per-delta
-# full-render loop (the unpaced burst case is the stream_throughput.py
-# settle dim).
-TOKENS_PER_SECOND = 200
-PLAIN_WORDS = 1600 # ~5.2k tokens -> ~26s of streaming at the pace above
-CODE_BLOCKS = 60
-CODE_LINES_PER_BLOCK = 8
-PLAIN_TAIL = "plain-turn-settled"
-CODE_TAIL = "code-turn-settled"
-TOOL_MARKER = "cpu-guard-tool-done"
-TOOL_SLEEP_S = 8
-
-SPINNERS = "\u280b\u2819\u2839\u2838\u283c\u2834\u2826\u2827\u2807\u280f"
-PULSES = "\u25f4\u25f7\u25f6\u25f5\u25cb\u25f8\u25fb\u25fc"
-SPINNER_CLASS = "[" + SPINNERS + PULSES + "]"
-
-
-def tmux(*args, check=True):
- result = subprocess.run(
- ["env", "-u", "TMUX", "tmux", *args], capture_output=True, text=True
- )
- if check and result.returncode != 0:
- raise RuntimeError(f"tmux {' '.join(args)} failed: {result.stderr}")
- return result.stdout
-
-
-def capture(session):
- return tmux("capture-pane", "-p", "-t", session)
-
-
-def find_runtime_package_dir():
- releases = os.path.expanduser("~/.local/share/prime-agent/releases")
- candidates = [
- entry
- for entry in sorted(os.listdir(releases))
- if os.path.isdir(os.path.join(releases, entry, "prime-agent-runtime"))
- ]
- if not candidates:
- raise SystemExit("cannot find the prime-agent-runtime sidecar; set PI_PACKAGE_DIR")
- return os.path.join(releases, candidates[-1])
-
-
-TS_FAUX_EXTENSION = open(
- os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "ts_faux_extension.js"),
- encoding="utf-8",
-).read()
-
-
-def plain_text():
- parts = []
- for segment in range(PLAIN_WORDS // 50):
- parts.append(f"MARK-{segment:02d}")
- parts.append(" ".join(f"word{index}" for index in range(50)))
- return " ".join(parts)
-
-
-def code_text():
- parts = []
- for block in range(CODE_BLOCKS):
- parts.append(f"MARK-{block:02d}")
- parts.append("Paragraph of prose before block %d." % block)
- parts.append("```python")
- for line in range(CODE_LINES_PER_BLOCK):
- parts.append(f" result_{line} = compute_{block}(step={line}) # streaming")
- parts.append("```")
- return "\n".join(parts)
-
-
-def faux_script():
- return {
- "engine": "faux",
- "modelId": "faux-1",
- "modelName": "Faux Model",
- "reasoning": False,
- "contextWindow": 128000,
- "tokensPerSecond": TOKENS_PER_SECOND,
- "responses": [
- {"text": f"{plain_text()} {PLAIN_TAIL}"},
- {"text": f"{code_text()}\n{CODE_TAIL}"},
- {
- "content": [
- {
- # The product's tool is the `ipython` kernel (there is
- # no `bash` tool — a `bash` toolCall errors instantly,
- # so the long-tool window never exercises a tool).
- "type": "toolCall",
- "name": "ipython",
- "arguments": {
- "code": f"import time; time.sleep({TOOL_SLEEP_S}); print('{TOOL_MARKER}')"
- },
- }
- ]
- },
- {"text": "tool turn settled"},
- ],
- }
-
-
-class CpuSampler:
- """%CPU of one pid from /proc: mean over the whole window plus the
- max over 1s sub-windows (the sustained-spin symptom the dogfood
- report names: 99.8% spikes inside an otherwise quiet mean)."""
-
- def __init__(self, pid: int):
- self.pid = pid
- self.running = False
- self.samples: list[tuple[float, float]] = [] # (monotonic_t, cpu_seconds)
- self.thread = None
-
- def _read(self):
- with open(f"/proc/{self.pid}/stat") as f:
- fields = f.read().rsplit(")", 1)[1].split()
- utime, stime = int(fields[11]), int(fields[12])
- return (utime + stime) / CLK_TCK
-
- def start(self):
- self.running = True
- try:
- base = self._read()
- except OSError:
- self.running = False
- return
- self.samples.append((time.monotonic(), base))
-
- def loop():
- while self.running:
- time.sleep(0.2)
- try:
- self.samples.append((time.monotonic(), self._read()))
- except OSError:
- return
-
- self.thread = threading.Thread(target=loop, daemon=True)
- self.thread.start()
-
- def stop(self) -> dict:
- self.running = False
- if self.thread:
- self.thread.join(timeout=2)
- if len(self.samples) < 2:
- return {"mean_pct": None, "max_1s_pct": None, "samples": 0}
- start_t, start_cpu = self.samples[0]
- end_t, end_cpu = self.samples[-1]
- window = end_t - start_t
- mean = (end_cpu - start_cpu) / window * 100 if window > 0 else None
- # Max over 1s rolling sub-windows.
- max_1s = 0.0
- lo = 0
- for hi in range(len(self.samples)):
- while self.samples[hi][0] - self.samples[lo][0] > 1.0:
- lo += 1
- dt = self.samples[hi][0] - self.samples[lo][0]
- if dt > 0:
- max_1s = max(max_1s, (self.samples[hi][1] - self.samples[lo][1]) / dt * 100)
- return {
- "mean_pct": round(mean, 1) if mean is not None else None,
- "max_1s_pct": round(max_1s, 1),
- "samples": len(self.samples),
- "window_s": round(window, 1),
- }
-
-
-def processes_for(socket_path: str) -> dict:
- """The sandbox's interactive and daemon pids: every process whose argv
- references the run's daemon socket; `--mode daemon` classifies the
- daemon, everything else is the interactive TUI."""
- out = {"tui": None, "daemon": None}
- needle = socket_path
- for proc_dir in Path("/proc").iterdir():
- if not proc_dir.name.isdigit():
- continue
- try:
- argv = (proc_dir / "cmdline").read_bytes().decode(errors="replace").split("\0")
- except (OSError, PermissionError):
- continue
- # The socket is one argv element; the role check must compare argv
- # ELEMENTS (`--mode\0daemon` in the raw NUL-joined cmdline never
- # matches a "--mode daemon" substring, which misclassified the
- # daemon as the TUI and left the exit probe watching the daemon
- # forever).
- if needle not in argv:
- continue
- if "--mode" in argv:
- mode_at = argv.index("--mode") + 1
- if mode_at < len(argv) and argv[mode_at] == "daemon":
- out["daemon"] = int(proc_dir.name)
- continue
- out["tui"] = int(proc_dir.name)
- return out
-
-
-def wait_for(session, needle, timeout, poll=0.2):
- deadline = time.time() + timeout
- while time.time() < deadline:
- if needle in capture(session):
- return True
- time.sleep(poll)
- return False
-
-
-def wait_ready(session):
- deadline = time.time() + 60
- while time.time() < deadline:
- frame = capture(session)
- if "Share agent traces" in frame:
- tmux("send-keys", "-t", session, "Down")
- time.sleep(0.3)
- tmux("send-keys", "-t", session, "Enter")
- time.sleep(0.5)
- if re.search(r"^\s*>\s*$", frame, re.MULTILINE):
- return True
- time.sleep(0.3)
- raise AssertionError(f"editor never came up; pane:\n{capture(session)}")
-
-
-def measure_typing_during_stream(session, deadline_total=30.0):
- """Keystroke-to-render while a turn streams: each char must land on the
- prompt line inside TYPING_BUDGET_MS."""
- latencies = []
- typed = ""
- started = time.time()
- for ch in "typing0":
- typed += ch
- t0 = time.time()
- tmux("send-keys", "-t", session, "-l", ch)
- pattern = re.compile(r"^\s*>\s*" + re.escape(typed), re.MULTILINE)
- rendered = False
- deadline = t0 + 2.0
- while time.time() < deadline:
- frame = capture(session)
- if pattern.search(frame):
- rendered = True
- break
- time.sleep(0.005)
- if not rendered:
- latencies.append(round((time.time() - t0) * 1000, 1))
- break
- latencies.append(round((time.time() - t0) * 1000, 1))
- if time.time() - started > deadline_total:
- break
- return latencies
-
-
-def run_turn(session, prompt, settle_tail, out, label, pids):
- """Submit `prompt`, sample CPU until the turn settles, return the
- sample plus the pane settle time."""
- samplers = {name: CpuSampler(pid) for name, pid in pids.items() if pid}
- for sampler in samplers.values():
- sampler.start()
- started = time.time()
- tmux("send-keys", "-t", session, prompt)
- tmux("send-keys", "-t", session, "Enter")
- settled = False
- while time.time() - started < 300:
- pane = capture(session)
- if settle_tail in pane and not re.search(SPINNER_CLASS, pane):
- settled = True
- break
- time.sleep(0.2)
- settle_s = round(time.time() - started, 1)
- result = {name: sampler.stop() for name, sampler in samplers.items()}
- for name, sampler in samplers.items():
- out[f"{label}_{name}_mean_pct"] = result[name]["mean_pct"]
- out[f"{label}_{name}_max_1s_pct"] = result[name]["max_1s_pct"]
- out[f"{label}_settle_s"] = settle_s
- out[f"{label}_settled"] = settled
- return result, settle_s
-
-
-def run_side(side, script_path, sandbox, shared_cwd, out_dir, keep=False):
- session = f"{SESSION_PREFIX}-{side}"
- tmux("kill-session", "-t", session, check=False)
- tmux("new-session", "-d", "-s", session, "-x", SIZE[0], "-y", SIZE[1], "-c", shared_cwd)
- width, height = SIZE
- home = sandbox["home"]
- agent = sandbox["agent"]
- env = (
- f"HOME={home} "
- f"PRIME_AGENT_CODING_AGENT_DIR={agent} "
- f"PRIME_AGENT_FAUX_SCRIPT={script_path} "
- "PRIME_AGENT_DISABLE_ANALYTICS=1"
- )
- if side == "ts":
- command = (
- f"prime-agent --daemon-socket {agent}/daemon.sock "
- "--model faux-1"
- )
- else:
- rust = os.environ.get("PA_RUST_BINARY") or os.path.join(
- os.path.dirname(os.path.abspath(__file__)),
- "..",
- "..",
- "target",
- "release",
- "prime-agent",
- )
- package_dir = os.environ.get("PI_PACKAGE_DIR") or find_runtime_package_dir()
- command = (
- f"PI_PACKAGE_DIR={package_dir} "
- f"{rust} --daemon-socket {agent}/daemon.sock "
- "--model faux-1"
- )
- tmux("send-keys", "-t", session, f"{env} {command}", "Enter")
- wait_ready(session)
-
- socket_path = f"{agent}/daemon.sock"
- record: dict = {"session": session}
-
- # -- idle: 30s window, no turn ------------------------------------------
- time.sleep(2.0) # let the first frames settle
- pids = processes_for(socket_path)
- record["idle_pids"] = pids
- idle_samplers = {name: CpuSampler(pid) for name, pid in pids.items() if pid}
- for sampler in idle_samplers.values():
- sampler.start()
- time.sleep(IDLE_WINDOW_S)
- idle = {name: sampler.stop() for name, sampler in idle_samplers.items()}
- record["idle"] = idle
-
- # -- plain-text streaming turn ------------------------------------------
- pids = processes_for(socket_path)
- plain, plain_s = run_turn(
- session, "Write the plain answer.", PLAIN_TAIL, record, "plain", pids
- )
- record["plain"] = plain
-
- # -- code streaming turn, with the bug-#6 probe inside it ---------------
- pids = processes_for(socket_path)
- typing_probe: dict = {}
- samplers = {name: CpuSampler(pid) for name, pid in pids.items() if pid}
- for sampler in samplers.values():
- sampler.start()
- started = time.time()
- tmux("send-keys", "-t", session, "Write the code answer.")
- tmux("send-keys", "-t", session, "Enter")
- # Wait until the stream is visibly mid-turn, then run the no-escape
- # probe: scroll the viewport up (PageUp burst), toggle the detail
- # twice (Ctrl+O, the bug #6 trigger), type while streaming, then
- # measure keystroke-to-render.
- deadline = time.time() + 60
- mid = False
- while time.time() < deadline:
- pane = capture(session)
- if re.search(r"MARK-\d\d", pane) and re.search(SPINNER_CLASS, pane):
- mid = True
- break
- if CODE_TAIL in pane:
- break
- time.sleep(0.3)
- record["code_probe_mid_stream"] = mid
- if mid:
- # PageUp pause + detail toggles (the trapped-scroll repro sequence).
- tmux("send-keys", "-t", session, "PageUp")
- time.sleep(0.3)
- tmux("send-keys", "-t", session, "C-o")
- time.sleep(0.3)
- tmux("send-keys", "-t", session, "C-o")
- time.sleep(0.3)
- # While paused + expanded mid-stream, the typed chars must still
- # render inside the budget (keys not starved by the render loop).
- typing_probe["latencies_ms"] = measure_typing_during_stream(session)
- lat = typing_probe["latencies_ms"]
- typing_probe["median_ms"] = sorted(lat)[len(lat) // 2] if lat else None
- # The paused viewport must hold still while the stream continues
- # below it (no scroll ping-pong): two captures 2s apart agree on
- # their top transcript rows.
- top_a = "\n".join(capture(session).splitlines()[:10])
- time.sleep(2.0)
- top_b = "\n".join(capture(session).splitlines()[:10])
- typing_probe["viewport_stable"] = top_a == top_b
- # Resume following (TS/Rust `tui.viewport.follow`, ctrl+shift+down):
- # the settle waits and the exit probe below read the visible pane,
- # so the probe leaves the viewport following again — the code turn
- # then settles at its true tail instead of timing out against a
- # paused viewport, and the exit probe runs from the following state
- # (the paused state kept BOTH products alive past the bound).
- tmux("send-keys", "-t", session, "C-S-Down")
- # Let the turn run out and settle.
- while time.time() - started < 300:
- pane = capture(session)
- if CODE_TAIL in pane and not re.search(SPINNER_CLASS, pane):
- break
- time.sleep(0.2)
- record["code_settle_s"] = round(time.time() - started, 1)
- record["code"] = {name: sampler.stop() for name, sampler in samplers.items()}
- record["typing_probe"] = typing_probe
-
- # -- long tool-execution turn -------------------------------------------
- pids = processes_for(socket_path)
- tool, tool_s = run_turn(
- session, "Run the long command.", "tool turn settled", record, "tool", pids
- )
- record["tool"] = tool
-
- # -- exit probe: double Ctrl+C terminates the process -------------------
- exit_started = time.time()
- tmux("send-keys", "-t", session, "C-c")
- time.sleep(1.0)
- tmux("send-keys", "-t", session, "C-c")
- exited = False
- while time.time() - exit_started < EXIT_BOUND_S:
- pids_now = processes_for(socket_path)
- if not pids_now["tui"]:
- exited = True
- break
- time.sleep(0.2)
- record["exit_probe"] = {
- "exited": exited,
- "elapsed_s": round(time.time() - exit_started, 1),
- }
- tmux("kill-session", "-t", session, check=False)
-
- # -- assertions -----------------------------------------------------------
- failures = []
- tui_idle = (record.get("idle") or {}).get("tui") or {}
- if tui_idle.get("mean_pct") is None:
- failures.append("idle: no TUI cpu samples")
- elif tui_idle["mean_pct"] > IDLE_BUDGET_PCT:
- failures.append(f"idle {tui_idle['mean_pct']}% > {IDLE_BUDGET_PCT}%")
- for label in ("plain", "code", "tool"):
- tui = (record.get(label) or {}).get("tui") or {}
- budget = TOOL_BUDGET_PCT if label == "tool" else STREAM_BUDGET_PCT
- if tui.get("mean_pct") is None:
- failures.append(f"{label}: no TUI cpu samples")
- elif tui["mean_pct"] > budget:
- failures.append(f"{label} {tui['mean_pct']}% > {budget}%")
- median = (record.get("typing_probe") or {}).get("median_ms")
- if median is not None and median > TYPING_BUDGET_MS:
- failures.append(f"typing mid-stream median {median}ms > {TYPING_BUDGET_MS}ms")
- if not ((record.get("typing_probe") or {}).get("viewport_stable", False)):
- failures.append("viewport not stable while paused mid-stream (scroll ping-pong)")
- if not record.get("exit_probe", {}).get("exited"):
- failures.append(f"double Ctrl+C did not exit within {EXIT_BOUND_S}s")
- if not record.get("plain", {}).get("tui"):
- pass
- if not record.get("plain_settled"):
- failures.append("plain turn never settled")
- if not record.get("code_probe_mid_stream"):
- failures.append("code turn never reached mid-stream (probe window missed)")
- record["failures"] = failures
- record["passed"] = not failures
-
- out_path = Path(out_dir) / f"{side}-sustained-cpu.json"
- out_path.parent.mkdir(parents=True, exist_ok=True)
- out_path.write_text(json.dumps(record, indent=1))
- print(f"{side}: {'PASS' if record['passed'] else 'FAIL'}")
- print(
- f" idle {tui_idle.get('mean_pct')}% (max1s {tui_idle.get('max_1s_pct')}%), "
- f"plain {((record.get('plain') or {}).get('tui') or {}).get('mean_pct')}%, "
- f"code {((record.get('code') or {}).get('tui') or {}).get('mean_pct')}%, "
- f"tool {((record.get('tool') or {}).get('tui') or {}).get('mean_pct')}% "
- f"(tui process, mean over window)"
- )
- print(f" typing mid-stream median {median}ms, exit {record['exit_probe']['elapsed_s']}s")
- for failure in failures:
- print(f" FAIL {failure}")
- return record
-
-
-def main():
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--only", default=None, help="run a single binary (ts|rust)")
- parser.add_argument("--out", default=None, help="captures directory")
- parser.add_argument("--keep", action="store_true", help="keep the sandbox dir")
- args = parser.parse_args()
-
- if args.only in (None, "ts"):
- ts_identity.assert_ts_side_is_the_ts_product()
-
- base = tempfile.mkdtemp(prefix="sustained-cpu-sandbox-")
- out_dir = args.out or tempfile.mkdtemp(prefix="sustained-cpu-captures-")
- shared_cwd = os.path.join(base, "shared-cwd")
- os.makedirs(shared_cwd, exist_ok=True)
- script_path = os.path.join(base, "faux-script.json")
- with open(script_path, "w") as f:
- json.dump(faux_script(), f, indent=2)
- sandboxes = {}
- for binary in ("ts", "rust"):
- home = os.path.join(base, binary, "home")
- agent = os.path.join(base, binary, "agent")
- os.makedirs(os.path.join(agent, "extensions"), exist_ok=True)
- os.makedirs(os.path.join(agent, "sessions"), exist_ok=True)
- with open(os.path.join(agent, "settings.json"), "w") as f:
- json.dump({"onboardingCompleted": True}, f)
- sandboxes[binary] = {"home": home, "agent": agent}
- with open(os.path.join(sandboxes["ts"]["agent"], "extensions", "stream-faux.js"), "w") as f:
- f.write(TS_FAUX_EXTENSION)
-
- overall = 0
- try:
- sides = [args.only] if args.only else ["ts", "rust"]
- for side in sides:
- record = run_side(side, script_path, sandboxes[side], shared_cwd, out_dir, args.keep)
- if side == "rust" and not record["passed"]:
- overall = 1
- return overall
- finally:
- if not args.keep:
- shutil.rmtree(base, ignore_errors=True)
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/scripts/battery/ts_identity.py b/scripts/battery/ts_identity.py
deleted file mode 100644
index bfb57d4bab..0000000000
--- a/scripts/battery/ts_identity.py
+++ /dev/null
@@ -1,108 +0,0 @@
-#!/usr/bin/env python3
-"""Shared ts-identity guard for the parity harnesses.
-
-Every parity harness drives two products against each other: the deployed
-TS `prime-agent` binary (the "ts" side) and a Rust build of this repo (the
-"rust" side). The parity comparison is only a parity claim when the two
-sides are two products. A Rust build symlinked onto the PATH as
-`prime-agent` (seen in a sandbox harness run) plays a Rust build as the
-"ts" side and reports false divergences — e.g. a bold-escape d_expanded
-frame diff that current main cannot reproduce against the real TS binary.
-
-Every harness that launches the PATH ts binary calls the guard before
-launching anything, so no harness can run its "ts" side against a stale
-Rust build misidentified as TS:
-
- sys.path.insert(
- 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "battery")
- )
- import ts_identity # noqa: E402
- ts_identity.assert_ts_side_is_the_ts_product()
-
-Harnesses with non-default binaries pass them explicitly (perf_wave.py
-drives target/release/prime-agent rather than the debug build, and accepts
---ts-bin/--rust-bin):
-
- ts_identity.assert_ts_side_is_the_ts_product(ts_bin, rust_bin)
-
-The "same product" test is the `--version` first line: the deployed TS
-release and a Rust build of this repo report different version lines, so
-an exact match means the ts side is the Rust side. The manifest fallback
-keeps the guard working against an unbuilt tree (the workspace version is
-what a fresh build would report).
-"""
-
-import os
-import re
-import subprocess
-
-#: The env override every harness honors for the rust build it drives.
-RUST_BINARY_ENV = "PA_RUST_BINARY"
-
-#: This repo's root (scripts/battery/ -> repo root).
-REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-
-def default_rust_binary():
- """The Rust build a harness drives (PA_RUST_BINARY or the debug build)."""
- return os.environ.get(
- RUST_BINARY_ENV, os.path.join(REPO_ROOT, "target", "debug", "prime-agent")
- )
-
-
-def probe_version(command):
- """The first line of a prime-agent binary's `--version` output."""
- # The probe must isolate the binary's own product identity: a Rust
- # build launched with PI_PACKAGE_DIR pointed at a TS release reports
- # the installed package's version, which false-positives the
- # same-product refusal (seen in a sandbox harness run where the
- # release sidecar dir IS the TS release dir).
- env = {k: v for k, v in os.environ.items() if k != "PI_PACKAGE_DIR"}
- try:
- result = subprocess.run(
- f"{command} --version", shell=True, capture_output=True, text=True, timeout=60, env=env,
- )
- except subprocess.TimeoutExpired:
- return ""
- # The deployed release prints its version on stdout; the TS-main CLI
- # bundle (node dist/bundle/cli.js --version) prints on stderr.
- line = result.stdout.strip().splitlines() or result.stderr.strip().splitlines()
- return line[0] if line else ""
-
-
-def rust_version(rust_bin=None):
- """The Rust side's `--version` line, from the build or the workspace manifest."""
- rust = rust_bin or default_rust_binary()
- if os.path.exists(rust):
- version = probe_version(rust)
- if version:
- return version
- cargo = os.path.join(REPO_ROOT, "Cargo.toml")
- with open(cargo, encoding="utf-8") as manifest:
- text = manifest.read()
- section = text.split("[workspace.package]", 1)[-1]
- match = re.search(r'^version = "([^"]+)"', section, re.MULTILINE)
- return match.group(1) if match else ""
-
-
-def assert_ts_side_is_the_ts_product(ts_bin="prime-agent", rust_bin=None):
- """Fail fast when the ts binary is not the deployed TS build.
-
- `ts_bin` is the command the harness will launch as the ts side (the
- `prime-agent` on PATH by default); `rust_bin` is the Rust build the
- same harness drives (PA_RUST_BINARY or the debug build by default).
- Raises SystemExit (the harness's refusal) when the ts binary does not
- run at all, or when it reports the same `--version` line as the Rust
- build — i.e. when the "ts" side is actually this repo's Rust product.
- """
- ts_version = probe_version(ts_bin)
- if not ts_version:
- raise SystemExit(f"no working `{ts_bin}` for the ts side: the TS side cannot run")
- reference = rust_version(rust_bin)
- if reference and ts_version == reference:
- raise SystemExit(
- f"`{ts_bin}` (the ts side) reports version {ts_version!r}, the same "
- f"product as the Rust side ({reference!r}): point PATH at the "
- "deployed TS binary (e.g. /usr/local/bin/prime-agent from the "
- "release install)"
- )
diff --git a/scripts/ts_faux_extension.js b/scripts/ts_faux_extension.js
deleted file mode 100644
index d69808f111..0000000000
--- a/scripts/ts_faux_extension.js
+++ /dev/null
@@ -1,112 +0,0 @@
-// Shared faux-provider driver extension for the perf-wave dimensions
-// (scripts/battery/sustained_cpu.py, stream_throughput.py): registers the
-// faux provider with scripted responses read from PRIME_AGENT_FAUX_SCRIPT
-// (same harness contract the Rust rewrite uses). Verification harness only;
-// never installed for real users.
-import {
- registerFauxProvider,
- fauxAssistantMessage,
- fauxText,
- fauxThinking,
- fauxToolCall,
- getApiProvider,
- createAssistantMessageEventStream,
-} from "@earendil-works/pi-ai";
-import { readFileSync } from "node:fs";
-
-// The daemon's post-turn dashboard status line (daemon-session-summarizer).
-// It normally resolves to a small prime-inference model, but a daemon whose
-// status-line request falls back to the session model would otherwise
-// consume a scripted response and desync the faux queue mid-script.
-const AGENT_STATUS_SYSTEM_PROMPT_PREFIX =
- "You generate a status line for an AI coding agent dashboard.";
-
-function isStatusLineRequest(context) {
- return (
- typeof context?.systemPrompt === "string" &&
- context.systemPrompt.startsWith(AGENT_STATUS_SYSTEM_PROMPT_PREFIX)
- );
-}
-
-export default function registerVisualFaux(pi) {
- const scriptPath = process.env.PRIME_AGENT_FAUX_SCRIPT;
- const script = scriptPath ? JSON.parse(readFileSync(scriptPath, "utf8")) : {};
- const provider = script.provider || "faux";
- const modelId = script.modelId || "faux-1";
- const faux = registerFauxProvider({
- provider,
- api: "faux",
- models: [
- {
- id: modelId,
- name: script.modelName || "Faux Model",
- reasoning: script.reasoning ?? false,
- contextWindow: script.contextWindow ?? 128000,
- },
- ],
- tokensPerSecond: script.tokensPerSecond,
- });
- const responses = (script.responses || []).map((entry) => {
- let content;
- if (typeof entry === "string") {
- content = [fauxText(entry)];
- } else if (Array.isArray(entry.content)) {
- content = entry.content.map((block) => {
- if (block.type === "thinking") return fauxThinking(block.thinking);
- if (block.type === "toolCall") return fauxToolCall(block.name, block.arguments, { id: block.id });
- return fauxText(block.text);
- });
- } else {
- content = [fauxText(entry.text || "")];
- }
- const stopReason =
- entry.stopReason ||
- (content.some((block) => block.type === "toolCall") ? "toolUse" : "stop");
- // Optional scripted error text (the Rust faux script's contract):
- // rides the message with `stopReason: "error"`, so overflow-recovery
- // harnesses can script provider overflow responses.
- return fauxAssistantMessage(content, { stopReason, errorMessage: entry.errorMessage });
- });
- faux.setResponses(responses);
- const apiProvider = getApiProvider(faux.api);
- if (!apiProvider) {
- throw new Error("Faux API provider was not registered");
- }
- const scriptedStreamSimple = apiProvider.streamSimple;
- const streamSimple = (model, context, options) => {
- if (isStatusLineRequest(context)) {
- // Serve the dashboard status line from a canned empty verdict that
- // parses to no recap — the same visible state as the skipped
- // request — without consuming a scripted response.
- const stream = createAssistantMessageEventStream();
- const message = fauxAssistantMessage([fauxText("")], { stopReason: "stop" });
- message.api = model.api;
- message.provider = model.provider;
- message.model = model.id;
- queueMicrotask(() => {
- stream.push({ type: "start", partial: { ...message, content: [] } });
- stream.push({ type: "done", reason: "stop", message });
- stream.end(message);
- });
- return stream;
- }
- return scriptedStreamSimple(model, context, options);
- };
- pi.registerProvider(provider, {
- api: faux.api,
- apiKey: "faux-key",
- baseUrl: faux.getModel().baseUrl,
- streamSimple,
- models: faux.models.map((model) => ({
- api: model.api,
- baseUrl: model.baseUrl,
- contextWindow: model.contextWindow,
- cost: model.cost,
- id: model.id,
- input: model.input,
- maxTokens: model.maxTokens,
- name: model.name,
- reasoning: model.reasoning,
- })),
- });
-}