diff --git a/adapters/pi/adapter.sh b/adapters/pi/adapter.sh index 64a4290b9..be228cf56 100644 --- a/adapters/pi/adapter.sh +++ b/adapters/pi/adapter.sh @@ -1,6 +1,6 @@ #!/bin/sh -# Pi adapter: implements the Mosaic adapter contract for the pinned -# @earendil-works/pi-coding-agent CLI. +# Pi adapter: implements the Mosaic adapter contract for the +# @earendil-works/pi-coding-agent CLI. Its behaviour notes are read from 0.85.1. # # Contract: see /opt/mosaic/adapters/README.md. # Headless (default): stdout = response only; stderr = diagnostics; exit 0. diff --git a/packages/plugins/harness/pi/binary.mjs b/packages/plugins/harness/pi/binary.mjs new file mode 100644 index 000000000..2e69dfe34 --- /dev/null +++ b/packages/plugins/harness/pi/binary.mjs @@ -0,0 +1,67 @@ +// #1873 pi-unpin: the pi binary a session runs, and the package it comes from. Nothing here is +// pinned. The version label is read from the binary (or its package.json), never compared to a +// fixed one. The launcher, the bundle and the usage reader call these on the host. +import { accessSync, constants, readFileSync, realpathSync, statSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; + +const REPO = fileURLToPath(new URL("../../../../", import.meta.url)); +export const PACKAGE = "@earendil-works/pi-coding-agent"; +export const REPO_BIN = join(REPO, "node_modules", ".bin", "pi"); +const VERSION_MAX = 128; + +export const executable = (path) => { + try { + accessSync(path, constants.X_OK); + return statSync(path).isFile(); + } catch { + return false; + } +}; + +// The binary a session runs, with the name a refusal line uses for it, or why there is none. +export function locate() { + if (executable(REPO_BIN)) return { bin: REPO_BIN, label: "the repository's pi" }; + return { bin: null, problem: "pi isn't installed in the repository's node_modules; run npm ci in the repository" }; +} + +// The package directory that holds the binary's real file: the nearest directory above it whose +// package.json has a name. That name must be PACKAGE, or there is none (null). +export function packageDir(bin) { + let dir; + try { dir = dirname(realpathSync(bin)); } catch { return null; } + for (;;) { + let pkg = null; + try { pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); } catch { pkg = null; } + if (pkg && typeof pkg === "object" && pkg.name !== undefined) return pkg.name === PACKAGE ? dir : null; + const up = dirname(dir); + if (up === dir) return null; + dir = up; + } +} + +// The found package's own version, a file read with no spawn, or null. +export function packageVersion(bin) { + const dir = bin ? packageDir(bin) : null; + if (!dir) return null; + try { + const v = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).version; + return typeof v === "string" && cleanLabel(v) ? v : null; + } catch { + return null; + } +} + +// One printable line, short enough to record. +const cleanLabel = (s) => s.length > 0 && s.length <= VERSION_MAX && !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(s); + +// The first line ` --version` prints, or null when it fails, times out or prints something +// that is not one short printable line. The environment holds only a PATH that finds node. +export function printedVersion(bin) { + if (!bin) return null; + const r = spawnSync(bin, ["--version"], { encoding: "utf8", timeout: 5000, killSignal: "SIGKILL", env: { PATH: `${dirname(process.execPath)}:/usr/bin:/bin`, PI_OFFLINE: "1" } }); + if (r.status !== 0 || typeof r.stdout !== "string") return null; + const line = r.stdout.split("\n")[0].trim(); + return cleanLabel(line) ? line : null; +} diff --git a/packages/plugins/harness/pi/compactions.mjs b/packages/plugins/harness/pi/compactions.mjs index c6f312c0d..f425237c3 100644 --- a/packages/plugins/harness/pi/compactions.mjs +++ b/packages/plugins/harness/pi/compactions.mjs @@ -3,7 +3,7 @@ // `compactions` through the harness kind (packages/plugins/README.md has the contract). This file // reads only the session's native pi store and the Claude history beside it. // -// Pi (pinned 0.85.1): a completed compaction is one `type: "compaction"` entry, +// Pi (read from 0.85.1): a completed compaction is one `type: "compaction"` entry, // written by SessionManager.appendCompaction after the summary exists. A start // or an aborted compaction writes none. A `compactionSummary` message, a // message inside a compaction's retainedTail and a branch_summary are not @@ -19,8 +19,10 @@ import { createHash } from "node:crypto"; import { closeSync, constants as fsc, fstatSync, lstatSync, openSync, readdirSync, readSync } from "node:fs"; import { join } from "node:path"; +import { locate, packageVersion } from "./binary.mjs"; -export const PI_VERSION = "0.85.1"; +// #1873 S1: the found package's own version (its package.json, no spawn), or null. +const foundVersion = () => packageVersion(locate(process.env).bin); const TAIL = 4096; const CHUNK = 1 << 20; const STREAM = /^[A-Za-z0-9._-]{1,200}\.jsonl$/; @@ -158,9 +160,9 @@ export function compactions({ store, cursors, budget, streams, first }) { if (first && claudeHistory(store)) { // Claude runs before this ledger: their compactions can't be counted // (Vikunja 466), so the count is unknown for good, as after a Claude run. - return { found: [], cursors: {}, known: false, reason: "harness-unsupported", version: PI_VERSION }; + return { found: [], cursors: {}, known: false, reason: "harness-unsupported", version: foundVersion() }; } const scan = scanPi(store.session, cursors, budget, streams); const reason = REASONS.find((p) => scan.problems.includes(p)) ?? null; - return { found: scan.found, cursors: scan.cursors, known: reason === null, reason, version: PI_VERSION }; + return { found: scan.found, cursors: scan.cursors, known: reason === null, reason, version: foundVersion() }; } diff --git a/packages/plugins/harness/pi/index.mjs b/packages/plugins/harness/pi/index.mjs index f7bef1da7..6cbb638fe 100644 --- a/packages/plugins/harness/pi/index.mjs +++ b/packages/plugins/harness/pi/index.mjs @@ -1,18 +1,17 @@ -// The "pi" harness plug-in (row 65, REQ-PLUG-2, Q156): a managed session on the pinned -// @earendil-works/pi-coding-agent CLI, the repository's node_modules/.bin/pi. The tool gate is the +// The "pi" harness plug-in (row 65, REQ-PLUG-2, Q156): a managed session on the +// @earendil-works/pi-coding-agent CLI that binary.mjs finds (#1873: no version pin). The tool gate is the // Pi extension, which stays in packages/harness (a module can't change that boundary). The // launcher, the bundle and the usage reader call these on the host; the runner gets the answers // as data in session.json. packages/plugins/README.md lists the interface. -import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { lstatSync, mkdirSync, realpathSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; +import { locate, printedVersion } from "./binary.mjs"; export const interfaceVersion = 1; const REPO = fileURLToPath(new URL("../../../../", import.meta.url)); -const PACKAGE = "@earendil-works/pi-coding-agent"; -const BIN = join(REPO, "node_modules", ".bin", "pi"); const EXTENSION = fileURLToPath(new URL("../../../harness/src/pi-extension.mjs", import.meta.url)); // Row 66 (#1559): the unslop check, loaded as a second extension. It logs to MOSAIC_UNSLOP_LOG, // which the runner sets, and the runner tells the operator. @@ -37,18 +36,15 @@ export function preflight({ env = {}, proxy = null } = {}) { && !["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "ZAI_API_KEY"].some(name => Boolean(env[name]))) { return { code: "no-session-credential", message: "pi needs its own provider key or a session proxy key" }; } - if (!existsSync(BIN)) return { code: "harness-binary-missing", message: "pi isn't installed in the repository's node_modules; run npm ci in the repository" }; + const found = locate(env); + if (!found.bin) return { code: "harness-binary-missing", message: found.problem }; return null; } -// The exact pin from the repository's package.json. -export function version() { - try { - const pkg = JSON.parse(readFileSync(join(REPO, "package.json"), "utf8")); - return pkg.dependencies?.[PACKAGE] ?? pkg.devDependencies?.[PACKAGE] ?? null; - } catch { - return null; - } +// #1873 S1: what the found binary prints for --version (5 s timeout), or null. A label only: +// nothing compares it to a fixed version. +export function version({ env = {} } = {}) { + return printedVersion(locate(env).bin); } // Pi sessions run on a provider key, never the Claude account limit. diff --git a/packages/plugins/tests/harness.test.mjs b/packages/plugins/tests/harness.test.mjs index 18814db4e..bb32851e4 100644 --- a/packages/plugins/tests/harness.test.mjs +++ b/packages/plugins/tests/harness.test.mjs @@ -98,11 +98,11 @@ test("row 65 claude-code version asks MOSAIC_CLAUDE_BIN when set, else claude on assert.equal(claude.version({ env: { PATH: join(dir, "none") } }), null); }); -test("row 65 pi preflight refuses missing credentials, and its version is the package pin", async () => { +test("row 65 pi preflight refuses missing credentials, and its version is what the installed pi prints (#1873 S1)", async () => { const pi = await load("pi"); assert.equal(pi.preflight({ env: {} }).code, "no-session-credential"); - const pkg = JSON.parse(readFileSync(join(REPO, "package.json"), "utf8")); - assert.equal(pi.version({ env: {} }), pkg.dependencies?.["@earendil-works/pi-coding-agent"] ?? pkg.devDependencies?.["@earendil-works/pi-coding-agent"]); + const installed = JSON.parse(readFileSync(join(REPO, "node_modules", "@earendil-works", "pi-coding-agent", "package.json"), "utf8")).version; + assert.equal(pi.version({ env: {} }), installed); // Row 66: the unslop extension's files, bound read-only at their own paths. assert.deepEqual(pi.mounts({ env: {} }).map(m => m.dest ?? m.src), [join(REPO, "packages/plugins/harness/pi/model-stream.mjs"), join(REPO, "node_modules"), ...["extension.ts", "unslop-check.js", "lists.json"].map(f => join(REPO, "tools", "unslop-hook", f))]); }); diff --git a/packages/plugins/tests/pi-binary.test.mjs b/packages/plugins/tests/pi-binary.test.mjs new file mode 100644 index 000000000..598787100 --- /dev/null +++ b/packages/plugins/tests/pi-binary.test.mjs @@ -0,0 +1,76 @@ +// #1873 pi-unpin (design section 5, S1): pi's labels come from the binary the module finds, not +// from a pin. The version is what ` --version` prints, or null when that fails; the +// compaction count records the found package's own version. +import test from "node:test"; +import assert from "node:assert/strict"; +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const REPO = resolve(fileURLToPath(new URL("../../../", import.meta.url))); +const MODULE = join(REPO, "packages", "plugins", "harness", "pi"); +const NAME = "@earendil-works/pi-coding-agent"; + +function scratch(t) { + const root = mkdtempSync(join(tmpdir(), "mosaic-pi-bin-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + return root; +} + +// A pi package under `dir` (a node_modules directory), with `script` as its bin. +function standIn(dir, script, version) { + const pkg = join(dir, NAME); + mkdirSync(join(pkg, "dist", "bundle"), { recursive: true }); + writeFileSync(join(pkg, "package.json"), JSON.stringify({ name: NAME, version, bin: { pi: "dist/bundle/cli.js" } })); + writeFileSync(join(pkg, "dist", "bundle", "cli.js"), script, { mode: 0o755 }); + return join(pkg, "dist", "bundle", "cli.js"); +} + +// A copy of the pi module in a scratch repository whose node_modules holds a stand-in, so the +// module's repository copy is that stand-in and not the real pi. The rest of packages/ links to +// the real tree, for the modules the copy imports. +async function copyRepo(t, script, version) { + const root = scratch(t); + const mod = join(root, "packages", "plugins", "harness", "pi"); + mkdirSync(mod, { recursive: true }); + for (const f of readdirSync(MODULE)) if (f.endsWith(".mjs")) copyFileSync(join(MODULE, f), join(mod, f)); + for (const p of readdirSync(join(REPO, "packages"))) if (p !== "plugins") symlinkSync(join(REPO, "packages", p), join(root, "packages", p)); + standIn(join(root, "node_modules"), script, version); + mkdirSync(join(root, "node_modules", ".bin")); + symlinkSync(`../${NAME}/dist/bundle/cli.js`, join(root, "node_modules", ".bin", "pi")); + return { root, pi: await import(pathToFileURL(join(mod, "index.mjs")).href) }; +} + +const emptyStore = (t) => { + const root = scratch(t); + mkdirSync(join(root, "session")); + return { session: join(root, "session"), projects: join(root, "claude-projects") }; +}; + +test("pi-unpin S1: the version is what the found binary prints, and the compaction count records its package's version", async t => { + const { pi } = await copyRepo(t, "#!/bin/sh\n[ \"$1\" = --version ] && echo 9.9.9\n", "9.9.4"); + assert.equal(pi.version({ env: {} }), "9.9.9"); + const counted = pi.compactions({ store: emptyStore(t), cursors: {}, budget: 1 << 20, streams: 16, first: false }); + assert.equal(counted.version, "9.9.4"); +}); + +test("pi-unpin S1: a binary that exits 1 on --version gives a null version, not a guess", async t => { + const { pi } = await copyRepo(t, "#!/bin/sh\nexit 1\n", "8.8.8"); + assert.equal(pi.version({ env: {} }), null); + // The package's own file still names its version for the compaction count. + assert.equal(pi.compactions({ store: emptyStore(t), cursors: {}, budget: 1 << 20, streams: 16, first: false }).version, "8.8.8"); +}); + +test("pi-unpin S1: a version line with a control character or over 128 characters is not recorded", async t => { + const { pi } = await copyRepo(t, "#!/bin/sh\nprintf '1.0\\033[31m\\n'\n", "1.0.0"); + assert.equal(pi.version({ env: {} }), null); + const long = await copyRepo(t, `#!/bin/sh\necho ${"9".repeat(129)}\n`, "1.0.0"); + assert.equal(long.pi.version({ env: {} }), null); +}); + +test("pi-unpin S1: the repository's real pi reports its installed package's version", async () => { + const pi = await import(pathToFileURL(join(MODULE, "index.mjs")).href); + const installed = JSON.parse(readFileSync(join(REPO, "node_modules", NAME, "package.json"), "utf8")).version; + assert.equal(pi.version({ env: {} }), installed); +});