perf(ci): cut PR CI under 5 minutes (shared PG, E2E parallelism, routing, test pruning) (#22679)

## 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 typecheck,
build, server/DB/UI unit tests, and Playwright E2E shards.
> - Today PR CI takes 15–30+ minutes wall-clock on ordinary feature and
fix PRs (such as #22626) because every PR runs
release/packaging/runner-support bloat, boots 800+ separate embedded
Postgres clusters, runs Vitest serialized shards and E2E shards at 1
worker, builds the UI 8 separate times for E2E, emits 52 MB of React
`act(...)` stderr spam in UI tests, and runs 61 real-clock soak suites
plus hundreds of historical one-time SQL migration and mocked component
wiring tests.
> - Slow PR CI delays developer feedback, wastes runner capacity, and
encourages batching changes instead of shipping small, safe PRs.
> - This pull request cuts PR CI across all 6 bottlenecks (pipeline
routing/Build bloat, PR-scoped parallel typecheck, shared embedded
Postgres + batched/parallel Vitest runner, parallel E2E shards +
prebuilt UI cache, historical/soak DB+server pruning with a checked-in
nightly manifest, and UI stderr cleanup + low-value test pruning) while
preserving all core control-plane invariants and full post-merge/release
coverage.
> - The benefit is projected PR CI wall-clock drops from 15–30+ minutes
to ~3.8–4.4 minutes on ordinary PRs while keeping `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and
`full-ci` runs at full coverage.

## Linked Issues or Issue Description

Refs #22626.

**What existing behavior does this improve?**

Trusted pull-request CI wall-clock duration and runner efficiency across
`.github/workflows/pr-trusted.yml`, `turbo.json`,
`scripts/ci-typecheck-lane.mjs`, `scripts/run-vitest-stable.mjs`,
`tests/e2e/`, `packages/db`, `server`, and `ui` test suites.

**Subsystem affected**

Cross-cutting (multiple of the above)

**Current behavior**

Ordinary PRs take 15–30+ minutes wall-clock in PR CI:
- `Build` (~7.5–8.0m) runs a 231s clean public npm Grok install verifier
and a 57s embedded-Postgres boot smoke on every PR.
- `Canary Dry Run` (6.2m), `Runner support suite` (7.9m), `Docker
context integrity`, `General tests (chat 1–3/3)`, and `Verify Paperclip
Runner (vitest package 1–3/3)` fan out on ordinary app PRs due to broad
`turbo.json` inputs.
- `Typecheck + Release Registry` (7.1m) runs `test:release-registry`
(193s), all standalone sandbox provider installs/checks, all untouched
`tests/*` projects, and `--singleThreaded` `tsc` on every PR.
- `General tests` and `Verify serialized server suites` boot 800+
separate embedded Postgres clusters instead of using
`packages/db/src/test-postgres-command.ts`, run 17 serial Vitest
invocations in `workspaces-b`, and run `verify_serialized_server` with
`--no-file-parallelism --maxWorkers=1`.
- `e2e_shards` (8.6m slowest shard) rebuilds the UI 8 separate times and
forces `workers: 1` across all 56 specs because 7 specs mutate
instance-level flags.
- `workspaces-a` (8.3m × 2 shards) emits ~52 MB of React `act(...)` /
`IS_REACT_ACT_ENVIRONMENT` stderr spam and executes 992 UI test files
(including hundreds of brittle mocked wiring / `renderToStaticMarkup`
suites).
- `packages/db` and `server` run 43 historical one-time SQL migration
replay tests, 12 static prose-grep tests, and 61 real-clock
soak/crash/lease-expiry suites (~108.5 CPU-min) on every PR.

**Proposed behavior**

Ordinary PRs complete in under 5 minutes wall-clock while preserving
full control-plane invariant coverage and full
`master`/`release-verify`/`cloud-readiness`/`full-ci` verification:
- PR `Build` removes the 231s Grok clean-npm verifier (already covered
in `release-smoke.yml` and `docker-runner-check.yml`) and gates the 53s
boot smoke on `PAPERCLIP_CI_FULL=1` (keeping fast `build:runtime` on
every PR).
- `turbo.json` and `.github/ci-task-matrix.json` path-gate `Canary Dry
Run`, `Runner support suite`, `Docker context integrity`,
`general-chat`, `ci:runner-package`, `ci:workspaces-a`, and `ci:db`, and
narrow `tests/**` out of `globalDependencies`.
- `Typecheck + Release Registry` uses fail-closed PR-mode scoping
(`CI_PLAN`, `PAPERCLIP_CI_BASE_SHA`, `PAPERCLIP_CI_FULL`), parallel
`typecheck-test-programs.mjs`, and `--checkers` / `GOMAXPROCS=2` within
the 15.7 GiB RAM budget.
- `run-vitest-stable.mjs` automatically wraps Postgres-backed lanes with
one shared embedded Postgres template server
(`test-postgres-command.ts`), batches `workspaces-b` and `workspaces-a`
into single multi-project Vitest invocations, parallelizes isolated
`serialized` shards, and filters `scripts/ci/nightly-only-suites.json`
in PR mode (respecting `PAPERCLIP_CI_FULL=1`).
- `e2e_shards` restores a read-only exact-key `server/ui-dist` cache
written on canonical `master` pushes (`PAPERCLIP_E2E_SKIP_UI_BUILD=1`,
inline fallback on UI PRs), isolates the 7 flag-mutating specs onto 2
serial shards while running the other 6 shards at `workers: 3` +
`fullyParallel: true`, prunes 5 legacy/screenshot specs, and replaces
fixed 20s/30s sleeps with deterministic waits.
- `ui/vitest.setup.ts` eliminates >99.9% of stderr spam
(`IS_REACT_ACT_ENVIRONMENT = true`, clean localStorage/DOM stubs,
targeted `act(...)`/`No queryFn` suppression) and prunes 445 low-value
mocked/presentational/screenshot UI tests + slims 2 giant mocked suites
(keeping all `ui/src/lib`, `api`, `hooks`, `context`, `adapters`,
`features`, `plugins`, and privacy/authz tests).
- `packages/db` and `server` prune 43 historical one-time SQL migration
tests, 12 static prose-grep tests, and 28 redundant `it.each` cases in
`chat-channels.integration.test.ts`, and classify 61 real-clock
soak/restart/lease-expiry/workspace-recovery suites (6,510.2s / 108.5
CPU-min) into `scripts/ci/nightly-only-suites.json`.

**Reason and benefit**

Cuts ordinary PR CI wall-clock from 15–30+ minutes to a projected
~3.8–4.4 minutes and removes ~156,353 LOC of redundant/brittle test code
without dropping any core Paperclip invariant (company isolation, authz,
atomic checkout, single-assignee, approval gates, budget hard-stop,
activity logging).

**Breaking changes**

None for product runtime behavior. In PR CI, 61 real-clock soak suites
listed in `scripts/ci/nightly-only-suites.json` run on `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and PRs with
the `full-ci` label (`PAPERCLIP_CI_FULL=1`) instead of every ordinary
PR.

## What Changed

- **Pipeline & routing (`ci-fast/pipeline`):**
- `.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`, `.github/ci-task-matrix.json`,
`turbo.json`: removed Grok clean-npm verifier from PR `Build`, gated
`server-boot-smoke.sh` on `PAPERCLIP_CI_FULL=1`, path-gated
`canary_dry_run`, `verify_runner_e2e_support`,
`docker_context_integrity`, `general-chat`, `ci:runner-package`,
`ci:workspaces-a`, and `ci:db`, forwarded `CI_PLAN` /
`PAPERCLIP_CI_BASE_SHA` / `PAPERCLIP_CI_FULL` (keeping `profile-ci` in
PR mode), and added exact-key read-only `server/ui-dist` cache restore
in `e2e_shards` with a master-only writer in `release-verify.yml`.
- Updated `.github/scripts/tests/ci-plan.test.mjs`,
`scripts/__tests__/public-install-closure.test.mjs`, and
`scripts/__tests__/runner-release-crate-cache.test.mjs`.
- **Typecheck lane (`ci-fast/typecheck`):**
- `scripts/ci-typecheck-lane.mjs`,
`scripts/typecheck-test-programs.mjs`,
`scripts/typecheck-test-projects.mjs`,
`server/scripts/typecheck-layers.mjs`: added fail-closed PR-mode diff
scoping (skipping `test:release-registry`, standalone sandbox providers,
demo plugins, and untouched test projects/workspaces on unrelated PRs),
concurrent `typecheckTestProgramsAsync`, and `--checkers` /
`GOMAXPROCS=2` parallelism within 15.7 GiB RAM.
- Updated `scripts/__tests__/ci-typecheck-lane.test.mjs`,
`scripts/typecheck-test-programs.test.mjs`, and
`server/scripts/typecheck-layers.test.mjs`.
- **Vitest runner (`ci-fast/vitest-runner`):**
- `scripts/run-vitest-stable.mjs`,
`packages/db/src/test-postgres-command.ts`,
`scripts/__tests__/run-vitest-stable-shard.test.mjs`: wired automatic
shared embedded Postgres template DB (`test-postgres-command.ts` with
`fsync=off`), batched `workspaces-b` and `workspaces-a` into single
multi-project Vitest runs, parallelized isolated `serialized` shards
(`maxWorkers=3`), and added PR-mode filtering for
`scripts/ci/nightly-only-suites.json` (honoring `PAPERCLIP_CI_FULL=1`).
- **Playwright E2E (`ci-fast/e2e`):**
- `tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`,
`scripts/e2e-shard-durations.json`,
`scripts/__tests__/e2e-shard.test.mjs`, `maps/feature-map/recovery.md`:
added `PAPERCLIP_E2E_SKIP_UI_BUILD=1`, isolated the 7 instance-mutating
`SERIAL_SPECS` onto dedicated serial shards while running the remaining
44 specs across 6 shards at `workers: 3` + `fullyParallel: true`, pruned
5 legacy/screenshot specs (`-743 LOC`), and replaced fixed 20s/30s
sleeps in `disconnect-resilience.spec.ts` and `composer-stop.spec.ts`.
- **Server & DB test pruning + nightly soak manifest
(`ci-fast/server-prune`):**
- Deleted 41 historical one-time SQL migration tests + 5 obsolete
fixture SQLs in `packages/db/src`, 2 historical server SQL migration
tests, and 12 brittle static prose-guidance tests; trimmed
`packages/db/src/client.test.ts` (2,328 → 219 LOC),
`packages/db/src/better-auth-account-issuer-migration.test.ts` (167 → 19
LOC), and 2 redundant `it.each` matrices in
`server/src/__tests__/chat-channels.integration.test.ts`.
- Added `scripts/ci/nightly-only-suites.json` classifying 61 real-clock
soak/restart/lease-expiry/workspace-recovery suites (6,510.2s / 108.5
CPU-min).
- **UI test log spam fix & pruning (`ci-fast/ui-prune`):**
- `ui/vitest.setup.ts`, `ui/vitest.config.ts`: eliminated >99.9% stderr
spam (22–52 MB → 3.6 KB) by enabling `IS_REACT_ACT_ENVIRONMENT = true`,
adding clean DOM/localStorage stubs, and filtering React `act(...)` /
TanStack Query `No queryFn` noise.
- Pruned 445 low-value mocked/presentational/screenshot UI test files,
slimmed `AgentConfigForm.render.test.tsx` and `Browse.test.tsx` to their
privacy/access checks, updated 34 `maps/` files to remove dead test
links, and removed the stale `ui/src/pages/NewAgent.test-support.tsx`
allowlist entry in `scripts/check-query-error-rendering.mjs`.

## Verification

- Combined CI contract & shard test suite (`node --test
.github/scripts/tests/ci-plan.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/__tests__/e2e-shard.test.mjs
scripts/__tests__/public-install-closure.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs
scripts/__tests__/merge-queue-checks-workflow.test.mjs`): **136/136
PASS** (23.13s).
- Full `.github/scripts/tests/*.test.mjs` suite on `ci-fast/pipeline`:
**850/850 PASS** + Turbo cached-lane check **1/1 PASS**.
- `node scripts/check-query-error-rendering.mjs --enforce --summary` and
`node --test scripts/check-query-error-rendering.test.mjs`: **0
findings, 7/7 PASS**.
- `node scripts/check-maps.mjs`: **PASS** (`35 areas, 192 capability
IDs`).
- `pnpm --filter @paperclipai/db typecheck`: **PASS**
(`check:migrations` + `tsc --noEmit`).
- `pnpm --filter @paperclipai/ui typecheck`: **PASS** (`369 files, 3454
stories` + `run-tsc.mjs -b`).
- Component-level benchmarks verified on individual branches prior to
merge (`ci-typecheck-lane.mjs` 63.4s simulated PR run; real Playwright
3-worker parallel specs passing; UI suite full run reduced to 3.6 KB
stderr).
- Live GitHub PR CI run triggered on this draft PR to verify real runner
execution and measure before/after timings.

## Risks

- **Two-phase CI effect:** Because `.github/workflows/pr.yml` invokes
`pr-trusted.yml@master`, the workflow-level changes (removing Grok
clean-npm install from PR `Build`, path-gating `Canary Dry Run`/`Runner
support suite`/`general-chat`/`ci:runner-package`, passing
`CI_PLAN`/`PAPERCLIP_CI_BASE_SHA`/`PAPERCLIP_CI_FULL`, and restoring
`e2e-ui-dist`) take full effect only after merging to `master` (and
`e2e-ui-dist` warms on the first `master` push; until then `e2e_shards`
cleanly falls back to inline UI build). Furthermore, this PR modifies
global CI inputs (`turbo.json`, `scripts/**`, `.github/**`), so its own
PR CI runs the full matrix.
- **Nightly soak demotion:** The 61 real-clock soak suites in
`scripts/ci/nightly-only-suites.json` still run on every `master` push
(`release-verify.yml`), `cloud-readiness.yml`, local `pnpm test:run`,
and `full-ci`-labeled PRs, so regressions are caught post-merge rather
than blocking ordinary PRs.
- **Duration manifest rebalance:** Post-merge, the weekly
`ci-test-durations.yml` refresh will recalibrate shard weights to
reflect shared-Postgres timings for optimal LPT balance.
- **No product runtime or DB schema changes:** All changes are confined
to CI workflows, build/test orchestration scripts, test setup, test
suites, and feature-map references.

## Model Used

- Google Gemini 4 Neon (`Gemini 4 Neon (High)`), Google DeepMind, with
repository tools, code execution, and multi-agent swarm coordination.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-11-23 21:11:57 -06:00
1 parent 3cd1370141
commit 9a04538391
602 files changed
+7679 -162213

No files matched your search

+177 -4
View File
@@ -2,8 +2,17 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { getPriority } from "node:os";
import test from "node:test";
import { BACKGROUND_PRIORITY, createReporter, planLane, runLane, SERIAL_BUILD_GAPS } from "../ci-typecheck-lane.mjs";
import { PROJECTS } from "../typecheck-test-projects.mjs";
import {
BACKGROUND_PRIORITY,
createReporter,
planLane,
resolveScope,
runLane,
selectBuildGapPackages,
SERIAL_BUILD_GAPS,
shouldRunReleaseRegistryTests,
} from "../ci-typecheck-lane.mjs";
import { PROJECTS, selectTestProjects } from "../typecheck-test-projects.mjs";
const plan = () =>
planLane({
@@ -38,18 +47,25 @@ test("the shared outputs are written before the parallel checks start", () => {
test("every check of the sequential job is planned, and only declaration readers wait", () => {
const { tasks } = plan();
const byName = new Map(tasks.map((task) => [task.name, task]));
assert.deepEqual(byName.get("server declarations").args, ["server/scripts/typecheck-layers.mjs", "--declarations-only"]);
assert.deepEqual(byName.get("server declarations").args, [
"server/scripts/typecheck-layers.mjs",
"--declarations-only",
"--checkers",
"2",
]);
for (const layer of ["tests", "test-tree-0"]) {
const task = byName.get(`server layer ${layer}`);
assert.deepEqual(task.args, ["server/scripts/typecheck-layers.mjs", "--layer", layer]);
assert.deepEqual(task.args, ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"]);
assert.deepEqual(task.needs, ["server declarations"]);
}
for (const project of PROJECTS) {
const task = byName.get(`test project ${project}`);
assert.deepEqual(task.args.slice(-2), ["--reuse-declarations", project]);
assert.ok(task.args.includes("--checkers"));
assert.deepEqual(task.needs, ["server declarations"]);
}
for (const name of ["paperclipai", "@paperclipai/ui"]) assert.ok(byName.has(`typecheck ${name}`), name);
assert.deepEqual(byName.get("typecheck @paperclipai/ui").env, { GOMAXPROCS: "2" });
assert.deepEqual(byName.get("release registry tests").args, ["run", "test:release-registry"]);
assert.ok(!byName.has("CLI guidance safety"));
const waiting = tasks.filter((task) => task.needs);
@@ -60,6 +76,163 @@ test("every check of the sequential job is planned, and only declaration readers
);
});
test("resolveScope uses CI_PLAN in PR mode, honors PAPERCLIP_CI_FULL, and fails closed", () => {
const validPlan = JSON.stringify({ version: 1, mode: "enabled", forceReason: null, changed: ["server/src/a.ts"] });
assert.deepEqual(resolveScope({ root: "/repo", env: { CI_PLAN: validPlan } }), {
mode: "pr",
changedFiles: ["server/src/a.ts"],
reason: "CI_PLAN",
});
assert.equal(
resolveScope({ root: "/repo", env: { CI_PLAN: validPlan, PAPERCLIP_CI_FULL: "1" } }).mode,
"full",
);
assert.equal(
resolveScope({
root: "/repo",
env: { CI_PLAN: JSON.stringify({ mode: "full", forceReason: "Full CI requested", changed: ["server/src/a.ts"] }) },
}).mode,
"full",
);
assert.equal(
resolveScope({
root: "/repo",
env: { CI_PLAN: JSON.stringify({ mode: "enabled", forceReason: "Diff unavailable: shallow", changed: [] }) },
}).mode,
"full",
);
assert.equal(resolveScope({ root: "/repo", env: { CI_PLAN: "{bad json" } }).mode, "full");
assert.equal(resolveScope({ root: "/repo", env: {} }).mode, "full");
// Git merge-parent fallback when CI_PLAN is unset
const gitCalls = [];
const merged = resolveScope({
root: "/repo",
env: { PAPERCLIP_CI_BASE_SHA: "abc123" },
execGit: (args) => {
gitCalls.push(args);
if (args[0] === "rev-parse") return "head2sha\n";
return "server/src/x.ts\0ui/src/y.tsx\0";
},
});
assert.deepEqual(merged, {
mode: "pr",
changedFiles: ["server/src/x.ts", "ui/src/y.tsx"],
reason: "git diff HEAD^1 HEAD",
});
assert.equal(gitCalls[1].includes("HEAD^1"), true);
});
test("PR mode for a server-only change skips release registry, UI, runner, sandbox providers, and untouched test projects", () => {
const { prepare, tasks } = planLane({
buildGapPackages: [
"paperclipai",
"@paperclipai/paperclip-runner",
"@paperclipai/ui",
"@paperclipai/plugin-llm-wiki",
"@paperclipai/plugin-authoring-smoke-example",
],
testLayers: ["tests", "test-tree-0"],
changedFiles: ["server/src/services/isolated-unreferenced-feature.ts", "server/src/__tests__/isolated-unreferenced-feature.test.ts"],
});
const prepareNames = prepare.map((task) => task.name);
const taskNames = tasks.map((task) => task.name);
assert.ok(prepareNames.includes("build server without type checks"));
assert.ok(prepareNames.includes("CLI guidance safety"));
assert.ok(!prepareNames.includes("install test program dependencies"));
assert.ok(!prepareNames.includes("typecheck @paperclipai/paperclip-runner"));
assert.ok(taskNames.includes("server declarations"));
assert.ok(taskNames.includes("server layer tests"));
assert.ok(taskNames.includes("typecheck paperclipai"));
assert.ok(!taskNames.includes("release registry tests"));
assert.ok(!taskNames.includes("typecheck test programs"));
assert.ok(!taskNames.includes("typecheck @paperclipai/ui"));
assert.ok(!taskNames.includes("typecheck @paperclipai/plugin-llm-wiki"));
assert.ok(!taskNames.includes("typecheck @paperclipai/plugin-authoring-smoke-example"));
for (const skipped of PROJECTS) {
assert.ok(!taskNames.includes(`test project ${skipped}`), skipped);
}
});
test("selectTestProjects follows the import graph so imported UI and server helpers trigger their callers", () => {
for (const helper of [
"ui/src/lib/company-routes.ts",
"ui/src/lib/issue-reference.ts",
"ui/src/lib/markdown-reply-content.ts",
]) {
assert.deepEqual(selectTestProjects([helper]), ["tests/runner-e2e"], helper);
}
assert.deepEqual(selectTestProjects(["ui/src/components/Sidebar.tsx"]), []);
assert.ok(selectTestProjects(["server/src/services/issues.ts"]).includes("tests/runner-e2e"));
assert.ok(selectTestProjects(["server/src/services/issues.ts"]).includes("server/src/__tests__/helpers/maintenance"));
assert.ok(selectTestProjects(["tests/unknown-new-project/a.ts"], [...PROJECTS, "tests/unknown-new-project"]).includes("tests/unknown-new-project"));
const uiHelperPlan = planLane({
buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"],
testLayers: ["tests"],
changedFiles: ["ui/src/lib/company-routes.ts"],
});
assert.ok(uiHelperPlan.tasks.some((t) => t.name === "server declarations"));
assert.ok(uiHelperPlan.tasks.some((t) => t.name === "test project tests/runner-e2e"));
assert.ok(uiHelperPlan.tasks.some((t) => t.name === "typecheck @paperclipai/ui"));
});
test("PR mode for a pure UI component change skips server build/declarations, release registry, and sandbox providers", () => {
const { prepare, tasks } = planLane({
buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"],
testLayers: ["tests", "test-tree-0"],
changedFiles: ["ui/src/components/Sidebar.tsx", "ui/src/components/Sidebar.test.tsx"],
});
const prepareNames = prepare.map((task) => task.name);
const taskNames = tasks.map((task) => task.name);
assert.ok(prepareNames.includes("CLI guidance safety"));
assert.ok(!prepareNames.includes("build server without type checks"));
assert.ok(!prepareNames.includes("install test program dependencies"));
assert.ok(!taskNames.includes("server declarations"));
assert.ok(!taskNames.includes("release registry tests"));
assert.ok(!taskNames.includes("typecheck paperclipai"));
assert.ok(taskNames.includes("typecheck @paperclipai/ui"));
const programs = tasks.find((task) => task.name === "typecheck test programs");
assert.ok(programs.args.includes("--no-providers"));
assert.ok(programs.args.includes("--check-file"));
assert.ok(programs.args.includes("ui/src/components/Sidebar.test.tsx"));
assert.ok(programs.args.includes("tests/tsconfig.playwright.json"));
});
test("PR mode runs release registry tests for scripts, workflows, manifests, and release files", () => {
assert.equal(shouldRunReleaseRegistryTests(["server/src/index.ts"]), false);
assert.equal(shouldRunReleaseRegistryTests(["ui/src/pages/Issues.tsx"]), false);
for (const trigger of [
"scripts/release.sh",
".github/workflows/pr-trusted.yml",
"package.json",
"server/package.json",
"releases/v2026.11.0.md",
"Dockerfile",
]) {
assert.equal(shouldRunReleaseRegistryTests([trigger]), true, trigger);
}
});
test("PR mode fails closed for unknown build-gap packages and global typecheck inputs", () => {
assert.deepEqual(selectBuildGapPackages(["@paperclipai/ui", "@paperclipai/new-pkg"], ["server/src/a.ts"]), [
"@paperclipai/new-pkg",
]);
const globalPlan = planLane({
buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"],
testLayers: ["tests"],
changedFiles: ["tsconfig.base.json"],
});
assert.ok(globalPlan.prepare.some((t) => t.name === "install test program dependencies"));
assert.ok(globalPlan.prepare.some((t) => t.name === "typecheck @paperclipai/paperclip-runner"));
assert.ok(globalPlan.tasks.some((t) => t.name === "typecheck @paperclipai/ui"));
assert.ok(globalPlan.tasks.some((t) => t.name === "test project tests/runner-e2e"));
});
test("checks run at most the given number at a time, in priority order", async () => {
let running = 0;
let peak = 0;
+50 -16
View File
@@ -7,7 +7,15 @@ import { fileURLToPath } from "node:url";
import test from "node:test";
import { defaultSuiteWeight, loadShardDurations } from "../general-server-shard.mjs";
import { IGNORED_SPECS, listE2eSpecs, selectE2eShard } from "../e2e-shard.mjs";
import {
DEFAULT_PARALLEL_WORKERS,
IGNORED_SPECS,
SERIAL_SPECS,
isSerialE2eSpec,
listE2eSpecs,
partitionE2eShards,
selectE2eShard,
} from "../e2e-shard.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
const script = path.join(repoRoot, "scripts", "e2e-shard.mjs");
@@ -124,6 +132,32 @@ test("the ignored spec list matches playwright.config.ts testIgnore", () => {
assert.deepEqual([...configured].sort(), [...IGNORED_SPECS].sort());
});
test("the serial spec list matches playwright.config.ts SERIAL_SPECS and never mixes with parallel specs", () => {
const config = readFileSync(playwrightConfig, "utf8");
const match = config.match(/export const SERIAL_SPECS = \[([\s\S]*?)\];/);
assert.ok(match, "expected a SERIAL_SPECS array in playwright.config.ts");
const configured = [...match[1].matchAll(/"([^"]+)"/g)].map((entry) => entry[1]);
assert.deepEqual([...configured].sort(), [...SERIAL_SPECS].sort());
const specs = listE2eSpecs();
const durations = loadShardDurations(durationsManifest);
const shards = partitionE2eShards(specs, SHARD_COUNT, durations);
assert.equal(shards.length, SHARD_COUNT);
for (const shard of shards) {
const serialCount = shard.files.filter(isSerialE2eSpec).length;
assert.ok(
serialCount === 0 || serialCount === shard.files.length,
`shard must not mix serial and parallel specs: ${shard.files.join(", ")}`,
);
}
});
test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1", () => {
const config = readFileSync(playwrightConfig, "utf8");
assert.match(config, /PAPERCLIP_E2E_SKIP_UI_BUILD/);
assert.match(config, /ui-dist.*index\.html/);
});
test("the duration manifest only names specs that still exist", () => {
const durations = loadShardDurations(durationsManifest);
assert.ok(Object.keys(durations).length > 0, "expected a populated duration manifest");
@@ -136,25 +170,25 @@ test("the duration manifest only names specs that still exist", () => {
test("the weighted partition keeps the shards close to balanced", () => {
const durations = loadShardDurations(durationsManifest);
const specs = listE2eSpecs();
// New specs use the scheduler's median estimate until measured durations exist.
const fallbackWeight = defaultSuiteWeight(durations);
const weights = Array.from({ length: SHARD_COUNT }, (_, index) =>
selectE2eShard(specs, index, SHARD_COUNT, durations).reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0),
);
const shards = partitionE2eShards(specs, SHARD_COUNT, durations, {
parallelWorkers: DEFAULT_PARALLEL_WORKERS,
});
const wallWeights = shards.map((shard) => {
const serialSum = shard.files.reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0);
return shard.mode === "parallel" ? serialSum / DEFAULT_PARALLEL_WORKERS : serialSum;
});
const heaviest = Math.max(...weights);
const total = weights.reduce((sum, weight) => sum + weight, 0);
// Round-robin/count-based sharding would strand the ~168s smoke-lab spec on
// one runner alongside other specs. Assert the weighted split stays within
// 15% of an even cut so a future spec-time regression surfaces here instead
// of on the PR critical path. A single indivisible spec (smoke-lab) can
// legitimately exceed the even cut on its own, so the bound is floored at
// the largest per-spec weight — the best any file-level partition can do.
const largestSpec = Math.max(...specs.map((file) => durations[file] ?? fallbackWeight));
const bound = Math.max((total / SHARD_COUNT) * 1.15, largestSpec);
const heaviest = Math.max(...wallWeights);
const totalWall = wallWeights.reduce((sum, weight) => sum + weight, 0);
const largestSerialSpec = Math.max(
0,
...specs.filter(isSerialE2eSpec).map((file) => durations[file] ?? fallbackWeight),
);
const bound = Math.max((totalWall / SHARD_COUNT) * 1.15, largestSerialSpec);
assert.ok(
heaviest <= bound,
`heaviest shard ${heaviest}ms exceeds the balance bound (${bound}ms)`,
`heaviest shard ${Math.round(heaviest)}ms exceeds the balance bound (${Math.round(bound)}ms)`,
);
});
@@ -48,15 +48,15 @@ test('the warm-up refuses to run without the cache the verifier will read', () =
assert.match(result.stderr, /PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE/);
});
test('the Build lane warms the cache before pnpm build and hands the same directory to the verifier', () => {
const workflow = readFileSync(new URL('../../.github/workflows/pr-trusted.yml', import.meta.url), 'utf8');
const build = workflow.slice(workflow.indexOf('\n build:\n'), workflow.indexOf('\n verify_serialized_server:\n'));
const position = fragment => { const index = build.indexOf(fragment); assert.notEqual(index, -1, `Build job must contain ${fragment}`); return index; };
const warm = position('PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE="$RUNNER_TEMP/public-install-npm-cache" node scripts/warm-public-install-npm-cache.mjs');
assert.ok(position('- name: Install dependencies') < warm && warm < position('- name: Build\n'), 'the warm-up overlaps the Rust restore and pnpm build');
assert.ok(build.includes('set +e\n'), 'a failed warm-up still records its status, so the verifier never waits it out');
const verify = position('export PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE="$RUNNER_TEMP/public-install-npm-cache"');
assert.ok(verify < position('node scripts/verify-grok-npm-install.mjs'));
test('public npm install verification stays in release/docker checks rather than PR Build', () => {
const prWorkflow = readFileSync(new URL('../../.github/workflows/pr-trusted.yml', import.meta.url), 'utf8');
const build = prWorkflow.slice(prWorkflow.indexOf('\n build:\n'), prWorkflow.indexOf('\n verify_serialized_server:\n'));
assert.ok(!build.includes('node scripts/verify-grok-npm-install.mjs'), 'PR Build skips the 4-min public npm install verifier');
assert.ok(!build.includes('warm-public-install-npm-cache.mjs'), 'PR Build does not warm the unused public npm install cache');
const releaseSmoke = readFileSync(new URL('../../.github/workflows/release-smoke.yml', import.meta.url), 'utf8');
assert.ok(releaseSmoke.includes('node scripts/verify-grok-npm-install.mjs'), 'release-smoke.yml covers verify-grok-npm-install.mjs');
const dockerRunner = readFileSync(new URL('../../.github/workflows/docker-runner-check.yml', import.meta.url), 'utf8');
assert.ok(dockerRunner.includes('node scripts/verify-grok-npm-install.mjs'), 'docker-runner-check.yml covers verify-grok-npm-install.mjs');
const verifier = readFileSync(new URL('../verify-grok-npm-install.mjs', import.meta.url), 'utf8');
assert.ok(verifier.includes("const cache = process.env.PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE ? resolve(process.env.PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE) : join(root, 'cache');"));
});
@@ -0,0 +1,235 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { selectionHash } from "../ci/test-selection-manifest.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
const script = path.join(repoRoot, "scripts", "run-vitest-stable.mjs");
const nativeRunnerSuitePath = "server/src/services/native-runtime/plugin-runner-probe.test.ts";
function workflowEnv(envOverrides = {}) {
const env = { ...process.env, ...envOverrides };
for (const key of [
"GITHUB_WORKFLOW",
"PAPERCLIP_CI_FULL",
"PAPERCLIP_CI_EXCLUDE_NIGHTLY",
"PAPERCLIP_CI_NIGHTLY_SUITES_FILE",
"PAPERCLIP_VITEST_MAX_WORKERS",
"PAPERCLIP_TEST_POSTGRES_ADMIN_URL",
"PAPERCLIP_CI_TEST_SELECTION",
"PAPERCLIP_CI_SELECTION_HASH",
]) {
if (!(key in envOverrides)) {
delete env[key];
}
}
return env;
}
function dryRunJson(args, envOverrides = {}) {
const result = spawnSync(process.execPath, [script, ...args, "--dry-run"], {
cwd: repoRoot,
encoding: "utf8",
env: workflowEnv(envOverrides),
});
assert.equal(result.status, 0, `expected success for ${args.join(" ")}: ${result.stderr}`);
return JSON.parse(result.stdout);
}
test("general-workspaces-b and general-workspaces-a batch all projects into one vitest invocation", { skip: process.platform === "win32" }, () => {
const directory = mkdtempSync(path.join(os.tmpdir(), "batch-workspaces-"));
const receipt = path.join(directory, "calls.ndjson");
const fakePnpm = path.join(directory, "pnpm");
writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').appendFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n`);
chmodSync(fakePnpm, 0o755);
try {
const run = (args) => {
rmSync(receipt, { force: true });
const result = spawnSync(process.execPath, [script, ...args], {
cwd: repoRoot,
encoding: "utf8",
env: workflowEnv({
PATH: `${directory}${path.delimiter}${process.env.PATH}`,
PAPERCLIP_CI_PROFILE: "false",
PAPERCLIP_TEST_POSTGRES_SHARED: "0",
}),
});
assert.equal(result.status, 0, result.stdout + result.stderr);
return readFileSync(receipt, "utf8").trim().split("\n").map((line) => JSON.parse(line));
};
const workspacesBProjects = dryRunJson(["--mode", "general", "--group", "general-workspaces-b"]).workspaceProjects;
const bCalls = run(["--mode", "general", "--group", "general-workspaces-b"]);
assert.equal(bCalls.length, 1, "general-workspaces-b must invoke vitest once for all projects");
const bProjectsArg = bCalls[0].flatMap((arg, index) => (arg === "--project" ? [bCalls[0][index + 1]] : []));
assert.deepEqual(bProjectsArg, workspacesBProjects);
const workspacesAProjects = dryRunJson(["--mode", "general", "--group", "general-workspaces-a"]).workspaceProjects;
const aCalls = run(["--mode", "general", "--group", "general-workspaces-a", "--shard-index", "1", "--shard-count", "2"]);
assert.equal(aCalls.length, 1, "general-workspaces-a must invoke vitest once for all projects in the shard");
const aProjectsArg = aCalls[0].flatMap((arg, index) => (arg === "--project" ? [aCalls[0][index + 1]] : []));
assert.deepEqual(aProjectsArg, workspacesAProjects);
assert.ok(aCalls[0].includes("--shard=2/2"));
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
test("nightly-only suites manifest excludes listed suites only in PR mode and respects PAPERCLIP_CI_FULL=1", { skip: process.platform === "win32" }, () => {
const directory = mkdtempSync(path.join(os.tmpdir(), "nightly-manifest-"));
const manifestFile = path.join(directory, "nightly-only-suites.json");
const fullGeneral = dryRunJson(["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"], { GITHUB_WORKFLOW: "PR", PAPERCLIP_CI_FULL: "1" });
const sampleGeneralSuite = fullGeneral.selectedGeneralServerSuites[0];
const sampleKeptGeneralSuite = fullGeneral.selectedGeneralServerSuites[1];
const fullSerialized = dryRunJson(["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"]);
const sampleSerializedSuite = fullSerialized.selectedSerializedSuites[0];
const sampleNativeSuite = nativeRunnerSuitePath;
const sampleDbSuite = "packages/db/src/client.test.ts";
writeFileSync(manifestFile, JSON.stringify({
$comment: "fixture manifest",
suites: [
{ path: sampleGeneralSuite, category: "soak", reason: "fixture", measuredMs: 120000 },
sampleSerializedSuite,
{ path: sampleNativeSuite, category: "restart-lease-soak", reason: "fixture", measuredMs: 200000 },
{ path: sampleDbSuite, category: "db-soak", reason: "fixture", measuredMs: 90000 },
],
}, null, 2));
try {
const prEnv = { GITHUB_WORKFLOW: "PR", PAPERCLIP_CI_NIGHTLY_SUITES_FILE: manifestFile };
const prGeneral = dryRunJson(["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"], prEnv);
assert.equal(prGeneral.nightlyExclusionActive, true);
assert.ok(!prGeneral.selectedGeneralServerSuites.includes(sampleGeneralSuite));
assert.deepEqual(prGeneral.excludedNightlySuites, [sampleGeneralSuite]);
const prSerialized = dryRunJson(["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"], prEnv);
assert.ok(!prSerialized.selectedSerializedSuites.includes(sampleSerializedSuite));
assert.equal(prSerialized.serializedSuiteCount, fullSerialized.serializedSuiteCount - 1);
assert.deepEqual(prSerialized.excludedNightlySuites, [sampleSerializedSuite]);
const prNative = dryRunJson(["--mode", "general", "--group", "general-server-native-runner"], prEnv);
assert.ok(!prNative.selectedGeneralServerSuites.includes(sampleNativeSuite));
assert.deepEqual(prNative.excludedNightlySuites, [sampleNativeSuite]);
// PAPERCLIP_CI_FULL=1, Release, Cloud readiness, and local runs retain all suites.
for (const fullEnv of [
{ ...prEnv, PAPERCLIP_CI_FULL: "1" },
{ GITHUB_WORKFLOW: "Release", PAPERCLIP_CI_NIGHTLY_SUITES_FILE: manifestFile },
{ GITHUB_WORKFLOW: "Cloud readiness", PAPERCLIP_CI_NIGHTLY_SUITES_FILE: manifestFile },
{ PAPERCLIP_CI_NIGHTLY_SUITES_FILE: manifestFile },
]) {
const general = dryRunJson(["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"], fullEnv);
assert.equal(general.nightlyExclusionActive, false);
assert.deepEqual(general.excludedNightlySuites, []);
assert.ok(general.selectedGeneralServerSuites.includes(sampleGeneralSuite));
const serialized = dryRunJson(["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"], fullEnv);
assert.ok(serialized.selectedSerializedSuites.includes(sampleSerializedSuite));
const native = dryRunJson(["--mode", "general", "--group", "general-server-native-runner"], fullEnv);
assert.ok(native.selectedGeneralServerSuites.includes(sampleNativeSuite));
}
// Empty-list guard: when every native-runner suite is excluded in PR mode, vitest must NOT run unfiltered.
const allNative = dryRunJson(["--mode", "general", "--group", "general-server-native-runner"]).selectedGeneralServerSuites;
const allNativeManifest = path.join(directory, "all-native-nightly.json");
writeFileSync(allNativeManifest, JSON.stringify({ suites: allNative }));
const receipt = path.join(directory, "empty-guard-calls.ndjson");
const fakePnpm = path.join(directory, "pnpm");
writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').appendFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n`);
chmodSync(fakePnpm, 0o755);
const emptyResult = spawnSync(process.execPath, [script, "--mode", "general", "--group", "general-server-native-runner"], {
cwd: repoRoot,
encoding: "utf8",
env: workflowEnv({
GITHUB_WORKFLOW: "PR",
PAPERCLIP_CI_NIGHTLY_SUITES_FILE: allNativeManifest,
PAPERCLIP_CI_PROFILE: "false",
PAPERCLIP_TEST_POSTGRES_SHARED: "0",
PATH: `${directory}${path.delimiter}${process.env.PATH}`,
}),
});
assert.equal(emptyResult.status, 0, emptyResult.stdout + emptyResult.stderr);
assert.equal(existsSync(receipt), false, "an empty filtered suite set must skip vitest instead of running unfiltered");
// Selected runs in PR mode also filter nightly-only suites unless PAPERCLIP_CI_FULL=1.
const selectionFile = path.join(directory, "selection-manifest.json");
const head = spawnSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" }).stdout.trim();
const selManifest = {
version: 1,
head,
lanes: {
"general-server-without-chat": {
shards: [{ "@paperclipai/server": [sampleGeneralSuite, sampleKeptGeneralSuite] }],
},
},
};
writeFileSync(selectionFile, JSON.stringify(selManifest));
const selHash = selectionHash(selManifest);
const prSelected = dryRunJson(
["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"],
{ ...prEnv, PAPERCLIP_CI_TEST_SELECTION: selectionFile, PAPERCLIP_CI_SELECTION_HASH: selHash },
);
assert.deepEqual(prSelected.selection["@paperclipai/server"], [sampleKeptGeneralSuite], "selected PR run must drop nightly-only suite");
const fullSelected = dryRunJson(
["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"],
{ ...prEnv, PAPERCLIP_CI_FULL: "1", PAPERCLIP_CI_TEST_SELECTION: selectionFile, PAPERCLIP_CI_SELECTION_HASH: selHash },
);
assert.deepEqual(
fullSelected.selection["@paperclipai/server"],
[sampleGeneralSuite, sampleKeptGeneralSuite],
"PAPERCLIP_CI_FULL=1 selected run must keep nightly-only suite",
);
// general-workspaces-c forwards packages/db nightly excludes to vitest --exclude.
rmSync(receipt, { force: true });
const dbResult = spawnSync(process.execPath, [script, "--mode", "general", "--group", "general-workspaces-c"], {
cwd: repoRoot,
encoding: "utf8",
env: workflowEnv({
...prEnv,
PAPERCLIP_CI_PROFILE: "false",
PAPERCLIP_TEST_POSTGRES_SHARED: "0",
PATH: `${directory}${path.delimiter}${process.env.PATH}`,
}),
});
assert.equal(dbResult.status, 0, dbResult.stdout + dbResult.stderr);
const dbCall = JSON.parse(readFileSync(receipt, "utf8").trim());
assert.ok(dbCall.includes("--exclude") && dbCall.includes("src/client.test.ts"), `expected db nightly exclude in ${dbCall.join(" ")}`);
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
test("shared Postgres wrapper skips non-Postgres workspace groups even when opted in", { skip: process.platform === "win32" }, () => {
const directory = mkdtempSync(path.join(os.tmpdir(), "shared-pg-skip-"));
const receipt = path.join(directory, "env.json");
const fakePnpm = path.join(directory, "pnpm");
writeFileSync(
fakePnpm,
`#!/usr/bin/env node\nrequire('node:fs').writeFileSync(${JSON.stringify(receipt)}, JSON.stringify({ admin: process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL ?? null, template: process.env.PAPERCLIP_TEST_POSTGRES_TEMPLATE ?? null }));\n`,
);
chmodSync(fakePnpm, 0o755);
try {
for (const group of ["general-workspaces-a", "general-workspaces-b"]) {
rmSync(receipt, { force: true });
const result = spawnSync(process.execPath, [script, "--mode", "general", "--group", group], {
cwd: repoRoot,
encoding: "utf8",
env: workflowEnv({
PATH: `${directory}${path.delimiter}${process.env.PATH}`,
PAPERCLIP_CI_PROFILE: "false",
PAPERCLIP_TEST_POSTGRES_SHARED: "1",
}),
});
assert.equal(result.status, 0, result.stdout + result.stderr);
assert.deepEqual(JSON.parse(readFileSync(receipt, "utf8")), { admin: null, template: null }, `${group} must not boot shared Postgres`);
}
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
@@ -31,8 +31,17 @@ const serializedDurationsManifest = path.join(
// themselves run inside a workflow on CI.
function workflowEnv(envOverrides = {}) {
const env = { ...process.env, ...envOverrides };
if (!("GITHUB_WORKFLOW" in envOverrides)) {
delete env.GITHUB_WORKFLOW;
for (const key of [
"GITHUB_WORKFLOW",
"PAPERCLIP_CI_FULL",
"PAPERCLIP_CI_EXCLUDE_NIGHTLY",
"PAPERCLIP_CI_NIGHTLY_SUITES_FILE",
"PAPERCLIP_VITEST_MAX_WORKERS",
"PAPERCLIP_TEST_POSTGRES_ADMIN_URL",
]) {
if (!(key in envOverrides)) {
delete env[key];
}
}
return env;
}
@@ -383,7 +392,11 @@ test("12 PR without-chat shards plus the dedicated chat and native-runner lanes
assert.ok(!files.includes(pluginWarmOwnerSuitePath));
assert.ok(!files.includes(pluginReleaseResumeSuitePath));
assert.ok(!files.includes(pluginEvictionSuitePath));
assert.deepEqual([...files, chatSuitePath, nativeRunnerSuitePath, ingressRetrySuitePath, dotRunnerSuitePath, restartRecoverySuitePath, ...restartWaitSuites, cutTurnStartRetrySuitePath, usageDeliverySuitePath, warmCheckpointOwnershipSuitePath, warmSuccessorRunnerReleaseSuitePath, pluginWarmOwnerSuitePath, pluginReleaseResumeSuitePath, pluginEvictionSuitePath, "server/src/services/native-runtime/plugin-runner-probe.test.ts"].sort(), full.selectedGeneralServerSuites.sort());
const excludedNightly = shards[0].excludedNightlySuites ?? [];
for (const shard of shards) {
assert.deepEqual(shard.excludedNightlySuites ?? [], excludedNightly, "nightly exclusions must agree across shards");
}
assert.deepEqual([...files, ...excludedNightly, chatSuitePath, nativeRunnerSuitePath, ingressRetrySuitePath, dotRunnerSuitePath, restartRecoverySuitePath, ...restartWaitSuites, cutTurnStartRetrySuitePath, usageDeliverySuitePath, warmCheckpointOwnershipSuitePath, warmSuccessorRunnerReleaseSuitePath, pluginWarmOwnerSuitePath, pluginReleaseResumeSuitePath, pluginEvictionSuitePath, "server/src/services/native-runtime/plugin-runner-probe.test.ts"].sort(), full.selectedGeneralServerSuites.sort());
assert.equal(new Set(files).size, files.length);
const defaultRun = dryRunJson([], prEnv);
assert.ok(defaultRun.generalServerSuiteCount === full.generalServerSuiteCount);
@@ -468,7 +481,11 @@ test("the PR workflow wiring for the native-runner lane holds", () => {
const vitestLanes = matrix.verify_paperclip_runner.filter((entry) => entry.command.startsWith("test:typescript:vitest"));
for (const entry of vitestLanes) {
assert.match(entry.command, /^test:typescript:vitest (--package-lane=\d+\/\d+|--native-server)$/, entry.lane_label);
assert.equal(entry.task, "ci:runner-vitest", entry.lane_label);
assert.equal(
entry.task,
entry.command.endsWith("--native-server") ? "ci:runner-vitest" : "ci:runner-package",
entry.lane_label,
);
}
const lanes = vitestLanes
.map((entry) => /--package-lane=(\d+)\/(\d+)$/.exec(entry.command))
@@ -769,7 +786,8 @@ function defaultLauncher({ shared = false, failureIndex = null } = {}) {
const result = spawnSync(process.execPath, [script, "--mode", "general"], {
cwd: repoRoot, encoding: "utf8", timeout: 30_000,
env: workflowEnv({ GITHUB_WORKFLOW: "PR", PATH: `${directory}${path.delimiter}${process.env.PATH}`,
PAPERCLIP_TEST_DATABASE_URL: shared ? "postgresql://shared/test" : "", PAPERCLIP_CI_PROFILE: "false" }),
PAPERCLIP_TEST_DATABASE_URL: shared ? "postgresql://shared/test" : "", PAPERCLIP_CI_PROFILE: "false",
PAPERCLIP_TEST_POSTGRES_SHARED: "0" }),
});
const events = existsSync(receipt) ? readFileSync(receipt, "utf8").trim().split("\n").map(line => JSON.parse(line)) : [];
return { result, events, lines };
@@ -857,7 +875,7 @@ test("a failed chat child fails the job after its sibling finishes", { skip: pro
"--shard-index", "0", "--shard-count", "3"], {
cwd: repoRoot, encoding: "utf8", timeout: 30_000,
env: { ...process.env, PATH: `${directory}${path.delimiter}${process.env.PATH}`,
PAPERCLIP_TEST_DATABASE_URL: "", PAPERCLIP_CI_PROFILE: "false" },
PAPERCLIP_TEST_DATABASE_URL: "", PAPERCLIP_CI_PROFILE: "false", PAPERCLIP_TEST_POSTGRES_SHARED: "0" },
});
assert.equal(result.status, 1, result.stdout + result.stderr);
assert.match(result.stderr, /failed \(7\)/);
@@ -867,10 +885,11 @@ test("a failed chat child fails the job after its sibling finishes", { skip: pro
}
});
for (const [group, parallelWorkers, shardArgs] of [
["general-server-native-runner", 4, []],
["general-server-without-chat-or-native-runner", 3, ["--shard-index", "0", "--shard-count", "12"]],
]) test(`${group} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => {
for (const [label, modeArgs, parallelWorkers] of [
["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], 4],
["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], 4],
["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], 3],
]) test(`${label} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => {
const directory = mkdtempSync(path.join(os.tmpdir(), "native-file-workers-"));
const receipt = path.join(directory, "args.json");
const fakePnpm = path.join(directory, "pnpm");
@@ -882,19 +901,24 @@ for (const [group, parallelWorkers, shardArgs] of [
[{ PAPERCLIP_TEST_DATABASE_URL: "postgresql://shared/test" }, 1],
[{ PAPERCLIP_ISSUE_RECOVERY_TEST_DATABASE_URL: "postgresql://shared/recovery_test" }, 1],
[{ PAPERCLIP_TEST_POSTGRES_ADMIN_URL: "postgresql://owned/postgres" }, parallelWorkers],
[{ PAPERCLIP_VITEST_MAX_WORKERS: "2" }, 2],
]) {
const env = workflowEnv({ PATH: `${directory}${path.delimiter}${process.env.PATH}`, PAPERCLIP_CI_PROFILE: "false" });
const env = workflowEnv({
PATH: `${directory}${path.delimiter}${process.env.PATH}`,
PAPERCLIP_CI_PROFILE: "false",
PAPERCLIP_TEST_POSTGRES_SHARED: "0",
});
for (const key of Object.keys(env)) if (key.endsWith("_TEST_DATABASE_URL")) delete env[key];
Object.assign(env, databaseEnv);
const result = spawnSync(process.execPath, [script, "--mode", "general", "--group", group, ...shardArgs], {
const result = spawnSync(process.execPath, [script, ...modeArgs], {
cwd: repoRoot, encoding: "utf8", env,
});
assert.equal(result.status, 0, result.stdout + result.stderr);
const args = JSON.parse(readFileSync(receipt, "utf8"));
assert.ok(args.includes(`--maxWorkers=${workers}`));
assert.ok(args.includes(`--maxWorkers=${workers}`), `expected --maxWorkers=${workers} in ${args.join(" ")}`);
assert.ok(args.includes(workers > 1 ? "--fileParallelism" : "--no-file-parallelism"));
if (workers > 1) assert.ok(args.includes("--pool=forks") && args.includes("--isolate"));
if (group === "general-server-native-runner") {
if (label === "general-server-native-runner") {
for (const file of [restartRecoverySuitePath, ...restartWaitSuites]) assert.ok(args.includes(file));
}
}
@@ -362,11 +362,14 @@ test("the Verify Paperclip Runner job restores the crate only in the lanes that
const lanes = JSON.parse(readFileSync(path.join(repoRoot, ".github/ci-task-matrix.json"), "utf8"))
.verify_paperclip_runner.map((entry) => [entry.lane_label, entry.release_crate === true]);
assert.deepEqual(lanes, [
["static checks", false],
["static checks", true],
["rust", true],
["vitest package (1/3)", false],
["vitest package (2/3)", false],
["vitest package (3/3)", false],
["vitest package (1/6)", false],
["vitest package (2/6)", false],
["vitest package (3/6)", false],
["vitest package (4/6)", false],
["vitest package (5/6)", false],
["vitest package (6/6)", false],
["vitest native server", true],
]);
for (const stepName of [KEY_STEP, RESTORE_STEP]) {
@@ -419,7 +422,9 @@ test("only the master Rust lane writes the crate, after a lookup, with the reade
// The dependency cache's own writer gate is the same expression.
assert.match(body, new RegExp(`save-if: \\$\\{\\{ ${WRITER_GATE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} \\}\\}`));
assert.equal((releaseWorkflow.match(/actions\/cache\/save@/g) ?? []).length, 2, "release and debug workspace caches have separate guarded writers");
assert.equal((body.match(/actions\/cache\/save@/g) ?? []).length, 2, "release and debug workspace caches have separate guarded writers");
// The only other cache save in release-verify.yml is the master-guarded E2E UI dist writer in `build`.
assert.equal((releaseWorkflow.match(/actions\/cache\/save@/g) ?? []).length, 3, "release-verify.yml has guarded writers for release crate, debug crate, and E2E UI dist");
});
test("the scope names the platform, the compiler and the checkout root, and survives a missing rustc", () => {
-1
View File
@@ -62,7 +62,6 @@ export const ALLOWLIST = new Set([
"ui/src/artifact-directions/main.tsx:retry-false",
"ui/src/wizard-preview-main.tsx:retry-false",
"ui/src/fixtures/TaskChatPerfHarness.tsx:retry-false",
"ui/src/pages/NewAgent.test-support.tsx:retry-false",
"ui/src/components/TaskChatThread.tsx:is-error-render",
"ui/src/components/transcript/RunTranscriptView.tsx:is-error-render",
"ui/src/components/task-chat/transcript-adapter.ts:is-error-render",
+341 -51
View File
@@ -1,79 +1,344 @@
#!/usr/bin/env node
import { spawn, spawnSync } from "node:child_process";
import { execFileSync, spawn, spawnSync } from "node:child_process";
import { availableParallelism, setPriority } 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 } from "./run-tsc.mjs";
import { PROJECTS } from "./typecheck-test-projects.mjs";
import { selectTestPrograms } from "./typecheck-test-programs.mjs";
import { PROJECTS, 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 = 2;
const SERVER_DECLARATIONS = "server declarations";
export const CLI_GUIDANCE_SAFETY = "CLI guidance safety";
const lowMemory = { [LOW_MEMORY_VARIABLE]: "1" };
export function planLane({ buildGapPackages, testLayers, projects = PROJECTS }) {
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/plugins/sdk/",
"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),
);
}
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,
testProgramsConcurrency = DEFAULT_TEST_PROGRAMS_CONCURRENCY,
}) {
const isPrMode = Array.isArray(changedFiles);
const selectedBuildGaps = selectBuildGapPackages(buildGapPackages, changedFiles);
const selectedProjects = selectTestProjects(changedFiles, projects);
const runServer = shouldRunServerTypecheck(changedFiles, selectedProjects);
const runReleaseRegistry = shouldRunReleaseRegistryTests(changedFiles);
const programSelection = selectTestPrograms(changedFiles);
const typecheckPackage = (name, background) => ({
name: `typecheck ${name}`,
command: "pnpm",
args: ["--filter", name, "typecheck"],
env: lowMemory,
// UI typecheck runs ~7x faster without --singleThreaded while staying at ~4.4 GiB with GOMAXPROCS=2.
env: name === "@paperclipai/ui" ? { GOMAXPROCS: "2" } : lowMemory,
background,
});
const prepare = [
{ name: "link workspace packages", command: "pnpm", args: ["run", "preflight:workspace-links"] },
{ name: "build plugin SDK", command: "pnpm", args: ["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"] },
{
name: "build server without type checks",
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: "pnpm",
args: ["--filter", "@paperclipai/server", "build"],
env: { [EMIT_ONLY_VARIABLE]: "1" },
},
{
name: "check server runtime assets",
command: "node",
args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"],
},
{ name: "install test program dependencies", command: "node", args: ["scripts/typecheck-test-programs.mjs", "--prepare-only"] },
...buildGapPackages.filter((name) => SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, false)),
args: ["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"],
});
}
if (runServer) {
prepare.push(
{
name: "build server without type checks",
command: "pnpm",
args: ["--filter", "@paperclipai/server", "build"],
env: { [EMIT_ONLY_VARIABLE]: "1" },
},
{
name: "check server runtime assets",
command: "node",
args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"],
},
);
}
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 needsDeclarations = [SERVER_DECLARATIONS];
const tasks = [
{
const tasks = [];
if (runServer) {
tasks.push({
name: SERVER_DECLARATIONS,
command: "node",
args: ["server/scripts/typecheck-layers.mjs", "--declarations-only"],
env: lowMemory,
},
{ name: "release registry tests", command: "pnpm", args: ["run", "test:release-registry"] },
{
args: ["server/scripts/typecheck-layers.mjs", "--declarations-only", "--checkers", "2"],
});
}
if (runReleaseRegistry) {
tasks.push({ name: "release registry tests", command: "pnpm", args: ["run", "test:release-registry"] });
}
if (programSelection.programs.length > 0 || programSelection.checkCoverage) {
const programArgs = [
"scripts/typecheck-test-programs.mjs",
"--skip-prepare",
"--checkers",
"1",
"--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: ["scripts/typecheck-test-programs.mjs", "--low-memory", "--skip-prepare"],
args: programArgs,
background: true,
},
...testLayers.map((layer) => ({
name: `server layer ${layer}`,
command: "node",
args: ["server/scripts/typecheck-layers.mjs", "--layer", layer],
env: lowMemory,
needs: needsDeclarations,
})),
...projects.map((project) => ({
name: `test project ${project}`,
command: "node",
args: ["scripts/typecheck-test-projects.mjs", "--low-memory", "--reuse-declarations", project],
needs: needsDeclarations,
})),
...buildGapPackages.filter((name) => !SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, true)),
];
});
}
if (runServer) {
tasks.push(
...testLayers.map((layer) => ({
name: `server layer ${layer}`,
command: "node",
args: ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"],
needs: needsDeclarations,
})),
...selectedProjects.map((project) => ({
name: `test project ${project}`,
command: "node",
args: ["scripts/typecheck-test-projects.mjs", "--checkers", "1", "--reuse-declarations", project],
needs: needsDeclarations,
})),
);
}
tasks.push(
...selectedBuildGaps.filter((name) => !SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, true)),
);
return { prepare, tasks };
}
@@ -259,11 +524,26 @@ function listBuildGapPackages(root) {
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2);
const concurrencyIndex = args.indexOf("--concurrency");
const concurrency = concurrencyIndex === -1 ? availableParallelism() : Number(args[concurrencyIndex + 1]);
const extra = args.filter((_, index) => concurrencyIndex === -1 || (index !== concurrencyIndex && index !== concurrencyIndex + 1));
if (!Number.isInteger(concurrency) || concurrency < 1 || extra.length > 0) {
console.error("Usage: node scripts/ci-typecheck-lane.mjs [--concurrency <n>]");
let concurrency = Math.max(1, Math.min(DEFAULT_MAX_CONCURRENCY, availableParallelism()));
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]");
process.exitCode = 2;
} else {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
@@ -274,8 +554,18 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
const testLayers = listLayers(path.join(root, "server"))
.filter((layer) => !layer.emitsDeclarations)
.map((layer) => layer.name);
console.log(`typecheck lane: ${concurrency} at a time; build gaps: ${buildGapPackages.join(", ")}`);
process.exitCode = await runLane({ ...planLane({ buildGapPackages, testLayers }), concurrency, cwd: root });
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 });
console.log(
`typecheck lane: ${concurrency} at a time; mode: ${scopeDetail}; ` +
`prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` +
`build gaps: ${buildGapPackages.join(", ")}`,
);
process.exitCode = await runLane({ ...lanePlan, concurrency, cwd: root });
}
}
}
File diff suppressed because it is too large. Load diff
+67
View File
@@ -0,0 +1,67 @@
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ciScriptsDir = path.dirname(fileURLToPath(import.meta.url));
export const PR_WORKFLOW_NAME = "PR";
export function resolveNightlyOnlySuitesPath({
repoRoot = process.cwd(),
env = process.env,
} = {}) {
const override = env.PAPERCLIP_CI_NIGHTLY_SUITES_FILE?.trim();
if (override) {
return path.resolve(repoRoot, override);
}
return path.join(ciScriptsDir, "nightly-only-suites.json");
}
export function loadNightlyOnlySuites(manifestPath) {
if (!existsSync(manifestPath)) {
return new Set();
}
let parsed;
try {
parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
} catch (error) {
throw new Error(`Failed to parse nightly-only suites manifest ${manifestPath}: ${error.message}`);
}
const entries = Array.isArray(parsed) ? parsed : parsed?.suites;
if (!Array.isArray(entries)) {
throw new Error(`Nightly-only suites manifest ${manifestPath} must contain a "suites" array.`);
}
const suites = new Set();
for (const entry of entries) {
const suitePath = typeof entry === "string" ? entry : entry?.path;
if (typeof suitePath !== "string" || suitePath.trim() === "") {
throw new Error(`Invalid entry in nightly-only suites manifest ${manifestPath}.`);
}
suites.add(suitePath.trim().split(path.sep).join("/"));
}
return suites;
}
export function isNightlyExclusionEnabled(env = process.env) {
const fullOverride = env.PAPERCLIP_CI_FULL?.trim().toLowerCase();
if (fullOverride === "1" || fullOverride === "true") {
return false;
}
const excludeOverride = env.PAPERCLIP_CI_EXCLUDE_NIGHTLY?.trim().toLowerCase();
if (excludeOverride === "0" || excludeOverride === "false") {
return false;
}
if (excludeOverride === "1" || excludeOverride === "true") {
return true;
}
return env.GITHUB_WORKFLOW === PR_WORKFLOW_NAME;
}
export function activeNightlySuitesForEnv({
repoRoot = process.cwd(),
env = process.env,
} = {}) {
if (!isNightlyExclusionEnabled(env)) {
return new Set();
}
return loadNightlyOnlySuites(resolveNightlyOnlySuitesPath({ repoRoot, env }));
}
+4 -2
View File
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
import path from "node:path";
import assert from "node:assert/strict";
import { refineTestPlan, selectionDurations } from "./test-selection-plan.mjs";
import { activeNightlySuitesForEnv } from "./nightly-only-suites.mjs";
import { productInputs } from "../../.github/scripts/ci-inputs.mjs";
import { mergeDiff } from "../../.github/scripts/ci-diff.mjs";
import { selectProjects } from "./select-projects.mjs";
@@ -30,7 +31,7 @@ function runnerInventory(group) {
const args = group === "serialized" ? ["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"]
: ["--mode", "general", "--group", group,
...(group === "general-server-without-chat" ? ["--shard-index", "0", "--shard-count", "1"] : [])];
const env = { ...process.env, GITHUB_WORKFLOW: "PR" };
const env = { ...process.env, GITHUB_WORKFLOW: "PR", PAPERCLIP_CI_FULL: "1" };
delete env.PAPERCLIP_CI_TEST_SELECTION;
return JSON.parse(execFileSync(process.execPath, ["scripts/run-vitest-stable.mjs", ...args, "--dry-run"],
{ env, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }));
@@ -77,7 +78,8 @@ export async function createTestSelection(plan, head) {
...native.selectedGeneralServerSuites, "server/src/__tests__/chat-channels.integration.test.ts"].sort(),
server.inventory, "Server inventory must be completely covered by existing lane ownership");
}
return { ...refineTestPlan({ plan, head, owners, graphs, durations: selectionDurations() }), graphs };
const excludedSuites = activeNightlySuitesForEnv();
return { ...refineTestPlan({ plan, head, owners, graphs, durations: selectionDurations(), excludedSuites }), graphs };
}
async function main() {
+1 -1
View File
@@ -18,7 +18,7 @@ export function validateSelection(manifest, { head, hash } = {}) {
const seen = new Set();
for (const [group, lane] of Object.entries(manifest.lanes)) {
assert.ok(selectableGroups.includes(group), `Unknown selection group: ${group}`);
assert.ok(Array.isArray(lane.shards) && lane.shards.length > 0 && lane.shards.length <= 12);
assert.ok(Array.isArray(lane.shards) && lane.shards.length > 0 && lane.shards.length <= 24);
for (const shard of lane.shards) {
assert.ok(shard && typeof shard === "object" && !Array.isArray(shard));
let count = 0;
+2 -2
View File
@@ -12,7 +12,7 @@ export function partitionSelection(inventory, selected, maxShards, durations = {
return selected.length ? partitionGeneralServerSuites(selected, count, durations).map((shard) => shard.files) : [];
}
export function refineTestPlan({ plan, head, owners, graphs, durations = {} }) {
export function refineTestPlan({ plan, head, owners, graphs, durations = {}, excludedSuites = new Set() }) {
const result = structuredClone(plan);
const manifest = { version: 1, head, lanes: {} };
const stats = [];
@@ -38,7 +38,7 @@ export function refineTestPlan({ plan, head, owners, graphs, durations = {} }) {
assert.ok(inventory.has(file), `Runner/Vitest inventory disagreement: ${file}`);
assert.ok(!projectByFile.has(file), `Ambiguous owner: ${file}`);
projectByFile.set(file, project);
if (affected.has(file)) selected.push(file);
if (affected.has(file) && !excludedSuites.has(file)) selected.push(file);
}
}
const partitions = partitionSelection([...projectByFile.keys()], selected, original.length, durations[group]);
@@ -237,10 +237,10 @@ test("collection skips unmerged, absent, stale-head and incomplete runs, and sam
});
test("general server weights come from complete full-width PR shard sets that cover the lane", async () => {
assert.equal(generalServerShardCount(), 12);
assert.deepEqual(generalServerJob("ci / General tests (server (3/12))", 12), { index: 3, count: 12 });
for (const name of ["ci / General tests (server (1/3))", "ci / General tests (chat (1/3))", "ci / Serialized tests (1/9)"]) {
assert.equal(generalServerJob(name, 12), null);
assert.equal(generalServerShardCount(), 20);
assert.deepEqual(generalServerJob("ci / General tests (server (3/20))", 20), { index: 3, count: 20 });
for (const name of ["ci / General tests (server (1/3))", "ci / General tests (chat (1/5))", "ci / Serialized tests (1/9)"]) {
assert.equal(generalServerJob(name, 20), null);
}
const api = "/repos/paperclipai/paperclip";
const timing = (file, ms) => `2026-11-13T00:00:00.0000000Z ${timingPrefix}${JSON.stringify({ version: 1, file, durationMs: ms })}`;
@@ -232,3 +232,35 @@ test("mixed audited documentation stays graph eligible and large complete source
assert.ok(selectionEligibility({ ...plan, changed: ["doc/DEVELOPING.md"] }));
assert.ok(selectionEligibility({ ...plan, changed: [...plan.changed, "docs/api/issues.md"] }));
});
test("refineTestPlan applies nightly exclusions before partitioning while keeping full inventory validation", () => {
const nightlySuite = "server/src/__tests__/heartbeat-process-recovery.test.ts";
const fastSuite = "server/src/__tests__/issues-service.test.ts";
const entries = [0, 1].map((shard_index) => ({
group: "general-server-without-chat",
group_label: `server (${shard_index + 1}/2)`,
shard_index,
shard_count: 2,
task: "ci:server",
}));
const plan = {
version: 1,
mode: "enabled",
forceReason: null,
changed: ["server/src/services/heartbeat.ts"],
jobs: {
general_tests: { run: true, matrix: { include: entries }, selected: 2, total: 2 },
verify_serialized_server: { run: false, matrix: { include: [{ task: "ci:serialized" }] } },
},
};
const owners = { "general-server-without-chat": { "@paperclipai/server": [nightlySuite, fastSuite] } };
const graphs = [{ project: "@paperclipai/server", inventory: [nightlySuite, fastSuite], selected: [nightlySuite, fastSuite] }];
const prRefined = refineTestPlan({ plan, head, owners, graphs, excludedSuites: new Set([nightlySuite]) });
const prFiles = prRefined.manifest.lanes["general-server-without-chat"].shards.flatMap((s) => s["@paperclipai/server"]);
assert.deepEqual(prFiles, [fastSuite], "PR selection must exclude nightly-only suites before partitioning");
const fullRefined = refineTestPlan({ plan, head, owners, graphs });
const fullFiles = fullRefined.manifest.lanes["general-server-without-chat"].shards.flatMap((s) => s["@paperclipai/server"]);
assert.deepEqual(fullFiles.sort(), [fastSuite, nightlySuite].sort(), "full selection must retain nightly-only suites");
});
+90
View File
@@ -0,0 +1,90 @@
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
export function resolveTsxLoaderPath(repoRoot) {
const candidates = [
path.join(repoRoot, "packages", "db", "node_modules", "tsx", "dist", "loader.mjs"),
path.join(repoRoot, "node_modules", "tsx", "dist", "loader.mjs"),
path.join(repoRoot, "cli", "node_modules", "tsx", "dist", "loader.mjs"),
];
return candidates.find((candidate) => existsSync(candidate)) ?? null;
}
export function shouldWrapWithSharedPostgres({
repoRoot,
dryRun,
hasSharedTestDatabase,
usesPostgres,
hasScheduledSuites,
env = process.env,
}) {
if (dryRun) return false;
if (env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL?.trim()) return false;
if (hasSharedTestDatabase) return false;
const sharedOverride = env.PAPERCLIP_TEST_POSTGRES_SHARED?.trim().toLowerCase();
if (sharedOverride === "0" || sharedOverride === "false") return false;
// Mocked-pnpm node:test harnesses run under NODE_TEST_CONTEXT; don't boot a
// real Postgres cluster for unit tests unless explicitly opted in.
if (env.NODE_TEST_CONTEXT && sharedOverride !== "1" && sharedOverride !== "true") return false;
if (!usesPostgres) return false;
if (!hasScheduledSuites) return false;
const wrapperScript = path.join(repoRoot, "packages", "db", "src", "test-postgres-command.ts");
if (!existsSync(wrapperScript)) return false;
return resolveTsxLoaderPath(repoRoot) !== null;
}
export async function runUnderSharedPostgres({
repoRoot,
runnerScriptPath,
argv = process.argv.slice(2),
env = process.env,
}) {
const tsxLoader = resolveTsxLoaderPath(repoRoot);
const wrapperScript = path.join(repoRoot, "packages", "db", "src", "test-postgres-command.ts");
const child = spawn(
process.execPath,
[
"--import",
pathToFileURL(tsxLoader).href,
wrapperScript,
"--",
process.execPath,
runnerScriptPath,
...argv,
],
{
cwd: repoRoot,
env,
stdio: "inherit",
},
);
const forwardSignal = (signal) => {
if (child.exitCode === null && child.signalCode === null) {
try {
child.kill(signal);
} catch {
// Ignore ESRCH if child already exited.
}
}
};
process.on("SIGINT", forwardSignal);
process.on("SIGTERM", forwardSignal);
process.on("SIGHUP", forwardSignal);
try {
const status = await new Promise((resolve, reject) => {
child.once("error", reject);
child.once("exit", (code, signal) => {
if (signal) resolve(128 + (os.constants.signals[signal] ?? 1));
else resolve(code ?? 1);
});
});
process.exitCode = status;
} finally {
process.removeListener("SIGINT", forwardSignal);
process.removeListener("SIGTERM", forwardSignal);
process.removeListener("SIGHUP", forwardSignal);
}
}
+14 -19
View File
@@ -25,9 +25,9 @@
}
],
"coverage": {
"measured": 56,
"withSetup": 56,
"inventory": 56
"measured": 51,
"withSetup": 51,
"inventory": 51
},
"durations": {
"tests/e2e/acp-stop-continuation.spec.ts": 67299,
@@ -35,52 +35,47 @@
"tests/e2e/agent-chat-messages.spec.ts": 23569,
"tests/e2e/agent-chat-projects.spec.ts": 206156,
"tests/e2e/agent-chat-sessions.spec.ts": 117218,
"tests/e2e/agent-configuration.spec.ts": 105794,
"tests/e2e/agent-configuration.spec.ts": 109800,
"tests/e2e/agentmail.spec.ts": 27227,
"tests/e2e/ai-personal-connection-recovery.spec.ts": 12373,
"tests/e2e/announcement-first-session.spec.ts": 9986,
"tests/e2e/announcement-placement.spec.ts": 18485,
"tests/e2e/app-not-connected.spec.ts": 10832,
"tests/e2e/application-delete-screenshot.spec.ts": 2970,
"tests/e2e/applications-crud.spec.ts": 23859,
"tests/e2e/apps-dark-mode-shots.spec.ts": 18910,
"tests/e2e/applications-crud.spec.ts": 15000,
"tests/e2e/apps-prosumer-mcp-flow.spec.ts": 13276,
"tests/e2e/archived-company-url.spec.ts": 6145,
"tests/e2e/artifact-tab-arrival.spec.ts": 20087,
"tests/e2e/artifact-tab-arrival.spec.ts": 19900,
"tests/e2e/artifact-uploads.spec.ts": 28200,
"tests/e2e/board-attachment-receipts.spec.ts": 112020,
"tests/e2e/cases-read-only.spec.ts": 9657,
"tests/e2e/cases-read-only.spec.ts": 12700,
"tests/e2e/chat-adapters-ui-messaging.spec.ts": 181303,
"tests/e2e/chat-adapters-ui-providers.spec.ts": 181541,
"tests/e2e/chunk-load-recovery.spec.ts": 16330,
"tests/e2e/classic-workspace.spec.ts": 6483,
"tests/e2e/classic-workspace.spec.ts": 8000,
"tests/e2e/cloud-auth.spec.ts": 33711,
"tests/e2e/company-context-refresh.spec.ts": 4128,
"tests/e2e/completed-task-paused-assignee.spec.ts": 25016,
"tests/e2e/composer-stop.spec.ts": 74978,
"tests/e2e/composer-stop.spec.ts": 55500,
"tests/e2e/conference-room-typing-intro.spec.ts": 30042,
"tests/e2e/connection-intents.spec.ts": 23775,
"tests/e2e/connection-reviews.spec.ts": 134583,
"tests/e2e/connection-intents.spec.ts": 20100,
"tests/e2e/connection-reviews.spec.ts": 75000,
"tests/e2e/coordinator-inbox-views.spec.ts": 18241,
"tests/e2e/daytona-connector.spec.ts": 2603,
"tests/e2e/disconnect-resilience.spec.ts": 200278,
"tests/e2e/disconnect-resilience.spec.ts": 55000,
"tests/e2e/disconnect-write-recovery.spec.ts": 51072,
"tests/e2e/document-image-gallery.spec.ts": 46344,
"tests/e2e/legacy-failure-continuation.spec.ts": 89961,
"tests/e2e/mcp-user-stories.spec.ts": 37417,
"tests/e2e/new-task-picker-touch.spec.ts": 22514,
"tests/e2e/nux-phase4-screenshots.spec.ts": 11330,
"tests/e2e/onboarding.spec.ts": 62933,
"tests/e2e/onboarding.spec.ts": 68700,
"tests/e2e/paused-composer.spec.ts": 38240,
"tests/e2e/plan-task-fixture.spec.ts": 7828,
"tests/e2e/planning-mode-visual-verification.spec.ts": 26325,
"tests/e2e/project-repositories.spec.ts": 13403,
"tests/e2e/railway-catalog.spec.ts": 2813,
"tests/e2e/runner-e2e-dashboard.spec.ts": 4985,
"tests/e2e/runner-task-creation.spec.ts": 32437,
"tests/e2e/sidebar-takeover.spec.ts": 9119,
"tests/e2e/signoff-policy.spec.ts": 52229,
"tests/e2e/smoke-lab-p1-p4.spec.ts": 22390,
"tests/e2e/smoke-lab-p1-p4.spec.ts": 19700,
"tests/e2e/smoke-lab-p5-p7.spec.ts": 16416,
"tests/e2e/task-loading-frame.spec.ts": 31309,
"tests/e2e/task-reload.spec.ts": 20988,
+82 -6
View File
@@ -14,6 +14,31 @@ const DURATIONS_MANIFEST = path.join(HERE, "e2e-shard-durations.json");
// test in scripts/__tests__/e2e-shard.test.mjs fails if the two ever drift.
export const IGNORED_SPECS = ["in-feed-native/**", "multi-user.spec.ts", "multi-user-authenticated.spec.ts"];
// Specs that mutate instance-wide state on the shared throwaway server or
// assert strict real-time latency / focus restoration sensitive to concurrent
// Chromium contention, and therefore must run with `workers: 1`. Keep in sync
// with `SERIAL_SPECS` in tests/e2e/playwright.config.ts —
// `scripts/__tests__/e2e-shard.test.mjs` fails if the two ever drift.
export const SERIAL_SPECS = [
"agent-configuration.spec.ts",
"cases-read-only.spec.ts",
"classic-workspace.spec.ts",
"composer-stop.spec.ts",
"connection-intents.spec.ts",
"document-image-gallery.spec.ts",
"onboarding.spec.ts",
"smoke-lab-p1-p4.spec.ts",
"smoke-lab-p5-p7.spec.ts",
];
// Matches the CI worker count in tests/e2e/playwright.config.ts for shards
// that contain only parallel-safe specs.
export const DEFAULT_PARALLEL_WORKERS = 2;
export function isSerialE2eSpec(file) {
return SERIAL_SPECS.includes(path.posix.basename(file.split(path.sep).join("/")));
}
// Enumerates the specs the default e2e lane actually runs, as repo-relative
// paths so the output can be handed straight to `playwright test`.
export function listE2eSpecs(e2eDir = E2E_DIR, repoRoot = REPO_ROOT) {
@@ -23,12 +48,63 @@ export function listE2eSpecs(e2eDir = E2E_DIR, repoRoot = REPO_ROOT) {
.sort((a, b) => a.localeCompare(b));
}
// Playwright's own --shard balances by test count, which is useless here: one
// spec (smoke-lab) is ~40% of the lane's wall clock. Reuse the deterministic
// longest-processing-time partition already proven on the general-server lane
// so every runner computes the identical, non-overlapping split.
export function selectE2eShard(files, shardIndex, shardCount, durations = {}) {
return partitionGeneralServerSuites(files, shardCount, durations)[shardIndex].files;
// Isolate instance-mutating specs onto dedicated serial shards so every other
// shard runs purely parallel-safe specs with `workers > 1` and `fullyParallel`.
// Choose the serial/parallel shard split that minimizes projected max wall-clock
// across all shards (serial shards run at 1x, parallel shards at 1/parallelWorkers).
export function partitionE2eShards(
files,
shardCount,
durations = {},
{ parallelWorkers = DEFAULT_PARALLEL_WORKERS } = {},
) {
const serialFiles = files.filter(isSerialE2eSpec);
const parallelFiles = files.filter((file) => !isSerialE2eSpec(file));
if (shardCount <= 1 || serialFiles.length === 0 || parallelFiles.length === 0) {
const mode = serialFiles.length > 0 ? "serial" : "parallel";
const effectiveWorkers = mode === "parallel" ? parallelWorkers : 1;
return partitionGeneralServerSuites(files, shardCount, durations).map((shard) => ({
...shard,
mode,
estimatedWallMs: shard.totalWeight / effectiveWorkers,
}));
}
const maxSerialShards = Math.min(serialFiles.length, shardCount - 1);
let bestPlan = null;
for (let serialShardCount = 1; serialShardCount <= maxSerialShards; serialShardCount += 1) {
const parallelShardCount = shardCount - serialShardCount;
if (parallelShardCount > parallelFiles.length) continue;
const serialShards = partitionGeneralServerSuites(serialFiles, serialShardCount, durations).map((shard) => ({
...shard,
mode: "serial",
estimatedWallMs: shard.totalWeight,
}));
const parallelShards = partitionGeneralServerSuites(parallelFiles, parallelShardCount, durations).map((shard) => ({
...shard,
mode: "parallel",
estimatedWallMs: shard.totalWeight / parallelWorkers,
}));
const combined = [...serialShards, ...parallelShards];
const maxWallMs = Math.max(...combined.map((shard) => shard.estimatedWallMs));
if (!bestPlan || maxWallMs < bestPlan.maxWallMs) {
bestPlan = { maxWallMs, shards: combined };
}
}
return bestPlan.shards;
}
// Playwright's own --shard balances by test count, which is useless here: spec
// durations vary by 80x and a handful of specs mutate instance-wide settings.
// Partition into dedicated serial and parallel shards weighted by estimated
// wall-clock time so every runner finishes together.
export function selectE2eShard(files, shardIndex, shardCount, durations = {}, options = {}) {
return partitionE2eShards(files, shardCount, durations, options)[shardIndex].files;
}
function parseArgs(argv) {
File diff suppressed because it is too large. Load diff
+12 -6
View File
@@ -13,7 +13,7 @@ function inventory(root, env, group) {
: ["--shard-index", "0", "--shard-count", "1"];
return JSON.parse(execFileSync(process.execPath, [path.join(root, "scripts/run-vitest-stable.mjs"), ...args,
...shards, "--dry-run"], {
cwd: root, env, encoding: "utf8", maxBuffer: 16 * 1024 * 1024,
cwd: root, env: { ...env, PAPERCLIP_CI_FULL: "1" }, encoding: "utf8", maxBuffer: 16 * 1024 * 1024,
}));
}
@@ -39,13 +39,18 @@ export async function planVerification({ root, env, diff, full = false }) {
if (uncovered.length) throw new Error(`Changes outside resolved test graphs: ${uncovered.join(", ")}`);
const byProject = new Map(graphs.map(graph => [graph.project, graph]));
const manifest = { version: 1, head: diff.head, lanes: {} }, jobs = [], selectedFiles = new Set();
const scheduleChat = () => {
if (selectedFiles.has(chatSuite)) return;
if (byProject.get("@paperclipai/server")?.selected.includes(chatSuite)) {
selectedFiles.add(chatSuite);
for (let index = 0; index < 6; index++) jobs.push({ id: `chat-${index + 1}`, cacheable: false, args: ["--mode", "general", "--group", "general-chat",
"--shard-index", String(index), "--shard-count", "6", "--serial-chat"] });
}
};
const matrixHasChat = (lanes.general_tests ?? []).some((entry) => entry.group === "general-chat");
for (const group of groups) {
if (group === "general-chat") {
if (byProject.get("@paperclipai/server")?.selected.includes(chatSuite)) {
selectedFiles.add(chatSuite);
for (let index = 0; index < 6; index++) jobs.push({ id: `chat-${index + 1}`, cacheable: false, args: ["--mode", "general", "--group", group,
"--shard-index", String(index), "--shard-count", "6", "--serial-chat"] });
}
scheduleChat();
continue;
}
const value = inventories.get(group);
@@ -70,6 +75,7 @@ export async function planVerification({ root, env, diff, full = false }) {
cacheable: files === reusable, selected: true, args: ["--mode", group === "serialized" ? "serialized" : "general",
...(group === "serialized" ? [] : ["--group", group]), "--shard-index", String(index), "--shard-count", String(partitions.length)] });
}
if (matrixHasChat) scheduleChat();
const expected = new Set(graphs.flatMap(graph => graph.selected));
if (expected.size !== selectedFiles.size || [...expected].some(file => !selectedFiles.has(file))) {
throw new Error("Selected tests are not completely covered by local runner ownership");
+234 -44
View File
@@ -1,12 +1,19 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadShardDurations, selectGeneralServerShard } from "./general-server-shard.mjs";
import { invocationEnv } from "./ci-profile/record.mjs";
import { vitestRetryArgs } from "./ci/vitest-retry.mjs";
import {
PR_WORKFLOW_NAME,
isNightlyExclusionEnabled,
loadNightlyOnlySuites,
resolveNightlyOnlySuitesPath,
} from "./ci/nightly-only-suites.mjs";
import { runUnderSharedPostgres, shouldWrapWithSharedPostgres } from "./ci/vitest-shared-postgres.mjs";
import { assertSelectedTests, partitionTestLines } from "./test-line-shard.mjs";
import { loadSelection, selectedShard } from "./ci/test-selection-manifest.mjs";
@@ -120,11 +127,35 @@ const nativeRunnerSuites = [
// caller of the same group keeps the suite in the server shards, so a renamed or
// unknown workflow degrades to today's slower-but-covered behavior rather
// than dropping the suite.
const prWorkflowName = "PR";
const prWorkflowName = PR_WORKFLOW_NAME;
const nativeRunnerSuiteRunsInRustCachedLane = process.env.GITHUB_WORKFLOW === prWorkflowName;
const withoutChatExcludedSuites = nativeRunnerSuiteRunsInRustCachedLane
? [chatSuite, ...nativeRunnerSuites]
: [chatSuite];
const nightlyOnlySuitesPath = resolveNightlyOnlySuitesPath({ repoRoot });
const strictlySerialServerTests = new Set([]);
let allNightlyOnlySuites;
try {
allNightlyOnlySuites = loadNightlyOnlySuites(nightlyOnlySuitesPath);
} catch (error) {
fail(error.message);
}
const nightlyExclusionActive = isNightlyExclusionEnabled();
const activeNightlyOnlySuites = nightlyExclusionActive ? allNightlyOnlySuites : new Set();
function activeNativeRunnerSuites() {
return nativeRunnerSuites.filter((file) => !activeNightlyOnlySuites.has(file));
}
function resolveServerParallelWorkers(defaultWorkers) {
const raw = process.env.PAPERCLIP_VITEST_MAX_WORKERS?.trim();
if (!raw) {
return defaultWorkers;
}
return parsePositiveInteger(raw, "PAPERCLIP_VITEST_MAX_WORKERS");
}
// Release verification selects this explicit group and runs the omitted suites
// in its cached Runner job. Local callers keep the complete default group.
const generalServerGroups = [
@@ -132,11 +163,18 @@ const generalServerGroups = [
generalServerWithoutChatGroupName,
generalServerWithoutChatOrNativeRunnerGroupName,
];
function excludedServerSuites(groupName) {
function baseExcludedServerSuites(groupName) {
if (groupName === generalServerWithoutChatOrNativeRunnerGroupName) return [chatSuite, ...nativeRunnerSuites];
if (groupName === generalServerWithoutChatGroupName) return withoutChatExcludedSuites;
return [];
}
function excludedServerSuites(groupName) {
const base = baseExcludedServerSuites(groupName);
if (groupName === generalServerGroupName || activeNightlyOnlySuites.size === 0) {
return base;
}
return [...new Set([...base, ...activeNightlyOnlySuites])];
}
const generalWorkspacesAGroupName = "general-workspaces-a";
const generalWorkspacesBGroupName = "general-workspaces-b";
const generalWorkspacesCGroupName = "general-workspaces-c";
@@ -512,17 +550,20 @@ async function runGeneralSuites(routeTests, chatShards) {
}
}
async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null) {
// With shard args, lean on Vitest's native --shard: each matrix job runs the
// same per-project invocations but only its slice of each project's test
// files. Vitest's sharding is deterministic for an identical file list, so
// the matrix jobs form a complete, non-overlapping cover of every project.
async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null, excludedFiles = []) {
// Run the whole group in a single multi-project Vitest invocation so Vitest
// boots once and shares module transform/worker pool overhead across packages.
// With shard args, Vitest's native --shard deterministically partitions the
// combined file list across runners into a complete, non-overlapping cover.
const shardArgs =
shardCount !== null && shardCount > 1 ? [`--shard=${shardIndex + 1}/${shardCount}`] : [];
const shardSuffix = shardArgs.length > 0 ? ` shard ${shardIndex + 1}/${shardCount}` : "";
for (const project of projects) {
await runVitest(["--project", project, ...shardArgs], `${groupName} project ${project}${shardSuffix}`);
}
const excludeArgs = excludedFiles.flatMap((file) => ["--exclude", file]);
const projectArgs = projects.flatMap((project) => ["--project", project]);
const label = projects.length === 1
? `${groupName} project ${projects[0]}${shardSuffix}`
: `${groupName} (${projects.length} projects)${shardSuffix}`;
await runVitest([...projectArgs, ...excludeArgs, ...shardArgs], label);
}
function chatShardWorkers(index, count) {
@@ -533,10 +574,50 @@ function chatShardWorkers(index, count) {
}));
}
function groupUsesPostgres(opts, sel) {
if (sel) {
return Boolean(sel["@paperclipai/server"]?.length || sel["@paperclipai/db"]?.length);
}
if (opts.mode === serializedModeName || opts.mode === allModeName) {
return true;
}
if (opts.mode === generalModeName) {
if (opts.group === null) return true;
return (
generalServerGroups.includes(opts.group) ||
opts.group === generalChatGroupName ||
opts.group === generalServerNativeRunnerGroupName ||
opts.group === generalWorkspacesCGroupName
);
}
return false;
}
function hasScheduledSuitesForRun(opts, sel) {
if (sel) {
return Object.values(sel).some((files) => files.length > 0);
}
if (opts.mode === serializedModeName) {
return selectSerializedSuites(activeRouteTests, opts.shardIndex, opts.shardCount).length > 0;
}
if (opts.mode === generalModeName && opts.group === generalServerNativeRunnerGroupName) {
return activeNativeRunnerSuites().length > 0;
}
if (opts.mode === generalModeName && generalServerGroups.includes(opts.group)) {
const excluded = new Set(excludedServerSuites(opts.group));
const files = generalServerTestFiles.filter((file) => !excluded.has(file));
if (opts.shardCount !== null && opts.shardCount > 1) {
return selectGeneralServerShard(files, opts.shardIndex, opts.shardCount, generalServerShardDurations).length > 0;
}
return files.length > 0;
}
return true;
}
async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCount = null, additionalExcludedSuites = []) {
if (groupName === generalChatGroupName) {
// Each invocation gets its own temporary home and embedded PostgreSQL.
// Wait for both children even on failure so no sibling is abandoned.
// Each invocation gets its own temporary home and disposable PostgreSQL database.
// Wait for all children even on failure so no sibling is abandoned.
const args = ["--project", "@paperclipai/server", ...serializedServerVitestArgs, chatSuite];
const workers = chatShardWorkers(shardIndex, shardCount);
const collected = await collectVitestList(args, isolatedTestEnv(), "all");
@@ -548,13 +629,18 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo
return;
}
if (groupName === generalServerNativeRunnerGroupName) {
const suites = activeNativeRunnerSuites();
if (suites.length === 0) {
console.log("\n[test:run] native runner vertical-slice suite: 0 suites after nightly filtering; skipping");
return;
}
await runVitest(
["--project", "@paperclipai/server",
// Each file owns its database, home, and processes. Keep cases serial,
// but overlap long real lease windows in four isolated fork workers.
...(hasSharedTestDatabase ? serializedServerVitestArgs
: ["--pool=forks", "--isolate", "--fileParallelism", "--maxWorkers=4"]),
...nativeRunnerSuites],
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`]),
...suites],
"native runner vertical-slice suite",
);
return;
@@ -576,16 +662,18 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo
return;
}
const workers = resolveServerParallelWorkers(4);
await runVitest(
[
"--project",
"@paperclipai/server",
// Files have separate fork processes and isolated homes/configs.
// Keep each file's cases serial; overlap three independent files.
// An explicit shared test database cannot be isolated this way.
// Files have separate fork processes, isolated homes/configs, and
// disposable per-file databases on the shared test PostgreSQL server.
// Keep each file's cases serial; overlap independent files across workers.
// An explicit shared mutable test database cannot be isolated this way.
...(hasSharedTestDatabase
? serializedServerVitestArgs
: ["--pool=forks", "--isolate", "--fileParallelism", "--maxWorkers=3"]),
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${workers}`]),
...shardFiles,
],
`${groupName} shard ${shardIndex + 1}/${shardCount}`,
@@ -593,9 +681,16 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo
return;
}
if (files.length === 0) {
console.log(`\n[test:run] ${groupName}: 0 suites after filtering; skipping`);
return;
}
const excludeRouteArgs = routeTests.flatMap((file) => ["--exclude", file.serverPath]);
for (const suite of excludedSuites) {
excludeRouteArgs.push("--exclude", suite.replace(/^server\//, ""));
if (suite.startsWith("server/")) {
excludeRouteArgs.push("--exclude", suite.replace(/^server\//, ""));
}
}
await runVitest(
[
@@ -612,8 +707,8 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo
if (groupName === generalWorkspacesAGroupName) {
// The ui project dominates this lane (~224s of a 319s job in actions run
// 31371439296, 2026-08-10, where workspaces-a was the slowest PR check).
// Its 439 test files shard cleanly with Vitest's native --shard, so the
// lane splits across runners without a duration manifest.
// Its test files shard cleanly with Vitest's native --shard, so the lane
// splits across runners without a duration manifest.
await runProjectGroup(generalWorkspacesAProjects, groupName, shardIndex, shardCount);
return;
}
@@ -624,20 +719,27 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo
}
if (groupName === generalWorkspacesCGroupName) {
await runProjectGroup(generalWorkspacesCProjects, groupName);
const dbNightlyExcludes = [...activeNightlyOnlySuites]
.filter((file) => file.startsWith("packages/db/"))
.map((file) => file.replace(/^packages\/db\//, ""));
await runProjectGroup(generalWorkspacesCProjects, groupName, null, null, dbNightlyExcludes);
return;
}
fail(`Unknown group "${groupName}".`);
}
async function runSerializedSuites(routeTests, shardIndex, shardCount) {
const shardTests = selectSerializedSuites(routeTests, shardIndex, shardCount);
async function runSerializedSuites(suites, shardIndex, shardCount) {
const shardTests = selectSerializedSuites(suites, shardIndex, shardCount);
console.log(
`\n[test:run] serialized shard ${shardIndex + 1}/${shardCount} running ${shardTests.length} of ${routeTests.length} suites`,
`\n[test:run] serialized shard ${shardIndex + 1}/${shardCount} running ${shardTests.length} of ${suites.length} suites`,
);
if (shardTests.length > 0) {
if (shardTests.length === 0) {
return;
}
if (hasSharedTestDatabase) {
await runVitest(
[
"--project",
@@ -649,6 +751,40 @@ async function runSerializedSuites(routeTests, shardIndex, shardCount) {
],
`serialized shard ${shardIndex + 1}/${shardCount}`,
);
return;
}
const parallelTests = shardTests.filter((test) => !strictlySerialServerTests.has(test.repoPath));
const serialOnlyTests = shardTests.filter((test) => strictlySerialServerTests.has(test.repoPath));
if (parallelTests.length > 0) {
const workers = resolveServerParallelWorkers(3);
await runVitest(
[
"--project",
"@paperclipai/server",
...parallelTests.map((test) => test.repoPath),
"--pool=forks",
"--isolate",
"--fileParallelism",
`--maxWorkers=${workers}`,
],
`serialized shard ${shardIndex + 1}/${shardCount}`,
);
}
if (serialOnlyTests.length > 0) {
await runVitest(
[
"--project",
"@paperclipai/server",
...serialOnlyTests.map((test) => test.repoPath),
"--pool=forks",
"--isolate",
...serializedServerVitestArgs,
],
`serialized shard ${shardIndex + 1}/${shardCount} (strictly serial)`,
);
}
}
@@ -659,11 +795,12 @@ const routeTests = walk(serverTestsDir)
serverPath: toServerPath(file),
}))
.sort((a, b) => a.repoPath.localeCompare(b.repoPath));
const activeRouteTests = routeTests.filter((test) => !activeNightlyOnlySuites.has(test.repoPath));
// Every server test file that the general-server group is responsible for,
// i.e. the whole server project minus the route/authz suites that run in the
// dedicated serialized shards. The default server config keeps files serial;
// the sharded entry point overlaps two isolated files per runner unless an
// the sharded entry point overlaps isolated files per runner unless an
// explicit shared test database requires serial execution.
// Suites are partitioned by recorded duration (scripts/general-server-shard.mjs)
// rather than round-robin, so one slow suite cluster can't stretch a single shard.
@@ -688,11 +825,16 @@ const selection = process.env.PAPERCLIP_CI_TEST_SELECTION
? selectedShard(loadSelection(), options, selectionProjects) : null;
if (selection?.["@paperclipai/server"]) {
const owned = new Set(options.mode === serializedModeName ? routeTests.map((test) => test.repoPath)
: generalServerTestFiles.filter((file) => !excludedServerSuites(options.group).includes(file)));
: generalServerTestFiles.filter((file) => !baseExcludedServerSuites(options.group).includes(file)));
for (const file of selection["@paperclipai/server"]) {
if (!owned.has(file)) fail(`Selected test belongs to another server lane: ${file}`);
}
}
if (selection && activeNightlyOnlySuites.size > 0) {
for (const [project, files] of Object.entries(selection)) {
selection[project] = files.filter((file) => !activeNightlyOnlySuites.has(file));
}
}
if (selection && options.dryRun) {
writeFileSync(1, JSON.stringify({ selection }));
process.exit(0);
@@ -700,11 +842,41 @@ if (selection && options.dryRun) {
const defaultChatShards = !selection && options.group === null && options.mode !== serializedModeName && !hasSharedTestDatabase
? Array.from({ length: 6 }, (_, index) => ({ index, count: 6 }))
: null;
function dryRunExcludedNightlySuites() {
if (activeNightlyOnlySuites.size === 0) {
return [];
}
if (options.mode === serializedModeName) {
return routeTests
.map((test) => test.repoPath)
.filter((file) => activeNightlyOnlySuites.has(file));
}
if (options.mode === generalModeName && options.group === generalServerNativeRunnerGroupName) {
return nativeRunnerSuites.filter((file) => activeNightlyOnlySuites.has(file));
}
if (
options.mode === generalModeName &&
(options.group === generalServerWithoutChatGroupName ||
options.group === generalServerWithoutChatOrNativeRunnerGroupName)
) {
const baseExcluded = new Set(baseExcludedServerSuites(options.group));
return generalServerTestFiles.filter(
(file) => !baseExcluded.has(file) && activeNightlyOnlySuites.has(file),
);
}
if (options.mode === generalModeName && options.group === generalWorkspacesCGroupName) {
return [...activeNightlyOnlySuites].filter((file) => file.startsWith("packages/db/")).sort();
}
return [];
}
if (options.dryRun) {
const serializedPool = options.mode === serializedModeName ? activeRouteTests : routeTests;
const serializedSuites =
options.mode === serializedModeName
? selectSerializedSuites(routeTests, options.shardIndex, options.shardCount)
: routeTests;
? selectSerializedSuites(serializedPool, options.shardIndex, options.shardCount)
: serializedPool;
// The inventory exceeds pipe buffers; flush it before the immediate exit.
writeFileSync(1,
JSON.stringify(
@@ -714,14 +886,16 @@ if (options.dryRun) {
shardCount: options.shardCount,
group: options.group,
availableGeneralGroups: allowedGeneralGroupNames,
serializedSuiteCount: routeTests.length,
nightlyExclusionActive,
excludedNightlySuites: dryRunExcludedNightlySuites(),
serializedSuiteCount: serializedPool.length,
selectedSerializedSuites: serializedSuites.map((routeTest) => routeTest.repoPath),
generalServerSuiteCount: generalServerTestFiles.length,
selectedGeneralServerSuites:
defaultChatShards
? generalServerTestFiles.filter(file => file !== chatSuite)
: options.mode === generalModeName && options.group === generalServerNativeRunnerGroupName
? nativeRunnerSuites
? activeNativeRunnerSuites()
: options.mode === generalModeName &&
generalServerGroups.includes(options.group) &&
options.shardCount !== null
@@ -757,25 +931,41 @@ if (options.dryRun) {
}
try {
if (selection) {
if (shouldWrapWithSharedPostgres({
repoRoot,
dryRun: options.dryRun,
hasSharedTestDatabase,
usesPostgres: groupUsesPostgres(options, selection),
hasScheduledSuites: hasScheduledSuitesForRun(options, selection),
})) {
await runUnderSharedPostgres({
repoRoot,
runnerScriptPath: fileURLToPath(import.meta.url),
});
} else if (selection) {
for (const [project, files] of Object.entries(selection)) {
if (files.length === 0) continue;
const serverArgs = project !== "@paperclipai/server" ? []
: options.mode === serializedModeName || hasSharedTestDatabase
: hasSharedTestDatabase
? ["--pool=forks", "--isolate", ...serializedServerVitestArgs]
: ["--pool=forks", "--isolate", "--fileParallelism", "--maxWorkers=3"];
: options.mode === serializedModeName
? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(3)}`]
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`];
await runVitest(["--project", project, ...serverArgs, ...files],
`selected ${project}: ${files.length} files`, null, true);
}
} else if (options.mode === generalModeName || options.mode === allModeName) {
if (options.group) {
await runGeneralGroup(routeTests, options.group, options.shardIndex, options.shardCount);
} else {
await runGeneralSuites(routeTests, defaultChatShards);
} else {
if (options.mode === generalModeName || options.mode === allModeName) {
if (options.group) {
await runGeneralGroup(routeTests, options.group, options.shardIndex, options.shardCount);
} else {
await runGeneralSuites(routeTests, defaultChatShards);
}
}
}
if (!selection && (options.mode === serializedModeName || options.mode === allModeName)) {
await runSerializedSuites(routeTests, options.shardIndex ?? 0, options.shardCount ?? 1);
if (options.mode === serializedModeName || options.mode === allModeName) {
await runSerializedSuites(activeRouteTests, options.shardIndex ?? 0, options.shardCount ?? 1);
}
}
} catch (error) {
console.error(`[test:run] ${error.message}`);
+182 -188
View File
@@ -3,202 +3,196 @@
"unit": "ms",
"sources": [
{
"run": 43133035381,
"pull": 22679,
"run": 45238253588,
"attempt": 1,
"sha": "42fd790e80953000a7be99eff30fb9a81bf9c7b7",
"url": "https://github.com/paperclipai/paperclip/actions/runs/43133035381"
},
{
"run": 43134251278,
"attempt": 2,
"sha": "9dfdeaad8662d9cd73a93490d09516877ef8a276",
"url": "https://github.com/paperclipai/paperclip/actions/runs/43134251278"
},
{
"run": 43145252393,
"attempt": 2,
"sha": "7d9973405c8726d6aadc7d0e6b4f6076085ebc45",
"url": "https://github.com/paperclipai/paperclip/actions/runs/43145252393"
"sha": "8d513d5b1ab8fbfa2905d41be44c165b03a8a320",
"url": "https://github.com/paperclipai/paperclip/actions/runs/45238253588"
}
],
"coverage": {
"measured": 173,
"withSetup": 173,
"inventory": 173
"measured": 178,
"withSetup": 178,
"inventory": 178
},
"durations": {
"server/src/__tests__/access-routes-hidden-floor.test.ts": 4459,
"server/src/__tests__/access-routes-permissions-upgrade.test.ts": 5465,
"server/src/__tests__/activity-routes.test.ts": 10563,
"server/src/__tests__/adapter-auth-signal-routes.test.ts": 9084,
"server/src/__tests__/adapter-model-refresh-routes.test.ts": 4075,
"server/src/__tests__/adapter-routes-authz.test.ts": 10176,
"server/src/__tests__/adapter-routes.test.ts": 3958,
"server/src/__tests__/agent-action-audit-routes.test.ts": 5904,
"server/src/__tests__/agent-adapter-validation-routes.test.ts": 50458,
"server/src/__tests__/agent-cross-tenant-authz-routes.test.ts": 4272,
"server/src/__tests__/agent-device-login-routes.test.ts": 6231,
"server/src/__tests__/agent-hire-auth-inheritance-routes.test.ts": 8399,
"server/src/__tests__/agent-hire-idempotency-routes.test.ts": 6320,
"server/src/__tests__/agent-instructions-routes.test.ts": 3851,
"server/src/__tests__/agent-live-run-routes.test.ts": 47196,
"server/src/__tests__/agent-permissions-routes.test.ts": 5042,
"server/src/__tests__/agent-runner-qualification-routes.test.ts": 5808,
"server/src/__tests__/agent-secrets-routes.test.ts": 5616,
"server/src/__tests__/agent-skills-routes.test.ts": 4780,
"server/src/__tests__/agent-task-hierarchy-depth-routes.test.ts": 5914,
"server/src/__tests__/agent-test-environment-routes.test.ts": 4386,
"server/src/__tests__/ai-connection-router.test.ts": 28008,
"server/src/__tests__/announcements-routes.test.ts": 4480,
"server/src/__tests__/approval-routes-idempotency.test.ts": 4100,
"server/src/__tests__/artifact-review-document-routes.test.ts": 6376,
"server/src/__tests__/assets.test.ts": 5477,
"server/src/__tests__/auth-routes.test.ts": 4182,
"server/src/__tests__/auth-session-route.test.ts": 3352,
"server/src/__tests__/authz-company-access.test.ts": 1190,
"server/src/__tests__/authz-existence-oracle-guard.test.ts": 100,
"server/src/__tests__/authz-secret-context.test.ts": 1184,
"server/src/__tests__/board-bootstrap-routes.test.ts": 5136,
"server/src/__tests__/board-chat-route-feature-flag.test.ts": 815,
"server/src/__tests__/bootstrap-claim-routes.test.ts": 3801,
"server/src/__tests__/browser-use-route-scope.test.ts": 3617,
"server/src/__tests__/built-in-agent-routes.test.ts": 9291,
"server/src/__tests__/cases-routes.test.ts": 11134,
"server/src/__tests__/cli-auth-routes.test.ts": 17169,
"server/src/__tests__/cloud-routes.test.ts": 3736,
"server/src/__tests__/companies-route-cross-company-authz.test.ts": 15423,
"server/src/__tests__/companies-route-path-guard.test.ts": 3778,
"server/src/__tests__/company-branding-route.test.ts": 6936,
"server/src/__tests__/company-default-decision-owner-route.test.ts": 6504,
"server/src/__tests__/company-import-transfer-routes.test.ts": 4904,
"server/src/__tests__/company-portability-routes.test.ts": 5250,
"server/src/__tests__/company-portability.test.ts": 9588,
"server/src/__tests__/company-search-extract-routes.test.ts": 4424,
"server/src/__tests__/company-search-rate-limit-routes.test.ts": 4412,
"server/src/__tests__/company-skill-policy-routes.test.ts": 4527,
"server/src/__tests__/company-skills-import-authz-routes.test.ts": 5740,
"server/src/__tests__/company-skills-routes.test.ts": 3796,
"server/src/__tests__/company-user-directory-route.test.ts": 3829,
"server/src/__tests__/cost-data-quality-routes.test.ts": 3649,
"server/src/__tests__/costs-service.test.ts": 5218,
"server/src/__tests__/decision-queues-routes.test.ts": 6413,
"server/src/__tests__/document-annotation-routes.test.ts": 6425,
"server/src/__tests__/email-routes-provider-errors.test.ts": 3667,
"server/src/__tests__/environment-custom-image-routes.test.ts": 3810,
"server/src/__tests__/environment-instance-routes.test.ts": 3784,
"server/src/__tests__/environment-routes.test.ts": 3862,
"server/src/__tests__/environment-selection-route-guards.test.ts": 4439,
"server/src/__tests__/execution-workspace-runtime-lease-route.test.ts": 5683,
"server/src/__tests__/execution-workspaces-routes.test.ts": 3883,
"server/src/__tests__/express5-auth-wildcard.test.ts": 120,
"server/src/__tests__/external-object-routes.test.ts": 4334,
"server/src/__tests__/folders-routes.test.ts": 3921,
"server/src/__tests__/health-dev-server-token.test.ts": 4171,
"server/src/__tests__/health.test.ts": 3773,
"server/src/__tests__/heartbeat-dependency-scheduling.test.ts": 50657,
"server/src/__tests__/access-routes-hidden-floor.test.ts": 7709,
"server/src/__tests__/access-routes-permissions-upgrade.test.ts": 7117,
"server/src/__tests__/activity-routes.test.ts": 21578,
"server/src/__tests__/adapter-auth-signal-routes.test.ts": 17029,
"server/src/__tests__/adapter-model-refresh-routes.test.ts": 6222,
"server/src/__tests__/adapter-routes-authz.test.ts": 19486,
"server/src/__tests__/adapter-routes.test.ts": 17941,
"server/src/__tests__/agent-action-audit-routes.test.ts": 10946,
"server/src/__tests__/agent-adapter-validation-routes.test.ts": 100370,
"server/src/__tests__/agent-cross-tenant-authz-routes.test.ts": 6553,
"server/src/__tests__/agent-device-login-routes.test.ts": 23028,
"server/src/__tests__/agent-hire-auth-inheritance-routes.test.ts": 23298,
"server/src/__tests__/agent-hire-idempotency-routes.test.ts": 8900,
"server/src/__tests__/agent-instructions-routes.test.ts": 7607,
"server/src/__tests__/agent-live-run-routes.test.ts": 85464,
"server/src/__tests__/agent-permissions-routes.test.ts": 19196,
"server/src/__tests__/agent-runner-qualification-routes.test.ts": 8686,
"server/src/__tests__/agent-secrets-routes.test.ts": 8763,
"server/src/__tests__/agent-skills-routes.test.ts": 7999,
"server/src/__tests__/agent-task-hierarchy-depth-routes.test.ts": 10309,
"server/src/__tests__/agent-test-environment-routes.test.ts": 19471,
"server/src/__tests__/ai-connection-router.test.ts": 42177,
"server/src/__tests__/announcements-routes.test.ts": 6400,
"server/src/__tests__/approval-routes-idempotency.test.ts": 5399,
"server/src/__tests__/artifact-review-document-routes.test.ts": 9350,
"server/src/__tests__/assets.test.ts": 9131,
"server/src/__tests__/auth-routes.test.ts": 7299,
"server/src/__tests__/auth-session-route.test.ts": 5366,
"server/src/__tests__/authz-company-access.test.ts": 1619,
"server/src/__tests__/authz-existence-oracle-guard.test.ts": 569,
"server/src/__tests__/authz-secret-context.test.ts": 1421,
"server/src/__tests__/board-bootstrap-routes.test.ts": 5950,
"server/src/__tests__/board-chat-route-feature-flag.test.ts": 1578,
"server/src/__tests__/board-route-statement-census.test.ts": 8356,
"server/src/__tests__/bootstrap-claim-routes.test.ts": 5323,
"server/src/__tests__/browser-use-route-scope.test.ts": 4166,
"server/src/__tests__/built-in-agent-routes.test.ts": 14052,
"server/src/__tests__/cases-routes.test.ts": 15579,
"server/src/__tests__/cli-auth-routes.test.ts": 26031,
"server/src/__tests__/cloud-routes.test.ts": 7000,
"server/src/__tests__/companies-route-cross-company-authz.test.ts": 19290,
"server/src/__tests__/companies-route-path-guard.test.ts": 4572,
"server/src/__tests__/company-branding-route.test.ts": 13767,
"server/src/__tests__/company-default-decision-owner-route.test.ts": 9824,
"server/src/__tests__/company-import-transfer-routes.test.ts": 7926,
"server/src/__tests__/company-portability-routes.test.ts": 16020,
"server/src/__tests__/company-portability.test.ts": 11437,
"server/src/__tests__/company-search-extract-routes.test.ts": 6767,
"server/src/__tests__/company-search-rate-limit-routes.test.ts": 6118,
"server/src/__tests__/company-skill-policy-routes.test.ts": 6222,
"server/src/__tests__/company-skills-import-authz-routes.test.ts": 7892,
"server/src/__tests__/company-skills-routes.test.ts": 6446,
"server/src/__tests__/company-user-directory-route.test.ts": 6130,
"server/src/__tests__/cost-data-quality-routes.test.ts": 5213,
"server/src/__tests__/costs-service.test.ts": 5309,
"server/src/__tests__/decision-queues-routes.test.ts": 6023,
"server/src/__tests__/document-annotation-routes.test.ts": 10105,
"server/src/__tests__/email-routes-provider-errors.test.ts": 5765,
"server/src/__tests__/environment-custom-image-routes.test.ts": 6238,
"server/src/__tests__/environment-instance-routes.test.ts": 6976,
"server/src/__tests__/environment-routes.test.ts": 14035,
"server/src/__tests__/environment-selection-route-guards.test.ts": 7244,
"server/src/__tests__/execution-workspace-runtime-lease-route.test.ts": 7541,
"server/src/__tests__/execution-workspaces-routes.test.ts": 5986,
"server/src/__tests__/express5-auth-wildcard.test.ts": 836,
"server/src/__tests__/external-object-routes.test.ts": 7481,
"server/src/__tests__/folders-routes.test.ts": 3807,
"server/src/__tests__/health-dev-server-token.test.ts": 7458,
"server/src/__tests__/health.test.ts": 5117,
"server/src/__tests__/heartbeat-dependency-scheduling.test.ts": 79302,
"server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts": 54768,
"server/src/__tests__/heartbeat-process-recovery.test.ts": 344017,
"server/src/__tests__/heartbeat-run-privacy-routes.test.ts": 9270,
"server/src/__tests__/inbox-agent-policy-routes.test.ts": 4707,
"server/src/__tests__/inbox-archive-routes.test.ts": 7445,
"server/src/__tests__/inbox-mine-routes.test.ts": 7381,
"server/src/__tests__/instance-database-backups-routes.test.ts": 3506,
"server/src/__tests__/instance-settings-routes.test.ts": 4187,
"server/src/__tests__/invite-accept-existing-member.test.ts": 3588,
"server/src/__tests__/invite-accept-gateway-defaults.test.ts": 4603,
"server/src/__tests__/invite-accept-replay.test.ts": 4210,
"server/src/__tests__/invite-create-route.test.ts": 6191,
"server/src/__tests__/invite-expiry.test.ts": 4468,
"server/src/__tests__/invite-join-manager.test.ts": 4095,
"server/src/__tests__/invite-list-route.test.ts": 3806,
"server/src/__tests__/invite-logo-route.test.ts": 4470,
"server/src/__tests__/invite-onboarding-text.test.ts": 4598,
"server/src/__tests__/invite-rate-limit-route.test.ts": 5758,
"server/src/__tests__/invite-summary-route.test.ts": 6219,
"server/src/__tests__/invite-test-resolution-route.test.ts": 4021,
"server/src/__tests__/invite-url-public-base-url.test.ts": 4803,
"server/src/__tests__/issue-access-grants-routes.test.ts": 7311,
"server/src/__tests__/issue-activity-events-routes.test.ts": 8154,
"server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts": 15844,
"server/src/__tests__/issue-assigned-backlog-contract-routes.test.ts": 4282,
"server/src/__tests__/issue-assignee-invokability-routes.test.ts": 3973,
"server/src/__tests__/issue-attachment-routes.test.ts": 4512,
"server/src/__tests__/issue-blocker-diagnostics-routes.test.ts": 5372,
"server/src/__tests__/issue-chat-bootstrap-routes.test.ts": 7382,
"server/src/__tests__/issue-closed-workspace-routes.test.ts": 3977,
"server/src/__tests__/issue-comment-attribution-audit-routes.test.ts": 5540,
"server/src/__tests__/issue-comment-cancel-routes.test.ts": 3798,
"server/src/__tests__/issue-comment-reopen-routes.test.ts": 6776,
"server/src/__tests__/issue-confirm-run-stopped-routes.test.ts": 7677,
"server/src/__tests__/issue-create-deduplication-routes.test.ts": 6041,
"server/src/__tests__/issue-created-from-routes.test.ts": 5645,
"server/src/__tests__/issue-creation-source-routes.test.ts": 6585,
"server/src/__tests__/issue-dependency-wakeups-routes.test.ts": 8660,
"server/src/__tests__/issue-document-restore-routes.test.ts": 6269,
"server/src/__tests__/issue-execution-policy-routes.test.ts": 4346,
"server/src/__tests__/issue-feedback-routes.test.ts": 4382,
"server/src/__tests__/issue-identifier-routes.test.ts": 5515,
"server/src/__tests__/issue-list-assignee-filter-routes.test.ts": 12312,
"server/src/__tests__/issue-list-updatedsince-filter-routes.test.ts": 4929,
"server/src/__tests__/issue-onboarding-first-task-routes.test.ts": 13445,
"server/src/__tests__/issue-queued-comments-routes.test.ts": 118620,
"server/src/__tests__/issue-scheduled-retry-routes.test.ts": 14427,
"server/src/__tests__/issue-stale-execution-lock-routes.test.ts": 7268,
"server/src/__tests__/issue-stalled-review-decision-routes.test.ts": 6458,
"server/src/__tests__/issue-status-version-route-service.test.ts": 5591,
"server/src/__tests__/issue-subtree-diagnostics-routes.test.ts": 6142,
"server/src/__tests__/issue-summaries-routes.test.ts": 5147,
"server/src/__tests__/issue-telemetry-routes.test.ts": 4790,
"server/src/__tests__/issue-thread-interaction-routes.test.ts": 14207,
"server/src/__tests__/issue-tree-control-routes.test.ts": 3888,
"server/src/__tests__/issue-update-comment-wakeup-routes.test.ts": 4533,
"server/src/__tests__/issue-wake-diagnostics-routes.test.ts": 5628,
"server/src/__tests__/issue-watchdogs-routes.test.ts": 11962,
"server/src/__tests__/issue-workspace-command-authz.test.ts": 4185,
"server/src/__tests__/issues-checkout-wakeup.test.ts": 100,
"server/src/__tests__/issues-goal-context-routes.test.ts": 4365,
"server/src/__tests__/issues-service.test.ts": 39512,
"server/src/__tests__/link-preview-routes.test.ts": 3783,
"server/src/__tests__/llms-routes.test.ts": 4025,
"server/src/__tests__/low-trust-red-team-routes.test.ts": 40548,
"server/src/__tests__/heartbeat-run-privacy-routes.test.ts": 25152,
"server/src/__tests__/inbox-agent-policy-routes.test.ts": 9188,
"server/src/__tests__/inbox-archive-routes.test.ts": 8268,
"server/src/__tests__/inbox-mine-routes.test.ts": 10977,
"server/src/__tests__/instance-database-backups-routes.test.ts": 6034,
"server/src/__tests__/instance-server-metrics-routes.test.ts": 16867,
"server/src/__tests__/instance-settings-routes.test.ts": 5803,
"server/src/__tests__/invite-accept-existing-member.test.ts": 6558,
"server/src/__tests__/invite-accept-gateway-defaults.test.ts": 8151,
"server/src/__tests__/invite-accept-replay.test.ts": 6489,
"server/src/__tests__/invite-create-route.test.ts": 9982,
"server/src/__tests__/invite-expiry.test.ts": 4886,
"server/src/__tests__/invite-join-manager.test.ts": 6003,
"server/src/__tests__/invite-list-route.test.ts": 5932,
"server/src/__tests__/invite-logo-route.test.ts": 5533,
"server/src/__tests__/invite-onboarding-text.test.ts": 7361,
"server/src/__tests__/invite-rate-limit-route.test.ts": 6103,
"server/src/__tests__/invite-summary-route.test.ts": 8714,
"server/src/__tests__/invite-test-resolution-route.test.ts": 6673,
"server/src/__tests__/invite-url-public-base-url.test.ts": 6521,
"server/src/__tests__/issue-access-grants-routes.test.ts": 9735,
"server/src/__tests__/issue-activity-events-routes.test.ts": 15122,
"server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts": 17814,
"server/src/__tests__/issue-assigned-backlog-contract-routes.test.ts": 7165,
"server/src/__tests__/issue-assignee-invokability-routes.test.ts": 7237,
"server/src/__tests__/issue-attachment-routes.test.ts": 17644,
"server/src/__tests__/issue-blocker-diagnostics-routes.test.ts": 9650,
"server/src/__tests__/issue-chat-bootstrap-routes.test.ts": 10756,
"server/src/__tests__/issue-closed-workspace-routes.test.ts": 7089,
"server/src/__tests__/issue-comment-attribution-audit-routes.test.ts": 8446,
"server/src/__tests__/issue-comment-cancel-routes.test.ts": 6164,
"server/src/__tests__/issue-comment-reopen-routes.test.ts": 19442,
"server/src/__tests__/issue-confirm-run-stopped-routes.test.ts": 9839,
"server/src/__tests__/issue-create-deduplication-routes.test.ts": 9136,
"server/src/__tests__/issue-created-from-routes.test.ts": 7614,
"server/src/__tests__/issue-creation-source-routes.test.ts": 10770,
"server/src/__tests__/issue-dependency-wakeups-routes.test.ts": 12551,
"server/src/__tests__/issue-document-restore-routes.test.ts": 10496,
"server/src/__tests__/issue-execution-policy-routes.test.ts": 8945,
"server/src/__tests__/issue-feedback-routes.test.ts": 5778,
"server/src/__tests__/issue-identifier-routes.test.ts": 7007,
"server/src/__tests__/issue-list-assignee-filter-routes.test.ts": 27792,
"server/src/__tests__/issue-list-updatedsince-filter-routes.test.ts": 8596,
"server/src/__tests__/issue-onboarding-first-task-routes.test.ts": 14748,
"server/src/__tests__/issue-queued-comments-routes.test.ts": 99424,
"server/src/__tests__/issue-scheduled-retry-routes.test.ts": 22055,
"server/src/__tests__/issue-stale-execution-lock-routes.test.ts": 9935,
"server/src/__tests__/issue-stalled-review-decision-routes.test.ts": 17957,
"server/src/__tests__/issue-status-version-route-service.test.ts": 8577,
"server/src/__tests__/issue-subtree-diagnostics-routes.test.ts": 7841,
"server/src/__tests__/issue-summaries-routes.test.ts": 9355,
"server/src/__tests__/issue-telemetry-routes.test.ts": 10283,
"server/src/__tests__/issue-thread-interaction-routes.test.ts": 17322,
"server/src/__tests__/issue-tree-control-routes.test.ts": 6060,
"server/src/__tests__/issue-update-comment-wakeup-routes.test.ts": 7306,
"server/src/__tests__/issue-wake-diagnostics-routes.test.ts": 15170,
"server/src/__tests__/issue-watchdogs-routes.test.ts": 15822,
"server/src/__tests__/issue-workspace-command-authz.test.ts": 6275,
"server/src/__tests__/issues-checkout-wakeup.test.ts": 1065,
"server/src/__tests__/issues-goal-context-routes.test.ts": 6658,
"server/src/__tests__/issues-service.test.ts": 35882,
"server/src/__tests__/link-preview-routes.test.ts": 6145,
"server/src/__tests__/llms-routes.test.ts": 6553,
"server/src/__tests__/low-trust-red-team-routes.test.ts": 51564,
"server/src/__tests__/maintenance-server-routes.test.ts": 276429,
"server/src/__tests__/managed-agent-profile-routes-authz.test.ts": 3791,
"server/src/__tests__/multilingual-issues-routes.test.ts": 5790,
"server/src/__tests__/muse-qualification-routes.test.ts": 3804,
"server/src/__tests__/onboarding-seed-route.test.ts": 6481,
"server/src/__tests__/openapi-routes.test.ts": 5123,
"server/src/__tests__/openclaw-invite-prompt-route.test.ts": 3811,
"server/src/__tests__/opencode-local-adapter-environment.test.ts": 6723,
"server/src/__tests__/openrouter-attribution.test.ts": 685,
"server/src/__tests__/permissions-upgrade-boundary-routes.test.ts": 6152,
"server/src/__tests__/plugin-install-route-security.test.ts": 5289,
"server/src/__tests__/plugin-routes-authz.test.ts": 3612,
"server/src/__tests__/plugin-scoped-api-routes.test.ts": 3890,
"server/src/__tests__/project-decision-owner-route.test.ts": 6221,
"server/src/__tests__/project-goal-telemetry-routes.test.ts": 4390,
"server/src/__tests__/project-routes-env.test.ts": 4228,
"server/src/__tests__/project-workspace-managed-sandbox-routes.test.ts": 6636,
"server/src/__tests__/projects-list-archived-routes.test.ts": 5176,
"server/src/__tests__/redaction.test.ts": 160,
"server/src/__tests__/resource-memberships-routes.test.ts": 5530,
"server/src/__tests__/routine-document-annotation-routes.test.ts": 4747,
"server/src/__tests__/routines-e2e.test.ts": 15930,
"server/src/__tests__/routines-routes.test.ts": 11937,
"server/src/__tests__/secret-proposals-routes.test.ts": 15931,
"server/src/__tests__/secrets-routes-claude-oauth-service.test.ts": 5401,
"server/src/__tests__/secrets-routes.test.ts": 4414,
"server/src/__tests__/sidebar-preferences-routes.test.ts": 6241,
"server/src/__tests__/skill-update-diff-routes.test.ts": 4160,
"server/src/__tests__/subscription-routes.test.ts": 3452,
"server/src/__tests__/summary-slot-routes.test.ts": 8150,
"server/src/__tests__/task-connector-read-routes.test.ts": 6479,
"server/src/__tests__/task-title-routes.test.ts": 13501,
"server/src/__tests__/teams-catalog-routes.test.ts": 7702,
"server/src/__tests__/user-profile-routes.test.ts": 4153,
"server/src/__tests__/workspace-command-authz.test.ts": 100,
"server/src/__tests__/workspace-preferences-routes.test.ts": 3922,
"server/src/__tests__/workspace-restore-repair-route.test.ts": 7023,
"server/src/__tests__/workspace-runtime-routes-authz.test.ts": 4185,
"server/src/__tests__/workspace-runtime-service-authz.test.ts": 2027
"server/src/__tests__/managed-agent-profile-routes-authz.test.ts": 6245,
"server/src/__tests__/multilingual-issues-routes.test.ts": 8186,
"server/src/__tests__/muse-qualification-routes.test.ts": 5311,
"server/src/__tests__/native-child-task-read-routes.test.ts": 8905,
"server/src/__tests__/onboarding-seed-route.test.ts": 7929,
"server/src/__tests__/openapi-routes.test.ts": 19600,
"server/src/__tests__/openclaw-invite-prompt-route.test.ts": 6484,
"server/src/__tests__/opencode-local-adapter-environment.test.ts": 7463,
"server/src/__tests__/openrouter-attribution.test.ts": 1697,
"server/src/__tests__/openrouter-catalog-error-handler.test.ts": 3983,
"server/src/__tests__/permissions-upgrade-boundary-routes.test.ts": 8104,
"server/src/__tests__/plugin-install-route-security.test.ts": 8271,
"server/src/__tests__/plugin-routes-authz.test.ts": 14858,
"server/src/__tests__/plugin-scoped-api-routes.test.ts": 13393,
"server/src/__tests__/project-decision-owner-route.test.ts": 10045,
"server/src/__tests__/project-goal-telemetry-routes.test.ts": 5925,
"server/src/__tests__/project-routes-env.test.ts": 8038,
"server/src/__tests__/project-workspace-managed-sandbox-routes.test.ts": 9106,
"server/src/__tests__/projects-list-archived-routes.test.ts": 7611,
"server/src/__tests__/redaction.test.ts": 654,
"server/src/__tests__/resource-memberships-routes.test.ts": 7719,
"server/src/__tests__/routine-document-annotation-routes.test.ts": 6388,
"server/src/__tests__/routines-e2e.test.ts": 42624,
"server/src/__tests__/routines-routes.test.ts": 25919,
"server/src/__tests__/secret-proposals-routes.test.ts": 34207,
"server/src/__tests__/secrets-routes-claude-oauth-service.test.ts": 8198,
"server/src/__tests__/secrets-routes.test.ts": 6718,
"server/src/__tests__/sidebar-preferences-routes.test.ts": 7854,
"server/src/__tests__/skill-update-diff-routes.test.ts": 7253,
"server/src/__tests__/subscription-routes.test.ts": 5517,
"server/src/__tests__/summary-slot-routes.test.ts": 13804,
"server/src/__tests__/tailscale-connection-routes.test.ts": 5215,
"server/src/__tests__/task-connector-read-routes.test.ts": 10338,
"server/src/__tests__/task-title-routes.test.ts": 25360,
"server/src/__tests__/teams-catalog-routes.test.ts": 12771,
"server/src/__tests__/user-profile-routes.test.ts": 6490,
"server/src/__tests__/workspace-command-authz.test.ts": 668,
"server/src/__tests__/workspace-preferences-routes.test.ts": 5757,
"server/src/__tests__/workspace-restore-repair-route.test.ts": 9418,
"server/src/__tests__/workspace-runtime-routes-authz.test.ts": 6436,
"server/src/__tests__/workspace-runtime-service-authz.test.ts": 2659
}
}
+436 -19
View File
@@ -12,17 +12,19 @@
// 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] [tsconfig ...]
// Naming a tsconfig runs only that program and skips the coverage check.
// 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 { spawnSync } from "node:child_process";
import { spawn, spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { availableParallelism } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { linkExcludedPlugins } from "./link-plugin-dev-sdk.mjs";
import { LOW_MEMORY_VARIABLE, runTsc } from "./run-tsc.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 const SANDBOX_PROVIDERS = [
@@ -60,6 +62,126 @@ export const PROGRAMS = [
// 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/"]);
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"],
@@ -114,6 +236,56 @@ function listProgramFiles(config, { cwd, env }) {
};
}
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,
@@ -160,18 +332,105 @@ export function checkCoverage({
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,
includeProviders = true,
onlyFiles = null,
concurrency = Math.min(4, 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 = PROJECTS.map((project) => `${project}/tsconfig.json`);
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,
}) {
for (const args of PREPARE_STEPS) {
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 });
@@ -203,6 +462,10 @@ export function typecheckTestPrograms({
programs = PROGRAMS,
coverage = true,
prepare = true,
includeProviders = true,
includeRunnerEval = true,
includePluginSdk = true,
checkers,
pnpm = runPnpm,
linkPlugins = linkExcludedPlugins,
run = runTsc,
@@ -211,14 +474,25 @@ export function typecheckTestPrograms({
logError = console.error,
}) {
if (prepare) {
const prepared = prepareTestPrograms({ root, env, pnpm, linkPlugins, log, logError });
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], { cwd: root, env });
const { status, signal } = run(["-p", config, ...checkerArgs], { cwd: root, env });
if (signal) return status || 1;
if (status !== 0) exitCode = status;
}
@@ -237,32 +511,175 @@ export function typecheckTestPrograms({
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 = [...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);
const flags = args.filter((arg) => arg.startsWith("--"));
const programs = args.filter((arg) => !arg.startsWith("--"));
const unknownFlags = flags.filter((flag) => !["--low-memory", "--prepare-only", "--skip-prepare"].includes(flag));
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 = Math.max(1, Math.min(DEFAULT_CONCURRENCY, availableParallelism()));
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 = flags.includes("--low-memory") ? { ...process.env, [LOW_MEMORY_VARIABLE]: "1" } : process.env;
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 (flags.includes("--prepare-only") && (flags.includes("--skip-prepare") || programs.length > 0)) {
} 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 (flags.includes("--prepare-only")) {
process.exitCode = prepareTestPrograms({ root, env });
} else {
process.exitCode = typecheckTestPrograms({
} else if (prepareOnly) {
process.exitCode = prepareTestPrograms({
root,
env,
programs: programs.length > 0 ? programs : PROGRAMS,
coverage: programs.length === 0,
prepare: !flags.includes("--skip-prepare"),
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,
});
}
}
+151
View File
@@ -7,14 +7,18 @@ import { test } from "node:test";
import { fileURLToPath } from "node:url";
import {
checkCoverage,
checkCoverageAsync,
findUncheckedTests,
LOCKED_PROVIDERS,
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)), "..");
@@ -260,3 +264,150 @@ test("a real type error in a test-style program makes tsc exit non-zero", () =>
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);
});
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"]);
});
+339 -7
View File
@@ -11,15 +11,18 @@
// --reuse-declarations skips the build. Use it only straight after a server
// typecheck on the same commit, because stale declarations pass silently.
//
// Usage: node scripts/typecheck-test-projects.mjs [--low-memory] [--reuse-declarations] [project ...]
// Usage: node scripts/typecheck-test-projects.mjs [--low-memory] [--checkers <n>] [--reuse-declarations] [project ...]
import { spawnSync } from "node:child_process";
import { existsSync, readdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { LOW_MEMORY_VARIABLE, runTsc } from "./run-tsc.mjs";
import { runPnpm } from "./typecheck-low-memory.mjs";
import { isTestFile, typecheckLayers } from "../server/scripts/typecheck-layers.mjs";
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
export const PROJECTS = [
"server/src/__tests__/helpers/maintenance",
"tests/e2e",
@@ -29,6 +32,310 @@ export const PROJECTS = [
"tests/speko-native",
];
const GLOBAL_PROJECT_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-projects.mjs",
"server/scripts/typecheck-layers.mjs",
"server/src/types/express.d.ts",
"server/tsconfig.json",
]);
const SOURCE_FILE_PATTERN = /\.(?:[cm]?[jt]s|[jt]sx)$/;
const RESOLVE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".mjs", ".cjs", ".js", ".jsx", ".json"];
const IMPORT_SPECIFIER_PATTERN =
/(?:(?:import|export)\s+(?:type\s+)?(?:[^;]*?\s+from\s+)?|import\s*\()[\s\n]*["']([^"']+)["']/g;
const toPosix = (value) => value.split(path.sep).join("/");
const stripSourceExtension = (value) => value.replace(/\.(?:[cm]?[jt]s|[jt]sx)$/, "");
const rootGraphCaches = new Map();
function getRootCache(root) {
let cache = rootGraphCaches.get(root);
if (cache) return cache;
cache = {
dirFiles: new Map(),
fileEdges: new Map(),
workspacePackages: null,
projects: new Map(),
};
rootGraphCaches.set(root, cache);
return cache;
}
function getDirFiles(cache, dir) {
let set = cache.dirFiles.get(dir);
if (set) return set;
set = new Set();
try {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.isFile()) set.add(entry.name);
}
} catch {}
cache.dirFiles.set(dir, set);
return set;
}
function hasFile(cache, absPath) {
return getDirFiles(cache, path.dirname(absPath)).has(path.basename(absPath));
}
function loadWorkspacePackages(root, cache) {
if (cache.workspacePackages) return cache.workspacePackages;
const map = new Map();
const registerDir = (absDir) => {
const pkgPath = path.join(absDir, "package.json");
if (!hasFile(cache, pkgPath)) return;
try {
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
if (typeof pkg?.name === "string" && pkg.name.length > 0) {
const relDir = toPosix(path.relative(root, absDir));
map.set(pkg.name, relDir ? `${relDir}/` : "");
}
} catch {}
};
const walkPackages = (absDir, depth) => {
if (depth > 3) return;
registerDir(absDir);
let entries;
try {
entries = readdirSync(absDir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === "node_modules" || entry.name === "dist" || entry.name.startsWith(".")) {
continue;
}
walkPackages(path.join(absDir, entry.name), depth + 1);
}
};
for (const top of ["cli", "server", "ui"]) registerDir(path.join(root, top));
walkPackages(path.join(root, "packages"), 0);
cache.workspacePackages = map;
return map;
}
function resolveCandidateFile(cache, basePath) {
if (hasFile(cache, basePath)) return basePath;
const stripped = basePath.replace(/\.(?:[cm]?js|jsx)$/, "");
for (const ext of RESOLVE_EXTENSIONS) {
if (hasFile(cache, `${stripped}${ext}`)) return `${stripped}${ext}`;
}
for (const ext of RESOLVE_EXTENSIONS) {
const indexPath = path.join(stripped, `index${ext}`);
if (hasFile(cache, indexPath)) return indexPath;
}
return null;
}
function resolvePathAliases(specifier, projectDir, pathsConfig) {
if (!pathsConfig || typeof pathsConfig !== "object") return [];
const targets = [];
for (const [pattern, replacements] of Object.entries(pathsConfig)) {
if (!Array.isArray(replacements)) continue;
const starIndex = pattern.indexOf("*");
if (starIndex === -1) {
if (specifier !== pattern) continue;
for (const replacement of replacements) {
if (typeof replacement === "string") targets.push(path.resolve(projectDir, replacement));
}
continue;
}
const prefix = pattern.slice(0, starIndex);
const suffix = pattern.slice(starIndex + 1);
if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) continue;
const captured = specifier.slice(prefix.length, specifier.length - suffix.length);
for (const replacement of replacements) {
if (typeof replacement === "string") {
targets.push(path.resolve(projectDir, replacement.replace("*", captured)));
}
}
}
return targets;
}
function extractFileSpecifiers(cache, absFile) {
let cached = cache.fileEdges.get(absFile);
if (cached) return cached;
const specifiers = [];
try {
const source = readFileSync(absFile, "utf8");
IMPORT_SPECIFIER_PATTERN.lastIndex = 0;
let match;
while ((match = IMPORT_SPECIFIER_PATTERN.exec(source))) {
specifiers.push(match[1].split("?")[0]);
}
} catch {}
cache.fileEdges.set(absFile, specifiers);
return specifiers;
}
function walkSourceFiles(absDir, out = []) {
let entries;
try {
entries = readdirSync(absDir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
if (entry.name === "node_modules" || entry.name === "dist") continue;
const full = path.join(absDir, entry.name);
if (entry.isDirectory()) walkSourceFiles(full, out);
else if (SOURCE_FILE_PATTERN.test(entry.name)) out.push(full);
}
return out;
}
function expandTsconfigIncludes(root, projectDir, includeEntries, cache) {
const files = [];
const patterns = [];
if (!Array.isArray(includeEntries)) return { files, patterns };
for (const entry of includeEntries) {
if (typeof entry !== "string") continue;
const resolved = path.resolve(projectDir, entry);
if (!entry.includes("*")) {
if (hasFile(cache, resolved)) files.push(resolved);
const rel = toPosix(path.relative(root, resolved));
if (!rel.startsWith("..")) patterns.push(rel);
continue;
}
// Single-segment wildcard pattern (e.g. "../../maintenance-*.test.ts", "../../server/test-baselines/*.ts")
if (!entry.includes("**")) {
const dir = path.dirname(resolved);
const basePattern = path.basename(resolved);
const regex = new RegExp(`^${basePattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*")}$`);
for (const fileName of getDirFiles(cache, dir)) {
if (regex.test(fileName)) files.push(path.join(dir, fileName));
}
const relDir = toPosix(path.relative(root, dir));
if (!relDir.startsWith("..")) {
patterns.push({ dir: relDir ? `${relDir}/` : "", regex });
}
}
}
return { files, patterns };
}
export function collectProjectDependencies(project, root = REPO_ROOT) {
const cache = getRootCache(root);
const existing = cache.projects.get(project);
if (existing) return existing;
const projectDir = path.join(root, project);
if (!existsSync(projectDir)) return null;
const workspacePackages = loadWorkspacePackages(root, cache);
let tsconfig = null;
const tsconfigPath = path.join(projectDir, "tsconfig.json");
if (hasFile(cache, tsconfigPath)) {
try {
tsconfig = JSON.parse(readFileSync(tsconfigPath, "utf8"));
} catch {}
}
const pathsConfig = tsconfig?.compilerOptions?.paths ?? null;
const { files: includeFiles, patterns: includePatterns } = expandTsconfigIncludes(
root,
projectDir,
tsconfig?.include,
cache,
);
const visited = new Set();
const unresolvedStems = new Set();
const prefixes = new Set([`${toPosix(project)}/`]);
const queue = [...walkSourceFiles(projectDir), ...includeFiles];
for (const file of queue) visited.add(file);
const enqueueTarget = (absBase) => {
const resolved = resolveCandidateFile(cache, absBase);
if (resolved) {
if (!resolved.includes(`${path.sep}node_modules${path.sep}`) && !visited.has(resolved)) {
visited.add(resolved);
queue.push(resolved);
}
return;
}
const rel = toPosix(path.relative(root, absBase));
if (!rel.startsWith("..") && !rel.includes("node_modules/")) {
unresolvedStems.add(stripSourceExtension(rel));
}
};
while (queue.length > 0) {
const current = queue.pop();
const specifiers = extractFileSpecifiers(cache, current);
for (const specifier of specifiers) {
if (specifier.startsWith(".")) {
enqueueTarget(path.resolve(path.dirname(current), specifier));
continue;
}
const aliasTargets = resolvePathAliases(specifier, projectDir, pathsConfig);
if (aliasTargets.length > 0) {
for (const target of aliasTargets) enqueueTarget(target);
continue;
}
const pkgName = specifier.startsWith("@")
? specifier.split("/").slice(0, 2).join("/")
: specifier.split("/")[0];
const workspaceDir = workspacePackages.get(pkgName);
if (workspaceDir) prefixes.add(workspaceDir);
}
}
const files = new Set();
for (const absFile of visited) {
const rel = toPosix(path.relative(root, absFile));
if (!rel.startsWith("..")) files.add(rel);
}
const deps = { files, unresolvedStems, prefixes, includePatterns };
cache.projects.set(project, deps);
return deps;
}
function matchesProjectDependencies(file, deps) {
if (deps.files.has(file)) return true;
if (deps.unresolvedStems.has(stripSourceExtension(file))) return true;
for (const prefix of deps.prefixes) {
if (file === prefix || file.startsWith(prefix)) return true;
}
for (const pattern of deps.includePatterns) {
if (typeof pattern === "string") {
if (file === pattern) return true;
} else if (file.startsWith(pattern.dir)) {
const rest = file.slice(pattern.dir.length);
if (!rest.includes("/") && pattern.regex.test(rest)) return true;
}
}
return false;
}
/**
* Selects the test projects affected by `changedFiles` in PR mode using each project's
* static import graph and tsconfig includes. Returns all `projects` when `changedFiles`
* is null/undefined or touches global inputs.
*/
export function selectTestProjects(changedFiles, projects = PROJECTS, { root = REPO_ROOT } = {}) {
if (!Array.isArray(changedFiles)) return [...projects];
const normalizedFiles = changedFiles.map(toPosix);
if (normalizedFiles.some((file) => GLOBAL_PROJECT_INPUTS.has(file) || file.startsWith("patches/"))) {
return [...projects];
}
return projects.filter((project) => {
const deps = collectProjectDependencies(project, root);
// Fail closed for any new or missing project whose import graph cannot be inspected.
if (!deps) return true;
return normalizedFiles.some((file) => matchesProjectDependencies(file, deps));
});
}
// The same steps as the server's typecheck script.
export const PREPARE_STEPS = [
["--filter", "@paperclipai/paperclip-runner", "run", "build:typescript"],
@@ -65,6 +372,7 @@ export function typecheckTestProjects({
root,
projects = PROJECTS,
reuseDeclarations = false,
checkers,
env = process.env,
pnpm = runPnpm,
run = runTsc,
@@ -82,6 +390,7 @@ export function typecheckTestProjects({
const layers = typecheckLayers({
serverRoot,
declarationsOnly: true,
checkers,
run: (args, options) => run(args, { ...options, env }),
log,
});
@@ -89,11 +398,12 @@ export function typecheckTestProjects({
if (layers !== 0) return layers;
}
const checkerArgs = Number.isInteger(checkers) && checkers >= 1 ? ["--checkers", String(checkers)] : [];
let exitCode = 0;
for (const project of projects) {
log(`typecheck:test-projects: ${project}`);
const config = path.posix.join(project, "tsconfig.layers.json");
const { status, signal } = run(["-p", config], { cwd: root, env });
const { status, signal } = run(["-p", config, ...checkerArgs], { cwd: root, env });
if (signal) return status || 1;
if (status !== 0) exitCode = status;
@@ -117,13 +427,34 @@ export function typecheckTestProjects({
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2);
const flags = args.filter((arg) => arg.startsWith("--"));
const projects = args.filter((arg) => !arg.startsWith("--"));
const unknownFlags = flags.filter((flag) => !["--low-memory", "--reuse-declarations"].includes(flag));
let lowMemory = false;
let reuseDeclarations = false;
let checkers;
const projects = [];
const unknownFlags = [];
let invalidCheckers = false;
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
if (arg === "--low-memory") {
lowMemory = true;
} else if (arg === "--reuse-declarations") {
reuseDeclarations = true;
} else if (arg === "--checkers") {
checkers = Number(args[++i]);
if (!Number.isInteger(checkers) || checkers < 1) invalidCheckers = true;
} else if (arg.startsWith("--")) {
unknownFlags.push(arg);
} else {
projects.push(arg);
}
}
const unknown = projects.filter((project) => !PROJECTS.includes(project));
if (unknownFlags.length > 0) {
console.error(`Unknown option: ${unknownFlags.join(", ")}`);
process.exitCode = 2;
} else if (invalidCheckers) {
console.error("--checkers requires a positive integer");
process.exitCode = 2;
} else if (unknown.length > 0) {
console.error(`Unknown project: ${unknown.join(", ")}. Known projects: ${PROJECTS.join(", ")}`);
process.exitCode = 2;
@@ -131,8 +462,9 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
process.exitCode = typecheckTestProjects({
root: path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."),
projects: projects.length > 0 ? projects : PROJECTS,
reuseDeclarations: flags.includes("--reuse-declarations"),
env: args.includes("--low-memory") ? { ...process.env, [LOW_MEMORY_VARIABLE]: "1" } : process.env,
reuseDeclarations,
checkers,
env: lowMemory ? { ...process.env, [LOW_MEMORY_VARIABLE]: "1" } : process.env,
});
}
}