facade-dts.test.ts 19 KB

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