perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Pull-request CI checks run on every commit before maintainers can
merge code
> - PR #22679 cut PR CI from 15–30+ minutes down toward 4.5–5.5 minutes
on 4-core runners
> - Remaining wall-clock bottlenecks sit in unsharded `workspaces-b`,
serial typecheck preparation, E2E server/UI startup, fixed Vitest worker
caps, and remaining soak and duplicated UI tests
> - This pull request adds Phase 2 optimizations across server soak
triage, typecheck DAG overlap, E2E fast boot and shard balance, dynamic
CPU-aware workers, pure-Node workspace link preflight, UI pruning, and
permanent test-budget enforcement
> - The benefit is ordinary feature PRs finish in ~3.1–3.8 minutes on
4-core runners and scale automatically to ~2.0–3.0 minutes on 8-core
runners while keeping core invariants and nightly coverage intact

## Linked Issues or Issue Description

Refs #22679

**Problem Statement**
After #22679 landed, several PR lanes still took 4.5–6 minutes on 4-core
runners (`general-workspaces-b` ran unsharded, `Typecheck + Release
Registry` waited on a serial server build before starting UI and
test-program checks, E2E shards paid full `cli onboard` + minified UI
build overhead, and Vitest worker counts did not scale with runner CPU
count).

**Proposed Solution**
Split `general-workspaces-b` across two duration-balanced shards,
overlap typecheck preparation tasks behind a shared runner-vendor node,
replace E2E `onboard` with a direct template-PG boot + unminified inline
UI build, scale Vitest/Playwright/Typecheck workers dynamically by CPU
and RAM, replace `tsx` in workspace-link preflight with pure Node, prune
redundant mocked UI tests and additional real-clock server soak suites
(still run on `master`, `release-verify`, `cloud-readiness`, and
`PAPERCLIP_CI_FULL=1`), and add a permanent test-budget policy check.

**Expected Benefit**
Brings ordinary PR CI wall-clock down to ~3.1–3.8 minutes on 4-core
runners (and ~2.0–3.0 minutes on 8-core runners) with automated
guardrails against future test-time regressions.

## What Changed

- **Server soak triage & permanent test-budget guardrail
(`scripts/ci/nightly-only-suites.json`, `rules/test-budget.mdc`,
`.greptile/files.json`, `scripts/check-test-budget.mjs`,
`scripts/check-test-budget.test.mjs`,
`.github/workflows/pr-trusted.yml`):** Expanded the PR-excluded
soak/heavy-integration manifest to 568 genuine heavy suites (preserving
100% of company isolation, authz, checkout, approval, budget,
activity-log, security, telemetry, and serialized suites on every PR)
and wired `node scripts/check-test-budget.mjs` into the `policy` job.
- **Typecheck DAG overlap & CPU/RAM scaling
(`scripts/ci-typecheck-lane.mjs`, `scripts/typecheck-test-programs.mjs`,
`scripts/__tests__/ci-typecheck-lane.test.mjs`,
`scripts/typecheck-test-programs.test.mjs`):** Moved `build server
without type checks` and `check server runtime assets` out of serial
`prepare` into parallel DAG nodes behind `prepare runner vendor`, added
`computeResourceProfile` scaling across 2/4/8-core runners, and added
missing UI/Runner consumer routing inputs (`packages/paperclip-runner/`
for `@paperclipai/ui`, `packages/adapter-utils/` for Runner test
programs).
- **E2E fast boot, dynamic workers & 8-shard rebalance
(`tests/e2e/start-e2e-server.ts`, `tests/e2e/playwright.config.ts`,
`scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Added direct throwaway
template-PG boot (`fsync=off`), unminified inline Vite fallback build,
dynamic parallel workers (`min(4, floor(cpus/2))`), empirical `1.5x`
parallel speedup weighting across 8 shards, targeted trims to slowest
E2E specs, and hashed workspace `package.json` manifests into the
`e2e-ui-dist-v2` cache key.
- **Dynamic Vitest workers, 2-shard `workspaces-b`, and pure-Node
preflight (`scripts/ci/vitest-workers.mjs`,
`scripts/ci/workspaces-b-shard.mjs`,
`scripts/ensure-workspace-package-links.mjs`,
`scripts/ci-dependency-cache.mjs`,
`packages/db/src/test-embedded-postgres.ts`,
`.github/ci-task-matrix.json`,
`.github/actions/setup-ci-dependencies/action.yml`, `package.json`):**
Scaled Vitest workers dynamically (`4→7` general, `3→5` serialized) with
`max_connections=300` before PostgreSQL start, split
`general-workspaces-b` into 2 duration-weighted shards
(backward-compatible unsharded for release workflows), replaced `tsx`
workspace-link preflight with pure Node (~29× faster), and parallelized
`ci-dependency-cache.mjs` child queries.
- **UI Vitest worker scaling, fake timers & E2E-duplicated suite pruning
(`ui/vitest.config.ts`, 4 `maps/` files, and UI test suites):** Scaled
UI `maxWorkers` dynamically, converted real-clock sleeps in kept suites
to fake timers, removed 34 E2E-duplicated mocked jsdom suites, and
updated corresponding `maps/` prose references.

## Verification

- `node --test .github/scripts/tests/ci-plan.test.mjs
.github/scripts/tests/ci-dependency-cache.test.mjs
.github/scripts/tests/pr-dependency-cache.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/__tests__/e2e-shard.test.mjs scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs`: **160/160 PASS**
- `node scripts/check-test-budget.mjs`: **PASS** (`568` nightly suites
validated)
- `node scripts/check-maps.mjs`: **PASS** (`35 areas, 192 capability
IDs`)
- `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter
@paperclipai/db typecheck`: **PASS**
- Live CI verification runs on the new `pr-trusted.yml@master` (from
#22679) with `profile-ci` enabled to export the full job/step/file
waterfall to Honeycomb `paperclip-ci`.

## Risks

- Medium CI scope: touches workflow matrix partitioning, E2E startup,
and test runners; does not change production app runtime behavior.
- All PR-demoted soak suites continue to execute on `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and
`PAPERCLIP_CI_FULL=1`.
- All new `policy` and `setup-ci-dependencies` commands keep
file-existence guards so reruns of older PR branches continue to work.

## Model Used

- Google Gemini (Antigravity swarm orchestrating specialized worker
agents with shell, file editing, and test execution tools) and Anthropic
Claude Opus (verification and optimization sub-agents).

## 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-24 10:53:19 -06:00
1 parent 28aa32e7d7
commit 0731cd3afc
78 files changed
+3376 -11238

No files matched your search

+90 -14
View File
@@ -4,8 +4,11 @@ import { getPriority } from "node:os";
import test from "node:test";
import {
BACKGROUND_PRIORITY,
BUILD_SERVER_EMIT_ONLY,
computeResourceProfile,
createReporter,
planLane,
PREPARE_RUNNER_VENDOR,
resolveScope,
runLane,
selectBuildGapPackages,
@@ -23,12 +26,19 @@ const plan = () =>
const quietReporter = (lines = []) => createReporter({ write: (text) => lines.push(text), github: false });
const node = (name, source, needs) => ({ name, command: process.execPath, args: ["-e", source], needs });
test("the shared outputs are written before the parallel checks start", () => {
test("the shared outputs are written before dependent checks start, while emit-only server build overlaps", () => {
const { prepare, tasks } = plan();
const names = prepare.map((task) => task.name);
const build = prepare.find((task) => task.args.includes("@paperclipai/server") && task.args.includes("build"));
assert.deepEqual(build.env, { PAPERCLIP_TSC_EMIT_ONLY: "1" });
assert.ok(names.indexOf("check server runtime assets") > names.indexOf(build.name));
const byName = new Map(tasks.map((task) => [task.name, task]));
assert.ok(!prepare.some((task) => task.name === BUILD_SERVER_EMIT_ONLY));
assert.ok(!prepare.some((task) => task.name === "check server runtime assets"));
const build = byName.get(BUILD_SERVER_EMIT_ONLY);
assert.deepEqual(build.env, {
PAPERCLIP_TSC_EMIT_ONLY: "1",
PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT: "1",
});
assert.deepEqual(build.needs, [PREPARE_RUNNER_VENDOR]);
assert.equal(build.background, true);
assert.deepEqual(byName.get("check server runtime assets").needs, [BUILD_SERVER_EMIT_ONLY]);
assert.ok(prepare.some((task) => task.args.join(" ") === "scripts/typecheck-test-programs.mjs --prepare-only"));
for (const name of SERIAL_BUILD_GAPS) {
assert.ok(prepare.some((task) => task.name === `typecheck ${name}`), name);
@@ -37,22 +47,26 @@ test("the shared outputs are written before the parallel checks start", () => {
const guidance = prepare.find((task) => task.name === "CLI guidance safety");
assert.ok(guidance.args.includes("server/src/__tests__/cli-invocation-safety.test.ts"));
assert.equal(guidance.background, undefined);
const programs = tasks.find((task) => task.name === "typecheck test programs");
const programs = byName.get("typecheck test programs");
assert.ok(programs.args.includes("--skip-prepare"));
assert.deepEqual(programs.needs, [PREPARE_RUNNER_VENDOR]);
for (const task of tasks) {
assert.ok(!(task.args.includes("@paperclipai/server") && task.args.includes("typecheck")), task.name);
}
});
test("every check of the sequential job is planned, and only declaration readers wait", () => {
test("every check of the sequential job is planned with exact DAG dependencies", () => {
const { tasks } = plan();
const byName = new Map(tasks.map((task) => [task.name, task]));
assert.deepEqual(byName.get(PREPARE_RUNNER_VENDOR).args, ["--filter", "@paperclipai/server", "run", "prepare:runner-vendor"]);
assert.equal(byName.get(PREPARE_RUNNER_VENDOR).needs, undefined);
assert.deepEqual(byName.get("server declarations").args, [
"server/scripts/typecheck-layers.mjs",
"--declarations-only",
"--checkers",
"2",
]);
assert.deepEqual(byName.get("server declarations").needs, [PREPARE_RUNNER_VENDOR]);
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, "--checkers", "1"]);
@@ -65,15 +79,68 @@ test("every check of the sequential job is planned, and only declaration readers
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").needs, [PREPARE_RUNNER_VENDOR]);
assert.equal(byName.get("typecheck @paperclipai/ui").needs, undefined);
assert.deepEqual(byName.get("typecheck @paperclipai/ui").env, { GOMAXPROCS: "2" });
assert.deepEqual(byName.get("release registry tests").args, ["run", "test:release-registry"]);
assert.equal(byName.get("release registry tests").needs, undefined);
assert.ok(!byName.has("CLI guidance safety"));
const waiting = tasks.filter((task) => task.needs);
assert.equal(waiting.length, 2 + PROJECTS.length);
assert.deepEqual(
tasks.filter((task) => !task.background).map((task) => task.name),
["server declarations", "release registry tests", ...waiting.map((task) => task.name)],
);
const declarationReaders = tasks.filter((task) => task.needs?.includes("server declarations"));
assert.equal(declarationReaders.length, 2 + PROJECTS.length);
});
test("computeResourceProfile scales concurrency, checkers, and UI GOMAXPROCS across 2/4/8-core runners", () => {
const GiB = 1024 ** 3;
assert.deepEqual(computeResourceProfile({ cpus: 2, totalMemoryBytes: 8 * GiB }), {
laneConcurrency: 2,
serverDeclCheckers: 1,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 1,
testProgramsConcurrency: 1,
testProgramsCheckers: 1,
});
assert.deepEqual(computeResourceProfile({ cpus: 4, totalMemoryBytes: 16 * GiB }), {
laneConcurrency: 3,
serverDeclCheckers: 2,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 2,
testProgramsConcurrency: 2,
testProgramsCheckers: 1,
});
// 8-core / 16 GiB (c8i.2xlarge): 4 concurrent tasks so all 4 server layers finish in 1 wave under 16 GiB.
const c8i = computeResourceProfile({ cpus: 8, totalMemoryBytes: 16 * GiB });
assert.deepEqual(c8i, {
laneConcurrency: 4,
serverDeclCheckers: 3,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 4,
testProgramsConcurrency: 3,
testProgramsCheckers: 1,
});
// 8-core / 32 GiB (m8i.2xlarge): higher checkers and concurrency.
const m8i = computeResourceProfile({ cpus: 8, totalMemoryBytes: 32 * GiB });
assert.deepEqual(m8i, {
laneConcurrency: 6,
serverDeclCheckers: 4,
serverLayerCheckers: 2,
testProjectCheckers: 2,
uiGomaxprocs: 4,
testProgramsConcurrency: 4,
testProgramsCheckers: 2,
});
const { tasks } = planLane({
buildGapPackages: ["@paperclipai/ui"],
testLayers: ["tests"],
resources: c8i,
});
const byName = new Map(tasks.map((t) => [t.name, t]));
assert.deepEqual(byName.get("server declarations").args.slice(-2), ["--checkers", "3"]);
assert.deepEqual(byName.get("typecheck @paperclipai/ui").env, { GOMAXPROCS: "4" });
assert.ok(byName.get("typecheck test programs").args.join(" ").includes("--concurrency 3"));
});
test("resolveScope uses CI_PLAN in PR mode, honors PAPERCLIP_CI_FULL, and fails closed", () => {
@@ -138,11 +205,14 @@ test("PR mode for a server-only change skips release registry, UI, runner, sandb
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("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(PREPARE_RUNNER_VENDOR));
assert.ok(taskNames.includes(BUILD_SERVER_EMIT_ONLY));
assert.ok(taskNames.includes("check server runtime assets"));
assert.ok(taskNames.includes("server declarations"));
assert.ok(taskNames.includes("server layer tests"));
assert.ok(taskNames.includes("typecheck paperclipai"));
@@ -167,6 +237,8 @@ test("selectTestProjects follows the import graph so imported UI and server help
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(["server/src/index.ts"]).includes("tests/e2e"));
assert.ok(selectTestProjects(["packages/db/src/test-embedded-postgres.ts"]).includes("tests/e2e"));
assert.ok(selectTestProjects(["tests/unknown-new-project/a.ts"], [...PROJECTS, "tests/unknown-new-project"]).includes("tests/unknown-new-project"));
const uiHelperPlan = planLane({
@@ -222,6 +294,10 @@ test("PR mode fails closed for unknown build-gap packages and global typecheck i
assert.deepEqual(selectBuildGapPackages(["@paperclipai/ui", "@paperclipai/new-pkg"], ["server/src/a.ts"]), [
"@paperclipai/new-pkg",
]);
assert.deepEqual(
selectBuildGapPackages(["@paperclipai/ui"], ["packages/paperclip-runner/src/drivers/acpx/pi-extension-adapter.ts"]),
["@paperclipai/ui"],
);
const globalPlan = planLane({
buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"],
testLayers: ["tests"],
+6 -3
View File
@@ -9,6 +9,7 @@ import test from "node:test";
import { defaultSuiteWeight, loadShardDurations } from "../general-server-shard.mjs";
import {
DEFAULT_PARALLEL_WORKERS,
EFFECTIVE_PARALLEL_SPEEDUP,
IGNORED_SPECS,
SERIAL_SPECS,
isSerialE2eSpec,
@@ -152,10 +153,12 @@ test("the serial spec list matches playwright.config.ts SERIAL_SPECS and never m
}
});
test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1", () => {
test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1 and uses unminified inline builds", () => {
const config = readFileSync(playwrightConfig, "utf8");
assert.match(config, /PAPERCLIP_E2E_SKIP_UI_BUILD/);
assert.match(config, /ui-dist.*index\.html/);
assert.match(config, /--minify false/);
assert.match(config, /availableParallelism/);
});
test("the duration manifest only names specs that still exist", () => {
@@ -172,11 +175,11 @@ test("the weighted partition keeps the shards close to balanced", () => {
const specs = listE2eSpecs();
const fallbackWeight = defaultSuiteWeight(durations);
const shards = partitionE2eShards(specs, SHARD_COUNT, durations, {
parallelWorkers: DEFAULT_PARALLEL_WORKERS,
parallelWorkers: EFFECTIVE_PARALLEL_SPEEDUP,
});
const wallWeights = shards.map((shard) => {
const serialSum = shard.files.reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0);
return shard.mode === "parallel" ? serialSum / DEFAULT_PARALLEL_WORKERS : serialSum;
return shard.mode === "parallel" ? serialSum / EFFECTIVE_PARALLEL_SPEEDUP : serialSum;
});
const heaviest = Math.max(...wallWeights);
@@ -6,6 +6,13 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { selectionHash } from "../ci/test-selection-manifest.mjs";
import {
defaultServerParallelWorkers,
resolveServerParallelWorkers,
resolveWorkspaceParallelWorkers,
} from "../ci/vitest-workers.mjs";
import { partitionWorkspaceProjects, selectWorkspaceProjectsShard } from "../ci/workspaces-b-shard.mjs";
import { discoverWorkspacePackagePaths, ensureAllWorkspaceLinksCurrent } from "../ensure-workspace-package-links.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
const script = path.join(repoRoot, "scripts", "run-vitest-stable.mjs");
@@ -19,6 +26,7 @@ function workflowEnv(envOverrides = {}) {
"PAPERCLIP_CI_EXCLUDE_NIGHTLY",
"PAPERCLIP_CI_NIGHTLY_SUITES_FILE",
"PAPERCLIP_VITEST_MAX_WORKERS",
"PAPERCLIP_VITEST_CPU_COUNT",
"PAPERCLIP_TEST_POSTGRES_ADMIN_URL",
"PAPERCLIP_CI_TEST_SELECTION",
"PAPERCLIP_CI_SELECTION_HASH",
@@ -74,6 +82,7 @@ test("general-workspaces-b and general-workspaces-a batch all projects into one
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"));
assert.ok(aCalls[0].some((arg) => /^--maxWorkers=\d+$/.test(arg)), `expected top-level --maxWorkers in ${aCalls[0].join(" ")}`);
} finally {
rmSync(directory, { recursive: true, force: true });
}
@@ -233,3 +242,152 @@ test("shared Postgres wrapper skips non-Postgres workspace groups even when opte
rmSync(directory, { recursive: true, force: true });
}
});
test("dynamic server workers scale cleanly across 4-core and 8-core runners while honoring explicit overrides", { skip: process.platform === "win32" }, () => {
assert.equal(defaultServerParallelWorkers("general", 1), 1);
assert.equal(defaultServerParallelWorkers("general", 4), 4);
assert.equal(defaultServerParallelWorkers("general", 8), 7);
assert.equal(defaultServerParallelWorkers("general", 16), 8);
assert.equal(defaultServerParallelWorkers("serialized", 1), 1);
assert.equal(defaultServerParallelWorkers("serialized", 4), 3);
assert.equal(defaultServerParallelWorkers("serialized", 8), 5);
assert.equal(defaultServerParallelWorkers("serialized", 16), 6);
assert.equal(resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_CPU_COUNT: "8" }), 7);
assert.equal(resolveServerParallelWorkers("serialized", { PAPERCLIP_VITEST_CPU_COUNT: "8" }), 5);
assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "4" }), 4);
assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "8" }), 7);
assert.equal(resolveWorkspaceParallelWorkers({ PAPERCLIP_VITEST_CPU_COUNT: "8", PAPERCLIP_VITEST_MAX_WORKERS: "3" }), 3);
assert.equal(
resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_CPU_COUNT: "8", PAPERCLIP_VITEST_MAX_WORKERS: "2" }),
2,
);
assert.throws(() => resolveServerParallelWorkers("general", { PAPERCLIP_VITEST_MAX_WORKERS: "0" }));
const directory = mkdtempSync(path.join(os.tmpdir(), "dynamic-workers-"));
const receipt = path.join(directory, "args.json");
const fakePnpm = path.join(directory, "pnpm");
writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').writeFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)));\n`);
chmodSync(fakePnpm, 0o755);
try {
for (const [cpuCount, expectedGeneral, expectedSerialized] of [
["4", 4, 3],
["8", 7, 5],
]) {
for (const [modeArgs, expectedWorkers] of [
[["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], expectedGeneral],
[["--mode", "general", "--group", "general-server-native-runner"], expectedGeneral],
[["--mode", "serialized", "--shard-index", "0", "--shard-count", "9"], expectedSerialized],
]) {
const result = spawnSync(process.execPath, [script, ...modeArgs], {
cwd: repoRoot,
encoding: "utf8",
env: workflowEnv({
PATH: `${directory}${path.delimiter}${process.env.PATH}`,
PAPERCLIP_CI_PROFILE: "false",
PAPERCLIP_TEST_POSTGRES_SHARED: "0",
PAPERCLIP_VITEST_CPU_COUNT: cpuCount,
}),
});
assert.equal(result.status, 0, result.stdout + result.stderr);
const args = JSON.parse(readFileSync(receipt, "utf8"));
assert.ok(args.includes(`--maxWorkers=${expectedWorkers}`), `cpu=${cpuCount} expected --maxWorkers=${expectedWorkers} in ${args.join(" ")}`);
}
}
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
test("general-workspaces-b 2-shard split partitions projects cleanly without Vitest --shard and balances adapter-utils", { skip: process.platform === "win32" }, () => {
const unsharded = dryRunJson(["--mode", "general", "--group", "general-workspaces-b"]);
const shard0 = dryRunJson(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "0", "--shard-count", "2"]);
const shard1 = dryRunJson(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "1", "--shard-count", "2"]);
assert.equal(shard0.workspacesVitestShard, null);
assert.equal(shard1.workspacesVitestShard, null);
assert.deepEqual(shard0.workspaceProjects, ["@paperclipai/adapter-utils"]);
assert.ok(shard1.workspaceProjects.length === unsharded.workspaceProjects.length - 1);
const combined = [...shard0.workspaceProjects, ...shard1.workspaceProjects].sort();
assert.deepEqual(combined, [...unsharded.workspaceProjects].sort(), "2-shard partition must cover every project exactly once");
// Unknown future projects get default weight and are still partitioned cleanly.
const withFuture = partitionWorkspaceProjects([...unsharded.workspaceProjects, "@paperclipai/future-pkg"], 2);
assert.ok(withFuture.flatMap((s) => s.projects).includes("@paperclipai/future-pkg"));
assert.deepEqual(selectWorkspaceProjectsShard(unsharded.workspaceProjects, 0, 1), unsharded.workspaceProjects);
const directory = mkdtempSync(path.join(os.tmpdir(), "workspaces-b-shards-"));
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 existsSync(receipt)
? readFileSync(receipt, "utf8").trim().split("\n").map((line) => JSON.parse(line))
: [];
};
for (const [index, expectedProjects] of [
["0", shard0.workspaceProjects],
["1", shard1.workspaceProjects],
]) {
const calls = run(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", index, "--shard-count", "2"]);
assert.equal(calls.length, 1, `workspaces-b shard ${index}/2 must invoke vitest once`);
const projectsArg = calls[0].flatMap((arg, i) => (arg === "--project" ? [calls[0][i + 1]] : []));
assert.deepEqual(projectsArg, expectedProjects);
assert.ok(!calls[0].some((arg) => arg.startsWith("--shard=")), "project-partitioned shard must not pass --shard");
}
// Over-sharded empty bucket skips vitest rather than running unfiltered.
const emptyCalls = run(["--mode", "general", "--group", "general-workspaces-b", "--shard-index", "20", "--shard-count", "25"]);
assert.deepEqual(emptyCalls, []);
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
test("ensure-workspace-package-links discovers workspace packages and repairs stale links without tsx", { skip: process.platform === "win32" }, async () => {
const discovered = discoverWorkspacePackagePaths(repoRoot);
for (const name of ["@paperclipai/server", "@paperclipai/ui", "@paperclipai/shared", "@paperclipai/db", "@paperclipai/plugin-sdk", "paperclipai"]) {
assert.ok(discovered.has(name), `expected workspace package ${name}`);
}
const fixtureRoot = mkdtempSync(path.join(os.tmpdir(), "ws-links-fixture-"));
const { mkdirSync, symlinkSync, realpathSync } = await import("node:fs");
try {
const sharedDir = path.join(fixtureRoot, "packages", "shared");
const staleDir = path.join(fixtureRoot, "stale-target");
const serverDir = path.join(fixtureRoot, "server");
mkdirSync(path.join(sharedDir, "src"), { recursive: true });
mkdirSync(staleDir, { recursive: true });
mkdirSync(path.join(serverDir, "node_modules", "@paperclipai"), { recursive: true });
writeFileSync(path.join(sharedDir, "package.json"), JSON.stringify({ name: "@paperclipai/shared" }));
writeFileSync(path.join(serverDir, "package.json"), JSON.stringify({
name: "@paperclipai/server",
dependencies: { "@paperclipai/shared": "workspace:*" },
}));
symlinkSync(staleDir, path.join(serverDir, "node_modules", "@paperclipai", "shared"));
await ensureAllWorkspaceLinksCurrent(fixtureRoot);
assert.equal(
realpathSync(path.join(serverDir, "node_modules", "@paperclipai", "shared")),
realpathSync(sharedDir),
);
} finally {
rmSync(fixtureRoot, { recursive: true, force: true });
}
});
@@ -15,6 +15,7 @@ import {
import { assertManifestSource } from "../ci/pr-run-durations.mjs";
import { assertSelectedTests, partitionTestLines } from "../test-line-shard.mjs";
import { chatManifestData, entryDurations } from "../ci/refresh-chat-shard-durations.mjs";
import { defaultServerParallelWorkers } from "../ci/vitest-workers.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
const script = path.join(repoRoot, "scripts", "run-vitest-stable.mjs");
@@ -37,6 +38,7 @@ function workflowEnv(envOverrides = {}) {
"PAPERCLIP_CI_EXCLUDE_NIGHTLY",
"PAPERCLIP_CI_NIGHTLY_SUITES_FILE",
"PAPERCLIP_VITEST_MAX_WORKERS",
"PAPERCLIP_VITEST_CPU_COUNT",
"PAPERCLIP_TEST_POSTGRES_ADMIN_URL",
]) {
if (!(key in envOverrides)) {
@@ -101,12 +103,10 @@ test("general shards retain scripts and route-named suites outside the serialize
]) assert.ok(general.selectedGeneralServerSuites.includes(file), `missing configured server suite: ${file}`);
});
for (const group of ["general-workspaces-b", "general-workspaces-c"]) {
test(`shard flags are rejected for the ${group} group`, () => {
const result = dryRun(["--mode", "general", "--group", group, "--shard-index", "0", "--shard-count", "3"]);
assert.notEqual(result.status, 0, `${group} must not accept shard flags`);
});
}
test("shard flags are rejected for the general-workspaces-c group", () => {
const result = dryRun(["--mode", "general", "--group", "general-workspaces-c", "--shard-index", "0", "--shard-count", "3"]);
assert.notEqual(result.status, 0, "general-workspaces-c must not accept shard flags");
});
test("workspace lanes cover every non-server project in the root Vitest configuration", () => {
const config = readFileSync(path.join(repoRoot, "vitest.config.ts"), "utf8");
@@ -183,11 +183,19 @@ test("workspaces-c runs the db project alone and workspaces-b no longer carries
const sharded = entries.filter(entry => entry.group === "general-workspaces-a");
assert.ok(sharded.length > 0 && sharded.every(entry => entry.keys.includes("shard_index") && entry.keys.includes("shard_count")),
`${workflow} must carry the sharded workspaces-a entries`);
for (const group of ["general-workspaces-b", "general-workspaces-c"]) {
const matching = entries.filter(entry => entry.group === group);
assert.equal(matching.length, 1, `${workflow} must run ${group} exactly once`);
assert.ok(matching[0].keys.includes("group_label"), `${workflow} must label the ${group} job`);
assert.deepEqual(matching[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} must run ${group} unsharded`);
const workspacesCEntries = entries.filter(entry => entry.group === "general-workspaces-c");
assert.equal(workspacesCEntries.length, 1, `${workflow} must run general-workspaces-c exactly once`);
assert.ok(workspacesCEntries[0].keys.includes("group_label"), `${workflow} must label the general-workspaces-c job`);
assert.deepEqual(workspacesCEntries[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} must run general-workspaces-c unsharded`);
const workspacesBEntries = entries.filter(entry => entry.group === "general-workspaces-b");
assert.ok(workspacesBEntries.length >= 1, `${workflow} must run general-workspaces-b`);
assert.ok(workspacesBEntries.every(entry => entry.keys.includes("group_label")), `${workflow} must label every general-workspaces-b job`);
if (workspacesBEntries.length === 1) {
assert.deepEqual(workspacesBEntries[0].keys.filter(key => key.startsWith("shard_")), [], `${workflow} single general-workspaces-b entry must be unsharded`);
} else {
assert.ok(workspacesBEntries.every(entry => entry.keys.includes("shard_index") && entry.keys.includes("shard_count")),
`${workflow} multi-shard general-workspaces-b entries must declare shard_index and shard_count`);
}
}
});
@@ -885,11 +893,12 @@ test("a failed chat child fails the job after its sibling finishes", { skip: pro
}
});
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],
for (const [label, modeArgs, lane] of [
["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], "general"],
["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], "general"],
["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], "serialized"],
]) test(`${label} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => {
const parallelWorkers = defaultServerParallelWorkers(lane);
const directory = mkdtempSync(path.join(os.tmpdir(), "native-file-workers-"));
const receipt = path.join(directory, "args.json");
const fakePnpm = path.join(directory, "pnpm");
+469
View File
@@ -0,0 +1,469 @@
#!/usr/bin/env node
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const repoRootDefault = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
export const NIGHTLY_MANIFEST_REL = "scripts/ci/nightly-only-suites.json";
const TEST_FILE_PATTERN = /^(?:packages\/db\/src|server\/src|ui\/src)\/.+\.test\.tsx?$|^tests\/e2e\/.+\.spec\.ts$/;
const SLEEP_CALL_START_PATTERN = /\b(setTimeout|delay|waitForTimeout)\s*\(/g;
const READ_FILE_START_PATTERN = /\breadFile(?:Sync)?\s*\(/g;
const HISTORICAL_MIGRATION_FILE_PATTERN = /^(?:packages\/db\/src|server\/src)\/.*migration\.test\.ts$/;
const HISTORICAL_MIGRATION_CONTENT_PATTERN = /\b0\d{3}_[a-z0-9_]+\.sql\b|--> statement-breakpoint/;
const GUIDANCE_FILE_PATTERN = /-guidance\.test\.ts$/;
const PROSE_TARGET_PATTERN = /\.(?:md|tsx)\b|SKILL\.md|AGENTS\.md|README\.md/;
const EMBEDDED_PG_PATTERN = /\b(?:startEmbeddedPostgresTestDatabase|createTestPostgres)\b/;
export const PROTECTED_INVARIANT_PATTERN =
/(?:auth|authz|-access(?:\.|\/|$)|company-access|isolation|checkout|assignee|approval|(?:^|\/)budget-|budget-policy|budget-cancellation|budget-evaluation|budget-hold|activity-log|secret|csrf|redaction|guard|security|tenant|privacy|sentry|telemetry|otel|observability|injection|ssrf|oracle|cli-invocation-safety|webhook-ingress|credential|signature|device-login|policy-sweep|connection-management|document-scope)/i;
const MAX_PR_SLEEP_MS = 1_000;
const TINY_DB_FILE_MAX_LOC = 80;
function extractBalancedCallArgs(text, openParenIndex) {
let depth = 0;
let quote = null;
let escaped = false;
let argStart = openParenIndex + 1;
const args = [];
for (let i = openParenIndex; i < text.length; i += 1) {
const ch = text[i];
if (quote) {
if (escaped) {
escaped = false;
} else if (ch === "\\") {
escaped = true;
} else if (ch === quote) {
quote = null;
}
continue;
}
if (ch === "'" || ch === '"' || ch === "`") {
quote = ch;
continue;
}
if (ch === "(" || ch === "[" || ch === "{") {
depth += 1;
continue;
}
if (ch === ")" || ch === "]" || ch === "}") {
depth -= 1;
if (depth === 0) {
args.push(text.slice(argStart, i));
return { args, endIndex: i };
}
continue;
}
if (ch === "," && depth === 1) {
args.push(text.slice(argStart, i));
argStart = i + 1;
}
}
return null;
}
function evaluateDurationExprMs(expr) {
const cleaned = expr.replace(/\/\*[\s\S]*?\*\//g, "").trim();
if (!cleaned) return 0;
// Match pure numeric expressions like `2500`, `1_500`, `60 * 1000`, `5 * 60 * 1_000`, `2_000 + 500`.
if (/^[\d_\s+*().]+$/.test(cleaned)) {
const sumTerms = cleaned.replace(/[()]/g, "").split("+");
let total = 0;
for (const term of sumTerms) {
const factors = term.split("*").map((part) => Number(part.trim().replaceAll("_", "")));
if (factors.some((n) => !Number.isFinite(n))) return 0;
total += factors.reduce((acc, n) => acc * n, 1);
}
return total;
}
// Fallback: inspect the largest standalone numeric literal inside a compound expression.
let max = 0;
for (const m of cleaned.matchAll(/\b(\d[\d_]*)\b/g)) {
const value = Number(m[1].replaceAll("_", ""));
if (Number.isFinite(value) && value > max) max = value;
}
return max;
}
function lineNumberAt(source, offset) {
let line = 1;
for (let i = 0; i < offset; i += 1) {
if (source.charCodeAt(i) === 10) line += 1;
}
return line;
}
function hasProseSourceRead(source) {
READ_FILE_START_PATTERN.lastIndex = 0;
let match;
while ((match = READ_FILE_START_PATTERN.exec(source)) !== null) {
const openParen = match.index + match[0].length - 1;
const call = extractBalancedCallArgs(source, openParen);
const firstArg = call?.args[0] ?? "";
if (PROSE_TARGET_PATTERN.test(firstArg)) {
return true;
}
}
return false;
}
function fakeTimersFakesSetTimeout(rawArgs) {
const args = (rawArgs ?? "").trim();
if (!args) return true;
const toFakeMatch = args.match(/\btoFake\s*:\s*\[([^\]]*)\]/);
if (toFakeMatch) {
return /['"`]setTimeout['"`]/.test(toFakeMatch[1]);
}
const doNotFakeMatch = args.match(/\bdoNotFake\s*:\s*\[([^\]]*)\]/);
if (doNotFakeMatch && /['"`]setTimeout['"`]/.test(doNotFakeMatch[1])) {
return false;
}
return true;
}
function buildFakeTimeoutRanges(source) {
// Walk timer-mode transitions and test boundaries in source order so partial
// fakes (e.g. `toFake: ["Date"]`) and real-clock tests in mixed-clock files
// are still checked for unbudgeted `setTimeout` sleeps.
const events = [];
const hookRanges = [];
const hookRe = /\b(beforeEach|beforeAll|afterEach|afterAll)\s*\(/g;
let m;
while ((m = hookRe.exec(source)) !== null) {
const call = extractBalancedCallArgs(source, m.index + m[0].length - 1);
if (!call) continue;
hookRanges.push({ kind: m[1], start: m.index, end: call.endIndex });
}
const hookKindAt = (offset) => {
for (const h of hookRanges) {
if (offset >= h.start && offset <= h.end) return h.kind;
}
return null;
};
const fakeRe = /\b(?:vi|jest)\.useFakeTimers\s*\(/g;
while ((m = fakeRe.exec(source)) !== null) {
const call = extractBalancedCallArgs(source, m.index + m[0].length - 1);
const fakesSetTimeout = fakeTimersFakesSetTimeout(call?.args[0] ?? "");
const hook = hookKindAt(m.index);
events.push({
offset: m.index,
kind: hook === "beforeEach" || hook === "beforeAll" ? "hook-fake" : "fake",
fakesSetTimeout,
});
}
const realRe = /\b(?:vi|jest)\.useRealTimers\s*\(/g;
while ((m = realRe.exec(source)) !== null) {
const hook = hookKindAt(m.index);
if (hook === "afterEach" || hook === "afterAll") continue;
events.push({ offset: m.index, kind: "real", fakesSetTimeout: false });
}
const testBoundaryRe = /^\s*(?:it|test|describe)(?:\.(?:only|skip|concurrent|sequential|each))?\s*\(/gm;
while ((m = testBoundaryRe.exec(source)) !== null) {
events.push({ offset: m.index, kind: "boundary", fakesSetTimeout: false });
}
events.sort((a, b) => a.offset - b.offset);
return function isSetTimeoutFakedAt(offset) {
let hookFake = false;
let localFake = false;
for (const ev of events) {
if (ev.offset > offset) break;
if (ev.kind === "hook-fake") {
hookFake = ev.fakesSetTimeout;
localFake = hookFake;
} else if (ev.kind === "boundary") {
localFake = hookFake;
} else if (ev.kind === "fake") {
localFake = ev.fakesSetTimeout;
} else if (ev.kind === "real") {
localFake = false;
}
}
return localFake;
};
}
export function findUnbudgetedSleeps(source, { onlyLineNumbers = null } = {}) {
const violations = [];
const lines = source.split(/\r?\n/);
const isSetTimeoutFakedAt = buildFakeTimeoutRanges(source);
const clearedHandles = new Set(
[...source.matchAll(/\bclearTimeout\s*\(\s*([A-Za-z_$][\w$]*)\s*\)/g)].map((m) => m[1]),
);
SLEEP_CALL_START_PATTERN.lastIndex = 0;
let match;
while ((match = SLEEP_CALL_START_PATTERN.exec(source)) !== null) {
const lineNumber = lineNumberAt(source, match.index);
const line = lines[lineNumber - 1] ?? "";
if (/^\s*\/\//.test(line)) continue;
const openParen = match.index + match[0].length - 1;
const call = extractBalancedCallArgs(source, openParen);
if (!call) continue;
const endLineNumber = lineNumberAt(source, call.endIndex);
if (onlyLineNumbers) {
let touchesAdded = false;
for (let ln = lineNumber; ln <= endLineNumber; ln += 1) {
if (onlyLineNumbers.has(ln)) {
touchesAdded = true;
break;
}
}
if (!touchesAdded) continue;
}
let allowed = false;
for (let ln = lineNumber; ln <= endLineNumber; ln += 1) {
if ((lines[ln - 1] ?? "").includes("test-budget:allow-sleep")) {
allowed = true;
break;
}
}
if (allowed) continue;
const callee = match[1];
if (callee === "setTimeout") {
if (isSetTimeoutFakedAt(match.index)) continue;
// Ignore cancellable deadline timers (e.g. `const timer = setTimeout(...); ... clearTimeout(timer)`).
const beforeOnLine = source.slice(Math.max(0, match.index - 80), match.index);
const assignedVar = beforeOnLine.match(/([A-Za-z_$][\w$]*)\s*=\s*$/);
if (assignedVar && clearedHandles.has(assignedVar[1])) {
continue;
}
}
const delayArg = callee === "setTimeout" ? call.args[1] ?? "" : call.args[0] ?? "";
const ms = evaluateDurationExprMs(delayArg);
if (ms > MAX_PR_SLEEP_MS) {
violations.push({
rule: "sleep-over-1s",
line: lineNumber,
message: `Unbudgeted real-clock sleep (${ms}ms > ${MAX_PR_SLEEP_MS}ms). Use fake timers/condition waits, move soak suite to ${NIGHTLY_MANIFEST_REL}, or annotate with // test-budget:allow-sleep: <reason>.`,
});
}
}
return violations;
}
export function validateNightlyManifest(root = repoRootDefault, manifestRel = NIGHTLY_MANIFEST_REL) {
const fullPath = path.join(root, manifestRel);
const violations = [];
if (!existsSync(fullPath)) {
return { paths: new Set(), violations: [{ file: manifestRel, rule: "nightly-manifest", message: "Missing nightly manifest." }] };
}
let parsed;
try {
parsed = JSON.parse(readFileSync(fullPath, "utf8"));
} catch (error) {
return {
paths: new Set(),
violations: [{ file: manifestRel, rule: "nightly-manifest", message: `Invalid JSON: ${error.message}` }],
};
}
if (!Array.isArray(parsed?.suites)) {
return {
paths: new Set(),
violations: [{ file: manifestRel, rule: "nightly-manifest", message: "Manifest must contain a suites array." }],
};
}
const seen = new Set();
for (const entry of parsed.suites) {
const suitePath = typeof entry === "string" ? entry : entry?.path;
if (typeof suitePath !== "string" || !suitePath.trim()) {
violations.push({ file: manifestRel, rule: "nightly-manifest", message: "Suite entry is missing a non-empty string path." });
continue;
}
if (suitePath.startsWith("/") || suitePath.includes("\\") || suitePath.split("/").includes("..")) {
violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Invalid non-repo-relative path: ${suitePath}` });
continue;
}
if (seen.has(suitePath)) {
violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Duplicate suite path: ${suitePath}` });
continue;
}
seen.add(suitePath);
if (!existsSync(path.join(root, suitePath))) {
violations.push({ file: manifestRel, rule: "nightly-manifest", message: `Nightly suite does not exist on disk: ${suitePath}` });
}
if (PROTECTED_INVARIANT_PATTERN.test(suitePath)) {
violations.push({
file: manifestRel,
rule: "protected-invariant",
message: `Core control-plane / security / privacy invariant suite must remain on PRs, not in ${manifestRel}: ${suitePath}`,
});
}
}
return { paths: seen, violations };
}
export function checkTestFileBudget(fileRel, source, { isNew = true, nightlyPaths = new Set(), addedLineNumbers = null } = {}) {
if (!TEST_FILE_PATTERN.test(fileRel)) return [];
const violations = [];
const isNightly = nightlyPaths.has(fileRel);
if (!isNightly) {
for (const v of findUnbudgetedSleeps(source, { onlyLineNumbers: isNew ? null : addedLineNumbers })) {
violations.push({ file: fileRel, ...v });
}
}
if (isNew) {
if (
HISTORICAL_MIGRATION_FILE_PATTERN.test(fileRel) &&
HISTORICAL_MIGRATION_CONTENT_PATTERN.test(source) &&
!source.includes("test-budget:allow-migration-test")
) {
violations.push({
file: fileRel,
rule: "historical-migration-test",
message: "Do not add standalone historical SQL migration replay tests; extend core runner tests in packages/db/src/client.test.ts or migration-compatibility.test.ts.",
});
}
if (
GUIDANCE_FILE_PATTERN.test(fileRel) &&
hasProseSourceRead(source) &&
!source.includes("test-budget:allow-prose-check")
) {
violations.push({
file: fileRel,
rule: "prose-guidance-grep",
message: "Do not add brittle static prose-grep guidance tests over .md/.tsx files.",
});
}
const lineCount = source.split(/\r?\n/).length;
if (
!isNightly &&
lineCount <= TINY_DB_FILE_MAX_LOC &&
EMBEDDED_PG_PATTERN.test(source) &&
!source.includes("test-budget:allow-standalone-db")
) {
violations.push({
file: fileRel,
rule: "tiny-standalone-db-test",
message: `New embedded-Postgres test file is only ${lineCount} LOC (<= ${TINY_DB_FILE_MAX_LOC}). Extend the owning service/route suite instead, or annotate with // test-budget:allow-standalone-db: <reason>.`,
});
}
}
return violations;
}
function addedLinesFromDiff(root, baseRef, fileRel) {
const diff = execFileSync("git", ["diff", "-U0", `${baseRef}...HEAD`, "--", fileRel], {
cwd: root,
encoding: "utf8",
});
const added = new Set();
let currentLine = 0;
for (const line of diff.split(/\r?\n/)) {
const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
if (hunk) {
currentLine = Number(hunk[1]);
continue;
}
if (line.startsWith("+") && !line.startsWith("+++")) {
added.add(currentLine);
currentLine += 1;
} else if (!line.startsWith("-")) {
currentLine += 1;
}
}
return added;
}
function changedTestFilesFromBase(root, baseRef) {
const out = execFileSync("git", ["diff", "--diff-filter=AM", "--name-status", `${baseRef}...HEAD`], {
cwd: root,
encoding: "utf8",
});
const entries = [];
for (const raw of out.split(/\r?\n/)) {
if (!raw.trim()) continue;
const [status, fileRel] = raw.split("\t");
if (!fileRel || !TEST_FILE_PATTERN.test(fileRel)) continue;
entries.push({ fileRel, isNew: status === "A" });
}
return entries;
}
export function parseBudgetArgs(argv) {
const options = { base: null, files: [], root: repoRootDefault, manifestOnly: false };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === "--base") {
options.base = argv[++i] ?? null;
} else if (arg.startsWith("--base=")) {
options.base = arg.slice("--base=".length);
} else if (arg === "--root") {
options.root = path.resolve(argv[++i] ?? repoRootDefault);
} else if (arg === "--manifest-only") {
options.manifestOnly = true;
} else if (arg === "--files") {
while (i + 1 < argv.length && !argv[i + 1].startsWith("--")) {
options.files.push(argv[++i]);
}
} else if (!arg.startsWith("--")) {
options.files.push(arg);
}
}
return options;
}
export function runTestBudgetCheck(options) {
const root = options.root ?? repoRootDefault;
const { paths: nightlyPaths, violations } = validateNightlyManifest(root);
if (options.manifestOnly) {
return { nightlyCount: nightlyPaths.size, checkedFiles: 0, violations };
}
let targets = [];
if (options.files?.length) {
targets = options.files.map((fileRel) => ({ fileRel, isNew: true, addedLineNumbers: null }));
} else if (options.base) {
targets = changedTestFilesFromBase(root, options.base).map((entry) => ({
...entry,
addedLineNumbers: entry.isNew ? null : addedLinesFromDiff(root, options.base, entry.fileRel),
}));
}
for (const target of targets) {
const absPath = path.join(root, target.fileRel);
if (!existsSync(absPath)) continue;
const source = readFileSync(absPath, "utf8");
violations.push(
...checkTestFileBudget(target.fileRel, source, {
isNew: target.isNew,
nightlyPaths,
addedLineNumbers: target.addedLineNumbers,
}),
);
}
return { nightlyCount: nightlyPaths.size, checkedFiles: targets.length, violations };
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const options = parseBudgetArgs(process.argv.slice(2));
const result = runTestBudgetCheck(options);
if (result.violations.length > 0) {
console.error(`[check-test-budget] FAILED with ${result.violations.length} violation(s):`);
for (const v of result.violations) {
const loc = v.line ? `${v.file}:${v.line}` : v.file;
console.error(` - [${v.rule}] ${loc}: ${v.message}`);
}
process.exit(1);
}
console.log(
`[check-test-budget] PASS (${result.nightlyCount} nightly suites validated, ${result.checkedFiles} test file(s) checked).`,
);
}
+212
View File
@@ -0,0 +1,212 @@
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import {
checkTestFileBudget,
findUnbudgetedSleeps,
runTestBudgetCheck,
validateNightlyManifest,
} from "./check-test-budget.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
test("checked-in scripts/ci/nightly-only-suites.json passes full manifest & invariant validation", () => {
const result = runTestBudgetCheck({ manifestOnly: true });
assert.deepEqual(result.violations, []);
assert.ok(result.nightlyCount > 0, "expected non-empty nightly-only-suites.json");
});
test("findUnbudgetedSleeps flags real-clock sleeps >1000ms (including inline callbacks and products) and respects allow-sleep annotations", () => {
const source = [
"await delay(500);",
"await delay(1000);",
"await delay(1_500);",
"await setTimeout(resolve, 2500);",
"await new Promise((resolve) => setTimeout(() => resolve(), 2500));",
"await new Promise((resolve) => setTimeout(() => { resolve(); }, 60 * 1000));",
"await delay(2 * 1000);",
"await page.waitForTimeout(3000);",
"await delay(5000); // test-budget:allow-sleep: socket idle check",
"// await delay(9000);",
].join("\n");
const violations = findUnbudgetedSleeps(source);
assert.deepEqual(
violations.map((v) => ({ rule: v.rule, line: v.line })),
[
{ rule: "sleep-over-1s", line: 3 },
{ rule: "sleep-over-1s", line: 4 },
{ rule: "sleep-over-1s", line: 5 },
{ rule: "sleep-over-1s", line: 6 },
{ rule: "sleep-over-1s", line: 7 },
{ rule: "sleep-over-1s", line: 8 },
],
);
// Cancellable deadline timers and full fake-timer scopes must not produce false positives.
assert.deepEqual(
findUnbudgetedSleeps(
"const timer = setTimeout(() => reject(new Error('timeout')), 60_000);\nclearTimeout(timer);",
),
[],
);
assert.deepEqual(
findUnbudgetedSleeps("vi.useFakeTimers();\nsetTimeout(() => done(), 10_000);"),
[],
);
assert.deepEqual(
findUnbudgetedSleeps(
'beforeEach(() => { vi.useFakeTimers(); });\nafterEach(() => { vi.useRealTimers(); });\nit("faked", () => {\n setTimeout(() => done(), 5000);\n});',
),
[],
);
assert.deepEqual(
findUnbudgetedSleeps(
'vi.useFakeTimers({ toFake: ["Date", "setTimeout"] });\nsetTimeout(() => done(), 2500);',
),
[],
);
// Partial fake timers (e.g. Date-only) and real-clock tests in mixed-clock files MUST still be flagged.
assert.deepEqual(
findUnbudgetedSleeps(
'vi.useFakeTimers({ toFake: ["Date"] });\nawait new Promise((resolve) => setTimeout(resolve, 2500));',
).map((v) => ({ rule: v.rule, line: v.line })),
[{ rule: "sleep-over-1s", line: 2 }],
);
assert.deepEqual(
findUnbudgetedSleeps(
'vi.useFakeTimers({ doNotFake: ["setTimeout"] });\nawait new Promise((resolve) => setTimeout(resolve, 2500));',
).map((v) => ({ rule: v.rule, line: v.line })),
[{ rule: "sleep-over-1s", line: 2 }],
);
assert.deepEqual(
findUnbudgetedSleeps(
[
'it("faked", () => {',
" vi.useFakeTimers();",
" setTimeout(() => done(), 5000);",
"});",
'it("real", async () => {',
" await new Promise((resolve) => setTimeout(resolve, 2500));",
"});",
].join("\n"),
).map((v) => ({ rule: v.rule, line: v.line })),
[{ rule: "sleep-over-1s", line: 6 }],
);
assert.deepEqual(
findUnbudgetedSleeps(
[
'it("restores", async () => {',
" vi.useFakeTimers();",
" setTimeout(() => done(), 5000);",
" vi.useRealTimers();",
" await new Promise((resolve) => setTimeout(resolve, 2500));",
"});",
].join("\n"),
).map((v) => ({ rule: v.rule, line: v.line })),
[{ rule: "sleep-over-1s", line: 5 }],
);
});
test("checkTestFileBudget enforces migration, prose-guidance, and tiny embedded-PG rules on new files", () => {
const mig = checkTestFileBudget(
"packages/db/src/old-backfill-migration.test.ts",
'const sql = readFileSync("./migrations/0420_backfill.sql", "utf8");',
{ isNew: true },
);
assert.deepEqual(mig.map((v) => v.rule), ["historical-migration-test"]);
const guidance = checkTestFileBudget(
"server/src/__tests__/foo-guidance.test.ts",
'const text = readFileSync("ui/src/App.tsx", "utf8"); expect(text).toContain("Settings");',
{ isNew: true },
);
assert.deepEqual(guidance.map((v) => v.rule), ["prose-guidance-grep"]);
const nestedGuidance = checkTestFileBudget(
"server/src/__tests__/bar-guidance.test.ts",
'const text = readFileSync(path.join(dir, "README.md"), "utf8"); expect(text).toContain("Usage");',
{ isNew: true },
);
assert.deepEqual(nestedGuidance.map((v) => v.rule), ["prose-guidance-grep"]);
const tinyPg = checkTestFileBudget(
"server/src/__tests__/tiny-one-off.test.ts",
'import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";\nit("works", async () => {});',
{ isNew: true },
);
assert.deepEqual(tinyPg.map((v) => v.rule), ["tiny-standalone-db-test"]);
const tinyPgAllowed = checkTestFileBudget(
"server/src/__tests__/tiny-one-off.test.ts",
'// test-budget:allow-standalone-db: needs isolated process env\nimport { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";',
{ isNew: true },
);
assert.deepEqual(tinyPgAllowed, []);
// Nightly-registered suites are exempt from PR sleep & tiny-DB limits.
const nightly = checkTestFileBudget(
"server/src/__tests__/soak-example.test.ts",
'import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";\nawait delay(5000);',
{ isNew: true, nightlyPaths: new Set(["server/src/__tests__/soak-example.test.ts"]) },
);
assert.deepEqual(nightly, []);
});
test("validateNightlyManifest rejects missing files, duplicates, and protected core invariant suites", () => {
const tmp = mkdtempSync(path.join(os.tmpdir(), "paperclip-test-budget-"));
try {
mkdirSync(path.join(tmp, "scripts/ci"), { recursive: true });
mkdirSync(path.join(tmp, "server/src/__tests__"), { recursive: true });
mkdirSync(path.join(tmp, "server/src/services/connectors"), { recursive: true });
writeFileSync(path.join(tmp, "server/src/__tests__/authz-company-access.test.ts"), "// authz\n");
writeFileSync(path.join(tmp, "server/src/services/connectors/slack-access.test.ts"), "// access\n");
writeFileSync(path.join(tmp, "server/src/services/budget-resume-continuation.test.ts"), "// budget\n");
writeFileSync(path.join(tmp, "server/src/__tests__/webhook-ingress.test.ts"), "// webhook\n");
writeFileSync(path.join(tmp, "server/src/__tests__/storage-s3-credential-rotation.test.ts"), "// cred\n");
writeFileSync(path.join(tmp, "server/src/__tests__/connection-management.integration.test.ts"), "// isolation\n");
writeFileSync(path.join(tmp, "server/src/__tests__/real-soak.test.ts"), "// soak\n");
writeFileSync(
path.join(tmp, "scripts/ci/nightly-only-suites.json"),
JSON.stringify({
suites: [
{ path: "server/src/__tests__/real-soak.test.ts" },
{ path: "server/src/__tests__/real-soak.test.ts" },
{ path: "server/src/__tests__/missing-suite.test.ts" },
{ path: "server/src/__tests__/authz-company-access.test.ts" },
{ path: "server/src/services/connectors/slack-access.test.ts" },
{ path: "server/src/services/budget-resume-continuation.test.ts" },
{ path: "server/src/__tests__/webhook-ingress.test.ts" },
{ path: "server/src/__tests__/storage-s3-credential-rotation.test.ts" },
{ path: "server/src/__tests__/connection-management.integration.test.ts" },
],
}),
);
const { violations } = validateNightlyManifest(tmp);
assert.deepEqual(
violations.map((v) => v.rule),
[
"nightly-manifest",
"nightly-manifest",
"protected-invariant",
"protected-invariant",
"protected-invariant",
"protected-invariant",
"protected-invariant",
"protected-invariant",
],
);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
test("pr-trusted.yml invokes check-test-budget.mjs with --base on pull requests", () => {
const workflow = readFileSync(path.join(repoRoot, ".github/workflows/pr-trusted.yml"), "utf8");
assert.match(workflow, /node \.\/scripts\/check-test-budget\.mjs --base "\$base_sha"/);
});
+15 -5
View File
@@ -1,10 +1,13 @@
import { execFileSync } from "node:child_process";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { appendFileSync, existsSync, readFileSync, realpathSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { readPluginsUnder } from "./link-plugin-dev-sdk.mjs";
const execFileAsync = promisify(execFile);
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const postinstallHooks = new Map([
@@ -55,9 +58,16 @@ export function cachePlan({ files, read, scope, packageDirs }) {
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const files = execFileSync("git", ["ls-files", "-z"], { cwd: root }).toString().split("\0").filter(Boolean);
const command = (args) => execFileSync("pnpm", args, { cwd: root, encoding: "utf8" }).trim();
const workspaces = JSON.parse(command(['-r', 'list', '--depth=-1', '--json']));
const command = (bin, args) =>
execFileAsync(bin, args, { cwd: root, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).then(({ stdout }) => stdout);
const [gitFilesRaw, workspacesRaw, pnpmVersionRaw, pnpmStoreRaw] = await Promise.all([
command("git", ["ls-files", "-z"]),
command("pnpm", ["-r", "list", "--depth=-1", "--json"]),
command("pnpm", ["--version"]),
command("pnpm", ["store", "path", "--silent"]),
]);
const files = gitFilesRaw.split("\0").filter(Boolean);
const workspaces = JSON.parse(workspacesRaw.trim());
const packageDirs = ['.',
...workspaces.map((workspace) => path.relative(root, workspace.path).split(path.sep).join('/') || '.'),
...readPluginsUnder(path.join(root, 'packages/plugins/sandbox-providers')).map((directory) => path.relative(root, directory).split(path.sep).join('/')),
@@ -71,7 +81,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
root: realpathSync(root), node: process.version, abi: process.versions.modules,
platform: process.platform, arch: process.arch,
libc: process.report.getReport().header.glibcVersionRuntime ?? null,
pnpm: command(["--version"]), store: command(["store", "path", "--silent"]),
pnpm: pnpmVersionRaw.trim(), store: pnpmStoreRaw.trim(),
},
});
const output = [
+138 -36
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { execFileSync, spawn, spawnSync } from "node:child_process";
import { availableParallelism, setPriority } from "node:os";
import { availableParallelism, setPriority, totalmem } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { listLayers } from "../server/scripts/typecheck-layers.mjs";
@@ -13,10 +13,72 @@ 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;
export const PREPARE_RUNNER_VENDOR = "prepare runner vendor";
export const BUILD_SERVER_EMIT_ONLY = "build server without type checks";
const SERVER_DECLARATIONS = "server declarations";
export const CLI_GUIDANCE_SAFETY = "CLI guidance safety";
const lowMemory = { [LOW_MEMORY_VARIABLE]: "1" };
/**
* Computes CPU- and RAM-aware concurrency and TypeScript 7 checker/GOMAXPROCS settings.
* Keeps peak memory safely under 16 GiB on 4-core (m8i.xlarge) and 8-core (c8i.2xlarge)
* runners while scaling up cleanly on 8+ core / >= 24 GiB machines.
*/
export function computeResourceProfile({ cpus = availableParallelism(), totalMemoryBytes = totalmem() } = {}) {
const safeCpus = Math.max(1, Number.isFinite(cpus) ? Math.floor(cpus) : 4);
const totalMemGiB = totalMemoryBytes / 1024 ** 3;
if (safeCpus <= 2 || totalMemGiB < 12) {
return {
laneConcurrency: Math.min(2, safeCpus),
serverDeclCheckers: 1,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 1,
testProgramsConcurrency: 1,
testProgramsCheckers: 1,
};
}
if (safeCpus <= 4) {
return {
laneConcurrency: 3,
serverDeclCheckers: 2,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 2,
testProgramsConcurrency: 2,
testProgramsCheckers: 1,
};
}
if (totalMemGiB < 24) {
// 8-core / 16 GiB (e.g. c8i.2xlarge): run all 4 server test layers in 1 wave at 1 checker each (~10 GiB),
// give server declarations 3 checkers (~6.5 GiB) and UI GOMAXPROCS=4 (~4.4 GiB).
return {
laneConcurrency: Math.min(4, safeCpus),
serverDeclCheckers: 3,
serverLayerCheckers: 1,
testProjectCheckers: 1,
uiGomaxprocs: 4,
testProgramsConcurrency: 3,
testProgramsCheckers: 1,
};
}
// 6-8+ core / >= 24 GiB (e.g. m8i.2xlarge or local dev): maximize parallelism across declarations, layers, and UI.
return {
laneConcurrency: Math.min(6, safeCpus),
serverDeclCheckers: Math.min(4, Math.max(3, Math.floor(safeCpus / 2))),
serverLayerCheckers: 2,
testProjectCheckers: 2,
uiGomaxprocs: 4,
testProgramsConcurrency: 4,
testProgramsCheckers: 2,
};
}
export const DEFAULT_RESOURCE_PROFILE = computeResourceProfile({
cpus: 4,
totalMemoryBytes: 16 * 1024 ** 3,
});
const GLOBAL_TYPECHECK_INPUTS = new Set([
"package.json",
"pnpm-lock.yaml",
@@ -89,7 +151,9 @@ export function selectBuildGapPackages(buildGapPackages, changedFiles) {
"packages/shared/",
"packages/adapter-utils/",
"packages/adapters/",
"packages/paperclip-runner/",
"packages/plugins/sdk/",
"announcements/examples/animated/",
"maps/",
]);
}
@@ -208,7 +272,8 @@ export function planLane({
testLayers,
projects = PROJECTS,
changedFiles = null,
testProgramsConcurrency = DEFAULT_TEST_PROGRAMS_CONCURRENCY,
resources = DEFAULT_RESOURCE_PROFILE,
testProgramsConcurrency = resources.testProgramsConcurrency ?? DEFAULT_TEST_PROGRAMS_CONCURRENCY,
}) {
const isPrMode = Array.isArray(changedFiles);
const selectedBuildGaps = selectBuildGapPackages(buildGapPackages, changedFiles);
@@ -217,13 +282,14 @@ export function planLane({
const runReleaseRegistry = shouldRunReleaseRegistryTests(changedFiles);
const programSelection = selectTestPrograms(changedFiles);
const typecheckPackage = (name, background) => ({
const typecheckPackage = (name, background, needs) => ({
name: `typecheck ${name}`,
command: "pnpm",
args: ["--filter", name, "typecheck"],
// UI typecheck runs ~7x faster without --singleThreaded while staying at ~4.4 GiB with GOMAXPROCS=2.
env: name === "@paperclipai/ui" ? { GOMAXPROCS: "2" } : lowMemory,
// UI typecheck runs ~7-10x faster without --singleThreaded while staying at ~4.4 GiB with bounded GOMAXPROCS.
env: name === "@paperclipai/ui" ? { GOMAXPROCS: String(resources.uiGomaxprocs) } : lowMemory,
background,
...(needs ? { needs } : {}),
});
const prepare = [{ name: "link workspace packages", command: "pnpm", args: ["run", "preflight:workspace-links"] }];
@@ -231,27 +297,11 @@ export function planLane({
if (runServer || selectedBuildGaps.length > 0 || programSelection.programs.length > 0) {
prepare.push({
name: "build plugin SDK",
command: "pnpm",
args: ["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"],
command: "node",
args: ["scripts/ensure-plugin-build-deps.mjs"],
});
}
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) {
@@ -271,15 +321,31 @@ export function planLane({
},
);
const needsRunnerVendor = [PREPARE_RUNNER_VENDOR];
const needsDeclarations = [SERVER_DECLARATIONS];
const tasks = [];
if (runServer) {
tasks.push({
name: SERVER_DECLARATIONS,
command: "node",
args: ["server/scripts/typecheck-layers.mjs", "--declarations-only", "--checkers", "2"],
});
// Ensure packages/paperclip-runner/dist is current once in parallel with UI / non-runner checks,
// then fan out server declarations and emit-only server build without racing on runner dist.
tasks.push(
{
name: PREPARE_RUNNER_VENDOR,
command: "pnpm",
args: ["--filter", "@paperclipai/server", "run", "prepare:runner-vendor"],
},
{
name: SERVER_DECLARATIONS,
command: "node",
args: [
"server/scripts/typecheck-layers.mjs",
"--declarations-only",
"--checkers",
String(resources.serverDeclCheckers),
],
needs: needsRunnerVendor,
},
);
}
if (runReleaseRegistry) {
@@ -291,7 +357,7 @@ export function planLane({
"scripts/typecheck-test-programs.mjs",
"--skip-prepare",
"--checkers",
"1",
String(resources.testProgramsCheckers),
"--concurrency",
String(testProgramsConcurrency),
];
@@ -315,6 +381,7 @@ export function planLane({
command: "node",
args: programArgs,
background: true,
...(runServer && programSelection.includeRunnerEval ? { needs: needsRunnerVendor } : {}),
});
}
@@ -323,20 +390,53 @@ export function planLane({
...testLayers.map((layer) => ({
name: `server layer ${layer}`,
command: "node",
args: ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"],
args: [
"server/scripts/typecheck-layers.mjs",
"--layer",
layer,
"--checkers",
String(resources.serverLayerCheckers),
],
needs: needsDeclarations,
})),
...selectedProjects.map((project) => ({
name: `test project ${project}`,
command: "node",
args: ["scripts/typecheck-test-projects.mjs", "--checkers", "1", "--reuse-declarations", project],
args: [
"scripts/typecheck-test-projects.mjs",
"--checkers",
String(resources.testProjectCheckers),
"--reuse-declarations",
project,
],
needs: needsDeclarations,
})),
{
name: BUILD_SERVER_EMIT_ONLY,
command: "pnpm",
args: ["--filter", "@paperclipai/server", "build"],
env: {
[EMIT_ONLY_VARIABLE]: "1",
PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT: "1",
},
needs: needsRunnerVendor,
background: true,
},
{
name: "check server runtime assets",
command: "node",
args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"],
needs: [BUILD_SERVER_EMIT_ONLY],
},
);
}
tasks.push(
...selectedBuildGaps.filter((name) => !SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, true)),
...selectedBuildGaps
.filter((name) => !SERIAL_BUILD_GAPS.includes(name))
.map((name) =>
typecheckPackage(name, true, runServer && name === "paperclipai" ? needsRunnerVendor : undefined),
),
);
return { prepare, tasks };
@@ -524,7 +624,8 @@ function listBuildGapPackages(root) {
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2);
let concurrency = Math.max(1, Math.min(DEFAULT_MAX_CONCURRENCY, availableParallelism()));
const resources = computeResourceProfile();
let concurrency = resources.laneConcurrency;
let base;
let full = false;
let valid = true;
@@ -559,10 +660,11 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
scope.mode === "pr"
? `PR (${scope.changedFiles.length} changed files via ${scope.reason})`
: `full (${scope.reason})`;
const lanePlan = planLane({ buildGapPackages, testLayers, changedFiles: scope.changedFiles });
const lanePlan = planLane({ buildGapPackages, testLayers, changedFiles: scope.changedFiles, resources });
console.log(
`typecheck lane: ${concurrency} at a time; mode: ${scopeDetail}; ` +
`prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` +
`typecheck lane: ${concurrency} at a time (${availableParallelism()} vCPU, ${(totalmem() / 1024 ** 3).toFixed(1)} GiB; ` +
`decl=${resources.serverDeclCheckers}, layers=${resources.serverLayerCheckers}, ui=${resources.uiGomaxprocs}); ` +
`mode: ${scopeDetail}; prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` +
`build gaps: ${buildGapPackages.join(", ")}`,
);
process.exitCode = await runLane({ ...lanePlan, concurrency, cwd: root });
File diff suppressed because it is too large. Load diff
+59
View File
@@ -0,0 +1,59 @@
import os from "node:os";
function parsePositiveIntegerEnv(raw, name) {
const parsed = Number(raw);
if (raw.trim() === "" || !Number.isInteger(parsed) || parsed < 1) {
throw new Error(`${name} must be a positive integer. Received "${raw}".`);
}
return parsed;
}
export function resolveAvailableCpuCount(env = process.env) {
const override = env.PAPERCLIP_VITEST_CPU_COUNT?.trim();
if (override) {
return parsePositiveIntegerEnv(override, "PAPERCLIP_VITEST_CPU_COUNT");
}
return Math.max(1, os.availableParallelism());
}
export function defaultServerParallelWorkers(lane, cpuCount = resolveAvailableCpuCount()) {
if (!Number.isInteger(cpuCount) || cpuCount < 1) {
throw new Error(`CPU count must be a positive integer. Received "${cpuCount}".`);
}
if (lane === "general") {
// 4-core runners keep 4 workers; 8-core runners scale to 7 (leaving 1 core
// for shared PostgreSQL + Vitest coordinator) and cap at 8 on large hosts.
if (cpuCount <= 4) {
return cpuCount;
}
return Math.min(8, cpuCount - 1);
}
if (lane === "serialized") {
// Route/authz suites are heavier per fork; keep 3 workers on 4-core runners
// and scale smoothly to 5 workers on 8-core runners (capped at 6).
if (cpuCount <= 2) return 1;
if (cpuCount === 3) return 2;
if (cpuCount === 4) return 3;
return Math.min(6, Math.max(3, Math.round((cpuCount * 5) / 8)));
}
throw new Error(`Unknown server worker lane "${lane}". Expected "general" or "serialized".`);
}
export function resolveServerParallelWorkers(lane, env = process.env) {
const raw = env.PAPERCLIP_VITEST_MAX_WORKERS?.trim();
if (raw) {
return parsePositiveIntegerEnv(raw, "PAPERCLIP_VITEST_MAX_WORKERS");
}
return defaultServerParallelWorkers(lane, resolveAvailableCpuCount(env));
}
export function resolveWorkspaceParallelWorkers(env = process.env) {
const raw = env.PAPERCLIP_VITEST_MAX_WORKERS?.trim();
if (raw) {
return parsePositiveIntegerEnv(raw, "PAPERCLIP_VITEST_MAX_WORKERS");
}
// Vitest defaults to cpus - 1 for forks (3 workers on 4-core CI, leaving a core idle).
// Use 4 workers on 4-core runners and cap at 7 on 8+-core runners so 1 core stays
// free for the Vite transform server.
return Math.min(7, resolveAvailableCpuCount(env));
}
+91
View File
@@ -0,0 +1,91 @@
// Duration-weighted project sharding for `general-workspaces-b`.
// Measured weights (ms, batched multi-project Vitest run on 4-core runners):
// `@paperclipai/adapter-utils` (~2,146 tests, ~135s) dominates the 17-project
// lane and equals the combined batched runtime of the remaining 16 packages
// (~133s), so a 2-shard LPT split naturally balances ~2.2m per shard.
export const DEFAULT_WORKSPACE_PROJECT_WEIGHT_MS = 10_000;
export const WORKSPACES_B_PROJECT_DURATIONS_MS = Object.freeze({
"@paperclipai/adapter-utils": 135_000,
"@paperclipai/plugin-daytona": 34_000,
"@paperclipai/adapter-claude-local": 20_000,
"@paperclipai/adapter-codex-local": 17_500,
"@paperclipai/adapter-gemini-local": 8_800,
"@paperclipai/hermes-paperclip-adapter": 7_900,
"@paperclipai/adapter-grok-local": 7_400,
"@paperclipai/shared": 6_500,
"@paperclipai/plugin-sdk": 6_000,
"@paperclipai/adapter-opencode-local": 5_100,
"@paperclipai/adapter-kimi-local": 5_000,
"@paperclipai/adapter-openclaw-gateway": 4_100,
"@paperclipai/adapter-cursor-local": 4_000,
"@paperclipai/adapter-pi-local": 2_300,
"@paperclipai/adapter-cursor-cloud": 2_300,
"@paperclipai/skills-catalog": 1_600,
"@paperclipai/create-paperclip-plugin": 700,
});
function projectWeight(project, weights) {
const value = weights?.[project];
return typeof value === "number" && Number.isFinite(value) && value > 0
? value
: DEFAULT_WORKSPACE_PROJECT_WEIGHT_MS;
}
export function partitionWorkspaceProjects(
projects,
shardCount,
weights = WORKSPACES_B_PROJECT_DURATIONS_MS,
) {
if (!Number.isInteger(shardCount) || shardCount < 1) {
throw new Error(`shardCount must be a positive integer. Received "${shardCount}".`);
}
const shards = Array.from({ length: shardCount }, (_, index) => ({
index,
projects: [],
totalWeight: 0,
}));
const weighted = projects
.map((project, order) => ({
project,
order,
weight: projectWeight(project, weights),
}))
.sort((a, b) => b.weight - a.weight || a.project.localeCompare(b.project));
for (const item of weighted) {
let target = shards[0];
for (let i = 1; i < shards.length; i += 1) {
const candidate = shards[i];
if (
candidate.totalWeight < target.totalWeight ||
(candidate.totalWeight === target.totalWeight && candidate.projects.length < target.projects.length)
) {
target = candidate;
}
}
target.projects.push(item);
target.totalWeight += item.weight;
}
return shards.map((shard) => ({
index: shard.index,
projects: shard.projects.sort((a, b) => a.order - b.order).map((item) => item.project),
totalWeight: shard.totalWeight,
}));
}
export function selectWorkspaceProjectsShard(
projects,
shardIndex,
shardCount,
weights = WORKSPACES_B_PROJECT_DURATIONS_MS,
) {
if (shardCount === null || shardCount === undefined || shardCount <= 1) {
return [...projects];
}
if (!Number.isInteger(shardIndex) || shardIndex < 0 || shardIndex >= shardCount) {
throw new Error(`shardIndex must be in [0, ${shardCount}). Received "${shardIndex}".`);
}
return partitionWorkspaceProjects(projects, shardCount, weights)[shardIndex].projects;
}
+37 -37
View File
@@ -32,54 +32,54 @@
"durations": {
"tests/e2e/acp-stop-continuation.spec.ts": 67299,
"tests/e2e/action-test-agent-picker.spec.ts": 13115,
"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": 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/applications-crud.spec.ts": 15000,
"tests/e2e/agent-chat-messages.spec.ts": 42000,
"tests/e2e/agent-chat-projects.spec.ts": 155000,
"tests/e2e/agent-chat-sessions.spec.ts": 80000,
"tests/e2e/agent-configuration.spec.ts": 101200,
"tests/e2e/agentmail.spec.ts": 22000,
"tests/e2e/ai-personal-connection-recovery.spec.ts": 14900,
"tests/e2e/announcement-first-session.spec.ts": 11600,
"tests/e2e/announcement-placement.spec.ts": 20400,
"tests/e2e/app-not-connected.spec.ts": 15300,
"tests/e2e/applications-crud.spec.ts": 11400,
"tests/e2e/apps-prosumer-mcp-flow.spec.ts": 13276,
"tests/e2e/archived-company-url.spec.ts": 6145,
"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": 12700,
"tests/e2e/chat-adapters-ui-messaging.spec.ts": 181303,
"tests/e2e/archived-company-url.spec.ts": 6500,
"tests/e2e/artifact-tab-arrival.spec.ts": 11800,
"tests/e2e/artifact-uploads.spec.ts": 34900,
"tests/e2e/board-attachment-receipts.spec.ts": 78000,
"tests/e2e/cases-read-only.spec.ts": 10500,
"tests/e2e/chat-adapters-ui-messaging.spec.ts": 125000,
"tests/e2e/chat-adapters-ui-providers.spec.ts": 181541,
"tests/e2e/chunk-load-recovery.spec.ts": 16330,
"tests/e2e/classic-workspace.spec.ts": 8000,
"tests/e2e/cloud-auth.spec.ts": 33711,
"tests/e2e/classic-workspace.spec.ts": 7600,
"tests/e2e/cloud-auth.spec.ts": 40400,
"tests/e2e/company-context-refresh.spec.ts": 4128,
"tests/e2e/completed-task-paused-assignee.spec.ts": 25016,
"tests/e2e/composer-stop.spec.ts": 55500,
"tests/e2e/conference-room-typing-intro.spec.ts": 30042,
"tests/e2e/connection-intents.spec.ts": 20100,
"tests/e2e/composer-stop.spec.ts": 55400,
"tests/e2e/conference-room-typing-intro.spec.ts": 53600,
"tests/e2e/connection-intents.spec.ts": 20900,
"tests/e2e/connection-reviews.spec.ts": 75000,
"tests/e2e/coordinator-inbox-views.spec.ts": 18241,
"tests/e2e/daytona-connector.spec.ts": 2603,
"tests/e2e/coordinator-inbox-views.spec.ts": 21600,
"tests/e2e/daytona-connector.spec.ts": 4700,
"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/mcp-user-stories.spec.ts": 37417,
"tests/e2e/new-task-picker-touch.spec.ts": 22514,
"tests/e2e/onboarding.spec.ts": 68700,
"tests/e2e/paused-composer.spec.ts": 38240,
"tests/e2e/disconnect-write-recovery.spec.ts": 61000,
"tests/e2e/document-image-gallery.spec.ts": 47800,
"tests/e2e/mcp-user-stories.spec.ts": 45600,
"tests/e2e/new-task-picker-touch.spec.ts": 25700,
"tests/e2e/onboarding.spec.ts": 70300,
"tests/e2e/paused-composer.spec.ts": 60500,
"tests/e2e/plan-task-fixture.spec.ts": 7828,
"tests/e2e/project-repositories.spec.ts": 13403,
"tests/e2e/railway-catalog.spec.ts": 2813,
"tests/e2e/runner-e2e-dashboard.spec.ts": 4985,
"tests/e2e/project-repositories.spec.ts": 16000,
"tests/e2e/railway-catalog.spec.ts": 3000,
"tests/e2e/runner-e2e-dashboard.spec.ts": 4700,
"tests/e2e/runner-task-creation.spec.ts": 32437,
"tests/e2e/sidebar-takeover.spec.ts": 9119,
"tests/e2e/sidebar-takeover.spec.ts": 7700,
"tests/e2e/signoff-policy.spec.ts": 52229,
"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,
"tests/e2e/text-attachment-tabs.spec.ts": 12758,
"tests/e2e/unikraft-connector.spec.ts": 2613
"tests/e2e/task-loading-frame.spec.ts": 37600,
"tests/e2e/task-reload.spec.ts": 21200,
"tests/e2e/text-attachment-tabs.spec.ts": 18200,
"tests/e2e/unikraft-connector.spec.ts": 4000
}
}
+10 -3
View File
@@ -20,7 +20,10 @@ export const IGNORED_SPECS = ["in-feed-native/**", "multi-user.spec.ts", "multi-
// 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-chat-projects.spec.ts",
"agent-chat-sessions.spec.ts",
"agent-configuration.spec.ts",
"ai-personal-connection-recovery.spec.ts",
"cases-read-only.spec.ts",
"classic-workspace.spec.ts",
"composer-stop.spec.ts",
@@ -31,9 +34,13 @@ export const SERIAL_SPECS = [
"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.
// Matches the 4-vCPU CI worker count in tests/e2e/playwright.config.ts for
// shards that contain only parallel-safe specs. Empirical wall-clock speedup
// on 4-vCPU runners with 2 Chromium workers sharing one server + Postgres is
// ~1.5x (measured on run 45245582904); using the empirical factor avoids
// under-allocating shards to parallel specs.
export const DEFAULT_PARALLEL_WORKERS = 2;
export const EFFECTIVE_PARALLEL_SPEEDUP = 1.5;
export function isSerialE2eSpec(file) {
return SERIAL_SPECS.includes(path.posix.basename(file.split(path.sep).join("/")));
@@ -56,7 +63,7 @@ export function partitionE2eShards(
files,
shardCount,
durations = {},
{ parallelWorkers = DEFAULT_PARALLEL_WORKERS } = {},
{ parallelWorkers = EFFECTIVE_PARALLEL_SPEEDUP } = {},
) {
const serialFiles = files.filter(isSerialE2eSpec);
const parallelFiles = files.filter((file) => !isSerialE2eSpec(file));
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env node
import fs from "node:fs/promises";
import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const IGNORED_DIR_NAMES = new Set([
".git",
".paperclip",
".storybook",
"__tests__",
"coverage",
"dist",
"migrations",
"node_modules",
"provider-assets",
"public",
"src",
"stories",
"target",
"test",
"tests",
]);
function readJsonFile(filePath) {
return JSON.parse(readFileSync(filePath, "utf8"));
}
export function discoverWorkspacePackagePaths(rootDir = repoRoot) {
const packagePaths = new Map();
function visit(dirPath) {
if (!existsSync(dirPath)) return;
const packageJsonPath = path.join(dirPath, "package.json");
if (existsSync(packageJsonPath)) {
const packageJson = readJsonFile(packageJsonPath);
if (typeof packageJson.name === "string" && packageJson.name.length > 0) {
packagePaths.set(packageJson.name, dirPath);
}
}
for (const entry of readdirSync(dirPath, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
if (IGNORED_DIR_NAMES.has(entry.name)) continue;
visit(path.join(dirPath, entry.name));
}
}
for (const root of ["packages", "server", "ui", "cli"]) {
visit(path.join(rootDir, root));
}
return packagePaths;
}
export function findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir = repoRoot) {
const nodeModulesDir = path.join(rootDir, workspaceDir, "node_modules");
if (!existsSync(nodeModulesDir)) {
return [];
}
const packageJson = readJsonFile(path.join(rootDir, workspaceDir, "package.json"));
const dependencies = {
...(packageJson.dependencies ?? undefined),
...(packageJson.devDependencies ?? undefined),
};
const mismatches = [];
for (const [packageName, version] of Object.entries(dependencies)) {
if (typeof version !== "string" || !version.startsWith("workspace:")) continue;
const expectedPath = workspacePackagePaths.get(packageName);
if (!expectedPath) continue;
const linkPath = path.join(rootDir, workspaceDir, "node_modules", ...packageName.split("/"));
const canonicalExpectedPath = existsSync(expectedPath)
? path.resolve(realpathSync(expectedPath))
: path.resolve(expectedPath);
const actualPath = existsSync(linkPath) ? path.resolve(realpathSync(linkPath)) : null;
if (actualPath === canonicalExpectedPath) continue;
mismatches.push({
workspaceDir,
packageName,
expectedPath: canonicalExpectedPath,
actualPath,
});
}
return mismatches;
}
export async function ensureAllWorkspaceLinksCurrent(rootDir = repoRoot) {
const workspacePackagePaths = discoverWorkspacePackagePaths(rootDir);
const workspaceDirs = Array.from(
new Set(
Array.from(workspacePackagePaths.values())
.map((packagePath) => path.relative(rootDir, packagePath))
.filter((workspaceDir) => workspaceDir.length > 0),
),
).sort();
for (const workspaceDir of workspaceDirs) {
const mismatches = findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir);
if (mismatches.length === 0) continue;
console.log(`[paperclip] detected stale workspace package links for ${workspaceDir}; relinking dependencies...`);
for (const mismatch of mismatches) {
console.log(
`[paperclip] ${mismatch.packageName}: ${mismatch.actualPath ?? "missing"} -> ${mismatch.expectedPath}`,
);
}
for (const mismatch of mismatches) {
const linkPath = path.join(rootDir, mismatch.workspaceDir, "node_modules", ...mismatch.packageName.split("/"));
await fs.mkdir(path.dirname(linkPath), { recursive: true });
await fs.rm(linkPath, { recursive: true, force: true });
await fs.symlink(mismatch.expectedPath, linkPath);
}
const remainingMismatches = findWorkspaceLinkMismatches(workspaceDir, workspacePackagePaths, rootDir);
if (remainingMismatches.length > 0) {
throw new Error(
`Workspace relink did not repair all ${workspaceDir} package links: ${remainingMismatches.map((item) => item.packageName).join(", ")}`,
);
}
}
}
const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : null;
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
await ensureAllWorkspaceLinksCurrent();
}
+2 -115
View File
@@ -1,117 +1,4 @@
#!/usr/bin/env -S node --import tsx
import fs from "node:fs/promises";
import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import path from "node:path";
import { repoRoot } from "./dev-service-profile.ts";
import { ensureAllWorkspaceLinksCurrent } from "./ensure-workspace-package-links.mjs";
type WorkspaceLinkMismatch = {
workspaceDir: string;
packageName: string;
expectedPath: string;
actualPath: string | null;
};
function readJsonFile(filePath: string): Record<string, unknown> {
return JSON.parse(readFileSync(filePath, "utf8")) as Record<string, unknown>;
}
function discoverWorkspacePackagePaths(rootDir: string): Map<string, string> {
const packagePaths = new Map<string, string>();
const ignoredDirNames = new Set([".git", ".paperclip", "dist", "node_modules"]);
function visit(dirPath: string) {
const packageJsonPath = path.join(dirPath, "package.json");
if (existsSync(packageJsonPath)) {
const packageJson = readJsonFile(packageJsonPath);
if (typeof packageJson.name === "string" && packageJson.name.length > 0) {
packagePaths.set(packageJson.name, dirPath);
}
}
for (const entry of readdirSync(dirPath, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
if (ignoredDirNames.has(entry.name)) continue;
visit(path.join(dirPath, entry.name));
}
}
visit(path.join(rootDir, "packages"));
visit(path.join(rootDir, "server"));
visit(path.join(rootDir, "ui"));
visit(path.join(rootDir, "cli"));
return packagePaths;
}
const workspacePackagePaths = discoverWorkspacePackagePaths(repoRoot);
const workspaceDirs = Array.from(
new Set(
Array.from(workspacePackagePaths.values())
.map((packagePath) => path.relative(repoRoot, packagePath))
.filter((workspaceDir) => workspaceDir.length > 0),
),
).sort();
function findWorkspaceLinkMismatches(workspaceDir: string): WorkspaceLinkMismatch[] {
const nodeModulesDir = path.join(repoRoot, workspaceDir, "node_modules");
if (!existsSync(nodeModulesDir)) {
return [];
}
const packageJson = readJsonFile(path.join(repoRoot, workspaceDir, "package.json"));
const dependencies = {
...(packageJson.dependencies as Record<string, unknown> | undefined),
...(packageJson.devDependencies as Record<string, unknown> | undefined),
};
const mismatches: WorkspaceLinkMismatch[] = [];
for (const [packageName, version] of Object.entries(dependencies)) {
if (typeof version !== "string" || !version.startsWith("workspace:")) continue;
const expectedPath = workspacePackagePaths.get(packageName);
if (!expectedPath) continue;
const linkPath = path.join(repoRoot, workspaceDir, "node_modules", ...packageName.split("/"));
const actualPath = existsSync(linkPath) ? path.resolve(realpathSync(linkPath)) : null;
if (actualPath === path.resolve(expectedPath)) continue;
mismatches.push({
workspaceDir,
packageName,
expectedPath: path.resolve(expectedPath),
actualPath,
});
}
return mismatches;
}
async function ensureWorkspaceLinksCurrent(workspaceDir: string) {
const mismatches = findWorkspaceLinkMismatches(workspaceDir);
if (mismatches.length === 0) return;
console.log(`[paperclip] detected stale workspace package links for ${workspaceDir}; relinking dependencies...`);
for (const mismatch of mismatches) {
console.log(
`[paperclip] ${mismatch.packageName}: ${mismatch.actualPath ?? "missing"} -> ${mismatch.expectedPath}`,
);
}
for (const mismatch of mismatches) {
const linkPath = path.join(repoRoot, mismatch.workspaceDir, "node_modules", ...mismatch.packageName.split("/"));
await fs.mkdir(path.dirname(linkPath), { recursive: true });
await fs.rm(linkPath, { recursive: true, force: true });
await fs.symlink(mismatch.expectedPath, linkPath);
}
const remainingMismatches = findWorkspaceLinkMismatches(workspaceDir);
if (remainingMismatches.length === 0) return;
throw new Error(
`Workspace relink did not repair all ${workspaceDir} package links: ${remainingMismatches.map((item) => item.packageName).join(", ")}`,
);
}
for (const workspaceDir of workspaceDirs) {
await ensureWorkspaceLinksCurrent(workspaceDir);
}
await ensureAllWorkspaceLinksCurrent();
+31 -20
View File
@@ -14,6 +14,8 @@ import {
resolveNightlyOnlySuitesPath,
} from "./ci/nightly-only-suites.mjs";
import { runUnderSharedPostgres, shouldWrapWithSharedPostgres } from "./ci/vitest-shared-postgres.mjs";
import { resolveServerParallelWorkers, resolveWorkspaceParallelWorkers } from "./ci/vitest-workers.mjs";
import { selectWorkspaceProjectsShard } from "./ci/workspaces-b-shard.mjs";
import { assertSelectedTests, partitionTestLines } from "./test-line-shard.mjs";
import { loadSelection, selectedShard } from "./ci/test-selection-manifest.mjs";
@@ -148,12 +150,12 @@ 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;
function resolveWorkers(lane) {
try {
return resolveServerParallelWorkers(lane);
} catch (error) {
fail(error.message);
}
return parsePositiveInteger(raw, "PAPERCLIP_VITEST_MAX_WORKERS");
}
// Release verification selects this explicit group and runs the omitted suites
@@ -387,12 +389,12 @@ function parseCliOptions(argv) {
const shardAllowed =
mode === serializedModeName ||
(mode === generalModeName &&
([...generalServerGroups, generalChatGroupName, generalWorkspacesAGroupName].includes(group)
([...generalServerGroups, generalChatGroupName, generalWorkspacesAGroupName, generalWorkspacesBGroupName].includes(group)
|| Boolean(process.env.PAPERCLIP_CI_TEST_SELECTION)
&& [generalWorkspacesBGroupName, generalWorkspacesCGroupName].includes(group)));
&& generalWorkspacesCGroupName === group));
if (!shardAllowed && shardIndex !== null) {
fail(
"--shard-index/--shard-count require serialized mode, a shardable general server/chat/workspaces-a group, or a selected workspace group.",
"--shard-index/--shard-count require serialized mode, a shardable general server/chat/workspaces-a/workspaces-b group, or a selected workspace group.",
);
}
@@ -550,7 +552,7 @@ async function runGeneralSuites(routeTests, chatShards) {
}
}
async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null, excludedFiles = []) {
async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null, excludedFiles = [], extraArgs = []) {
// 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
@@ -563,7 +565,7 @@ async function runProjectGroup(projects, groupName, shardIndex = null, shardCoun
const label = projects.length === 1
? `${groupName} project ${projects[0]}${shardSuffix}`
: `${groupName} (${projects.length} projects)${shardSuffix}`;
await runVitest([...projectArgs, ...excludeArgs, ...shardArgs], label);
await runVitest([...projectArgs, ...excludeArgs, ...shardArgs, ...extraArgs], label);
}
function chatShardWorkers(index, count) {
@@ -637,9 +639,9 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo
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.
// but overlap long real lease windows across isolated fork workers.
...(hasSharedTestDatabase ? serializedServerVitestArgs
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`]),
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`]),
...suites],
"native runner vertical-slice suite",
);
@@ -662,7 +664,7 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo
return;
}
const workers = resolveServerParallelWorkers(4);
const workers = resolveWorkers("general");
await runVitest(
[
"--project",
@@ -708,13 +710,22 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo
// 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 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);
// splits across runners without a duration manifest. Pass --maxWorkers at
// the top level so both projects share one worker pool (Vitest 5 rejects
// per-project maxWorkers mismatches within the same sequence.groupOrder).
await runProjectGroup(generalWorkspacesAProjects, groupName, shardIndex, shardCount, [], [
`--maxWorkers=${resolveWorkspaceParallelWorkers()}`,
]);
return;
}
if (groupName === generalWorkspacesBGroupName) {
await runProjectGroup(generalWorkspacesBProjects, groupName);
const projects = selectWorkspaceProjectsShard(generalWorkspacesBProjects, shardIndex, shardCount);
if (projects.length === 0) {
console.log(`\n[test:run] ${groupName} shard ${shardIndex + 1}/${shardCount}: 0 projects; skipping`);
return;
}
await runProjectGroup(projects, groupName);
return;
}
@@ -758,7 +769,7 @@ async function runSerializedSuites(suites, shardIndex, shardCount) {
const serialOnlyTests = shardTests.filter((test) => strictlySerialServerTests.has(test.repoPath));
if (parallelTests.length > 0) {
const workers = resolveServerParallelWorkers(3);
const workers = resolveWorkers("serialized");
await runVitest(
[
"--project",
@@ -912,7 +923,7 @@ if (options.dryRun) {
options.group === generalWorkspacesAGroupName
? generalWorkspacesAProjects
: options.group === generalWorkspacesBGroupName
? generalWorkspacesBProjects
? selectWorkspaceProjectsShard(generalWorkspacesBProjects, options.shardIndex, options.shardCount)
: options.group === generalWorkspacesCGroupName
? generalWorkspacesCProjects
: null,
@@ -949,8 +960,8 @@ try {
: hasSharedTestDatabase
? ["--pool=forks", "--isolate", ...serializedServerVitestArgs]
: options.mode === serializedModeName
? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(3)}`]
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`];
? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("serialized")}`]
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`];
await runVitest(["--project", project, ...serverArgs, ...files],
`selected ${project}: ${files.length} files`, null, true);
}
+16 -4
View File
@@ -17,7 +17,7 @@
import { spawn, spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { availableParallelism } from "node:os";
import { availableParallelism, totalmem } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { linkExcludedPlugins } from "./link-plugin-dev-sdk.mjs";
@@ -27,6 +27,14 @@ import { PROJECTS } from "./typecheck-test-projects.mjs";
export const DEFAULT_CONCURRENCY = 3;
export const PROVIDER_WORKSPACE = "scripts/typecheck-sandbox-providers";
export function defaultConcurrency({ cpus = availableParallelism(), totalMemoryBytes = totalmem() } = {}) {
const memGiB = totalMemoryBytes / 1024 ** 3;
if (cpus <= 2 || memGiB < 12) return 1;
if (cpus <= 4) return 2;
if (memGiB < 24) return Math.min(3, cpus);
return Math.min(4, cpus);
}
export const SANDBOX_PROVIDERS = [
"packages/plugins/sandbox-providers/boxd",
"packages/plugins/sandbox-providers/cloudflare",
@@ -124,7 +132,11 @@ export function selectTestPrograms(changedFiles, programs = PROGRAMS) {
"scripts/typecheck-sandbox-providers/",
"scripts/link-plugin-dev-sdk.mjs",
]);
const runnerChanged = hasPrefix(changedFiles, ["packages/paperclip-runner/", "packages/paperclip-eval-kernel/"]);
const runnerChanged = hasPrefix(changedFiles, [
"packages/paperclip-runner/",
"packages/paperclip-eval-kernel/",
"packages/adapter-utils/",
]);
const cloudflareChanged = hasPrefix(changedFiles, ["packages/plugins/sandbox-providers/cloudflare/"]);
const selected = programs.filter((program) => {
@@ -342,7 +354,7 @@ export async function checkCoverageAsync({
programs = PROGRAMS,
includeProviders = true,
onlyFiles = null,
concurrency = Math.min(4, availableParallelism()),
concurrency = Math.max(1, Math.min(6, availableParallelism())),
workspaceConfigs = listWorkspaceConfigs,
trackedFiles = listTrackedFiles,
listFilesAsync = listProgramFilesAsync,
@@ -606,7 +618,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
let noCoverage = false;
let forceCoverage = false;
let coverageOnly = false;
let concurrency = Math.max(1, Math.min(DEFAULT_CONCURRENCY, availableParallelism()));
let concurrency = defaultConcurrency();
let checkers;
const checkFiles = [];
const programs = [];
+13
View File
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
import {
checkCoverage,
checkCoverageAsync,
defaultConcurrency,
findUncheckedTests,
LOCKED_PROVIDERS,
PROGRAMS,
@@ -306,6 +307,10 @@ test("selectTestPrograms skips sandbox providers and examples unless their input
const tsconfigEdit = selectTestPrograms(["ui/tsconfig.json"]);
assert.equal(tsconfigEdit.checkCoverage, true);
assert.equal(tsconfigEdit.changedTestFiles, null);
const adapterUtilsEdit = selectTestPrograms(["packages/adapter-utils/src/github-launcher.ts"]);
assert.ok(adapterUtilsEdit.programs.some((program) => program.startsWith("packages/paperclip-runner/")));
assert.equal(adapterUtilsEdit.includeRunnerEval, true);
});
test("prepareTestPrograms can skip sandbox provider installs, runner eval prep, and plugin SDK", () => {
@@ -411,3 +416,11 @@ test("checkCoverageAsync checks targeted files with early exit and skips uninsta
});
assert.deepEqual(uncovered, ["ui/src/Orphan.test.tsx"]);
});
test("defaultConcurrency scales safely with CPU count and memory", () => {
const GiB = 1024 ** 3;
assert.equal(defaultConcurrency({ cpus: 2, totalMemoryBytes: 8 * GiB }), 1);
assert.equal(defaultConcurrency({ cpus: 4, totalMemoryBytes: 16 * GiB }), 2);
assert.equal(defaultConcurrency({ cpus: 8, totalMemoryBytes: 16 * GiB }), 3);
assert.equal(defaultConcurrency({ cpus: 8, totalMemoryBytes: 32 * GiB }), 4);
});