Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(test): close source-read bypasses and isolate guard workers
MagicLizib7d9e3eebe2a
diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex f4fc4e7db5..a5f9f50c0c 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -74,6 +74,13 @@ Linux 及 package script 的启动方式不变。回归测试通过真实 runner保留接收者类型信息。独立核实全部 2,238 个根文件、2,297 个 Program 文件及 6 个有类型身份的发送位置完全一致,未改检查器、违规判定或超时。一次本机独立进程对照为 6.93→6.10 秒;这只是解析成本对照,CI 并发下是否解决超时仍由新 head 验证。+head `968677d3b7` 的 CI 仍在 15.20 秒触发同一限制。该轮日志显示 Desktop 与+Mobile guard 的默认 worker 池重叠运行约 20 秒;独立单进程 profile 保留全部根文件、+真实 checker 与 6 个发送位置,总计 5.25 秒、RSS 约 1 GiB,主要成本为解析和绑定。+现在 Desktop guard 复用既有 `exclusive` 屏障并限制为 1 个 worker,避免跨 workspace+和 Desktop 文件间争用,所有必需 guard 与原 15 秒限制不变。真实 manifest→计划→+调度回归在旧配置下因重叠失败,新配置通过;没有据此声称 CPU 是唯一原因,最终+CI 仍须重新通过。随后补齐 Promise 定时器的首参数时长、导入别名与遮蔽判定;基线逐文件、逐规则与可信 Git 基准比较,拒绝同一提交手改抬高额度,缺失基准或格式错误均失败。真实临时 Git@@ -83,6 +90,12 @@ Linux 及 package script 的启动方式不变。回归测试通过真实 runner模块重载检测同样按 Vitest 绑定追踪解构、赋值与 namespace 别名,并检查 hook 及其本地准备/清理函数;同名参数和非 Vitest 对象不会误判。既有账号用量初始化回归改为带明确理由的单次直接重载,原 34 项通过(约 0.7 秒),不新增逐用例重载。+源码读取也按真实 fs 绑定跟踪别名、namespace、Promise API 和静态解构,保留本地+同名 wrapper 与执行源码的行为 harness,屏蔽局部遮蔽及 fixture 字符串中的伪代码。+取消 `scripts/` 的目录级豁免,只按完整路径登记 5 份已有跨文件契约并写明理由;+其模块重载与真实等待规则仍适用,新普通脚本测试读取应用源码会失败。扫描器自测+4 项约 2.4 秒,全仓 AST 扫描约 20 秒(比最初的文本扫描成本更高)。通过 `--update`+只删除 zero-wiring 内嵌 fixture 造成的 8 次误报,基线从 375 收紧为 374 个文件。导入设置恢复真实组件挂载回归,验证首次自动扫描与重入时先显示缓存、再更新结果,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 cc48585380..619567c23b 100644--- a/scripts/__tests__/check-test-hygiene.test.mjs+++ b/scripts/__tests__/check-test-hygiene.test.mjs@@ -4,6 +4,7 @@import assert from "node:assert/strict";import { execFileSync, spawnSync } from "node:child_process";import fs from "node:fs";+import { createRequire } from "node:module";import os from "node:os";import path from "node:path";import test from "node:test";@@ -185,6 +186,31 @@ test("scanTestSource counts only unjustified hits for each rule", () => {{ sourceReads: 0 },],["workspace cwd source", "readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8');", { sourceReads: 1 }],+ // PR #6196: aliases must reach the same source-read decision as the real+ // fs API, while lexical shadows and executable-source harnesses stay valid.+ // Minimal unit inputs exercise scanTestSource directly; no files are read.+ ["named fs read alias", "import { readFileSync as readText } from 'node:fs'; readText(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["namespace and function aliases", "import * as files from 'fs'; const disk = files; const load = disk.readFileSync; load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["promise fs named read alias", "import { readFile as load } from 'node:fs/promises'; await load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["promise namespace destructuring", "import files from 'fs/promises'; const { readFile: load } = files; await load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["fs promises export alias", "import { promises as files } from 'node:fs'; const { readFile: load } = files; await load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["fs promises property", "import files from 'node:fs'; const load = files.promises['readFile']; await load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["nested fs promises destructuring", "import fs from 'node:fs'; const { promises: { readFile } } = fs; const source = await readFile(new URL('../Component.tsx', import.meta.url)); expect(source).toContain('className');", { sourceReads: 1 }],+ ["CommonJS destructured fs alias", "const { readFileSync: load } = require('node:fs'); load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["dynamic import destructured fs alias", "const { readFileSync: load } = await import('node:fs'); load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["dynamic import promise namespace alias", "const files = await import('node:fs/promises'); const load = files.readFile; await load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["assigned fs read alias", "import files from 'node:fs'; let load; ({ readFileSync: load } = files); load(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["read alias parameter shadow", "import { readFileSync as load } from 'node:fs'; function check(load) { load(new URL('../Component.tsx', import.meta.url)); }", { sourceReads: 0 }],+ ["fs namespace method parameter shadow", "import files from 'node:fs'; const check = { run(files) { files.readFileSync(new URL('../Component.tsx', import.meta.url)); } };", { sourceReads: 0 }],+ ["local read-shaped helper is not fs", "function readFileSync(value) { return value; } readFileSync(new URL('../Component.tsx', import.meta.url));", { sourceReads: 0 }],+ ["local read-shaped wrapper forwards to fs", "import fs from 'node:fs'; function readFileSync(file) { return fs.readFileSync(file, 'utf8'); } readFileSync(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["block arrow read-shaped wrapper forwards to fs", "import fs from 'node:fs'; const readFileSync = file => { return fs.readFileSync(file, 'utf8'); }; readFileSync(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["function expression read-shaped wrapper forwards to fs", "import fs from 'node:fs'; const readFileSync = function(file) { return fs.readFileSync(file, 'utf8'); }; readFileSync(new URL('../Component.tsx', import.meta.url));", { sourceReads: 1 }],+ ["another module's read API is not fs", "import { readFileSync } from 'test-double'; readFileSync(new URL('../Component.tsx', import.meta.url));", { sourceReads: 0 }],+ ["alias helper reads production source", "import { readFileSync as load } from 'node:fs'; const read = (relative: string) => load(resolve(__dirname, relative), 'utf8'); read('../Component.tsx');", { sourceReads: 1 }],+ ["aliased read follows execution exemption", "import { readFileSync as load } from 'node:fs'; const source = load(new URL('../Component.tsx', import.meta.url)); expect(new Function(source)()).toBe(true);", { sourceReads: 0 }],+ ["aliased read keeps mixed text assertion", "import { readFileSync as load } from 'node:fs'; const source = load(new URL('../Component.tsx', import.meta.url)); new Function(source)(); expect(source).toContain('return true');", { sourceReads: 1 }],+ ["embedded source code is only a fixture string", String.raw`const example = "readFileSync(new URL('../Component.tsx', import.meta.url));";`, { sourceReads: 0 }],["cwd fixture stays test data", "readFileSync(resolve(process.cwd(), 'fixtures/helper.ts'), 'utf8');", { sourceReads: 0 }],["executed source is a behavior harness", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); const run = new Function(source); expect(run()).toBe(true);", { sourceReads: 0 }],["a local factory returns executed behavior", "const source = readFileSync(resolve(process.cwd(), 'src/helper.ts'), 'utf8'); function make(code) { return new Function(code); } const run = make(source); expect(run()).toBe(true);", { sourceReads: 0 }],@@ -252,15 +278,24 @@ test("scanTestSource counts only unjustified hits for each rule", () => {);});-test("repository scan covers runner performance without rejecting its source contracts", async () => {+test("repository scan grants source exemptions only to explicit script contracts", async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-hygiene-scan-"));try {fs.mkdirSync(path.join(root, "scripts", "__tests__"), { recursive: true });fs.writeFileSync(path.join(root, "scripts", "test-workspaces.config.mjs"), "export default { workspaces: [] };");fs.writeFileSync(path.join(root, "scripts", "__tests__", "runner.test.mjs"),"vi.resetModules(); setTimeout(done, 100); readFileSync(resolve(__dirname, '../runner.mjs'));");+ // PR #6196: a new ordinary scripts test must not bypass the unit rule+ // by its directory. The registered docs/CI contract retains only the+ // source exemption; module reloads and real waits must still be rejected.+ const appRead = "import { readFileSync as readText } from 'node:fs'; readText(new URL('../../apps/desktop/src/Component.tsx', import.meta.url));";+ fs.writeFileSync(path.join(root, "scripts", "__tests__", "ordinary.test.mjs"), appRead);+ fs.writeFileSync(path.join(root, "scripts", "__tests__", "dev-docs-contract.test.mjs"),+ appRead + "vi.resetModules(); setTimeout(done, 100);");assert.deepEqual(await scanRepository(root), {- "scripts/__tests__/runner.test.mjs": { resetModules: 1, realWaits: 1, sourceReads: 0 },+ "scripts/__tests__/dev-docs-contract.test.mjs": { resetModules: 1, realWaits: 1, sourceReads: 0 },+ "scripts/__tests__/ordinary.test.mjs": { resetModules: 0, realWaits: 0, sourceReads: 1 },+ "scripts/__tests__/runner.test.mjs": { resetModules: 1, realWaits: 1, sourceReads: 1 },});} finally {fs.rmSync(root, { recursive: true, force: true });@@ -295,7 +330,11 @@ test("compareWithBaseline only lets counts stay or shrink", () => {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: "" };+ // The copied CLI still uses Desktop's declared TypeScript parser; make that+ // existing dependency available in this deliberately dependency-free repo.+ const requireDesktop = createRequire(new URL("../../apps/desktop/package.json", import.meta.url));+ const parserModules = path.dirname(path.dirname(path.dirname(requireDesktop.resolve("typescript"))));+ const environment = { ...process.env, CI: "", GITHUB_EVENT_PATH: "", GITHUB_EVENT_NAME: "", GITHUB_BASE_REF: "", GITHUB_SHA: "", NODE_PATH: parserModules };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"); };diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex 9c356b6de2..3dc136d069 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -956,7 +956,7 @@ test("planRuns includes manual tiers only for explicit tier runs", () => {assert.equal(planRuns(workspaces, { tier: "db", explicit: false }).length, 0);});-test("planRuns includes the required source-contract guard tiers", () => {+test("planRuns keeps required guard tiers from competing with the typed-send scan", async () => {const runs = planRuns(manifest.workspaces, { tier: "guard" });assert.deepEqual(runs.map((run) => [run.workspace.cwd, run.tier]),@@ -965,6 +965,21 @@ test("planRuns includes the required source-contract guard tiers", () => {["apps/mobile", "guard"],],);+ // PR #6196: CI ran both default CPU-sized pools beside the 1 GiB TS+ // Program and twice hit its existing 15s limit. Use the real manifest and+ // scheduler: two guard runs plus one microtask must never overlap Desktop.+ // This observes scheduling, not source text or host-dependent timings.+ let active = 0;+ await runWithExclusiveBarriers(runs, 2, async (run) => {+ assert.equal(active, 0, "Desktop's runtime guard must have the workspace budget");+ active += 1;+ await Promise.resolve();+ active -= 1;+ if (run.workspace.cwd === "apps/desktop") {+ assert.ok(run.tierConfig.command.args.includes("--maxWorkers=1"),+ "other Desktop guards must not compete with the TypeScript Program");+ }+ });});test("filterRunsByWorkspace selects by manifest name or cwd and supports exclude", () => {diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjsindex ed0b5a9999..6536501c3a 100644--- a/scripts/check-test-hygiene.mjs+++ b/scripts/check-test-hygiene.mjs@@ -36,6 +36,20 @@ const NON_UNIT_TEST = /(?:^|[-.])(?:integration|e2e|git-integration)\.(?:test|spexport const RULES = ['resetModules', 'realWaits', 'sourceReads'];const REAL_WAIT_MIN_MS = 100;const REAL_WAIT_NAMES = new Set(['sleep', 'delay', 'wait', 'waitMs', 'pause']);+// These exact root-runner suites own cross-file contracts that cannot execute+// the full application in node:test. New scripts tests receive no exemption.+const ROOT_SOURCE_CONTRACTS = new Map([+ // TS brand identity and executable/userData names mirrored by build scripts.+ ['scripts/__tests__/brand-identity-sync.test.mjs', 'cross-runtime brand identity'],+ // Documented commands, required CI gates and locale-aware QA artifact wiring.+ ['scripts/__tests__/dev-docs-contract.test.mjs', 'developer/CI and QA artifact contracts'],+ // Dev startup must prepare every supported Agent runtime before it can launch.+ ['scripts/__tests__/ensure-agent-binaries.test.mjs', 'runtime preparation startup wiring'],+ // Restart scripts and app bootstrap must agree on isolation/process boundaries.+ ['scripts/__tests__/restart-desktop-remote.test.mjs', 'restart and bootstrap isolation contracts'],+ // Packaged notice generation and both application entry points must stay wired.+ ['scripts/__tests__/third-party-notices.test.mjs', 'cross-platform bundled license contracts'],+]);// Reuse Desktop's declared parser to locate test/hook callbacks and local helpers.// No type checking or module loading is needed.const requireDesktop = createRequire(new URL('../apps/desktop/package.json', import.meta.url));@@ -569,6 +583,158 @@ 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/;+/** 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.+ */+function normalizeSourceReads(code) {+ const ts = typescript ??= requireDesktop('typescript');+ const source = parseTestSource(ts, code);+ const scopes = new WeakMap();+ const calls = [];+ const writes = new Map();+ const isFunction = node => ts.isFunctionLike(node) && Boolean(node.body);+ function declare(name, declaration, scope) {+ if (ts.isIdentifier(name)) scope.bindings.set(name.text, declaration);+ else for (const element of name.elements) {+ if (ts.isBindingElement(element)) declare(element.name, element, scope);+ }+ }+ 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) || ts.isCatchClause(node)) scope = { parent: scope, bindings: new Map() };+ scopes.set(node, scope);+ if (isFunction(node)) {+ if (node.name && (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node))) scope.bindings.set(node.name.text, node);+ for (const parameter of node.parameters) declare(parameter.name, parameter, scope);+ }+ if (ts.isVariableDeclaration(node)) declare(node.name, node, scope);+ if (ts.isImportSpecifier(node) || ts.isNamespaceImport(node) || ts.isImportClause(node) && node.name) scope.bindings.set(node.name.text, node);+ if (ts.isCallExpression(node)) calls.push(node);+ ts.forEachChild(node, child => collect(child, scope));+ }+ collect(source, null);+ function binding(identifier) {+ for (let scope = scopes.get(identifier); scope; scope = scope.parent) {+ if (scope.bindings.has(identifier.text)) return scope.bindings.get(identifier.text);+ }+ return null;+ }+ function unwrap(node) {+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isNonNullExpression(node) || ts.isAwaitExpression(node)) node = node.expression;+ return node;+ }+ const propertyName = node => node && (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) ? node.text : null;+ function recordWrite(target, expression, property = null) {+ target = unwrap(target);+ if (ts.isIdentifier(target)) {+ const bound = binding(target);+ if (bound) writes.set(bound, [...(writes.get(bound) ?? []), { expression, property }]);+ } else if (ts.isObjectLiteralExpression(target)) {+ for (const member of target.properties) {+ if (ts.isShorthandPropertyAssignment(member)) recordWrite(member.name, expression, member.name.text);+ else if (ts.isPropertyAssignment(member)) recordWrite(member.initializer, expression, propertyName(member.name));+ }+ }+ }+ function collectWrites(node) {+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) recordWrite(node.left, node.right);+ ts.forEachChild(node, collectWrites);+ }+ collectWrites(source);+ function propertyMatches(expression, property, kind, seen) {+ return kind === 'promises' && property === 'promises' && matches(expression, 'fs', seen)+ || kind === 'read' && (property === 'readFileSync' && matches(expression, 'fs', seen)+ || property === 'readFile' && (matches(expression, 'fs', seen) || matches(expression, 'promises', seen)));+ }+ function boundMatches(bound, kind, seen) {+ if (!bound || seen.has(bound)) return false;+ seen = new Set(seen).add(bound);+ let declaration = bound;+ while (declaration && !ts.isImportDeclaration(declaration)) declaration = declaration.parent;+ const module = declaration && !declaration.importClause?.isTypeOnly && !bound.isTypeOnly+ && ts.isStringLiteral(declaration.moduleSpecifier) ? declaration.moduleSpecifier.text : '';+ if (/^(?:node:)?fs(?:\/promises)?$/.test(module)) {+ const namespace = module.endsWith('/promises') ? 'promises' : 'fs';+ if (ts.isNamespaceImport(bound) || ts.isImportClause(bound)) return kind === namespace;+ if (ts.isImportSpecifier(bound)) {+ const name = bound.propertyName?.text ?? bound.name.text;+ return kind === 'read' && (name === 'readFile' || namespace === 'fs' && name === 'readFileSync')+ || kind === 'promises' && namespace === 'fs' && name === 'promises';+ }+ }+ if (ts.isBindingElement(bound) && ts.isObjectBindingPattern(bound.parent) && !bound.dotDotDotToken) {+ const owner = bound.parent.parent;+ const property = propertyName(bound.propertyName ?? bound.name);+ if (ts.isVariableDeclaration(owner) && owner.initializer && propertyMatches(owner.initializer, property, kind, seen)) return true;+ if (ts.isBindingElement(owner) && propertyMatches(owner, property, kind, seen)) return true;+ if ((writes.get(owner) ?? []).some(write => !write.property && propertyMatches(write.expression, property, kind, seen))) return true;+ }+ if (ts.isVariableDeclaration(bound) && bound.initializer && matches(bound.initializer, kind, seen)) return true;+ return (writes.get(bound) ?? []).some(write => write.property+ ? propertyMatches(write.expression, write.property, kind, seen) : matches(write.expression, kind, seen));+ }+ function matches(node, kind, seen = new Set()) {+ node = unwrap(node);+ if (ts.isBindingElement(node)) return boundMatches(node, kind, seen);+ if (ts.isIdentifier(node)) {+ const bound = binding(node);+ return bound ? boundMatches(bound, kind, seen)+ : kind === 'read' && /^(?:readFileSync|readFile)$/.test(node.text);+ }+ if (ts.isPropertyAccessExpression(node)) return propertyMatches(node.expression, node.name.text, kind, seen);+ if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression)) return propertyMatches(node.expression, node.argumentExpression.text, kind, seen);+ if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword+ || ts.isIdentifier(node.expression) && node.expression.text === 'require' && !binding(node.expression))) {+ const module = node.arguments[0];+ return module && ts.isStringLiteral(module) && /^(?:node:)?fs(?:\/promises)?$/.test(module.text)+ && kind === (module.text.endsWith('/promises') ? 'promises' : 'fs');+ }+ return false;+ }+ const wrapperReads = new WeakMap();+ function localReadWrapper(bound) {+ const value = bound && ts.isVariableDeclaration(bound) ? bound.initializer : bound;+ const fn = value && unwrap(value);+ if (!fn || !isFunction(fn)) return false;+ if (!wrapperReads.has(fn)) wrapperReads.set(fn, calls.some(call => {+ if (!matches(call.expression, 'read')) return false;+ for (let owner = call.parent; owner; owner = owner.parent) {+ if (isFunction(owner)) return owner === fn;+ }+ return false;+ }));+ return wrapperReads.get(fn);+ }+ const edits = [];+ for (const call of calls) {+ const expression = call.expression;+ const name = ts.isIdentifier(expression) ? expression.text+ : ts.isPropertyAccessExpression(expression) ? expression.name.text : '';+ // Retain the old read-shaped wrapper behavior for all local function forms,+ // but a same-named passthrough or shadow must not masquerade as an fs read.+ const actualRead = matches(expression, 'read') || /^(?:readFileSync|readFile)$/.test(name)+ && ts.isIdentifier(expression) && localReadWrapper(binding(expression));+ if (actualRead && /^(?:readFileSync|readFile)$/.test(name)) continue;+ if (actualRead || /^(?:readFileSync|readFile)$/.test(name)) {+ edits.push({ start: expression.getStart(source), end: expression.end, text: actualRead ? 'readFileSync' : '__nonFsRead' });+ }+ }+ for (const edit of edits.sort((a, b) => b.start - a.start)) code = code.slice(0, edit.start) + edit.text + code.slice(edit.end);+ const normalizedSource = edits.length ? parseTestSource(ts, code) : source;+ const literals = [];+ function collectLiterals(node) {+ if (ts.isStringLiteralLike(node)) {+ const literal = [node.getText(normalizedSource), null, node.text];+ literal.index = node.getStart(normalizedSource);+ literals.push(literal);+ }+ ts.forEachChild(node, collectLiterals);+ }+ collectLiterals(normalizedSource);+ return { code, literals };+}+function findEnclosingReadCall(code, index, pattern = /\breadFile(?:Sync)?\s*\(/g) {const starts = [...code.matchAll(pattern)];for (let n = starts.length - 1; n >= 0; n -= 1) {@@ -836,12 +1002,13 @@ export function scanTestSource(source, { isGuard = false } = {}) {const resetModules = countModuleResets(code, lines);const realWaits = countRealWaits(executableCode, lines, code);let sourceReads = 0;- if (!isGuard && /\breadFileSync\b|\breadFile\s*\(|\?raw/.test(code)) {- const sourceReadHelpers = findSourceReadHelpers(code);- const executablePaths = /\bFunction\b|\brunIn(?:New)?Context\b/.test(code) ? executedSourcePaths(code) : new Set();- for (const match of code.matchAll(/(['"`])([^'"`\n$]+)\1/g)) {+ if (!isGuard && /\breadFile(?:Sync)?\b|\?raw/.test(code)) {+ const normalized = normalizeSourceReads(code);+ const sourceReadHelpers = findSourceReadHelpers(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(code, match, sourceReadHelpers)) sourceReads += 1;+ if (match[2].endsWith('?raw') || isSourcePathLiteral(normalized.code, match, sourceReadHelpers)) sourceReads += 1;}}return { resetModules, realWaits, sourceReads };@@ -882,9 +1049,9 @@ export async function scanRepository(root = ROOT) {const counts = {};for (const file of files.sort()) {const rel = path.relative(root, file).split(path.sep).join('/');- // Root runner tests are a dedicated infrastructure/contract tier. Their- // source contracts remain valid; the performance rules still apply.- const result = scanTestSource(readFileSync(file, 'utf8'), { isGuard: guard.has(rel) || rel.startsWith('scripts/') });+ // Only explicitly registered contracts may inspect application source;+ // their reload/wait rules still run, just like workspace guard suites.+ const result = scanTestSource(readFileSync(file, 'utf8'), { isGuard: guard.has(rel) || ROOT_SOURCE_CONTRACTS.has(rel) });if (RULES.some((rule) => result[rule] > 0)) counts[rel] = result;}return counts;diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.jsonindex 098fe67142..4a6930cefb 100644--- a/scripts/test-hygiene-baseline.json+++ b/scripts/test-hygiene-baseline.json@@ -1044,9 +1044,6 @@"apps/mobile/src/debug/localDiagnostics.test.ts": {"resetModules": 1},- "packages/design-tokens/src/__tests__/zero-wiring.test.ts": {- "sourceReads": 8- },"packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts": {"sourceReads": 1},diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex aa4671683d..73083595cb 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -396,7 +396,11 @@ export default {guard: {status: 'required',coverage: 'allowlist',- command: vitestBin('run'),+ // The typed-send guard builds a ~1 GiB TypeScript Program. Give it+ // the workspace budget and keep other Desktop files out of its CPU+ // slot rather than letting two default-sized guard pools contend.+ execution: 'exclusive',+ command: vitestBin('run', '--maxWorkers=1'),include: ['src/main/__tests__/directSessionSendGuard.test.ts','src/main/__tests__/makerSendToSessionOrdering.test.ts',