Files
PaperClipAI/scripts/typecheck-test-programs.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

486 lines
19 KiB
JavaScript

import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import {
checkCoverage,
checkCoverageAsync,
defaultConcurrency,
findUncheckedTests,
LOCKED_PROVIDERS,
orderProgramsLpt,
PROGRAMS,
prepareTestPrograms,
PROVIDER_WORKSPACE,
RESOLVE_ARGS,
SANDBOX_PROVIDER_PROGRAMS,
SANDBOX_PROVIDERS,
selectTestPrograms,
typecheckTestPrograms,
typecheckTestProgramsAsync,
} from "./typecheck-test-programs.mjs";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const tsc = path.join(root, "node_modules", "typescript", "bin", "tsc");
const harness = (overrides = {}) => {
const calls = { pnpm: [], tsc: [], linked: 0, errors: [] };
return {
calls,
options: {
root: "/repo",
programs: ["a/tsconfig.test.json", "b/tsconfig.test.json"],
pnpm: (args, { cwd }) => {
calls.pnpm.push({ args, cwd });
return 0;
},
linkPlugins: () => {
calls.linked += 1;
},
run: (args) => {
calls.tsc.push(args);
return { status: 0 };
},
checkFiles: () => [],
log: () => {},
logError: (message) => calls.errors.push(message),
...overrides,
},
};
};
test("findUncheckedTests reports only test files outside programs and other checks", () => {
assert.deepEqual(
findUncheckedTests({
trackedFiles: ["a/x.test.ts", "a/y.spec.tsx", "a/z.test.tsx", "a/helper.ts", "a/n.test.mjs", "server/src/s.test.ts"],
checkedFiles: ["a/x.test.ts", "a/y.spec.tsx"],
checkedElsewhere: ["server/src/"],
}),
["a/z.test.tsx"],
);
});
test("every program exists, and the provider list matches the tracked provider packages", () => {
for (const program of PROGRAMS) assert.ok(existsSync(path.join(root, program)), program);
assert.ok(existsSync(path.join(root, PROVIDER_WORKSPACE, "pnpm-lock.yaml")));
const tracked = execFileSync("git", ["ls-files", "packages/plugins/sandbox-providers"], { cwd: root, encoding: "utf8" });
const manifests = tracked.split("\n").filter((file) => file.endsWith("/package.json"));
assert.deepEqual(manifests.map((manifest) => path.dirname(manifest)).sort(), [...SANDBOX_PROVIDERS].sort());
});
test("the provider workspace lists every provider without its own lockfile by full path, so Dependabot sees them", () => {
const workspace = readFileSync(path.join(root, PROVIDER_WORKSPACE, "pnpm-workspace.yaml"), "utf8");
const listed = [...workspace.matchAll(/^\s+-\s+(\S+)\s*$/gm)].map((match) => match[1]);
assert.ok(listed.every((entry) => !entry.includes("*")), "Dependabot does not expand a glob that starts with ../");
const providers = listed.map((entry) => path.posix.normalize(path.posix.join(PROVIDER_WORKSPACE, entry)));
const unlocked = SANDBOX_PROVIDERS.filter((provider) => !LOCKED_PROVIDERS.includes(provider));
assert.deepEqual(providers.sort(), unlocked.sort());
});
test("each provider with its own lockfile is a provider and has that lockfile", () => {
for (const provider of LOCKED_PROVIDERS) {
assert.ok(SANDBOX_PROVIDERS.includes(provider), provider);
assert.ok(existsSync(path.join(root, provider, "pnpm-lock.yaml")), provider);
}
});
test("no provider commits a lockfile, except the one Daytona already has", () => {
const tracked = execFileSync("git", ["ls-files", "packages/plugins/sandbox-providers"], { cwd: root, encoding: "utf8" });
assert.deepEqual(
tracked.split("\n").filter((file) => file.endsWith("/pnpm-lock.yaml")),
["packages/plugins/sandbox-providers/daytona/pnpm-lock.yaml"],
);
});
test("a type error in one program still checks the rest and fails the run", () => {
const { options, calls } = harness({
run: (args) => {
calls.tsc.push(args);
return { status: args[1].startsWith("a/") ? 2 : 0 };
},
});
assert.equal(typecheckTestPrograms(options), 2);
assert.deepEqual(calls.tsc, [
["-p", "a/tsconfig.test.json"],
["-p", "b/tsconfig.test.json"],
]);
});
test("a killed compiler stops the run", () => {
const { options, calls } = harness({
run: (args) => {
calls.tsc.push(args);
return { status: null, signal: "SIGKILL" };
},
});
assert.equal(typecheckTestPrograms(options), 1);
assert.equal(calls.tsc.length, 1);
});
test("providers install frozen without scripts, then relink the SDK", () => {
const { options, calls } = harness();
assert.equal(typecheckTestPrograms(options), 0);
const install = calls.pnpm.find(({ cwd }) => cwd === path.join("/repo", PROVIDER_WORKSPACE));
assert.ok(install.args.includes("--frozen-lockfile"));
assert.ok(install.args.includes("--ignore-scripts"));
assert.equal(calls.linked, 1);
});
test("preparation runs on its own, and a run that skips it only checks", () => {
const prepared = harness();
assert.equal(prepareTestPrograms(prepared.options), 0);
assert.ok(prepared.calls.pnpm.some(({ cwd }) => cwd === path.join("/repo", PROVIDER_WORKSPACE)));
assert.equal(prepared.calls.linked, 1);
assert.deepEqual(prepared.calls.tsc, []);
const checked = harness();
assert.equal(typecheckTestPrograms({ ...checked.options, prepare: false }), 0);
assert.deepEqual(checked.calls.pnpm, []);
assert.equal(checked.calls.linked, 0);
assert.equal(checked.calls.tsc.length, 2);
});
test("a locked provider installs frozen from its own lockfile, outside any workspace", () => {
const { options, calls } = harness();
assert.equal(typecheckTestPrograms(options), 0);
for (const provider of LOCKED_PROVIDERS) {
const install = calls.pnpm.find(({ cwd }) => cwd === path.join("/repo", provider));
assert.ok(install.args.includes("--ignore-workspace"));
assert.ok(install.args.includes("--frozen-lockfile"));
assert.ok(install.args.includes("--ignore-scripts"));
}
});
// Each directory's first frozen install fails; resolution and the second frozen install pass.
const staleOnce = (directory, calls) => {
const cwd = path.join("/repo", directory);
let frozenAttempts = 0;
return (args, options) => {
calls.pnpm.push({ args, cwd: options.cwd });
if (options.cwd !== cwd || !args.includes("--frozen-lockfile")) return 0;
frozenAttempts += 1;
return frozenAttempts === 1 ? 1 : 0;
};
};
const installSteps = (calls, directory) =>
calls.pnpm
.filter(({ cwd }) => cwd === path.join("/repo", directory))
.map(({ args }) => (args.includes("--frozen-lockfile") ? "frozen" : args));
test("a stale provider lockfile is resolved in place, then installed frozen", () => {
const { options, calls } = harness();
options.pnpm = staleOnce(PROVIDER_WORKSPACE, calls);
assert.equal(typecheckTestPrograms(options), 0);
assert.deepEqual(installSteps(calls, PROVIDER_WORKSPACE), ["frozen", RESOLVE_ARGS, "frozen"]);
assert.ok(RESOLVE_ARGS.includes("--resolution-only") && RESOLVE_ARGS.includes("--ignore-scripts"));
assert.equal(calls.tsc.length, 2);
});
test("a stale locked-provider lockfile is resolved in place, outside any workspace", () => {
const [provider] = LOCKED_PROVIDERS;
const { options, calls } = harness();
options.pnpm = staleOnce(provider, calls);
assert.equal(typecheckTestPrograms(options), 0);
const [, resolve] = installSteps(calls, provider);
assert.deepEqual(installSteps(calls, provider), ["frozen", resolve, "frozen"]);
for (const flag of ["--ignore-workspace", "--resolution-only", "--ignore-scripts", "--no-frozen-lockfile"]) {
assert.ok(resolve.includes(flag), flag);
}
assert.equal(calls.tsc.length, 2);
});
test("a locked provider install that still fails stops before any program runs", () => {
const [provider] = LOCKED_PROVIDERS;
const { options, calls } = harness({
pnpm: (args, { cwd }) => (cwd === path.join("/repo", provider) ? 1 : 0),
});
assert.equal(typecheckTestPrograms(options), 1);
assert.equal(calls.tsc.length, 0);
assert.ok(calls.errors[0].includes(provider), calls.errors[0]);
});
test("a provider install that still fails stops before any program runs", () => {
const { options, calls } = harness({
pnpm: (args, { cwd }) => (cwd === path.join("/repo", PROVIDER_WORKSPACE) ? 1 : 0),
});
assert.equal(typecheckTestPrograms(options), 1);
assert.equal(calls.tsc.length, 0);
assert.match(calls.errors[0], /could not install the sandbox providers/);
});
test("an uncovered test file fails the run and is named", () => {
const { options, calls } = harness({ checkFiles: () => ["a/z.test.tsx"] });
assert.equal(typecheckTestPrograms(options), 1);
assert.match(calls.errors[0], /a\/z\.test\.tsx/);
});
test("the coverage check fails closed when a program cannot be listed", () => {
const { options } = harness({ checkFiles: () => null });
assert.equal(typecheckTestPrograms(options), 1);
});
test("naming programs skips the coverage check", () => {
let checked = false;
const { options } = harness({
coverage: false,
checkFiles: () => {
checked = true;
return [];
},
});
assert.equal(typecheckTestPrograms(options), 0);
assert.equal(checked, false);
});
test("checkCoverage uses the compiler's file list, so a dropped sibling is caught", () => {
const directory = mkdtempSync(path.join(root, "node_modules", ".typecheck-test-programs-"));
try {
const relative = path.relative(root, directory).split(path.sep).join("/");
writeFileSync(path.join(directory, "foo.test.ts"), "export {};\n");
writeFileSync(path.join(directory, "foo.test.tsx"), "export {};\n");
writeFileSync(path.join(directory, "tsconfig.json"), JSON.stringify({ compilerOptions: { noEmit: true, jsx: "preserve" }, include: ["*"] }));
const unchecked = checkCoverage({
root,
programs: [`${relative}/tsconfig.json`],
projects: [],
workspaceConfigs: () => [],
trackedFiles: () => [`${relative}/foo.test.ts`, `${relative}/foo.test.tsx`],
});
assert.deepEqual(unchecked, [`${relative}/foo.test.tsx`]);
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
test("a real type error in a test-style program makes tsc exit non-zero", () => {
const directory = mkdtempSync(path.join(tmpdir(), "typecheck-test-programs-"));
try {
writeFileSync(path.join(directory, "bad.test.ts"), "export const value: number = 'text';\n");
writeFileSync(path.join(directory, "tsconfig.json"), JSON.stringify({ compilerOptions: { noEmit: true, types: [] }, include: ["*.ts"] }));
const { status, stdout } = spawnSync(process.execPath, [tsc, "-p", directory, "--pretty", "false"], { encoding: "utf8" });
assert.notEqual(status, 0);
assert.match(stdout, /bad\.test\.ts.*TS2322/);
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
test("selectTestPrograms skips sandbox providers and examples unless their inputs or SDK/shared changed", () => {
const full = selectTestPrograms(null);
assert.deepEqual(full.programs, PROGRAMS);
assert.equal(full.includeProviders, true);
assert.equal(full.checkCoverage, true);
const serverOnly = selectTestPrograms(["server/src/services/issues.ts", "server/src/__tests__/issues.test.ts"]);
assert.deepEqual(serverOnly.programs, []);
assert.equal(serverOnly.includeProviders, false);
assert.equal(serverOnly.includeRunnerEval, false);
assert.equal(serverOnly.checkCoverage, false);
const daytonaOnly = selectTestPrograms(["packages/plugins/sandbox-providers/daytona/src/plugin.ts"]);
assert.deepEqual(daytonaOnly.programs, ["packages/plugins/sandbox-providers/daytona/tsconfig.test.json"]);
assert.equal(daytonaOnly.includeProviders, true);
assert.equal(daytonaOnly.includeRunnerEval, false);
const cloudflare = selectTestPrograms(["packages/plugins/sandbox-providers/cloudflare/src/plugin.ts"]);
assert.deepEqual(cloudflare.programs, [
"packages/plugins/sandbox-providers/cloudflare/tsconfig.test.json",
"packages/plugins/sandbox-providers/cloudflare/bridge-template/tsconfig.test.json",
]);
assert.equal(cloudflare.includeProviders, true);
const sdkChange = selectTestPrograms(["packages/plugins/sdk/src/index.ts"]);
assert.equal(sdkChange.includeProviders, true);
for (const providerProgram of SANDBOX_PROVIDER_PROGRAMS) {
assert.ok(sdkChange.programs.includes(providerProgram), providerProgram);
}
assert.ok(sdkChange.programs.includes("packages/kv-demo-mcp-server/tsconfig.test.json"));
assert.ok(sdkChange.programs.includes("packages/plugins/examples/plugin-orchestration-smoke-example/tsconfig.test.json"));
const uiWithTest = selectTestPrograms(["ui/src/components/Card.tsx", "ui/src/components/Card.test.tsx"]);
assert.deepEqual(uiWithTest.programs, ["tests/tsconfig.playwright.json"]);
assert.equal(uiWithTest.includeProviders, false);
assert.equal(uiWithTest.checkCoverage, true);
assert.deepEqual(uiWithTest.changedTestFiles, ["ui/src/components/Card.test.tsx"]);
const tsconfigEdit = selectTestPrograms(["ui/tsconfig.json"]);
assert.equal(tsconfigEdit.checkCoverage, true);
assert.equal(tsconfigEdit.changedTestFiles, null);
const adapterUtilsEdit = selectTestPrograms(["packages/adapter-utils/src/github-launcher.ts"]);
assert.ok(adapterUtilsEdit.programs.some((program) => program.startsWith("packages/paperclip-runner/")));
assert.equal(adapterUtilsEdit.includeRunnerEval, true);
});
test("prepareTestPrograms can skip sandbox provider installs, runner eval prep, and plugin SDK", () => {
const { options, calls } = harness();
assert.equal(
prepareTestPrograms({ ...options, includeProviders: false, includeRunnerEval: false, includePluginSdk: false }),
0,
);
assert.deepEqual(calls.pnpm, []);
assert.equal(calls.linked, 0);
const evalOnly = harness();
assert.equal(
prepareTestPrograms({ ...evalOnly.options, includeProviders: false, includeRunnerEval: true, includePluginSdk: false }),
0,
);
assert.equal(evalOnly.calls.pnpm.length, 1);
assert.ok(evalOnly.calls.pnpm[0].args.includes("ensure:eval-build-deps"));
assert.equal(evalOnly.calls.linked, 0);
});
test("typecheckTestProgramsAsync runs programs concurrently up to the limit and preserves failure/signal semantics", async () => {
let active = 0;
let peak = 0;
const started = [];
const status = await typecheckTestProgramsAsync({
root: "/repo",
programs: ["a/tsconfig.test.json", "b/tsconfig.test.json", "c/tsconfig.test.json", "d/tsconfig.test.json"],
prepare: false,
coverage: false,
concurrency: 2,
checkers: 1,
log: () => {},
logError: () => {},
runAsync: async (args) => {
started.push(args);
active += 1;
peak = Math.max(peak, active);
await new Promise((resolve) => setTimeout(resolve, 10));
active -= 1;
return { status: args[1].startsWith("b/") ? 2 : 0, signal: null, output: "", durationMs: 10 };
},
});
assert.equal(status, 2);
assert.equal(peak, 2);
assert.equal(started.length, 4);
assert.deepEqual(started[0], ["-p", "a/tsconfig.test.json", "--checkers", "1"]);
// A killed compiler stops queuing further programs.
const killedStarts = [];
const killedStatus = await typecheckTestProgramsAsync({
root: "/repo",
programs: ["a/tsconfig.test.json", "b/tsconfig.test.json", "c/tsconfig.test.json"],
prepare: false,
coverage: false,
concurrency: 1,
log: () => {},
logError: () => {},
runAsync: async (args) => {
killedStarts.push(args[1]);
return { status: 1, signal: "SIGKILL", output: "", durationMs: 5 };
},
});
assert.equal(killedStatus, 1);
assert.deepEqual(killedStarts, ["a/tsconfig.test.json"]);
});
test("checkCoverageAsync checks targeted files with early exit and skips uninstalled providers", async () => {
const listed = [];
const covered = await checkCoverageAsync({
root: "/repo",
includeProviders: false,
onlyFiles: ["ui/src/Card.test.tsx"],
concurrency: 1,
workspaceConfigs: () => ["cli/tsconfig.json", "ui/tsconfig.json"],
trackedFiles: () => ["ui/src/Card.test.tsx", "packages/plugins/sandbox-providers/daytona/src/x.test.ts"],
listFilesAsync: async (config) => {
listed.push(config);
return {
status: 0,
output: "",
files: config === "ui/tsconfig.json" ? ["ui/src/Card.test.tsx"] : [],
};
},
logError: () => {},
});
assert.deepEqual(covered, []);
// Prioritized ui/tsconfig.json first and stopped immediately once covered.
assert.deepEqual(listed, ["ui/tsconfig.json"]);
const uncovered = await checkCoverageAsync({
root: "/repo",
includeProviders: false,
onlyFiles: ["ui/src/Orphan.test.tsx"],
concurrency: 2,
workspaceConfigs: () => ["ui/tsconfig.json"],
trackedFiles: () => ["ui/src/Orphan.test.tsx"],
listFilesAsync: async (config) => {
assert.ok(!SANDBOX_PROVIDER_PROGRAMS.includes(config), `should skip uninstalled provider ${config}`);
return { status: 0, output: "", files: [] };
},
logError: () => {},
});
assert.deepEqual(uncovered, ["ui/src/Orphan.test.tsx"]);
});
test("defaultConcurrency scales safely with CPU count and memory", () => {
const GiB = 1024 ** 3;
assert.equal(defaultConcurrency({ cpus: 2, totalMemoryBytes: 8 * GiB }), 1);
assert.equal(defaultConcurrency({ cpus: 4, totalMemoryBytes: 16 * GiB }), 3);
assert.equal(defaultConcurrency({ cpus: 8, totalMemoryBytes: 16 * GiB }), 4);
assert.equal(defaultConcurrency({ cpus: 8, totalMemoryBytes: 32 * GiB }), 4);
});
test("orderProgramsLpt schedules heaviest test programs first while preserving unknown order", () => {
const ordered = orderProgramsLpt([
"packages/plugins/sdk/tsconfig.test.json",
"packages/db/tsconfig.test.json",
"tests/tsconfig.playwright.json",
"packages/paperclip-runner/tsconfig.test.json",
]);
assert.equal(ordered[0], "tests/tsconfig.playwright.json");
assert.equal(ordered[1], "packages/paperclip-runner/tsconfig.test.json");
assert.equal(ordered[2], "packages/db/tsconfig.test.json");
assert.equal(ordered[3], "packages/plugins/sdk/tsconfig.test.json");
});
test("checkCoverageAsync prefers tsconfig.layers.json for test projects when server declarations exist", async () => {
const tmpRoot = mkdtempSync(path.join(tmpdir(), "coverage-layers-"));
try {
mkdirSync(path.join(tmpRoot, "tests", "e2e"), { recursive: true });
writeFileSync(path.join(tmpRoot, "tests", "e2e", "tsconfig.json"), "{}\n");
writeFileSync(path.join(tmpRoot, "tests", "e2e", "tsconfig.layers.json"), "{}\n");
const listedWithoutDecls = [];
await checkCoverageAsync({
root: tmpRoot,
programs: [],
projects: ["tests/e2e"],
workspaceConfigs: () => [],
trackedFiles: () => [],
listFilesAsync: async (config) => {
listedWithoutDecls.push(config);
return { status: 0, output: "", files: [] };
},
});
assert.deepEqual(listedWithoutDecls, ["tests/e2e/tsconfig.json"]);
mkdirSync(path.join(tmpRoot, "server", "node_modules", ".cache", "paperclip-typecheck"), { recursive: true });
writeFileSync(
path.join(tmpRoot, "server", "node_modules", ".cache", "paperclip-typecheck", "tsconfig.declarations.json"),
"{}\n",
);
const listedWithDecls = [];
await checkCoverageAsync({
root: tmpRoot,
programs: [],
projects: ["tests/e2e"],
workspaceConfigs: () => [],
trackedFiles: () => [],
listFilesAsync: async (config) => {
listedWithDecls.push(config);
return { status: 0, output: "", files: [] };
},
});
assert.deepEqual(listedWithDecls, ["tests/e2e/tsconfig.layers.json"]);
} finally {
rmSync(tmpRoot, { recursive: true, force: true });
}
});