Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(tests): close hygiene scanner alias gaps
MagicLizi65d8f489acc8
diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex 050c725728..0482552231 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -100,17 +100,17 @@ CI 仍须重新通过。取消 `scripts/` 的目录级豁免,只按完整路径登记 5 份已有跨文件契约并写明理由;其模块重载与真实等待规则仍适用,新普通脚本测试读取应用源码会失败。扫描器自测4 项约 2.4 秒,全仓 AST 扫描约 20 秒(比最初的文本扫描成本更高)。通过 `--update`-只删除 zero-wiring 内嵌 fixture 造成的 8 次误报,基线从 375 收紧为 374 个文件。+只删除 zero-wiring 内嵌 fixture 造成的 8 次误报,基线从 375 收紧为 374 个文件;本轮继续收紧掉已不再被误判为等待的 token-speed 条目,基线为 373 个文件。源码路径别名会沿本地 resolve/join 锚点传播,描述性变量名不能绕过普通 unit 的源码读取门;已有跨文件源码契约明确加入对应 guard allowlist。计时器模式也沿真实 Vitest 绑定追踪属性、解构、namespace 和静态赋值别名,并在实际调用或 hook 执行处生效;恢复真实时钟后,后续测试的长等待不会沿用假时钟豁免。未调用的别名、局部同名对象及 fixture 字符串不改变模式,基线未放宽。真实回调定时器也跟踪静态 `const` 别名与解构,并按函数被捕获时的时钟判定:提前保存的原生函数不会因之后启用假时钟而豁免,假时钟下保存的函数也不会因恢复真实时钟而误报。`node:timers` 的 named/namespace/default 绑定保留原生身份;-当前 Vitest 3.2.7 的真实函数身份验证与 scanner 正反例均通过,基线保持 374 个文件。+当前 Vitest 3.2.7 的真实函数身份验证与 scanner 正反例均通过,基线保持 373 个文件。Promise timer 的本地 wrapper 也按导入绑定识别,并使用 Promise API 的首个时长参数;named 与 namespace wrapper、短等待、常量内层等待和参数/fixture 遮蔽均有回归,-避免把包装后的真实等待漏出卫生门。+避免把包装后的真实等待漏出卫生门。对象方法(如 meter.pause(1_000))不再仅凭方法名计入真实等待;只有直接函数调用或已解析的计时器包装才会进入门禁,避免把同步状态机接口误报为异步等待。导入设置恢复真实组件挂载回归,验证首次自动扫描与重入时先显示缓存、再更新结果,2 项单文件命令约 2.2 秒。slash 空结果、目录队列插入与语音输入保护并入既有 ChatInput文件,经过真实编辑器/hook 验证键盘消费、目录 chip、语音全生命周期只读与顶层弹层diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjsindex 36124dd465..5bcbd53612 100644--- a/scripts/__tests__/check-test-hygiene.test.mjs+++ b/scripts/__tests__/check-test-hygiene.test.mjs@@ -307,6 +307,13 @@ test("scanTestSource counts only unjustified hits for each rule", () => {"function read(relative: string): string { return readFileSync(resolve(__dirname, relative), 'utf8'); }\nconst source = read('../ChatInput.tsx');",{ sourceReads: 1 },],+ [+ "source read through an anchor-derived descriptive binding",+ "const agentsRoot = resolve(__dirname, '..'); const source = readFileSync(resolve(agentsRoot, 'agents', 'index.ts'), 'utf8');",+ { sourceReads: 1 },+ ],+ ["domain object pause is not a real wait", "const meter = { pause(ms) {} }; meter.pause(1_000);", { realWaits: 0 }],+ ["domain object sleep is not a real wait", "const sleeper = { sleep(ms) {} }; sleeper.sleep(1_000);", { realWaits: 0 }],];for (const [name, source, expected] of cases) {const result = scanTestSource(source);diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex 3dc136d069..116bb17b1c 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -224,6 +224,7 @@ test("unit workspace concurrency reserves the full worker budget for heavy works"**/*.integration.test.ts","**/*.e2e.test.ts","**/*.git-integration.test.ts",+ "src/agents/shared/auto-review-remote-wiring.test.ts",]);assert.deepEqual(makerCore.tiers.unit.command, {type: "packageBin",@@ -963,6 +964,7 @@ test("planRuns keeps required guard tiers from competing with the typed-send sca[["apps/desktop", "guard"],["apps/mobile", "guard"],+ ["packages/maker-core", "guard"],],);// PR #6196: CI ran both default CPU-sized pools beside the 1 GiB TSdiff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjsindex 8f38b24550..1918e04175 100644--- a/scripts/check-test-hygiene.mjs+++ b/scripts/check-test-hygiene.mjs@@ -484,7 +484,9 @@ function staticWaitCalls(code) {duration = number(call.arguments[1]);clockIndex = callback.clockIndex;}- else if (REAL_WAIT_NAMES.has(name) && !shadowedPromiseTimer) duration = number(call.arguments[0]);+ // Generic wait names are only meaningful as direct local calls. A method+ // such as meter.pause(1_000) is ordinary domain data, not a real wait.+ else if (ts.isIdentifier(call.expression) && REAL_WAIT_NAMES.has(name) && !shadowedPromiseTimer) duration = number(call.arguments[0]);else {if (!ts.isIdentifier(call.expression)) continue;const bound = binding(call.expression);@@ -741,6 +743,39 @@ const SOURCE_LITERAL = new RegExp('\\.' + SOURCE_EXTENSION + '[\'"]', 'i');// usually hold an mkdtemp() directory whose fake source files are test input.const REPO_ANCHOR = /__dirname|import\.meta\.(?:url|dirname)|process\.cwd\s*\(\s*\)|\b(?:REPO_ROOT|repoRoot|desktopRoot)\b/;+/** Follow simple local path bindings so an anchor-derived directory cannot be+ * hidden behind a descriptive variable name (for example agentsRoot).+ * This intentionally stays local and syntax-only; it does not evaluate+ * arbitrary expressions or cross module boundaries.+ */+function findRepoAnchorNames(code) {+ const names = new Set();+ let changed = true;+ while (changed) {+ changed = false;+ const declarations = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([^;\n]+)/g;+ for (const match of code.matchAll(declarations)) {+ const rhs = match[2];+ const identifiers = rhs.match(/\b[A-Za-z_$][\w$]*\b/g) ?? [];+ const pathFactory = /^\s*(?:new\s+)?(?:resolve|join|URL)\s*\(/.test(rhs);+ const directAnchor = /^\s*(?:__dirname|import\.meta\.(?:url|dirname)|process\.cwd\s*\(\s*\)|REPO_ROOT|repoRoot|desktopRoot)\b/.test(rhs);+ const alias = /^\s*[A-Za-z_$][\w$]*\s*$/.test(rhs);+ if ((directAnchor || pathFactory && (REPO_ANCHOR.test(rhs) || identifiers.some(identifier => names.has(identifier)))+ || alias && identifiers.some(identifier => names.has(identifier)))+ && !names.has(match[1])) {+ names.add(match[1]);+ changed = true;+ }+ }+ }+ return names;+}++function hasRepoAnchor(text, anchorNames = new Set()) {+ if (REPO_ANCHOR.test(text)) return true;+ return (text.match(/\b[A-Za-z_$][\w$]*\b/g) ?? []).some(identifier => anchorNames.has(identifier));+}+/** Normalize only calls bound to fs reads, leaving strings and local shadows* untouched. All path/execution offsets below come from this same final text.* This is static local alias tracking, not arbitrary inter-module evaluation.@@ -932,7 +967,7 @@ function findSourceReadHelpers(code) {return helpers;}-function isSourcePathLiteral(code, match, sourceReadHelpers = new Set()) {+function isSourcePathLiteral(code, match, sourceReadHelpers = new Set(), anchorNames = new Set()) {const value = match[2];if (!SOURCE_EXT.test(value) || /fixture|:\/\//i.test(value)) return false;if (IMPORT_CONTEXT.test(code.slice(Math.max(0, match.index - 24), match.index))) return false;@@ -945,7 +980,7 @@ function isSourcePathLiteral(code, match, sourceReadHelpers = new Set()) {const helperCall = prefix.match(/\b([A-Za-z_$][\w$]*)\s*\(\s*$/)?.[1];if (helperCall && sourceReadHelpers.has(helperCall)) return true;// resolve(__dirname, '..', 'Sidebar.tsx') or new URL('../x.ts', import.meta.url).- if (REPO_ANCHOR.test(line) && findEnclosingReadCall(code, match.index) >= 0) return true;+ if (hasRepoAnchor(line, anchorNames) && findEnclosingReadCall(code, match.index) >= 0) return true;// A separately declared sourcePath may be formatted over several lines before// it is passed to readFileSync. Keep that equivalent to the inline path form.const pathStart = findEnclosingReadCall(code, match.index, /\b(?:resolve|join|URL)\s*\(/g);@@ -955,7 +990,7 @@ function isSourcePathLiteral(code, match, sourceReadHelpers = new Set()) {const binding = code.slice(Math.max(0, pathStart - 150), pathStart).match(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:new\s+)?(?:[A-Za-z_$][\w$]*\.)?$/)?.[1];const readBinding = binding && new RegExp('\\breadFile(?:Sync)?\\s*\\(\\s*' + binding + '\\b').test(code);- if (readBinding && REPO_ANCHOR.test(pathContext) && !/fixture/i.test(pathContext)) return true;+ if (readBinding && hasRepoAnchor(pathContext, anchorNames) && !/fixture/i.test(pathContext)) return true;}// Keep the same decision for a formatted multi-line readFileSync call. The// current line may only contain the final path segment, while the repository@@ -965,7 +1000,7 @@ function isSourcePathLiteral(code, match, sourceReadHelpers = new Set()) {const callContext = code.slice(callStart, match.index + match[0].length);const previousContext = callContext.slice(0, -match[0].length);const hasPriorSourceLiteral = SOURCE_LITERAL.test(previousContext);- if (/\n/.test(callContext) && !hasPriorSourceLiteral && !/[;{}]/.test(callContext) && REPO_ANCHOR.test(callContext) && !/fixture/i.test(callContext)) return true;+ if (/\n/.test(callContext) && !hasPriorSourceLiteral && !/[;{}]/.test(callContext) && hasRepoAnchor(callContext, anchorNames) && !/fixture/i.test(callContext)) return true;}// readFileSync('../x.ts') reads relative to the test process, i.e. the checkout.return callStart >= 0 && (value.startsWith('./') || value.startsWith('../'));@@ -1163,10 +1198,11 @@ export function scanTestSource(source, { isGuard = false } = {}) {if (!isGuard && /\breadFile(?:Sync)?\b|\?raw/.test(code)) {const normalized = normalizeSourceReads(code);const sourceReadHelpers = findSourceReadHelpers(normalized.code);+ const anchorNames = findRepoAnchorNames(normalized.code);const executablePaths = /\bFunction\b|\brunIn(?:New)?Context\b/.test(normalized.code) ? executedSourcePaths(normalized.code) : new Set();for (const match of normalized.literals) {if (executablePaths.has(match.index)) continue;- if (match[2].endsWith('?raw') || isSourcePathLiteral(normalized.code, match, sourceReadHelpers)) sourceReads += 1;+ if (match[2].endsWith('?raw') || isSourcePathLiteral(normalized.code, match, sourceReadHelpers, anchorNames)) sourceReads += 1;}}return { resetModules, realWaits, sourceReads };diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.jsonindex 4a6930cefb..9ce0c2c674 100644--- a/scripts/test-hygiene-baseline.json+++ b/scripts/test-hygiene-baseline.json@@ -1106,9 +1106,6 @@"realWaits": 3,"sourceReads": 2},- "packages/maker-core/src/agents/shared/token-speed.test.ts": {- "realWaits": 6- },"packages/maker-core/src/session.origin.test.ts": {"realWaits": 3},diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 73083595cb..3ff9d4b9fe 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -89,6 +89,9 @@ const makerCoreIntegrationInclude = ['src/agents/claude-code/__tests__/*.integration.test.ts','src/agents/pi/__tests__/*.integration.test.ts',];+const makerCoreGuardInclude = [+ 'src/agents/shared/auto-review-remote-wiring.test.ts',+];const makerPiManagerIntegrationInclude = ['src/__tests__/pi-manager.integration.test.ts',];@@ -147,6 +150,14 @@ const mobileGuardInclude = [// for a new source scan to silently become part of the ordinary unit gate.const desktopGuardInclude = ['src/renderer/__tests__/sessionAgentSwitchRemoteRouting.contract.test.ts',+ 'src/main/__tests__/deviceLinkVoiceCredentialBootstrap.test.ts',+ 'src/main/__tests__/discordExternalization.test.ts',+ 'src/main/__tests__/sessionRuntimeControlWiring.test.ts',+ 'src/main/localDb/ipc/__tests__/sessionCreatedBroadcast.test.ts',+ 'src/renderer/__tests__/promptRecommendationBadge.test.ts',+ 'src/renderer/__tests__/sessionHeaderMenuParity.test.ts',+ 'src/renderer/__tests__/typographyDiscipline.test.ts',+ 'src/renderer/__tests__/windowBackdropAcrylic.test.ts',// Existing credential/permission/protocol contracts, separated from runtime units.'src/main/__tests__/analyticsConsentMigrationGuards.test.ts','src/main/__tests__/authAccountDeletionLifecycle.test.ts',@@ -445,7 +456,14 @@ export default {status: 'required',execution: 'exclusive',command: unitVitestCommand(desktopUnitWorkerCount(), 'forks'),- exclude: ['**/*.integration.test.ts', '**/*.e2e.test.ts', '**/*.git-integration.test.ts'],+ exclude: ['**/*.integration.test.ts', '**/*.e2e.test.ts', '**/*.git-integration.test.ts', ...makerCoreGuardInclude],+ },+ guard: {+ status: 'required',+ coverage: 'allowlist',+ execution: 'exclusive',+ command: vitestBin('run', '--maxWorkers=1'),+ include: makerCoreGuardInclude,},'git-integration': {status: 'manual',