facade-dts.test.ts 18 KB

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