Port upstream runtime while preserving Boat staging migration history

This commit is contained in:
Dotta committed 2026-10-11 00:01:05 -05:00
1 parent 780ecec585
commit d50dd0f49b
30 files changed
+4089 -698

No files matched your search

+37 -4
View File
@@ -10,7 +10,8 @@ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."
// Exercise the real startup helper and child-process boundary without registry
// traffic. The npm fixture installs a real executable into its isolated prefix.
export async function canaryStartup({ mode, onboard = "success", budget = 5000, delay = 5, cancelAtKind, playwright = false }) {
export async function canaryStartup({ mode, onboard = "success", budget = 5000, delay = 5, cancelAtKind, playwright = false,
config = "public", metadata = "valid", version = "2026.1009.0-canary.1" }) {
const root = mkdtempSync(path.join(os.tmpdir(), "canary-startup-test-"));
const calls = path.join(root, "calls.jsonl");
const fixtureBin = path.join(root, "bin");
@@ -39,15 +40,35 @@ if (process.env.FIXTURE_ONBOARD === "serve") {
const fs = require("node:fs");
const path = require("node:path");
const args = process.argv.slice(2);
if (args[0] === "config") {
fs.appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"config", pid:process.pid, args}) + "\\n");
if (process.env.FIXTURE_CONFIG === "hang") {
const { spawn } = require("node:child_process");
const child = spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>{}); setTimeout(()=>process.exit(0),10000)"], {stdio:"ignore"});
fs.appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"config-descendant", pid:child.pid}) + "\\n");
process.on("SIGTERM", () => {});
setTimeout(() => process.exit(0), 10000);
} else {
if (process.env.FIXTURE_CONFIG === "large") console.log("x".repeat(8192));
console.log("registry=" + (process.env.FIXTURE_CONFIG === "private" ? "https://fixture-user:fixture-password@registry.example.invalid/" : "https://registry.npmjs.org/") + "\\n@paperclipai:registry=undefined");
console.error("fixture config diagnostic must stay private");
}
} else {
const entries = fs.existsSync(process.env.FIXTURE_CALLS) ? fs.readFileSync(process.env.FIXTURE_CALLS, "utf8").trim().split("\\n").filter(Boolean).map(JSON.parse) : [];
const attempt = entries.filter(e => e.kind === "npm").length + 1;
fs.appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"npm", pid:process.pid, args, cache:process.env.npm_config_cache}) + "\\n");
const mode = process.env.FIXTURE_MODE;
if (mode === "hang") { setTimeout(() => {}, 10000); }
else if (mode === "permanent" || (mode === "recover" && attempt === 1)) { console.error("npm error code ETARGET"); process.exit(1); }
else if (mode === "multibyte-recover" && attempt === 1) { console.error("npm error code ETARGET\\n" + "界".repeat(30 * 1024)); process.exit(1); }
else if (mode === "auth") { console.error("npm error code E401"); process.exit(1); }
else if (mode === "mixed") { console.error("npm error code ETARGET\\nnpm error code E401"); process.exit(1); }
else if (mode === "network") { console.error("npm error code ECONNRESET"); process.exit(1); }
else if (mode === "tarball-permanent" || mode === "tarball-large" || (mode === "tarball-recover" && attempt === 1)) {
const url = "https://registry.npmjs.org/@paperclipai/server/-/server-" + process.env.PAPERCLIPAI_VERSION + ".tgz";
if (mode === "tarball-large") console.error("npm error code E401\\n" + "x".repeat(70 * 1024));
console.error("npm error code E404\\nnpm error 404 Not Found - GET " + url + " - Not found"); process.exit(1);
}
else {
const prefix = args[args.indexOf("--prefix") + 1];
const bin = path.join(prefix, "node_modules", ".bin");
@@ -55,12 +76,24 @@ else {
fs.writeFileSync(path.join(bin, "paperclipai"), ${JSON.stringify(cli).replaceAll('$','\$')});
fs.chmodSync(path.join(bin, "paperclipai"), 0o755);
}
}
`);
chmodSync(npmFixture, 0o755);
const helper = new URL("../../tests/canary-onboarding/start-published-canary.mjs", import.meta.url).href;
const driver = path.join(root, "driver.mjs");
writeFileSync(driver, `import { startPublishedCanary } from ${JSON.stringify(helper)};
try { await startPublishedCanary({version:"2026.1009.0-canary.1", workspace:${JSON.stringify(root)}, dataDir:${JSON.stringify(path.join(root,"data"))}, installBudgetMs:${budget}, retryDelayMs:${delay}}); }
import { appendFileSync } from "node:fs";
globalThis.fetch = async (url, options) => {
appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"metadata", url, redirect:options.redirect, credentials:options.credentials, headers:options.headers}) + "\\n");
const manifest = {name:"@paperclipai/server",version:process.env.PAPERCLIPAI_VERSION,dist:{tarball:"https://registry.npmjs.org/@paperclipai/server/-/server-" + process.env.PAPERCLIPAI_VERSION + ".tgz",integrity:"sha512-" + Buffer.alloc(64).toString("base64")}};
const body = process.env.FIXTURE_METADATA === "hang" ? new ReadableStream({
start(controller) { options.signal.addEventListener("abort", () => controller.error(options.signal.reason), {once:true}); },
}) : JSON.stringify(manifest);
const response = new Response(body, {status:process.env.FIXTURE_METADATA === "missing" ? 404 : 200});
Object.defineProperty(response,"url",{value:url});
return response;
};
try { await startPublishedCanary({version:${JSON.stringify(version)}, workspace:${JSON.stringify(root)}, dataDir:${JSON.stringify(path.join(root,"data"))}, installBudgetMs:${budget}, retryDelayMs:${delay}}); }
catch (error) { console.error(error.message); process.exitCode = 1; }
`);
const playwrightConfig = path.join(root, "playwright.config.mjs");
@@ -80,8 +113,8 @@ export default {...original, testDir:${JSON.stringify(root)}, testMatch:"fixture
? [fileURLToPath(helper), "2026.1009.0-canary.1", root, path.join(root, "data")]
: [driver], { cwd: repoRoot, env: {
...process.env, PATH: fixtureBin + path.delimiter + process.env.PATH,
FIXTURE_MODE: mode, FIXTURE_ONBOARD: onboard, FIXTURE_CALLS: calls, FIXTURE_PORT: String(port),
PAPERCLIPAI_VERSION: "2026.1009.0-canary.1", PAPERCLIP_CANARY_SMOKE_BASE_URL: `http://127.0.0.1:${port}`, PAPERCLIP_CANARY_SMOKE_SERVER_LOG: path.join(root,"server.log"),
FIXTURE_MODE: mode, FIXTURE_ONBOARD: onboard, FIXTURE_CALLS: calls, FIXTURE_PORT: String(port), FIXTURE_CONFIG: config, FIXTURE_METADATA: metadata,
PAPERCLIPAI_VERSION: version, PAPERCLIP_CANARY_SMOKE_BASE_URL: `http://127.0.0.1:${port}`, PAPERCLIP_CANARY_SMOKE_SERVER_LOG: path.join(root,"server.log"),
npm_config_cache: path.join(root, "fresh-cache"),
}, stdio: ["ignore", "pipe", "pipe"] });
let output = "";
@@ -81,6 +81,35 @@ test('verification never elevates PR-controlled provisioning or cleanup on the h
assert.ok(source.includes("const prerequisite = join(root, 'native/grok')"));
});
test('the image and Grok downloads start before staging and join without weakening the npm checks', () => {
const source = readFileSync(new URL('../verify-grok-npm-install.mjs', import.meta.url), 'utf8');
const position = fragment => { const index = source.indexOf(fragment); assert.notEqual(index, -1, `verifier must contain ${fragment}`); return index; };
// Exactly the pinned consumer image is pulled, for the platform the probes run on.
const imagePull = position("prefetch('image', 'docker', ['pull', '--platform', 'linux/amd64', GROK_PUBLIC_INSTALL_IMAGE])");
// Grok is provisioned into the prefetch directory, never straight into `native/grok`.
const grokProvision = position("prefetch('grok', process.execPath, [join(repo, 'packages/paperclip-runner/scripts/provision-grok.mjs'), stagedGrok])");
assert.ok(source.includes("const stagedGrok = join(prefetched, 'grok')"));
assert.doesNotMatch(source, /provision-grok\.mjs'\), prerequisite\]/);
// Both downloads start before any package is staged and before the first sandbox runs.
const staging = position("visit('@paperclipai/server')");
const firstSandbox = position("isolated(['npm', 'install', '--ignore-scripts', '--omit=dev'");
assert.ok(imagePull < staging && grokProvision < staging);
assert.ok(position("await awaited('image', imageReady)") < firstSandbox);
// The binary moves to the canonical host path only after npm is proven not to
// have provisioned it, after the negative probe, and before the positive probe.
const npmCheck = position("'npm must not provision Grok'");
const negativeProbe = position("isolated(['node', '/packages/probe.mjs', 'missing'])");
const grokJoin = position("await awaited('grok', grokReady)");
const move = position('renameSync(stagedGrok, prerequisite)');
const positiveProbe = position("isolated(['node', '/packages/probe.mjs', 'present'], { prerequisite })");
assert.ok(npmCheck < negativeProbe && negativeProbe < grokJoin && grokJoin < move && move < positiveProbe);
// The children run through the helper covered by prefetch-child.test.mjs, and
// cleanup waits for them before removing the directory they write into.
assert.ok(source.includes("import { startPrefetch, stopPrefetches } from './prefetch-child.mjs'"));
assert.ok(position('await stopPrefetches(prefetches)') < position('rmSync(root, { recursive: true, force: true })'));
assert.equal(source.match(/rmSync\(root/g).length, 1);
});
test('the installed Codex probe exercises the public export and rejects incomplete or mismatched packages', () => {
const root = realpathSync(mkdtempSync(join(tmpdir(), 'installed-codex-probe-')));
try {
+93
View File
@@ -0,0 +1,93 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { startPrefetch, stopPrefetches } from '../prefetch-child.mjs';
// Small local Node children stand in for the image pull and the Grok download;
// none of these tests needs Docker or a network.
const withScratch = async body => {
const root = mkdtempSync(join(tmpdir(), 'prefetch-child-'));
try { await body(root); } finally { rmSync(root, { recursive: true, force: true }); }
};
const start = (root, name, script, cmd = process.execPath, args = ['-e', script]) =>
startPrefetch({ name, cmd, args, cwd: root, env: process.env, logPath: join(root, `${name}.log`) });
const blockFor = ms => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
const untilLogHas = async (path, text) => {
for (let attempt = 0; attempt < 400; attempt++) {
try { if (readFileSync(path, 'utf8').includes(text)) return; } catch {}
await new Promise(resolve => setTimeout(resolve, 25));
}
throw new Error(`log never contained ${text}`);
};
test('a successful prefetch resolves, keeps its output, and is left alone by stop', async () => withScratch(async root => {
const handle = start(root, 'ok', "setTimeout(() => process.stdout.write('fetched\\n'), 150)");
await handle.done;
assert.equal(handle.child.exitCode, 0);
assert.equal(readFileSync(join(root, 'ok.log'), 'utf8'), 'fetched\n');
assert.ok(handle.durationMs >= 100 && handle.durationMs < 5000, `durationMs ${handle.durationMs}`);
await stopPrefetches([handle]);
assert.equal(handle.child.signalCode, null);
}));
test('the duration ends at the download, not when a blocked parent notices the exit', async () => withScratch(async root => {
const handle = start(root, 'early', "setTimeout(() => process.stdout.write('Status: Downloaded\\n'), 100)");
// Synchronous work in the parent, as package staging is in the verifier.
blockFor(1500);
const noticed = Date.now();
await handle.done;
assert.ok(Date.now() - noticed < 500, 'the exit was pending by the time the parent yielded');
assert.ok(handle.durationMs < 900, `durationMs ${handle.durationMs} must not include the 1500ms the parent was blocked`);
}));
test('a nonzero exit rejects with the log tail where the result is awaited', async () => withScratch(async root => {
const handle = start(root, 'bad', "process.stderr.write('registry unreachable\\n'); process.exit(3)");
await assert.rejects(handle.done, /^Error: bad prefetch failed \(exit 3\): registry unreachable$/);
await stopPrefetches([handle]);
}));
test('a command that cannot start rejects instead of hanging the join or the stop', async () => withScratch(async root => {
const handle = start(root, 'missing', '', join(root, 'no-such-command'), []);
await assert.rejects(handle.done, /missing prefetch failed \(.*ENOENT/);
await stopPrefetches([handle]);
}));
test('stopping a running prefetch waits for it to exit so its directory can be removed safely', async () => withScratch(async root => {
const handle = start(root, 'slow', "process.stdout.write('started\\n'); setInterval(() => {}, 1000)");
await untilLogHas(join(root, 'slow.log'), 'started');
const stopping = Date.now();
await stopPrefetches([handle]);
assert.ok(Date.now() - stopping < 4000);
assert.equal(handle.child.signalCode, 'SIGTERM');
assert.equal(handle.child.exitCode, null);
await assert.rejects(handle.done, /slow prefetch failed \(SIGTERM\): started/);
}));
test('a prefetch that ignores SIGTERM is killed after the grace period', async () => withScratch(async root => {
const handle = start(root, 'stubborn', "process.on('SIGTERM', () => {}); process.stdout.write('ignoring\\n'); setInterval(() => {}, 1000)");
await untilLogHas(join(root, 'stubborn.log'), 'ignoring');
const stopping = Date.now();
await stopPrefetches([handle], { graceMs: 200 });
assert.ok(Date.now() - stopping >= 200 && Date.now() - stopping < 4000);
assert.equal(handle.child.signalCode, 'SIGKILL');
}));
test('an unawaited failure never becomes an unhandled rejection', () => {
const script = `
import { startPrefetch } from ${JSON.stringify(new URL('../prefetch-child.mjs', import.meta.url).href)};
import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path';
const root = mkdtempSync(join(tmpdir(), 'prefetch-unawaited-'));
try {
startPrefetch({ name: 'ignored', cmd: process.execPath, args: ['-e', 'process.exit(2)'], cwd: root, env: process.env, logPath: join(root, 'ignored.log') });
await new Promise(resolve => setTimeout(resolve, 500));
console.log('still running');
} finally { rmSync(root, { recursive: true, force: true }); }
`;
const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 10_000 });
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /still running/);
assert.doesNotMatch(result.stderr, /unhandled/i);
});
@@ -5,7 +5,9 @@ import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { createServer } from "node:http";
import { canaryStartup } from "./canary-startup-fixture.mjs";
import { canRetryPublishedTarball404, TARBALL_METADATA_TIMEOUT_MS } from "../../tests/canary-onboarding/start-published-canary.mjs";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -102,6 +104,131 @@ test("canary reuses exact-source proof while stable keeps full verification", ()
);
});
function canaryAttachmentScript() {
const publish = readWorkflow("release.yml").split(" publish_canary:\n")[1].split(" smoke_canary_onboarding:\n")[0];
const step = publish.split(" - name: Attach verified canary source to local master\n")[1]?.split("\n - ")[0];
assert.ok(step, "the trusted publisher must attach its pinned checkout before releasing");
assert.match(step, /SOURCE_SHA: \$\{\{ github\.sha \}\}/);
const script = step.match(/run: \|\n((?: {10}[^\n]*\n)+)/)?.[1];
assert.ok(script, "missing inline canary branch attachment shell");
return script.replace(/^ {10}/gm, "");
}
function withCanaryGitFixture(check) {
const root = mkdtempSync(path.join(os.tmpdir(), "canary-publisher-git-"));
const cwd = path.join(root, "repository with spaces");
mkdirSync(cwd);
const git = (...args) => {
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
assert.equal(result.status, 0, result.stderr);
return result.stdout.trim();
};
try {
git("init", "--initial-branch=master");
git("config", "user.name", "Release fixture");
git("config", "user.email", "release-fixture@example.invalid");
git("config", "commit.gpgsign", "false");
git("config", "core.hooksPath", "/dev/null");
writeFileSync(path.join(cwd, "source.txt"), "pinned source\n");
git("add", "source.txt");
git("commit", "-m", "Create pinned source");
const pinned = git("rev-parse", "HEAD");
writeFileSync(path.join(cwd, "source.txt"), "newer master source\n");
git("commit", "-am", "Advance master");
const newer = git("rev-parse", "HEAD");
git("update-ref", "refs/remotes/origin/master", newer);
git("checkout", "--detach", pinned);
const env = {
...process.env, REPO_ROOT: cwd, SOURCE_SHA: pinned,
GITHUB_ACTIONS: "true", GITHUB_REPOSITORY: "paperclipai/paperclip",
GITHUB_EVENT_NAME: "push", GITHUB_REF: "refs/heads/master",
};
const attach = (overrides = {}) => spawnSync("bash", ["--noprofile", "--norc", "-c", canaryAttachmentScript()], {
cwd, env: { ...env, ...overrides }, encoding: "utf8", timeout: 5_000,
});
// Run the original release guard without running release.sh, npm, or a publisher.
const guard = () => spawnSync("bash", ["-c", 'source "$1"; require_on_master_branch', "guard", path.join(repoRoot, "scripts/release-lib.sh")], {
cwd, env, encoding: "utf8", timeout: 5_000,
});
check({ cwd, git, pinned, newer, attach, guard });
} finally {
rmSync(root, { recursive: true, force: true });
}
}
test("canary publisher attaches the exact source while local and remote master are newer", () => {
withCanaryGitFixture(({ cwd, git, pinned, newer, attach, guard }) => {
assert.equal(guard().status, 1, "the unchanged release guard must reject detached HEAD even in Actions");
assert.equal(git("rev-parse", "master"), newer);
const result = attach();
assert.equal(result.status, 0, result.stderr);
assert.equal(git("symbolic-ref", "--short", "HEAD"), "master");
assert.equal(git("rev-parse", "HEAD"), pinned);
assert.equal(git("rev-parse", "master"), pinned);
assert.equal(git("rev-parse", "origin/master"), newer, "do not fetch or follow floating remote master");
assert.equal(readFileSync(path.join(cwd, "source.txt"), "utf8"), "pinned source\n");
assert.equal(git("status", "--porcelain"), "");
assert.equal(guard().status, 0, "the real release guard must accept the pinned local master");
});
});
for (const [name, overrides] of [
["fork repository", { GITHUB_REPOSITORY: "example/paperclip" }],
["manual dispatch", { GITHUB_EVENT_NAME: "workflow_dispatch" }],
["scheduled release", { GITHUB_EVENT_NAME: "schedule" }],
["non-master push", { GITHUB_REF: "refs/heads/topic" }],
["tag push", { GITHUB_REF: "refs/tags/canary/v1" }],
["missing source SHA", { SOURCE_SHA: "" }],
["abbreviated source SHA", { SOURCE_SHA: "a".repeat(12) }],
["malformed source SHA", { SOURCE_SHA: "z".repeat(40) }],
]) {
test(`canary publisher rejects ${name} before changing any Git reference`, () => {
withCanaryGitFixture(({ git, pinned, attach, guard }) => {
const refs = git("show-ref");
const result = attach(overrides);
assert.equal(result.status, 1, result.stderr);
assert.equal(git("show-ref"), refs);
assert.equal(git("rev-parse", "HEAD"), pinned);
assert.equal(guard().status, 1, "the rejected checkout must remain detached");
});
});
}
test("canary publisher rejects a different valid source SHA before changing Git references", () => {
withCanaryGitFixture(({ git, pinned, newer, attach, guard }) => {
const refs = git("show-ref");
const result = attach({ SOURCE_SHA: newer });
assert.equal(result.status, 1, result.stderr);
assert.equal(git("show-ref"), refs);
assert.equal(git("rev-parse", "HEAD"), pinned);
assert.equal(guard().status, 1);
});
});
test("the original canary release guard still rejects a non-master local branch in Actions", () => {
withCanaryGitFixture(({ git, pinned, guard }) => {
git("checkout", "-b", "topic", pinned);
const refs = git("show-ref");
assert.equal(guard().status, 1);
assert.equal(git("symbolic-ref", "--short", "HEAD"), "topic");
assert.equal(git("show-ref"), refs);
});
});
test("canary branch attachment keeps exact-source checkout and artifact order in its publishing lane", () => {
const workflow = readWorkflow("release.yml");
const publish = workflow.split(" publish_canary:\n")[1].split(" smoke_canary_onboarding:\n")[0];
assert.equal(workflow.split("name: Attach verified canary source to local master").length, 2);
assert.match(publish, /ref: \$\{\{ github\.sha \}\}/);
assert.match(publish, /name: canary-smoke-lockfile-\$\{\{ github\.sha \}\}/);
const steps = ["Checkout repository", "Attach verified canary source to local master", "Install dependencies", "Save canary smoke lockfile", "Restore tracked install-time changes", "Publish canary"];
for (let i = 1; i < steps.length; i++) {
assert.ok(publish.indexOf(`name: ${steps[i - 1]}`) < publish.indexOf(`name: ${steps[i]}`));
}
assert.match(publish, /run: \.\/scripts\/release\.sh canary --skip-verify/);
assert.doesNotMatch(canaryAttachmentScript(), /git fetch|git pull|checkout (?:master|origin\/master)(?:\s|$)/);
});
test("source proof requires every source check and does not wait on image publication", () => {
const readiness = readWorkflow("cloud-readiness.yml");
const proof = readiness.split(" source_verified:\n")[1];
@@ -378,7 +505,7 @@ test("release verify workflow covers the same split test surface as stable PR ve
assert.match(buildJob, /persist-credentials: false/);
assert.doesNotMatch(buildJob, /cache: pnpm/);
for (const group of ["general-server-without-chat-or-native-runner", "general-chat", "general-workspaces-a", "general-workspaces-b"]) {
for (const group of ["general-server-without-chat-or-native-runner", "general-chat", "general-workspaces-a", "general-workspaces-b", "general-workspaces-c"]) {
assert.match(verifyWorkflow, new RegExp(`group: ${group}`));
}
for (const [group, count] of [["general-server-without-chat-or-native-runner", 10], ["general-chat", 3]]) {
@@ -705,3 +832,327 @@ test("nested ETARGET output does not retry a final authentication or network fai
assert.equal(result.calls.length, 1);
}
});
const exactCanary = "2026.1009.0-canary.1";
const canaryTarball = `https://registry.npmjs.org/@paperclipai/server/-/server-${exactCanary}.tgz`;
const tarballFailure = (url = canaryTarball, prefix = "npm error") => `${prefix} code E404\n${prefix} 404 Not Found - GET ${url} - Not found\n${prefix} 404\n${prefix} 404 The requested resource '@paperclipai/server@${url}' could not be found or you do not have permission to access it.\n`;
function tarballProof({ config = {}, manifest = {}, status = 200, redirected = false, responseUrl, rawBody } = {}) {
const calls = [];
const dist = { tarball: canaryTarball, integrity: `sha512-${Buffer.alloc(64).toString("base64")}`, ...manifest.dist };
const data = { name: "@paperclipai/server", version: exactCanary, ...manifest, dist };
return { calls, options: {
signal: new AbortController().signal, prefix: "/fixture/install", env: {},
runConfig: async (command, args, options) => {
calls.push({ kind: "config", command, args, options });
return { code: 0, stdout: "registry=https://registry.npmjs.org/\n@paperclipai:registry=undefined\n", ...config };
},
fetchMetadata: async (url, options) => {
calls.push({ kind: "metadata", url, options });
return { status, redirected, url: responseUrl ?? url, body: new Response(rawBody ?? JSON.stringify(data)).body };
},
} };
}
test("exact published tarball proof uses quiet effective config and fresh public metadata without credentials", async () => {
for (const prefix of ["npm error", "npm ERR!"]) {
const fixture = tarballProof();
assert.equal(await canRetryPublishedTarball404(tarballFailure(canaryTarball, prefix), exactCanary, fixture.options), true);
const [config, metadata] = fixture.calls;
assert.deepEqual(config.args, ["config", "get", "registry", "@paperclipai:registry", "--prefix", "/fixture/install"]);
assert.equal(config.options.env, fixture.options.env);
assert.equal(config.options.quiet, true);
assert.equal(config.options.captureStdout, true);
assert.equal(config.options.captureStderr, true);
assert.equal(config.options.outputLimit, 4096);
assert.equal(metadata.url, `https://registry.npmjs.org/%40paperclipai%2Fserver/${exactCanary}`);
assert.equal(metadata.options.signal, config.options.signal);
assert.equal(metadata.options.redirect, "error");
assert.equal(metadata.options.credentials, "omit");
assert.deepEqual(metadata.options.headers, { accept: "application/json", "cache-control": "no-cache" });
}
});
test("mixed npm errors and noncanonical or unreleased tarballs never read config or metadata", async () => {
const errors = [
"npm error code ETARGET\n", "npm error code E401\n", "npm error code ECONNRESET\n",
`${tarballFailure()}npm error code E401\n`, `${tarballFailure()}npm error code 1\n`,
`npm error code ENEEDAUTH\n${tarballFailure()}`, `${tarballFailure()}${tarballFailure()}`,
`${tarballFailure()}npm error 404 Not Found - GET https://registry.example.invalid/a.tgz - Not found\n`,
`${tarballFailure()}npm error 404 The requested resource 'other@${canaryTarball}' could not be found\n`,
tarballFailure().replace(" - GET ", " - PUT "),
...[
canaryTarball + "?token=fixture", canaryTarball + "#fragment", canaryTarball.replace("npmjs.org/", "npmjs.org:443/"),
canaryTarball.replace("npmjs.org/", "npmjs.org.example.invalid/"), canaryTarball.replace("npmjs.org/", "fixture@npmjs.org/"),
canaryTarball.replace("https:", "http:"), canaryTarball.replace("@paperclipai/server", "%40paperclipai%2Fserver"),
canaryTarball.replace("@paperclipai/server", "@paperclipai/../server"), canaryTarball.replace(exactCanary, "2026.1009.0-canary.2"),
"https://registry.npmjs.org/@paperclipai/not-released/-/not-released-2026.1009.0-canary.1.tgz",
"https://registry.npmjs.org/@paperclipai/plugin-createos/-/plugin-createos-2026.1009.0-canary.1.tgz",
"https://registry.npmjs.org/%40paperclipai%2Fserver/2026.1009.0-canary.1",
].map((url) => tarballFailure(url)),
];
for (const error of errors) {
const fixture = tarballProof();
assert.equal(await canRetryPublishedTarball404(error, exactCanary, fixture.options), false, error);
assert.deepEqual(fixture.calls, [], error);
}
for (const version of ["2026.1009.0", "2026.1009.0-nightly.1", "2026.1009.0-beta.1", "2026.1009.0-canary.1+build"]) {
const fixture = tarballProof();
assert.equal(await canRetryPublishedTarball404(tarballFailure(canaryTarball.replace(exactCanary, version)), version, fixture.options), false);
assert.deepEqual(fixture.calls, []);
}
});
test("effective registry authority respects scope precedence and rejects unknown or private config", async () => {
const configs = [
[{ stdout: "registry=https://registry.example.invalid/\n@paperclipai:registry=https://registry.npmjs.org/\n" }, true],
[{ stdout: "registry=undefined\n@paperclipai:registry=https://registry.npmjs.org/\n" }, true],
[{ stdout: "registry=https://registry.npmjs.org/\n@paperclipai:registry=https://registry.example.invalid/\n" }, false],
[{ stdout: "registry=https://registry.example.invalid/\n@paperclipai:registry=undefined\n" }, false],
[{ stdout: "registry=undefined\n@paperclipai:registry=undefined\n" }, false],
[{ stdout: "registry=https://registry.npmjs.org/\n@paperclipai:registry=\n" }, false],
[{ stdout: "registry=https://fixture:secret@registry.npmjs.org/\n@paperclipai:registry=undefined\n" }, false],
[{ stdout: "unexpected output\n" }, false], [{ code: 1 }, false], [{ signal: "SIGTERM" }, false], [{ outputTruncated: true }, false],
];
for (const [config, expected] of configs) {
const fixture = tarballProof({ config });
assert.equal(await canRetryPublishedTarball404(tarballFailure(), exactCanary, fixture.options), expected);
assert.equal(fixture.calls.filter((call) => call.kind === "metadata").length, expected ? 1 : 0);
}
});
test("metadata must identify the exact published artifact with valid SHA512 syntax, not merely exist", async () => {
const fixtures = [
{ status: 404 }, { status: 401 }, { status: 403 }, { status: 302 }, { redirected: true },
{ responseUrl: "https://registry.example.invalid/metadata" }, { rawBody: "not json" },
{ manifest: { name: "@paperclipai/shared" } }, { manifest: { version: "2026.1009.0-canary.2" } },
{ manifest: { dist: { tarball: canaryTarball + "?query=1" } } },
...[undefined, "", "sha512-A===", `sha256-${Buffer.alloc(32).toString("base64")}`, `sha512-${Buffer.alloc(64).toString("base64")} extra`]
.map((integrity) => ({ manifest: { dist: { integrity } } })),
{ rawBody: JSON.stringify({ padding: "x".repeat(65 * 1024) }) },
];
for (const input of fixtures) {
const fixture = tarballProof(input);
assert.equal(await canRetryPublishedTarball404(tarballFailure(), exactCanary, fixture.options), false, JSON.stringify(input).slice(0, 200));
}
});
test("rejected and oversized native response bodies cancel without waiting for slow or rejected cleanup", async () => {
for (const [status, pending] of [[200, true], [200, false], [404, true], [404, false]]) {
let cancelled = false;
const fixture = tarballProof();
fixture.options.fetchMetadata = async (url) => ({ status, redirected: false, url, body: new Response(new ReadableStream({
start(controller) { controller.enqueue(new Uint8Array(65 * 1024)); },
cancel() { cancelled = true; return pending ? new Promise(() => {}) : Promise.reject(new Error("fixture rejected cancellation")); },
})).body });
const started = Date.now();
assert.equal(await canRetryPublishedTarball404(tarballFailure(), exactCanary, fixture.options), false);
assert.equal(cancelled, true);
assert.ok(Date.now() - started < 1000, "cancellation acknowledgement must not extend a rejection");
}
});
test("aborting a stalled metadata read cancels its reader without waiting for acknowledgement", { timeout: 2000 }, async () => {
let cancelled = false;
const fixture = tarballProof();
fixture.options.fetchMetadata = async (url) => ({ status: 200, redirected: false, url,
body: new Response(new ReadableStream({
cancel() { cancelled = true; return new Promise(() => {}); },
})).body });
const budget = new AbortController();
const timer = setTimeout(() => budget.abort(new Error("fixture body budget expired")), 100);
const started = Date.now();
try {
await assert.rejects(canRetryPublishedTarball404(tarballFailure(), exactCanary, {
...fixture.options, signal: budget.signal,
}), /fixture body budget expired/);
assert.equal(cancelled, true);
assert.ok(Date.now() - started < 1000);
} finally { clearTimeout(timer); }
});
test("metadata headers cannot outlive the budget and late response bodies are cancelled", { timeout: 2000 }, async () => {
let headersArrive;
let cancelled = false;
const fixture = tarballProof();
fixture.options.fetchMetadata = (url) => new Promise((resolve) => {
headersArrive = () => resolve({ status: 200, redirected: false, url,
body: new Response(new ReadableStream({ cancel() { cancelled = true; } })).body });
});
const budget = new AbortController();
const timer = setTimeout(() => budget.abort(new Error("fixture headers budget expired")), 100);
const started = Date.now();
try {
await assert.rejects(canRetryPublishedTarball404(tarballFailure(), exactCanary, {
...fixture.options, signal: budget.signal,
}), /fixture headers budget expired/);
assert.ok(Date.now() - started < 1000);
headersArrive();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(cancelled, true);
} finally { clearTimeout(timer); }
});
test("real npm effective registry reads isolated prefix, user, and environment configuration", async () => {
const root = mkdtempSync(path.join(os.tmpdir(), "canary-config-proof-"));
mkdirSync(path.join(root, "prefix"));
writeFileSync(path.join(root, "global.npmrc"), "");
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toLowerCase().startsWith("npm_config_")));
env.npm_config_userconfig = path.join(root, "user.npmrc");
env.npm_config_globalconfig = path.join(root, "global.npmrc");
try {
for (const [user, project, override, expected] of [
["registry=https://registry.npmjs.org/\n", "", undefined, true],
["registry=https://registry.example.invalid/\n", "@paperclipai:registry=https://registry.npmjs.org/\n", undefined, true],
["registry=https://registry.npmjs.org/\n", "@paperclipai:registry=https://registry.example.invalid/\n", undefined, false],
["registry=https://registry.npmjs.org/\n", "", "https://registry.example.invalid/", false],
]) {
writeFileSync(path.join(root, "user.npmrc"), user);
writeFileSync(path.join(root, "prefix", ".npmrc"), project);
const fixture = tarballProof();
delete fixture.options.runConfig;
assert.equal(await canRetryPublishedTarball404(tarballFailure(), exactCanary, {
...fixture.options, prefix: path.join(root, "prefix"), env: { ...env, ...(override ? { npm_config_registry: override } : {}) },
}), expected);
assert.equal(fixture.calls.length, expected ? 1 : 0);
}
} finally { rmSync(root, { recursive: true, force: true }); }
});
async function stalledMetadata(run) {
let closed = false;
let closing = false;
let observeClose;
const connectionClosed = new Promise((resolve) => { observeClose = resolve; });
const server = createServer((_request, response) => {
response.on("close", () => { closed = true; observeClose(); });
response.writeHead(200, { "content-type": "application/json" });
response.write('{"name":');
});
// An HTTP client can replace an aborted pooled connection while shutdown
// starts. Own late connections too, so server.close cannot wait on them.
server.on("connection", (socket) => { if (closing) socket.destroy(); });
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const fixture = tarballProof();
fixture.options.fetchMetadata = async (url, options) => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/metadata`, options);
Object.defineProperty(response, "url", { value: url });
return response;
};
let closeDeadline;
try {
await run(fixture.options);
await Promise.race([connectionClosed, new Promise((_, reject) => {
closeDeadline = setTimeout(() => reject(new Error("metadata connection outlived cancellation")), 1000);
})]);
assert.equal(closed, true, "metadata connection must close before fixture-forced cleanup");
}
finally {
clearTimeout(closeDeadline);
closing = true;
await new Promise((resolve) => {
server.close(resolve);
server.closeAllConnections();
});
}
}
test("shared acquisition cancellation aborts the metadata body before the lookup deadline", async () => {
await stalledMetadata(async (options) => {
const budget = new AbortController();
const timer = setTimeout(() => budget.abort(new Error("fixture shared budget expired")), 250);
try {
await assert.rejects(canRetryPublishedTarball404(tarballFailure(), exactCanary, { ...options, signal: budget.signal }), /fixture shared budget expired/);
} finally { clearTimeout(timer); }
});
});
test("the short config and metadata deadline also covers a stalled real HTTP body", { timeout: 10_000 }, async () => {
assert.equal(TARBALL_METADATA_TIMEOUT_MS, 5000);
const started = Date.now();
await stalledMetadata(async (options) => {
assert.equal(await canRetryPublishedTarball404(tarballFailure(), exactCanary, options), false);
});
assert.ok(Date.now() - started < 7000, "metadata must not consume the 120s acquisition budget");
});
test("a verified canary tarball404 retries acquisition and runs onboarding once", async () => {
const result = await canaryStartup({ mode: "tarball-recover" });
assert.equal(result.code, 0, result.output);
assert.equal(result.calls.filter((call) => call.kind === "npm").length, 2);
assert.equal(result.calls.filter((call) => call.kind === "config").length, 1);
assert.equal(result.calls.filter((call) => call.kind === "metadata").length, 1);
assert.equal(result.calls.filter((call) => call.kind === "onboard").length, 1);
assert.doesNotMatch(result.output, /fixture config diagnostic/);
});
test("persistent promised tarball404s stop at three installs without a final lookup or onboarding", async () => {
const result = await canaryStartup({ mode: "tarball-permanent" });
assert.equal(result.code, 1);
assert.equal(result.calls.filter((call) => call.kind === "npm").length, 3);
assert.equal(result.calls.filter((call) => call.kind === "config").length, 2);
assert.equal(result.calls.filter((call) => call.kind === "metadata").length, 2);
assert.equal(result.calls.filter((call) => call.kind === "onboard").length, 0);
assert.match(result.output, /installation failed.*onboarding was not started/);
});
test("private or oversized config and unpublished metadata404 fail without retry or leaking config", async () => {
for (const input of [{ config: "private" }, { config: "large" }, { metadata: "missing" }]) {
const result = await canaryStartup({ mode: "tarball-permanent", ...input });
assert.equal(result.code, 1);
assert.equal(result.calls.filter((call) => call.kind === "npm").length, 1);
assert.equal(result.calls.filter((call) => call.kind === "onboard").length, 0);
assert.doesNotMatch(result.output, /fixture-user|fixture-password|fixture config diagnostic/);
}
});
test("truncated npm output cannot hide an earlier auth failure and qualify a tarball retry", async () => {
const result = await canaryStartup({ mode: "tarball-large" });
assert.equal(result.code, 1);
assert.equal(result.calls.filter((call) => call.kind === "npm").length, 1);
assert.equal(result.calls.filter((call) => call.kind === "config").length, 0);
assert.equal(result.calls.filter((call) => call.kind === "onboard").length, 0);
});
test("tarball recovery does not replay onboarding failures or change ETARGET for other exact versions", async () => {
const failed = await canaryStartup({ mode: "tarball-recover", onboard: "fail" });
assert.equal(failed.code, 1);
assert.equal(failed.calls.filter((call) => call.kind === "npm").length, 2);
assert.equal(failed.calls.filter((call) => call.kind === "onboard").length, 1);
assert.match(failed.output, /onboarding failed \(exit 17\)/);
const other = await canaryStartup({ mode: "recover", version: "2026.1009.0-nightly.1" });
assert.equal(other.code, 0, other.output);
assert.equal(other.calls.filter((call) => call.kind === "npm").length, 2);
assert.equal(other.calls.filter((call) => call.kind === "onboard").length, 1);
assert.equal(other.calls.filter((call) => call.kind === "config").length, 0);
});
test("existing ETARGET character-tail behavior survives long multibyte npm diagnostics", async () => {
const result = await canaryStartup({ mode: "multibyte-recover" });
assert.equal(result.code, 0, result.output);
assert.equal(result.calls.filter((call) => call.kind === "npm").length, 2);
assert.equal(result.calls.filter((call) => call.kind === "onboard").length, 1);
assert.equal(result.calls.filter((call) => call.kind === "config").length, 0);
});
test("metadata lookup and backoff both consume the unchanged shared acquisition budget", async () => {
for (const input of [{ metadata: "hang" }, { delay: 5000 }]) {
const result = await canaryStartup({ mode: "tarball-permanent", budget: 1000, ...input });
assert.equal(result.code, 1);
assert.equal(result.calls.filter((call) => call.kind === "npm").length, 1);
assert.equal(result.calls.filter((call) => call.kind === "onboard").length, 0);
assert.match(result.output, /exceeded its startup budget/);
assert.ok(result.elapsed < 4000, `shared-budget cancellation took ${result.elapsed}ms`);
}
});
test("cancellation reaps a config process and its descendant that ignore SIGTERM", async () => {
const result = await canaryStartup({ mode: "tarball-permanent", config: "hang", cancelAtKind: "config-descendant" });
assert.equal(result.code, 1);
assert.equal(result.calls.filter((call) => call.kind === "npm").length, 1);
assert.equal(result.calls.filter((call) => call.kind === "onboard").length, 0);
for (const child of result.calls.filter((call) => ["config", "config-descendant"].includes(call.kind))) {
assert.throws(() => process.kill(child.pid, 0), { code: "ESRCH" });
}
assert.match(result.output, /stopped by SIGTERM/);
});
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -783,7 +783,7 @@ const apps = [
{
serverUrl: "https://mcp.sentry.dev/mcp",
discoveryUrl:
"https://sentry.io/.well-known/oauth-authorization-server",
"https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp",
},
"S2",
"Connect the Sentry organization and projects agents need for incident work.",
+60
View File
@@ -0,0 +1,60 @@
// Background downloads for verification scripts: start a child early with its
// output in a log file, join it where the result is needed, and stop it before
// the scratch directory it writes into is removed. No shell, no inherited
// terminal, and a failure is reported where the caller awaits it.
import { spawn } from 'node:child_process';
import { closeSync, openSync, readFileSync, statSync } from 'node:fs';
const running = child => child.pid !== undefined && child.exitCode === null && child.signalCode === null;
// Returns { name, child, done, durationMs }. `done` resolves on exit code 0
// and otherwise rejects with the tail of the log; the rejection is observed
// here so an unawaited failure never surfaces as an unhandled rejection.
export function startPrefetch({ name, cmd, args, cwd, env, logPath }) {
const startedAt = Date.now();
const log = openSync(logPath, 'w');
let child;
try {
child = spawn(cmd, args, { cwd, env, stdio: ['ignore', log, log] });
} finally {
closeSync(log); // the child holds its own descriptor
}
const handle = { name, child, done: null, durationMs: null };
let settled = false;
handle.done = new Promise((settle, reject) => {
const finish = failure => {
if (settled) return;
settled = true;
// The caller may be blocked in synchronous work when the child exits, so
// this event can arrive long after the fact. When the child wrote
// anything, its last write is the end time; both downloads this serves
// print their final status line as they complete. A silent child falls
// back to the time the exit was observed.
let finishedAt = Date.now();
try {
const { mtimeMs, size } = statSync(logPath);
if (size > 0) finishedAt = Math.min(finishedAt, mtimeMs);
} catch {}
handle.durationMs = Math.max(0, Math.round(finishedAt - startedAt));
if (failure === null) return settle();
let output = '';
try { output = readFileSync(logPath, 'utf8').trim().slice(-2000); } catch {}
reject(new Error(`${name} prefetch failed (${failure}): ${output}`));
};
child.once('error', error => finish(error.message));
child.once('exit', (code, signal) => finish(code === 0 ? null : (signal ?? `exit ${code}`)));
});
handle.done.catch(() => {});
return handle;
}
// Stops every prefetch that is still running and resolves only once all of
// them have exited, so the caller can remove their working directory without
// racing a write. A child that ignores SIGTERM is killed after `graceMs`.
export async function stopPrefetches(prefetches, { graceMs = 5000 } = {}) {
await Promise.all(prefetches.map(async ({ child, done }) => {
if (running(child)) child.kill('SIGTERM');
const escalate = setTimeout(() => { if (running(child)) child.kill('SIGKILL'); }, graceMs);
try { await done; } catch {} finally { clearTimeout(escalate); }
}));
}
+49 -4
View File
@@ -4,12 +4,13 @@
// explicit and separate from npm installation, and is removed in finally.
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { materializePublishManifest, prepareBundledPackage } from './prepare-bundled-package.mjs';
import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource } from './grok-public-install-sandbox.mjs';
import { startPrefetch, stopPrefetches } from './prefetch-child.mjs';
import { retainRunnerQualificationPackages } from './retain-runner-qualification-packages.mjs';
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
assert.equal(process.platform, 'linux', 'Run this verification on disposable EC2 Linux, not a developer host');
@@ -19,7 +20,31 @@ const env = { ...process.env, NODE_PATH: '', PAPERCLIP_RELEASE_REUSE_UI_DIST: '1
const run = (cmd, args, cwd = root) => execFileSync(cmd, args, { cwd, env, stdio: 'pipe', maxBuffer: 32 * 1024 * 1024 });
const sourceRevision = run('git', ['rev-parse', 'HEAD'], repo).toString().trim();
const releaseVersion = `0.0.0-grok-verify.${sourceRevision.slice(0, 12)}`;
// The two network downloads the probes need do not depend on anything packed
// below, so they overlap the CPU-bound staging instead of running after it.
// The consumer image is pinned by digest and the Grok binary is checked against
// its pinned sha256 by the provisioning script, so an early start changes no
// verified property. Neither touches the consumer, the assets, nor the
// `native/grok` path that the post-install assertion inspects.
const prefetched = join(root, 'prefetch'); mkdirSync(prefetched);
const stagedGrok = join(prefetched, 'grok');
const prefetches = [];
const timing = {};
// A prefetch failure surfaces where its result is awaited, never as an
// unhandled rejection that would mask an earlier staging error.
const prefetch = (name, cmd, args) => {
const handle = startPrefetch({ name, cmd, args, cwd: root, env, logPath: join(prefetched, `${name}.log`) });
prefetches.push(handle);
return handle.done;
};
let phaseStarted = performance.now();
const phase = name => { const now = performance.now(); timing[`${name}_ms`] = Math.round(now - phaseStarted); phaseStarted = now; };
const awaited = async (name, promise) => { const started = performance.now(); await promise; timing[`${name}_wait_ms`] = Math.round(performance.now() - started); };
try {
const imageReady = prefetch('image', 'docker', ['pull', '--platform', 'linux/amd64', GROK_PUBLIC_INSTALL_IMAGE]);
// Provision as the unprivileged verification user, never into the host's /opt.
// Only the positive probe sees this file at the canonical sandbox path.
const grokReady = prefetch('grok', process.execPath, [join(repo, 'packages/paperclip-runner/scripts/provision-grok.mjs'), stagedGrok]);
const listing = run(process.execPath, [join(repo, 'scripts/release-package-map.mjs'), 'list'], repo).toString().trim().split('\n').map(line => line.split('\t'));
const packages = new Map(listing.map(([dir, name]) => [name, { dir, manifest: JSON.parse(readFileSync(join(repo, dir, 'package.json'), 'utf8')) }]));
const needed = new Set();
@@ -81,9 +106,12 @@ try {
const sentinel = join(consumer, 'node_modules/paperclip-verification-lifecycle-sentinel/lifecycle-ran');
const consumerUid = process.getuid();
const isolated = (command, options = {}) => run('docker', grokConsumerDockerArgs({ assets, consumer, cache, uid: consumerUid, gid: process.getgid(), command, ...options }));
phase('stage_packages');
await awaited('image', imageReady);
// npm resolution is intentionally the public consumer graph, not the pnpm
// workspace graph. Freeze that result before any lifecycle script can run.
isolated(['npm', 'install', '--ignore-scripts', '--omit=dev', ...readdirSync(assets).filter(file => file.endsWith('.tgz')).map(file => `/packages/${file}`)], { download: true });
phase('consumer_install');
assert.equal(existsSync(sentinel), false, 'Dependency download must not run lifecycle scripts');
const consumerLock = readFileSync(join(consumer, 'package-lock.json'), 'utf8');
// npm ci rejects bundled optional platform dependencies absent from its own
@@ -92,6 +120,7 @@ try {
isolated(GROK_PUBLIC_INSTALL_LIFECYCLE);
assert.equal(readFileSync(sentinel, 'utf8'), 'ok', 'Offline lifecycle scripts must actually execute');
assert.equal(readFileSync(join(consumer, 'package-lock.json'), 'utf8'), consumerLock, 'Lifecycle execution must preserve the resolved consumer lock');
phase('lifecycle_rebuild');
for (const name of needed) {
const installedManifest = JSON.parse(readFileSync(join(consumer, 'node_modules', name, 'package.json'), 'utf8'));
assert.equal(installedManifest.version, releaseVersion, `Installed release version for ${name}`);
@@ -104,6 +133,7 @@ try {
writeFileSync(join(assets, 'codex-probe.mjs'), installedCodexProbeSource(
'/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/index.js', '/consumer', codexVersion), { mode: 0o644 });
const codex = JSON.parse(isolated(['node', '/packages/codex-probe.mjs']).toString().trim());
phase('codex_probe');
assert.equal(codex.codexConsumerHostOnly, true);
assert.equal(codex.codexPlatformPackageSource, 'official npm');
assert.ok(existsSync(join(installed, 'providers/grok/launcher.cjs')));
@@ -122,10 +152,14 @@ try {
`;
writeFileSync(join(assets, 'probe.mjs'), probe, { mode: 0o644 });
isolated(['node', '/packages/probe.mjs', 'missing']);
// Provision as the unprivileged verification user, never into the host's /opt.
// Only the positive probe sees this file at the canonical sandbox path.
run(process.execPath, [join(repo, 'packages/paperclip-runner/scripts/provision-grok.mjs'), prerequisite]);
// The binary was provisioned outside `native/grok` while the packages were
// staged, so the assertion above still proves npm put nothing there. It moves
// into place only now, so only the positive probe sees it.
await awaited('grok', grokReady);
mkdirSync(dirname(prerequisite), { recursive: true });
renameSync(stagedGrok, prerequisite);
isolated(['node', '/packages/probe.mjs', 'present'], { prerequisite });
phase('grok_probes');
console.log(JSON.stringify({ schema: 'paperclip.grok.public-npm-install.v1', sourceRevision, releaseVersion, lifecycleScriptsEnabled: true, lifecycleSentinelVerified: true, lifecycleNetwork: 'none', consumerImage: GROK_PUBLIC_INSTALL_IMAGE, consumerUid, consumerLockPreserved: true, cleanNpmInstall: true, packageCount: needed.size, codexPackedPayloadsOmitted: true, codexPackedPackagesChecked: tarballs.length, ...codex, builtinLauncherPresent: true, separateGrokPackage: false, npmProvisionedBinary: false, missingPrerequisiteRejected: true, provisionedBinaryVerified: true, commandLeaseVerified: true, providerCalls: 0 }));
// Exercise Pi's public CLI and installed server, never a private workspace
// package or binary override. Public dependency downloads are explicit and
@@ -137,6 +171,7 @@ try {
// temporary capacity than the smaller offline lifecycle probes.
const setup = isolated(['node', '/consumer/node_modules/paperclipai/dist/index.js', 'runtime', 'setup', 'pi'], { download: true, temporarySizeMiB: 2048 }).toString();
const receipt = JSON.parse(setup.trim());
phase('pi_setup');
assert.equal(receipt.status, 'installed_verified');
assert.equal(receipt.target, 'linux-x64');
assert.equal(readFileSync(join(consumer, 'package-lock.json'), 'utf8'), consumerLock, 'Pi setup must preserve the consumer dependency graph');
@@ -144,6 +179,13 @@ try {
// Docker defaults tmpfs to noexec. The offline admission probe must execute
// its verified private snapshot while keeping lifecycle/download scratch noexec.
console.log(isolated(['node', '/packages/pi-public-install-probe.mjs', '/consumer/node_modules/@paperclipai/server'], { temporarySizeMiB: 2048, temporaryExecutable: true }).toString().trim());
phase('pi_probe');
// Wall time per phase, so the slow part of this step is visible in the CI log
// without re-running it. `*_prefetch_ms` runs from a download's start to its
// last output, and `*_wait_ms` is how long the main flow waited for a
// prefetch that had not finished yet; zero means the overlap hid it entirely.
const downloads = Object.fromEntries(prefetches.map(({ name, durationMs }) => [`${name}_prefetch_ms`, durationMs]));
console.log(JSON.stringify({ schema: 'paperclip.public-npm-install.timing.v1', ...timing, ...downloads }));
if (process.env.PAPERCLIP_RUNNER_QUALIFICATION_PACKAGES_DIR) {
const retained = retainRunnerQualificationPackages({ repo, output: process.env.PAPERCLIP_RUNNER_QUALIFICATION_PACKAGES_DIR, sourceRevision, releaseVersion, env,
publicArchives: [...needed].map((name, index) => ({ name, file: tarballs[index] })),
@@ -151,5 +193,8 @@ try {
console.log(JSON.stringify(retained));
}
} finally {
// An earlier failure must not leave a prefetch running, and scratch is
// removed only once both children have stopped writing into it.
await stopPrefetches(prefetches);
rmSync(root, { recursive: true, force: true });
}