Files
PaperClipAI/scripts/verify-grok-npm-install.mjs
T
2223b7de9e perf(ci): stop building the standalone packages inside the public-install verifier (#15908)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Every pull request runs the `Build` check. Its last step is the
public npm install verifier, `scripts/verify-grok-npm-install.mjs`,
which stages the eighteen public packages reachable from the server and
the CLI, packs them, and installs them in a clean consumer.
> - Before it stages anything, the verifier runs
`scripts/build-standalone-public-packages.mjs`. That script installs and
compiles the seven sandbox-provider plugins that live outside the pnpm
workspace: one network `pnpm install --ignore-workspace` and one `tsc`
per plugin. The line was copied from the build block of `release.sh`
when the verifier was written in #14024.
> - release.sh needs that build because it publishes those plugins. The
verifier does not for anything it stages. Its package closure follows
`workspace:` specs from the server and the CLI, and a `workspace:` spec
can only name a workspace package, so none of the eighteen packages it
packs is a standalone package and no tarball reads that build's output.
> - One optional path at the end of the verifier does read it:
qualification-package retention, which `docker-runner-check.yml` enables
with `PAPERCLIP_RUNNER_QUALIFICATION_PACKAGES_DIR` after running only
`pnpm build`, packs the Daytona plugin from its `dist`. The PR `Build`
job never sets that variable.
> - The timing line from #15868 and #15888 puts the verifier's staging
phase at 75.8s on the latest run, of which the staged sources, the
bundled installs and the packs account for 46.5s. The rest, about 29s,
is the work before staging, and the standalone build is almost all of
it. `Build` at 433-530s is the slowest check in most PR runs once the
server shards drop, so that time sits on the run's critical path.
> - This pull request runs the standalone build only when retention is
requested, keeps the `ui-dist` copy the server package needs, and times
both on the timing line so what is left before staging is visible.
> - The benefit is a `Build` job about 21-28s shorter, with no change to
what the verifier installs or checks, no loss of coverage for the
standalone build because Canary Dry Run still runs it through
`release.sh`, and no change to the retention path that reads it.

## Linked Issues or Issue Description

Replaces #15892, which GitHub closed automatically when the branch of
#15888 (its base at the time) was deleted on merge. Same two commits,
rebased onto `master` on top of #15888 (1ac48aff), #15868 (026bdcd0) and
#15861 (85f4205d), which are all merged. #15892 reached Greptile 5/5
with every check green on the same content; the review history is there.

**What existing behavior does this improve?**

The `Build` PR check. Its public npm install verifier builds the seven
standalone sandbox-provider plugins before it stages the eighteen
packages it installs, and none of those packages uses that build.

**Subsystem affected**

CI and release scripts (`scripts/verify-grok-npm-install.mjs`,
`scripts/build-standalone-public-packages.mjs`).

**Current behavior**

The verifier runs `node scripts/build-standalone-public-packages.mjs`
and then `bash scripts/prepare-server-ui-dist.sh` before it stages any
package, on every run. The first script removes each sandbox-provider
plugin's `node_modules`, runs `pnpm install --ignore-workspace` against
the registry, links the in-repo plugin SDK, and runs the plugin's `tsc`
build, four plugins at a time. On the last `Build` run before this
change
([38146108750](https://github.com/paperclipai/paperclip/actions/runs/38146108750))
`stage_packages_ms` was 75.8s and the staged sources, bundled installs
and packs inside it took 0.9s, 15.7s and 29.9s, which leaves about 29s
before staging. The verifier's package closure, computed in the same way
as the script computes it, contains eighteen workspace packages and no
sandbox-provider plugin.

**Proposed behavior**

Run the standalone build only when
`PAPERCLIP_RUNNER_QUALIFICATION_PACKAGES_DIR` is set, because that is
the one path that reads it, and report it as `stage_standalone_build_ms`
when it runs. Always run the `ui-dist` copy before staging. With
`PAPERCLIP_RELEASE_REUSE_UI_DIST=1`, which the verifier already sets,
that copies the `ui/dist` that `pnpm build` produced into
`server/ui-dist`, which the server package publishes. Report that copy
as `stage_ui_dist_ms` on the timing line. Leave `release.sh` unchanged,
so the release flow and Canary Dry Run still build the standalone
packages where they are published.

**Reason and benefit**

The verifier proves that the eighteen public packages install cleanly
from the public registry. The standalone build adds seven network
installs and compiles whose output is never packed. Removing it from the
PR path shortens the staging phase by about 21-28s. Measured on this
PR's first commit
([38150787810](https://github.com/paperclipai/paperclip/actions/runs/38150787810)):
`stage_packages_ms` 54.2s against 75.8s, with `stage_ui_dist_ms` 21ms,
and the time before staging, `stage_packages_ms` minus the four staging
keys, down from about 29s to under 0.1s.

**Breaking changes**

None. The same eighteen packages are staged, packed, checked and
installed from the same sources. The retention path builds exactly what
it built before. `scripts/build-standalone-public-packages.mjs` exports
two existing helpers for the new guard test and otherwise does not
change.

## What Changed

- `scripts/verify-grok-npm-install.mjs`: the
`build-standalone-public-packages.mjs` call before staging runs only
when `PAPERCLIP_RUNNER_QUALIFICATION_PACKAGES_DIR` is set, in the same
position as before, and reports `stage_standalone_build_ms`. The flag is
read once into `retainQualificationPackages`, and the retention call at
the end is gated by the same variable, so the build and the retention
that reads it cannot diverge. The `prepare-server-ui-dist.sh` call
stays, is timed, and reports `stage_ui_dist_ms`. The comment explains
why release.sh and the retention path need the standalone build and the
staged packages do not. The timing-line comment lists both new keys.
- `scripts/build-standalone-public-packages.mjs`:
`parseWorkspaceEntries` and `isWorkspacePackage` are exported. No
behavior change.
- `scripts/__tests__/grok-public-install-sandbox.test.mjs`: one new
guard test. It asserts the verifier references the standalone build
exactly once, inside the retention gate, timed under its own key, and
that no second reading of the retention variable exists; that
`retain-runner-qualification-packages.mjs` still packs the Daytona
plugin from its `dist`, and that the Daytona plugin is a standalone
package, so the gate cannot pass vacuously; recomputes the verifier's
package closure from `release-package-map.mjs list` and the manifests
through `workspace:` specs; checks that the public package map still
carries packages outside the pnpm workspace; checks that every package
in the closure is inside the workspace globs of `pnpm-workspace.yaml`;
checks that the server package still publishes `ui-dist`; and checks the
order: closure, gated standalone build, `ui-dist` copy, then staging,
with the reuse flag set and the timing keys written.

### Review fix, second commit

Greptile's P1 on the first commit was valid: `docker-runner-check.yml`
runs `pnpm build` and then the verifier with
`PAPERCLIP_RUNNER_QUALIFICATION_PACKAGES_DIR` set, and
`retainRunnerQualificationPackages` copies
`packages/plugins/sandbox-providers/daytona/dist`. The Daytona plugin is
excluded from the pnpm workspace, so `pnpm build` never produces that
directory and the first commit would have failed that job with `ENOENT`
after every install check had passed. The second commit restores the
build on exactly that path: the verifier builds the standalone packages
when, and only when, retention is requested, and the guard test pins the
gate to the reason for it.

## Verification

- `node --test scripts/__tests__/grok-public-install-sandbox.test.mjs
scripts/__tests__/pack-staged-packages.test.mjs
scripts/__tests__/stage-bundled-packages.test.mjs
scripts/__tests__/prefetch-child.test.mjs
scripts/__tests__/retain-runner-qualification-packages.test.mjs`: 37
tests pass.
- The updated guard test fails against the first commit's verifier (no
retention gate around the build) and passes with the second commit. The
first commit's test failed against #15888's verifier the same way.
- `node --check` passes on the verifier.
- The verifier itself needs Docker and a network, which this workspace
does not have. The first commit's `Build` job
([38150787810](https://github.com/paperclipai/paperclip/actions/runs/38150787810))
ran the branch's verifier and measured the saving: `stage_packages_ms`
54.2s (was 75.8s), `stage_ui_dist_ms` 21ms, `stage_sources_ms` 0.8s,
`stage_bundled_ms` 21.0s, `stage_pack_ms` 32.4s, so under 0.1s remains
before staging where about 29s was. The second commit does not change
the PR path: the gate is false on every PR run, so that job's timing
line should show the same shape with no `stage_standalone_build_ms` key.
- The retention path was not run here: it needs Docker and the
`docker-runner-check` workflow's inputs. The code on that path is the
same `run(process.execPath, [...build-standalone-public-packages.mjs])`
call the verifier made before this PR, in the same position.
- `scripts/__tests__/release-dry-run-notes.test.mjs` exercises the
standalone build inside `release.sh` and is unchanged; 11 of its 12
tests spawn `pnpm`, which is not installed in this workspace, and fail
the same way on #15888's head. They pass in CI, where `pnpm` is
installed.
- The first commit's run failed only on `General tests (server
(11/12))`: all 74 files and 1257 tests passed, then Vitest caught a
teardown `EACCES` removing the per-worker `PAPERCLIP_HOME` under
`native-session-resumption.test.ts`, the same error as the first attempt
of #15888's run 38146108750. Neither PR touches server code; the failure
is noted on the tracking issue.

## Risks

- If a future change makes a package the verifier installs depend on a
standalone package, the verifier would stage an unbuilt `dist`. That
cannot happen through a `workspace:` spec, which is the only kind the
closure follows, and the guard test fails if the closure ever contains a
package outside the workspace globs.
- If a future path in the verifier reads a standalone build without
setting the retention variable, it would see no `dist`. The guard test
pins the single reference to the gate; a new reader has to extend the
gate and the test together.
- The sandbox-provider plugins' builds are no longer exercised on every
PR by the `Build` job. They are still built by `release.sh` in Canary
Dry Run on every PR, by the verifier whenever retention is requested,
and the `build-standalone-concurrency` and `release-dry-run-notes` tests
still cover the script.
- Low risk otherwise. The bundled installs, the packs, the consumer
install, and every probe are unchanged.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Fable 5.1 (Anthropic), model ID `claude-fable-5-1`, run as a
Paperclip agent through the Claude Code local adapter with tool use
(shell, file edits, GitHub CLI). Reasoning mode: extended thinking.

## 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
#` / `Refs #` 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
- [ ] All Paperclip CI gates are green (CI is running on the second
commit)
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(the P1 on the first commit is fixed in the second; re-review pending)
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Bender (Fable) <bender-fable@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
2026-10-11 12:14:32 -07:00

262 lines
19 KiB
JavaScript

#!/usr/bin/env node
// Run on a disposable Linux verification host after pnpm build. No publication,
// credentials, inference, or changes to release versions. Native provisioning is
// 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, 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 { packConcurrency, packStagedPackages, packTimings } from './pack-staged-packages.mjs';
import { materializePublishManifest } 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';
import { bundledInstallTimings, startBundledInstalls } from './stage-bundled-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');
const root = mkdtempSync(join(tmpdir(), 'paperclip-grok-public-install-'));
const prerequisite = join(root, 'native/grok');
const env = { ...process.env, NODE_PATH: '', PAPERCLIP_RELEASE_REUSE_UI_DIST: '1', npm_config_ignore_scripts: 'false', npm_config_audit: 'false', npm_config_fund: 'false' };
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');
// Every background child, downloads and bundled-dependency installs alike, is
// stopped in `finally`; `downloads` is the subset the timing line reports as
// prefetches.
const prefetches = [];
const downloads = [];
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);
downloads.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();
function visit(name) {
if (needed.has(name)) return;
const entry = packages.get(name); assert.ok(entry, `Missing public workspace dependency ${name}`); needed.add(name);
for (const [dep, spec] of Object.entries({ ...entry.manifest.dependencies, ...entry.manifest.optionalDependencies })) {
if (spec.startsWith('workspace:')) visit(dep);
}
}
visit('@paperclipai/server');
visit('paperclipai');
// release.sh also builds the standalone public packages (the sandbox-provider
// plugins outside the pnpm workspace) before it stages anything, because it
// publishes them. Nothing staged here reaches them: `needed` is closed under
// `workspace:` specs, so every package staged below is a workspace package
// that `pnpm build` already built, and that build would only cost one
// network install and compile per plugin whose output no tarball reads.
// Canary Dry Run still runs it through release.sh. The one path that does
// read a standalone build is qualification-package retention at the end:
// it packs the Daytona plugin from its `dist`, which only this build
// produces, so the build runs when retention is requested and nowhere else.
const retainQualificationPackages = Boolean(process.env.PAPERCLIP_RUNNER_QUALIFICATION_PACKAGES_DIR);
if (retainQualificationPackages) {
const standaloneStarted = performance.now();
run(process.execPath, [join(repo, 'scripts/build-standalone-public-packages.mjs')], repo);
timing.stage_standalone_build_ms = Math.round(performance.now() - standaloneStarted);
}
// The server's `ui-dist` payload is prepared here; with the reuse flag set
// above, that copies the `ui/dist` that `pnpm build` produced instead of
// building the UI again.
const uiDistStarted = performance.now();
run('bash', [join(repo, 'scripts/prepare-server-ui-dist.sh')], repo);
timing.stage_ui_dist_ms = Math.round(performance.now() - uiDistStarted);
// Match release.sh's unified versioning in temporary staging directories.
// Source manifests remain untouched, including independently versioned SDKs.
// Each package's published files are staged into `source-<index>` and its
// pack input into `package-<index>`, with <index> in dependency order so the
// tarball list keeps matching `needed`. The packages that bundle dependencies
// each need a host-side `npm install` of their bundled closure; those installs
// write only their own `package-<index>` and read nothing another package
// produces, so they start first and run together while the other packages
// are copied, instead of one after another inside one loop. Packing is a
// Node start-up plus CPU-bound gzip per package that reads only the package's
// own directory, so the packs also run together, each into its own
// `pack-<index>`, and the tarballs are checked in order once all are made.
const entries = [...needed].map((name, index) => {
const { dir, manifest } = packages.get(name);
const bundled = (manifest.bundleDependencies ?? manifest.bundledDependencies ?? []).length > 0;
return { name, index, dir, manifest, bundled, target: join(root, `package-${index}`), stagedSource: join(root, `source-${index}`), destination: join(root, `pack-${index}`) };
});
const stageSource = ({ dir, manifest, stagedSource }) => {
mkdirSync(stagedSource);
for (const file of manifest.files ?? ['dist']) {
// release.sh stages runtime skills into these public packages before pack.
const releaseSkills = file === 'skills' && ['server', 'packages/adapters/claude-local', 'packages/adapters/codex-local'].includes(dir);
// Other adapters declare an optional skills directory that npm pack omits
// when absent. Do not fabricate extra release payloads for those adapters.
if (file === 'skills' && !releaseSkills && !existsSync(join(repo, dir, file))) continue;
cpSync(releaseSkills ? join(repo, 'skills') : join(repo, dir, file), join(stagedSource, file), { recursive: true });
}
const releaseManifest = { ...manifest, version: releaseVersion };
writeFileSync(join(stagedSource, 'package.json'), JSON.stringify(releaseManifest));
return releaseManifest;
};
const sourcesStarted = performance.now();
for (const entry of entries.filter(entry => entry.bundled)) stageSource(entry);
const installsStarted = performance.now();
const installs = startBundledInstalls(entries.filter(entry => entry.bundled), { logDir: prefetched, cwd: repo });
prefetches.push(...installs.map(({ handle }) => handle));
for (const entry of entries.filter(entry => !entry.bundled)) {
const releaseManifest = stageSource(entry);
mkdirSync(entry.target);
cpSync(entry.stagedSource, entry.target, { recursive: true });
writeFileSync(join(entry.target, 'package.json'), JSON.stringify(materializePublishManifest(releaseManifest)));
}
timing.stage_sources_ms = Math.round(performance.now() - sourcesStarted);
await awaited('bundled', Promise.all(installs.map(({ handle }) => handle.done)));
timing.stage_bundled_ms = Math.round(performance.now() - installsStarted);
const packStarted = performance.now();
// The bundled packages make the largest tarballs, so they are launched first
// and the short packs fill the remaining slots behind them. Each pack is
// registered for cleanup as it starts, so a failure stops the ones still
// running before the scratch root is removed. The results are put back into
// dependency order before the tarballs are checked and copied.
const concurrency = packConcurrency();
const packs = await packStagedPackages([...entries].sort((a, b) => Number(b.bundled) - Number(a.bundled)), { logDir: prefetched, env, concurrency, register: handle => prefetches.push(handle) });
packs.sort((a, b) => a.index - b.index);
const checksStarted = performance.now();
const tarballs = packs.map(({ tarball }) => tarball);
for (const tarball of tarballs) assertNoBundledCodexPayloads(run('tar', ['-tzf', tarball]).toString().trim().split('\n'));
timing.stage_pack_check_ms = Math.round(performance.now() - checksStarted);
timing.stage_pack_ms = Math.round(performance.now() - packStarted);
Object.assign(timing, packTimings(packs, concurrency));
const assets = join(root, 'assets'); mkdirSync(assets, { mode: 0o755 });
const consumer = join(root, 'consumer'); mkdirSync(consumer);
const cache = join(root, 'cache'); mkdirSync(cache);
writeFileSync(join(consumer, 'package.json'), JSON.stringify({ private: true, type: 'module' }));
for (const tarball of tarballs) {
const destination = join(assets, basename(tarball)); cpSync(tarball, destination); chmodSync(destination, 0o644);
}
// Prove lifecycle execution is real even if npm changes its script defaults.
const sentinelSource = join(root, 'lifecycle-sentinel'); mkdirSync(sentinelSource);
writeFileSync(join(sentinelSource, 'package.json'), JSON.stringify({
name: 'paperclip-verification-lifecycle-sentinel', version: '1.0.0', private: true,
scripts: { postinstall: 'node -e "require(\'node:fs\').writeFileSync(\'lifecycle-ran\', \'ok\')"' },
}));
run('npm', ['pack', '--ignore-scripts', '--pack-destination', assets], sentinelSource);
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
// generated lock. Rebuild runs the deferred install hooks on the installed
// graph without re-resolving it; network isolation and lock checks still hold.
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}`);
}
assert.equal(existsSync(prerequisite), false, 'npm must not provision Grok');
const server = join(consumer, 'node_modules/@paperclipai/server');
const installed = join(server, 'dist/vendor/paperclip-runner');
const codexVersion = JSON.parse(readFileSync(join(repo, 'packages/paperclip-runner/acpx-profiles.json'), 'utf8')).profiles.codex.agentRuntimeVersion;
assert.match(codexVersion, /^\d+\.\d+\.\d+$/);
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')));
assert.equal(existsSync(join(consumer, 'node_modules/@paperclipai/grok-acp')), false);
assert.equal(existsSync(join(installed, 'providers/grok/bin')), false);
// Use real installed compiled code and its actual npm dependency graph. A
// separate process prevents module resolution from borrowing this checkout.
const probe = `
import assert from 'node:assert/strict';
import { verifyQualifiedAcpxInstallation } from '/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/drivers/acpx/installation-integrity.js';
import { resolveQualifiedAcpxProfile } from '/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/drivers/acpx/qualified-profiles.js';
const profile = resolveQualifiedAcpxProfile('grok', 'grok-4.7');
const inspect = () => verifyQualifiedAcpxInstallation(profile, () => { throw new Error('Grok must not resolve an npm package'); });
if (process.argv[2] === 'missing') await assert.rejects(inspect, /prerequisite missing/);
else { const installation = await inspect(); assert.equal(installation.agentServerPackageJsonPath, null); assert.equal(installation.agentRuntimePackageJsonPath, null); await (await installation.openCommand()).close(); }
`;
writeFileSync(join(assets, 'probe.mjs'), probe, { mode: 0o644 });
isolated(['node', '/packages/probe.mjs', 'missing']);
// 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
// isolated; the actual admission probe runs without a network or credentials.
const piProbe = join(assets, 'pi-public-install-probe.mjs');
cpSync(join(repo, 'scripts/pi-public-install-probe.mjs'), piProbe); chmodSync(piProbe, 0o644);
// Pi assembles a bundled runtime in scratch space before atomic publication.
// Keep the existing sandbox and memory bound; only this download needs more
// 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');
// Verified launch leases also materialize the runtime in private scratch.
// 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.
// `stage_ui_dist_ms`, `stage_sources_ms`, `stage_bundled_ms` and
// `stage_pack_ms` split the staging phase, and `stage_bundled_<package>_ms`
// is each concurrent install. `stage_standalone_build_ms` appears only when
// qualification-package retention made the standalone build necessary.
const downloaded = Object.fromEntries(downloads.map(({ name, durationMs }) => [`${name}_prefetch_ms`, durationMs]));
console.log(JSON.stringify({ schema: 'paperclip.public-npm-install.timing.v1', ...timing, ...downloaded, ...bundledInstallTimings(installs) }));
if (retainQualificationPackages) {
const retained = retainRunnerQualificationPackages({ repo, output: process.env.PAPERCLIP_RUNNER_QUALIFICATION_PACKAGES_DIR, sourceRevision, releaseVersion, env,
publicArchives: [...needed].map((name, index) => ({ name, file: tarballs[index] })),
});
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 });
}