Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(test): 本地测试默认独立运行,收窄选测与执行要求 (#5042)
Chris Zhang80c3020bb1aa
diff --git a/AGENTS.md b/AGENTS.mdindex 0eb9afeb02..382346f83d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -176,16 +176,14 @@瞬时 commit(不存在于本仓库、GitHub 上查不到该 SHA);对这类合成 SHA 跑`check:dco` 的失败结果不构成缺签证据,不要据此报告 DCO 问题。判定 DCO 是否通过,一律以 PR 上的 DCO App check 与真实提交范围(`origin/main..PR head`)的结果为准。-- **提交前测试门禁(硬性要求)**:无论是提 PR 还是直接 commit,提交前都必须在本地- 跑完仓库根 `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`。-- 在上述门禁之上按风险追加验证:跨模块、高风险或基础设施改动追加更广泛验证(如+- **提交前验证**:提交前必须完成与改动风险匹配的测试和相关 package 的类型检查。+ 默认使用根 `pnpm test:unit:related` 选测;已按影响面完成等效定向验证时,不要求为了+ commit 重跑整仓测试。相关 package 运行+ `pnpm --filter <包名> run --if-present typecheck`(包名以该 package 的 `package.json`+ 为准)。已执行检查的失败必须修复或明确说明既有故障,未执行项和原因须如实记录。+ 本机资源预算、并发与跨任务排队由使用者或宿主决定,仓库不强制多个 session 串行。+ GitHub CI 保留完整单测与合并门禁;细则见 `docs/dev-rules/development-workflow.md`。+- 按风险追加验证:跨模块、高风险或基础设施改动追加更广泛验证(如`pnpm test:all`),最终以 CI 门禁为准。不得通过跳过、删除或弱化测试制造通过。## 绝对安全底线diff --git a/apps/desktop/src/main/__tests__/desktopTestResourceLock.test.ts b/apps/desktop/src/main/__tests__/desktopTestResourceLock.test.tsdeleted file mode 100644index 7cf08c1091..0000000000--- a/apps/desktop/src/main/__tests__/desktopTestResourceLock.test.ts+++ /dev/null@@ -1,40 +0,0 @@-import { describe, expect, it } from 'vitest';--import {- classifyDesktopTestLockProbeError,- decideDesktopTestLock,- type DesktopTestLockProbeResult,-} from '../../test/vitest/desktopTestResourceLock';--function probes(...results: DesktopTestLockProbeResult[]) {- return results.map((result, index) => ({ port: 50_000 + index, result }));-}--describe('decideDesktopTestLock', () => {- it('waits for an existing owner on a fallback port before taking an earlier free port', () => {- expect(decideDesktopTestLock(probes('retry', 'owner', 'collision'))).toEqual({- type: 'wait',- });- });-- it('takes the first available candidate only when no existing owner was found', () => {- expect(decideDesktopTestLock(probes('collision', 'retry', 'retry'))).toEqual({- type: 'acquire',- port: 50_001,- });- });-- it('fails closed when every deterministic candidate belongs to an unrelated service', () => {- expect(decideDesktopTestLock(probes('collision', 'collision'))).toEqual({- type: 'unavailable',- });- });-});--describe('classifyDesktopTestLockProbeError', () => {- it('only retries when the candidate port refused the connection', () => {- expect(classifyDesktopTestLockProbeError('ECONNREFUSED')).toBe('retry');- expect(classifyDesktopTestLockProbeError('ECONNRESET')).toBe('collision');- expect(classifyDesktopTestLockProbeError('ETIMEDOUT')).toBe('collision');- });-});diff --git a/apps/desktop/src/test/vitest/desktopTestResourceLock.ts b/apps/desktop/src/test/vitest/desktopTestResourceLock.tsdeleted file mode 100644index 9cfb76cd7f..0000000000--- a/apps/desktop/src/test/vitest/desktopTestResourceLock.ts+++ /dev/null@@ -1,197 +0,0 @@-import { createHash } from 'node:crypto';-import { promises as fs } from 'node:fs';-import net from 'node:net';-import path from 'node:path';-import { fileURLToPath } from 'node:url';--const LOCK_HOST = '127.0.0.1';-const LOCK_PORT_START = 49_152;-const LOCK_PORT_COUNT = 16_000;-const LOCK_PORT_CANDIDATES = 32;-const RETRY_DELAY_MS = 250;-const PROBE_TIMEOUT_MS = 1_000;-const LOCK_PROTOCOL = 'cindy-desktop-test-lock-v1';-const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', '..');--interface DesktopTestLock {- port: number;- release: () => Promise<void>;-}--export type DesktopTestLockProbeResult = 'owner' | 'retry' | 'collision';--export type DesktopTestLockDecision =- | { type: 'wait' }- | { type: 'acquire'; port: number }- | { type: 'unavailable' };--export function classifyDesktopTestLockProbeError(- code: string | undefined,-): DesktopTestLockProbeResult {- return code === 'ECONNREFUSED' ? 'retry' : 'collision';-}--/**- * Decide only after every deterministic candidate has been probed. An owner- * can be on a fallback port because an earlier unrelated service occupied the- * primary port when it started; taking a now-free earlier port before checking- * the fallbacks would split the shared budget between two worktrees.- */-export function decideDesktopTestLock(- probes: readonly { port: number; result: DesktopTestLockProbeResult }[],-): DesktopTestLockDecision {- if (probes.some(({ result }) => result === 'owner')) return { type: 'wait' };- const available = probes.find(({ result }) => result === 'retry');- return available ? { type: 'acquire', port: available.port } : { type: 'unavailable' };-}--function delay(durationMs: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, durationMs));-}--async function resolveGitCommonDir(repoRoot: string): Promise<string> {- const dotGitPath = path.join(repoRoot, '.git');- let dotGitStat;- try {- dotGitStat = await fs.stat(dotGitPath);- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;- // Source archives and exported checkouts may not carry Git metadata.- // They still get a stable per-checkout lock instead of failing test setup.- return fs.realpath(repoRoot);- }- if (dotGitStat.isDirectory()) return fs.realpath(dotGitPath);-- const gitDirLine = (await fs.readFile(dotGitPath, 'utf8')).trim();- const gitDirMatch = /^gitdir:\s*(.+)$/i.exec(gitDirLine);- if (!gitDirMatch) throw new Error(`Invalid gitdir file: ${dotGitPath}`);- const gitDir = path.resolve(repoRoot, gitDirMatch[1]);- try {- const commonDir = (await fs.readFile(path.join(gitDir, 'commondir'), 'utf8')).trim();- return fs.realpath(path.resolve(gitDir, commonDir));- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;- return fs.realpath(gitDir);- }-}--function lockIdentity(commonDir: string): string {- const normalized = process.platform === 'win32' ? commonDir.toLowerCase() : commonDir;- return createHash('sha256').update(normalized).digest('hex');-}--function lockPort(identity: string, candidate: number): number {- const baseOffset = Number.parseInt(identity.slice(0, 8), 16) % LOCK_PORT_COUNT;- return LOCK_PORT_START + ((baseOffset + candidate) % LOCK_PORT_COUNT);-}--function listen(server: net.Server, port: number): Promise<void> {- return new Promise((resolve, reject) => {- const onError = (error: Error) => {- server.off('listening', onListening);- reject(error);- };- const onListening = () => {- server.off('error', onError);- resolve();- };- server.once('error', onError);- server.once('listening', onListening);- server.listen({ host: LOCK_HOST, port, exclusive: true });- });-}--function close(server: net.Server): Promise<void> {- return new Promise((resolve, reject) => {- server.close((error) => {- if (error) reject(error);- else resolve();- });- });-}--async function probeLock(port: number, expectedBanner: string): Promise<DesktopTestLockProbeResult> {- return new Promise((resolve) => {- const socket = net.createConnection({ host: LOCK_HOST, port });- let response = '';- let settled = false;-- const finish = (result: DesktopTestLockProbeResult) => {- if (settled) return;- settled = true;- socket.destroy();- resolve(result);- };-- socket.setEncoding('utf8');- socket.setTimeout(PROBE_TIMEOUT_MS);- socket.on('data', (chunk) => {- response += chunk;- if (response.includes('\n')) {- finish(response.trim() === expectedBanner ? 'owner' : 'collision');- }- });- socket.on('end', () => finish(response.trim() === expectedBanner ? 'owner' : 'collision'));- socket.on('timeout', () => finish('collision'));- socket.on('error', (error: NodeJS.ErrnoException) => {- finish(classifyDesktopTestLockProbeError(error.code));- });- });-}--export async function acquireDesktopTestLock(repoRoot: string): Promise<DesktopTestLock> {- const commonDir = await resolveGitCommonDir(repoRoot);- const identity = lockIdentity(commonDir);- const banner = `${LOCK_PROTOCOL}:${identity}`;- let reportedWait = false;- const ports = Array.from(- { length: LOCK_PORT_CANDIDATES },- (_, candidate) => lockPort(identity, candidate),- );-- while (true) {- const probes = await Promise.all(ports.map(async (port) => ({- port,- result: await probeLock(port, banner),- })));- const decision = decideDesktopTestLock(probes);-- if (decision.type === 'wait') {- if (!reportedWait) {- reportedWait = true;- process.stdout.write('WAIT desktop tests: another worktree is using the shared Desktop test budget\n');- }- await delay(RETRY_DELAY_MS);- continue;- }- if (decision.type === 'unavailable') {- // A random or OS-assigned fallback cannot be rediscovered by later- // worktrees and would silently break mutual exclusion. Fail closed only- // after the expanded deterministic window is genuinely unavailable.- throw new Error(- `All ${LOCK_PORT_CANDIDATES} Desktop test resource-lock ports are occupied by other local services`,- );- }-- const server = net.createServer((socket) => {- socket.end(`${banner}\n`);- });- try {- await listen(server, decision.port);- return {- port: decision.port,- release: () => close(server),- };- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error;- // Another contender may have won between the probe and listen phases.- // Re-scan every candidate so its owner banner is observed before retrying.- await delay(RETRY_DELAY_MS);- }- }-}--export default async function setupDesktopTestResourceLock(): Promise<() => Promise<void>> {- const lock = await acquireDesktopTestLock(REPO_ROOT);- return lock.release;-}diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.tsindex 841f4f0e5c..37ec3e82c0 100644--- a/apps/desktop/vitest.config.ts+++ b/apps/desktop/vitest.config.ts@@ -114,7 +114,6 @@ export default defineConfig({name: 'git-integration',include: gitIntegrationTestInclude,exclude: cliTestExclude,- globalSetup: ['src/test/vitest/desktopTestResourceLock.ts'],},},],diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.mdindex 8cfb554556..428e170a43 100644--- a/docs/dev-rules/desktop-development.md+++ b/docs/dev-rules/desktop-development.md@@ -164,9 +164,9 @@ localStorage 按 **origin + userData 目录** 分家——dev 的 renderer 从工作目录误报缺失或切到备用目录时,参见[工作目录异常日志判读](../working-directory-diagnostics.md),按探测阶段、恢复结果与匿名关联标识区分原因,不要仅凭超时推断掉盘。-本节指导**开发过程中的增量验证**;提交(commit/PR)前的强制门禁以-`development-workflow.md` 的「提交前测试门禁」为准(仓库根 `pnpm test:unit:related` 与相关-package 的 typecheck 全部通过;CI 仍跑完整 `pnpm test:unit`)。开发过程中根据实际改动选择最小但充分的检查:+本节指导本地验证;提交前按 `development-workflow.md` 的「提交前验证」覆盖改动影响面,+默认使用 `pnpm test:unit:related`,也可采用等效定向测试与相关 package 的类型检查。+本机并发预算由使用者或宿主决定,CI 保留完整单测。根据实际改动选择最小但充分的检查:```bashpnpm --filter desktop typecheckdiff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex 06a51c0c59..b12b5dc41e 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -66,20 +66,19 @@ Desktop 测试按成本拆成默认层与显式层:- `standard`:普通单测,以及一条代表性的真实 Git smoke;默认 `test:unit` 只运行这一层。- `git-integration`:文件名为 `*.git-integration.test.ts` 的完整真实 Git 覆盖,由- `pnpm test:git-integration` 显式运行,并通过 global setup 获取以 Git common-dir- 派生的本机回环端口锁。+ `pnpm test:git-integration` 显式运行。Vitest 内部不再获取跨 worktree 资源锁。远端 `client-ci` 以独立并行 job 在每个 PR、`main` push 和手动触发时运行完整-`git-integration` 层;本地提交前门禁默认是 `test:unit:related`,修改真实 Git 行为时可按需-显式补跑完整层。CI 仍跑完整 `test:unit`。+`git-integration` 层;本地按改动风险选测,默认入口为 `test:unit:related`。-因此同一仓库的多个 worktree 可以并行完成默认单测;只有显式运行完整 Git 集成层时才排队:+同一仓库的多个 worktree 默认独立执行测试,不共享单任务配额。需要主动排队时,在根级+测试命令后传 `--lock`;它只协调同样选择排队的本地重型 runner,不能限制其它入口。+锁按 Git common-dir 区分 clone,只监听 `127.0.0.1`,退出后自动释放,等待上限为+15 分钟;CI 与 guard 不参与。`--no-lock` 仍接受为兼容参数,两个选项不能同时使用。+单次运行的 worker 默认值与并发限制保持不变,可按本机预算选择定向 Vitest 参数。++测试分层仍需满足:-- 同一主仓的 worktree 共享 common-dir,因此只有重型层排队执行。-- 独立仓库不共享锁,不会互相阻塞。-- 锁只监听 `127.0.0.1`,不发起业务网络请求;测试进程退出后由操作系统自动释放,不产生- stale lock 文件。-- 无 `.git` 的源码归档按 checkout 实际路径派生锁,不因缺少 Git 元数据而启动失败。- 两个 project 的 include/exclude 必须互补;默认层以低成本 smoke 守住主链路,完整层保留index、patch、hook、ref、worktree 等组合语义。- Vitest 3.2 的 inline project 不会自动继承根 CLI 的 `--exclude`;配置必须把这些排除项diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.mdindex fba49fca40..d05709dd70 100644--- a/docs/dev-rules/development-workflow.md+++ b/docs/dev-rules/development-workflow.md@@ -19,11 +19,12 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径命令超时)。- **你的编辑对运行中的 app 无效**:Vite HMR 只 watch 启动 dev 实例的那个 checkout,worktree 下的改动既不热更也不随重启生效。「改了没反应」不是 bug。开发过程中的增量验证在本- worktree 内跑 `pnpm --filter desktop typecheck` / 定向 `vitest run`;**提交前仍须通过- 第 2 节的提交前测试门禁**。需要运行时验证时 commit + push 后交用户(你无法重启宿主)。+ worktree 内跑 `pnpm --filter desktop typecheck` / 定向 `vitest run`;**提交前仍须完成+ 第 2 节的提交前验证**。需要运行时验证时 commit + push 后交用户(你无法重启宿主)。- **宿主 app 日志不在你的 cwd 下**:dev 日志在启动 checkout(通常是 baseRepo)的`apps/desktop/logs/`,读日志时拼 baseRepo 的绝对路径。-- **结束前必须 commit**:会话被删除或归档时脏 worktree 会先存内容快照再删目录。**PR+- **会话结束与工作区保留**:是否 commit 由用户或宿主工作流决定,不能仅因会话结束+ 强制提交。会话被删除或归档时脏 worktree 会先存内容快照再删目录。**PRmerged/closed 不等于 Cindy 会话已结束**:只要 owning session 仍 active,任何外部 Gitcleanup 都必须跳过该 `.cindy-worktrees` / `.xdt-worktrees` 目录与本地 `cindy/*` / `xdt/*` 分支,交给用户显式归档/删除会话时回收;禁止手动 `git worktree remove` 造成 active session 的 cwd@@ -75,44 +76,42 @@ worktree 建成空目录或自动切到项目根继续修改代码。改这个脚本时不要放宽 name/邮箱比对,否则会出现「本地绿、PR 红」。- 漏签不要重新造一份提交:用 `git commit --amend -s --no-edit` 或`git rebase --signoff <base>` 补签后 `git push --force-with-lease`。-- **提交前测试门禁(硬性要求)**:无论是提 PR 还是直接 commit,提交前都必须在本地跑完- 仓库根 `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。- - **相关单测怎么选**:`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 使用基准验证过的单池最多- 8-worker 配额,低于 8 CPU 时按 `os.availableParallelism()` 自动下调。重型 workspace- 必须独占执行,避免外层并发与内部 worker 池相乘。- 排查并发相关问题时可用- `pnpm test:unit -- --workspace-concurrency=1` 临时退回 workspace 串行;该参数只改变- workspace 调度,不减少测试覆盖。- - **跨 worktree 重型门禁串行**:本地运行 `unit`、`all`、`db`、`git-integration`- tier 时,`test-workspaces.mjs` 会按 Git common-dir 获取同仓共享的 loopback TCP 锁;- 同一 clone 的后到进程会打印持有者 PID、tier 与 worktree 路径并排队,不同 clone- 互不影响。`guard` tier 和 CI/GitHub Actions 不参与。等待超过 15 分钟以退出码 `75`- 结束,表示测试尚未运行,不得当作测试失败排查;排队是正常状态,不要 kill 后重跑。- 只有明确确认资源足够且需要有意重叠时,才可追加 `--no-lock` 作为逃生口。-- **在门禁之上按风险追加验证**:跨模块、高风险或基础设施改动追加更广泛验证(如仓库根+- **提交前验证**:提交前完成与改动影响面匹配的测试,并对涉及的每个 package 运行+ `pnpm --filter <包名> run --if-present typecheck`。默认可用仓库根+ `pnpm test:unit:related` 选测;已经完成等效的定向测试与类型检查时,无须为每次 commit+ 再跑一遍整仓。文档改动运行 `pnpm check:dev-docs` 等适用检查即可,不要求无关业务单测。+ - **验证目标与本机执行方式分开**:用户或宿主决定本机资源预算、并发、执行时机和是否+ 跨任务排队。仓库默认值不能覆盖这些选择,也不授权启动额外测试进程、终止其它任务或+ 把一次机器过载经验升级为所有贡献者的固定限制。+ - **如实记录结果**:本次改动导致的失败须修复;既有或环境故障说明证据、影响和未完成项,+ 不伪造通过、不删除或放宽有效断言。需要保存未完成工作时可作 WIP commit。完整测试与+ 远端必需检查仍由 CI 和合并规则保障,本地定向验证不能冒充完整 CI 通过。+ - **相关单测怎么选**:`test:unit:related` 优先使用 `upstream` 默认分支(含+ `upstream/main` / `upstream/master`),其次 `origin` 默认分支,最后才回退本地+ `main` / `master`,避免落后的个人 fork 扩大测试范围;运行前应先更新目标分支引用。+ 选测包含已提交、已暂存、未暂存和未跟踪文件。同一包源码通过 Vitest `related` 选测;+ 公共包源码变化时,依赖方跑整包单测。包内 `package.json`、Vitest 配置或删除文件时,+ 对所属包及受影响依赖方跑整包;说明性文档不触发根级 runner 或业务单测。+ `i18n/GLOSSARY.md` 与 `docs/legal/notices/` 是有内容断言的生成产物,仍运行根级+ runner 验证,不能仅因扩展名是 Markdown/文本而跳过。+ 测试调度脚本、根依赖清单/锁文件、workspace 配置、根 Vitest 配置或无法确定 Git 基准+ 时仍保守选择完整单测;普通 workflow 变化只触发根级 runner 校验。+ 若选测范围超出本机预算,按真实影响面执行并记录定向验证,把完整门禁交给 CI,+ 不因选测器的保守回退强制占满本机。+ - **单次运行的并发默认值**:workspace runner 默认最多并行+ `min(4, os.availableParallelism())` 个普通 workspace,每个普通 Vitest workspace+ 使用 1 个 worker;Mobile 使用 4 个 worker,Desktop 最多 8 个且随可用 CPU 下调。+ 重型 workspace 在本次 runner 内独占;这些边界不限制其它 session。+ 可用 `--workspace-concurrency=1` 调低同一次运行的 workspace 并发;需要不同 worker+ 配额时,可直接调用目标包 Vitest 的 `--maxWorkers` 参数。+ - **跨 worktree 排队默认关闭**:只有主动传 `--lock` 的本地重型测试命令才参与同仓共享+ loopback TCP 锁。`--no-lock` 保留兼容,不能与 `--lock` 同时使用。直接运行 Desktop+ Vitest 也不再隐式加第二层锁。选择排队后,等待超过 15 分钟以退出码 `75` 结束,表示+ 测试尚未执行;`guard` 和 CI 不参与。锁只协调同样选择 `--lock` 的进程,不能管理+ 未选择排队的任务;有意统一预算时由使用者或宿主协调各入口。+ - **长测试调用**:耗时不确定的检查优先后台运行并保留进度。工具结束等待不等于测试失败,+ 不因等待时间较长重复启动或终止仍在正常运行的测试;外层超时按选定范围和本机情况设置。+- **按风险追加验证**:跨模块、高风险或基础设施改动追加更广泛验证(如仓库根`pnpm test:all`),**最终以 CI 门禁为准**。不得通过 skip、删除或弱化测试制造通过;PR「怎么验证的」一节必须**如实**填写,没跑不许写已跑。- **直推 `main` 的额外门禁**:push 前由独立 reviewer 对最终 diff 做一次对抗性 review,对照diff --git a/docs/dev-rules/engineering-conventions.md b/docs/dev-rules/engineering-conventions.mdindex 554deeaf34..9e5458d6ba 100644--- a/docs/dev-rules/engineering-conventions.md+++ b/docs/dev-rules/engineering-conventions.md@@ -195,7 +195,7 @@ PR 门禁必须在 Windows 上用两个并行分片完整覆盖 `pnpm test:unit`权限卡片按钮是硬编码中文,与应用内 `permissions.alwaysAllowForSession` 是同一个动作。改产品术语时这类「同一动作、两处独立文案」要一起找出来,否则用户在 Slack 和 App 里看到两种说法。-- **批量改术语时必须跑全量 `pnpm test:unit`**:仓库里有若干测试直接断言中文文案+- **批量改术语时覆盖相关文案断言,完整单测由 CI 兜底**:仓库里有若干测试直接断言中文文案(`automationGeneratedSessions.test.ts`、`builtinToolsCollabDescriptionI18n.test.ts`、mobile 的 `sessionMenu.test.ts` 等)。它们是有意的文案锁,改词后要同步更新期望值,不能靠 guard 绿灯就认为改完了。反过来这也是一层兜底——Session→对话 那轮正是diff --git a/scripts/__tests__/test-related.test.mjs b/scripts/__tests__/test-related.test.mjsindex 326fb56dc4..acf3e89795 100644--- a/scripts/__tests__/test-related.test.mjs+++ b/scripts/__tests__/test-related.test.mjs@@ -1,5 +1,9 @@import assert from "node:assert/strict";import test from "node:test";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { execFileSync } from "node:child_process";import {buildDependentMap,collectChangedFiles,@@ -63,13 +67,13 @@ const packageJsonByCwd = {},};-test("isWideFile covers test scheduler, lockfile, and CI workflows", () => {+test("isWideFile keeps only repository-wide dependency and runner inputs", () => {assert.equal(isWideFile("package.json"), true);- assert.equal(isWideFile("apps/desktop/package.json"), true);+ assert.equal(isWideFile("apps/desktop/package.json"), false);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(".github/workflows/ci.yml"), false);assert.equal(isWideFile("apps/desktop/src/main/foo.ts"), false);});@@ -81,14 +85,14 @@ test("isSkippableFile and isTestFile classify docs versus tests", () => {assert.equal(isTestFile("apps/desktop/src/main/foo.ts"), false);});-test("shouldRunTestRunner only when something outside apps/packages changed", () => {+test("shouldRunTestRunner excludes documentation and workspace-only changes", () => {assert.equal(shouldRunTestRunner(["apps/desktop/src/main/foo.ts"]),false,);assert.equal(shouldRunTestRunner(["docs/dev-rules/desktop-development.md"]),- true,+ false,);assert.equal(shouldRunTestRunner(["scripts/check-i18n.mjs"]), true);});@@ -133,7 +137,7 @@ test("collectChangedFiles unions committed, staged, unstaged, and untracked filebase: "base123",baseRef: "origin/main",});- assert.deepEqual(calls[0], ["rev-parse", "--verify", "origin/main"]);+ assert.ok(calls.some((args) => args.join(" ") === "rev-parse --verify upstream/main"));});test("collectChangedFiles falls back when git base cannot be resolved", () => {@@ -215,8 +219,8 @@ test("planRelatedUnitTests skips markdown-only changes", () => {workspaces,packageJsonByCwd,});- assert.equal(plan.mode, "related");- assert.equal(plan.runTestRunner, true);+ assert.equal(plan.mode, "skip");+ assert.equal(plan.runTestRunner, false);assert.deepEqual(plan.runs, []);});@@ -234,15 +238,24 @@ test("planRelatedUnitTests skips when there are no changes", () => {});});-test("planRelatedUnitTests drops deleted files from related args", () => {+test("generated glossary and legal text retain their runner checks without business suites", () => {+ for (const file of ["i18n/GLOSSARY.md", "docs/legal/notices/desktop-win.txt"]) {+ const plan = planRelatedUnitTests({ changedFiles: [file], workspaces, packageJsonByCwd });+ assert.equal(plan.mode, "related", file);+ assert.equal(plan.runTestRunner, true, file);+ assert.deepEqual(plan.runs, [], file);+ }+});++test("planRelatedUnitTests runs the owner suite when a file is deleted", () => {const plan = planRelatedUnitTests({changedFiles: ["apps/desktop/src/main/gone.ts"],workspaces,packageJsonByCwd,fileExists: () => false,});- assert.equal(plan.mode, "skip");- assert.deepEqual(plan.runs, []);+ assert.equal(plan.mode, "related");+ assert.deepEqual(plan.runs, [{ cwd: "apps/desktop", name: "desktop", relatedFiles: null }]);});test("buildDependentMap and collectTransitiveDependents follow workspace:* edges", () => {@@ -256,3 +269,61 @@ test("buildDependentMap and collectTransitiveDependents follow workspace:* edges[],);});++test("workspace manifest and Vitest configuration changes stay in the affected dependency graph", () => {+ for (const file of ["packages/maker-core/package.json", "packages/maker-core/vitest.config.ts"]) {+ const plan = planRelatedUnitTests({ changedFiles: [file], workspaces, packageJsonByCwd });+ assert.equal(plan.mode, "related");+ assert.deepEqual(plan.runs.map(({ cwd, relatedFiles }) => [cwd, relatedFiles]), [+ ["apps/desktop", null], ["packages/maker-core", null],+ ]);+ }+});++test("workflow edits validate the runner without scheduling every workspace", () => {+ const plan = planRelatedUnitTests({+ changedFiles: [".github/workflows/pr-design-basis.yml"], workspaces, packageJsonByCwd,+ });+ assert.equal(plan.mode, "related");+ assert.equal(plan.runTestRunner, true);+ assert.deepEqual(plan.runs, []);+});++test("a stale fork does not count upstream commits as local work, including from a worktree", () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "related-git-base-"));+ const repo = path.join(root, "repo");+ fs.mkdirSync(repo);+ // Git for Windows cannot open Node's \\.\nul device path as a config file.+ const globalConfig = path.join(root, "empty.gitconfig");+ fs.writeFileSync(globalConfig, "");+ const env = { ...process.env, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: globalConfig };+ const git = (cwd, args) => execFileSync("git", args, { cwd, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });+ try {+ git(repo, ["init", "-b", "main"]);+ git(repo, ["config", "user.name", "Test"]);+ git(repo, ["config", "user.email", "[email protected]"]);+ git(repo, ["commit", "--allow-empty", "-m", "base"]);+ git(repo, ["update-ref", "refs/remotes/origin/main", "HEAD"]);+ fs.writeFileSync(path.join(repo, "upstream.ts"), "export const upstream = true;\n");+ git(repo, ["add", "upstream.ts"]);+ git(repo, ["commit", "-m", "upstream change"]);+ git(repo, ["update-ref", "refs/remotes/upstream/trunk", "HEAD"]);+ git(repo, ["symbolic-ref", "refs/remotes/upstream/HEAD", "refs/remotes/upstream/trunk"]);+ assert.deepEqual(collectChangedFiles((args) => git(repo, args)).files, []);+ const worktree = path.join(root, "task");+ git(repo, ["worktree", "add", "-b", "task", worktree]);+ fs.writeFileSync(path.join(worktree, "local.ts"), "export const local = true;\n");+ const result = collectChangedFiles((args) => git(worktree, args));+ assert.equal(result.baseRef, "refs/remotes/upstream/HEAD");+ assert.deepEqual(result.files, ["local.ts"]);+ git(repo, ["symbolic-ref", "--delete", "refs/remotes/upstream/HEAD"]);+ git(repo, ["update-ref", "refs/remotes/upstream/main", "HEAD"]);+ assert.deepEqual(collectChangedFiles((args) => git(worktree, args)).files, ["local.ts"]);+ git(repo, ["update-ref", "-d", "refs/remotes/upstream/main"]);+ assert.equal(collectChangedFiles((args) => git(worktree, args)).baseRef, "origin/main");+ git(repo, ["update-ref", "-d", "refs/remotes/origin/main"]);+ assert.equal(collectChangedFiles((args) => git(worktree, args)).baseRef, "main");+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex 1386fe3849..df8f54d9ef 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import fs from "node:fs";import os from "node:os";import path from "node:path";+import { spawn } from "node:child_process";import { EventEmitter } from "node:events";import test from "node:test";import { fileURLToPath } from "node:url";@@ -976,6 +977,7 @@ test("parseCliOptions rejects --tier without a value", () => {workspaces: [],excludeWorkspaces: [],workspaceConcurrency: undefined,+ lock: false,noLock: false,related: false,});@@ -999,6 +1001,7 @@ test("parseCliOptions supports workspace include and exclude selectors", () => {workspaces: ["desktop", "apps/server", "@cindy/maker-core"],excludeWorkspaces: ["packages/orca-workflow"],workspaceConcurrency: undefined,+ lock: false,noLock: false,related: false,},@@ -1037,7 +1040,9 @@ test("workspace concurrency defaults to a bounded CPU count and accepts both CLI() => parseCliOptions(["--workspace-concurrency"]),/requires a positive integer/,);+ assert.equal(parseCliOptions(["--lock"]).lock, true);assert.equal(parseCliOptions(["--no-lock"]).noLock, true);+ assert.throws(() => parseCliOptions(["--lock", "--no-lock"]), /cannot be combined/);assert.equal(parseCliOptions(["--related"]).related, true);assert.throws(() => parseCliOptions(["--related", "--all"]),@@ -1054,23 +1059,19 @@ test("unit CI shard arguments cover valid halves and reject malformed input", ()}});-test("test gate lock covers heavy local tiers but skips guard, CI, and explicit bypass", () => {+test("cross-worktree locking is opt-in and CI never participates", () => {for (const tier of ["unit", "db", "git-integration", "integration", "e2e"]) {- assert.equal(shouldUseTestGateLock({ tier, env: {} }), true);+ assert.equal(shouldUseTestGateLock({ tier, env: {} }), false);+ assert.equal(shouldUseTestGateLock({ tier, lock: true, env: {} }), true);}- assert.equal(shouldUseTestGateLock({ all: true, env: {} }), true);- assert.equal(shouldUseTestGateLock({ tier: "guard", env: {} }), false);- assert.equal(- shouldUseTestGateLock({ tier: "unit", noLock: true, env: {} }),- false,- );+ assert.equal(shouldUseTestGateLock({ all: true, env: {} }), false);+ assert.equal(shouldUseTestGateLock({ all: true, lock: true, env: {} }), true);+ assert.equal(shouldUseTestGateLock({ tier: "guard", lock: true, env: {} }), false);+ assert.equal(shouldUseTestGateLock({ lock: true, noLock: true, env: {} }), false);for (const env of [{ CI: "1" }, { CI: "true" }, { GITHUB_ACTIONS: "true" }]) {- assert.equal(shouldUseTestGateLock({ tier: "unit", env }), false);+ assert.equal(shouldUseTestGateLock({ lock: true, env }), false);}- assert.equal(- shouldUseTestGateLock({ tier: "unit", env: { CI: "false" } }),- true,- );+ assert.equal(shouldUseTestGateLock({ lock: true, env: { CI: "false" } }), true);});test("test gate lock identity is stable per clone and normalizes Windows case", () => {@@ -2219,3 +2220,69 @@ test("printSummary includes complete command line and skipped workspaces", () =>/SKIP apps\/heartbeat-server notApplicable: No tests yet/,);});++test("CLI runs independently while another worktree budget is held, and waits only with --lock", async () => {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "test-lock-opt-in-")));+ let heldLock;+ try {+ for (const dir of [".git", "scripts/shared", "packages/sample"]) {+ fs.mkdirSync(path.join(root, dir), { recursive: true });+ }+ for (const file of ["test-workspaces.mjs", "test-related.mjs", "test-gate-lock.mjs", "shared/pnpm-invocation.mjs"]) {+ fs.copyFileSync(path.join(ROOT, "scripts", file), path.join(root, "scripts", file));+ }+ fs.writeFileSync(path.join(root, "pnpm-workspace.yaml"), 'packages:\n - "packages/*"\n');+ fs.writeFileSync(path.join(root, "packages/sample/package.json"), '{"name":"sample"}');+ fs.writeFileSync(path.join(root, "packages/sample/sample.test.js"), "// test fixture\n");+ fs.writeFileSync(path.join(root, "scripts/test-workspaces.config.mjs"), `export default ${JSON.stringify({+ workspaces: [{ name: "sample", cwd: "packages/sample", status: "required", tiers: {+ unit: { status: "required", command: { type: "packageScript", script: "probe" } },+ } }],+ })};`);+ const pnpmStub = path.join(root, "pnpm-probe.mjs");+ fs.writeFileSync(pnpmStub, 'import assert from "node:assert/strict"; assert.ok(process.argv.includes("probe")); console.log("PROBE_EXECUTED");');+ heldLock = await acquireTestGateLock({ repoRoot: root, owner: { pid: process.pid, tier: "unit", cwd: root } });+ const run = (args, onOutput) => new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [path.join(root, "scripts/test-workspaces.mjs"), ...args], {+ env: { ...process.env, CI: "false", GITHUB_ACTIONS: "false", npm_execpath: pnpmStub },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ let failure;+ const timer = setTimeout(() => {+ failure = new Error(`CLI did not finish: ${output}`);+ child.kill();+ }, 30_000);+ for (const stream of [child.stdout, child.stderr]) stream.on("data", (chunk) => {+ output += chunk.toString();+ onOutput?.(output);+ });+ child.on("error", (error) => { clearTimeout(timer); reject(error); });+ child.on("close", (code) => {+ clearTimeout(timer);+ if (failure) reject(failure);+ else resolve({ code, output });+ });+ });+ for (const args of [[], ["--no-lock"]]) {+ const result = await run(args);+ assert.equal(result.code, 0, result.output);+ assert.match(result.output, /PASS packages\/sample unit/);+ assert.doesNotMatch(result.output, /WAIT test gate/);+ }+ let releasePromise;+ const queued = await run(["--lock"], (output) => {+ if (output.includes("WAIT test gate") && !releasePromise) {+ releasePromise = heldLock.release();+ heldLock = undefined;+ }+ });+ await releasePromise;+ assert.equal(queued.code, 0, queued.output);+ assert.match(queued.output, /WAIT test gate/);+ assert.match(queued.output, /PASS packages\/sample unit/);+ } finally {+ await heldLock?.release();+ fs.rmSync(root, { recursive: true, force: true });+ }+});diff --git a/scripts/help.mjs b/scripts/help.mjsindex 22cdd089b7..635f970b4c 100644--- a/scripts/help.mjs+++ b/scripts/help.mjs@@ -84,6 +84,8 @@ export function printHelp(log = console.log) {log(' pnpm test:unit');log(' # 排查并发相关问题时,可把 workspace runner 临时退回串行');log(' pnpm test:unit -- --workspace-concurrency=1');+ log(' # 仅在需要跨 worktree 排队时主动开启;默认各任务独立运行');+ log(' pnpm test:unit:related -- --lock');log(' pnpm benchmark:desktop-workers -- --workers=1,2,4,8 --output=<report.json>');log(' pnpm test:all');log(' pnpm test:db');diff --git a/scripts/test-gate-lock.mjs b/scripts/test-gate-lock.mjsindex c9d8843106..2300a92585 100644--- a/scripts/test-gate-lock.mjs+++ b/scripts/test-gate-lock.mjs@@ -45,10 +45,11 @@ export function isTestGateCiEnvironment(env = process.env) {export function shouldUseTestGateLock({all = false,tier = "unit",+ lock = false,noLock = false,env = process.env,} = {}) {- if (noLock || isTestGateCiEnvironment(env)) return false;+ if (!lock || noLock || isTestGateCiEnvironment(env)) return false;return all || HEAVY_TEST_TIERS.has(tier);}@@ -306,7 +307,7 @@ export async function acquireTestGateLock({}if (now() - lastReportAt >= waitReportIntervalMs) {output(- `WAIT test gate: ${describeOwner(decision.owner)}; waited ${formatWaitDuration(waitedMs)} (timeout ${formatWaitDuration(timeoutMs)}). Do not kill and restart; use --no-lock only when intentional overlap is safe.`,+ `WAIT test gate (--lock): ${describeOwner(decision.owner)}; waited ${formatWaitDuration(waitedMs)} (timeout ${formatWaitDuration(timeoutMs)}). Run without --lock to use independent test processes.`,);lastReportAt = now();}diff --git a/scripts/test-related.mjs b/scripts/test-related.mjsindex 5e19e792a5..4f185f5612 100644--- a/scripts/test-related.mjs+++ b/scripts/test-related.mjs@@ -5,6 +5,10 @@ const WIDE_ROOT_FILES = new Set(["package.json","pnpm-lock.yaml","pnpm-workspace.yaml",+ "scripts/test-workspaces.mjs",+ "scripts/test-workspaces.config.mjs",+ "scripts/test-related.mjs",+ "scripts/test-gate-lock.mjs",]);const SKIP_EXTENSIONS = new Set([".md",@@ -45,7 +49,12 @@ const SKIP_BASENAMES = new Set([".prettierignore",".eslintignore",]);-const GIT_BASE_REFS = ["origin/main", "main", "origin/master", "master"];+// A fork's origin can lag behind the contribution target. Prefer the upstream+// default branch before origin, and use local branches only as a fallback.+const GIT_BASE_REFS = [+ "refs/remotes/upstream/HEAD", "upstream/main", "upstream/master",+ "refs/remotes/origin/HEAD", "origin/main", "origin/master", "main", "master",+];export function normalizeRelPath(value) {return String(value).replace(/\\/g, "/");@@ -66,23 +75,20 @@ export function isSkippableFile(file) {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/");+ return /^vitest\.config\.[cm]?[jt]s$/.test(normalized);}export function shouldRunTestRunner(files) {return files.some((file) => {const normalized = normalizeRelPath(file);+ // These text artifacts are executable test inputs, not explanatory docs:+ // glossary-rules and third-party-notices validate their generated content.+ if (+ normalized === "i18n/GLOSSARY.md" ||+ normalized.startsWith("docs/legal/notices/")+ ) return true;return (+ !isSkippableFile(normalized) &&!normalized.startsWith("apps/") && !normalized.startsWith("packages/"));});@@ -286,6 +292,7 @@ export function planRelatedUnitTests({);const ownerRelated = new Map();const sourceChangedCwds = new Set();+ const fullWorkspaces = new Set();for (const file of testable) {const cwd = workspaceForFile(file, workspaceCwds);@@ -294,6 +301,11 @@ export function planRelatedUnitTests({if (!workspace || !hasRequiredUnitTier(workspace)) continue;if (!ownerRelated.has(cwd)) ownerRelated.set(cwd, new Set());if (fileExists(file)) ownerRelated.get(cwd).add(file);+ if (+ file === `${cwd}/package.json` ||+ /(^|\/)vitest\.config\.[cm]?[jt]s$/.test(file.slice(cwd.length + 1)) ||+ !fileExists(file)+ ) fullWorkspaces.add(cwd);if (isPackagePublicSource(file)) sourceChangedCwds.add(cwd);}@@ -308,7 +320,8 @@ export function planRelatedUnitTests({const workspace = byCwd.get(cwd);if (!workspace || !hasRequiredUnitTier(workspace)) return [];const ownFiles = [...(ownerRelated.get(cwd) ?? [])].sort();- const relatedFiles = dependents.has(cwd) ? null : ownFiles;+ const relatedFiles = dependents.has(cwd) || fullWorkspaces.has(cwd)+ ? null : ownFiles;if (Array.isArray(relatedFiles) && relatedFiles.length === 0) return [];return [{diff --git a/scripts/test-workspaces.mjs b/scripts/test-workspaces.mjsindex ac5f752b5a..fdfddd202c 100644--- a/scripts/test-workspaces.mjs+++ b/scripts/test-workspaces.mjs@@ -55,6 +55,7 @@ export function parseCliOptions(args) {workspaces: [],excludeWorkspaces: [],workspaceConcurrency: undefined,+ lock: false,noLock: false,related: false,};@@ -65,6 +66,10 @@ export function parseCliOptions(args) {options.all = true;continue;}+ if (arg === "--lock") {+ options.lock = true;+ continue;+ }if (arg === "--no-lock") {options.noLock = true;continue;@@ -108,6 +113,9 @@ export function parseCliOptions(args) {}throw new Error(`Unknown option: ${arg}`);}+ if (options.lock && options.noLock) {+ throw new Error("--lock cannot be combined with --no-lock");+ }if (options.related && options.all) {throw new Error("--related cannot be combined with --all");}@@ -1025,6 +1033,7 @@ async function main() {tier,excludeWorkspaces,workspaceConcurrency,+ lock: useLock,noLock,related,} = options;@@ -1063,7 +1072,7 @@ async function main() {(relatedPlan?.mode === "full" || relatedPlan?.runTestRunner);if (related && !willRunWorkspaces && !willRunTestRunner) return;- const lock = shouldUseTestGateLock({ all, tier, noLock })+ const lock = shouldUseTestGateLock({ all, tier, lock: useLock, noLock })? await acquireTestGateLock({repoRoot: ROOT,owner: {