adopt.mjs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /**
  2. * architecture:adopt —— 把一个目录登记为 managed 模块。
  3. *
  4. * 设计目的:unmanaged-new-file 规则要求新代码必须落在 managed 模块内,那么"登记一个模块"
  5. * 必须比"绕过规则"更便宜。本命令一次完成:
  6. * 1. 从实际 import 反推 requires(可与 --requires 合并)
  7. * 2. 生成缺失的五件套骨架(module.ts / contract.ts / contract.example.ts / contract.test.ts / CONTRACT.md)
  8. * 3. 在 architecture-policy.yaml 登记(保留注释;已存在则置 managed: true,不重复添加)
  9. */
  10. import { promises as fs } from "node:fs";
  11. import path from "node:path";
  12. import { parseDocument } from "yaml";
  13. import {
  14. discoverFiles,
  15. importsOf,
  16. loadPolicy,
  17. moduleForFile,
  18. posix,
  19. resolveImport,
  20. } from "./policy.mjs";
  21. import { loadWorkspace } from "./resolver.mjs";
  22. const ARTIFACTS = [
  23. "module.ts",
  24. "contract.ts",
  25. "contract.example.ts",
  26. "contract.test.ts",
  27. "CONTRACT.md",
  28. ];
  29. function camel(id) {
  30. return id.replace(/[-_](\w)/g, (_, c) => c.toUpperCase());
  31. }
  32. function templates({ id, requires, layer }) {
  33. const name = camel(id);
  34. return {
  35. "module.ts": `/**
  36. * ${id} 模块清单(architecture-governance managed 模块)。
  37. * 层:${layer}。修改 requires 时同步更新 architecture-policy.yaml(检查器会校验两者一致)。
  38. */
  39. export const ${name}Module = {
  40. id: "${id}",
  41. requires: [${requires.map((item) => `"${item}"`).join(", ")}],
  42. provides: ["${id}"],
  43. publicEntrypoints: ["index.ts", "contract.ts"],
  44. } as const;
  45. `,
  46. "contract.ts": `/**
  47. * ${id} 对外契约:调用方要想正确调用就必须知道的一切都写在这里;其余对外不可见。
  48. * 每个方法注释写清:前置/后置条件、幂等性、发出哪些事件、是否等待持久化。
  49. */
  50. export type ${name[0].toUpperCase() + name.slice(1)}Id = string & { readonly __brand: "${name[0].toUpperCase() + name.slice(1)}Id" };
  51. export interface ${name[0].toUpperCase() + name.slice(1)}Contract {
  52. // TODO(${id}): 一个意图一个方法,不超过 8 个。
  53. }
  54. `,
  55. "contract.example.ts": `/**
  56. * ${id} 标准调用示例:agent 靠模仿写代码,这里放的就是该模仿的那份。
  57. */
  58. import type { ${name[0].toUpperCase() + name.slice(1)}Contract } from "./contract.js";
  59. export function example${name[0].toUpperCase() + name.slice(1)}(_contract: ${name[0].toUpperCase() + name.slice(1)}Contract): void {
  60. // TODO(${id}): 展示最常见的一次完整调用。
  61. }
  62. `,
  63. "contract.test.ts": `import { describe, expect, it } from "vitest";
  64. import { ${name}Module } from "./module.js";
  65. // 契约测试只 import contract 与 module,不知道实现是谁;同一份测试应同时跑真实现与跨进程代理。
  66. describe("${id} contract", () => {
  67. it("declares its module manifest", () => {
  68. expect(${name}Module.id).toBe("${id}");
  69. });
  70. });
  71. `,
  72. "CONTRACT.md": `# ${id}
  73. 一页以内。只写类型与测试表达不了的三样:模块存在的意图、不变量、与其它模块的交集在哪个 hook 点处理。
  74. 不变量:
  75. - TODO
  76. `,
  77. };
  78. }
  79. export async function adoptModule({
  80. cwd = process.cwd(),
  81. id,
  82. roots,
  83. layer = "adapters",
  84. owner = null,
  85. requires = [],
  86. publicEntrypoints = null,
  87. }) {
  88. if (!id || !/^[a-z][a-z0-9-]*$/.test(id)) throw new Error(`模块 id 非法: ${id}`);
  89. if (!Array.isArray(roots) || roots.length === 0) throw new Error("必须提供至少一个 --root");
  90. const absoluteRoots = roots.map((root) => path.resolve(cwd, root));
  91. for (const root of absoluteRoots) {
  92. const stat = await fs.stat(root).catch(() => null);
  93. if (!stat?.isDirectory()) throw new Error(`root 不是目录: ${root}`);
  94. }
  95. const policyPath = path.join(cwd, "architecture-policy.yaml");
  96. const doc = parseDocument(await fs.readFile(policyPath, "utf8"));
  97. const modules = doc.get("modules");
  98. if (!modules || typeof modules.items === "undefined")
  99. throw new Error("architecture-policy.yaml 缺少 modules 序列");
  100. const existing = modules.items.find((item) => item.get?.("id") === id);
  101. const primaryRoot = posix(path.relative(cwd, absoluteRoots[0]));
  102. const entrypoints = publicEntrypoints ?? [
  103. `${primaryRoot}/index.ts`,
  104. `${primaryRoot}/contract.ts`,
  105. ];
  106. // 先用"假设已登记"的策略视图反推 requires,避免新模块的文件被算成它所在的 legacy 模块。
  107. const currentPolicy = await loadPolicy(cwd);
  108. const virtualModule = {
  109. id,
  110. roots: absoluteRoots,
  111. managed: true,
  112. requires: [],
  113. publicEntrypoints: entrypoints,
  114. layers: { [layer]: "." },
  115. layerOrder: [layer],
  116. owner,
  117. };
  118. const virtualPolicy = {
  119. ...currentPolicy,
  120. modules: [...currentPolicy.modules.filter((module) => module.id !== id), virtualModule],
  121. };
  122. const workspace = await loadWorkspace(cwd);
  123. const files = await discoverFiles(virtualPolicy);
  124. const knownFiles = new Set(files);
  125. const inferred = new Set(requires);
  126. for (const file of files) {
  127. if (moduleForFile(file, virtualPolicy)?.id !== id) continue;
  128. const source = await fs.readFile(file, "utf8");
  129. for (const specifier of importsOf(file, source)) {
  130. const target = resolveImport(file, specifier, knownFiles, workspace);
  131. const targetModule = target && moduleForFile(target, virtualPolicy);
  132. if (targetModule && targetModule.id !== id) inferred.add(targetModule.id);
  133. }
  134. }
  135. const finalRequires = [...inferred].sort();
  136. const created = [];
  137. const rendered = templates({ id, requires: finalRequires, layer });
  138. for (const artifact of ARTIFACTS) {
  139. const target = path.join(absoluteRoots[0], artifact);
  140. const exists = await fs.stat(target).catch(() => null);
  141. if (exists) continue;
  142. await fs.writeFile(target, rendered[artifact]);
  143. created.push(posix(path.relative(cwd, target)));
  144. }
  145. let registered = false;
  146. if (existing) {
  147. existing.set("managed", true);
  148. if (!existing.has("requires")) existing.set("requires", finalRequires);
  149. if (!existing.has("publicEntrypoints")) existing.set("publicEntrypoints", entrypoints);
  150. if (!existing.has("layers")) existing.set("layers", { [layer]: "." });
  151. if (owner && !existing.has("owner")) existing.set("owner", owner);
  152. } else {
  153. const node = doc.createNode({
  154. id,
  155. roots: absoluteRoots.map((root) => posix(path.relative(cwd, root))),
  156. managed: true,
  157. requires: finalRequires,
  158. publicEntrypoints: entrypoints,
  159. layers: { [layer]: "." },
  160. ...(owner ? { owner } : {}),
  161. });
  162. node.commentBefore = ` ${id}:由 architecture:adopt 登记`;
  163. modules.add(node);
  164. registered = true;
  165. }
  166. await fs.writeFile(policyPath, doc.toString({ lineWidth: 0 }));
  167. await loadPolicy(cwd);
  168. return {
  169. id,
  170. roots: absoluteRoots.map((root) => posix(path.relative(cwd, root))),
  171. requires: finalRequires,
  172. created,
  173. registered,
  174. };
  175. }