fix(release): retry incomplete canary dependency publications (#15743)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Release checks must test the exact package that a new user installs.
> - The canary onboarding smoke uses a fresh npm dependency graph.
> - An upstream package can reference a dependency before that version
is available.
> - The smoke then exits before Paperclip onboarding starts.
> - This pull request retries only that npm acquisition failure within
the existing startup limit.
> - Onboarding still runs once, and all other errors remain visible.

## Linked Issues or Issue Description

**What happened?**

[Release run
37986221440](https://github.com/paperclipai/paperclip/actions/runs/37986221440)
published `2026.1009.0-canary.13`, then failed the onboarding smoke. The
retained server log contains npm `ETARGET` for
`@aws-sdk/credential-provider-env@^3.972.73`. The upstream parent
package was published before this dependency. The missing version became
available during the smoke startup. Paperclip onboarding never ran.

**Expected behavior**

Retry a short dependency publication window before onboarding starts.
Stop on a permanent install failure. Never repeat onboarding to hide a
startup failure.

**Steps to reproduce**

1. Start the exact-version canary smoke with an empty npm cache.
2. Make the first npm install return `ETARGET` because a dependency
version is not available.
3. Make the next install succeed after registry metadata changes.
4. Confirm that onboarding starts once. Repeat with permanent `ETARGET`
and an unrelated failure; onboarding must not start.

**Paperclip version or commit**

The observed release source was
`cb291bf1298ab484a2792c05eb977f3440f1f351`.

**Deployment mode**

Linux release CI. The change affects the canary smoke harness.

Related: #15712 fixes a separate lockfile mismatch in the smoke's
repository dependency install. This change covers the fresh
published-package npm install.

## What Changed

- Separate npm package acquisition from the onboarding command.
- Retry only the final npm `ETARGET` error, up to three attempts with
online metadata and clean temporary prefixes.
- Share a two-minute acquisition budget across attempts and backoff.
Keep the existing five-minute Playwright startup limit.
- Run the installed exact-version CLI once. Preserve authentication,
network, lifecycle, and onboarding failures.
- Stop owned process groups on cancellation and remove owned install
prefixes. Keep server logs and instance data for diagnostics.
- Keep dependency-free helper subprocess tests in the required policy
lane. Run real Playwright lifecycle tests in the required
release-registry lane after its dependencies are installed.
- Document the bounded behavior in the release runbook.

## Verification

- `node --test scripts/__tests__/release-verify-workflow.test.mjs`: 24
passed in a clean source snapshot with no `node_modules`. These cover
transient and permanent missing versions, other npm errors, nested error
codes, onboarding failure, deadline expiry, and cancellation.
- `pnpm test:release-registry`: 153 passed, including real Playwright
teardown with a descendant that ignores SIGTERM and startup-timeout
cleanup of a detached npm installer.
- `pnpm -r typecheck`: passed.
- `pnpm build`: passed.
- `pnpm test:run`: deliberately stopped after complete hosted CI passed;
this is not a local full-suite pass. The run's 15 warm-runtime real-DB
cases failed before assertions because the local macOS PostgreSQL
package lacked library symlinks after installation with
`--ignore-scripts`. After running the package's local hydration step,
all 15 affected cases passed in a targeted rerun. The remaining
aggregate was stopped with exact owned-process cleanup.
- [Hosted
CI](https://github.com/paperclipai/paperclip/actions/runs/37994486323)
is complete and green at `1c80e6f`: all tests, build, typecheck, policy,
release registry, E2E, and canary dry run passed. Greptile scored the
same head 5/5 with no unresolved comments.
- Independent review covered all seven changed files and the exact
policy and release-registry commands. It also used real npm 11.9 against
a loopback registry: a required version was absent, then became
available. The retry refreshed metadata and started the installed
exact-version CLI once. The one-attempt negative control failed.
- The new subprocess tests use local npm and CLI fixtures. They do not
contact a registry or start a real Paperclip instance.
- The patch preserves the exact-version clean-install check. It adds no
dependency pins, credentials, or workflow reruns.

## Risks

The install phase now has a two-minute budget inside the existing
five-minute startup limit. An unusually slow valid install can still
fail the smoke. Permanent missing versions remain failures after the
bounded retry. The lifecycle tests cover the Linux release runner
behavior; Playwright does not support graceful SIGTERM on Windows. No
application, database, or deployment behavior changes.

## Model Used

OpenAI GPT-6 through Codex, with reasoning and code execution tools. The
exact service variant and context window are not exposed in this
session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` /
`Closes: #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-10-09 17:15:02 -07:00
1 parent 23b9aaa8e6
commit 935fb63ed5
7 files changed
+369 -7

No files matched your search

+1
View File
@@ -100,6 +100,7 @@ It:
- publishes the user-facing `paperclipai` package last, so `paperclipai@canary` does not advance before the full package set exists
- verifies that `canary` resolves to the just-published version and that published internal dependencies exist on npm
- installs `paperclipai@canary` into a clean temporary prefix as the final npm gate
- starts the exact published canary through a separate fresh npm install for the onboarding smoke; only npm `ETARGET` install failures retry, up to three attempts within two minutes, before onboarding runs once under the existing five-minute startup deadline
- fails by default if npm leaves `latest` pointing at a canary; use `--allow-canary-latest` only when that state is intentional
- creates a git tag `canary/vYYYY.MDD.P-canary.N`
+1 -1
View File
@@ -61,7 +61,7 @@
"smoke:posthog-live": "node scripts/smoke/posthog-live.mjs",
"smoke:pipelines-tutorial": "./scripts/smoke/pipelines-tutorial-smoke.sh",
"smoke:terminal-bench-loop-skill": "node scripts/smoke/terminal-bench-loop-skill-smoke.mjs",
"test:release-registry": "node --test scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs",
"test:release-registry": "node --test scripts/__tests__/canary-startup-playwright.test.mjs scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs",
"storybook-visual:baseline": "node scripts/storybook-visual-baseline.mjs",
"test:storybook-visual": "node scripts/storybook-visual-baseline.mjs download && node scripts/storybook-visual-baseline.mjs verify && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts",
"test:storybook-visual:update": "node scripts/storybook-visual-baseline.mjs download && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts --update-snapshots && node scripts/storybook-visual-baseline.mjs pack",
@@ -0,0 +1,114 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import os from "node:os";
import net from "node:net";
import path from "node:path";
import { fileURLToPath } from "node:url";
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 }) {
const root = mkdtempSync(path.join(os.tmpdir(), "canary-startup-test-"));
const calls = path.join(root, "calls.jsonl");
const fixtureBin = path.join(root, "bin");
mkdirSync(fixtureBin);
const npmFixture = path.join(fixtureBin, "npm");
const port = await new Promise((resolve, reject) => {
const server = net.createServer();
server.on("error", reject);
server.listen(0, "127.0.0.1", () => { const port = server.address().port; server.close(() => resolve(port)); });
});
const cli = `#!/usr/bin/env node
const { appendFileSync } = require("node:fs");
appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"onboard", pid:process.pid, args:process.argv.slice(2)}) + "\\n");
if (process.env.FIXTURE_ONBOARD === "fail") { console.error("npm error code ETARGET"); process.exit(17); }
if (process.env.FIXTURE_ONBOARD === "hang") { setTimeout(() => {}, 10000); }
if (process.env.FIXTURE_ONBOARD === "serve") {
const { spawn } = require("node:child_process");
const child = spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>{}); setTimeout(()=>process.exit(0),10000)"], {stdio:"ignore"});
appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"descendant", pid:child.pid}) + "\\n");
process.on("SIGTERM", () => {});
setTimeout(() => process.exit(0), 10000);
require("node:http").createServer((req,res) => {res.end("ok");}).listen(Number(process.env.FIXTURE_PORT), "127.0.0.1");
}
`;
writeFileSync(npmFixture, `#!/usr/bin/env node
const fs = require("node:fs");
const path = require("node:path");
const args = process.argv.slice(2);
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 === "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 {
const prefix = args[args.indexOf("--prefix") + 1];
const bin = path.join(prefix, "node_modules", ".bin");
fs.mkdirSync(bin, {recursive:true});
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}}); }
catch (error) { console.error(error.message); process.exitCode = 1; }
`);
const playwrightConfig = path.join(root, "playwright.config.mjs");
if (playwright) {
const originalConfig = path.join(repoRoot, "tests/canary-onboarding/playwright.config.ts");
const testApi = new URL("../../node_modules/@playwright/test/index.mjs", import.meta.url).href;
writeFileSync(path.join(root,"fixture.spec.mjs"), `import { test } from ${JSON.stringify(testApi)}; test("fixture", async()=>{});`);
writeFileSync(playwrightConfig, `import original from ${JSON.stringify(originalConfig)};
export default {...original, testDir:${JSON.stringify(root)}, testMatch:"fixture.spec.mjs", reporter:"list", projects:[{name:"fixture"}], webServer:{...original.webServer, timeout:${mode === "hang" ? 2500 : 300000}}};`);
}
const started = Date.now();
try {
const result = await new Promise((resolve, reject) => {
const child = spawn(process.execPath, playwright
? [path.join(repoRoot, "node_modules/@playwright/test/cli.js"), "test", "--config", playwrightConfig]
: cancelAtKind
? [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"),
npm_config_cache: path.join(root, "fresh-cache"),
}, stdio: ["ignore", "pipe", "pipe"] });
let output = "";
const cancellation = cancelAtKind && setInterval(() => {
if (!existsSync(calls)) return;
const rows = readFileSync(calls, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse);
if (rows.some(row => row.kind === cancelAtKind)) {
clearInterval(cancellation);
child.kill("SIGTERM");
}
}, 10);
child.stdout.on("data", (data) => { output += data; });
child.stderr.on("data", (data) => { output += data; });
child.on("error", reject);
child.on("close", (code) => { clearInterval(cancellation); resolve({code, output}); });
});
if (playwright && existsSync(path.join(root,"server.log"))) result.output += readFileSync(path.join(root,"server.log"), "utf8");
const records = existsSync(calls) ? readFileSync(calls,"utf8").trim().split("\n").filter(Boolean).map(JSON.parse) : [];
const prefixes = records.filter(call => call.kind === "npm").map(call => call.args[call.args.indexOf("--prefix") + 1]);
if (playwright) {
const deadline = Date.now() + 2000;
while (prefixes.some(prefix => existsSync(prefix)) && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 20));
}
}
assert.deepEqual(prefixes.filter(prefix => existsSync(prefix)), [], "helper-owned install prefixes must be removed");
return { ...result, elapsed: Date.now()-started, calls: records };
} finally { rmSync(root, {recursive:true, force:true}); }
}
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import test from "node:test";
import { canaryStartup } from "./canary-startup-fixture.mjs";
test("actual Playwright teardown stops the CLI and descendants that ignore SIGTERM", async () => {
const result = await canaryStartup({ mode: "success", onboard: "serve", playwright: true });
assert.equal(result.code, 0, result.output);
assert.equal(result.calls.filter(call => call.kind === "onboard").length, 1);
const processes = result.calls.filter(call => ["onboard", "descendant"].includes(call.kind));
assert.equal(processes.length, 2);
for (const call of processes) {
const deadline = Date.now() + 2000;
while (Date.now() < deadline) {
try { process.kill(call.pid, 0); } catch (error) { if (error.code === "ESRCH") break; throw error; }
await new Promise(resolve => setTimeout(resolve, 20));
}
assert.throws(() => process.kill(call.pid, 0), {code:"ESRCH"}, `fixture ${call.kind} outlived bounded teardown`);
}
});
test("actual Playwright startup timeout cancels a detached npm install", async () => {
const result = await canaryStartup({ mode: "hang", playwright: true });
assert.equal(result.code, 1);
const installs = result.calls.filter(call => call.kind === "npm");
assert.equal(installs.length, 1, result.output);
assert.equal(result.calls.filter(call => call.kind === "onboard").length, 0);
assert.throws(() => process.kill(installs[0].pid,0), {code:"ESRCH"});
assert.ok(result.elapsed < 10000, `startup timeout did not stop npm: ${result.elapsed}ms`);
});
@@ -5,6 +5,7 @@ import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { canaryStartup } from "./canary-startup-fixture.mjs";
const repoRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -574,3 +575,94 @@ test("direct protocol concurrency override only lowers the configured ceiling",
if (expected !== null) assert.equal(result.stdout, expected);
}
});
test("canary startup refreshes an incomplete dependency publication, then onboards once", async () => {
const result = await canaryStartup({ mode: "recover" });
assert.equal(result.code, 0, result.output);
const installs = result.calls.filter(call => call.kind === "npm");
const onboarding = result.calls.filter(call => call.kind === "onboard");
assert.equal(installs.length, 2);
assert.equal(onboarding.length, 1);
for (const call of installs) {
assert.equal(call.args[0], "install");
assert.ok(call.args.includes("paperclipai@2026.1009.0-canary.1"));
assert.ok(call.args.includes("--no-package-lock"));
assert.ok(call.args.includes("--no-save"));
}
assert.ok(!installs[0].args.includes("--prefer-online"));
assert.ok(installs[1].args.includes("--prefer-online"));
assert.notEqual(installs[0].args[2], installs[1].args[2]);
assert.equal(installs[0].cache, installs[1].cache);
assert.deepEqual(onboarding[0].args.slice(0, 3), ["onboard", "--yes", "--data-dir"]);
});
test("permanent missing versions stop after three attempts without onboarding", async () => {
const result = await canaryStartup({ mode: "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 === "onboard").length, 0);
assert.match(result.output, /installation failed.*onboarding was not started/);
});
test("npm failures other than ETARGET fail immediately without onboarding", async () => {
const result = await canaryStartup({ mode: "auth" });
assert.equal(result.code, 1);
assert.equal(result.calls.length, 1);
assert.match(result.output, /E401/);
});
test("onboarding failures are never retried, even when they mention ETARGET", async () => {
const result = await canaryStartup({ mode: "success", onboard: "fail" });
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, 1);
assert.match(result.output, /onboarding failed \(exit 17\)/);
});
test("a hanging npm install is stopped within the shared acquisition budget", async () => {
const result = await canaryStartup({ mode: "hang", budget: 1000 });
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.ok(result.elapsed < 4000, `install exceeded bounded cancellation: ${result.elapsed}ms`);
assert.match(result.output, /exceeded its startup budget/);
});
test("backoff consumes the shared budget and does not begin another install after expiry", async () => {
const result = await canaryStartup({ mode: "permanent", budget: 1000, delay: 5000 });
assert.equal(result.code, 1);
assert.equal(result.calls.length, 1);
assert.match(result.output, /exceeded its startup budget/);
});
test("Playwright cancellation stops an onboarding process without replay", async () => {
const result = await canaryStartup({ mode: "success", onboard: "hang", cancelAtKind: "onboard" });
assert.equal(result.code, 1);
assert.equal(result.calls.filter(call => call.kind === "npm").length, 1);
const onboarding = result.calls.filter(call => call.kind === "onboard");
assert.equal(onboarding.length, 1);
assert.throws(() => process.kill(onboarding[0].pid, 0), {code:"ESRCH"});
assert.match(result.output, /stopped by SIGTERM/);
assert.ok(result.elapsed < 2500, `onboarding cancellation took ${result.elapsed}ms`);
});
test("canary install retries retain the existing overall Playwright startup deadline", async () => {
const { INSTALL_BUDGET_MS } = await import("../../tests/canary-onboarding/start-published-canary.mjs");
const config = readFileSync(path.join(repoRoot, "tests/canary-onboarding/playwright.config.ts"), "utf8");
assert.equal(INSTALL_BUDGET_MS, 120_000);
assert.match(config, /timeout: 300_000/);
assert.match(config, /start-published-canary\.mjs/);
assert.match(config, /reuseExistingServer: false/);
});
test("nested ETARGET output does not retry a final authentication or network failure", async () => {
for (const mode of ["mixed", "network"]) {
const result = await canaryStartup({ mode });
assert.equal(result.code, 1);
assert.equal(result.calls.length, 1);
}
});
+5 -6
View File
@@ -34,12 +34,10 @@ function shellQuote(value: string): string {
}
const command = [
"npx",
"--yes",
shellQuote(`paperclipai@${canaryVersion}`),
"onboard",
"--yes",
"--data-dir",
shellQuote(process.execPath),
shellQuote(path.resolve("tests/canary-onboarding/start-published-canary.mjs")),
shellQuote(canaryVersion),
shellQuote(workspace),
shellQuote(dataDir),
">",
shellQuote(serverLog),
@@ -76,6 +74,7 @@ export default defineConfig({
command,
url: `${baseUrl}/api/health`,
reuseExistingServer: false,
gracefulShutdown: { signal: "SIGTERM", timeout: 5_000 },
timeout: 300_000,
env: {
...process.env,
@@ -0,0 +1,127 @@
import { spawn } from "node:child_process";
import { mkdtemp, rm } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
// Leave three minutes for onboarding inside Playwright's existing five-minute
// startup deadline. This budget includes every install attempt and backoff.
export const INSTALL_BUDGET_MS = 120_000;
const MAX_INSTALL_ATTEMPTS = 3;
const STDERR_TAIL_CHARS = 64 * 1024;
function run(command, args, { env, signal, captureStderr = false }) {
return new Promise((resolve, reject) => {
signal.throwIfAborted();
const grouped = process.platform !== "win32";
const child = spawn(command, args, {
env, detached: grouped, stdio: ["ignore", "inherit", captureStderr ? "pipe" : "inherit"],
});
let stderr = "";
let stopping;
const kill = (kind) => {
try {
if (grouped) process.kill(-child.pid, kind);
else child.kill(kind);
} catch (error) {
if (error.code !== "ESRCH") throw error;
}
};
const stop = () => {
if (stopping || !child.pid) return;
kill("SIGTERM");
// Also stop any lifecycle-script children even if npm exits first.
stopping = new Promise((done) => setTimeout(() => { kill("SIGKILL"); done(); }, 500));
};
signal.addEventListener("abort", stop, { once: true });
child.stderr?.on("data", (chunk) => {
process.stderr.write(chunk);
stderr = (stderr + chunk.toString()).slice(-STDERR_TAIL_CHARS);
});
child.on("error", reject);
child.on("close", async (code, exitSignal) => {
signal.removeEventListener("abort", stop);
await stopping;
if (signal.aborted) reject(signal.reason);
else resolve({ code, signal: exitSignal, stderr });
});
});
}
function delay(ms, signal) {
return new Promise((resolve, reject) => {
signal.throwIfAborted();
const timer = setTimeout(() => {
signal.removeEventListener("abort", stop);
resolve();
}, ms);
const stop = () => { clearTimeout(timer); reject(signal.reason); };
signal.addEventListener("abort", stop, { once: true });
});
}
export async function startPublishedCanary({
version, workspace, dataDir, env = process.env,
installBudgetMs = INSTALL_BUDGET_MS, retryDelayMs = 10_000,
signal = new AbortController().signal,
}) {
if (!version || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) {
throw new Error("An exact published Paperclip version is required");
}
let prefix;
try {
const budget = new AbortController();
const timer = setTimeout(() => budget.abort(new Error("Canary npm installation exceeded its startup budget")), installBudgetMs);
const installSignal = AbortSignal.any([signal, budget.signal]);
try {
for (let attempt = 1; attempt <= MAX_INSTALL_ATTEMPTS; attempt++) {
installSignal.throwIfAborted();
// Every attempt gets a clean prefix. The fresh per-smoke npm cache still
// retains downloaded tarballs, but --prefer-online refreshes metadata.
prefix = await mkdtemp(path.join(workspace, "npm-install-"));
const result = await run(process.platform === "win32" ? "npm.cmd" : "npm", [
"install", "--prefix", prefix, "--no-save", "--no-package-lock", "--no-audit", "--no-fund",
...(attempt > 1 ? ["--prefer-online"] : []), `paperclipai@${version}`,
], { env, signal: installSignal, captureStderr: true });
if (result.code === 0) break;
const codes = [...result.stderr.matchAll(/^npm (?:error|ERR!) code ([A-Z0-9_]+)\r?$/gm)];
const missingVersion = codes.at(-1)?.[1] === "ETARGET";
if (!missingVersion || result.signal || attempt === MAX_INSTALL_ATTEMPTS) {
throw new Error(`Canary npm installation failed (exit ${result.code ?? result.signal}); onboarding was not started`);
}
await rm(prefix, { recursive: true, force: true });
prefix = undefined;
process.stderr.write(`Canary dependency publication is incomplete; retrying npm installation (${attempt}/${MAX_INSTALL_ATTEMPTS})\n`);
await delay(retryDelayMs * attempt, installSignal);
}
} finally {
clearTimeout(timer);
}
signal.throwIfAborted();
// Start the installed CLI exactly once. Its own failures must never trigger
// another onboarding run or another dependency-install attempt.
const result = await run(path.join(prefix, "node_modules", ".bin", process.platform === "win32" ? "paperclipai.cmd" : "paperclipai"),
["onboard", "--yes", "--data-dir", dataDir], { env, signal });
if (result.code !== 0) throw new Error(`Canary onboarding failed (exit ${result.code ?? result.signal})`);
} finally {
if (prefix) await rm(prefix, { recursive: true, force: true });
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const [version, workspace, dataDir] = process.argv.slice(2);
const cancellation = new AbortController();
const stop = (kind) => cancellation.abort(new Error(`Canary startup stopped by ${kind}`));
const interrupt = () => stop("SIGINT");
const terminate = () => stop("SIGTERM");
process.on("SIGINT", interrupt);
process.on("SIGTERM", terminate);
try {
await startPublishedCanary({ version, workspace, dataDir, signal: cancellation.signal });
} catch (error) {
console.error(error.message);
process.exitCode = 1;
} finally {
process.removeListener("SIGINT", interrupt);
process.removeListener("SIGTERM", terminate);
}
}