compile.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. analyzeWorkflowScript,
  4. collectSites,
  5. compileWorkflowScript,
  6. createWorkflowProgram,
  7. lowerWorkflow,
  8. lowerWorkflowScript,
  9. synthesizeAskSchemas,
  10. synthesizeWorkflowSchemas,
  11. } from "../src/index.js";
  12. import { collectDiagnostics } from "../src/compiler/compile.js";
  13. // Script-shaped cases live in tests/workflows/ (fixture suite with `// error`
  14. // markers); this file covers the CompileResult API shape itself.
  15. describe("compileWorkflowScript API", () => {
  16. it("returns ok with no diagnostics for a clean script", () => {
  17. const result = compileWorkflowScript(`return await agent("a").ask("do it");`);
  18. expect(result).toEqual({ diagnostics: [], ok: true });
  19. });
  20. it("positions diagnostics on the author's 1-based script lines", () => {
  21. const result = compileWorkflowScript(`const x: number = "not a number";`);
  22. expect(result.ok).toBe(false);
  23. expect(result.diagnostics[0]?.line).toBe(1);
  24. expect(result.diagnostics[0]?.column).toBeGreaterThan(0);
  25. });
  26. it("carries the compiler message and code", () => {
  27. const result = compileWorkflowScript(`process.exit(1);`);
  28. expect(result.diagnostics[0]?.message).toContain("Cannot find name 'process'");
  29. expect(result.diagnostics[0]?.code).toBeGreaterThan(0);
  30. });
  31. });
  32. // Models reach for `declare interface R { ... }` often enough that the raw TS1184
  33. // text ("Modifiers cannot appear here.") became the self-repair loop's main dead
  34. // end: it never names the offending modifier. These pin the rewrite — the message
  35. // must name `declare` / `export` and say to remove it, while the code and the
  36. // script-mapped position stay untouched so the model can still find the line.
  37. describe("ambient-modifier diagnostics", () => {
  38. const declareForms = [
  39. ["declare interface", `declare interface R { a: number }\nreturn 1;`],
  40. ["declare const", `declare const x: number;\nreturn 1;`],
  41. ["declare function", `declare function f(): void;\nreturn 1;`],
  42. ] as const;
  43. for (const [form, script] of declareForms) {
  44. it(`names \`declare\` and says to remove it for ${form}`, () => {
  45. const result = compileWorkflowScript(script);
  46. expect(result.ok).toBe(false);
  47. const diagnostic = result.diagnostics[0];
  48. expect(diagnostic?.message).toContain("`declare`");
  49. expect(diagnostic?.message).toMatch(/Remove `declare`/);
  50. expect(diagnostic?.message).not.toContain("Modifiers cannot appear here");
  51. // Code and position are the model's only handle on *where*: keep both.
  52. expect(diagnostic?.code).toBe(1184);
  53. expect(diagnostic?.line).toBe(1);
  54. expect(diagnostic?.column).toBe(1);
  55. });
  56. }
  57. it("keeps the mapped line when the offending statement is not first", () => {
  58. const result = compileWorkflowScript(
  59. `const before = 1;\n declare interface R { a: number }\nreturn before;`,
  60. );
  61. const diagnostic = result.diagnostics[0];
  62. expect(diagnostic?.code).toBe(1184);
  63. expect(diagnostic?.line).toBe(2);
  64. expect(diagnostic?.column).toBe(3);
  65. expect(diagnostic?.message).toContain("`declare`");
  66. });
  67. it("names `export` and points at the final return instead", () => {
  68. const result = compileWorkflowScript(`export const y = 1;\nreturn y;`);
  69. expect(result.ok).toBe(false);
  70. const diagnostic = result.diagnostics[0];
  71. expect(diagnostic?.message).toContain("`export`");
  72. expect(diagnostic?.message).toMatch(/Remove `export`/);
  73. expect(diagnostic?.message).toContain("return");
  74. expect(diagnostic?.message).not.toContain("Modifiers cannot appear here");
  75. expect(diagnostic?.code).toBe(1184);
  76. expect(diagnostic?.line).toBe(1);
  77. });
  78. it("leaves a plain interface script diagnostic-free", () => {
  79. const result = compileWorkflowScript(
  80. `interface R { done: boolean }\nconst r = await agent("a").ask<R>("do");\nreturn r.done;`,
  81. );
  82. expect(result).toEqual({ diagnostics: [], ok: true });
  83. });
  84. it("keeps the original message for other misplaced modifiers", () => {
  85. // Fallback: only the exact `declare` / `export` spans are rewritten, so an
  86. // unrelated TS1184 still reads as the compiler wrote it.
  87. const result = compileWorkflowScript(`public const z = 1;\nreturn z;`);
  88. const misplaced = result.diagnostics.find((d) => d.code === 1184);
  89. expect(misplaced?.message).toBe("Modifiers cannot appear here.");
  90. });
  91. });
  92. // 脚本以 `strict` 编译但**关闭** `noUncheckedIndexedAccess`(决策记录:docs/dynamic-workflow/
  93. // authoring.md「Compiler options」)。模型按该开关关闭的世界书写——训练语料几乎全是关闭的——
  94. // 开着时 `items[i]` 上的 TS2532/TS18048 是编译失败的最大单一来源,且几乎全落在周围逻辑已经
  95. // 证明了边界的索引上。这里钉住两侧:索引读取不再报 undefined;而 `strictNullChecks` 覆盖的
  96. // 真实风险(`.find()`、`match()`、可选属性、可选参数)仍然照旧报错。
  97. describe("undefined diagnostics under the chosen strictness", () => {
  98. it("accepts an unguarded array index", () => {
  99. const result = compileWorkflowScript(
  100. `const xs: number[] = [1, 2, 3];\nreturn xs[0].toFixed(0);`,
  101. );
  102. expect(result).toEqual({ diagnostics: [], ok: true });
  103. });
  104. it("accepts an unguarded record index and a computed 2-D index", () => {
  105. const result = compileWorkflowScript(
  106. [
  107. `const m: Record<string, number> = {};`,
  108. `const b: string[][] = [["."]];`,
  109. `let n = 0;`,
  110. `for (let r = 0; r < b.length; r++) for (let c = 0; c < b[r].length; c++) n += b[r][c].length;`,
  111. `return m["k"].toFixed(n);`,
  112. ].join("\n"),
  113. );
  114. expect(result).toEqual({ diagnostics: [], ok: true });
  115. });
  116. it("still reports a dereferenced `.find()` result", () => {
  117. const result = compileWorkflowScript(
  118. `const xs: string[] = [];\nconst hit = xs.find((x) => x.length > 0);\nreturn hit.length;`,
  119. );
  120. expect(result.diagnostics[0]?.code).toBe(18048);
  121. expect(result.diagnostics[0]?.message).toContain("'hit' is possibly 'undefined'");
  122. });
  123. it("still reports a dereferenced `match()` result", () => {
  124. const result = compileWorkflowScript(`const m = "a1".match(/\\d/);\nreturn m[0];`);
  125. expect(result.diagnostics[0]?.code).toBe(18047);
  126. expect(result.diagnostics[0]?.message).toContain("possibly 'null'");
  127. });
  128. it("still reports an optional property and an optional parameter", () => {
  129. const property = compileWorkflowScript(
  130. `interface R { a?: string }\nconst r: R = {};\nreturn r.a.length;`,
  131. );
  132. expect(property.diagnostics[0]?.code).toBe(18048);
  133. const parameter = compileWorkflowScript(`const f = (x?: string) => x.length;\nreturn f("a");`);
  134. expect(parameter.diagnostics[0]?.code).toBe(18048);
  135. });
  136. });
  137. // The submit path compiles once and shares the one `ts.Program` across all four
  138. // consumers (diagnostics / site table / schema synthesis / lowering); see the
  139. // 「编译一次」 boundary in docs/dynamic-workflow/presentation.md. These assertions pin the
  140. // promotion of `createWorkflowProgram` + `collectSites` onto the public surface, and
  141. // that one program yields byte-identical site ids to the three-program convenience
  142. // entries. Site ids are journal keys: a drift here surfaces as a `script_hash` /
  143. // `inputHash` mismatch at resume, a long way from its cause.
  144. describe("public one-program chain", () => {
  145. const script = [
  146. `const paths = await files.glob("src/**/*.ts");`,
  147. `const lead = agent("lead");`,
  148. `const plan = await lead.ask<{ steps: string[] }>("Plan the work.");`,
  149. `const notes = await agent("scribe").ask("Summarize.");`,
  150. `return { plan, notes, count: paths.length };`,
  151. ].join("\n");
  152. it("shares one program across site collection, schema synthesis and lowering", () => {
  153. const workflow = createWorkflowProgram(script);
  154. expect(collectDiagnostics(workflow.program)).toEqual([]);
  155. const table = collectSites(workflow);
  156. const { diagnostics, schemas } = synthesizeAskSchemas(workflow, table);
  157. const lowered = lowerWorkflow(workflow, table);
  158. expect(diagnostics).toEqual([]);
  159. expect(table.asks.map((a) => a.id)).toEqual(["ask#1", "ask#2"]);
  160. // A typed ask gets a schema, an untyped one does not: the keys of `schemas` ARE the
  161. // typed-ask predicate.
  162. expect(Object.keys(schemas)).toEqual(["ask#1"]);
  163. expect(lowered.siteIds).toContain("ask#1");
  164. });
  165. it("produces the same site ids as the separate script-level entries", () => {
  166. const workflow = createWorkflowProgram(script);
  167. const table = collectSites(workflow);
  168. // analyze / synthesize / lower each build their own program; one compile must agree
  169. // with them verbatim.
  170. const analyzed = analyzeWorkflowScript(script);
  171. expect(analyzed.ok).toBe(true);
  172. // The graph's ask / world-read nodes are exactly the table's sites (source / sink are
  173. // virtual endpoints and have none).
  174. const graphSiteIds = (analyzed.graph?.nodes ?? [])
  175. .filter((n) => n.kind === "ask" || n.kind === "world-read")
  176. .map((n) => n.id)
  177. .sort();
  178. const tableSiteIds = [...table.asks.map((a) => a.id), ...table.worldReads.map((w) => w.id)].sort();
  179. expect(graphSiteIds).toEqual(tableSiteIds);
  180. expect(tableSiteIds).toEqual(["ask#1", "ask#2", "world-read#1"]);
  181. expect(Object.keys(synthesizeAskSchemas(workflow, table).schemas)).toEqual(
  182. Object.keys(synthesizeWorkflowSchemas(script).schemas),
  183. );
  184. expect(lowerWorkflow(workflow, table)).toEqual(lowerWorkflowScript(script).lowered);
  185. });
  186. it("leaves site ids untouched when the same program is walked twice", () => {
  187. // Site ids come from independent per-kind counters, reset on every collectSites call:
  188. // walking one program twice must not drift the numbering. A newly collected construct
  189. // that consumed the global `order` counter would fail this.
  190. const workflow = createWorkflowProgram(script);
  191. const first = collectSites(workflow);
  192. const second = collectSites(workflow);
  193. expect(second.asks.map((a) => a.id)).toEqual(first.asks.map((a) => a.id));
  194. expect(second.worldReads.map((w) => w.id)).toEqual(first.worldReads.map((w) => w.id));
  195. expect(second.asks.map((a) => a.order)).toEqual(first.asks.map((a) => a.order));
  196. });
  197. });