import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { test, type TestContext } from "node:test"; import { FileCapacityBroker } from "../../delegate/capacity.ts"; import { buildChildArgs } from "../../delegate/spawn.ts"; import { validateLeaseIdentity, sameLease, readLeaseIdentity } from "../lease.ts"; import { LEASE_ENV, LEASE_NOTICE } from "../lease-startup.ts"; import { encodeRpc, type RunPiChildInput } from "../spawn.ts"; import { mockChild, runMockPiChild } from "./helpers.ts"; const linux = { skip: process.platform !== "linux" }; function fixture(t: TestContext) { const root = mkdtempSync("/tmp/pi-delegate-lease-runtime-"); const lease = new FileCapacityBroker(root).tryAcquire({ key: "runtime-test", capacity: 1 })!; t.after(() => { lease.release(); rmSync(root, { recursive: true, force: true }); }); const proc = mockChild(); let options: any, args: readonly string[] = []; const input: RunPiChildInput = { cwd: root, model: "test/model", task: "must wait for lease acknowledgement", hardTimeoutMs: 0, maxOutputBytes: 1000, env: {}, buildArgs: () => [], resourceLease: lease.inherited, promptSourcePath: fileURLToPath(new URL("../../delegate/config.json", import.meta.url)), leaseStartupMs: 1000, spawnFn: (_command, argv, value) => { args = argv; options = value; return proc; }, }; return { input, proc, lease, options: () => options, args: () => args }; } test("lease identities reject malformed values and reserve fd 3+ for non-stdio files", linux, () => { assert.deepEqual(validateLeaseIdentity({ dev: "12", ino: "34" }), { dev: "12", ino: "34" }); for (const value of [null, {}, { dev: 1, ino: "2" }, { dev: "-1", ino: "2" }, { dev: "1", ino: "x" }]) assert.throws(() => validateLeaseIdentity(value)); assert.equal(sameLease(undefined, undefined), true); assert.equal(sameLease({ dev: "1", ino: "2" }, undefined), false); for (const fd of [0, 1, 2, -1, 1.5, NaN]) assert.throws(() => readLeaseIdentity(fd), /descriptor/); }); test("leased child startup preserves extension policy and requires its correlated acknowledgement", linux, async t => { for (const extensions of [false, true]) { const f = fixture(t), pending = runMockPiChild({ ...f.input, buildArgs: promptPath => buildChildArgs({ model: f.input.model, thinking: "off", tools: ["*"], extensions, promptPath, sessionFile: `${f.input.cwd}/session.jsonl` }), }); try { assert.equal(f.args().includes("--no-extensions"), !extensions); assert.ok(f.args().includes("--extension"), "lease helper must load even when discovery is disabled"); const options = f.options(); assert.deepEqual(options.stdio, ["pipe", "pipe", "pipe", f.lease.inherited.fd]); const config = JSON.parse(options.env[LEASE_ENV]); assert.deepEqual(config.lease, { dev: f.lease.inherited.dev, ino: f.lease.inherited.ino }); assert.equal(f.proc.stdinBytes, ""); f.proc.stdout!.write(encodeRpc({ type: "extension_ui_request", method: "notify", message: JSON.stringify({ type: LEASE_NOTICE, nonce: "another-child-nonce", version: 1, lease: config.lease, }) })); await Promise.resolve(); assert.equal(f.proc.stdinBytes, "", "another child's receipt cannot release the task"); f.proc.stdout!.write(encodeRpc({ type: "extension_ui_request", method: "notify", message: JSON.stringify({ type: LEASE_NOTICE, nonce: config.nonce, version: 1, lease: config.lease, }) })); for (let i = 0; i < 20 && !f.proc.stdinBytes.includes('"id":"p1"'); i++) await Promise.resolve(); assert.ok(f.proc.stdinBytes.includes('"id":"p1"')); f.proc.stdout!.write(encodeRpc({ type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "Done." }] } })); f.proc.stdout!.write(encodeRpc({ type: "agent_settled" })); assert.equal((await pending).stopReason, "stop"); assert.doesNotThrow(() => readLeaseIdentity(f.lease.inherited.fd), "runtime must not close the scheduler's borrowed descriptor"); } finally { f.proc.close(1); await pending; } } }); for (const acknowledgement of ["missing", "wrong"] as const) { test(`${acknowledgement} inherited-lease acknowledgement refuses the task`, linux, async t => { const f = fixture(t), pending = runMockPiChild(f.input); try { const config = JSON.parse(f.options().env[LEASE_ENV]); const lease = acknowledgement === "wrong" ? { dev: config.lease.dev, ino: config.lease.ino === "0" ? "1" : "0" } : undefined; f.proc.stdout!.write(encodeRpc({ type: "extension_ui_request", method: "notify", message: JSON.stringify({ type: LEASE_NOTICE, nonce: config.nonce, version: 1, lease, }) })); const result = await pending; assert.equal(result.stopReason, "error"); assert.match(result.text, /expected resource lease|Invalid resource lease identity/); assert.equal(f.proc.stdinBytes.includes('"id":"p1"'), false); } finally { f.proc.close(1); await pending; } }); } test("lease-only startup withholds task and early steering until acknowledgement, and fails closed", linux, async t => { for (const mode of ["ready", "wrong", "late-wrong", "timeout", "exit", "abort"] as const) { const f = fixture(t), control = new AbortController(); const pending = runMockPiChild({ ...f.input, leaseStartupMs: 30, signal: control.signal, onControl: ctl => { assert.equal(ctl.wrap("Finish briefly"), true); }, beforePrompt: async () => { if (mode !== "late-wrong") return; const config = JSON.parse(f.options().env[LEASE_ENV]); f.proc.stdout!.write(encodeRpc({ type: "extension_ui_request", method: "notify", message: JSON.stringify({ type: LEASE_NOTICE, version: 1, nonce: config.nonce, lease: { dev: "0", ino: "0" }, }) })); }, }); try { assert.equal(f.proc.stdinBytes, "", "even early wrap must not reach the model before startup"); assert.equal(f.options().env.PI_DELEGATE_RUNTIME_GUARD, undefined); const config = JSON.parse(f.options().env[LEASE_ENV]); if (mode === "ready" || mode === "wrong" || mode === "late-wrong") { f.proc.stdout!.write(encodeRpc({ type: "extension_ui_request", method: "notify", message: JSON.stringify({ type: LEASE_NOTICE, version: 1, nonce: config.nonce, lease: mode === "wrong" ? { dev: "0", ino: "0" } : config.lease, }) })); } else if (mode === "exit") f.proc.close(0); else if (mode === "abort") control.abort(); if (mode === "ready") { for (let i = 0; i < 20 && !f.proc.stdinBytes; i++) await Promise.resolve(); assert.deepEqual(f.proc.stdinBytes.trim().split("\n").map(line => JSON.parse(line).type), ["prompt", "steer"]); f.proc.stdout!.write(encodeRpc({ type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "Evidence." }] } })); f.proc.stdout!.write(encodeRpc({ type: "agent_settled" })); } const result = await pending; assert.equal(result.finalization, undefined, "lease-only startup must not activate finalization policy"); assert.equal(result.stopReason === "stop", mode === "ready"); assert.equal(result.evidence?.taskSent, mode === "ready"); if (mode !== "ready") assert.equal(f.proc.stdinBytes.includes('"prompt"'), false); assert.doesNotThrow(() => readLeaseIdentity(f.lease.inherited.fd)); } finally { f.proc.close(1); await pending; } } }); test("missing startup policy or changed parent descriptor fails before spawning, never uncoordinated", linux, async t => { const f = fixture(t); let spawns = 0; const spawnFn = () => { spawns++; return f.proc; }; await assert.rejects(runMockPiChild({ ...f.input, leaseStartupMs: undefined, spawnFn }), /require explicit lease-only startup/); await assert.rejects(runMockPiChild({ ...f.input, resourceLease: { ...f.lease.inherited, ino: "0" }, spawnFn }), /identity changed/); await assert.rejects(runMockPiChild({ ...f.input, resourceLease: null as any, spawnFn }), /descriptor/); assert.equal(spawns, 0); });