Files
PaperClipAI/scripts/ci-typecheck-lane.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

746 lines
27 KiB
JavaScript

#!/usr/bin/env node
import { execFileSync, spawn, spawnSync } from "node:child_process";
import { mkdirSync } from "node:fs";
import { availableParallelism, setPriority, totalmem } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { listLayers } from "../server/scripts/typecheck-layers.mjs";
import { LOW_MEMORY_VARIABLE, EMIT_ONLY_VARIABLE, runTsc } from "./run-tsc.mjs";
import { selectTestPrograms } from "./typecheck-test-programs.mjs";
import { PROJECTS, orderProjectsLpt, selectTestProjects } from "./typecheck-test-projects.mjs";
export const SERIAL_BUILD_GAPS = ["@paperclipai/paperclip-runner"];
export const BACKGROUND_PRIORITY = 10;
export const DEFAULT_MAX_CONCURRENCY = 3;
export const DEFAULT_TEST_PROGRAMS_CONCURRENCY = 3;
export const PREPARE_RUNNER_VENDOR = "prepare runner vendor";
export const BUILD_SERVER_EMIT_ONLY = "build server without type checks";
const SERVER_DECLARATIONS = "server declarations";
export const CLI_GUIDANCE_SAFETY = "CLI guidance safety";
export const UI_TSBUILDINFO = "ui/node_modules/.cache/paperclip-ui.tsbuildinfo";
const lowMemory = { [LOW_MEMORY_VARIABLE]: "1" };
/**
* Computes CPU- and RAM-aware concurrency and TypeScript 7 checker/GOMAXPROCS settings.
* Keeps peak memory safely under 16 GiB on 4-core (m8i.xlarge) and 8-core (c8i.2xlarge)
* runners while scaling up cleanly on 8+ core / >= 24 GiB machines.
*/
export function computeResourceProfile({ cpus = availableParallelism(), totalMemoryBytes = totalmem() } = {}) {
const safeCpus = Math.max(1, Number.isFinite(cpus) ? Math.floor(cpus) : 4);
const totalMemGiB = totalMemoryBytes / 1024 ** 3;
if (safeCpus <= 2 || totalMemGiB < 12) {
return {
laneConcurrency: Math.min(2, safeCpus),
serverDeclCheckers: 1,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 1,
testProgramsConcurrency: 1,
testProgramsCheckers: 1,
};
}
if (safeCpus <= 4) {
return {
laneConcurrency: 3,
serverDeclCheckers: 2,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 2,
testProgramsConcurrency: 3,
testProgramsCheckers: 1,
};
}
if (totalMemGiB < 24) {
// 8-core / 16 GiB (e.g. c8i.2xlarge): run all 4 server test layers in 1 wave at 1 checker each (~10 GiB),
// give server declarations 3 checkers (~6.5 GiB) and UI GOMAXPROCS=4 (~4.4 GiB).
return {
laneConcurrency: Math.min(4, safeCpus),
serverDeclCheckers: 3,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 4,
testProgramsConcurrency: 4,
testProgramsCheckers: 1,
};
}
// 6-8+ core / >= 24 GiB (e.g. m8i.2xlarge or local dev): maximize parallelism across declarations, layers, and UI.
return {
laneConcurrency: Math.min(6, safeCpus),
serverDeclCheckers: Math.min(4, Math.max(3, Math.floor(safeCpus / 2))),
serverLayerCheckers: 2,
testProjectCheckers: 2,
uiGomaxprocs: 4,
testProgramsConcurrency: 4,
testProgramsCheckers: 2,
};
}
export const DEFAULT_RESOURCE_PROFILE = computeResourceProfile({
cpus: 4,
totalMemoryBytes: 16 * 1024 ** 3,
});
const GLOBAL_TYPECHECK_INPUTS = new Set([
"package.json",
"pnpm-lock.yaml",
"pnpm-workspace.yaml",
"tsconfig.base.json",
".npmrc",
"scripts/run-tsc.mjs",
"scripts/ci-typecheck-lane.mjs",
"scripts/typecheck-test-programs.mjs",
"scripts/typecheck-test-projects.mjs",
"server/scripts/typecheck-layers.mjs",
]);
const SERVER_UI_INPUTS = [
"ui/src/lib/",
"ui/src/api/",
"ui/src/types/",
"ui/src/index.css",
"ui/src/bootstrapSetup.ts",
"ui/src/pages/CompanyExport.tsx",
"ui/src/components/MarkdownBody.tsx",
];
const hasPrefix = (files, prefixes) =>
files.some((file) => prefixes.some((prefix) => file === prefix || file.startsWith(prefix)));
export function isGlobalTypecheckInput(file) {
return GLOBAL_TYPECHECK_INPUTS.has(file) || file.startsWith("patches/");
}
export function shouldRunReleaseRegistryTests(changedFiles) {
if (!Array.isArray(changedFiles)) return true;
return changedFiles.some(
(file) =>
file.startsWith("scripts/") ||
file.startsWith(".github/") ||
file === "package.json" ||
file.endsWith("/package.json") ||
file === "pnpm-lock.yaml" ||
file === "pnpm-workspace.yaml" ||
file.startsWith("releases/") ||
file.startsWith("patches/") ||
file.startsWith("Dockerfile") ||
file.startsWith("docker/") ||
file === "turbo.json" ||
file.startsWith("vitest.config.") ||
file === "packages/paperclip-runner/acpx-profiles.json" ||
file === "packages/paperclip-runner/antigravity-distributions.json" ||
file.startsWith("packages/paperclip-runner/cursor-") ||
file.startsWith("packages/paperclip-runner/vitest.config.") ||
file.startsWith("packages/paperclip-runner/scripts/"),
);
}
export function selectBuildGapPackages(buildGapPackages, changedFiles) {
if (!Array.isArray(changedFiles)) return [...buildGapPackages];
if (changedFiles.some(isGlobalTypecheckInput)) return [...buildGapPackages];
return buildGapPackages.filter((name) => {
if (name === "@paperclipai/paperclip-runner") {
return hasPrefix(changedFiles, [
"packages/paperclip-runner/",
"packages/paperclip-eval-kernel/",
"packages/shared/",
"packages/adapter-utils/",
]);
}
if (name === "@paperclipai/ui") {
return hasPrefix(changedFiles, [
"ui/",
"packages/shared/",
"packages/adapter-utils/",
"packages/adapters/",
"packages/paperclip-runner/",
"packages/plugins/sdk/",
"announcements/examples/animated/",
"maps/",
]);
}
if (name === "paperclipai") {
return hasPrefix(changedFiles, [
"cli/",
"server/",
"packages/db/",
"packages/shared/",
"packages/adapter-utils/",
"packages/adapters/",
]);
}
if (name === "@paperclipai/plugin-llm-wiki") {
return hasPrefix(changedFiles, [
"packages/plugins/plugin-llm-wiki/",
"packages/plugins/sdk/",
"packages/shared/",
]);
}
if (name === "@paperclipai/plugin-authoring-smoke-example") {
return hasPrefix(changedFiles, [
"packages/plugins/examples/plugin-authoring-smoke-example/",
"packages/plugins/sdk/",
"packages/shared/",
]);
}
// Fail closed for any unknown build-gap workspace package.
return true;
});
}
export function shouldRunServerTypecheck(changedFiles, selectedProjects = []) {
if (!Array.isArray(changedFiles)) return true;
if (selectedProjects.length > 0) return true;
return changedFiles.some(
(file) =>
isGlobalTypecheckInput(file) ||
file.startsWith("server/") ||
file.startsWith("packages/") ||
file.startsWith("cli/") ||
SERVER_UI_INPUTS.some((prefix) => file === prefix || file.startsWith(prefix)) ||
/^ui\/[^/]+$/.test(file),
);
}
/**
* Rust typecheck (`cargo fmt --check && cargo check`) only reads files inside `packages/paperclip-runner/`
* and Rust toolchain config. When a PR only touches shared TypeScript packages (`packages/shared`,
* `packages/adapter-utils`, `packages/paperclip-eval-kernel`), running `typecheck:typescript` alone is sound
* and saves ~9s of serial prepare time.
*/
export function shouldRunRunnerRustTypecheck(changedFiles) {
if (!Array.isArray(changedFiles)) return true;
if (changedFiles.some(isGlobalTypecheckInput)) return true;
return changedFiles.some(
(file) =>
file.startsWith("packages/paperclip-runner/") ||
file.startsWith("rust-toolchain") ||
file.startsWith(".cargo/"),
);
}
export function typecheckUiIncremental({
root,
env = process.env,
spawnSyncImpl = spawnSync,
runTscImpl = runTsc,
}) {
const uiDir = path.join(root, "ui");
const catalog = spawnSyncImpl(process.execPath, [path.join(root, "scripts", "storybook-catalog.mjs")], {
cwd: uiDir,
env,
stdio: "inherit",
});
if (catalog.error) throw catalog.error;
if ((catalog.status ?? 1) !== 0) return catalog.status ?? 1;
const tsBuildInfoPath = path.join(root, UI_TSBUILDINFO);
mkdirSync(path.dirname(tsBuildInfoPath), { recursive: true });
const relTsBuildInfo = path.relative(uiDir, tsBuildInfoPath).split(path.sep).join(path.posix.sep);
return runTscImpl(["-p", "tsconfig.json", "--incremental", "--tsBuildInfoFile", relTsBuildInfo], {
cwd: uiDir,
env,
}).status;
}
function readGitDiff(root, rangeArgs, execGit) {
const output = execGit(["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "-z", ...rangeArgs, "--"], {
cwd: root,
encoding: "utf8",
maxBuffer: 16 * 1024 * 1024,
});
return output.split("\0").filter(Boolean);
}
export function resolveScope({
root,
env = process.env,
base,
full = false,
execGit = (args, options) => execFileSync("git", args, options),
} = {}) {
if (full || env.PAPERCLIP_CI_FULL === "1" || env.PAPERCLIP_CI_FULL === "true") {
return { mode: "full", changedFiles: null, reason: "PAPERCLIP_CI_FULL" };
}
if (env.CI_PLAN) {
try {
const plan = JSON.parse(env.CI_PLAN);
if (
plan?.mode === "full" ||
plan?.forceReason === "Full CI requested" ||
plan?.forceReason === "Missing or invalid diff" ||
(typeof plan?.forceReason === "string" && plan.forceReason.startsWith("Diff unavailable:"))
) {
return { mode: "full", changedFiles: null, reason: plan.forceReason || "CI_PLAN mode=full" };
}
if (Array.isArray(plan?.changed) && plan.changed.length > 0) {
return { mode: "pr", changedFiles: plan.changed, reason: "CI_PLAN" };
}
return { mode: "full", changedFiles: null, reason: "CI_PLAN had no changed files" };
} catch {
return { mode: "full", changedFiles: null, reason: "invalid CI_PLAN" };
}
}
const baseSha = base || env.PAPERCLIP_CI_BASE_SHA;
if (!baseSha && env.GITHUB_EVENT_NAME !== "pull_request") {
return { mode: "full", changedFiles: null, reason: "full default" };
}
try {
if (base) {
const changedFiles = readGitDiff(root, [`${base}...HEAD`], execGit);
if (changedFiles.length > 0) return { mode: "pr", changedFiles, reason: `git diff ${base}...HEAD` };
return { mode: "full", changedFiles: null, reason: "empty git diff" };
}
let hasMergeSecondParent = false;
try {
execGit(["rev-parse", "--verify", "--quiet", "HEAD^2"], { cwd: root, encoding: "utf8" });
hasMergeSecondParent = true;
} catch {}
const rangeArgs = hasMergeSecondParent ? ["HEAD^1", "HEAD"] : [`${baseSha}...HEAD`];
const changedFiles = readGitDiff(root, rangeArgs, execGit);
if (changedFiles.length > 0) {
return { mode: "pr", changedFiles, reason: `git diff ${rangeArgs.join(" ")}` };
}
return { mode: "full", changedFiles: null, reason: "empty git diff" };
} catch {
return { mode: "full", changedFiles: null, reason: "git diff unavailable" };
}
}
export function planLane({
buildGapPackages,
testLayers,
projects = PROJECTS,
changedFiles = null,
resources = DEFAULT_RESOURCE_PROFILE,
testProgramsConcurrency = resources.testProgramsConcurrency ?? DEFAULT_TEST_PROGRAMS_CONCURRENCY,
}) {
const isPrMode = Array.isArray(changedFiles);
const selectedBuildGaps = selectBuildGapPackages(buildGapPackages, changedFiles);
const selectedProjects = orderProjectsLpt(selectTestProjects(changedFiles, projects));
const runServer = shouldRunServerTypecheck(changedFiles, selectedProjects);
const runReleaseRegistry = shouldRunReleaseRegistryTests(changedFiles);
const runRunnerRust = shouldRunRunnerRustTypecheck(changedFiles);
const programSelection = selectTestPrograms(changedFiles);
const typecheckPackage = (name, background, needs) => {
if (name === "@paperclipai/ui") {
return {
name: `typecheck ${name}`,
command: "node",
args: ["scripts/ci-typecheck-lane.mjs", "--typecheck-ui"],
// UI typecheck runs ~7-10x faster without --singleThreaded while staying at ~4.4 GiB with bounded GOMAXPROCS,
// and persists ui/node_modules/.cache/paperclip-ui.tsbuildinfo for incremental reuse across runs.
env: { GOMAXPROCS: String(resources.uiGomaxprocs) },
background,
...(needs ? { needs } : {}),
};
}
const args =
name === "@paperclipai/paperclip-runner" && !runRunnerRust
? ["--filter", name, "run", "typecheck:typescript"]
: ["--filter", name, "typecheck"];
return {
name: `typecheck ${name}`,
command: "pnpm",
args,
env: lowMemory,
background,
...(needs ? { needs } : {}),
};
};
const prepare = [{ name: "link workspace packages", command: "pnpm", args: ["run", "preflight:workspace-links"] }];
if (runServer || selectedBuildGaps.length > 0 || programSelection.programs.length > 0) {
prepare.push({
name: "build plugin SDK",
command: "node",
args: ["scripts/ensure-plugin-build-deps.mjs"],
});
}
if (programSelection.includeProviders || programSelection.includeRunnerEval) {
const prepareArgs = ["scripts/typecheck-test-programs.mjs", "--prepare-only"];
if (isPrMode) {
prepareArgs.push("--skip-plugin-sdk");
if (!programSelection.includeProviders) prepareArgs.push("--no-providers");
if (!programSelection.includeRunnerEval) prepareArgs.push("--no-runner-eval");
}
prepare.push({ name: "install test program dependencies", command: "node", args: prepareArgs });
}
prepare.push(
...selectedBuildGaps.filter((name) => SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, false)),
{
name: CLI_GUIDANCE_SAFETY,
command: "pnpm",
args: ["exec", "vitest", "run", "--project", "@paperclipai/server", "server/src/__tests__/cli-invocation-safety.test.ts"],
},
);
const needsRunnerVendor = [PREPARE_RUNNER_VENDOR];
const needsDeclarations = [SERVER_DECLARATIONS];
const tasks = [];
if (runServer) {
// Ensure packages/paperclip-runner/dist is current once in parallel with UI / non-runner checks,
// then fan out server declarations and emit-only server build without racing on runner dist.
tasks.push(
{
name: PREPARE_RUNNER_VENDOR,
command: "pnpm",
args: ["--filter", "@paperclipai/server", "run", "prepare:runner-vendor"],
},
{
name: SERVER_DECLARATIONS,
command: "node",
args: [
"server/scripts/typecheck-layers.mjs",
"--declarations-only",
"--checkers",
String(resources.serverDeclCheckers),
],
needs: needsRunnerVendor,
},
);
}
if (runReleaseRegistry) {
tasks.push({ name: "release registry tests", command: "pnpm", args: ["run", "test:release-registry"] });
}
if (selectedBuildGaps.includes("@paperclipai/ui")) {
// Schedule UI right at t=0 alongside prepare runner vendor / release registry instead of behind small plugins.
tasks.push(typecheckPackage("@paperclipai/ui", true));
}
if (programSelection.programs.length > 0 || programSelection.checkCoverage) {
const programArgs = [
"scripts/typecheck-test-programs.mjs",
"--skip-prepare",
"--checkers",
String(resources.testProgramsCheckers),
"--concurrency",
String(testProgramsConcurrency),
];
if (isPrMode) {
if (!programSelection.includeProviders) programArgs.push("--no-providers");
if (!programSelection.checkCoverage) {
programArgs.push("--no-coverage");
} else if (programSelection.changedTestFiles) {
for (const file of programSelection.changedTestFiles) programArgs.push("--check-file", file);
} else {
programArgs.push("--force-coverage");
}
if (programSelection.programs.length === 0) {
programArgs.push("--coverage-only");
} else {
programArgs.push(...programSelection.programs);
}
}
tasks.push({
name: "typecheck test programs",
command: "node",
args: programArgs,
background: true,
...(runServer && programSelection.includeRunnerEval ? { needs: needsRunnerVendor } : {}),
});
}
if (runServer) {
// Start LPT-ordered test projects (longest non-incremental project like tests/runner-e2e first)
// alongside incremental server test layers so they never form a late tail wave.
tasks.push(
...selectedProjects.map((project) => ({
name: `test project ${project}`,
command: "node",
args: [
"scripts/typecheck-test-projects.mjs",
"--checkers",
String(resources.testProjectCheckers),
"--reuse-declarations",
project,
],
needs: needsDeclarations,
})),
...testLayers.map((layer) => ({
name: `server layer ${layer}`,
command: "node",
args: [
"server/scripts/typecheck-layers.mjs",
"--layer",
layer,
"--checkers",
String(resources.serverLayerCheckers),
],
needs: needsDeclarations,
})),
{
name: BUILD_SERVER_EMIT_ONLY,
command: "pnpm",
args: ["--filter", "@paperclipai/server", "build"],
env: {
[EMIT_ONLY_VARIABLE]: "1",
PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT: "1",
},
needs: needsRunnerVendor,
background: true,
},
{
name: "check server runtime assets",
command: "node",
args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"],
needs: [BUILD_SERVER_EMIT_ONLY],
},
);
}
tasks.push(
...selectedBuildGaps
.filter((name) => !SERIAL_BUILD_GAPS.includes(name) && name !== "@paperclipai/ui")
.map((name) =>
typecheckPackage(name, true, runServer && name === "paperclipai" ? needsRunnerVendor : undefined),
),
);
return { prepare, tasks };
}
const seconds = (ms) => `${(ms / 1000).toFixed(1)}s`;
function spawnTask(task, { cwd, env, stdio }) {
return spawn(task.command, task.args, {
cwd,
env: { ...env, ...task.env },
stdio,
shell: process.platform === "win32",
});
}
function runCaptured(task, options) {
return new Promise((resolve) => {
const started = Date.now();
const output = [];
let child;
try {
child = spawnTask(task, { ...options, stdio: ["ignore", "pipe", "pipe"] });
} catch (error) {
resolve({ status: 1, output: `${error.message}\n`, durationMs: Date.now() - started });
return;
}
if (task.background && child.pid) {
try {
setPriority(child.pid, BACKGROUND_PRIORITY);
} catch {}
}
child.stdout.on("data", (chunk) => output.push(chunk));
child.stderr.on("data", (chunk) => output.push(chunk));
child.on("error", (error) => output.push(Buffer.from(`${error.message}\n`)));
child.on("close", (code, signal) => {
if (signal) output.push(Buffer.from(`${task.name}: terminated by ${signal}\n`));
resolve({ status: signal ? 1 : (code ?? 1), output: Buffer.concat(output).toString("utf8"), durationMs: Date.now() - started });
});
});
}
function runStreamed(task, options) {
return new Promise((resolve) => {
const started = Date.now();
let child;
try {
child = spawnTask(task, { ...options, stdio: "inherit" });
} catch (error) {
resolve({ status: 1, output: `${error.message}\n`, durationMs: Date.now() - started });
return;
}
child.on("error", (error) => process.stderr.write(`${error.message}\n`));
child.on("close", (code, signal) => {
if (signal) process.stderr.write(`${task.name}: terminated by ${signal}\n`);
resolve({ status: signal ? 1 : (code ?? 1), durationMs: Date.now() - started });
});
});
}
export function createReporter({ write = (text) => process.stdout.write(text), github = Boolean(process.env.GITHUB_ACTIONS) } = {}) {
const groupStart = (title) => write(github ? `::group::${title}\n` : `\n=== ${title}\n`);
const groupEnd = () => write(github ? "::endgroup::\n" : "");
const ensureNewline = (text) => (text.length === 0 || text.endsWith("\n") ? text : `${text}\n`);
return {
prepareStart(task) {
groupStart(`${task.name}: ${task.command} ${task.args.join(" ")}`);
},
prepareEnd(task, result) {
groupEnd();
write(`${result.status === 0 ? "passed" : "FAILED"}: ${task.name} (${seconds(result.durationMs)})\n`);
},
taskEnd(task, result) {
const title = `${task.name}: ${task.command} ${task.args.join(" ")}`;
const output = ensureNewline(result.output);
if (result.status === 0) {
groupStart(`passed in ${seconds(result.durationMs)}: ${title}`);
write(output);
groupEnd();
return;
}
if (github) write(`::error title=Typecheck lane::${task.name} failed with exit code ${result.status}\n`);
write(`\n=== FAILED in ${seconds(result.durationMs)} with exit code ${result.status}: ${title}\n${output}=== end of ${task.name}\n`);
},
taskSkipped(task, missing) {
write(`skipped: ${task.name}, because ${missing.join(", ")} did not pass\n`);
},
summary(rows) {
const width = Math.max(...rows.map((row) => row.name.length));
write("\nTypecheck lane summary (start offset, duration, result):\n");
for (const row of rows) {
const start = row.startMs === undefined ? "" : seconds(row.startMs);
const duration = row.durationMs === undefined ? "" : seconds(row.durationMs);
write(` ${row.name.padEnd(width)} ${start.padStart(7)} ${duration.padStart(7)} ${row.result}\n`);
}
},
};
}
export async function runLane({
prepare,
tasks,
concurrency,
cwd = process.cwd(),
env = process.env,
runPrepare = runStreamed,
runTask = runCaptured,
reporter = createReporter(),
now = Date.now,
}) {
const laneStart = now();
const rows = [];
for (const task of prepare) {
reporter.prepareStart(task);
const startMs = now() - laneStart;
const result = await runPrepare(task, { cwd, env });
reporter.prepareEnd(task, result);
rows.push({ name: task.name, startMs, durationMs: result.durationMs, result: result.status === 0 ? "passed" : "FAILED" });
if (result.status !== 0) {
for (const remaining of [...prepare.slice(prepare.indexOf(task) + 1), ...tasks]) {
rows.push({ name: remaining.name, result: "not run" });
}
reporter.summary(rows);
return result.status || 1;
}
}
const states = new Map(tasks.map((task) => [task.name, "pending"]));
const results = new Map();
const running = new Set();
await new Promise((resolve) => {
const schedule = () => {
for (const task of tasks) {
if (states.get(task.name) !== "pending") continue;
const needs = task.needs ?? [];
const missing = needs.filter((name) => ["failed", "skipped"].includes(states.get(name)));
if (missing.length > 0) {
states.set(task.name, "skipped");
reporter.taskSkipped(task, missing);
continue;
}
if (running.size >= concurrency || !needs.every((name) => states.get(name) === "passed")) continue;
states.set(task.name, "running");
const startMs = now() - laneStart;
const promise = runTask(task, { cwd, env }).then((result) => {
running.delete(promise);
states.set(task.name, result.status === 0 ? "passed" : "failed");
results.set(task.name, { ...result, startMs });
reporter.taskEnd(task, result);
schedule();
});
running.add(promise);
}
if (running.size === 0) resolve();
};
schedule();
});
let exitCode = 0;
for (const task of tasks) {
const state = states.get(task.name);
const result = results.get(task.name);
if (state !== "passed") exitCode ||= result?.status || 1;
rows.push({
name: task.name,
startMs: result?.startMs,
durationMs: result?.durationMs,
result: state === "passed" ? "passed" : state === "failed" ? `FAILED (exit ${result.status})` : "skipped",
});
}
reporter.summary(rows);
return exitCode;
}
function listBuildGapPackages(root) {
const result = spawnSync(process.execPath, ["scripts/run-typecheck-build-gaps.mjs", "--list-packages"], {
cwd: root,
encoding: "utf8",
stdio: ["ignore", "pipe", "inherit"],
});
if (result.error) throw result.error;
if (result.status !== 0) return null;
return JSON.parse(result.stdout.trim().split("\n").at(-1));
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2);
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
if (args.length === 1 && args[0] === "--typecheck-ui") {
process.exitCode = typecheckUiIncremental({ root, env: process.env });
} else {
const resources = computeResourceProfile();
let concurrency = resources.laneConcurrency;
let base;
let full = false;
let valid = true;
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
if (arg === "--concurrency") {
concurrency = Number(args[++i]);
if (!Number.isInteger(concurrency) || concurrency < 1) valid = false;
} else if (arg === "--base") {
base = args[++i];
if (!base || base.startsWith("--")) valid = false;
} else if (arg === "--full") {
full = true;
} else {
valid = false;
}
}
if (!valid) {
console.error("Usage: node scripts/ci-typecheck-lane.mjs [--concurrency <n>] [--base <ref>] [--full] | --typecheck-ui");
process.exitCode = 2;
} else {
const buildGapPackages = listBuildGapPackages(root);
if (buildGapPackages === null) {
process.exitCode = 1;
} else {
const testLayers = listLayers(path.join(root, "server"))
.filter((layer) => !layer.emitsDeclarations)
.map((layer) => layer.name);
const scope = resolveScope({ root, env: process.env, base, full });
const scopeDetail =
scope.mode === "pr"
? `PR (${scope.changedFiles.length} changed files via ${scope.reason})`
: `full (${scope.reason})`;
const lanePlan = planLane({ buildGapPackages, testLayers, changedFiles: scope.changedFiles, resources });
console.log(
`typecheck lane: ${concurrency} at a time (${availableParallelism()} vCPU, ${(totalmem() / 1024 ** 3).toFixed(1)} GiB; ` +
`decl=${resources.serverDeclCheckers}, layers=${resources.serverLayerCheckers}, ui=${resources.uiGomaxprocs}); ` +
`mode: ${scopeDetail}; prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` +
`build gaps: ${buildGapPackages.join(", ")}`,
);
process.exitCode = await runLane({ ...lanePlan, concurrency, cwd: root });
}
}
}
}