architecture-governance.test.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { test } from "node:test";
  7. import { execFile } from "node:child_process";
  8. import { promisify } from "node:util";
  9. import { setTimeout } from "node:timers/promises";
  10. import {
  11. changedFilesFromGit,
  12. checkArchitecture,
  13. loadPolicy,
  14. updateBaseline,
  15. } from "../architecture/index.mjs";
  16. const execFileAsync = promisify(execFile);
  17. async function git(cwd, ...args) {
  18. return execFileAsync("git", args, { cwd });
  19. }
  20. async function initializeGit(cwd) {
  21. await git(cwd, "init");
  22. await git(cwd, "config", "user.name", "Architecture Test");
  23. await git(cwd, "config", "user.email", "architecture-test@example.invalid");
  24. await git(cwd, "config", "commit.gpgsign", "false");
  25. await git(cwd, "-c", "core.hooksPath=", "commit", "--allow-empty", "-m", "fixture");
  26. }
  27. async function fixture(files, fn) {
  28. const cwd = await mkdtemp(join(tmpdir(), "zcode-architecture-"));
  29. try {
  30. for (const [relative, content] of Object.entries(files)) {
  31. const target = join(cwd, relative);
  32. await mkdir(join(target, ".."), { recursive: true });
  33. await writeFile(target, content);
  34. }
  35. return await fn(cwd);
  36. } finally {
  37. // Windows 上 git 子进程与索引句柄会短暂滞留,直接 rm(recursive) 偶发
  38. // EBUSY(本机连续多轮复现);指数退避重试,仍失败则放过目录——它在
  39. // 系统 temp 下,不影响测试结论。
  40. // 注意:清理是 best-effort,这里绝不能 return/throw——finally 中的
  41. // return 会丢弃 try 块挂起的断言异常,让治理测试空转通过(评审
  42. // CR-01 修复),非 EBUSY 与重试耗尽一律 break 放过目录。
  43. for (let attempt = 0; attempt < 6; attempt++) {
  44. try {
  45. await rm(cwd, { recursive: true, force: true });
  46. break;
  47. } catch (error) {
  48. if (attempt === 5 || error.code !== "EBUSY") break;
  49. await setTimeout(20 * 2 ** attempt);
  50. }
  51. }
  52. }
  53. }
  54. const POLICY = `version: 1
  55. modules:
  56. - id: alpha
  57. roots: [src/alpha]
  58. managed: true
  59. requires: [beta]
  60. publicEntrypoints: [src/alpha/contract.ts]
  61. - id: beta
  62. roots: [src/beta]
  63. managed: true
  64. requires: []
  65. publicEntrypoints: [src/beta/contract.ts]
  66. global:
  67. maxFileLines: 20
  68. maxContractLines: 10
  69. `;
  70. const POLICY_UNDECLARED = POLICY.replace("requires: [beta]", "requires: []");
  71. test("fixture 回调中的断言异常必须向上传播(finally 清理不得吞异常)", async () => {
  72. // 回归锚点:finally 清理循环曾用 return 收尾,JS 语义下会丢弃 try 块中
  73. // 挂起的断言异常,导致整个治理测试文件空转通过(评审 CR-01)。
  74. await assert.rejects(
  75. fixture({ "architecture-policy.yaml": POLICY }, async () => {
  76. throw new Error("intentional assertion failure");
  77. }),
  78. /intentional assertion failure/,
  79. );
  80. });
  81. test("managed module needs contracts and documentation but no unit test", async () => {
  82. const files = { "architecture-policy.yaml": POLICY };
  83. for (const module of ["alpha", "beta"]) {
  84. for (const name of ["module.ts", "contract.ts", "contract.example.ts"]) {
  85. files[`src/${module}/${name}`] = "export {};\n";
  86. }
  87. // 文档示例故意超过源码行数限制且含 import;它们不是可执行的跨模块依赖。
  88. files[`src/${module}/CONTRACT.md`] = 'import "../beta/internal.js";\n'.repeat(30);
  89. }
  90. await fixture(files, async (cwd) => {
  91. assert.deepEqual((await checkArchitecture({ cwd })).violations, []);
  92. await rm(join(cwd, "src/alpha/CONTRACT.md"));
  93. const missing = (await checkArchitecture({ cwd })).violations;
  94. assert.equal(missing.length, 1);
  95. assert.equal(missing[0].rule, "missing-module-artifact");
  96. assert.equal(missing[0].module, "alpha");
  97. assert.equal(missing[0].detail, "CONTRACT.md");
  98. });
  99. });
  100. test("repository policy discovers both refactored provider modules", async () => {
  101. const root = fileURLToPath(new URL("../../", import.meta.url));
  102. const policy = await loadPolicy(root);
  103. for (const id of ["provider", "provider-node"]) {
  104. // 新门禁若沿用旧仓库目录,会漏掉重构后的模块,使 context 无法找到其源码。
  105. const module = policy.modules.find((item) => item.id === id);
  106. assert.ok(module, `missing module: ${id}`);
  107. assert.deepEqual(module.roots, [join(root, "packages", id, "src")]);
  108. }
  109. });
  110. test("changed files exclude CI caches but retain tracked and untracked source paths", async () => {
  111. const ignore = await readFile(new URL("../../.gitignore", import.meta.url), "utf8");
  112. await fixture({ ".gitignore": ignore, "tracked.ts": "before" }, async (cwd) => {
  113. await initializeGit(cwd);
  114. await git(cwd, "add", ".gitignore", "tracked.ts");
  115. await git(cwd, "-c", "core.hooksPath=", "commit", "-m", "tracked files");
  116. await writeFile(join(cwd, "tracked.ts"), "after");
  117. const paths = [" 新文件 name.ts", "staged.ts"];
  118. if (process.platform !== "win32") paths.push('line\nbreak".ts');
  119. for (const file of paths) await writeFile(join(cwd, file), "export {};\n");
  120. await git(cwd, "add", "staged.ts");
  121. for (const cache of [
  122. ".electron-builder-cache",
  123. ".electron-cache",
  124. ".pnpm-store",
  125. ".npm-cache",
  126. ]) {
  127. await mkdir(join(cwd, cache));
  128. await writeFile(join(cwd, cache, "cached.ts"), "export {};\n");
  129. }
  130. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), ["tracked.ts", ...paths].sort());
  131. });
  132. });
  133. test("changed files support Git output larger than 1 MiB for untracked and tracked files", async () => {
  134. await fixture({}, async (cwd) => {
  135. await initializeGit(cwd);
  136. await mkdir(join(cwd, "src"));
  137. const paths = Array.from(
  138. { length: 8192 },
  139. (_, i) => `src/${String(i).padStart(5, "0")}-${"x".repeat(120)}.ts`,
  140. );
  141. assert.ok(Buffer.byteLength(paths.join("\0")) > 1024 * 1024);
  142. // 真 Git 输出跨过原缓冲区上限;不能用忽略缓存或截断列表假装修复。
  143. for (let offset = 0; offset < paths.length; offset += 100) {
  144. await Promise.all(
  145. paths.slice(offset, offset + 100).map((file) => writeFile(join(cwd, file), "")),
  146. );
  147. }
  148. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), paths);
  149. await git(cwd, "add", "src");
  150. await git(cwd, "-c", "core.hooksPath=", "commit", "--quiet", "-m", "large tracked tree");
  151. await rm(join(cwd, "src"), { recursive: true });
  152. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), paths);
  153. });
  154. });
  155. test("Git enumeration failures reject instead of reporting an empty changed set", async () => {
  156. await fixture({}, async (cwd) => {
  157. await assert.rejects(changedFilesFromGit(cwd), /git/i);
  158. });
  159. });
  160. test("policy loader validates modules and global thresholds", async () => {
  161. await fixture({ "architecture-policy.yaml": POLICY }, async (cwd) => {
  162. const policy = await loadPolicy(cwd);
  163. assert.equal(policy.version, 1);
  164. assert.equal(policy.modules.length, 2);
  165. assert.equal(policy.global.maxFileLines, 20);
  166. });
  167. });
  168. test("undeclared cross-module import is reported", async () => {
  169. await fixture(
  170. {
  171. "architecture-policy.yaml": POLICY_UNDECLARED,
  172. "src/alpha/contract.ts": "export type Alpha = string;\n",
  173. "src/alpha/index.ts": 'import { beta } from "../beta/index.js";\nexport { beta };\n',
  174. "src/beta/contract.ts": "export const beta = 1;\n",
  175. "src/beta/index.ts": "export const beta = 1;\n",
  176. },
  177. async (cwd) => {
  178. const result = await checkArchitecture({ cwd });
  179. assert.ok(result.violations.some((v) => v.rule === "module-dependency"));
  180. },
  181. );
  182. });
  183. test("deep import and cycle are reported with stable fingerprints", async () => {
  184. await fixture(
  185. {
  186. "architecture-policy.yaml": POLICY,
  187. "src/alpha/contract.ts": "export type Alpha = string;\n",
  188. "src/alpha/a.ts": 'import "../beta/internal.js";\n',
  189. "src/alpha/b.ts": 'import "./a.js";\n',
  190. "src/beta/contract.ts": "export type Beta = string;\n",
  191. "src/beta/internal.ts": 'import "../alpha/b.js";\n',
  192. },
  193. async (cwd) => {
  194. const result = await checkArchitecture({ cwd });
  195. const rules = new Set(result.violations.map((v) => v.rule));
  196. assert.ok(rules.has("deep-import"));
  197. assert.ok(rules.has("cycle"));
  198. for (const violation of result.violations) {
  199. assert.match(violation.fingerprint, /^[a-f0-9]{16}$/);
  200. }
  201. },
  202. );
  203. });
  204. test("baseline suppresses existing violations but rejects new ones", async () => {
  205. await fixture(
  206. {
  207. "architecture-policy.yaml": POLICY,
  208. "src/alpha/contract.ts": "export type Alpha = string;\n",
  209. "src/alpha/index.ts": 'import "../beta/internal.js";\n',
  210. "src/beta/contract.ts": "export type Beta = string;\n",
  211. "src/beta/internal.ts": "export const value = 1;\n",
  212. },
  213. async (cwd) => {
  214. const initial = await checkArchitecture({ cwd });
  215. await updateBaseline({ cwd, violations: initial.violations });
  216. const baseline = JSON.parse(await readFile(join(cwd, ".architecture-baseline.json"), "utf8"));
  217. assert.equal(baseline.violations.length, initial.violations.length);
  218. await writeFile(join(cwd, "src/alpha/new.ts"), 'import "../beta/internal.js";\n');
  219. const changed = await checkArchitecture({ cwd, changedFiles: ["src/alpha/new.ts"] });
  220. assert.ok(changed.newViolations.length >= 1);
  221. assert.equal(changed.baselineViolations.length, 0);
  222. },
  223. );
  224. });
  225. test("managed modules require contract artifacts and enforce layer and domain boundaries", async () => {
  226. const policy = `version: 1
  227. modules:
  228. - id: alpha
  229. roots: [src/alpha]
  230. managed: true
  231. layers:
  232. contract: contract
  233. domain: domain
  234. ui: ui
  235. layerOrder: [contract, domain, ui]
  236. publicEntrypoints: [contract.ts]
  237. global:
  238. maxFileLines: 100
  239. maxContractLines: 20
  240. `;
  241. await fixture(
  242. {
  243. "architecture-policy.yaml": policy,
  244. "src/alpha/module.ts": "export const alphaModule = { id: 'alpha' } as const;\n",
  245. "src/alpha/contract.ts": "export type Alpha = string;\n",
  246. "src/alpha/domain/value.ts":
  247. "import { readFile } from 'node:fs';\nimport '../ui/view.js';\nexport const value = readFile;\n",
  248. "src/alpha/ui/view.ts": "import '../domain/value.js';\n",
  249. },
  250. async (cwd) => {
  251. const result = await checkArchitecture({ cwd });
  252. const rules = new Set(result.violations.map((v) => v.rule));
  253. assert.ok(rules.has("missing-module-artifact"));
  254. assert.ok(rules.has("domain-io"));
  255. assert.ok(rules.has("layer-direction"));
  256. },
  257. );
  258. });
  259. test("relative public entrypoints resolve from a module root", async () => {
  260. await fixture(
  261. {
  262. "architecture-policy.yaml": POLICY,
  263. "src/alpha/contract.ts": "export type Alpha = string;\n",
  264. "src/alpha/index.ts": 'import { beta } from "../beta/contract.js";\nexport { beta };\n',
  265. "src/beta/contract.ts": "export const beta = 1;\n",
  266. },
  267. async (cwd) => {
  268. const result = await checkArchitecture({ cwd });
  269. assert.equal(result.violations.filter((v) => v.rule === "deep-import").length, 0);
  270. },
  271. );
  272. });
  273. test("expired exceptions are global blocking violations", async () => {
  274. const policy = `${POLICY}\nexceptions:\n - id: old\n rule: deep-import\n paths: [src/**]\n expires: 2020-01-01\n`;
  275. await fixture(
  276. {
  277. "architecture-policy.yaml": policy,
  278. "src/alpha/contract.ts": "export type Alpha = string;\n",
  279. "src/beta/contract.ts": "export type Beta = string;\n",
  280. },
  281. async (cwd) => {
  282. const result = await checkArchitecture({ cwd, changedFiles: [] });
  283. assert.ok(result.newViolations.some((v) => v.rule === "expired-exception"));
  284. },
  285. );
  286. });