mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## 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
742 lines
28 KiB
JavaScript
742 lines
28 KiB
JavaScript
#!/usr/bin/env node
|
|
// Typechecks the test files that no build or package typecheck reads.
|
|
//
|
|
// Most package tsconfigs exclude tests so that `tsc` does not emit them, and
|
|
// Vitest strips types, so a type error in those tests fails nothing. Each program
|
|
// in PROGRAMS reads them without emitting. Sandbox providers are outside the
|
|
// workspace, so the root install has none of their dependencies. They install from
|
|
// typecheck-sandbox-providers/pnpm-lock.yaml here, because their SDK types are part
|
|
// of what a test checks. A provider with its own lockfile (LOCKED_PROVIDERS) installs
|
|
// from that lockfile instead, so each lockfile has one owner and one Dependabot entry.
|
|
//
|
|
// The script then fails if a tracked test file is in no program. tsc decides that,
|
|
// not a glob: `include` silently drops foo.test.tsx when foo.test.ts exists.
|
|
//
|
|
// Usage: node scripts/typecheck-test-programs.mjs [--low-memory] [--checkers <n>] [--concurrency <n>] [tsconfig ...]
|
|
// Naming a tsconfig runs only that program and skips the coverage check unless --check-file or --force-coverage is given.
|
|
|
|
import { spawn, spawnSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { availableParallelism, totalmem } from "node:os";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { linkExcludedPlugins } from "./link-plugin-dev-sdk.mjs";
|
|
import { emitOnlyTscArgs, lowMemoryTscArgs, LOW_MEMORY_VARIABLE, runTsc } from "./run-tsc.mjs";
|
|
import { PROJECTS } from "./typecheck-test-projects.mjs";
|
|
|
|
export const DEFAULT_CONCURRENCY = 3;
|
|
export const PROVIDER_WORKSPACE = "scripts/typecheck-sandbox-providers";
|
|
|
|
export function defaultConcurrency({ cpus = availableParallelism(), totalMemoryBytes = totalmem() } = {}) {
|
|
const memGiB = totalMemoryBytes / 1024 ** 3;
|
|
if (cpus <= 2 || memGiB < 12) return 1;
|
|
if (cpus <= 4) return 3;
|
|
if (memGiB < 24) return Math.min(4, cpus);
|
|
return Math.min(4, cpus);
|
|
}
|
|
|
|
// Measured CI durations (seconds, run 45440355579 / 45444347449) so concurrent
|
|
// execution starts the heaviest programs first instead of leaving 26s tails at the end.
|
|
export const PROGRAM_DURATION_WEIGHTS = {
|
|
"tests/tsconfig.playwright.json": 26.3,
|
|
"packages/paperclip-runner/tsconfig.test.json": 25.9,
|
|
"packages/db/tsconfig.test.json": 23.7,
|
|
"packages/paperclip-runner/tsconfig.browser.test.json": 9.6,
|
|
"packages/paperclip-runner/tsconfig.surfaces.test.json": 8.8,
|
|
"packages/plugins/sandbox-providers/daytona/tsconfig.test.json": 7.5,
|
|
"tests/runner-acceptance/tsconfig.json": 7.3,
|
|
"packages/plugins/plugin-workspace-diff/tsconfig.test.json": 7.2,
|
|
"packages/plugins/sdk/tsconfig.test.json": 6.8,
|
|
"packages/plugins/sandbox-providers/kubernetes/tsconfig.test.json": 6.6,
|
|
"packages/plugins/sandbox-providers/e2b/tsconfig.test.json": 5.7,
|
|
"packages/plugins/sandbox-providers/exe-dev/tsconfig.test.json": 5.6,
|
|
"packages/plugins/sandbox-providers/modal/tsconfig.test.json": 4.4,
|
|
"packages/plugins/sandbox-providers/createos/tsconfig.test.json": 4.2,
|
|
"packages/plugins/sandbox-providers/novita/tsconfig.test.json": 3.9,
|
|
"packages/plugins/sandbox-providers/cloudflare/tsconfig.test.json": 3.8,
|
|
"packages/plugins/sandbox-providers/boxd/tsconfig.test.json": 3.7,
|
|
"packages/plugins/examples/plugin-orchestration-smoke-example/tsconfig.test.json": 1.6,
|
|
"packages/kv-demo-mcp-server/tsconfig.test.json": 1.5,
|
|
"scripts/scale-ramp/tsconfig.json": 0.4,
|
|
"packages/plugins/sandbox-providers/cloudflare/bridge-template/tsconfig.test.json": 0.4,
|
|
};
|
|
|
|
export function orderProgramsLpt(programs = PROGRAMS) {
|
|
return [...programs].sort(
|
|
(left, right) => (PROGRAM_DURATION_WEIGHTS[right] ?? 5) - (PROGRAM_DURATION_WEIGHTS[left] ?? 5),
|
|
);
|
|
}
|
|
|
|
export const SANDBOX_PROVIDERS = [
|
|
"packages/plugins/sandbox-providers/boxd",
|
|
"packages/plugins/sandbox-providers/cloudflare",
|
|
"packages/plugins/sandbox-providers/cloudflare/bridge-template",
|
|
"packages/plugins/sandbox-providers/createos",
|
|
"packages/plugins/sandbox-providers/daytona",
|
|
"packages/plugins/sandbox-providers/e2b",
|
|
"packages/plugins/sandbox-providers/exe-dev",
|
|
"packages/plugins/sandbox-providers/kubernetes",
|
|
"packages/plugins/sandbox-providers/modal",
|
|
"packages/plugins/sandbox-providers/novita",
|
|
];
|
|
|
|
// Providers that commit their own pnpm-lock.yaml. The release build and the Daytona
|
|
// end-to-end job install it frozen, so the shared workspace leaves them out.
|
|
export const LOCKED_PROVIDERS = ["packages/plugins/sandbox-providers/daytona"];
|
|
|
|
export const PROGRAMS = [
|
|
"packages/db/tsconfig.test.json",
|
|
"packages/kv-demo-mcp-server/tsconfig.test.json",
|
|
"packages/paperclip-runner/tsconfig.browser.test.json",
|
|
"packages/paperclip-runner/tsconfig.surfaces.test.json",
|
|
"packages/paperclip-runner/tsconfig.test.json",
|
|
"packages/plugins/examples/plugin-orchestration-smoke-example/tsconfig.test.json",
|
|
"packages/plugins/plugin-workspace-diff/tsconfig.test.json",
|
|
"packages/plugins/sdk/tsconfig.test.json",
|
|
...SANDBOX_PROVIDERS.map((directory) => `${directory}/tsconfig.test.json`),
|
|
"scripts/scale-ramp/tsconfig.json",
|
|
"tests/runner-acceptance/tsconfig.json",
|
|
"tests/tsconfig.playwright.json",
|
|
];
|
|
|
|
// server/scripts/typecheck-layers.mjs reads this tree. Everything else must be in a program.
|
|
export const CHECKED_ELSEWHERE = ["server/src/"];
|
|
|
|
export const SANDBOX_PROVIDER_PROGRAMS = SANDBOX_PROVIDERS.map((directory) => `${directory}/tsconfig.test.json`);
|
|
|
|
const GLOBAL_PROGRAM_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",
|
|
]);
|
|
|
|
const PLAYWRIGHT_TEST_PREFIXES = [
|
|
"tests/tsconfig.playwright.json",
|
|
"tests/ai-connections-app/",
|
|
"tests/ai-connections-review/",
|
|
"tests/canary-onboarding/",
|
|
"tests/hiring-ai-connections/",
|
|
"tests/html-preview/",
|
|
"tests/perf/",
|
|
"tests/release-smoke/",
|
|
"tests/storybook-visual/",
|
|
"ui/src/",
|
|
];
|
|
|
|
const hasPrefix = (files, prefixes) =>
|
|
files.some((file) => prefixes.some((prefix) => file === prefix || file.startsWith(prefix)));
|
|
|
|
/**
|
|
* Selects the test programs, preparation needs, and coverage scope affected by `changedFiles` in PR mode.
|
|
* Returns full coverage when `changedFiles` is null/undefined or touches global typecheck inputs.
|
|
*/
|
|
export function selectTestPrograms(changedFiles, programs = PROGRAMS) {
|
|
if (!Array.isArray(changedFiles)) {
|
|
return {
|
|
programs: [...programs],
|
|
includeProviders: true,
|
|
includeRunnerEval: true,
|
|
checkCoverage: true,
|
|
changedTestFiles: null,
|
|
};
|
|
}
|
|
if (changedFiles.some((file) => GLOBAL_PROGRAM_INPUTS.has(file) || file.startsWith("patches/"))) {
|
|
return {
|
|
programs: [...programs],
|
|
includeProviders: true,
|
|
includeRunnerEval: true,
|
|
checkCoverage: true,
|
|
changedTestFiles: null,
|
|
};
|
|
}
|
|
|
|
const sharedChanged = hasPrefix(changedFiles, ["packages/shared/"]);
|
|
const sdkOrSharedChanged =
|
|
sharedChanged ||
|
|
hasPrefix(changedFiles, [
|
|
"packages/plugins/sdk/",
|
|
"scripts/typecheck-sandbox-providers/",
|
|
"scripts/link-plugin-dev-sdk.mjs",
|
|
]);
|
|
const runnerChanged = hasPrefix(changedFiles, [
|
|
"packages/paperclip-runner/",
|
|
"packages/paperclip-eval-kernel/",
|
|
"packages/adapter-utils/",
|
|
]);
|
|
const cloudflareChanged = hasPrefix(changedFiles, ["packages/plugins/sandbox-providers/cloudflare/"]);
|
|
|
|
const selected = programs.filter((program) => {
|
|
if (program === "packages/db/tsconfig.test.json") {
|
|
return sharedChanged || hasPrefix(changedFiles, ["packages/db/"]);
|
|
}
|
|
if (program === "packages/kv-demo-mcp-server/tsconfig.test.json") {
|
|
return sdkOrSharedChanged || hasPrefix(changedFiles, ["packages/kv-demo-mcp-server/"]);
|
|
}
|
|
if (program.startsWith("packages/paperclip-runner/")) {
|
|
return sharedChanged || runnerChanged;
|
|
}
|
|
if (program === "packages/plugins/examples/plugin-orchestration-smoke-example/tsconfig.test.json") {
|
|
return sdkOrSharedChanged || hasPrefix(changedFiles, ["packages/plugins/examples/plugin-orchestration-smoke-example/"]);
|
|
}
|
|
if (program === "packages/plugins/plugin-workspace-diff/tsconfig.test.json") {
|
|
return sdkOrSharedChanged || hasPrefix(changedFiles, ["packages/plugins/plugin-workspace-diff/"]);
|
|
}
|
|
if (program === "packages/plugins/sdk/tsconfig.test.json") {
|
|
return sdkOrSharedChanged;
|
|
}
|
|
if (program.startsWith("packages/plugins/sandbox-providers/")) {
|
|
if (sdkOrSharedChanged) return true;
|
|
const directory = path.posix.dirname(program);
|
|
if (directory.startsWith("packages/plugins/sandbox-providers/cloudflare")) return cloudflareChanged;
|
|
return hasPrefix(changedFiles, [`${directory}/`]);
|
|
}
|
|
if (program === "scripts/scale-ramp/tsconfig.json") {
|
|
return hasPrefix(changedFiles, ["scripts/scale-ramp/", "scripts/scale-agents-ramp.ts"]);
|
|
}
|
|
if (program === "tests/runner-acceptance/tsconfig.json") {
|
|
return sharedChanged || runnerChanged || hasPrefix(changedFiles, ["tests/runner-acceptance/"]);
|
|
}
|
|
if (program === "tests/tsconfig.playwright.json") {
|
|
return sharedChanged || hasPrefix(changedFiles, PLAYWRIGHT_TEST_PREFIXES);
|
|
}
|
|
// Fail closed for any newly added program without an explicit rule.
|
|
return true;
|
|
});
|
|
|
|
const providerSet = new Set(SANDBOX_PROVIDER_PROGRAMS);
|
|
const includeProviders = selected.some((program) => providerSet.has(program));
|
|
const includeRunnerEval = selected.some((program) => program.startsWith("packages/paperclip-runner/"));
|
|
const changedTestFiles = changedFiles.filter(
|
|
(file) => /\.(test|spec)\.tsx?$/.test(file) && !CHECKED_ELSEWHERE.some((prefix) => file.startsWith(prefix)),
|
|
);
|
|
const tsconfigChanged = changedFiles.some((file) => /(?:^|\/)tsconfig(?:\.[^/]+)?\.json$/.test(file));
|
|
|
|
return {
|
|
programs: selected,
|
|
includeProviders,
|
|
includeRunnerEval,
|
|
checkCoverage: changedTestFiles.length > 0 || tsconfigChanged,
|
|
changedTestFiles: tsconfigChanged ? null : changedTestFiles.length > 0 ? changedTestFiles : null,
|
|
};
|
|
}
|
|
|
|
const PREPARE_STEPS = [
|
|
["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"],
|
|
["--filter", "@paperclipai/paperclip-runner", "run", "ensure:eval-build-deps"],
|
|
];
|
|
// Replacing a provider's standalone node_modules would otherwise ask for confirmation.
|
|
const INSTALL_ARGS = ["install", "--frozen-lockfile", "--ignore-scripts", "--prefer-offline", "--config.confirmModulesPurge=false"];
|
|
const LOCKED_INSTALL_ARGS = ["install", "--ignore-workspace", ...INSTALL_ARGS.slice(1)];
|
|
// Contributors do not commit provider lockfiles: the lockfile refresh workflow regenerates them after
|
|
// merge, as it does the root pnpm-lock.yaml. Until then a changed manifest leaves the lockfile stale,
|
|
// so resolve it in place, like the root install in CI.
|
|
export const RESOLVE_ARGS = ["install", "--resolution-only", "--ignore-scripts", "--no-frozen-lockfile"];
|
|
const LOCKED_RESOLVE_ARGS = ["install", "--ignore-workspace", ...RESOLVE_ARGS.slice(1)];
|
|
|
|
export function findUncheckedTests({ trackedFiles, checkedFiles, checkedElsewhere = CHECKED_ELSEWHERE }) {
|
|
const checked = new Set(checkedFiles);
|
|
return trackedFiles.filter(
|
|
(file) =>
|
|
/\.(test|spec)\.tsx?$/.test(file) &&
|
|
!checked.has(file) &&
|
|
!checkedElsewhere.some((prefix) => file.startsWith(prefix)),
|
|
);
|
|
}
|
|
|
|
function runPnpm(args, { cwd, env }) {
|
|
const result = spawnSync("pnpm", args, {
|
|
cwd,
|
|
env,
|
|
stdio: "inherit",
|
|
// A bare `pnpm` on Windows is pnpm.cmd, which needs the shell to resolve.
|
|
shell: process.platform === "win32",
|
|
});
|
|
if (result.error) throw result.error;
|
|
return result.status ?? 1;
|
|
}
|
|
|
|
function listProgramFiles(config, { cwd, env }) {
|
|
const tsc = path.join(cwd, "node_modules", "typescript", "bin", "tsc");
|
|
const result = spawnSync(process.execPath, [tsc, "-p", config, "--listFilesOnly"], {
|
|
cwd,
|
|
env,
|
|
encoding: "utf8",
|
|
maxBuffer: 1 << 28,
|
|
});
|
|
if (result.error) throw result.error;
|
|
return {
|
|
status: result.status ?? 1,
|
|
output: result.stdout,
|
|
files: result.stdout
|
|
.split("\n")
|
|
.filter(Boolean)
|
|
.map((file) => path.relative(cwd, file).split(path.sep).join("/")),
|
|
};
|
|
}
|
|
|
|
function listProgramFilesAsync(config, { cwd, env }) {
|
|
const tsc = path.join(cwd, "node_modules", "typescript", "bin", "tsc");
|
|
return new Promise((resolve, reject) => {
|
|
const chunks = [];
|
|
const child = spawn(process.execPath, [tsc, "-p", config, "--listFilesOnly"], {
|
|
cwd,
|
|
env,
|
|
stdio: ["ignore", "pipe", "pipe"],
|
|
});
|
|
child.stdout.on("data", (chunk) => chunks.push(chunk));
|
|
child.stderr.on("data", (chunk) => chunks.push(chunk));
|
|
child.on("error", reject);
|
|
child.on("close", (code, signal) => {
|
|
const output = Buffer.concat(chunks).toString("utf8");
|
|
resolve({
|
|
status: signal ? 1 : (code ?? 1),
|
|
output,
|
|
files: output
|
|
.split("\n")
|
|
.filter(Boolean)
|
|
.map((file) => path.relative(cwd, file).split(path.sep).join("/")),
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
function runTscAsync(args, { cwd = process.cwd(), env = process.env } = {}) {
|
|
const tsc = path.join(cwd, "node_modules", "typescript", "bin", "tsc");
|
|
return new Promise((resolve, reject) => {
|
|
const started = Date.now();
|
|
const chunks = [];
|
|
const child = spawn(process.execPath, [tsc, ...args, ...lowMemoryTscArgs(env), ...emitOnlyTscArgs(env)], {
|
|
cwd,
|
|
env,
|
|
stdio: ["ignore", "pipe", "pipe"],
|
|
});
|
|
child.stdout.on("data", (chunk) => chunks.push(chunk));
|
|
child.stderr.on("data", (chunk) => chunks.push(chunk));
|
|
child.on("error", reject);
|
|
child.on("close", (code, signal) => {
|
|
resolve({
|
|
status: signal ? 1 : (code ?? 1),
|
|
signal,
|
|
output: Buffer.concat(chunks).toString("utf8"),
|
|
durationMs: Date.now() - started,
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
function listWorkspaceConfigs(root) {
|
|
const result = spawnSync("pnpm", ["ls", "-r", "--depth", "-1", "--json"], {
|
|
cwd: root,
|
|
encoding: "utf8",
|
|
maxBuffer: 1 << 26,
|
|
shell: process.platform === "win32",
|
|
});
|
|
if (result.error) throw result.error;
|
|
if (result.status !== 0) throw new Error("Unable to list pnpm workspace packages.");
|
|
return JSON.parse(result.stdout)
|
|
.map((workspace) => path.relative(root, path.join(workspace.path, "tsconfig.json")).split(path.sep).join("/"))
|
|
.filter((config) => config !== "server/tsconfig.json" && existsSync(path.join(root, config)));
|
|
}
|
|
|
|
function listTrackedFiles(root) {
|
|
const result = spawnSync("git", ["ls-files", "-z"], { cwd: root, encoding: "utf8", maxBuffer: 1 << 28 });
|
|
if (result.error) throw result.error;
|
|
if (result.status !== 0) throw new Error("Unable to list tracked files.");
|
|
return result.stdout.split("\0").filter(Boolean);
|
|
}
|
|
|
|
function projectCoverageConfigs(root, projects = PROJECTS) {
|
|
const hasServerDeclarations = existsSync(
|
|
path.join(root, "server", "node_modules", ".cache", "paperclip-typecheck", "tsconfig.declarations.json"),
|
|
);
|
|
return projects.map((project) => {
|
|
const layered = `${project}/tsconfig.layers.json`;
|
|
return hasServerDeclarations && existsSync(path.join(root, layered)) ? layered : `${project}/tsconfig.json`;
|
|
});
|
|
}
|
|
|
|
/** Returns the test files in no program, or null if a program could not be listed. */
|
|
export function checkCoverage({
|
|
root,
|
|
env = process.env,
|
|
programs = PROGRAMS,
|
|
projects = PROJECTS,
|
|
workspaceConfigs = listWorkspaceConfigs,
|
|
trackedFiles = listTrackedFiles,
|
|
listFiles = listProgramFiles,
|
|
logError = console.error,
|
|
}) {
|
|
const checkedFiles = [];
|
|
// `pnpm build` and `typecheck:build-gaps` check each workspace's tsconfig.json.
|
|
// scripts/typecheck-test-projects.mjs checks these same files through tsconfig.layers.json.
|
|
const projectConfigs = projectCoverageConfigs(root, projects);
|
|
for (const config of [...workspaceConfigs(root), ...projectConfigs, ...programs]) {
|
|
const listing = listFiles(config, { cwd: root, env });
|
|
if (listing.status !== 0) {
|
|
logError(`typecheck:test-programs: could not list the files of ${config}\n${listing.output ?? ""}`);
|
|
return null;
|
|
}
|
|
checkedFiles.push(...listing.files);
|
|
}
|
|
return findUncheckedTests({ trackedFiles: trackedFiles(root), checkedFiles });
|
|
}
|
|
|
|
/**
|
|
* Parallel coverage check. When `onlyFiles` is provided, stops as soon as every
|
|
* tracked target test file is confirmed to belong to a typechecked program.
|
|
*/
|
|
export async function checkCoverageAsync({
|
|
root,
|
|
env = process.env,
|
|
programs = PROGRAMS,
|
|
projects = PROJECTS,
|
|
includeProviders = true,
|
|
onlyFiles = null,
|
|
concurrency = Math.max(1, Math.min(6, availableParallelism())),
|
|
workspaceConfigs = listWorkspaceConfigs,
|
|
trackedFiles = listTrackedFiles,
|
|
listFilesAsync = listProgramFilesAsync,
|
|
logError = console.error,
|
|
}) {
|
|
const tracked = trackedFiles(root);
|
|
const checkedElsewhere = includeProviders
|
|
? CHECKED_ELSEWHERE
|
|
: [...CHECKED_ELSEWHERE, "packages/plugins/sandbox-providers/"];
|
|
|
|
let remaining = null;
|
|
if (Array.isArray(onlyFiles)) {
|
|
const trackedSet = new Set(tracked);
|
|
const candidates = findUncheckedTests({
|
|
trackedFiles: onlyFiles.filter((file) => trackedSet.has(file)),
|
|
checkedFiles: [],
|
|
checkedElsewhere,
|
|
});
|
|
if (candidates.length === 0) return [];
|
|
remaining = new Set(candidates);
|
|
}
|
|
|
|
const providerSet = new Set(SANDBOX_PROVIDER_PROGRAMS);
|
|
const coveragePrograms = includeProviders ? programs : programs.filter((program) => !providerSet.has(program));
|
|
const projectConfigs = projectCoverageConfigs(root, projects);
|
|
let configs = [...workspaceConfigs(root), ...projectConfigs, ...coveragePrograms];
|
|
|
|
if (remaining) {
|
|
const targets = [...remaining];
|
|
const matchesTargetDir = (config) => {
|
|
const dir = path.posix.dirname(config);
|
|
if (dir === ".") return false;
|
|
return targets.some((file) => file.startsWith(`${dir}/`));
|
|
};
|
|
configs = [
|
|
...configs.filter((config) => matchesTargetDir(config)),
|
|
...configs.filter((config) => !matchesTargetDir(config)),
|
|
];
|
|
}
|
|
|
|
const checkedFiles = [];
|
|
const queue = [...configs];
|
|
let failed = false;
|
|
const workerCount = Math.max(1, Math.min(concurrency, queue.length));
|
|
async function worker() {
|
|
while (!failed && !(remaining && remaining.size === 0)) {
|
|
const config = queue.shift();
|
|
if (!config) return;
|
|
const listing = await listFilesAsync(config, { cwd: root, env });
|
|
if (listing.status !== 0) {
|
|
logError(`typecheck:test-programs: could not list the files of ${config}\n${listing.output ?? ""}`);
|
|
failed = true;
|
|
return;
|
|
}
|
|
if (remaining) {
|
|
for (const file of listing.files) remaining.delete(file);
|
|
} else {
|
|
checkedFiles.push(...listing.files);
|
|
}
|
|
}
|
|
}
|
|
await Promise.all(Array.from({ length: workerCount }, worker));
|
|
if (failed) return null;
|
|
if (remaining) return [...remaining];
|
|
return findUncheckedTests({ trackedFiles: tracked, checkedFiles, checkedElsewhere });
|
|
}
|
|
|
|
export function prepareTestPrograms({
|
|
root,
|
|
env = process.env,
|
|
includeProviders = true,
|
|
includeRunnerEval = true,
|
|
includePluginSdk = true,
|
|
pnpm = runPnpm,
|
|
linkPlugins = linkExcludedPlugins,
|
|
log = console.log,
|
|
logError = console.error,
|
|
}) {
|
|
const steps = PREPARE_STEPS.filter((args) => {
|
|
if (!includePluginSdk && args.includes("@paperclipai/plugin-sdk")) return false;
|
|
if (!includeRunnerEval && args.includes("@paperclipai/paperclip-runner")) return false;
|
|
return true;
|
|
});
|
|
for (const args of steps) {
|
|
const status = pnpm(args, { cwd: root, env });
|
|
if (status !== 0) return status;
|
|
}
|
|
if (!includeProviders) return 0;
|
|
const install = (directory, frozenArgs, resolveArgs) => {
|
|
const cwd = path.join(root, directory);
|
|
let status = pnpm(frozenArgs, { cwd, env });
|
|
if (status !== 0) {
|
|
log(
|
|
`typecheck:test-programs: ${directory}/pnpm-lock.yaml does not match its manifests. ` +
|
|
`Resolving it in place. Do not commit it: the lockfile refresh workflow updates it after merge.`,
|
|
);
|
|
status = pnpm(resolveArgs, { cwd, env });
|
|
if (status === 0) status = pnpm(frozenArgs, { cwd, env });
|
|
}
|
|
if (status !== 0) logError(`typecheck:test-programs: could not install the sandbox providers in ${directory}`);
|
|
return status;
|
|
};
|
|
const installed = install(PROVIDER_WORKSPACE, INSTALL_ARGS, RESOLVE_ARGS);
|
|
if (installed !== 0) return installed;
|
|
for (const provider of LOCKED_PROVIDERS) {
|
|
const status = install(provider, LOCKED_INSTALL_ARGS, LOCKED_RESOLVE_ARGS);
|
|
if (status !== 0) return status;
|
|
}
|
|
// The installs remove the SDK link from each provider's node_modules.
|
|
linkPlugins();
|
|
return 0;
|
|
}
|
|
|
|
export function typecheckTestPrograms({
|
|
root,
|
|
env = process.env,
|
|
programs = PROGRAMS,
|
|
coverage = true,
|
|
prepare = true,
|
|
includeProviders = true,
|
|
includeRunnerEval = true,
|
|
includePluginSdk = true,
|
|
checkers,
|
|
pnpm = runPnpm,
|
|
linkPlugins = linkExcludedPlugins,
|
|
run = runTsc,
|
|
checkFiles = checkCoverage,
|
|
log = console.log,
|
|
logError = console.error,
|
|
}) {
|
|
if (prepare) {
|
|
const prepared = prepareTestPrograms({
|
|
root,
|
|
env,
|
|
includeProviders,
|
|
includeRunnerEval,
|
|
includePluginSdk,
|
|
pnpm,
|
|
linkPlugins,
|
|
log,
|
|
logError,
|
|
});
|
|
if (prepared !== 0) return prepared;
|
|
}
|
|
|
|
const checkerArgs = Number.isInteger(checkers) && checkers >= 1 ? ["--checkers", String(checkers)] : [];
|
|
let exitCode = 0;
|
|
for (const config of programs) {
|
|
log(`typecheck:test-programs: ${config}`);
|
|
const { status, signal } = run(["-p", config, ...checkerArgs], { cwd: root, env });
|
|
if (signal) return status || 1;
|
|
if (status !== 0) exitCode = status;
|
|
}
|
|
if (!coverage) return exitCode;
|
|
|
|
const unchecked = checkFiles({ root, env, logError });
|
|
if (unchecked === null) return exitCode || 1;
|
|
if (unchecked.length > 0) {
|
|
logError(
|
|
`typecheck:test-programs: ${unchecked.length} test files are in no typechecked program. ` +
|
|
`Add them to a program in scripts/typecheck-test-programs.mjs. A foo.test.tsx beside a foo.test.ts needs a new name.\n` +
|
|
unchecked.map((file) => ` ${file}`).join("\n"),
|
|
);
|
|
return exitCode || 1;
|
|
}
|
|
return exitCode;
|
|
}
|
|
|
|
export async function typecheckTestProgramsAsync({
|
|
root,
|
|
env = process.env,
|
|
programs = PROGRAMS,
|
|
coverage = true,
|
|
coverageFiles = null,
|
|
prepare = true,
|
|
includeProviders = true,
|
|
includeRunnerEval = true,
|
|
includePluginSdk = true,
|
|
concurrency = Math.max(1, Math.min(DEFAULT_CONCURRENCY, availableParallelism())),
|
|
checkers,
|
|
pnpm = runPnpm,
|
|
linkPlugins = linkExcludedPlugins,
|
|
runAsync = runTscAsync,
|
|
checkFilesAsync = checkCoverageAsync,
|
|
log = console.log,
|
|
logError = console.error,
|
|
}) {
|
|
if (prepare) {
|
|
const prepared = prepareTestPrograms({
|
|
root,
|
|
env,
|
|
includeProviders,
|
|
includeRunnerEval,
|
|
includePluginSdk,
|
|
pnpm,
|
|
linkPlugins,
|
|
log,
|
|
logError,
|
|
});
|
|
if (prepared !== 0) return prepared;
|
|
}
|
|
|
|
const checkerArgs = Number.isInteger(checkers) && checkers >= 1 ? ["--checkers", String(checkers)] : [];
|
|
let exitCode = 0;
|
|
let aborted = false;
|
|
const queue = orderProgramsLpt(programs);
|
|
const workerCount = Math.max(1, Math.min(concurrency, queue.length));
|
|
async function worker() {
|
|
while (!aborted) {
|
|
const config = queue.shift();
|
|
if (!config) return;
|
|
const result = await runAsync(["-p", config, ...checkerArgs], { cwd: root, env });
|
|
const elapsed = typeof result.durationMs === "number" ? ` (${(result.durationMs / 1000).toFixed(1)}s)` : "";
|
|
log(`typecheck:test-programs: ${config}${elapsed}`);
|
|
if (result.output) {
|
|
const trimmed = result.output.endsWith("\n") ? result.output.slice(0, -1) : result.output;
|
|
if (result.status === 0 && !result.signal) log(trimmed);
|
|
else logError(trimmed);
|
|
}
|
|
if (result.signal) {
|
|
aborted = true;
|
|
exitCode ||= result.status || 1;
|
|
return;
|
|
}
|
|
if (result.status !== 0) exitCode = result.status;
|
|
}
|
|
}
|
|
if (programs.length > 0) {
|
|
await Promise.all(Array.from({ length: workerCount }, worker));
|
|
}
|
|
if (aborted) return exitCode || 1;
|
|
if (!coverage) return exitCode;
|
|
|
|
const unchecked = await checkFilesAsync({
|
|
root,
|
|
env,
|
|
includeProviders,
|
|
onlyFiles: coverageFiles,
|
|
logError,
|
|
});
|
|
if (unchecked === null) return exitCode || 1;
|
|
if (unchecked.length > 0) {
|
|
logError(
|
|
`typecheck:test-programs: ${unchecked.length} test files are in no typechecked program. ` +
|
|
`Add them to a program in scripts/typecheck-test-programs.mjs. A foo.test.tsx beside a foo.test.ts needs a new name.\n` +
|
|
unchecked.map((file) => ` ${file}`).join("\n"),
|
|
);
|
|
return exitCode || 1;
|
|
}
|
|
return exitCode;
|
|
}
|
|
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
const args = process.argv.slice(2);
|
|
let lowMemory = false;
|
|
let prepareOnly = false;
|
|
let skipPrepare = false;
|
|
let includeProviders = true;
|
|
let includeRunnerEval = true;
|
|
let includePluginSdk = true;
|
|
let noCoverage = false;
|
|
let forceCoverage = false;
|
|
let coverageOnly = false;
|
|
let concurrency = defaultConcurrency();
|
|
let checkers;
|
|
const checkFiles = [];
|
|
const programs = [];
|
|
const unknownFlags = [];
|
|
let optionError = null;
|
|
|
|
for (let i = 0; i < args.length; i += 1) {
|
|
const arg = args[i];
|
|
if (arg === "--low-memory") lowMemory = true;
|
|
else if (arg === "--prepare-only") prepareOnly = true;
|
|
else if (arg === "--skip-prepare") skipPrepare = true;
|
|
else if (arg === "--no-providers") includeProviders = false;
|
|
else if (arg === "--no-runner-eval") includeRunnerEval = false;
|
|
else if (arg === "--skip-plugin-sdk") includePluginSdk = false;
|
|
else if (arg === "--no-coverage") noCoverage = true;
|
|
else if (arg === "--force-coverage") forceCoverage = true;
|
|
else if (arg === "--coverage-only") coverageOnly = true;
|
|
else if (arg === "--concurrency") {
|
|
concurrency = Number(args[++i]);
|
|
if (!Number.isInteger(concurrency) || concurrency < 1) optionError = "--concurrency requires a positive integer";
|
|
} else if (arg === "--checkers") {
|
|
checkers = Number(args[++i]);
|
|
if (!Number.isInteger(checkers) || checkers < 1) optionError = "--checkers requires a positive integer";
|
|
} else if (arg === "--check-file") {
|
|
const file = args[++i];
|
|
if (!file || file.startsWith("--")) optionError = "--check-file requires a path";
|
|
else checkFiles.push(file);
|
|
} else if (arg.startsWith("--")) {
|
|
unknownFlags.push(arg);
|
|
} else {
|
|
programs.push(arg);
|
|
}
|
|
}
|
|
|
|
const unknown = programs.filter((program) => !PROGRAMS.includes(program));
|
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
const env = lowMemory ? { ...process.env, [LOW_MEMORY_VARIABLE]: "1" } : process.env;
|
|
|
|
if (unknownFlags.length > 0) {
|
|
console.error(`Unknown option: ${unknownFlags.join(", ")}`);
|
|
process.exitCode = 2;
|
|
} else if (optionError) {
|
|
console.error(optionError);
|
|
process.exitCode = 2;
|
|
} else if (prepareOnly && (skipPrepare || programs.length > 0)) {
|
|
console.error("--prepare-only takes no programs and cannot be combined with --skip-prepare");
|
|
process.exitCode = 2;
|
|
} else if (unknown.length > 0) {
|
|
console.error(`Unknown program: ${unknown.join(", ")}. Known programs:\n ${PROGRAMS.join("\n ")}`);
|
|
process.exitCode = 2;
|
|
} else if (prepareOnly) {
|
|
process.exitCode = prepareTestPrograms({
|
|
root,
|
|
env,
|
|
includeProviders,
|
|
includeRunnerEval,
|
|
includePluginSdk,
|
|
});
|
|
} else {
|
|
const selectedPrograms = coverageOnly ? [] : programs.length > 0 ? programs : PROGRAMS;
|
|
const coverage = !noCoverage && (coverageOnly || forceCoverage || checkFiles.length > 0 || programs.length === 0);
|
|
process.exitCode = await typecheckTestProgramsAsync({
|
|
root,
|
|
env,
|
|
programs: selectedPrograms,
|
|
coverage,
|
|
coverageFiles: checkFiles.length > 0 && !forceCoverage ? checkFiles : null,
|
|
prepare: !skipPrepare,
|
|
includeProviders,
|
|
includeRunnerEval,
|
|
includePluginSdk,
|
|
concurrency,
|
|
checkers,
|
|
});
|
|
}
|
|
}
|