facade-dts.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import { createHash } from "node:crypto";
  2. import { describe, expect, it } from "vitest";
  3. import {
  4. analyzeWorkflowScript,
  5. collectDiagnostics,
  6. collectSites,
  7. collectWorldRunCommands,
  8. createWorkflowProgram,
  9. FACADE_DTS,
  10. lowerWorkflow,
  11. SNIPPET_FACADE_DTS,
  12. WORLD_RUN_LITERAL_CODE,
  13. } from "../src/index.js";
  14. // 段拆分(docs/dynamic-workflow/authoring.md「The facade」)承诺:FACADE_DTS 由段
  15. // 拼接后逐字节确定。哈希在每次**有意的** facade 文本变更时更新(更新历史即 facade 的
  16. // 变更账本),任何段级编辑都会撞上这条——那是有意的:改 facade 文本必须是一次显式决定,
  17. // 而不是重排段落时的静默漂移。
  18. // - dfd383f3…(2026-08-26):段拆分落地,对拆分前逐字节不变。
  19. // - fb2d9943…(2026-08-26):world.run 段加入(docs/dynamic-workflow/authoring.md)。
  20. // - 7f7d36ee…(2026-08-27):phase 段加入(docs/dynamic-workflow/presentation.md)。
  21. // - 198475cc…(2026-08-28):args 段加入(docs/dynamic-workflow/launch.md)。
  22. // - 807e4b79…(2026-08-29):merge 重算——feat/dynamic-workflow 的 phase 段与
  23. // dwf-reusable 的 args 段会师后的组合哈希(两侧各自的哈希均已不再是当前文本)。
  24. // - e7da7b7b…(2026-08-29):phase 段 JSDoc 重写——提示层强制(必填 + 阶段名人类
  25. // 可读、跟随会话语言),见 docs/dynamic-workflow/authoring.md「Phases」与
  26. // docs/dynamic-workflow/authoring.md「The skill」;声明集(declare 行)不变。
  27. // - 877a78c3…(2026-08-31):actor 段 `agent()` JSDoc 重写——「name 是展示标签」改成
  28. // 「非空名必须 run 内唯一,且是修订续跑(resume_from)缓存匹配的身份键」,含 fan-out
  29. // 里静态名的教改写;phase 段那句「不像 actor 名,那只是展示标签」同批改口径。见
  30. // docs/execution-engine.md「Amend-resume」。声明集(declare 行)不变。
  31. // - 05c3401c…(2026-09-04):artifact 段加入 + report 签名加第二实参
  32. // (docs/dynamic-workflow/authoring.md)。这一条**动了声明集**:新增 `declare const artifact`
  33. // 与七个 spec 接口,`report` 变为 `(item: unknown, artifactId?: string)`。
  34. // - 499c4179…(2026-09-04):`BoardSpec.title` 改名 `cardTitle`。原名与继承自
  35. // `ArtifactOptions` 的 `title`(看板自己的卡片标题)撞在同一个键上,两者都是 string 所以
  36. // TS 收下了它——代价是一个看板永远说不出「这块板叫内存回归,每张卡拿 name 字段当标题」。
  37. // spec 同日改名(docs/dynamic-workflow/authoring.md「The facade」)。
  38. // - 540a2054…(2026-09-04):**纯散文**——actor 段的 artifact → result/output value,
  39. // 把这个词让给 artifact.*。旧措辞(`Node<T>` 的「producing a typed artifact」、
  40. // `Agent.ask` 的「T is the task's output artifact」)说的是引擎内部那一义,而产物段
  41. // 就在同一份 .d.ts 里用同一个词说用户面产物——模型一次看到两义。同批改的还有
  42. // CreateWorkflow 的 RULES 与 dynamic-workflows 技能正文,见
  43. // docs/dynamic-workflow/authoring.md「The guidance」 与 docs/dynamic-workflow/authoring.md「Artifacts: what the user keeps」 的
  44. // 「术语」表。声明集(declare 行)不变。
  45. // - 0dd165d5…(2026-09-05):**纯散文**——phase 段加「每个阶段至少含一次 ask 或一次
  46. // world.run」的规则与改写后的 Idiom 句(docs/dynamic-workflow/presentation.md 同日追记:
  47. // 空阶段一闪而过、看不到进度,模型被教导不要写它)。声明集(declare 行)不变。
  48. // - 99abaa45…(2026-09-05):**纯散文**——`ToolProfile` 与 `AgentPersona.tools` / `model` 的
  49. // JSDoc 重写:「"none" suits cheap judge/extract personas」改成「只在 ask 文本已含全部所需
  50. // 时用 none;要核对文件、追引用、跑东西的用 readonly/default,无工具的子代理遇到那种 ask
  51. // 会升级而不是假装」。起因是实盘 `tools:"none"` 的 GLM 子代理被要求核对磁盘内容后发出
  52. // `escalate("placeholder")`,见 docs/execution-engine.md与
  53. // docs/dynamic-workflow/authoring.md「The skill」。声明集(declare 行)不变。
  54. // - 23aef592…(2026-09-05):上两条在两条分支上各自重钉;合并(dwf-visual-redesign ⇄
  55. // feat/dynamic-workflow)后两段散文同在,按合并结果重钉。声明集(declare 行)不变。
  56. // - b500809e…(2026-09-05):**纯散文**——`artifact` 段的总说明重写为两条习惯:每个 run 发布
  57. // 其**交付物**(用户要网页/PDF 就是那个文件走 file();要的是结论就是报告的长版,通常是
  58. // markdown();一行答案除外)、看板是给盯着 run 的人看的(只在有值得盯的中途状态时声明);
  59. // 外加两条「值不值一张卡」的检验(用户会单独打开吗、是否重复另一产物)。`markdown()` 的
  60. // JSDoc 由「不是 return 的复制」改成「报告型交付物的常见形态」。与 SKILL.md §9 /
  61. // examples.md 同批。声明集(declare 行)不变。
  62. // - f94af7c0…(2026-09-07):**纯散文**——phase 段的命名规则加一句回声:「像告诉同事现在
  63. // 在做什么那样说」,附一对中文正反例("确认测试仍然通过",不是 "执行测试验证任务")。
  64. // 同段重排行宽以守住 max-lines 400(模板字面量里的行算代码行,不算注释)。
  65. // 教法从「三个禁用词」改为「一条原则 + 成对例子」(docs/dynamic-workflow/presentation.md
  66. // 2026-09-07 裁决;完整例子表在 SKILL.md「Write for the user」一节)。声明集(declare 行)不变。
  67. // - 853ae664…(2026-09-11):**动了声明集**——`declare type ModelTier` 与 `AgentPersona.model`
  68. // 退场(docs/dynamic-workflow/authoring.md):宿主没有 lite 模型来源,档位早已是
  69. // 空转的旋钮,却仍占着 facade 的篇幅。子代理一律跑父会话当前模型。
  70. // - fe83dea7…(2026-09-11):**动了声明集**——`ToolProfile` 收成 `"default" | "readonly"`,
  71. // `"none"` 退场(同一决策记录):它比 readonly 多买到的只有「不去读文件」,而这靠 ask 文本
  72. // 就能做到;它另外带来了唯一一族退化升级与三处按档位分支的提示。`ToolProfile` 与
  73. // `AgentPersona.tools` 的 JSDoc 同批改写为两档的说法。
  74. // - dee40f0b…(2026-09-12):**动了声明集**——`declare type ToolProfile` 与 `AgentPersona.tools`
  75. // 整个退场(同一决策记录,第二轮):档位买到的只有「裁判不能改文件」,普通子代理也不靠
  76. // 档位保证这一点,ask 文本说清即可;`AgentPersona` 只剩 `system`,JSDoc 说明每个 actor 都有
  77. // 完整工作工具集。
  78. // - c19c9310…(2026-09-14):只改一句 JSDoc——createActor 名字注释里的「CreateWorkflow with
  79. // resume_from」改为「AmendWorkflow」(修订入口拆成独立工具,docs/dynamic-workflow/launch.md)。
  80. // - 21cb21e1…(2026-09-14):**动了声明集**——`ArtifactOptions.primary?: boolean`
  81. // (docs/dynamic-workflow/authoring.md「Ids, tags and versions」):脚本标出 run 的交付物,完成卡与 run 侧板
  82. // 以它带头。`description` 补 JSDoc(它现在会显示在交付物那一行旁边);`artifact` 的散文加一句
  83. // 「发布多于一件时给交付物标 primary」。
  84. // - abeaec0a…(2026-09-15):合并 dwf-better-artifacts——上两条(AmendWorkflow JSDoc 与
  85. // `ArtifactOptions.primary`)同时在场,哈希取并集后的文本。
  86. // - 7478845e…(2026-09-22):**动了声明集**——stream 段加入(docs/dynamic-workflow/authoring.md
  87. // 「Streams」):`Channel<T>`、`channel()`、`future()`,两个 facade 都含。段文本住在
  88. // facade/dts-stream.ts(dts.ts 顶在行数上限),仍由 dts.ts 拼接。
  89. // - 7fd6b30e…(2026-09-26):**动了声明集**——子代理模型回到 persona(docs/dynamic-workflow/
  90. // authoring.md「Choosing a model per subagent」):`ModelRef`(私有构造器的 class)、`model()`、
  91. // `AgentPersona.model?: ModelRef | string`。只在 actor 段,snippet 不含。
  92. // - 4f79960c…(2026-09-26):只改一句 JSDoc——`report()` 的条数上限由 256 改为 65,536
  93. // (docs/execution-engine.md「Progressive results: `report`」与「Reading the journal」)。
  94. // 声明集(declare 行)不变。
  95. // - 7f7dc6df…(2026-09-26):只改一句 JSDoc——`report()` 的单条上限由 32KB 改为 1 MiB,并加上
  96. // run 级 1 GiB 的字节总数上限(docs/execution-engine.md「Progressive results: `report`」)。
  97. // 声明集(declare 行)不变。
  98. // - a82956e9…(2026-09-26):合并 dwf-report-limit——上三条(persona 的 `ModelRef`/`model()` 与
  99. // `report()` 两句上限 JSDoc)同时在场,哈希取并集后的文本。
  100. // - f1990146…(2026-09-28):**动了声明集**——hole 段加入(docs/dynamic-workflow/authoring.md
  101. // 「Holes: `hole<T>()`」):`hole<T>(name, prompt?)` / `hole<T>(name, body)` /
  102. // `hole<T>(name, prompt, body)` 三个重载。段文本住在 facade/dts-hole.ts,拼在 phase 段之后;
  103. // **只进完整 facade**,snippet 不含(片段没有 run,也就没有可等主代理补全的东西)。
  104. // - b47c6183…(2026-09-28):只改一句 JSDoc——hole 段的禁区收窄为「数组方法的 fan-out 回调」
  105. // (for...of 体允许:顺序循环里第一轮停在留白、补全后每轮跑函数体),并加上「函数体必须
  106. // 内联」一句。声明集(declare 行)不变。
  107. // - 278970c4…(2026-09-30):**纯散文**——注释收成参考层(docs/dynamic-workflow/authoring.md
  108. // 「The facade」):判断层(阶段怎么命名、交付物两条习惯、门控惯用法、流水线阶段的写法等)
  109. // 删去,只留在技能正文里;其余注释按脚本作者的读法改写(actor → subagent、journaled → recorded、
  110. // hole 的读者就是主代理所以称「你」);facade 23 275 → 13 598 字节。声明集(declare 行)不变。
  111. const PINNED_FACADE_SHA256 = "278970c47a2b3e5225d8e993320193221b42bd524121228e363f84ee4654609d";
  112. describe("facade dts segments", () => {
  113. it("FACADE_DTS is byte-identical to the pinned composition", () => {
  114. const hash = createHash("sha256").update(FACADE_DTS, "utf8").digest("hex");
  115. expect(hash).toBe(PINNED_FACADE_SHA256);
  116. });
  117. // 注释只写参考层:做什么、返回什么、何时拒绝或让 run 失败、上限、实参的编译期规则
  118. // (docs/dynamic-workflow/authoring.md「The facade」)。判断层在技能正文里只说一次;facade
  119. // 只经技能 §16.2 进上下文,注释复述正文等于每次写作会话付两遍,且是会漂移的那一份。
  120. // 2026-09-30 去重前是 23 275 字节,其中约 2 万是注释。
  121. it("stays a reference: FACADE_DTS is under 14 000 bytes", () => {
  122. expect(Buffer.byteLength(FACADE_DTS, "utf8")).toBeLessThan(14_000);
  123. });
  124. // args 在**两个** facade 里都在:snippet 的「逐字可迁移」不变式要求一段引用 args 的
  125. // saved 脚本能原样丢进 EvalWorkflowSnippet 编译(运行时它是 `{}`)。
  126. it("SNIPPET_FACADE_DTS keeps world reads, world.run, log and args, drops actors/report/artifact/phase", () => {
  127. expect(SNIPPET_FACADE_DTS).toContain("declare const args");
  128. expect(FACADE_DTS).toContain("declare const args");
  129. expect(SNIPPET_FACADE_DTS).toContain("declare const files");
  130. expect(SNIPPET_FACADE_DTS).toContain("declare const git");
  131. expect(SNIPPET_FACADE_DTS).toContain("declare const world");
  132. expect(SNIPPET_FACADE_DTS).toContain("declare function log");
  133. // stream 段在两个 facade 里都在:流水线的纯逻辑正是片段要排练的东西。
  134. expect(SNIPPET_FACADE_DTS).toContain("declare function channel");
  135. expect(SNIPPET_FACADE_DTS).toContain("declare function future");
  136. expect(SNIPPET_FACADE_DTS).toContain("declare interface Channel<T>");
  137. expect(SNIPPET_FACADE_DTS).not.toContain("declare function agent");
  138. expect(SNIPPET_FACADE_DTS).not.toContain("declare function report");
  139. expect(SNIPPET_FACADE_DTS).not.toContain("declare function phase");
  140. // 模型声明属于 actor:snippet 里没有子代理,也就没有可选的模型。
  141. expect(FACADE_DTS).toContain("declare function model");
  142. expect(SNIPPET_FACADE_DTS).not.toContain("declare function model");
  143. expect(SNIPPET_FACADE_DTS).not.toContain("ModelRef");
  144. // 产物是「run 交给用户的产出」,而 snippet 没有 run:整段刻意缺席,连类型都不留。
  145. expect(FACADE_DTS).toContain("declare const artifact");
  146. expect(SNIPPET_FACADE_DTS).not.toContain("declare const artifact");
  147. expect(SNIPPET_FACADE_DTS).not.toContain("ArtifactRef");
  148. // 留白只在完整 facade 里(docs/dynamic-workflow/authoring.md「Holes」):片段没有 run。
  149. expect(FACADE_DTS).toContain(
  150. "declare function hole<T>(name: string, prompt?: string): Promise<T>;",
  151. );
  152. expect(FACADE_DTS).toContain(
  153. "declare function hole<T>(name: string, body: () => Promise<T>): Promise<T>;",
  154. );
  155. expect(FACADE_DTS).toContain(
  156. "declare function hole<T>(name: string, prompt: string, body: () => Promise<T>): Promise<T>;",
  157. );
  158. expect(SNIPPET_FACADE_DTS).not.toContain("declare function hole");
  159. });
  160. it("rejects hole() in the snippet facade at compile time (TS2304)", () => {
  161. const workflow = createWorkflowProgram(`return await hole<string>("决定");`, {
  162. facadeDts: SNIPPET_FACADE_DTS,
  163. });
  164. const diagnostics = collectDiagnostics(workflow.program);
  165. expect(diagnostics.length).toBeGreaterThan(0);
  166. expect(diagnostics[0]?.message).toContain("Cannot find name 'hole'");
  167. });
  168. // docs/dynamic-workflow/authoring.md「What the facade does not have」:脚本 facade 里没有 budget 标识符。
  169. it("neither facade declares budget", () => {
  170. expect(FACADE_DTS).not.toContain("budget");
  171. expect(SNIPPET_FACADE_DTS).not.toContain("budget");
  172. });
  173. });
  174. describe("snippet compilation (scratch facade)", () => {
  175. const compileSnippet = (scriptText: string) =>
  176. createWorkflowProgram(scriptText, { facadeDts: SNIPPET_FACADE_DTS });
  177. it("compiles a world-read + pure-logic snippet cleanly", () => {
  178. const workflow = compileSnippet(
  179. `const paths = await files.glob("src/**/*.ts");\n` +
  180. `log(\`found \${paths.length}\`);\n` +
  181. `return paths.filter((p) => p.endsWith(".test.ts"));`,
  182. );
  183. expect(collectDiagnostics(workflow.program)).toEqual([]);
  184. });
  185. it("rejects agent() at compile time (TS2304, not a runtime surprise)", () => {
  186. const workflow = compileSnippet(`return await agent("a").ask("do it");`);
  187. const diagnostics = collectDiagnostics(workflow.program);
  188. expect(diagnostics.length).toBeGreaterThan(0);
  189. expect(diagnostics[0]?.message).toContain("Cannot find name 'agent'");
  190. });
  191. it("rejects report() and phase() the same way", () => {
  192. for (const source of [`report({ found: 1 });`, `phase("gate");`]) {
  193. const workflow = compileSnippet(source);
  194. expect(collectDiagnostics(workflow.program).length).toBeGreaterThan(0);
  195. }
  196. });
  197. // facade 身份按声明文件名判定(registry / sites / misuse / lowering 五处);scratch
  198. // facade 若换了文件名,站点收集会静默变空、files.glob 不再降级到 __host.worldRead——
  199. // snippet 编译通过却什么都不做。这条钉住「同名注入」的不变量。
  200. it("lowers files.glob in a snippet to a world-read site (facade filename invariant)", () => {
  201. const workflow = compileSnippet(`return await files.glob("*.ts");`);
  202. expect(collectDiagnostics(workflow.program)).toEqual([]);
  203. const table = collectSites(workflow);
  204. const lowered = lowerWorkflow(workflow, table);
  205. expect(lowered.code).toContain(`__host.worldRead("world-read#1", "glob"`);
  206. });
  207. });
  208. // 产物的**类型面**(docs/dynamic-workflow/authoring.md「Two families」):两族成员的语义
  209. // 不对称必须在类型上就成立——内容成员可 await 出 ArtifactRef,预置成员是 void。
  210. describe("artifact facade (type surface)", () => {
  211. const diagnosticsOf = (scriptText: string) =>
  212. collectDiagnostics(createWorkflowProgram(scriptText).program);
  213. it("types content members as Promise<ArtifactRef>", () => {
  214. expect(
  215. diagnosticsOf(
  216. `const ref = await artifact.file("book", "out/book.pdf", { title: "Book", contentType: "application/pdf" });\n` +
  217. `const md = await artifact.markdown("notes", "# hi", { description: "d" });\n` +
  218. `return ref.id + String(ref.version) + md.id;`,
  219. ),
  220. ).toEqual([]);
  221. });
  222. it("rejects using a content member's result as anything but an ArtifactRef", () => {
  223. const diagnostics = diagnosticsOf(`const n: number = await artifact.file("book", "b.pdf");`);
  224. expect(diagnostics.length).toBeGreaterThan(0);
  225. expect(diagnostics[0]?.message).toContain("not assignable");
  226. });
  227. it("types preset members as void (a declaration has nothing to await)", () => {
  228. expect(
  229. diagnosticsOf(
  230. `artifact.chart("perf", { type: "line", x: { field: "round" }, y: [{ field: "ms", label: "ms" }], scale: "log", baseline: { field: "budget" } });\n` +
  231. `artifact.table("rows", { columns: [{ field: "name" }], key: "name" });\n` +
  232. `artifact.metrics("m", { metrics: [{ field: "p95", unit: "ms" }] });\n` +
  233. `artifact.board("b", { key: "id", status: "state", columns: ["todo", "done"], detail: [{ field: "owner" }] });`,
  234. ),
  235. ).toEqual([]);
  236. const diagnostics = diagnosticsOf(
  237. `const v: number = artifact.chart("perf", { x: { field: "r" }, y: { field: "m" } });`,
  238. );
  239. expect(diagnostics.length).toBeGreaterThan(0);
  240. });
  241. it("lets a board name itself and its cards separately (the cardTitle rename)", () => {
  242. expect(
  243. diagnosticsOf(
  244. `artifact.board("b", { title: "内存回归", key: "id", status: "state", columns: ["todo"], cardTitle: "name" });`,
  245. ),
  246. ).toEqual([]);
  247. // 旧名字不再是 BoardSpec 的字段名之外的东西:写 title 就是给板子起名,不是给卡片取标题。
  248. expect(FACADE_DTS).toContain("cardTitle?: string");
  249. });
  250. it("accepts primary on every member and rejects a non-boolean one", () => {
  251. expect(
  252. diagnosticsOf(
  253. `await artifact.file("book", "b.pdf", { primary: true });\n` +
  254. `await artifact.markdown("notes", "# hi", { title: "Notes", primary: false });\n` +
  255. `artifact.board("b", { key: "id", status: "state", columns: ["todo"], primary: true });`,
  256. ),
  257. ).toEqual([]);
  258. expect(
  259. diagnosticsOf(`await artifact.file("book", "b.pdf", { primary: "yes" });`).length,
  260. ).toBeGreaterThan(0);
  261. expect(FACADE_DTS).toContain("primary?: boolean");
  262. });
  263. it("rejects a malformed spec at compile time (missing y, wrong chart type)", () => {
  264. expect(diagnosticsOf(`artifact.chart("perf", { x: { field: "r" } });`).length).toBeGreaterThan(
  265. 0,
  266. );
  267. expect(
  268. diagnosticsOf(
  269. `artifact.chart("perf", { x: { field: "r" }, y: { field: "m" }, type: "pie" });`,
  270. ).length,
  271. ).toBeGreaterThan(0);
  272. });
  273. it("makes report's second argument an optional string", () => {
  274. expect(diagnosticsOf(`report({ a: 1 });\nreport({ a: 1 }, "perf");`)).toEqual([]);
  275. expect(diagnosticsOf(`report({ a: 1 }, 1);`).length).toBeGreaterThan(0);
  276. });
  277. it("leaves artifact out of the snippet facade (TS2304, not a runtime surprise)", () => {
  278. const workflow = createWorkflowProgram(`await artifact.file("book", "b.pdf");`, {
  279. facadeDts: SNIPPET_FACADE_DTS,
  280. });
  281. const diagnostics = collectDiagnostics(workflow.program);
  282. expect(diagnostics.length).toBeGreaterThan(0);
  283. expect(diagnostics[0]?.message).toContain("Cannot find name 'artifact'");
  284. });
  285. });
  286. describe("world.run (compile side)", () => {
  287. it("typechecks and lowers to the run op with positional args", () => {
  288. const workflow = createWorkflowProgram(
  289. `const r = await world.run("lean", ["--make", "proof.lean"], { timeoutMs: 60000 });\n` +
  290. `return r.exitCode === 0;`,
  291. );
  292. expect(collectDiagnostics(workflow.program)).toEqual([]);
  293. const table = collectSites(workflow);
  294. const lowered = lowerWorkflow(workflow, table);
  295. expect(lowered.code).toContain(`__host.worldRead("world-read#1", "run"`);
  296. });
  297. it("collects the deduplicated, sorted command set from literals", () => {
  298. const workflow = createWorkflowProgram(
  299. `await world.run("node", ["-e", "0"]);\n` +
  300. `await world.run(\`lean\`, ["a.lean"]);\n` +
  301. `await world.run("node", ["-e", "1"]);`,
  302. );
  303. const table = collectSites(workflow);
  304. const { commands, diagnostics } = collectWorldRunCommands(workflow, table);
  305. expect(diagnostics).toEqual([]);
  306. expect(commands).toEqual(["lean", "node"]);
  307. });
  308. it("rejects a non-literal cmd with a positioned WORLD_RUN_LITERAL_CODE diagnostic", () => {
  309. const workflow = createWorkflowProgram(
  310. `const cmd = "lean";\nconst r = await world.run(cmd, []);\nreturn r.exitCode;`,
  311. );
  312. expect(collectDiagnostics(workflow.program)).toEqual([]);
  313. const table = collectSites(workflow);
  314. const { diagnostics } = collectWorldRunCommands(workflow, table);
  315. expect(diagnostics).toHaveLength(1);
  316. expect(diagnostics[0]?.code).toBe(WORLD_RUN_LITERAL_CODE);
  317. expect(diagnostics[0]?.line).toBe(2);
  318. expect(diagnostics[0]?.message).toContain("string literal");
  319. // analyzeWorkflowScript 把它与 misuse 同席(ok:false)。
  320. const analyzed = analyzeWorkflowScript(
  321. `const cmd = "lean";\nconst r = await world.run(cmd, []);\nreturn r.exitCode;`,
  322. );
  323. expect(analyzed.ok).toBe(false);
  324. expect(analyzed.diagnostics[0]?.code).toBe(WORLD_RUN_LITERAL_CODE);
  325. });
  326. it("rejects a substitution template cmd", () => {
  327. const workflow = createWorkflowProgram(
  328. `const suffix = "n";\nawait world.run(\`lea\${suffix}\`, []);`,
  329. );
  330. const table = collectSites(workflow);
  331. const { diagnostics } = collectWorldRunCommands(workflow, table);
  332. expect(diagnostics).toHaveLength(1);
  333. });
  334. it("keeps the world.run step label carrying the command (confirmation surface)", () => {
  335. const analyzed = analyzeWorkflowScript(`await world.run("lean", ["a.lean"]);`);
  336. expect(analyzed.ok).toBe(true);
  337. const step = analyzed.causality?.steps.find((s) => s.label.includes("lean"));
  338. expect(step).toBeDefined();
  339. expect(step?.label).toBe("run lean");
  340. });
  341. });
  342. // args 的降级(docs/dynamic-workflow/launch.md「Running a saved workflow」):
  343. // 它是 facade 里唯一一个**值**而不是可调用物,所以走标识符级改写而不是站点。
  344. describe("args lowering", () => {
  345. it("lowers a facade args read to __host.args, with no site of its own", () => {
  346. const workflow = createWorkflowProgram(`const target = String(args.target);\nreturn target;`);
  347. expect(collectDiagnostics(workflow.program)).toEqual([]);
  348. const table = collectSites(workflow);
  349. const lowered = lowerWorkflow(workflow, table);
  350. expect(lowered.code).toContain("__host.args.target");
  351. // 读一个值不是等待点:它不占 site id,也就不会长出因果图节点。
  352. expect(lowered.siteIds).toEqual([]);
  353. });
  354. it("lowers args in the snippet facade too (verbatim portability)", () => {
  355. const workflow = createWorkflowProgram(`return String(args.x);`, {
  356. facadeDts: SNIPPET_FACADE_DTS,
  357. });
  358. expect(collectDiagnostics(workflow.program)).toEqual([]);
  359. const lowered = lowerWorkflow(workflow, collectSites(workflow));
  360. expect(lowered.code).toContain("__host.args.x");
  361. });
  362. // 判定按 checker 解析结果,不按名字:脚本自己声明的 args 解析到脚本文件的符号。
  363. // 名字启发式会把这段改写成 `const __host.args = ...`,一个运行期 SyntaxError。
  364. it("leaves a script-declared local `args` alone", () => {
  365. const workflow = createWorkflowProgram(`const args = { local: 1 };\nreturn args.local;`);
  366. expect(collectDiagnostics(workflow.program)).toEqual([]);
  367. const lowered = lowerWorkflow(workflow, collectSites(workflow));
  368. expect(lowered.code).not.toContain("__host.args");
  369. expect(lowered.code).toContain("args.local");
  370. });
  371. it("leaves a parameter named args and an unrelated `.args` property alone", () => {
  372. const workflow = createWorkflowProgram(
  373. [
  374. "function pick(args: { a: number }): number { return args.a; }",
  375. "const holder = { args: 7 };",
  376. "return pick({ a: 1 }) + holder.args;",
  377. ].join("\n"),
  378. );
  379. expect(collectDiagnostics(workflow.program)).toEqual([]);
  380. const lowered = lowerWorkflow(workflow, collectSites(workflow));
  381. expect(lowered.code).not.toContain("__host.args");
  382. });
  383. // 一段同时用 args 和 ask 的脚本:改写不能破坏站点,站点也不能吞掉 args。
  384. it("coexists with ask sites", () => {
  385. const workflow = createWorkflowProgram(
  386. `const r = await agent("w").ask(String(args.topic));\nreturn r;`,
  387. );
  388. expect(collectDiagnostics(workflow.program)).toEqual([]);
  389. const table = collectSites(workflow);
  390. const lowered = lowerWorkflow(workflow, table);
  391. expect(lowered.code).toContain("__host.args.topic");
  392. expect(lowered.code).toContain('__host.ask("ask#1"');
  393. });
  394. });