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(tests): follow namespaced repository paths and retain contracts

MagicLizi3c69d742bcaa
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
index 82adb43adb..f1e80f86a1 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -198,3 +198,37 @@ describe('Plugin Market IPC error boundary', () => {
expect(bootstrapSource).toContain('syncPluginMarketForActiveOwner(30_000);');
});
});
+
+// All production cache deletions must pass the lease boundary. Keep this
+// cross-file contract in guard; cacheLease runtime behavior remains in unit.
+describe('缓存删除收口(结构门禁)', () => {
+ const sourcesDir = resolve(
+ __dirname,
+ '..',
+ 'sources',
+ );
+ // 容忍链式换行(fs.promises\n.rm(…)):否则漏数 cacheLease/git 的真实删除点。
+ const countRawDeletions = (file: string): number =>
+ [
+ ...readFileSync(resolve(sourcesDir, file), 'utf8')
+ .matchAll(/fs\s*\.\s*(?:promises\s*\.\s*)?rm(?:Sync|dir)?\s*\(/g),
+ ].length;
+
+ // 门禁扩到整个 sources/,而不只 index.ts:任一 lease 管理的文件新增直接删除点
+ // 就是又一个绕过租约守卫的口子——这正是此前每一轮返工的形态。
+ it.each(['index.ts', 'store.ts', 'discover.ts', 'parse.ts', 'preflight.ts'])(
+ 'sources/%s never deletes filesystem paths directly',
+ (file) => {
+ expect(countRawDeletions(file)).toBe(0);
+ },
+ );
+
+ it('git.ts only deletes its own private clone staging, nothing else', () => {
+ // git.ts 的唯一直接删除是它自己 clone 出的 `<dest>.staging-<uuid>` 私有目录
+ // (UUID 私有、同函数内建同函数内删、从不被租约持有),是经过审阅的例外。
+ // 断言"只删 stagingPath":出现任何删别的路径的调用都要重新确认边界。
+ const git = readFileSync(resolve(sourcesDir, 'git.ts'), 'utf8');
+ const deletions = [...git.matchAll(/\.\s*rm(?:Sync|dir)?\s*\(\s*([A-Za-z]+)/g)].map((m) => m[1]);
+ expect(deletions).toEqual(['stagingPath']);
+ });
+});
diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts
index 73311dee0e..3d3cb19f66 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts
@@ -1,9 +1,9 @@
/**
- * 市场缓存删除的**结构门禁**。
+ * 市场缓存删除租约的行为回归。
*
* 这块反复出过七八轮同一类事故:每轮都是"又发现一个删除点没查租约"——交换旧
* 目录、清理历史版本、清理暂存目录、移除来源、失败回滚,各自直接 `fs.rm`。行为
- * 用例只能覆盖已知的那几条路径;真正防止下一轮的是这里的两条约束:
+ * 用例覆盖已知路径;跨文件结构门禁由 ipcErrorBoundary.test.ts 的 guard 执行:
*
* 1. `sources/index.ts` 不得出现任何直接的文件系统删除——所有删除必须经
* `cacheLease.removeCachePath` 这个唯一入口。新增删除点会在这里失败。
@@ -13,7 +13,6 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -176,36 +175,3 @@ describe('cacheLease 删除守卫', () => {
expect(fs.existsSync(tree.version)).toBe(false);
});
});
-
-describe('缓存删除收口(结构门禁)', () => {
- const sourcesDir = path.join(
- path.dirname(fileURLToPath(import.meta.url)),
- '..',
- 'sources',
- );
- // 容忍链式换行(fs.promises\n.rm(…)):否则漏数 cacheLease/git 的真实删除点。
- const countRawDeletions = (file: string): number =>
- [
- ...fs
- .readFileSync(path.join(sourcesDir, file), 'utf8')
- .matchAll(/fs\s*\.\s*(?:promises\s*\.\s*)?rm(?:Sync|dir)?\s*\(/g),
- ].length;
-
- // 门禁扩到整个 sources/,而不只 index.ts:任一 lease 管理的文件新增直接删除点
- // 就是又一个绕过租约守卫的口子——这正是此前每一轮返工的形态。
- it.each(['index.ts', 'store.ts', 'discover.ts', 'parse.ts', 'preflight.ts'])(
- 'sources/%s never deletes filesystem paths directly',
- (file) => {
- expect(countRawDeletions(file)).toBe(0);
- },
- );
-
- it('git.ts only deletes its own private clone staging, nothing else', () => {
- // git.ts 的唯一直接删除是它自己 clone 出的 `<dest>.staging-<uuid>` 私有目录
- // (UUID 私有、同函数内建同函数内删、从不被租约持有),是经过审阅的例外。
- // 断言"只删 stagingPath":出现任何删别的路径的调用都要重新确认边界。
- const git = fs.readFileSync(path.join(sourcesDir, 'git.ts'), 'utf8');
- const deletions = [...git.matchAll(/\.\s*rm(?:Sync|dir)?\s*\(\s*([A-Za-z]+)/g)].map((m) => m[1]);
- expect(deletions).toEqual(['stagingPath']);
- });
-});
diff --git a/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts b/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
index 0684dd5d33..e1937a6dd9 100644
--- a/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
@@ -148,4 +148,27 @@ describe('Markdown target rendering contract', () => {
'scroller.scrollTop = targetRect.top - scrollerRect.top + scroller.scrollTop',
);
});
+
+ it('has the session bubbles honour the boundary they are handed', () => {
+ // SubagentsBody component tests verify the boundary at the panel seam.
+ // This guard retains propagation through the real session bubble sources.
+ const chatDir = resolve(__dirname, '../components/chat');
+ const assistant = readFileSync(resolve(chatDir, 'AssistantMessage.tsx'), 'utf8')
+ .replace(/\r\n/g, '\n');
+ // Defaulting to true is what keeps every local caller unchanged, and is
+ // also what made the omission invisible.
+ expect(assistant).toContain('allowPrivilegedLinks = true');
+ // Both bodies: the streamed one and the settled one.
+ expect([...assistant.matchAll(/allowPrivilegedLinks=\{allowPrivilegedLinks\}/g)].length)
+ .toBeGreaterThanOrEqual(3);
+
+ const user = readFileSync(resolve(chatDir, 'UserMessage.tsx'), 'utf8')
+ .replace(/\r\n/g, '\n');
+ expect(user).toContain('allowPrivilegedLinks = true');
+ // A remote author's @-chip must not resolve against this filesystem: the
+ // click handler is withheld, which is the inert chip shape the component
+ // already uses for a collapsed long message.
+ expect(user).toContain('longMessageCollapsed || !allowPrivilegedLinks');
+ expect(user).toContain('allowPrivilegedLinks\n ? async (abs, name, chip)');
+ });
});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx
index 9ee2a938b2..033c2685d3 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx
@@ -1,8 +1,6 @@
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { readFileSync } from 'node:fs';
-import path from 'node:path';
import { act } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type {
@@ -358,31 +356,6 @@ describe('SubagentsBody', () => {
}
});
- it('has the session bubbles honour the boundary they are handed', () => {
- // The two tests above stop at the component seam, because the stubs replace
- // exactly the components that would carry the flag further. Asserted on the
- // source instead — same approach as `markdownTargetRendererContract` — so
- // the panel's boundary cannot be silently dropped one level down.
- const chatDir = path.resolve(__dirname, '../../../../../components/chat');
- const assistant = readFileSync(path.join(chatDir, 'AssistantMessage.tsx'), 'utf8')
- .replace(/\r\n/g, '\n');
- // Defaulting to true is what keeps every local caller unchanged, and is
- // also what made the omission invisible.
- expect(assistant).toContain('allowPrivilegedLinks = true');
- // Both bodies: the streamed one and the settled one.
- expect([...assistant.matchAll(/allowPrivilegedLinks=\{allowPrivilegedLinks\}/g)].length)
- .toBeGreaterThanOrEqual(3);
-
- const user = readFileSync(path.join(chatDir, 'UserMessage.tsx'), 'utf8')
- .replace(/\r\n/g, '\n');
- expect(user).toContain('allowPrivilegedLinks = true');
- // A remote author's @-chip must not resolve against this filesystem: the
- // click handler is withheld, which is the inert chip shape the component
- // already uses for a collapsed long message.
- expect(user).toContain('longMessageCollapsed || !allowPrivilegedLinks');
- expect(user).toContain('allowPrivilegedLinks\n ? async (abs, name, chip)');
- });
-
it('reloads the selected detail when a run change is pushed', async () => {
render(
<SubagentsBody
diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjs
index 15cc7c80f2..d2ec962727 100644
--- a/scripts/__tests__/check-test-hygiene.test.mjs
+++ b/scripts/__tests__/check-test-hygiene.test.mjs
@@ -320,6 +320,16 @@ test("scanTestSource counts only unjustified hits for each rule", () => {
"const agentsRoot = resolve(\n __dirname, '..',\n); const mainRoot = join(\n agentsRoot, 'main',\n); const source = readFileSync(resolve(mainRoot, 'index.ts'), 'utf8');",
{ sourceReads: 1 },
],
+ [
+ "namespace path factories retain derived repository anchors",
+ "import path from 'node:path';\nconst agentsRoot = path.resolve(__dirname, '..');\nconst mainRoot = path['join'](agentsRoot, 'main');\nconst source = readFileSync(path.resolve(mainRoot, 'index.ts'), 'utf8');",
+ { sourceReads: 1 },
+ ],
+ [
+ "namespace factories do not make temporary fixture paths repository-derived",
+ "import * as path from 'node:path';\nconst fixtureRoot = path.resolve(tmpdir(), 'fixture');\nconst source = readFileSync(path.join(fixtureRoot, 'index.ts'), 'utf8');",
+ { sourceReads: 0 },
+ ],
[
"semicolon-free fixture declarations do not absorb a later repository anchor",
"const fixtureRoot = mkdtempSync(join(tmpdir(), 'fixture-'))\nconst agentsRoot = resolve(\n __dirname, '..',\n)\nconst source = readFileSync(resolve(fixtureRoot, 'index.ts'), 'utf8');",
@@ -355,8 +365,19 @@ test("repository scan grants source exemptions only to explicit script contracts
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);");
+ const designContracts = ["design-inventory.test.mjs", "glossary-rules.test.mjs", "hardcoded-color-audit.test.mjs"];
+ for (const file of designContracts) fs.writeFileSync(path.join(root, "scripts", "__tests__", file),
+ appRead + "vi.resetModules(); setTimeout(done, 100);");
+ const dbDir = path.join(root, "apps", "desktop", "src", "main", "localDb", "__tests__");
+ fs.mkdirSync(dbDir, { recursive: true });
+ fs.writeFileSync(path.join(dbDir, "migrationCompatibility.test.ts"),
+ appRead + "vi.resetModules(); setTimeout(done, 100);");
+ fs.writeFileSync(path.join(dbDir, "ordinary.test.ts"), appRead);
assert.deepEqual(await scanRepository(root), {
+ "apps/desktop/src/main/localDb/__tests__/migrationCompatibility.test.ts": { resetModules: 1, realWaits: 1, sourceReads: 0 },
+ "apps/desktop/src/main/localDb/__tests__/ordinary.test.ts": { resetModules: 0, realWaits: 0, sourceReads: 1 },
"scripts/__tests__/dev-docs-contract.test.mjs": { resetModules: 1, realWaits: 1, sourceReads: 0 },
+ ...Object.fromEntries(designContracts.map(file => ["scripts/__tests__/" + file, { 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 },
});
diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjs
index 229b29d7fd..3c2c44ac30 100644
--- a/scripts/check-test-hygiene.mjs
+++ b/scripts/check-test-hygiene.mjs
@@ -43,6 +43,12 @@ const ROOT_SOURCE_CONTRACTS = new Map([
['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'],
+ // Design inventory must agree with production entry points and shared matchers.
+ ['scripts/__tests__/design-inventory.test.mjs', 'design inventory cross-file contracts'],
+ // Locale declarations and diagnostic prose implement the terminology policy.
+ ['scripts/__tests__/glossary-rules.test.mjs', 'locale and terminology policy contracts'],
+ // Approved design exceptions are bound to exact production declarations.
+ ['scripts/__tests__/hardcoded-color-audit.test.mjs', 'design exemption and CI 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.
@@ -50,6 +56,11 @@ const ROOT_SOURCE_CONTRACTS = new Map([
// Packaged notice generation and both application entry points must stay wired.
['scripts/__tests__/third-party-notices.test.mjs', 'cross-platform bundled license contracts'],
]);
+// This explicit DB-tier suite uses frozen companion bytes as input to real
+// hash/manifest repair, not source-spelling assertions. Keep reload/wait checks.
+const DB_SOURCE_INPUTS = new Set([
+ 'apps/desktop/src/main/localDb/__tests__/migrationCompatibility.test.ts',
+]);
// 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));
@@ -773,7 +784,7 @@ function findRepoAnchorNames(code) {
const declarations = [];
const collect = node => {
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
- declarations.push({ name: node.name.text, rhs: node.initializer.getText(source) });
+ declarations.push({ name: node.name.text, initializer: node.initializer });
}
ts.forEachChild(node, collect);
};
@@ -782,9 +793,16 @@ function findRepoAnchorNames(code) {
let changed = true;
while (changed) {
changed = false;
- for (const { name, rhs } of declarations) {
+ for (const { name, initializer } of declarations) {
+ const rhs = initializer.getText(source);
const identifiers = rhs.match(/\b[A-Za-z_$][\w$]*\b/g) ?? [];
- const pathFactory = /^\s*(?:new\s+)?(?:resolve|join|URL)\s*\(/.test(rhs);
+ let call = initializer;
+ while (ts.isParenthesizedExpression(call) || ts.isAsExpression(call) || ts.isNonNullExpression(call)) call = call.expression;
+ const callee = ts.isCallExpression(call) || ts.isNewExpression(call) ? call.expression : null;
+ const factoryName = callee && (ts.isIdentifier(callee) ? callee.text
+ : ts.isPropertyAccessExpression(callee) ? callee.name.text
+ : ts.isElementAccessExpression(callee) && ts.isStringLiteral(callee.argumentExpression) ? callee.argumentExpression.text : null);
+ const pathFactory = /^(?:resolve|join|URL)$/.test(factoryName ?? '');
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)))
@@ -1270,9 +1288,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('/');
- // 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) });
+ // Only explicitly registered contracts or frozen DB inputs may inspect
+ // application source; their reload/wait rules still run, like guard suites.
+ const result = scanTestSource(readFileSync(file, 'utf8'), { isGuard: guard.has(rel) || ROOT_SOURCE_CONTRACTS.has(rel) || DB_SOURCE_INPUTS.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.json
index 9ce0c2c674..7e6bccd993 100644
--- a/scripts/test-hygiene-baseline.json
+++ b/scripts/test-hygiene-baseline.json
@@ -662,9 +662,6 @@
"apps/desktop/src/renderer/__tests__/markdownStrikethrough.test.ts": {
"sourceReads": 1
},
- "apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts": {
- "sourceReads": 3
- },
"apps/desktop/src/renderer/__tests__/memorySettingsStore.test.ts": {
"resetModules": 1
},
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index 37e2f407d9..b989d0d9bc 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -217,6 +217,10 @@ const desktopGuardInclude = [
'src/renderer/__tests__/orcaModelWindowSelection.test.ts',
'src/renderer/__tests__/markdownRendererXdtAudio.test.ts',
'src/renderer/__tests__/markdownDiffBlock.test.ts',
+ // Cross-file entry isolation and privileged-link propagation contracts;
+ // component rendering and cache-lease behavior remain in the unit tier.
+ 'src/renderer/__tests__/resourceUsageEntryIsolation.test.ts',
+ 'src/renderer/__tests__/markdownTargetRendererContract.test.ts',
'src/renderer/__tests__/bulkSessionStatusRouting.test.ts',
'src/renderer/__tests__/homeUsageDashboardSource.test.ts',
'src/renderer/features/plugin/__tests__/unreadDotMotion.test.ts',