adopt.mjs 6.3 KB

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