🛡️ Enforce presentation and persistence dependency layers

This commit is contained in:
d-robotics 2026-10-21 23:48:17 +08:00
parent 571fbc1c3f
commit 01eed76937
4 changed files with 272 additions and 1 deletions

View File

@ -73,3 +73,19 @@ BROWSER_EXECUTABLE="/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Ed
## 第二阶段实施
2026-10-21 已继续完成保存协调与共享切片编辑会话的本地改造,见[实现与兼容性记录](annotation-persistence.md)。第一阶段看板配置不扩展到任务写入。
## 2026-10-21 分层依赖自动检查
保存协调、切片编辑会话、任务池、正式决定和审核草稿的分层已经分别落地,见同目录的 `annotation-persistence.md`、`annotation-pool-loading.md`、`review-decision-coordination.md` 和 `review-draft-persistence.md`。本轮把已拆出的部分职责约束加入 `npm run lint:architecture`,并由 `lint:web` 执行;现有本地提交钩子与发布流程调用 `lint:web`,因此无需另设发布入口。
检查复用项目已安装的 TypeScript AST,不新增依赖:
- 看板展示层只允许现有展示文件与 React、图标、Zod 依赖;业务数据 hook、HTTP 客户端、其他页面、别名导入与其他包不在允许范围内。
- 五个已拆出的协议入口(标注保存、切片会话、审核草稿、正式决定、决定完成协调)递归检查本地 `src/lib` 帮助模块,拒绝 React、业务 HTTP、页面等依赖,避免通过间接帮助模块重新耦合。
- 检查静态 import、export-from、类型导入、动态 import、require 及 module.require;Vite glob 加载因无法逐一静态确认而阻断。协议模块内 JSX 的隐式 React 依赖也阻断。无法静态确定的模块加载、同名不同扩展造成的解析歧义、缺失文件、未解析依赖和语法错误阻断;报告具体文件、行号与依赖链。循环依赖遍历会终止,不因循环漏掉其他分支。
这是当前已分层模块的导入规则,不是整个仓库已完成分层,也不是恶意代码检测或运行时沙箱。直接使用浏览器全局、CSS 内容、回调中夹带业务行为等仍须代码审阅和行为回归;agent 继续只能提交受严格 schema 校验的展示文档。添加新依赖或扩大保护范围时,应根据实际职责调整规则和测试,不加通用豁免。
本轮无应用运行时代码、接口、Mongo、工作流、分类或交付格式变化,不涉及在途任务迁移。10 组回归覆盖正常依赖图以及违规直接/间接导入、动态加载、类型导入、循环、缺失文件、解析失败、扩展名歧义、glob 与隐式 JSX 依赖。独立复核指出的三处漏检已经修正并补用例。三角色看板真实 HTTP 与内存夹具的 33 项检查、4 项布局补充检查通过;全量前端仍为 13 项历史失败,零新增,14 项基线未改。发布工具、类型与格式检查通过。
本轮证据保存于工作树忽略目录 `local-data/verification/architecture-dependencies-20261021/`。未推送、未提交 PR、未部署。

View File

@ -23,7 +23,8 @@
"preview": "vite preview",
"clean": "rm -rf dist build",
"lint": "npm run lint:web && npm run lint:go && npm run lint:scripts",
"lint:web": "tsc --noEmit",
"lint:web": "tsc --noEmit && npm run lint:architecture",
"lint:architecture": "node scripts/check-frontend-architecture.mjs && node --test tests/frontend/frontend-architecture.test.mjs",
"lint:go": "bash -lc 'test -z \"$(gofmt -l cmd internal)\"'",
"lint:scripts": "bash -n scripts/*.sh scripts/lib/*.sh scripts/deploy-envs/*.env && node --check scripts/*.mjs scripts/lib/*.mjs && python3 -m py_compile scripts/*.py scripts/lib/*.py",
"format": "prettier --write \"src/**/*.{ts,tsx,css}\" \"src/services/api/*.js\" \"tests/frontend/**/*.mjs\"",

View File

@ -0,0 +1,145 @@
#!/usr/bin/env node
// A scoped dependency rule, not a sandbox for untrusted generated code.
import ts from "typescript";
import { readFileSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const presentation = new Set([
"src/features/annotation-output/DashboardPresentation.tsx",
"src/features/annotation-output/presentation.ts",
"src/features/annotation-output/presentation.css",
]);
const protocols = [
"src/lib/annotation-persistence.js",
"src/lib/slice-edit-session.js",
"src/lib/review-draft-persistence.js",
"src/lib/review-decision-controller.js",
"src/lib/review-decision-completion.js",
];
const packages = new Set(["react", "lucide-react", "zod"]);
export function checkFrontendArchitecture({
root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."),
read = (file) => readFileSync(path.join(root, file), "utf8"),
exists = (file) => {
try {
return statSync(path.join(root, file)).isFile();
} catch {
return false;
}
},
} = {}) {
const issues = [];
const visited = new Set();
function walk(file, policy, chain) {
const key = `${policy}:${file}`;
if (visited.has(key)) return;
visited.add(key);
const fail = (line, message) => issues.push({ file, line, message, chain: [...chain, file] });
let text;
try {
text = read(file);
} catch {
fail(1, "Protected module is missing or unreadable");
return;
}
if (file.endsWith(".css")) return;
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
if (source.parseDiagnostics.length) {
for (const diagnostic of source.parseDiagnostics)
fail(
source.getLineAndCharacterOfPosition(diagnostic.start ?? 0).line + 1,
`Cannot parse module: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, " ")}`,
);
return;
}
const dependency = (node, specifier) => {
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
if (!specifier || !ts.isStringLiteralLike(specifier)) {
fail(line, "Computed module loading cannot be checked; use a literal import");
return;
}
const name = specifier.text;
if (policy === "presentation" && packages.has(name)) return;
if (!name.startsWith(".")) {
fail(line, `Dependency '${name}' is outside the ${policy} layer`);
return;
}
const base = path.posix.normalize(path.posix.join(path.posix.dirname(file), name));
const targets = [
base,
...[".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js"].map((ext) => base + ext),
].filter(exists);
if (targets.length > 1) {
fail(line, `Ambiguous dependency '${name}'; use an explicit file path`);
return;
}
const target = targets[0];
if (!target) {
fail(line, `Cannot resolve '${name}'`);
return;
}
const allowed =
policy === "presentation"
? presentation.has(target)
: target.startsWith("src/lib/") && /\.[jt]sx?$/.test(target);
if (!allowed) {
fail(line, `Dependency '${name}' is outside the ${policy} layer`);
return;
}
walk(target, policy, [...chain, file]);
};
const visit = (node) => {
if (
policy === "protocol" &&
(ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node))
) {
fail(
source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
"JSX introduces a React runtime dependency into a protocol module",
);
return;
}
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier)
dependency(node, node.moduleSpecifier);
else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference))
dependency(node, node.moduleReference.expression);
else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument))
dependency(node, node.argument.literal);
else if (ts.isCallExpression(node)) {
let callee = node.expression;
while (ts.isParenthesizedExpression(callee)) callee = callee.expression;
if (
callee.kind === ts.SyntaxKind.ImportKeyword ||
(ts.isIdentifier(callee) && callee.text === "require") ||
(ts.isPropertyAccessExpression(callee) &&
ts.isIdentifier(callee.expression) &&
callee.expression.text === "module" &&
callee.name.text === "require")
)
dependency(node, node.arguments[0]);
else if (
ts.isPropertyAccessExpression(callee) &&
ts.isMetaProperty(callee.expression) &&
["glob", "globEager"].includes(callee.name.text)
)
dependency(node, undefined);
}
ts.forEachChild(node, visit);
};
visit(source);
}
walk("src/features/annotation-output/DashboardPresentation.tsx", "presentation", []);
walk("src/features/annotation-output/presentation.ts", "presentation", []);
for (const file of protocols) walk(file, "protocol", []);
return issues;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const issues = checkFrontendArchitecture();
for (const issue of issues)
console.error(`${issue.file}:${issue.line}: ${issue.message}\n ${issue.chain.join(" → ")}`);
if (issues.length) process.exitCode = 1;
else console.log("Frontend architecture: presentation and persistence dependency rules passed.");
}

View File

@ -0,0 +1,109 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import { checkFrontendArchitecture } from "../../scripts/check-frontend-architecture.mjs";
const presenter = "src/features/annotation-output/DashboardPresentation.tsx";
const protocol = "src/lib/review-draft-persistence.js";
const check = (overrides) =>
checkFrontendArchitecture({
read: (file) =>
Object.hasOwn(overrides, file)
? overrides[file]
: fs.readFileSync(new URL(`../../${file}`, import.meta.url), "utf8"),
exists: (file) => Object.hasOwn(overrides, file) || fs.existsSync(new URL(`../../${file}`, import.meta.url)),
});
test("current presentation and protocol graphs satisfy their responsibility rules", () =>
assert.deepEqual(check({}), []));
test("presentation cannot import data flow, business API, alias or external transport", () => {
for (const module of [
"./useAnnotationOutputData",
"../../services/api/client",
"@/src/services/api/client",
"axios",
]) {
const issues = check({ [presenter]: `import x from '${module}';` });
assert.equal(issues.length, 1);
assert.equal(issues[0].file, presenter);
}
});
test("protocol rules trace indirect helpers and report the violating import chain", () => {
const helper = "src/lib/synthetic-helper.js";
const issues = check({
[protocol]: "import './synthetic-helper.js'",
[helper]: "export {APIError} from '../services/api/client'",
});
assert.equal(issues.length, 1);
assert.deepEqual(issues[0].chain, [protocol, helper]);
assert.equal(issues[0].line, 1);
assert.equal(
check({ [protocol]: "import './synthetic-helper.js'", [helper]: "import React from 'react'" }).length,
1,
);
});
test("dynamic, CommonJS, export and type imports cannot bypass dependency checks", () => {
for (const source of [
"import('../services/api/client')",
"require('../services/api/client')",
"export * from '../services/api/client'",
"type T = import('../services/api/client').APIError",
"import client = require('../services/api/client')",
"import(name)",
"require(name)",
])
assert.equal(check({ [protocol]: source }).length, 1, source);
});
test("comments and ordinary strings are not dependencies; local cycles terminate", () => {
const helper = "src/lib/synthetic-helper.js";
assert.deepEqual(check({ [protocol]: "// import React from 'react'\nconst message = \"require('axios')\";" }), []);
assert.deepEqual(
check({ [protocol]: "import './synthetic-helper.js'", [helper]: "export * from './review-draft-persistence.js'" }),
[],
);
});
test("missing protected modules and unresolved helpers fail closed", () => {
assert.equal(check({ [protocol]: "import './missing-protocol-helper.js'" }).length, 1);
const issues = checkFrontendArchitecture({
read: () => {
throw Error("missing");
},
exists: () => false,
});
assert.ok(issues.length > 0);
assert.ok(issues.every((issue) => issue.message.includes("unreadable")));
});
test("malformed protected source cannot silently pass the import check", () => {
const issues = check({ [protocol]: "import {" });
assert.equal(issues.length, 1);
assert.match(issues[0].message, /Cannot parse/);
});
test("ambiguous module extensions cannot hide a different bundler dependency", () => {
const issues = check({
[protocol]: "import './ambiguous-helper'",
"src/lib/ambiguous-helper.ts": "export {}",
"src/lib/ambiguous-helper.js": "import React from 'react'",
});
assert.equal(issues.length, 1);
assert.match(issues[0].message, /Ambiguous/);
});
test("parenthesized require, module.require and Vite globs cannot skip dependency rules", () => {
for (const source of [
"(require)('../services/api/client')",
"module.require('../services/api/client')",
"import.meta.glob('../services/api/*.ts')",
"import.meta.globEager('../services/api/*.ts')",
])
assert.equal(check({ [protocol]: source }).length, 1, source);
});
test("JSX helpers cannot introduce implicit React runtime imports into protocols", () => {
for (const source of [
"export const view = <div />",
"export const view = <div>text</div>",
"export const view = <>text</>",
]) {
const issues = check({ [protocol]: "import './jsx-helper.tsx'", "src/lib/jsx-helper.tsx": source });
assert.equal(issues.length, 1);
assert.match(issues[0].message, /JSX/);
}
});