Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(test): 本地提交默认只跑和改动相关的单测

Lizia94d01957915
diff --git a/AGENTS.md b/AGENTS.md
index 982ebf400c..08d3a45b5e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -155,11 +155,13 @@
`check:dco` 的失败结果不构成缺签证据,不要据此报告 DCO 问题。判定 DCO 是否通过,
一律以 PR 上的 DCO App check 与真实提交范围(`origin/main..PR head`)的结果为准。
- **提交前测试门禁(硬性要求)**:无论是提 PR 还是直接 commit,提交前都必须在本地
- 跑完仓库根 `pnpm test:unit`(全部单元测试),并对本次改动涉及的每个 package 跑
+ 跑完仓库根 `pnpm test:unit:related`(只跑这次改动能影响到的单测;改到测试调度、
+ 依赖清单、workspace 配置、Vitest 配置或单测 CI 时会自动退回全量 `pnpm test:unit`),
+ 并对本次改动涉及的每个 package 跑
`pnpm --filter <包名> run --if-present typecheck`(`<包名>` 用该 package 在
`package.json` 里的 `name`,如 `desktop`、`@cindy/maker-core`;没有 `typecheck`
script 的 package 该步自动跳过),全部通过后才允许提交;任何一项失败都不得提交,
- 必须先修复。细则与唯一例外(防丢数据的兜底保存)见
+ 必须先修复。GitHub CI 仍跑完整 `pnpm test:unit`。细则与唯一例外(防丢数据的兜底保存)见
`docs/dev-rules/development-workflow.md`。
- 在上述门禁之上按风险追加验证:跨模块、高风险或基础设施改动追加更广泛验证(如
`pnpm test:all`),最终以 CI 门禁为准。不得通过跳过、删除或弱化测试制造通过。
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index e8c4b7b286..a70c55eb72 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -119,8 +119,8 @@ localStorage 按 **origin + userData 目录** 分家——dev 的 renderer 从
## 分层验证
本节指导**开发过程中的增量验证**;提交(commit/PR)前的强制门禁以
-`development-workflow.md` 的「提交前测试门禁」为准(仓库根 `pnpm test:unit` 与相关
-package 的 typecheck 全部通过)。开发过程中根据实际改动选择最小但充分的检查:
+`development-workflow.md` 的「提交前测试门禁」为准(仓库根 `pnpm test:unit:related` 与相关
+package 的 typecheck 全部通过;CI 仍跑完整 `pnpm test:unit`)。开发过程中根据实际改动选择最小但充分的检查:
```bash
pnpm --filter desktop typecheck
@@ -128,6 +128,7 @@ pnpm --filter desktop lint
pnpm --filter desktop exec vitest run <测试文件路径>
pnpm --filter desktop test
pnpm build
+pnpm test:unit:related
pnpm test:unit
```
diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.md
index 640dfc93ef..06a51c0c59 100644
--- a/docs/dev-rules/desktop-unit-test-performance.md
+++ b/docs/dev-rules/desktop-unit-test-performance.md
@@ -70,8 +70,8 @@ Desktop 测试按成本拆成默认层与显式层:
派生的本机回环端口锁。
远端 `client-ci` 以独立并行 job 在每个 PR、`main` push 和手动触发时运行完整
-`git-integration` 层;本地提交前门禁仍只要求默认 `test:unit`,修改真实 Git 行为时可按需
-显式补跑完整层。
+`git-integration` 层;本地提交前门禁默认是 `test:unit:related`,修改真实 Git 行为时可按需
+显式补跑完整层。CI 仍跑完整 `test:unit`。
因此同一仓库的多个 worktree 可以并行完成默认单测;只有显式运行完整 Git 集成层时才排队:
diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.md
index f1601b4d06..531e6b269f 100644
--- a/docs/dev-rules/development-workflow.md
+++ b/docs/dev-rules/development-workflow.md
@@ -58,19 +58,28 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径
- 漏签不要重新造一份提交:用 `git commit --amend -s --no-edit` 或
`git rebase --signoff <base>` 补签后 `git push --force-with-lease`。
- **提交前测试门禁(硬性要求)**:无论是提 PR 还是直接 commit,提交前都必须在本地跑完
- 仓库根 `pnpm test:unit`(全部单元测试),并对本次改动涉及的每个 package 跑
- `pnpm --filter <包名> run --if-present typecheck`(`<包名>` 用该 package 在
+ 仓库根 `pnpm test:unit:related`(只跑这次改动能影响到的单测),并对本次改动涉及的每个
+ package 跑 `pnpm --filter <包名> run --if-present typecheck`(`<包名>` 用该 package 在
`package.json` 里的 `name`,如 `desktop`、`@cindy/maker-core`;没有 `typecheck`
script 的 package 该步自动跳过),全部通过后才允许提交;任何一项失败都不得提交,
必须先修复。worktree 会话内的 commit 同样适用。唯一例外是**防丢数据的兜底保存**:
宿主删除/归档会话时自动存的内容快照(见第 1 节),以及会话必须收尾、测试却来不及
修好时的收尾 commit——后者 commit message 必须标注 `WIP`,且在门禁通过前不得
push、不得提 PR。
- - **完整单测的外层超时**:`pnpm test:unit` 是全仓完整门禁,正常执行可能超过数分钟。
- 调用它的 agent/自动化工具不得使用 120 秒或更短的绝对超时;未知当前耗时时,外层
- 兜底超时至少设为 15 分钟。工具支持后台运行或 yielded process handle 时优先使用该
- 模式并短轮询进度,不要因为调用端停止等待就误判失败、杀掉仍在正常运行的测试或重复
- 启动一轮。Vitest 的单测试例超时仍由各 package 配置控制,不受这条外层约束影响。
+ - **相关单测怎么选**:`test:unit:related` 看相对 `main` 的已提交、已暂存、未暂存和未跟踪
+ 文件。同一包里用 Vitest `related` 只跑会引用这些文件的测试;改了会被别的包依赖的公共
+ 包源码时,依赖方跑该包自己的整包单测。只改文档等非代码文件则跳过 workspace 单测。
+ 改到测试调度(`scripts/test-workspaces*`、`scripts/test-related.mjs`、
+ `scripts/test-gate-lock.mjs`)、`package.json`、`pnpm-lock.yaml`、
+ `pnpm-workspace.yaml`、各包 `vitest.config.*`、单测 CI 工作流,或算不出 git 基准时,
+ 打印原因并退回全量 `pnpm test:unit`。批量改产品术语仍须全量,因为有测试直接锁中文文案。
+ GitHub CI 不受此影响,仍跑完整 `pnpm test:unit`。
+ - **完整单测的外层超时**:默认相关门禁通常比全仓短,但一旦退回全量,`pnpm test:unit`
+ 正常执行仍可能超过数分钟。调用全量门禁的 agent/自动化工具不得使用 120 秒或更短的
+ 绝对超时;未知当前耗时时,外层兜底超时至少设为 15 分钟。工具支持后台运行或 yielded
+ process handle 时优先使用该模式并短轮询进度,不要因为调用端停止等待就误判失败、杀掉
+ 仍在正常运行的测试或重复启动一轮。Vitest 的单测试例超时仍由各 package 配置控制,不受
+ 这条外层约束影响。
- **workspace 有界并行**:`test-workspaces.mjs` 默认最多并行
`min(4, os.availableParallelism())` 个普通 workspace;每个普通 Vitest workspace 只使用
1 个 worker。Mobile 使用完整的 4-worker 配额;Desktop 使用基准验证过的单池最多
diff --git a/package.json b/package.json
index 32b0672a8e..9b6943c624 100644
--- a/package.json
+++ b/package.json
@@ -117,8 +117,9 @@
"licenses:generate": "node scripts/generate-third-party-notices.mjs",
"lint": "pnpm -r lint",
"format": "pnpm -r format",
- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs",
+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs",
"test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit",
+ "test:unit:related": "node scripts/test-workspaces.mjs --tier unit --related",
"test:all": "pnpm test:runner && node scripts/test-workspaces.mjs --all",
"test:git-integration": "pnpm test:runner && node scripts/test-workspaces.mjs --tier git-integration",
"test:db": "pnpm test:runner && node scripts/test-workspaces.mjs --tier db",
diff --git a/scripts/__tests__/test-related.test.mjs b/scripts/__tests__/test-related.test.mjs
new file mode 100644
index 0000000000..326fb56dc4
--- /dev/null
+++ b/scripts/__tests__/test-related.test.mjs
@@ -0,0 +1,258 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ buildDependentMap,
+ collectChangedFiles,
+ collectTransitiveDependents,
+ isSkippableFile,
+ isTestFile,
+ isWideFile,
+ planRelatedUnitTests,
+ shouldRunTestRunner,
+ workspaceForFile,
+} from "../test-related.mjs";
+
+const workspaces = [
+ {
+ name: "desktop",
+ cwd: "apps/desktop",
+ status: "required",
+ tiers: { unit: { status: "required" } },
+ },
+ {
+ name: "@cindy/maker-core",
+ cwd: "packages/maker-core",
+ status: "required",
+ tiers: { unit: { status: "required" } },
+ },
+ {
+ name: "@cindy/maker-shared",
+ cwd: "packages/maker-shared",
+ status: "required",
+ tiers: { unit: { status: "required" } },
+ },
+ {
+ name: "project-context",
+ cwd: "packages/project-context",
+ status: "notApplicable",
+ reason: "No tests",
+ tiers: {},
+ },
+];
+
+const packageJsonByCwd = {
+ "apps/desktop": {
+ name: "desktop",
+ dependencies: {
+ "@cindy/maker-core": "workspace:*",
+ },
+ },
+ "packages/maker-core": {
+ name: "@cindy/maker-core",
+ dependencies: {
+ "@cindy/maker-shared": "workspace:*",
+ },
+ },
+ "packages/maker-shared": {
+ name: "@cindy/maker-shared",
+ dependencies: {},
+ },
+ "packages/project-context": {
+ name: "project-context",
+ dependencies: {},
+ },
+};
+
+test("isWideFile covers test scheduler, lockfile, and CI workflows", () => {
+ assert.equal(isWideFile("package.json"), true);
+ assert.equal(isWideFile("apps/desktop/package.json"), true);
+ assert.equal(isWideFile("pnpm-lock.yaml"), true);
+ assert.equal(isWideFile("scripts/test-related.mjs"), true);
+ assert.equal(isWideFile("scripts/test-workspaces.config.mjs"), true);
+ assert.equal(isWideFile(".github/workflows/ci.yml"), true);
+ assert.equal(isWideFile("apps/desktop/src/main/foo.ts"), false);
+});
+
+test("isSkippableFile and isTestFile classify docs versus tests", () => {
+ assert.equal(isSkippableFile("docs/dev-rules/development-workflow.md"), true);
+ assert.equal(isSkippableFile("LICENSE"), true);
+ assert.equal(isSkippableFile("apps/desktop/src/main/foo.ts"), false);
+ assert.equal(isTestFile("apps/desktop/src/main/foo.test.ts"), true);
+ assert.equal(isTestFile("apps/desktop/src/main/foo.ts"), false);
+});
+
+test("shouldRunTestRunner only when something outside apps/packages changed", () => {
+ assert.equal(
+ shouldRunTestRunner(["apps/desktop/src/main/foo.ts"]),
+ false,
+ );
+ assert.equal(
+ shouldRunTestRunner(["docs/dev-rules/desktop-development.md"]),
+ true,
+ );
+ assert.equal(shouldRunTestRunner(["scripts/check-i18n.mjs"]), true);
+});
+
+test("workspaceForFile picks the longest matching workspace prefix", () => {
+ assert.equal(
+ workspaceForFile("apps/desktop/src/main/foo.ts", [
+ "apps",
+ "apps/desktop",
+ ]),
+ "apps/desktop",
+ );
+ assert.equal(
+ workspaceForFile("README.md", ["apps/desktop", "packages/maker-core"]),
+ undefined,
+ );
+});
+
+test("collectChangedFiles unions committed, staged, unstaged, and untracked files", () => {
+ const calls = [];
+ const runGit = (args) => {
+ calls.push(args);
+ const key = args.join(" ");
+ if (key === "rev-parse --verify origin/main") return "abc\n";
+ if (key === "merge-base HEAD origin/main") return "base123\n";
+ if (key === "diff --name-only base123 HEAD")
+ return "apps/desktop/src/a.ts\n";
+ if (key === "diff --name-only --cached")
+ return "apps/desktop/src/b.ts\n";
+ if (key === "diff --name-only") return "apps/desktop/src/c.ts\n";
+ if (key === "ls-files --others --exclude-standard")
+ return "apps/desktop/src/d.ts\n";
+ throw new Error(`unexpected git ${key}`);
+ };
+ assert.deepEqual(collectChangedFiles(runGit), {
+ files: [
+ "apps/desktop/src/a.ts",
+ "apps/desktop/src/b.ts",
+ "apps/desktop/src/c.ts",
+ "apps/desktop/src/d.ts",
+ ],
+ base: "base123",
+ baseRef: "origin/main",
+ });
+ assert.deepEqual(calls[0], ["rev-parse", "--verify", "origin/main"]);
+});
+
+test("collectChangedFiles falls back when git base cannot be resolved", () => {
+ const runGit = () => {
+ throw new Error("not a git repo");
+ };
+ assert.deepEqual(collectChangedFiles(runGit), {
+ files: [],
+ base: null,
+ baseRef: null,
+ error: "cannot resolve git base against main",
+ });
+});
+
+test("planRelatedUnitTests runs only related tests for a leaf workspace file", () => {
+ const plan = planRelatedUnitTests({
+ changedFiles: ["apps/desktop/src/main/foo.ts"],
+ workspaces,
+ packageJsonByCwd,
+ });
+ assert.equal(plan.mode, "related");
+ assert.equal(plan.runTestRunner, false);
+ assert.deepEqual(plan.runs, [
+ {
+ cwd: "apps/desktop",
+ name: "desktop",
+ relatedFiles: ["apps/desktop/src/main/foo.ts"],
+ },
+ ]);
+});
+
+test("planRelatedUnitTests runs dependents fully when a shared package source changes", () => {
+ const plan = planRelatedUnitTests({
+ changedFiles: ["packages/maker-shared/src/index.ts"],
+ workspaces,
+ packageJsonByCwd,
+ });
+ assert.equal(plan.mode, "related");
+ assert.deepEqual(
+ plan.runs.map((run) => [run.cwd, run.relatedFiles]),
+ [
+ ["apps/desktop", null],
+ ["packages/maker-core", null],
+ ["packages/maker-shared", ["packages/maker-shared/src/index.ts"]],
+ ],
+ );
+});
+
+test("planRelatedUnitTests does not fan out dependents for a test-only change", () => {
+ const plan = planRelatedUnitTests({
+ changedFiles: ["packages/maker-core/src/foo.test.ts"],
+ workspaces,
+ packageJsonByCwd,
+ });
+ assert.deepEqual(plan.runs, [
+ {
+ cwd: "packages/maker-core",
+ name: "@cindy/maker-core",
+ relatedFiles: ["packages/maker-core/src/foo.test.ts"],
+ },
+ ]);
+});
+
+test("planRelatedUnitTests falls back to the full suite for wide files", () => {
+ const plan = planRelatedUnitTests({
+ changedFiles: ["package.json", "apps/desktop/src/main/foo.ts"],
+ workspaces,
+ packageJsonByCwd,
+ });
+ assert.equal(plan.mode, "full");
+ assert.match(plan.reason, /wide files changed: package\.json/);
+ assert.equal(plan.runTestRunner, true);
+ assert.deepEqual(plan.runs, []);
+});
+
+test("planRelatedUnitTests skips markdown-only changes", () => {
+ const plan = planRelatedUnitTests({
+ changedFiles: ["README.md", "docs/dev-rules/development-workflow.md"],
+ workspaces,
+ packageJsonByCwd,
+ });
+ assert.equal(plan.mode, "related");
+ assert.equal(plan.runTestRunner, true);
+ assert.deepEqual(plan.runs, []);
+});
+
+test("planRelatedUnitTests skips when there are no changes", () => {
+ const plan = planRelatedUnitTests({
+ changedFiles: [],
+ workspaces,
+ packageJsonByCwd,
+ });
+ assert.deepEqual(plan, {
+ mode: "skip",
+ reason: "no changes vs main",
+ runTestRunner: false,
+ runs: [],
+ });
+});
+
+test("planRelatedUnitTests drops deleted files from related args", () => {
+ const plan = planRelatedUnitTests({
+ changedFiles: ["apps/desktop/src/main/gone.ts"],
+ workspaces,
+ packageJsonByCwd,
+ fileExists: () => false,
+ });
+ assert.equal(plan.mode, "skip");
+ assert.deepEqual(plan.runs, []);
+});
+
+test("buildDependentMap and collectTransitiveDependents follow workspace:* edges", () => {
+ const dependents = buildDependentMap(workspaces, packageJsonByCwd);
+ assert.deepEqual(
+ [...collectTransitiveDependents(["packages/maker-shared"], dependents)].sort(),
+ ["apps/desktop", "packages/maker-core"],
+ );
+ assert.deepEqual(
+ [...collectTransitiveDependents(["apps/desktop"], dependents)],
+ [],
+ );
+});
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index c409fee5e7..679a602068 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -85,6 +85,10 @@ test("root unit and all scripts run runner self-tests before workspace sweep", (
scripts["test:unit"],
/^pnpm test:runner && node scripts\/test-workspaces\.mjs --tier unit$/,
);
+ assert.equal(
+ scripts["test:unit:related"],
+ "node scripts/test-workspaces.mjs --tier unit --related",
+ );
assert.match(
scripts["test:all"],
/^pnpm test:runner && node scripts\/test-workspaces\.mjs --all$/,
@@ -785,6 +789,7 @@ test("parseCliOptions rejects --tier without a value", () => {
excludeWorkspaces: [],
workspaceConcurrency: undefined,
noLock: false,
+ related: false,
});
});
@@ -807,6 +812,7 @@ test("parseCliOptions supports workspace include and exclude selectors", () => {
excludeWorkspaces: ["packages/orca-workflow"],
workspaceConcurrency: undefined,
noLock: false,
+ related: false,
},
);
assert.deepEqual(parseWorkspaceSelectorValue(" desktop, apps/server "), [
@@ -844,6 +850,11 @@ test("workspace concurrency defaults to a bounded CPU count and accepts both CLI
/requires a positive integer/,
);
assert.equal(parseCliOptions(["--no-lock"]).noLock, true);
+ assert.equal(parseCliOptions(["--related"]).related, true);
+ assert.throws(
+ () => parseCliOptions(["--related", "--all"]),
+ /--related cannot be combined with --all/,
+ );
});
test("unit CI shard arguments cover valid halves and reject malformed input", () => {
@@ -1867,6 +1878,32 @@ test("buildPnpmArgs rejects selected files outside the workspace", () => {
);
});
+test("buildPnpmArgs switches vitest to related mode when related files are provided", () => {
+ const args = buildPnpmArgs(
+ "F:/repo",
+ { cwd: "apps/desktop" },
+ {
+ type: "packageBin",
+ bin: "vitest",
+ args: ["run", "--pool=threads", "--maxWorkers=1"],
+ },
+ { exclude: ["**/*.bench.ts"] },
+ ["apps/desktop/src/main/foo.test.ts"],
+ ["apps/desktop/src/main/foo.ts"],
+ );
+ assert.equal(args[3], "vitest");
+ assert.deepEqual(args.slice(4, 9), [
+ "related",
+ "--run",
+ "--pool=threads",
+ "--maxWorkers=1",
+ "--passWithNoTests",
+ ]);
+ assert.equal(args.includes("src/main/foo.ts"), true);
+ assert.equal(args.includes("src/main/foo.test.ts"), false);
+ assert.deepEqual(args.slice(-2), ["--exclude", "**/*.bench.ts"]);
+});
+
test("buildPnpmArgs only loosens Vitest sharding for undersized workspaces", () => {
const root = "F:/repo";
const workspace = { cwd: "packages/example" };
diff --git a/scripts/help.mjs b/scripts/help.mjs
index 56536690f2..586b6e39ca 100644
--- a/scripts/help.mjs
+++ b/scripts/help.mjs
@@ -69,6 +69,7 @@ export function printHelp(log = console.log) {
log('\n 开发检查:');
log(' pnpm lint');
log(' pnpm test:runner');
+ log(' pnpm test:unit:related');
log(' pnpm test:unit');
log(' # 排查并发相关问题时,可把 workspace runner 临时退回串行');
log(' pnpm test:unit -- --workspace-concurrency=1');
diff --git a/scripts/test-related.mjs b/scripts/test-related.mjs
new file mode 100644
index 0000000000..5e19e792a5
--- /dev/null
+++ b/scripts/test-related.mjs
@@ -0,0 +1,384 @@
+import fs from "node:fs";
+import path from "node:path";
+
+const WIDE_ROOT_FILES = new Set([
+ "package.json",
+ "pnpm-lock.yaml",
+ "pnpm-workspace.yaml",
+]);
+const SKIP_EXTENSIONS = new Set([
+ ".md",
+ ".markdown",
+ ".txt",
+ ".rst",
+ ".png",
+ ".jpg",
+ ".jpeg",
+ ".gif",
+ ".webp",
+ ".svg",
+ ".ico",
+ ".bmp",
+ ".mp4",
+ ".webm",
+ ".mov",
+ ".mp3",
+ ".wav",
+ ".ogg",
+ ".woff",
+ ".woff2",
+ ".ttf",
+ ".otf",
+ ".eot",
+ ".pdf",
+]);
+const SKIP_BASENAMES = new Set([
+ "LICENSE",
+ "LICENSE.txt",
+ "DCO",
+ "NOTICE",
+ "NOTICE.txt",
+ ".gitignore",
+ ".gitattributes",
+ ".editorconfig",
+ ".npmrc",
+ ".prettierignore",
+ ".eslintignore",
+]);
+const GIT_BASE_REFS = ["origin/main", "main", "origin/master", "master"];
+
+export function normalizeRelPath(value) {
+ return String(value).replace(/\\/g, "/");
+}
+
+export function isTestFile(file) {
+ return /\.(test|spec)\.[cm]?[jt]sx?$/.test(normalizeRelPath(file));
+}
+
+export function isSkippableFile(file) {
+ const normalized = normalizeRelPath(file);
+ const basename = normalized.split("/").pop() ?? normalized;
+ if (SKIP_BASENAMES.has(basename)) return true;
+ const extension = path.posix.extname(basename).toLowerCase();
+ return SKIP_EXTENSIONS.has(extension);
+}
+
+export function isWideFile(file) {
+ const normalized = normalizeRelPath(file);
+ if (WIDE_ROOT_FILES.has(normalized)) return true;
+ if (normalized.endsWith("/package.json")) return true;
+ if (/(^|\/)vitest\.config\.[cm]?[jt]s$/.test(normalized)) return true;
+ if (
+ normalized === "scripts/test-workspaces.mjs" ||
+ normalized === "scripts/test-workspaces.config.mjs" ||
+ normalized === "scripts/test-related.mjs" ||
+ normalized === "scripts/test-gate-lock.mjs"
+ ) {
+ return true;
+ }
+ return normalized.startsWith(".github/workflows/");
+}
+
+export function shouldRunTestRunner(files) {
+ return files.some((file) => {
+ const normalized = normalizeRelPath(file);
+ return (
+ !normalized.startsWith("apps/") && !normalized.startsWith("packages/")
+ );
+ });
+}
+
+export function workspaceForFile(file, workspaceCwds) {
+ const normalized = normalizeRelPath(file);
+ return workspaceCwds
+ .map(normalizeRelPath)
+ .filter(
+ (cwd) => normalized === cwd || normalized.startsWith(`${cwd}/`),
+ )
+ .sort((left, right) => right.length - left.length)[0];
+}
+
+function isPackagePublicSource(file) {
+ const normalized = normalizeRelPath(file);
+ if (isTestFile(normalized)) return false;
+ return !(
+ normalized.includes("/__tests__/") || normalized.includes("/__mocks__/")
+ );
+}
+
+function isWorkspaceDependency(version) {
+ return typeof version === "string" && version.startsWith("workspace:");
+}
+
+export function buildDependentMap(workspaces, packageJsonByCwd) {
+ const nameToCwd = new Map();
+ for (const workspace of workspaces) {
+ nameToCwd.set(workspace.name, normalizeRelPath(workspace.cwd));
+ }
+ for (const [cwd, pkg] of Object.entries(packageJsonByCwd)) {
+ if (pkg?.name) nameToCwd.set(pkg.name, normalizeRelPath(cwd));
+ }
+
+ const dependents = new Map();
+ for (const workspace of workspaces) {
+ dependents.set(normalizeRelPath(workspace.cwd), new Set());
+ }
+
+ for (const workspace of workspaces) {
+ const cwd = normalizeRelPath(workspace.cwd);
+ const pkg =
+ packageJsonByCwd[cwd] ?? packageJsonByCwd[workspace.cwd] ?? null;
+ if (!pkg) continue;
+ const entries = [
+ ...Object.entries(pkg.dependencies ?? {}),
+ ...Object.entries(pkg.devDependencies ?? {}),
+ ...Object.entries(pkg.peerDependencies ?? {}),
+ ];
+ for (const [depName, version] of entries) {
+ if (!isWorkspaceDependency(version)) continue;
+ const producer = nameToCwd.get(depName);
+ if (!producer || producer === cwd) continue;
+ if (!dependents.has(producer)) dependents.set(producer, new Set());
+ dependents.get(producer).add(cwd);
+ }
+ }
+ return dependents;
+}
+
+export function collectTransitiveDependents(startCwds, dependentMap) {
+ const result = new Set();
+ const queue = startCwds.map(normalizeRelPath);
+ while (queue.length > 0) {
+ const cwd = queue.pop();
+ for (const dependent of dependentMap.get(cwd) ?? []) {
+ if (result.has(dependent)) continue;
+ result.add(dependent);
+ queue.push(dependent);
+ }
+ }
+ return result;
+}
+
+export function resolveGitBaseRef(runGit) {
+ for (const ref of GIT_BASE_REFS) {
+ try {
+ runGit(["rev-parse", "--verify", ref]);
+ return ref;
+ } catch {
+ // try the next conventional main-branch name
+ }
+ }
+ return null;
+}
+
+function addGitNames(files, output) {
+ for (const line of String(output).split(/\r?\n/)) {
+ const trimmed = line.trim();
+ if (trimmed) files.add(normalizeRelPath(trimmed));
+ }
+}
+
+export function collectChangedFiles(runGit) {
+ try {
+ const baseRef = resolveGitBaseRef(runGit);
+ if (!baseRef) {
+ return {
+ files: [],
+ base: null,
+ baseRef: null,
+ error: "cannot resolve git base against main",
+ };
+ }
+ const mergeBase = String(runGit(["merge-base", "HEAD", baseRef])).trim();
+ if (!mergeBase) {
+ return {
+ files: [],
+ base: null,
+ baseRef,
+ error: `cannot compute merge-base with ${baseRef}`,
+ };
+ }
+ const files = new Set();
+ addGitNames(files, runGit(["diff", "--name-only", mergeBase, "HEAD"]));
+ addGitNames(files, runGit(["diff", "--name-only", "--cached"]));
+ addGitNames(files, runGit(["diff", "--name-only"]));
+ addGitNames(files, runGit(["ls-files", "--others", "--exclude-standard"]));
+ return {
+ files: [...files].sort(),
+ base: mergeBase,
+ baseRef,
+ };
+ } catch (error) {
+ return {
+ files: [],
+ base: null,
+ baseRef: null,
+ error: error?.message ?? "git changed-file collection failed",
+ };
+ }
+}
+
+function hasRequiredUnitTier(workspace) {
+ const unit = workspace.tiers?.unit;
+ return unit?.status === "required";
+}
+
+function describeRelatedRuns(runs) {
+ if (runs.length === 0) return "no workspace unit tests";
+ return runs
+ .map((run) =>
+ Array.isArray(run.relatedFiles)
+ ? `${run.cwd} (related ${run.relatedFiles.length})`
+ : `${run.cwd} (full)`,
+ )
+ .join(", ");
+}
+
+export function planRelatedUnitTests({
+ changedFiles,
+ workspaces,
+ packageJsonByCwd,
+ fileExists = () => true,
+}) {
+ const files = (changedFiles ?? []).map(normalizeRelPath);
+ if (files.length === 0) {
+ return {
+ mode: "skip",
+ reason: "no changes vs main",
+ runTestRunner: false,
+ runs: [],
+ };
+ }
+
+ const wide = files.filter(isWideFile);
+ if (wide.length > 0) {
+ const preview = wide.slice(0, 5).join(", ");
+ const extra = wide.length > 5 ? "…" : "";
+ return {
+ mode: "full",
+ reason: `wide files changed: ${preview}${extra}`,
+ runTestRunner: true,
+ runs: [],
+ };
+ }
+
+ const runTestRunner = shouldRunTestRunner(files);
+ const testable = files.filter((file) => !isSkippableFile(file));
+ if (testable.length === 0) {
+ return {
+ mode: runTestRunner ? "related" : "skip",
+ reason: runTestRunner
+ ? "only non-code files changed; run root test:runner"
+ : "only non-code files changed",
+ runTestRunner,
+ runs: [],
+ };
+ }
+
+ const workspaceCwds = workspaces.map((workspace) =>
+ normalizeRelPath(workspace.cwd),
+ );
+ const byCwd = new Map(
+ workspaces.map((workspace) => [
+ normalizeRelPath(workspace.cwd),
+ workspace,
+ ]),
+ );
+ const ownerRelated = new Map();
+ const sourceChangedCwds = new Set();
+
+ for (const file of testable) {
+ const cwd = workspaceForFile(file, workspaceCwds);
+ if (!cwd) continue;
+ const workspace = byCwd.get(cwd);
+ if (!workspace || !hasRequiredUnitTier(workspace)) continue;
+ if (!ownerRelated.has(cwd)) ownerRelated.set(cwd, new Set());
+ if (fileExists(file)) ownerRelated.get(cwd).add(file);
+ if (isPackagePublicSource(file)) sourceChangedCwds.add(cwd);
+ }
+
+ const dependents = collectTransitiveDependents(
+ [...sourceChangedCwds],
+ buildDependentMap(workspaces, packageJsonByCwd),
+ );
+ const runCwds = new Set([...ownerRelated.keys(), ...dependents]);
+ const runs = [...runCwds]
+ .sort()
+ .flatMap((cwd) => {
+ const workspace = byCwd.get(cwd);
+ if (!workspace || !hasRequiredUnitTier(workspace)) return [];
+ const ownFiles = [...(ownerRelated.get(cwd) ?? [])].sort();
+ const relatedFiles = dependents.has(cwd) ? null : ownFiles;
+ if (Array.isArray(relatedFiles) && relatedFiles.length === 0) return [];
+ return [
+ {
+ cwd,
+ name: workspace.name,
+ relatedFiles,
+ },
+ ];
+ });
+
+ if (runs.length === 0 && !runTestRunner) {
+ return {
+ mode: "skip",
+ reason: "no related unit tests",
+ runTestRunner: false,
+ runs: [],
+ };
+ }
+
+ return {
+ mode: "related",
+ reason: describeRelatedRuns(runs),
+ runTestRunner,
+ runs,
+ };
+}
+
+export function readWorkspacePackages(
+ root,
+ workspaces,
+ readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8")),
+) {
+ const result = {};
+ for (const workspace of workspaces) {
+ const cwd = normalizeRelPath(workspace.cwd);
+ try {
+ result[cwd] = readJson(path.join(root, ...cwd.split("/"), "package.json"));
+ } catch {
+ result[cwd] = null;
+ }
+ }
+ return result;
+}
+
+export function createRelatedUnitPlan({
+ root,
+ manifest,
+ runGit,
+ readJson,
+ fileExists,
+}) {
+ const collected = collectChangedFiles(runGit);
+ if (collected.error) {
+ return {
+ mode: "full",
+ reason: collected.error,
+ runTestRunner: true,
+ runs: [],
+ };
+ }
+ return planRelatedUnitTests({
+ changedFiles: collected.files,
+ workspaces: manifest.workspaces,
+ packageJsonByCwd: readWorkspacePackages(
+ root,
+ manifest.workspaces,
+ readJson,
+ ),
+ fileExists:
+ fileExists ??
+ ((file) => fs.existsSync(path.join(root, ...normalizeRelPath(file).split("/")))),
+ });
+}
diff --git a/scripts/test-workspaces.mjs b/scripts/test-workspaces.mjs
index 09ea7d3682..8005879c23 100644
--- a/scripts/test-workspaces.mjs
+++ b/scripts/test-workspaces.mjs
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-import { spawn } from "node:child_process";
+import { execFileSync, spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
@@ -9,6 +9,7 @@ import {
acquireTestGateLock,
shouldUseTestGateLock,
} from "./test-gate-lock.mjs";
+import { createRelatedUnitPlan } from "./test-related.mjs";
const ROOT = path.resolve(fileURLToPath(new URL("..", import.meta.url)));
const IGNORED_PARTS = new Set([
@@ -52,6 +53,7 @@ export function parseCliOptions(args) {
excludeWorkspaces: [],
workspaceConcurrency: undefined,
noLock: false,
+ related: false,
};
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
@@ -64,6 +66,10 @@ export function parseCliOptions(args) {
options.noLock = true;
continue;
}
+ if (arg === "--related") {
+ options.related = true;
+ continue;
+ }
if (arg === "--tier") {
const value = args[index + 1];
if (!value || value.startsWith("--"))
@@ -99,6 +105,9 @@ export function parseCliOptions(args) {
}
throw new Error(`Unknown option: ${arg}`);
}
+ if (options.related && options.all) {
+ throw new Error("--related cannot be combined with --all");
+ }
return options;
}
@@ -465,36 +474,52 @@ function undersizedVitestShardArgs(commandSpec, selectedFiles) {
return selectedFiles.length < count ? ["--passWithNoTests"] : [];
}
+function toWorkspaceRelativeFile(workspace, file) {
+ const workspacePrefix = `${normalizeRelPath(workspace.cwd)}/`;
+ const normalized = normalizeRelPath(file);
+ if (!normalized.startsWith(workspacePrefix)) {
+ throw new Error(
+ `Selected test file is outside workspace ${workspace.cwd}: ${file}`,
+ );
+ }
+ return normalized.slice(workspacePrefix.length);
+}
+
+function vitestRelatedArgs(commandSpec) {
+ const rest = (commandSpec.args ?? []).filter((arg) => arg !== "run");
+ return ["related", "--run", ...rest];
+}
+
export function buildPnpmArgs(
root,
workspace,
commandSpec,
tierConfig = {},
selectedFiles = [],
+ relatedFiles,
) {
const workspaceAbs = path.join(root, workspace.cwd);
if (commandSpec.type === "packageScript")
return ["--dir", workspaceAbs, "run", commandSpec.script];
if (commandSpec.type === "packageBin") {
- const workspacePrefix = `${normalizeRelPath(workspace.cwd)}/`;
- const selectedArgs = tierConfig.include?.length
- ? selectedFiles.map((file) => {
- const normalized = normalizeRelPath(file);
- if (!normalized.startsWith(workspacePrefix)) {
- throw new Error(
- `Selected test file is outside workspace ${workspace.cwd}: ${file}`,
- );
- }
- return normalized.slice(workspacePrefix.length);
- })
- : [];
+ const useRelated =
+ commandSpec.bin === "vitest" && Array.isArray(relatedFiles);
+ const selectedArgs = useRelated
+ ? relatedFiles.map((file) => toWorkspaceRelativeFile(workspace, file))
+ : tierConfig.include?.length
+ ? selectedFiles.map((file) => toWorkspaceRelativeFile(workspace, file))
+ : [];
+ const binArgs = useRelated
+ ? vitestRelatedArgs(commandSpec)
+ : (commandSpec.args ?? []);
const args = [
"--dir",
workspaceAbs,
"exec",
commandSpec.bin,
- ...(commandSpec.args ?? []),
+ ...binArgs,
...undersizedVitestShardArgs(commandSpec, selectedFiles),
+ ...(useRelated ? ["--passWithNoTests"] : []),
...selectedArgs,
];
for (const pattern of tierConfig.exclude ?? []) {
@@ -758,6 +783,7 @@ export async function runPlannedTests({
allFiles,
runCommandImpl = runCommand,
workspaceConcurrency,
+ relatedFilesByWorkspace,
reporter,
now = Date.now,
}) {
@@ -855,12 +881,15 @@ export async function runPlannedTests({
return result;
}
}
+ const relatedFiles =
+ relatedFilesByWorkspace?.[normalizeRelPath(run.workspace.cwd)];
const pnpmArgs = buildPnpmArgs(
root,
run.workspace,
run.tierConfig.command,
run.tierConfig,
fileCheck.selected,
+ Array.isArray(relatedFiles) ? relatedFiles : undefined,
);
const invocation = resolvePnpmInvocation(pnpmArgs);
const commandResult = await runCommandImpl(
@@ -927,15 +956,98 @@ export function printSummary(results, manifest) {
}
}
+export function createRepoGitRunner(root = ROOT) {
+ return (args) =>
+ execFileSync("git", args, {
+ cwd: root,
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+}
+
+export async function runRootTestRunner({
+ root = ROOT,
+ runCommandImpl = runCommand,
+ now = Date.now,
+} = {}) {
+ console.log("START test:runner");
+ const startedAt = now();
+ const invocation = resolvePnpmInvocation(["run", "test:runner"]);
+ const commandResult = await runCommandImpl(
+ invocation.command,
+ invocation.args,
+ {
+ cwd: root,
+ env: invocation.env ? { ...process.env, ...invocation.env } : undefined,
+ shell: invocation.shell,
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,
+ },
+ );
+ const status = commandResult.exitCode === 0 ? "PASS" : "FAIL";
+ console.log(
+ `${status} test:runner (${formatElapsed(Math.max(0, now() - startedAt))})`,
+ );
+ return commandResult;
+}
+
+function intersectRelatedRuns(runs, requested, manifestWorkspaces) {
+ if (requested.length === 0) return runs;
+ return runs.filter((run) => {
+ const workspace = manifestWorkspaces.find(
+ (item) => normalizeRelPath(item.cwd) === normalizeRelPath(run.cwd),
+ );
+ return (
+ workspace &&
+ requested.some((selector) => workspaceMatchesSelector(workspace, selector))
+ );
+ });
+}
+
async function main() {
+ const options = parseCliOptions(process.argv.slice(2));
const {
all,
tier,
- workspaces,
excludeWorkspaces,
workspaceConcurrency,
noLock,
- } = parseCliOptions(process.argv.slice(2));
+ related,
+ } = options;
+ let workspaces = options.workspaces;
+ let relatedFilesByWorkspace;
+ let relatedPlan;
+
+ if (related) {
+ const manifest = (await import("./test-workspaces.config.mjs")).default;
+ relatedPlan = createRelatedUnitPlan({
+ root: ROOT,
+ manifest,
+ runGit: createRepoGitRunner(ROOT),
+ });
+ console.log(`RELATED ${relatedPlan.mode}: ${relatedPlan.reason}`);
+ if (relatedPlan.mode === "skip") return;
+ if (relatedPlan.mode === "related") {
+ const selectedRuns = intersectRelatedRuns(
+ relatedPlan.runs,
+ workspaces,
+ manifest.workspaces,
+ );
+ workspaces = selectedRuns.map((run) => run.cwd);
+ relatedFilesByWorkspace = Object.fromEntries(
+ selectedRuns.map((run) => [run.cwd, run.relatedFiles]),
+ );
+ }
+ }
+
+ const willRunWorkspaces =
+ !related ||
+ relatedPlan?.mode === "full" ||
+ workspaces.length > 0;
+ const willRunTestRunner =
+ related &&
+ (relatedPlan?.mode === "full" || relatedPlan?.runTestRunner);
+ if (related && !willRunWorkspaces && !willRunTestRunner) return;
+
const lock = shouldUseTestGateLock({ all, tier, noLock })
? await acquireTestGateLock({
repoRoot: ROOT,
@@ -948,6 +1060,15 @@ async function main() {
})
: null;
try {
+ if (willRunTestRunner) {
+ const runnerResult = await runRootTestRunner();
+ if (runnerResult.exitCode !== 0) {
+ process.exitCode = 1;
+ return;
+ }
+ }
+ if (!willRunWorkspaces) return;
+
const manifest = (await import("./test-workspaces.config.mjs")).default;
const results = await runPlannedTests({
root: ROOT,
@@ -957,6 +1078,7 @@ async function main() {
workspaces,
excludeWorkspaces,
workspaceConcurrency,
+ relatedFilesByWorkspace,
reporter: createWorkspaceRunReporter(),
});
printSummary(results, manifest);