Files
PaperClipAI/scripts/__tests__/e2e-shard.test.mjs
T
Dotta cffd17e78a perf(ci): Phase 3 PR CI under 3m — 4x Runner support, 12x E2E, incremental TS 7 cache, pure-Node postinstall, and rebalanced shards (#22804)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Pull request CI verifies every change before merge across build,
typecheck, server tests, Runner tests, and Playwright E2E shards.
> - After Phase 1 (#22679) and Phase 2 (#22729), full-fanout PR CI still
takes 9m45s wall-clock on 4-core AWS runners because of five
bottlenecks: an unsharded 7m22s `Runner support suite`, stale
server/chat/Runner shard duration manifests plus newly landed SSH/soak
whales, 28s of `pnpm -r run postinstall` replay on every job, cold
server/UI typecheck and single-build overhead, and 3 oversized (>180s)
Playwright E2E specs across 8 shards with double-start Postgres template
boot.
> - Docs-only prose edits under `doc/**` and `docs/**` also fanned out
to 66 CI jobs because only three doc paths bypassed global dependencies.
> - This pull request shards `Runner support suite` 4 ways with `pool:
"threads"`, shards E2E 12 ways after splitting the 3 oversized specs and
removing double-start Postgres boot, adds pure-Node workspace
postinstall replay, adds read-only master-warmed incremental TS 7 and
Runner dist caches, rebalances all server/chat/Runner duration
manifests, demotes 48 new non-invariant soak whales to nightly, and
routes audited prose docs without triggering 66-job storms.
> - The benefit is driving ordinary PR CI toward under 3 minutes
wall-clock while preserving every invariant check, cache boundary, and
full master/nightly test coverage.

## Linked Issues or Issue Description

Refs #22679
Refs #22729

**What existing behavior does this improve?**
Pull request CI wall-clock latency across
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`,
`.github/actions/setup-ci-dependencies/action.yml`, typecheck
orchestration, Vitest/Runner lanes, and Playwright E2E shards.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
Full-fanout PR CI takes 9m45s on 4-core runners (run `45440355579`),
dominated by `Runner support suite` (7m22s), `e2e shards` (5m02s–6m24s),
`General tests (server/chat)` (5m37s–6m01s), `Verify Paperclip Runner
(vitest package)` (6m25s on stale manifests), `Typecheck` (4m13s–6m30s),
`Build` (~4m), and 28s of `pnpm -r postinstall` per job. Prose edits
under `doc/**` trigger 66 jobs.

**Proposed behavior**
Shard `Runner support suite` (4x) and `e2e_shards` (12x), split the 3
oversized E2E specs, boot disposable E2E Postgres in a single
non-durable start, replay workspace `postinstall` in pure Node (<1s),
cache prebuilt Runner dist and TS 7 `.tsbuildinfo` from canonical
`master` pushes (read-only in PRs), use emit-only server compile in
ordinary PR `Build`, rebalance all shard duration manifests, demote 48
new non-invariant soak whales to nightly, and route audited prose docs
cleanly.

## What Changed

- **Pure-Node postinstall replay
(`scripts/replay-workspace-postinstall.mjs`,
`.github/actions/setup-ci-dependencies/action.yml`):** Replaces the 28s
`pnpm -r --if-present run postinstall && pnpm run postinstall` call on
every CI job with a pure-Node parallel runner (~0.84s locally) with
fallback for older checkouts.
- **4-way sharded `Runner support suite` + `threads` pool
(`.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`,
`tests/runner-e2e/run-unit.mjs`, `tests/runner-e2e/vitest.config.ts`):**
Shards Vitest and `node:test` suites 4 ways (`--shard-index 0..3
--shard-count 4`) and switches `tests/runner-e2e` to `pool: "threads"`
with CPU-aware `maxWorkers` while preserving `isolate: true`.
- **12-way E2E shards, single-start E2E Postgres boot, and 3 oversized
spec splits (`tests/e2e/start-e2e-server.ts`, `tests/e2e/*.spec.ts`,
`tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`,
`scripts/e2e-shard-durations.json`, `.github/ci-task-matrix.json`):**
Boots cold ephemeral E2E Postgres in one `initdb --no-sync` +
non-durable `postgresql.conf` start overlapped with server module
import; splits `agent-chat-projects`, `chat-adapters-ui-providers`, and
`chat-adapters-ui-messaging` cleanly with zero tests removed; balances
all 54 specs across 12 shards (6.8s spread).
- **Incremental TS 7 typecheck & Runner dist caching
(`server/scripts/typecheck-layers.mjs`, `scripts/ci-typecheck-lane.mjs`,
`scripts/typecheck-test-programs.mjs`,
`scripts/typecheck-test-projects.mjs`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Preserves portable
`.tsbuildinfo`/`.d.ts` with `layer-map.json` invalidation and
stale-declaration pruning, wires read-only `runner-dist-v1` and
`typecheck-incremental-v1` restores in `pr-trusted.yml` (zero
`actions/cache/save`) paired with canonical-`master`-only guarded
writers in `release-verify.yml`, skips redundant Runner Rust `cargo
check` on TS-only shared PRs, and uses LPT scheduling with concurrency 3
(4-core) / 4 (8-core).
- **Emit-only PR `Build` & audited prose doc routing
(`.github/workflows/pr-trusted.yml`, `.github/scripts/ci-inputs.mjs`):**
Passes `PAPERCLIP_TSC_EMIT_ONLY=1` on ordinary PR `Build` jobs (full
`pnpm build` on `full-ci` / `master`), and classifies audited prose
Markdown under `doc/**` and `docs/**` as `guidance` / `historical` while
keeping `docs/api/**`, JSON/TS fixtures, `maps/**`, and unknown files
fail-closed.
- **Rebalanced shard manifests & new soak demotions
(`scripts/ci/nightly-only-suites.json`,
`scripts/*-shard-durations.json`,
`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`packages/paperclip-runner/vitest.config.ts`,
`packages/paperclip-runner/scripts/vitest-sequencer.mjs`):** Demotes 48
newly landed/grown non-invariant soak suites (including 4 real-SSH
integration suites) to nightly, refreshes all 4 timing manifests from
live CI measurements (0.1s–0.6s LPT skew), and scales Runner package
Vitest CI `maxWorkers` to 3 on 4-core / 6 on 8-core.

## Verification

- `node --test .github/scripts/tests/*.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs
scripts/__tests__/public-install-closure.test.mjs
scripts/__tests__/merge-queue-checks-workflow.test.mjs
scripts/__tests__/e2e-shard.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/runner-vitest-package-lanes.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs
scripts/ci/test-selection-timings.test.mjs` — **973/973 PASS**
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(`609` nightly suites validated, zero protected invariants demoted)
- `node scripts/check-maps.mjs` — **PASS**
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs
tests/runner-e2e/unit-launcher.test.mjs` — **PASS**
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
scripts/vitest-sequencer.test.mjs` — **PASS**
- `cd server && node ../node_modules/vitest/vitest.mjs run
scripts/typecheck-layers.test.mjs
scripts/typecheck-layers-incremental.test.mjs` — **56/56 PASS** (real TS
7.0.2 incremental soundness tests)
- `node scripts/run-tsc.mjs -p tests/e2e/tsconfig.json --noEmit && node
scripts/run-tsc.mjs -p tests/tsconfig.playwright.json --noEmit && pnpm
run test:e2e:runner:typecheck` — **0 errors**
- Live Playwright smoke passed across all 6 split E2E spec files on the
cold non-durable Postgres boot path
(`PAPERCLIP_TEST_POSTGRES_TEMPLATE=0`).
- Live sharded `tests/runner-e2e` runs passed under `pool: "threads",
maxWorkers: 4` (shard `1/4` 172/172 PASS; shard `2/4` all Vitest + 65/65
`node:test` PASS).

## Risks

- **Cache invalidation on incremental typecheck / Runner dist:**
Mitigated by exact-key hashing (including
`packages/{shared,adapter-utils,plugins/sdk}/src/**` and
`packages/paperclip-runner/spec/**`) with no `restore-keys:` on
`runner-dist-v1`, SHA-256 self-validation inside
`prepare-runner-vendor.mjs`, `layer-map.json` invalidation + stale
`.d.ts` pruning in `typecheck-layers.mjs`, and read-only PR restores
(only canonical `master` pushes save caches).
- **Shard rebalancing & soak demotions:** All demoted suites remain in
`nightly-only-suites.json` and run on `full-ci` / `master` / nightly;
`check-test-budget.mjs` enforces zero protected invariants are demoted.
- **Workflow security boundaries:** `ci-routing.yml`, `pr.yml`,
`CODEOWNERS`, and all `runs-on:` expressions are unchanged;
`pr-trusted.yml` performs zero `actions/cache/save` calls.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local code/test execution across 6 parallel worker roles
(`ci-pipeline`, `vitest-runner`, `server-prune`, `e2e-opt`,
`typecheck-opt`, `verifier`).

## 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
- [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
2026-11-24 13:25:46 -06:00

451 lines
19 KiB
JavaScript

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 path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { defaultSuiteWeight, loadShardDurations } from "../general-server-shard.mjs";
import {
DEFAULT_PARALLEL_WORKERS,
EFFECTIVE_PARALLEL_SPEEDUP,
IGNORED_SPECS,
SERIAL_SPECS,
isSerialE2eSpec,
listE2eSpecs,
partitionE2eShards,
selectE2eShard,
} from "../e2e-shard.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
const script = path.join(repoRoot, "scripts", "e2e-shard.mjs");
const durationsManifest = path.join(repoRoot, "scripts", "e2e-shard-durations.json");
const playwrightConfig = path.join(repoRoot, "tests", "e2e", "playwright.config.ts");
const prCallerWorkflow = path.join(repoRoot, ".github", "workflows", "pr.yml");
const trustedPrWorkflowPath = ".github/workflows/pr-trusted.yml";
const trustedPrWorkflow = path.join(repoRoot, trustedPrWorkflowPath);
const routingWorkflow = path.join(repoRoot, ".github", "workflows", "ci-routing.yml");
const ciTaskMatrixPath = path.join(repoRoot, ".github", "ci-task-matrix.json");
const SHARD_COUNT = JSON.parse(readFileSync(ciTaskMatrixPath, "utf8")).e2e_shards.length;
const TARGET_PHASE3_SHARD_COUNT = 12;
function runShard(args) {
const result = spawnSync(process.execPath, [script, ...args], { cwd: repoRoot, encoding: "utf8" });
assert.equal(result.status, 0, `expected success for ${args.join(" ")}: ${result.stderr}`);
return result.stdout.trim().split(/\s+/).filter(Boolean);
}
function readTrustedPrWorkflow() {
const caller = readFileSync(prCallerWorkflow, "utf8");
assert.match(
caller,
/^\s+uses: paperclipai\/paperclip\/\.github\/workflows\/pr-trusted\.yml@master\s*$/m,
"pr.yml must call the trusted workflow from CODEOWNERS-protected master",
);
// Validate proposed workflow changes locally; CI executes the merged master version.
return readFileSync(trustedPrWorkflow, "utf8");
}
function readWorkflowJobs(workflow) {
const jobs = new Map();
let current = null;
for (const line of workflow.split("\n")) {
const header = /^ {2}([A-Za-z0-9_-]+):\s*$/.exec(line);
if (header) {
current = header[1];
jobs.set(current, []);
continue;
}
if (current && /^\S/.test(line)) current = null;
if (current) jobs.get(current).push(line);
}
for (const [id, lines] of jobs) jobs.set(id, lines.join("\n"));
return jobs;
}
function runStackScope(stack, prBaseRef) {
const workflow = readFileSync(routingWorkflow, "utf8");
const match = workflow.match(
/ - name: Select PR CI scope[\s\S]*? run: \|\n([\s\S]*?)(?=\n - name:|$)/,
);
assert.ok(match, "routing workflow must define the PR CI scope script");
const script = match[1]
.split("\n")
.map((line) => line.replace(/^ {10}/, ""))
.join("\n");
const scratch = mkdtempSync(path.join(tmpdir(), "paperclip-stack-scope-"));
const output = path.join(scratch, "github-output");
try {
const result = spawnSync("bash", ["-c", script], {
encoding: "utf8",
env: {
...process.env,
GITHUB_OUTPUT: output,
PR_BASE_REF: prBaseRef,
STACK_JSON: JSON.stringify(stack),
},
});
assert.equal(result.status, 0, result.stderr);
return Object.fromEntries(
readFileSync(output, "utf8")
.trim()
.split("\n")
.map((line) => line.split("=")),
);
} finally {
rmSync(scratch, { recursive: true, force: true });
}
}
function runAggregate(block, fullCi, overrides = {}) {
const code = block.split(" node --input-type=module <<'NODE'\n")[1].split("\n NODE")[0]
.split("\n").map((line) => line.slice(10)).join("\n");
const names = /needs: \[([^\]]+)\]/.exec(block)[1].split(", ");
const results = Object.fromEntries(names.map((name) => [name, { result: overrides[name]
?? (name === "gate" || name === "policy" || fullCi ? "success" : "skipped") }]));
return spawnSync(process.execPath, ["--input-type=module", "-e", code], { encoding: "utf8", env: {
...process.env, FULL_CI: String(fullCi), CI_PLAN: "", CI_RESULTS: JSON.stringify(results),
} });
}
test("the e2e shards form a complete, non-overlapping partition", () => {
const specs = listE2eSpecs();
assert.ok(specs.length > 0, "expected a non-empty e2e spec set");
const shards = Array.from({ length: SHARD_COUNT }, (_, index) =>
runShard(["--shard-index", String(index), "--shard-count", String(SHARD_COUNT)]),
);
const combined = shards.flat();
assert.equal(combined.length, specs.length, "every spec must land on exactly one shard");
assert.deepEqual([...combined].sort(), [...specs].sort());
for (const shard of shards) {
assert.ok(shard.length > 0, "no shard may be empty — Playwright fails a run with no matching specs");
}
});
test("the ignored spec list matches playwright.config.ts testIgnore", () => {
const config = readFileSync(playwrightConfig, "utf8");
const match = config.match(/testIgnore:\s*\[([^\]]*)\]/);
assert.ok(match, "expected a testIgnore array in playwright.config.ts");
const configured = [...match[1].matchAll(/"([^"]+)"/g)].map((entry) => entry[1]);
assert.deepEqual([...configured].sort(), [...IGNORED_SPECS].sort());
});
test("the serial spec list matches playwright.config.ts SERIAL_SPECS and never mixes with parallel specs", () => {
const config = readFileSync(playwrightConfig, "utf8");
const match = config.match(/export const SERIAL_SPECS = \[([\s\S]*?)\];/);
assert.ok(match, "expected a SERIAL_SPECS array in playwright.config.ts");
const configured = [...match[1].matchAll(/"([^"]+)"/g)].map((entry) => entry[1]);
assert.deepEqual([...configured].sort(), [...SERIAL_SPECS].sort());
const specs = listE2eSpecs();
const durations = loadShardDurations(durationsManifest);
const shards = partitionE2eShards(specs, SHARD_COUNT, durations);
assert.equal(shards.length, SHARD_COUNT);
for (const shard of shards) {
const serialCount = shard.files.filter(isSerialE2eSpec).length;
assert.ok(
serialCount === 0 || serialCount === shard.files.length,
`shard must not mix serial and parallel specs: ${shard.files.join(", ")}`,
);
}
});
test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1 and uses unminified inline builds", () => {
const config = readFileSync(playwrightConfig, "utf8");
assert.match(config, /PAPERCLIP_E2E_SKIP_UI_BUILD/);
assert.match(config, /ui-dist.*index\.html/);
assert.match(config, /--minify false/);
assert.match(config, /availableParallelism/);
});
test("start-e2e-server.ts boots disposable embedded Postgres without durable fsync before migrations", () => {
const bootstrap = readFileSync(path.join(repoRoot, "tests", "e2e", "start-e2e-server.ts"), "utf8");
assert.match(bootstrap, /--no-sync/);
assert.match(bootstrap, /fsync = off/);
assert.match(bootstrap, /synchronous_commit = off/);
assert.match(bootstrap, /full_page_writes = off/);
assert.match(bootstrap, /Promise\.all\(/);
});
test("12-shard partitioning stays complete, segregated, and balanced under 145s estimated wall-clock", () => {
const durations = loadShardDurations(durationsManifest);
const specs = listE2eSpecs();
const fallbackWeight = defaultSuiteWeight(durations);
const shards = partitionE2eShards(specs, TARGET_PHASE3_SHARD_COUNT, durations, {
parallelWorkers: EFFECTIVE_PARALLEL_SPEEDUP,
});
assert.equal(shards.length, TARGET_PHASE3_SHARD_COUNT);
const combined = shards.flatMap((shard) => shard.files);
assert.deepEqual([...combined].sort(), [...specs].sort());
for (const shard of shards) {
assert.ok(shard.files.length > 0, "no 12-shard bucket may be empty");
const serialCount = shard.files.filter(isSerialE2eSpec).length;
assert.ok(
serialCount === 0 || serialCount === shard.files.length,
`12-shard bucket must not mix serial and parallel specs: ${shard.files.join(", ")}`,
);
}
const wallWeights = shards.map((shard) => {
const serialSum = shard.files.reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0);
return shard.mode === "parallel" ? serialSum / EFFECTIVE_PARALLEL_SPEEDUP : serialSum;
});
const heaviest = Math.max(...wallWeights);
const totalWall = wallWeights.reduce((sum, weight) => sum + weight, 0);
const largestSerialSpec = Math.max(
0,
...specs.filter(isSerialE2eSpec).map((file) => durations[file] ?? fallbackWeight),
);
const bound = Math.max((totalWall / TARGET_PHASE3_SHARD_COUNT) * 1.15, largestSerialSpec);
assert.ok(
heaviest <= bound,
`heaviest 12-shard bucket ${Math.round(heaviest)}ms exceeds the balance bound (${Math.round(bound)}ms)`,
);
assert.ok(
heaviest <= 145_000,
`heaviest 12-shard bucket ${Math.round(heaviest)}ms exceeds 145s Phase 3 ceiling`,
);
});
test("the duration manifest only names specs that still exist", () => {
const durations = loadShardDurations(durationsManifest);
assert.ok(Object.keys(durations).length > 0, "expected a populated duration manifest");
const specs = new Set(listE2eSpecs());
for (const file of Object.keys(durations)) {
assert.ok(specs.has(file), `duration manifest names a spec that no longer runs: ${file}`);
}
});
test("the weighted partition keeps the shards close to balanced", () => {
const durations = loadShardDurations(durationsManifest);
const specs = listE2eSpecs();
const fallbackWeight = defaultSuiteWeight(durations);
const shards = partitionE2eShards(specs, SHARD_COUNT, durations, {
parallelWorkers: EFFECTIVE_PARALLEL_SPEEDUP,
});
const wallWeights = shards.map((shard) => {
const serialSum = shard.files.reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0);
return shard.mode === "parallel" ? serialSum / EFFECTIVE_PARALLEL_SPEEDUP : serialSum;
});
const heaviest = Math.max(...wallWeights);
const totalWall = wallWeights.reduce((sum, weight) => sum + weight, 0);
const largestSerialSpec = Math.max(
0,
...specs.filter(isSerialE2eSpec).map((file) => durations[file] ?? fallbackWeight),
);
const bound = Math.max((totalWall / SHARD_COUNT) * 1.15, largestSerialSpec);
assert.ok(
heaviest <= bound,
`heaviest shard ${Math.round(heaviest)}ms exceeds the balance bound (${Math.round(bound)}ms)`,
);
});
test("shard arguments are validated", () => {
for (const args of [
["--shard-index", "2", "--shard-count", "2"],
["--shard-index", "-1", "--shard-count", "2"],
["--shard-index", "0", "--shard-count", "0"],
]) {
const result = spawnSync(process.execPath, [script, ...args], { cwd: repoRoot, encoding: "utf8" });
assert.notEqual(result.status, 0, `expected failure for ${args.join(" ")}`);
}
});
test("pr.yml calls the trusted PR workflow from master", () => {
assert.ok(readTrustedPrWorkflow().length > 0);
});
test("the trusted PR workflow keeps a stable aggregate check named e2e over the shard matrix", () => {
// Branch protection requires a check literally named `e2e`. The shards run
// as `e2e shard (n/3)`, so the aggregate job below is what keeps the
// required-check contract intact — same pattern as the `verify` aggregate.
const workflow = readTrustedPrWorkflow();
const jobs = readWorkflowJobs(workflow);
const aggregate = jobs.get("e2e");
assert.ok(aggregate, "pr-trusted.yml must define an `e2e` job to satisfy branch protection");
assert.match(aggregate, /^ {4}name: e2e$/m, "the aggregate job must be named exactly `e2e`");
assert.match(aggregate, /^ {4}if: \$\{\{ always\(\) \}\}$/m, "the aggregate must run even when a shard fails");
assert.match(
aggregate,
/^ {4}needs: \[gate, (?:policy, )?e2e_shards\]$/m,
"the aggregate must depend on the runner gate, optional policy gate, and shard matrix",
);
assert.equal(runAggregate(aggregate, true).status, 0);
assert.equal(runAggregate(aggregate, false).status, 0);
for (const result of ["failure", "cancelled", "skipped"]) {
assert.notEqual(runAggregate(aggregate, true, { e2e_shards: result }).status, 0);
}
const shards = jobs.get("e2e_shards");
assert.ok(shards, "pr-trusted.yml must define the `e2e_shards` matrix job");
const matrixEntries = JSON.parse(readFileSync(path.join(repoRoot, ".github/ci-task-matrix.json"), "utf8"))
.e2e_shards.map((entry) => ({
shardIndex: entry.shard_index,
shardCount: entry.shard_count,
shardLabel: entry.shard_label,
}));
assert.equal(matrixEntries.length, SHARD_COUNT, "the shard matrix must define exactly SHARD_COUNT entries");
assert.deepEqual(
matrixEntries.map((entry) => entry.shardIndex).sort((a, b) => a - b),
Array.from({ length: SHARD_COUNT }, (_, index) => index),
"the shard matrix must define each shard index exactly once",
);
for (const entry of matrixEntries) {
assert.equal(entry.shardCount, SHARD_COUNT, "each shard matrix entry must use the same SHARD_COUNT");
assert.equal(entry.shardLabel, `${entry.shardIndex + 1}/${SHARD_COUNT}`, "each shard label must match its index");
}
});
test("runner authorization uses reserved capacity and executes metadata checks only", () => {
const workflow = readFileSync(routingWorkflow, "utf8");
const jobs = readWorkflowJobs(workflow.split(/^jobs:\n/m)[1]);
assert.deepEqual([...jobs.keys()], ["gate"]);
assert.match(jobs.get("gate"), /runs-on\/fleet=paperclip-ci-routing-x64\/env=public-ci/);
assert.doesNotMatch(jobs.get("gate"), /uses:|actions\/checkout|secrets\./);
assert.match(workflow, /^ {6}runner:\n {8}value: \$\{\{ jobs\.gate\.outputs\.runner \}\}$/m);
assert.match(workflow, /^ {6}full_ci:\n {8}value: \$\{\{ jobs\.gate\.outputs\.full_ci \}\}$/m);
assert.doesNotMatch(workflow, /^ {2}(?:actions|contents|pull-requests): write$/m);
});
test("the trusted PR workflow limits full CI to merge-relevant stack layers", () => {
const workflow = readFileSync(trustedPrWorkflow, "utf8");
const jobs = readWorkflowJobs(workflow);
assert.match(jobs.get("gate"), /uses: paperclipai\/paperclip\/\.github\/workflows\/ci-routing\.yml@master/);
const gate = readWorkflowJobs(readFileSync(routingWorkflow, "utf8")).get("gate");
assert.match(gate, /^ {6}full_ci: \$\{\{ steps\.scope\.outputs\.full_ci \}\}$/m);
assert.match(gate, /STACK_JSON: \$\{\{ toJSON\(github\.event\.pull_request\.stack\) \}\}/);
assert.match(gate, /stack_position == stack_size/);
assert.match(gate, /"\$stack_base_ref" == "\$PR_BASE_REF"/);
for (const jobId of [
"typecheck_release_registry",
"general_tests",
"verify_paperclip_runner",
"build",
"verify_serialized_server",
"canary_dry_run",
"e2e_shards",
"verify_runner_e2e_support",
]) {
assert.match(
jobs.get(jobId),
/^ {4}if: \$\{\{ (?:always\(\) && !cancelled\(\) && needs\.gate\.result == 'success' && )?needs\.gate\.outputs\.full_ci == 'true' && /m,
`${jobId} must run only when the gate selects full CI`,
);
}
assert.doesNotMatch(
jobs.get("policy"),
/needs\.gate\.outputs\.full_ci/,
"the policy job must run on every PR layer",
);
const verify = jobs.get("verify");
assert.match(
verify,
/^ {4}needs: \[gate, test_selection, policy, typecheck_release_registry, general_tests, verify_paperclip_runner, build, docker_context_integrity, sandbox_provider_tests, verify_serialized_server, canary_dry_run, verify_runner_e2e_support\]$/m,
);
assert.equal(runAggregate(verify, true).status, 0);
assert.equal(runAggregate(verify, false).status, 0);
for (const result of ["failure", "cancelled", "skipped"]) {
assert.equal(runAggregate(verify, true, { test_selection: result }).status, 0,
"an optional selector cannot block the successful original matrix");
}
for (const job of ["gate", "policy", "typecheck_release_registry", "general_tests", "verify_paperclip_runner",
"build", "docker_context_integrity", "sandbox_provider_tests", "verify_serialized_server", "canary_dry_run", "verify_runner_e2e_support"]) {
for (const result of ["failure", "cancelled", "skipped"]) {
assert.notEqual(runAggregate(verify, true, { [job]: result }).status, 0, `${job}: ${result}`);
}
if (job !== "gate" && job !== "policy") {
assert.notEqual(runAggregate(verify, false, { [job]: "success" }).status, 0, job);
}
}
const e2e = jobs.get("e2e");
assert.match(e2e, /^ {4}needs: \[gate, policy, e2e_shards\]$/m);
assert.notEqual(runAggregate(e2e, true, { policy: "failure" }).status, 0);
assert.notEqual(runAggregate(e2e, false, { e2e_shards: "success" }).status, 0);
});
test("the stacked PR scope selector runs full CI only where intended", () => {
assert.equal(runStackScope(null, "master").full_ci, "true");
assert.equal(
runStackScope({ position: 11, size: 11, base: { ref: "master" } }, "stack-10").full_ci,
"true",
);
assert.equal(
runStackScope({ position: 1, size: 11, base: { ref: "master" } }, "master").full_ci,
"true",
);
assert.equal(
runStackScope({ position: 6, size: 11, base: { ref: "master" } }, "stack-5").full_ci,
"false",
);
assert.equal(
runStackScope({ position: "invalid", size: 11, base: { ref: "master" } }, "stack-5").full_ci,
"true",
);
});
test("the trusted PR workflow passes the shard's spec filter to Playwright without a literal --", () => {
// `pnpm run test:e2e -- $specs` forwards the literal separator to Playwright,
// so the specs after it are not applied as file filters.
const workflow = readTrustedPrWorkflow();
assert.ok(
!/pnpm run test:e2e --\s/.test(workflow),
"pr-trusted.yml must not insert a literal `--` between `pnpm run test:e2e` and the spec filter",
);
assert.match(
workflow,
/pnpm run test:e2e \$specs/,
"pr-trusted.yml e2e_shards must invoke `pnpm run test:e2e $specs`",
);
});
test("the trusted PR workflow regenerates stale stacked lockfiles", () => {
// Validate the proposed workflow here. The caller executes the merged master
// workflow; edits to this workflow take effect after code-owner review and merge.
const workflow = readFileSync(trustedPrWorkflow, "utf8");
assert.match(
workflow,
/policy:\n needs: \[gate\][\s\S]{0,160}timeout-minutes: 10/,
"the unconditional resolution step needs the same timeout headroom as the lockfile refresh workflow",
);
const policy = workflow.split(" policy:\n")[1].split(" typecheck_release_registry:\n")[0];
assert.doesNotMatch(
policy,
/cache: pnpm|uses: actions\/cache/,
"resolution-only policy must not restore or save a dependency store",
);
assert.match(
policy,
/pnpm install --resolution-only --ignore-scripts --no-frozen-lockfile/,
"the policy job must resolve the complete merge tree without rewriting platform metadata",
);
// Test lanes no longer wait on a policy-job artifact: each install step
// resolves a stale lockfile inline, so a manifest-changing or stacked PR
// still installs while the policy job validates resolution in parallel.
const fallbackInstalls = workflow.match(
/if ! pnpm install --frozen-lockfile; then\n[\s\S]{0,240}?pnpm install --resolution-only --ignore-scripts --no-frozen-lockfile\n\s+pnpm install --frozen-lockfile\n\s+fi/g,
) ?? [];
assert.equal(
fallbackInstalls.length,
7,
"every downstream install job must resolve a stale lockfile inline",
);
assert.doesNotMatch(
workflow,
/Restore regenerated PR lockfile|lockfile_regenerated|name: pr-lockfile/,
"the policy lockfile artifact chain must stay removed; it put the policy job on every lane's critical path",
);
});