facade-dts.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. analyzeWorkflowScript,
  4. collectDiagnostics,
  5. collectSites,
  6. collectWorldRunCommands,
  7. createWorkflowProgram,
  8. FACADE_DTS,
  9. lowerWorkflow,
  10. SNIPPET_FACADE_DTS,
  11. WORLD_RUN_LITERAL_CODE,
  12. } from "../src/index.js";
  13. describe("facade dts segments", () => {
  14. // 注释只写参考层:做什么、返回什么、何时拒绝或让 run 失败、上限、实参的编译期规则
  15. // (docs/dynamic-workflow/authoring.md「The facade」)。判断层在技能正文里只说一次;facade
  16. // 只经技能 §16.2 进上下文,注释复述正文等于每次写作会话付两遍,且是会漂移的那一份。
  17. // 2026-09-30 去重前是 23 275 字节,其中约 2 万是注释。
  18. it("stays a reference: FACADE_DTS is under 14 000 bytes", () => {
  19. expect(Buffer.byteLength(FACADE_DTS, "utf8")).toBeLessThan(14_000);
  20. });
  21. // args 在**两个** facade 里都在:snippet 的「逐字可迁移」不变式要求一段引用 args 的
  22. // saved 脚本能原样丢进 EvalWorkflowSnippet 编译(运行时它是 `{}`)。
  23. it("SNIPPET_FACADE_DTS keeps world reads, world.run, log and args, drops actors/report/artifact/phase", () => {
  24. expect(SNIPPET_FACADE_DTS).toContain("declare const args");
  25. expect(FACADE_DTS).toContain("declare const args");
  26. expect(SNIPPET_FACADE_DTS).toContain("declare const files");
  27. expect(SNIPPET_FACADE_DTS).toContain("declare const git");
  28. expect(SNIPPET_FACADE_DTS).toContain("declare const world");
  29. expect(SNIPPET_FACADE_DTS).toContain("declare function log");
  30. // stream 段在两个 facade 里都在:流水线的纯逻辑正是片段要排练的东西。
  31. expect(SNIPPET_FACADE_DTS).toContain("declare function channel");
  32. expect(SNIPPET_FACADE_DTS).toContain("declare function future");
  33. expect(SNIPPET_FACADE_DTS).toContain("declare interface Channel<T>");
  34. expect(SNIPPET_FACADE_DTS).not.toContain("declare function agent");
  35. expect(SNIPPET_FACADE_DTS).not.toContain("declare function report");
  36. expect(SNIPPET_FACADE_DTS).not.toContain("declare function phase");
  37. // 模型声明属于 actor:snippet 里没有子代理,也就没有可选的模型。
  38. expect(FACADE_DTS).toContain("declare function model");
  39. expect(SNIPPET_FACADE_DTS).not.toContain("declare function model");
  40. expect(SNIPPET_FACADE_DTS).not.toContain("ModelRef");
  41. // 产物是「run 交给用户的产出」,而 snippet 没有 run:整段刻意缺席,连类型都不留。
  42. expect(FACADE_DTS).toContain("declare const artifact");
  43. expect(SNIPPET_FACADE_DTS).not.toContain("declare const artifact");
  44. expect(SNIPPET_FACADE_DTS).not.toContain("ArtifactRef");
  45. // 留白只在完整 facade 里(docs/dynamic-workflow/authoring.md「Holes」):片段没有 run。
  46. expect(FACADE_DTS).toContain(
  47. "declare function hole<T>(name: string, prompt?: string): Promise<T>;",
  48. );
  49. expect(FACADE_DTS).toContain(
  50. "declare function hole<T>(name: string, body: () => Promise<T>): Promise<T>;",
  51. );
  52. expect(FACADE_DTS).toContain(
  53. "declare function hole<T>(name: string, prompt: string, body: () => Promise<T>): Promise<T>;",
  54. );
  55. expect(SNIPPET_FACADE_DTS).not.toContain("declare function hole");
  56. });
  57. it("rejects hole() in the snippet facade at compile time (TS2304)", () => {
  58. const workflow = createWorkflowProgram(`return await hole<string>("决定");`, {
  59. facadeDts: SNIPPET_FACADE_DTS,
  60. });
  61. const diagnostics = collectDiagnostics(workflow.program);
  62. expect(diagnostics.length).toBeGreaterThan(0);
  63. expect(diagnostics[0]?.message).toContain("Cannot find name 'hole'");
  64. });
  65. });
  66. describe("snippet compilation (scratch facade)", () => {
  67. const compileSnippet = (scriptText: string) =>
  68. createWorkflowProgram(scriptText, { facadeDts: SNIPPET_FACADE_DTS });
  69. it("compiles a world-read + pure-logic snippet cleanly", () => {
  70. const workflow = compileSnippet(
  71. `const paths = await files.glob("src/**/*.ts");\n` +
  72. `log(\`found \${paths.length}\`);\n` +
  73. `return paths.filter((p) => p.endsWith(".test.ts"));`,
  74. );
  75. expect(collectDiagnostics(workflow.program)).toEqual([]);
  76. });
  77. it("rejects agent() at compile time (TS2304, not a runtime surprise)", () => {
  78. const workflow = compileSnippet(`return await agent("a").ask("do it");`);
  79. const diagnostics = collectDiagnostics(workflow.program);
  80. expect(diagnostics.length).toBeGreaterThan(0);
  81. expect(diagnostics[0]?.message).toContain("Cannot find name 'agent'");
  82. });
  83. it("rejects report() and phase() the same way", () => {
  84. for (const source of [`report({ found: 1 });`, `phase("gate");`]) {
  85. const workflow = compileSnippet(source);
  86. expect(collectDiagnostics(workflow.program).length).toBeGreaterThan(0);
  87. }
  88. });
  89. // facade 身份按声明文件名判定(registry / sites / misuse / lowering 五处);scratch
  90. // facade 若换了文件名,站点收集会静默变空、files.glob 不再降级到 __host.worldRead——
  91. // snippet 编译通过却什么都不做。这条钉住「同名注入」的不变量。
  92. it("lowers files.glob in a snippet to a world-read site (facade filename invariant)", () => {
  93. const workflow = compileSnippet(`return await files.glob("*.ts");`);
  94. expect(collectDiagnostics(workflow.program)).toEqual([]);
  95. const table = collectSites(workflow);
  96. const lowered = lowerWorkflow(workflow, table);
  97. expect(lowered.code).toContain(`__host.worldRead("world-read#1", "glob"`);
  98. });
  99. });
  100. // 产物的**类型面**(docs/dynamic-workflow/authoring.md「Two families」):两族成员的语义
  101. // 不对称必须在类型上就成立——内容成员可 await 出 ArtifactRef,预置成员是 void。
  102. describe("artifact facade (type surface)", () => {
  103. const diagnosticsOf = (scriptText: string) =>
  104. collectDiagnostics(createWorkflowProgram(scriptText).program);
  105. it("types content members as Promise<ArtifactRef>", () => {
  106. expect(
  107. diagnosticsOf(
  108. `const ref = await artifact.file("book", "out/book.pdf", { title: "Book", contentType: "application/pdf" });\n` +
  109. `const md = await artifact.markdown("notes", "# hi", { description: "d" });\n` +
  110. `return ref.id + String(ref.version) + md.id;`,
  111. ),
  112. ).toEqual([]);
  113. });
  114. it("rejects using a content member's result as anything but an ArtifactRef", () => {
  115. const diagnostics = diagnosticsOf(`const n: number = await artifact.file("book", "b.pdf");`);
  116. expect(diagnostics.length).toBeGreaterThan(0);
  117. expect(diagnostics[0]?.message).toContain("not assignable");
  118. });
  119. it("types preset members as void (a declaration has nothing to await)", () => {
  120. expect(
  121. diagnosticsOf(
  122. `artifact.chart("perf", { type: "line", x: { field: "round" }, y: [{ field: "ms", label: "ms" }], scale: "log", baseline: { field: "budget" } });\n` +
  123. `artifact.table("rows", { columns: [{ field: "name" }], key: "name" });\n` +
  124. `artifact.metrics("m", { metrics: [{ field: "p95", unit: "ms" }] });\n` +
  125. `artifact.board("b", { key: "id", status: "state", columns: ["todo", "done"], detail: [{ field: "owner" }] });`,
  126. ),
  127. ).toEqual([]);
  128. const diagnostics = diagnosticsOf(
  129. `const v: number = artifact.chart("perf", { x: { field: "r" }, y: { field: "m" } });`,
  130. );
  131. expect(diagnostics.length).toBeGreaterThan(0);
  132. });
  133. it("lets a board name itself and its cards separately (the cardTitle rename)", () => {
  134. expect(
  135. diagnosticsOf(
  136. `artifact.board("b", { title: "内存回归", key: "id", status: "state", columns: ["todo"], cardTitle: "name" });`,
  137. ),
  138. ).toEqual([]);
  139. // 旧名字不再是 BoardSpec 的字段名之外的东西:写 title 就是给板子起名,不是给卡片取标题。
  140. expect(FACADE_DTS).toContain("cardTitle?: string");
  141. });
  142. it("accepts primary on every member and rejects a non-boolean one", () => {
  143. expect(
  144. diagnosticsOf(
  145. `await artifact.file("book", "b.pdf", { primary: true });\n` +
  146. `await artifact.markdown("notes", "# hi", { title: "Notes", primary: false });\n` +
  147. `artifact.board("b", { key: "id", status: "state", columns: ["todo"], primary: true });`,
  148. ),
  149. ).toEqual([]);
  150. expect(
  151. diagnosticsOf(`await artifact.file("book", "b.pdf", { primary: "yes" });`).length,
  152. ).toBeGreaterThan(0);
  153. expect(FACADE_DTS).toContain("primary?: boolean");
  154. });
  155. it("rejects a malformed spec at compile time (missing y, wrong chart type)", () => {
  156. expect(diagnosticsOf(`artifact.chart("perf", { x: { field: "r" } });`).length).toBeGreaterThan(
  157. 0,
  158. );
  159. expect(
  160. diagnosticsOf(
  161. `artifact.chart("perf", { x: { field: "r" }, y: { field: "m" }, type: "pie" });`,
  162. ).length,
  163. ).toBeGreaterThan(0);
  164. });
  165. it("makes report's second argument an optional string", () => {
  166. expect(diagnosticsOf(`report({ a: 1 });\nreport({ a: 1 }, "perf");`)).toEqual([]);
  167. expect(diagnosticsOf(`report({ a: 1 }, 1);`).length).toBeGreaterThan(0);
  168. });
  169. it("leaves artifact out of the snippet facade (TS2304, not a runtime surprise)", () => {
  170. const workflow = createWorkflowProgram(`await artifact.file("book", "b.pdf");`, {
  171. facadeDts: SNIPPET_FACADE_DTS,
  172. });
  173. const diagnostics = collectDiagnostics(workflow.program);
  174. expect(diagnostics.length).toBeGreaterThan(0);
  175. expect(diagnostics[0]?.message).toContain("Cannot find name 'artifact'");
  176. });
  177. });
  178. describe("world.run (compile side)", () => {
  179. it("typechecks and lowers to the run op with positional args", () => {
  180. const workflow = createWorkflowProgram(
  181. `const r = await world.run("lean", ["--make", "proof.lean"], { timeoutMs: 60000 });\n` +
  182. `return r.exitCode === 0;`,
  183. );
  184. expect(collectDiagnostics(workflow.program)).toEqual([]);
  185. const table = collectSites(workflow);
  186. const lowered = lowerWorkflow(workflow, table);
  187. expect(lowered.code).toContain(`__host.worldRead("world-read#1", "run"`);
  188. });
  189. it("collects the deduplicated, sorted command set from literals", () => {
  190. const workflow = createWorkflowProgram(
  191. `await world.run("node", ["-e", "0"]);\n` +
  192. `await world.run(\`lean\`, ["a.lean"]);\n` +
  193. `await world.run("node", ["-e", "1"]);`,
  194. );
  195. const table = collectSites(workflow);
  196. const { commands, diagnostics } = collectWorldRunCommands(workflow, table);
  197. expect(diagnostics).toEqual([]);
  198. expect(commands).toEqual(["lean", "node"]);
  199. });
  200. it("rejects a non-literal cmd with a positioned WORLD_RUN_LITERAL_CODE diagnostic", () => {
  201. const workflow = createWorkflowProgram(
  202. `const cmd = "lean";\nconst r = await world.run(cmd, []);\nreturn r.exitCode;`,
  203. );
  204. expect(collectDiagnostics(workflow.program)).toEqual([]);
  205. const table = collectSites(workflow);
  206. const { diagnostics } = collectWorldRunCommands(workflow, table);
  207. expect(diagnostics).toHaveLength(1);
  208. expect(diagnostics[0]?.code).toBe(WORLD_RUN_LITERAL_CODE);
  209. expect(diagnostics[0]?.line).toBe(2);
  210. expect(diagnostics[0]?.message).toContain("string literal");
  211. // analyzeWorkflowScript 把它与 misuse 同席(ok:false)。
  212. const analyzed = analyzeWorkflowScript(
  213. `const cmd = "lean";\nconst r = await world.run(cmd, []);\nreturn r.exitCode;`,
  214. );
  215. expect(analyzed.ok).toBe(false);
  216. expect(analyzed.diagnostics[0]?.code).toBe(WORLD_RUN_LITERAL_CODE);
  217. });
  218. it("rejects a substitution template cmd", () => {
  219. const workflow = createWorkflowProgram(
  220. `const suffix = "n";\nawait world.run(\`lea\${suffix}\`, []);`,
  221. );
  222. const table = collectSites(workflow);
  223. const { diagnostics } = collectWorldRunCommands(workflow, table);
  224. expect(diagnostics).toHaveLength(1);
  225. });
  226. it("keeps the world.run step label carrying the command (confirmation surface)", () => {
  227. const analyzed = analyzeWorkflowScript(`await world.run("lean", ["a.lean"]);`);
  228. expect(analyzed.ok).toBe(true);
  229. const step = analyzed.causality?.steps.find((s) => s.label.includes("lean"));
  230. expect(step).toBeDefined();
  231. expect(step?.label).toBe("run lean");
  232. });
  233. });
  234. // args 的降级(docs/dynamic-workflow/launch.md「Running a saved workflow」):
  235. // 它是 facade 里唯一一个**值**而不是可调用物,所以走标识符级改写而不是站点。
  236. describe("args lowering", () => {
  237. it("lowers a facade args read to __host.args, with no site of its own", () => {
  238. const workflow = createWorkflowProgram(`const target = String(args.target);\nreturn target;`);
  239. expect(collectDiagnostics(workflow.program)).toEqual([]);
  240. const table = collectSites(workflow);
  241. const lowered = lowerWorkflow(workflow, table);
  242. expect(lowered.code).toContain("__host.args.target");
  243. // 读一个值不是等待点:它不占 site id,也就不会长出因果图节点。
  244. expect(lowered.siteIds).toEqual([]);
  245. });
  246. it("lowers args in the snippet facade too (verbatim portability)", () => {
  247. const workflow = createWorkflowProgram(`return String(args.x);`, {
  248. facadeDts: SNIPPET_FACADE_DTS,
  249. });
  250. expect(collectDiagnostics(workflow.program)).toEqual([]);
  251. const lowered = lowerWorkflow(workflow, collectSites(workflow));
  252. expect(lowered.code).toContain("__host.args.x");
  253. });
  254. // 判定按 checker 解析结果,不按名字:脚本自己声明的 args 解析到脚本文件的符号。
  255. // 名字启发式会把这段改写成 `const __host.args = ...`,一个运行期 SyntaxError。
  256. it("leaves a script-declared local `args` alone", () => {
  257. const workflow = createWorkflowProgram(`const args = { local: 1 };\nreturn args.local;`);
  258. expect(collectDiagnostics(workflow.program)).toEqual([]);
  259. const lowered = lowerWorkflow(workflow, collectSites(workflow));
  260. expect(lowered.code).not.toContain("__host.args");
  261. expect(lowered.code).toContain("args.local");
  262. });
  263. it("leaves a parameter named args and an unrelated `.args` property alone", () => {
  264. const workflow = createWorkflowProgram(
  265. [
  266. "function pick(args: { a: number }): number { return args.a; }",
  267. "const holder = { args: 7 };",
  268. "return pick({ a: 1 }) + holder.args;",
  269. ].join("\n"),
  270. );
  271. expect(collectDiagnostics(workflow.program)).toEqual([]);
  272. const lowered = lowerWorkflow(workflow, collectSites(workflow));
  273. expect(lowered.code).not.toContain("__host.args");
  274. });
  275. // 一段同时用 args 和 ask 的脚本:改写不能破坏站点,站点也不能吞掉 args。
  276. it("coexists with ask sites", () => {
  277. const workflow = createWorkflowProgram(
  278. `const r = await agent("w").ask(String(args.topic));\nreturn r;`,
  279. );
  280. expect(collectDiagnostics(workflow.program)).toEqual([]);
  281. const table = collectSites(workflow);
  282. const lowered = lowerWorkflow(workflow, table);
  283. expect(lowered.code).toContain("__host.args.topic");
  284. expect(lowered.code).toContain('__host.ask("ask#1"');
  285. });
  286. });