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。

fix(test): enforce trusted hygiene baseline and cover sidebar attention

MagicLizide6491dad368
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts
index 6647c5d773..842aa2844f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionNotifications.test.ts
@@ -1,7 +1,11 @@
+// @vitest-environment jsdom
+
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import ts from 'typescript';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createElement, useCallback, useEffect } from 'react';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import { isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';
@@ -38,6 +42,58 @@ const emitted = ts.transpileModule(
{ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None } },
).outputText;
+// PR #6196: helper tests cover receipt routing, but cannot catch the sidebar
+// forgetting to call it. Reuse this component's parsed source and run its actual
+// route/focus effects and row-click callback with React, not source assertions.
+const attentionStatements = expanded.body!.statements.filter(statement => {
+ if (ts.isVariableStatement(statement)) {
+ return statement.declarationList.declarations.some(declaration =>
+ ts.isIdentifier(declaration.name) && declaration.name.text === 'handleSessionClick',
+ );
+ }
+ if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)) return false;
+ const call = statement.expression;
+ if (!ts.isIdentifier(call.expression) || call.expression.text !== 'useEffect') return false;
+ const dependencies = call.arguments[1];
+ if (!dependencies || !ts.isArrayLiteralExpression(dependencies)) return false;
+ const names = dependencies.elements.map(dependency => dependency.getText(source));
+ return names.includes('activeRemoteAttentionRev')
+ || names.length === 1 && names[0] === 'viewedSessionId';
+});
+if (attentionStatements.length !== 3) throw new Error('Missing production sidebar attention consumers');
+const attentionCode = ts.transpileModule(
+ attentionStatements.map(statement => statement.getText(source)).join('\n')
+ .replaceAll('import.meta', 'importMeta'),
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+).outputText;
+
+function attentionSidebar() {
+ const clearAttention = vi.fn();
+ const bindings = {
+ useCallback, useEffect, window,
+ activeSessionRemoteReceiptKey: undefined, activeRemoteAttentionRev: 0,
+ markAutomationSessionRunsRead: vi.fn(), clearSystemSessionAttention: clearAttention,
+ hasSessionSelectionModifier: () => false,
+ selectedSessionIdsRef: { current: new Set<string>() }, setSelectedSessionIds: vi.fn(),
+ setSelectionAnchorSessionId: vi.fn(), urgentSetRef: { current: new Set<string>() },
+ attentionKindsRef: { current: new Map() }, sessionsByIdRef: { current: new Map() },
+ runningSessionIdsRef: { current: new Set() }, sidebarNotificationsRef: { current: new Set() },
+ holdSidebarViewedPriority: vi.fn(), sidebarPriorityContext: (context: unknown) => context,
+ clearNotification: vi.fn(), activeSessionIdRef: { current: 'shown' },
+ navigate: vi.fn(), resolveSessionRoute: async () => '/cc-agent/clicked',
+ importMeta: { env: { DEV: false } }, perfLog: { debug: vi.fn() },
+ };
+ const consume = new Function(...Object.keys(bindings), 'viewedSessionId',
+ attentionCode + '\nreturn handleSessionClick;') as (...args: unknown[]) => (id: string) => void;
+ function SidebarAttention({ viewedSessionId, clickedSessionId = 'clicked' }: { viewedSessionId: string | null; clickedSessionId?: string }) {
+ const onSessionClick = consume(...Object.values(bindings), viewedSessionId);
+ // The row is a DOM boundary adapter; its callback and both effects above are
+ // the production ExpandedView code. Receipt payloads stay in helper tests.
+ return createElement('button', { onClick: () => onSessionClick(clickedSessionId) }, 'Open task');
+ }
+ return { Component: SidebarAttention, clearAttention };
+}
+
type NotificationSession = {
id: string;
title: string;
@@ -50,6 +106,7 @@ const send = vi.fn();
const reviewTarget = vi.fn(async () => false);
const botTitle = vi.fn(async (): Promise<string | null> => null);
beforeEach(() => { vi.clearAllMocks(); });
+afterEach(cleanup);
function dispatcher(local: NotificationSession[], remote: NotificationSession[] = []) {
const bindings = {
@@ -124,3 +181,41 @@ describe('disabled Make notification dispatch', () => {
expect(send).toHaveBeenCalledWith('unknown', 'Unnamed task', 'error');
});
});
+
+describe('sidebar system attention consumers', () => {
+ it('clears the viewed task on opening and window focus, replacing and removing its focus listener', () => {
+ const { Component, clearAttention } = attentionSidebar();
+ const view = render(createElement(Component, { viewedSessionId: 'first' }));
+ expect(clearAttention.mock.calls).toEqual([['first']]);
+ fireEvent(window, new Event('focus'));
+ expect(clearAttention.mock.calls).toEqual([['first'], ['first']]);
+
+ view.rerender(createElement(Component, { viewedSessionId: 'second' }));
+ clearAttention.mockClear();
+ fireEvent(window, new Event('focus'));
+ expect(clearAttention.mock.calls).toEqual([['second']]);
+
+ view.rerender(createElement(Component, { viewedSessionId: null }));
+ clearAttention.mockClear();
+ fireEvent(window, new Event('focus'));
+ expect(clearAttention).not.toHaveBeenCalled();
+ view.rerender(createElement(Component, { viewedSessionId: 'third' }));
+ clearAttention.mockClear();
+ view.unmount();
+ fireEvent(window, new Event('focus'));
+ expect(clearAttention).not.toHaveBeenCalled();
+ });
+
+ it('clears the clicked task, including re-opening the already active task', async () => {
+ const { Component, clearAttention } = attentionSidebar();
+ const view = render(createElement(Component, { viewedSessionId: 'shown' }));
+ clearAttention.mockClear();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Open task' })));
+ expect(clearAttention.mock.calls).toEqual([['clicked']]);
+
+ view.rerender(createElement(Component, { viewedSessionId: 'shown', clickedSessionId: 'shown' }));
+ clearAttention.mockClear();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Open task' })));
+ expect(clearAttention.mock.calls).toEqual([['shown']]);
+ });
+});
diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.md
index e4456f4358..793584569d 100644
--- a/docs/dev-rules/desktop-unit-test-performance.md
+++ b/docs/dev-rules/desktop-unit-test-performance.md
@@ -43,6 +43,11 @@ Windows 四片为 809/1,006/812/661 秒,关键路径 16 分 46 秒,较
Linux 四片为 783/539/691/718 秒;独立 Windows runner/DB job 387 秒。此轮先于审查恢复必要
契约与同步主干,最终合并版本的 CI 还须单独核验,不能用这次结果代替。
+恢复必要契约并同步主干后的 head `49daa510b0`,client-ci run `38883713365` 也已全绿:
+Windows 四片为 715/680/932/1,057 秒,关键路径 17 分 37 秒,较原基线减少约 48%;
+Linux 四片为 754/535/693/699 秒,runner/DB 为 416 秒。后续卫生门与侧栏回归
+补丁仍须由其自身 head 的完整 CI 核验。
+
Vitest 每片切 `ceil(文件数 / 分片数)` 个文件,分片多于 2 个时,文件少的包末尾分片可能为空(6 个文件
分 4 片是 2、2、2、0)。runner 原来只在「文件数少于分片数」时补 `--passWithNoTests`,本机 4/4 分片因此
有 6 个包报 `NO_TESTS_REQUIRED`;现已按 Vitest 的切分方式判断空分片。
@@ -65,6 +70,12 @@ Linux 及 package script 的启动方式不变。回归测试通过真实 runner
不变。同机 4 项测试从 7.14 秒降到 4.95 秒,原有超时未提高;别名与 continuation
方法正反例验证仍能区分 maker Session 与其它同名 send。最终 CI 另行复验。
+随后补齐 Promise 定时器的首参数时长、导入别名与遮蔽判定;基线逐文件、逐规则与
+可信 Git 基准比较,拒绝同一提交手改抬高额度,缺失基准或格式错误均失败。真实临时 Git
+仓库的 CLI 回归覆盖首次登记、收紧、手改抬高、删除与读取失败,4 项 scanner 自测
+约 2.7 秒。侧栏清角标回归并入既有通知测试,通过真实生产 effects 与点击回调验证
+打开、聚焦、重复点击及监听清理,23 项约 3.1 秒;生产行为与 375 文件基线均未改。
+
### 2026-10-16 实验与落地
本机 Windows、32 CPU、Desktop 8 worker。隔离方式三组用同一分片(869 个文件)连续对照:
diff --git a/docs/dev-rules/engineering-conventions.md b/docs/dev-rules/engineering-conventions.md
index 2194c095d8..7a2da61181 100644
--- a/docs/dev-rules/engineering-conventions.md
+++ b/docs/dev-rules/engineering-conventions.md
@@ -171,8 +171,9 @@ Agent 在提交新增测试前必须在 PR 描述或测试文件邻近注释中
三类问题:没有写理由的 `vi.resetModules()`、没有写理由的 ≥100ms 真实等待、普通单测读取生产源码
文本(这类静态契约只能进 guard tier,不接受理由豁免)。存量计数记在
`scripts/test-hygiene-baseline.json`,只允许减少;修掉存量后运行
-`node scripts/check-test-hygiene.mjs --update` 收紧基线。不得手改基线放宽计数让门禁变绿;确有
-必要时在 PR「风险」中说明,由评审确认。
+`node scripts/check-test-hygiene.mjs --update` 收紧基线。门禁从 GitHub PR/合并队列/push 事件
+取得基准提交,本地使用 `origin/main`;逐文件、逐规则拒绝基线上调,手改 JSON 也不能放行。
+只有确认基准提交确实没有基线文件时才允许首次登记;基准缺失、读取失败或基线格式错误均失败。
### 3.3 路径断言的跨平台宪法
diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjs
index f5a99de760..6f32b4787d 100644
--- a/scripts/__tests__/check-test-hygiene.test.mjs
+++ b/scripts/__tests__/check-test-hygiene.test.mjs
@@ -2,10 +2,12 @@
// that flips one rule decision, so a detector regression cannot silently let
// slow or source-literal unit tests back into CI.
import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
+import { fileURLToPath } from "node:url";
import {
compareWithBaseline,
@@ -63,6 +65,14 @@ test("scanTestSource counts only unjustified hits for each rule", () => {
["constant timeout duration", "const SECOND = 1000; const timeout = 2 * SECOND; setTimeout(done, timeout);", { realWaits: 1 }],
["generic arrow in a ts file does not hide later waits", "const identity = <T>(value: T) => value; setTimeout(done, 200);", { realWaits: 1 }],
["property timeout keeps existing detection", "globalThis.setTimeout(done, 200);", { realWaits: 1 }],
+ ["promise timer uses its first argument", "import { setTimeout } from 'node:timers/promises'; await setTimeout(1_000);", { realWaits: 1 }],
+ ["promise timer import alias keeps the duration", "import { setTimeout as nap } from 'node:timers/promises'; await nap(1_000);", { realWaits: 1 }],
+ ["promise timer namespace keeps the duration", "import * as timers from 'node:timers/promises'; await timers.setTimeout(1_000);", { realWaits: 1 }],
+ ["promise timer namespace alias keeps the duration", "import timers from 'timers/promises'; const promises = timers; await promises.setTimeout(1_000);", { realWaits: 1 }],
+ ["short promise timer ignores its numeric return value", "import { setTimeout } from 'node:timers/promises'; await setTimeout(20, 1_000);", { realWaits: 0 }],
+ ["a parameter can shadow the promise timer", "import { setTimeout as delay } from 'node:timers/promises'; function example(delay) { delay(1_000); }", { realWaits: 0 }],
+ ["a local function can shadow the promise timer", "import { setTimeout as delay } from 'node:timers/promises'; function example() { const delay = value => value; delay(1_000); }", { realWaits: 0 }],
+ ["a parameter can shadow the timer namespace", "import * as timers from 'node:timers/promises'; function example(timers) { timers.setTimeout(1_000); }", { realWaits: 0 }],
["short wrapper and fixture shadow", "const tick = ms => new Promise(resolve => setTimeout(resolve, ms)); tick(20); function other(tick) { tick(500); }", { realWaits: 0 }],
["fake wrapper call", "const tick = ms => new Promise(resolve => setTimeout(resolve, ms)); it('fake', () => { vi.useFakeTimers(); tick(500); });", { realWaits: 0 }],
["an uncalled fake-timer helper does not hide real waits", "function enableFake() { vi.useFakeTimers(); } it('real', () => setTimeout(done, 200));", { realWaits: 1 }],
@@ -257,4 +267,83 @@ test("compareWithBaseline only lets counts stay or shrink", () => {
fail.violations.map((v) => `${v.file}:${v.rule}:${v.limit}`),
["a.test.ts:resetModules:2", "new.test.ts:realWaits:0"],
);
+
+ // Exercise the real CLI in its own Git repository. A same-PR JSON edit must
+ // not become trusted merely because it was committed or --update was used.
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-hygiene-ratchet-"));
+ const baselinePath = path.join(root, "scripts", "test-hygiene-baseline.json");
+ const testPath = path.join(root, "apps", "sample", "sample.test.ts");
+ const relativeTestPath = "apps/sample/sample.test.ts";
+ const scriptPath = path.join(root, "scripts", "check-test-hygiene.mjs");
+ const environment = { ...process.env, CI: "", GITHUB_EVENT_PATH: "", GITHUB_EVENT_NAME: "", GITHUB_BASE_REF: "", GITHUB_SHA: "", NODE_PATH: "" };
+ for (const key of Object.keys(environment)) if (key.startsWith("GIT_")) delete environment[key];
+ const git = (...args) => execFileSync("git", args, { cwd: root, env: environment, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim();
+ const commit = () => { git("add", "."); git("-c", "user.name=Hygiene Test", "-c", "[email protected]", "commit", "-s", "-qm", "fixture"); return git("rev-parse", "HEAD"); };
+ const writeBaseline = files => fs.writeFileSync(baselinePath, JSON.stringify({ files }));
+ const writeReads = count => fs.writeFileSync(testPath, Array.from({ length: count }, (_, index) => "readFileSync(resolve(process.cwd(), 'src/input-" + index + ".ts'), 'utf8');").join("\n"));
+ const cli = (args = [], extraEnv = {}) => spawnSync(process.execPath, [scriptPath, ...args], { cwd: root, env: { ...environment, ...extraEnv }, encoding: "utf8" });
+ const output = result => (result.stdout ?? "") + (result.stderr ?? "");
+ try {
+ fs.mkdirSync(path.dirname(testPath), { recursive: true });
+ fs.mkdirSync(path.dirname(scriptPath), { recursive: true });
+ fs.copyFileSync(fileURLToPath(new URL("../check-test-hygiene.mjs", import.meta.url)), scriptPath);
+ fs.writeFileSync(path.join(root, "scripts", "test-workspaces.config.mjs"), "export default { workspaces: [] };");
+ writeReads(1);
+ git("init", "-q", "-b", "main");
+ const firstIntroduction = commit();
+ git("update-ref", "refs/remotes/origin/main", firstIntroduction);
+ const bootstrap = cli(["--update"]);
+ assert.equal(bootstrap.status, 0, output(bootstrap));
+ assert.equal(cli().status, 0);
+ const trusted = commit();
+ git("update-ref", "refs/remotes/origin/main", trusted);
+ writeReads(2);
+ writeBaseline({ [relativeTestPath]: { sourceReads: 2 } });
+ commit();
+ const raised = fs.readFileSync(baselinePath, "utf8");
+ for (const args of [[], ["--update"]]) {
+ const result = cli(args);
+ assert.notEqual(result.status, 0, "committed hand-raised baseline must fail");
+ assert.match(output(result), /baseline.*(?:increase|raise)/i);
+ assert.equal(fs.readFileSync(baselinePath, "utf8"), raised);
+ }
+ const eventPath = path.join(root, "github-event.json");
+ for (const [eventName, event] of [["pull_request", { pull_request: { base: { sha: trusted } } }], ["merge_group", { merge_group: { base_sha: trusted } }], ["push", { before: trusted }]]) {
+ fs.writeFileSync(eventPath, JSON.stringify(event));
+ const result = cli([], { GITHUB_EVENT_NAME: eventName, GITHUB_EVENT_PATH: eventPath, GITHUB_BASE_REF: eventName === "pull_request" ? "main" : "" });
+ assert.notEqual(result.status, 0, eventName);
+ assert.match(output(result), /baseline.*(?:increase|raise)/i);
+ }
+ fs.writeFileSync(eventPath, JSON.stringify({ pull_request: { base: { sha: "1".repeat(40) } } }));
+ const unavailableCommit = cli([], { GITHUB_EVENT_NAME: "pull_request", GITHUB_EVENT_PATH: eventPath, GITHUB_BASE_REF: "main" });
+ assert.notEqual(unavailableCommit.status, 0);
+ assert.match(output(unavailableCommit), /trusted.*base/i);
+ for (const invalidBaseline of [{ files: { [relativeTestPath]: { sourceReads: "unlimited" } } }, { files: [] }, null]) {
+ fs.writeFileSync(baselinePath, JSON.stringify(invalidBaseline));
+ const invalid = cli();
+ assert.notEqual(invalid.status, 0);
+ assert.match(output(invalid), /invalid baseline/i);
+ }
+ fs.unlinkSync(baselinePath);
+ for (const args of [[], ["--update"]]) {
+ const removed = cli(args);
+ assert.notEqual(removed.status, 0);
+ assert.match(output(removed), /baseline.*missing|baseline.*removed/i);
+ assert.equal(fs.existsSync(baselinePath), false);
+ }
+ writeBaseline({ [relativeTestPath]: { sourceReads: 1 } });
+ writeReads(0);
+ const tightened = cli(["--update"]);
+ assert.equal(tightened.status, 0, output(tightened));
+ assert.deepEqual(JSON.parse(fs.readFileSync(baselinePath, "utf8")).files, {});
+ assert.equal(cli().status, 0);
+ git("update-ref", "-d", "refs/remotes/origin/main");
+ for (const args of [[], ["--update"]]) {
+ const missing = cli(args);
+ assert.notEqual(missing.status, 0);
+ assert.match(output(missing), /trusted.*base/i);
+ }
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
});
diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjs
index cb8d69f9ce..d12455c74f 100644
--- a/scripts/check-test-hygiene.mjs
+++ b/scripts/check-test-hygiene.mjs
@@ -16,17 +16,19 @@
// guard tier(scripts/test-workspaces.config.mjs),不接受理由豁免。
//
// 存量计数记在 scripts/test-hygiene-baseline.json,只允许减少:某文件的计数超过基线、
-// 或基线外的文件出现未豁免的命中,都会失败。`--update` 只会把基线往下收紧;确需放宽
-// 只能手改 JSON,让评审在 diff 里看见。
+// 或基线外的文件出现未豁免的命中,都会失败。门禁对照可信 Git 基准拒绝基线上调,
+// 手改 JSON 与 `--update` 均不能绕过;只有确认基准提交还没有基线文件时才首次登记。
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
import path from 'node:path';
import { createRequire } from 'node:module';
import process from 'node:process';
import { fileURLToPath, pathToFileURL } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-const BASELINE_PATH = path.join(ROOT, 'scripts', 'test-hygiene-baseline.json');
+const BASELINE_REL = 'scripts/test-hygiene-baseline.json';
+const BASELINE_PATH = path.join(ROOT, BASELINE_REL);
const SCAN_ROOTS = ['apps', 'packages', 'scripts'];
const SKIP_DIRS = new Set(['node_modules', 'dist', 'out', 'build', 'coverage', '.vite', '.expo', '.turbo']);
export const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/;
@@ -194,12 +196,19 @@ function maskStrings(source) {
}
function staticWaitCalls(code) {
- if (!/\b(?:setTimeout|sleep|delay|wait|waitMs|pause)\s*\(/.test(code)) return [];
+ if (!/\b(?:setTimeout|sleep|delay|wait|waitMs|pause)\s*\(|(?:node:)?timers\/promises/.test(code)) return [];
const ts = typescript ??= requireDesktop('typescript');
const source = parseTestSource(ts, code);
const nodeScopes = new WeakMap();
const calls = [];
+ const promiseTimerNames = new Set();
const isFunction = node => ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node);
+ function isPromiseTimerImport(bound) {
+ let declaration = bound;
+ while (declaration && !ts.isImportDeclaration(declaration)) declaration = declaration.parent;
+ return declaration && ts.isStringLiteral(declaration.moduleSpecifier)
+ && /^(?:node:)?timers\/promises$/.test(declaration.moduleSpecifier.text);
+ }
function collect(node, scope) {
if (ts.isFunctionDeclaration(node) && node.name) scope.bindings.set(node.name.text, node);
if (ts.isSourceFile(node) || ts.isBlock(node) || isFunction(node)) scope = { parent: scope, bindings: new Map() };
@@ -210,6 +219,11 @@ function staticWaitCalls(code) {
}
}
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) scope.bindings.set(node.name.text, node);
+ if (ts.isImportSpecifier(node) || ts.isNamespaceImport(node) || ts.isImportClause(node) && node.name) {
+ scope.bindings.set(node.name.text, node);
+ if (ts.isImportSpecifier(node) && (node.propertyName?.text ?? node.name.text) === 'setTimeout'
+ && isPromiseTimerImport(node)) promiseTimerNames.add(node.name.text);
+ }
if (ts.isCallExpression(node)) calls.push(node);
ts.forEachChild(node, child => collect(child, scope));
}
@@ -220,6 +234,23 @@ function staticWaitCalls(code) {
}
return null;
}
+ function promiseTimerNamespace(node, seen = new Set()) {
+ if (!ts.isIdentifier(node) || seen.has(node)) return false;
+ seen.add(node);
+ const bound = binding(node);
+ if (bound && ts.isVariableDeclaration(bound) && bound.initializer) return promiseTimerNamespace(bound.initializer, seen);
+ return bound && (ts.isNamespaceImport(bound) || ts.isImportClause(bound)) && isPromiseTimerImport(bound);
+ }
+ function isPromiseTimer(node, seen = new Set()) {
+ if (seen.has(node)) return false;
+ seen.add(node);
+ if (ts.isPropertyAccessExpression(node)) return node.name.text === 'setTimeout' && promiseTimerNamespace(node.expression);
+ if (!ts.isIdentifier(node)) return false;
+ const bound = binding(node);
+ if (bound && ts.isVariableDeclaration(bound) && bound.initializer) return isPromiseTimer(bound.initializer, seen);
+ return bound && ts.isImportSpecifier(bound) && (bound.propertyName?.text ?? bound.name.text) === 'setTimeout'
+ && isPromiseTimerImport(bound);
+ }
function number(node, parameters = new Map(), seen = new Set()) {
if (!node || seen.has(node)) return undefined;
seen = new Set(seen).add(node);
@@ -269,8 +300,11 @@ function staticWaitCalls(code) {
const name = ts.isIdentifier(call.expression) ? call.expression.text
: ts.isPropertyAccessExpression(call.expression) ? call.expression.name.text : '';
let duration;
- if (name === 'setTimeout') duration = number(call.arguments[1]);
- else if (REAL_WAIT_NAMES.has(name)) duration = number(call.arguments[0]);
+ const promiseTimer = isPromiseTimer(call.expression);
+ const shadowedPromiseTimer = ts.isIdentifier(call.expression) && promiseTimerNames.has(name) && !promiseTimer;
+ if (promiseTimer) duration = number(call.arguments[0]);
+ else if (name === 'setTimeout' && !shadowedPromiseTimer) duration = number(call.arguments[1]);
+ else if (REAL_WAIT_NAMES.has(name) && !shadowedPromiseTimer) duration = number(call.arguments[0]);
else {
if (!ts.isIdentifier(call.expression)) continue;
const bound = binding(call.expression);
@@ -417,11 +451,11 @@ function timerStateAt(index, timerEvents, scopes) {
return fake;
}
-function countRealWaits(code, lines) {
+function countRealWaits(code, lines, sourceCode = code) {
const timerEvents = [...code.matchAll(/\bvi\.(useFakeTimers|useRealTimers)\s*\(/g)];
const scopes = timerEvents.length > 0 ? timerScopes(code, timerEvents) : [];
let count = 0;
- const waits = staticWaitCalls(code).sort((a, b) => a.index - b.index);
+ const waits = staticWaitCalls(sourceCode).sort((a, b) => a.index - b.index);
for (const wait of waits) {
if (timerStateAt(wait.index, timerEvents, scopes)) continue;
if (wait.duration < REAL_WAIT_MIN_MS) continue;
@@ -704,7 +738,7 @@ export function scanTestSource(source, { isGuard = false } = {}) {
const lines = source.split(/\r?\n/);
const executableCode = maskStrings(code);
const resetModules = countModuleResets(executableCode, lines);
- const realWaits = countRealWaits(executableCode, lines);
+ const realWaits = countRealWaits(executableCode, lines, code);
let sourceReads = 0;
if (!isGuard && /\breadFileSync\b|\breadFile\s*\(|\?raw/.test(code)) {
const sourceReadHelpers = findSourceReadHelpers(code);
@@ -784,9 +818,50 @@ const HINTS = {
sourceReads: '普通单测不得读取源码文本做字面量断言;改为经生产入口验证行为,纯跨文件契约移入对应包的 guard tier',
};
+function parseBaseline(text, label) {
+ let body;
+ try { body = JSON.parse(text); } catch { throw new Error('invalid baseline JSON: ' + label); }
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
+ if (!record(body) || !record(body.files)) throw new Error('invalid baseline files: ' + label);
+ for (const [file, rules] of Object.entries(body.files)) {
+ if (!record(rules) || Object.entries(rules).some(([rule, count]) => !RULES.includes(rule) || !Number.isSafeInteger(count) || count < 0)) {
+ throw new Error('invalid baseline limits: ' + label + ' (' + file + ')');
+ }
+ }
+ return body.files;
+}
+
function readBaseline() {
if (!existsSync(BASELINE_PATH)) return {};
- return JSON.parse(readFileSync(BASELINE_PATH, 'utf8')).files ?? {};
+ return parseBaseline(readFileSync(BASELINE_PATH, 'utf8'), BASELINE_REL);
+}
+
+function readTrustedBaseline() {
+ const event = process.env.GITHUB_EVENT_PATH ? JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')) : {};
+ const remoteBase = process.env.GITHUB_BASE_REF ? 'refs/remotes/origin/' + process.env.GITHUB_BASE_REF : null;
+ const eventName = process.env.GITHUB_EVENT_NAME;
+ let ref;
+ if (eventName === 'pull_request') ref = event.pull_request?.base?.sha ?? remoteBase;
+ else if (eventName === 'merge_group') ref = event.merge_group?.base_sha;
+ else if (eventName === 'push') ref = event.before;
+ else ref = remoteBase ?? 'refs/remotes/origin/main';
+ if (!ref || /^0+$/.test(ref)) throw new Error('trusted Git base is unavailable for ' + (eventName || 'local check'));
+ const git = args => execFileSync('git', args, { cwd: ROOT, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ let commit;
+ let entry;
+ try {
+ commit = git(['rev-parse', '--verify', '--end-of-options', ref + '^{commit}']);
+ entry = git(['ls-tree', '--name-only', commit, '--', BASELINE_REL]);
+ } catch {
+ throw new Error('trusted Git base cannot be read: ' + ref);
+ }
+ // Only a successfully read commit with no baseline path is first adoption.
+ // Missing refs/history and Git failures must never silently bootstrap.
+ if (!entry) return { files: null, commit };
+ let text;
+ try { text = git(['show', commit + ':' + BASELINE_REL]); }
+ catch { throw new Error('trusted Git baseline cannot be read: ' + commit); }
+ return { files: parseBaseline(text, 'trusted ' + commit), commit };
}
function writeBaseline(files) {
@@ -799,8 +874,19 @@ function writeBaseline(files) {
}
export async function main(args = process.argv.slice(2)) {
- const counts = await scanRepository();
+ const trusted = readTrustedBaseline();
+ const hasBaseline = existsSync(BASELINE_PATH);
const baseline = readBaseline();
+ if (!hasBaseline && (trusted.files !== null || !args.includes('--update'))) throw new Error('baseline is missing: ' + BASELINE_REL);
+ if (trusted.files === null) console.log('[test-hygiene] bootstrap: trusted base ' + trusted.commit + ' has no baseline yet');
+ else {
+ const raised = compareWithBaseline(baseline, trusted.files).violations;
+ if (raised.length > 0) {
+ for (const item of raised) console.error('[test-hygiene] baseline cannot increase ' + item.file + ' ' + item.rule + ': ' + item.limit + ' -> ' + item.current);
+ return 1;
+ }
+ }
+ const counts = await scanRepository();
const { violations, tightenable } = compareWithBaseline(counts, baseline);
if (args.includes('--update')) {
// The very first run records the existing debt; afterwards --update only tightens.