architecture-governance.test.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 {
  10. changedFilesFromGit,
  11. checkArchitecture,
  12. loadPolicy,
  13. updateBaseline,
  14. } from "../architecture/index.mjs";
  15. const execFileAsync = promisify(execFile);
  16. async function git(cwd, ...args) {
  17. return execFileAsync("git", args, { cwd });
  18. }
  19. async function initializeGit(cwd) {
  20. await git(cwd, "init");
  21. await git(cwd, "config", "user.name", "Architecture Test");
  22. await git(cwd, "config", "user.email", "architecture-test@example.invalid");
  23. await git(cwd, "config", "commit.gpgsign", "false");
  24. await git(cwd, "-c", "core.hooksPath=", "commit", "--allow-empty", "-m", "fixture");
  25. }
  26. async function fixture(files, fn) {
  27. const cwd = await mkdtemp(join(tmpdir(), "zcode-architecture-"));
  28. try {
  29. for (const [relative, content] of Object.entries(files)) {
  30. const target = join(cwd, relative);
  31. await mkdir(join(target, ".."), { recursive: true });
  32. await writeFile(target, content);
  33. }
  34. return await fn(cwd);
  35. } finally {
  36. await rm(cwd, { recursive: true, force: true });
  37. }
  38. }
  39. const POLICY = `version: 1
  40. modules:
  41. - id: alpha
  42. roots: [src/alpha]
  43. managed: true
  44. requires: [beta]
  45. publicEntrypoints: [src/alpha/contract.ts]
  46. - id: beta
  47. roots: [src/beta]
  48. managed: true
  49. requires: []
  50. publicEntrypoints: [src/beta/contract.ts]
  51. global:
  52. maxFileLines: 20
  53. maxContractLines: 10
  54. `;
  55. const POLICY_UNDECLARED = POLICY.replace("requires: [beta]", "requires: []");
  56. test("managed module documents satisfy artifacts without being checked as source", async () => {
  57. const files = { "architecture-policy.yaml": POLICY };
  58. for (const module of ["alpha", "beta"]) {
  59. for (const name of ["module.ts", "contract.ts", "contract.example.ts", "contract.test.ts"]) {
  60. files[`src/${module}/${name}`] = "export {};\n";
  61. }
  62. // 文档示例故意超过源码行数限制且含 import;它们不是可执行的跨模块依赖。
  63. files[`src/${module}/CONTRACT.md`] = 'import "../beta/internal.js";\n'.repeat(30);
  64. }
  65. await fixture(files, async (cwd) => {
  66. assert.deepEqual((await checkArchitecture({ cwd })).violations, []);
  67. await rm(join(cwd, "src/alpha/CONTRACT.md"));
  68. const missing = (await checkArchitecture({ cwd })).violations;
  69. assert.equal(missing.length, 1);
  70. assert.equal(missing[0].rule, "missing-module-artifact");
  71. assert.equal(missing[0].module, "alpha");
  72. assert.equal(missing[0].detail, "CONTRACT.md");
  73. });
  74. });
  75. test("repository policy discovers both refactored provider modules", async () => {
  76. const root = fileURLToPath(new URL("../../", import.meta.url));
  77. const policy = await loadPolicy(root);
  78. for (const id of ["provider", "provider-node"]) {
  79. // 新门禁若沿用旧仓库目录,会漏掉重构后的模块,使 context 无法找到其源码。
  80. const module = policy.modules.find((item) => item.id === id);
  81. assert.ok(module, `missing module: ${id}`);
  82. assert.deepEqual(module.roots, [join(root, "packages", id, "src")]);
  83. }
  84. });
  85. test("changed files exclude CI caches but retain tracked and untracked source paths", async () => {
  86. const ignore = await readFile(new URL("../../.gitignore", import.meta.url), "utf8");
  87. await fixture({ ".gitignore": ignore, "tracked.ts": "before" }, async (cwd) => {
  88. await initializeGit(cwd);
  89. await git(cwd, "add", ".gitignore", "tracked.ts");
  90. await git(cwd, "-c", "core.hooksPath=", "commit", "-m", "tracked files");
  91. await writeFile(join(cwd, "tracked.ts"), "after");
  92. const paths = [" 新文件 name.ts", "staged.ts"];
  93. if (process.platform !== "win32") paths.push('line\nbreak".ts');
  94. for (const file of paths) await writeFile(join(cwd, file), "export {};\n");
  95. await git(cwd, "add", "staged.ts");
  96. for (const cache of [
  97. ".electron-builder-cache",
  98. ".electron-cache",
  99. ".pnpm-store",
  100. ".npm-cache",
  101. ]) {
  102. await mkdir(join(cwd, cache));
  103. await writeFile(join(cwd, cache, "cached.ts"), "export {};\n");
  104. }
  105. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), ["tracked.ts", ...paths].sort());
  106. });
  107. });
  108. test("changed files support Git output larger than 1 MiB for untracked and tracked files", async () => {
  109. await fixture({}, async (cwd) => {
  110. await initializeGit(cwd);
  111. await mkdir(join(cwd, "src"));
  112. const paths = Array.from(
  113. { length: 8192 },
  114. (_, i) => `src/${String(i).padStart(5, "0")}-${"x".repeat(120)}.ts`,
  115. );
  116. assert.ok(Buffer.byteLength(paths.join("\0")) > 1024 * 1024);
  117. // 真 Git 输出跨过原缓冲区上限;不能用忽略缓存或截断列表假装修复。
  118. for (let offset = 0; offset < paths.length; offset += 100) {
  119. await Promise.all(
  120. paths.slice(offset, offset + 100).map((file) => writeFile(join(cwd, file), "")),
  121. );
  122. }
  123. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), paths);
  124. await git(cwd, "add", "src");
  125. await git(cwd, "-c", "core.hooksPath=", "commit", "--quiet", "-m", "large tracked tree");
  126. await rm(join(cwd, "src"), { recursive: true });
  127. assert.deepEqual((await changedFilesFromGit(cwd)).sort(), paths);
  128. });
  129. });
  130. test("Git enumeration failures reject instead of reporting an empty changed set", async () => {
  131. await fixture({}, async (cwd) => {
  132. await assert.rejects(changedFilesFromGit(cwd), /git/i);
  133. });
  134. });
  135. test("policy loader validates modules and global thresholds", async () => {
  136. await fixture({ "architecture-policy.yaml": POLICY }, async (cwd) => {
  137. const policy = await loadPolicy(cwd);
  138. assert.equal(policy.version, 1);
  139. assert.equal(policy.modules.length, 2);
  140. assert.equal(policy.global.maxFileLines, 20);
  141. });
  142. });
  143. test("undeclared cross-module import is reported", async () => {
  144. await fixture(
  145. {
  146. "architecture-policy.yaml": POLICY_UNDECLARED,
  147. "src/alpha/contract.ts": "export type Alpha = string;\n",
  148. "src/alpha/index.ts": 'import { beta } from "../beta/index.js";\nexport { beta };\n',
  149. "src/beta/contract.ts": "export const beta = 1;\n",
  150. "src/beta/index.ts": "export const beta = 1;\n",
  151. },
  152. async (cwd) => {
  153. const result = await checkArchitecture({ cwd });
  154. assert.ok(result.violations.some((v) => v.rule === "module-dependency"));
  155. },
  156. );
  157. });
  158. test("deep import and cycle are reported with stable fingerprints", async () => {
  159. await fixture(
  160. {
  161. "architecture-policy.yaml": POLICY,
  162. "src/alpha/contract.ts": "export type Alpha = string;\n",
  163. "src/alpha/a.ts": 'import "../beta/internal.js";\n',
  164. "src/alpha/b.ts": 'import "./a.js";\n',
  165. "src/beta/contract.ts": "export type Beta = string;\n",
  166. "src/beta/internal.ts": 'import "../alpha/b.js";\n',
  167. },
  168. async (cwd) => {
  169. const result = await checkArchitecture({ cwd });
  170. const rules = new Set(result.violations.map((v) => v.rule));
  171. assert.ok(rules.has("deep-import"));
  172. assert.ok(rules.has("cycle"));
  173. for (const violation of result.violations) {
  174. assert.match(violation.fingerprint, /^[a-f0-9]{16}$/);
  175. }
  176. },
  177. );
  178. });
  179. test("baseline suppresses existing violations but rejects new ones", async () => {
  180. await fixture(
  181. {
  182. "architecture-policy.yaml": POLICY,
  183. "src/alpha/contract.ts": "export type Alpha = string;\n",
  184. "src/alpha/index.ts": 'import "../beta/internal.js";\n',
  185. "src/beta/contract.ts": "export type Beta = string;\n",
  186. "src/beta/internal.ts": "export const value = 1;\n",
  187. },
  188. async (cwd) => {
  189. const initial = await checkArchitecture({ cwd });
  190. await updateBaseline({ cwd, violations: initial.violations });
  191. const baseline = JSON.parse(await readFile(join(cwd, ".architecture-baseline.json"), "utf8"));
  192. assert.equal(baseline.violations.length, initial.violations.length);
  193. await writeFile(join(cwd, "src/alpha/new.ts"), 'import "../beta/internal.js";\n');
  194. const changed = await checkArchitecture({ cwd, changedFiles: ["src/alpha/new.ts"] });
  195. assert.ok(changed.newViolations.length >= 1);
  196. assert.equal(changed.baselineViolations.length, 0);
  197. },
  198. );
  199. });
  200. test("managed modules require contract artifacts and enforce layer and domain boundaries", async () => {
  201. const policy = `version: 1
  202. modules:
  203. - id: alpha
  204. roots: [src/alpha]
  205. managed: true
  206. layers:
  207. contract: contract
  208. domain: domain
  209. ui: ui
  210. layerOrder: [contract, domain, ui]
  211. publicEntrypoints: [contract.ts]
  212. global:
  213. maxFileLines: 100
  214. maxContractLines: 20
  215. `;
  216. await fixture(
  217. {
  218. "architecture-policy.yaml": policy,
  219. "src/alpha/module.ts": "export const alphaModule = { id: 'alpha' } as const;\n",
  220. "src/alpha/contract.ts": "export type Alpha = string;\n",
  221. "src/alpha/domain/value.ts":
  222. "import { readFile } from 'node:fs';\nimport '../ui/view.js';\nexport const value = readFile;\n",
  223. "src/alpha/ui/view.ts": "import '../domain/value.js';\n",
  224. },
  225. async (cwd) => {
  226. const result = await checkArchitecture({ cwd });
  227. const rules = new Set(result.violations.map((v) => v.rule));
  228. assert.ok(rules.has("missing-module-artifact"));
  229. assert.ok(rules.has("domain-io"));
  230. assert.ok(rules.has("layer-direction"));
  231. },
  232. );
  233. });
  234. test("relative public entrypoints resolve from a module root", async () => {
  235. await fixture(
  236. {
  237. "architecture-policy.yaml": POLICY,
  238. "src/alpha/contract.ts": "export type Alpha = string;\n",
  239. "src/alpha/index.ts": 'import { beta } from "../beta/contract.js";\nexport { beta };\n',
  240. "src/beta/contract.ts": "export const beta = 1;\n",
  241. },
  242. async (cwd) => {
  243. const result = await checkArchitecture({ cwd });
  244. assert.equal(result.violations.filter((v) => v.rule === "deep-import").length, 0);
  245. },
  246. );
  247. });
  248. test("expired exceptions are global blocking violations", async () => {
  249. const policy = `${POLICY}\nexceptions:\n - id: old\n rule: deep-import\n paths: [src/**]\n expires: 2020-01-01\n`;
  250. await fixture(
  251. {
  252. "architecture-policy.yaml": policy,
  253. "src/alpha/contract.ts": "export type Alpha = string;\n",
  254. "src/beta/contract.ts": "export type Beta = string;\n",
  255. },
  256. async (cwd) => {
  257. const result = await checkArchitecture({ cwd, changedFiles: [] });
  258. assert.ok(result.newViolations.some((v) => v.rule === "expired-exception"));
  259. },
  260. );
  261. });