context.mjs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { promises as fs } from "node:fs";
  2. import path from "node:path";
  3. import { discoverFiles, loadPolicy, moduleForFile, posix } from "./policy.mjs";
  4. export async function generateContext({ cwd = process.cwd(), moduleId }) {
  5. const policy = await loadPolicy(cwd);
  6. const module = policy.modules.find((item) => item.id === moduleId);
  7. if (!module) throw new Error(`未知模块: ${moduleId}`);
  8. const files = await discoverFiles(policy);
  9. const moduleFiles = files.filter((file) => moduleForFile(file, policy)?.id === moduleId);
  10. const manifest = moduleFiles.find((file) => path.basename(file) === "module.ts");
  11. const contracts = moduleFiles.filter((file) => path.basename(file).startsWith("contract."));
  12. // CONTRACT.md 不是源码扩展名,不在 discoverFiles 结果里,要按 root 直接探测。
  13. const contractDocs = (
  14. await Promise.all(
  15. module.roots.map((root) =>
  16. fs.stat(path.join(root, "CONTRACT.md")).then(
  17. () => path.join(root, "CONTRACT.md"),
  18. () => null,
  19. ),
  20. ),
  21. )
  22. ).filter(Boolean);
  23. const contractDoc = contractDocs[0];
  24. const dependencyContracts = module.requires.flatMap((dependencyId) => {
  25. const dependencyFiles = files.filter(
  26. (file) => moduleForFile(file, policy)?.id === dependencyId,
  27. );
  28. return dependencyFiles.filter((file) => path.basename(file) === "contract.ts");
  29. });
  30. const inline = async (file) => {
  31. const relative = posix(path.relative(cwd, file));
  32. const body = await fs.readFile(file, "utf8");
  33. const fence = file.endsWith(".md") ? "" : "```ts\n";
  34. return [`### ${relative}`, "", `${fence}${body.trimEnd()}\n${fence ? "```" : ""}`, ""];
  35. };
  36. const sections = [
  37. `# Architecture context: ${module.id}`,
  38. `owner: ${module.owner ?? "unassigned"}`,
  39. `managed: ${module.managed}`,
  40. `requires: ${module.requires.join(", ") || "none"}`,
  41. `layers: ${Object.keys(module.layers).length ? (module.layerOrder ?? Object.keys(module.layers)).join(" < ") : "none"}`,
  42. "",
  43. "## Files",
  44. ...(manifest ? [`- ${posix(path.relative(cwd, manifest))}`] : ["- module.ts: missing"]),
  45. ...contracts.map((file) => `- ${posix(path.relative(cwd, file))}`),
  46. ...module.publicEntrypoints.map((entry) => `- public: ${entry}`),
  47. "",
  48. ];
  49. // 阅读包内联契约正文:只列文件名会让 agent 再去打开实现;契约就是"读完就够"的那份。
  50. sections.push("## Contract");
  51. for (const file of [
  52. contractDoc,
  53. ...contracts.filter((f) => path.basename(f) === "contract.ts"),
  54. ].filter(Boolean)) {
  55. sections.push(...(await inline(file)));
  56. }
  57. sections.push("## Direct dependency contracts");
  58. if (dependencyContracts.length === 0) sections.push("- none discovered", "");
  59. for (const file of dependencyContracts) sections.push(...(await inline(file)));
  60. sections.push(
  61. "## Boundaries",
  62. "- Cross-module imports must use declared requirements and public entrypoints.",
  63. "- Add a contract example and contract test before exposing a new capability.",
  64. "- New source files must live inside a managed module (rule: unmanaged-new-file).",
  65. );
  66. return sections.join("\n");
  67. }