lowering.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import { readdirSync, readFileSync } from "node:fs";
  2. import { dirname, join } from "node:path";
  3. import { fileURLToPath } from "node:url";
  4. import { describe, expect, it } from "vitest";
  5. import { HOST_BINDING, lowerWorkflowScript } from "../src/lowering/index.js";
  6. // Lowering 快照 + 语义断言。快照是契约:人类可读的 lowered JS 落在 expected/<base>.js。
  7. // 语义断言超出快照本身:站点 id 恰好一次、类型全擦除(把输出当 JS 解析证明)、无 facade
  8. // 脚本降级为纯 JS、确定性(两次降级逐字节相同)。
  9. const here = dirname(fileURLToPath(import.meta.url));
  10. const loweringDir = join(here, "lowering");
  11. const graphsDir = join(here, "graphs");
  12. // AsyncFunction 构造器:用它把 lowered code 当 JS 解析,证明没有 TS 语法残留
  13. // (顶层 await/return 在 async 函数体里都合法)。
  14. const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor as new (
  15. ...args: string[]
  16. ) => unknown;
  17. /** 每个降级 code 应满足的通用不变量。 */
  18. function assertLowered(source: string): { code: string; siteIds: string[] } {
  19. const result = lowerWorkflowScript(source);
  20. expect(result.diagnostics).toEqual([]);
  21. expect(result.ok).toBe(true);
  22. const lowered = result.lowered;
  23. if (lowered === undefined) throw new Error("expected lowered output for a clean script");
  24. return lowered;
  25. }
  26. /** 站点 id -> 它应被打桩成的 __host.* 调用前缀(不含引号,兼容任意引号风格)。 */
  27. function hostCallFor(siteId: string): string {
  28. // 留白函数体内的站点带 `hole#N/` 前缀(docs/analysis.md「Sites」):按最后一段判种类。
  29. const kindStart = siteId.lastIndexOf("/") + 1;
  30. if (kindStart > 0) return hostCallFor(siteId.slice(kindStart));
  31. if (siteId.startsWith("ask#")) return "__host.ask(";
  32. if (siteId.startsWith("actor#")) return "__host.createActor(";
  33. if (siteId.startsWith("world-read#")) return "__host.worldRead(";
  34. if (siteId.startsWith("report#")) return "__host.report(";
  35. if (siteId.startsWith("hole#")) return "__host.hole(";
  36. throw new Error(`unexpected site id kind: ${siteId}`);
  37. }
  38. const SNAPSHOT_FIXTURES: { base: string; dir: string }[] = [
  39. { base: "log-only", dir: loweringDir },
  40. { base: "no-facade", dir: loweringDir },
  41. { base: "chained-inline-ask", dir: loweringDir },
  42. { base: "helper-asks", dir: loweringDir },
  43. { base: "files-read-glob", dir: loweringDir },
  44. { base: "git-and-grep", dir: loweringDir },
  45. { base: "report-and-log", dir: loweringDir },
  46. { base: "phase-markers", dir: loweringDir },
  47. { base: "channel-future", dir: loweringDir },
  48. { base: "holes", dir: loweringDir },
  49. // 复用三个 graph fixtures:planner-reviewer 覆盖 log/ask/for 循环/Promise.all,
  50. // glob-fanout 覆盖 files.glob + fan-out,user-defined-ask 是负向覆盖——同名的用户
  51. // 自定义 `.ask` 方法必须原样保留,只有 facade 的 agent().ask() 被降级。
  52. { base: "planner-reviewer", dir: graphsDir },
  53. { base: "glob-fanout", dir: graphsDir },
  54. { base: "user-defined-ask", dir: graphsDir },
  55. ];
  56. describe("lowering snapshots", () => {
  57. for (const { base, dir } of SNAPSHOT_FIXTURES) {
  58. it(base, async () => {
  59. const source = readFileSync(join(dir, `${base}.ts`), "utf8");
  60. const { code } = assertLowered(source);
  61. await expect(code).toMatchFileSnapshot(join(loweringDir, "expected", `${base}.js`));
  62. });
  63. }
  64. });
  65. // 广度语义断言:跑遍所有 graph fixtures + lowering fixtures,逐条证明不变量。
  66. const semanticFixtures = [
  67. ...readdirSync(loweringDir)
  68. .filter((n) => n.endsWith(".ts"))
  69. .map((n) => ({ dir: loweringDir, name: n })),
  70. ...readdirSync(graphsDir)
  71. .filter((n) => n.endsWith(".ts"))
  72. .map((n) => ({ dir: graphsDir, name: n })),
  73. ].sort((a, b) => a.name.localeCompare(b.name));
  74. describe("lowering semantics", () => {
  75. it("finds fixtures", () => {
  76. expect(semanticFixtures.length).toBeGreaterThan(0);
  77. });
  78. for (const { dir, name } of semanticFixtures) {
  79. it(`${name}: emits unique host sites, valid JS and deterministic output`, () => {
  80. const source = readFileSync(join(dir, name), "utf8");
  81. const a = assertLowered(source);
  82. const { code, siteIds } = a;
  83. // siteIds 去重后 == 原列表(每个站点唯一)。
  84. expect(new Set(siteIds).size).toBe(siteIds.length);
  85. for (const id of siteIds) {
  86. const quoted = new RegExp(`["']${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']`, "g");
  87. const hits = code.match(quoted) ?? [];
  88. expect(hits.length, `site id ${id} must appear exactly once`).toBe(1);
  89. expect(code, `site id ${id} must sit in ${hostCallFor(id)}`).toContain(
  90. `${hostCallFor(id)}"${id}"`,
  91. );
  92. }
  93. // 复用同一产物检查站点与语法,确定性仍由下方第二次独立降级验证。
  94. // 把输出当 JS 解析:TS 语法(interface / 类型注解 / <T> 类型实参)会让 AsyncFunction 抛错。
  95. expect(() => new AsyncFunction(HOST_BINDING, code)).not.toThrow();
  96. expect(code).not.toContain("interface ");
  97. expect(code).not.toContain("__host.ask<");
  98. // facade 全局名不应作为自由标识符残留——都改写成了 __host.*(phase 改写成 enterPhase)。
  99. expect(code).not.toMatch(/(^|[^.\w])files\.(glob|read|grep)\s*\(/);
  100. expect(code).not.toMatch(/(^|[^.\w])git\.(changedFiles|diff|status|log)\s*\(/);
  101. expect(code).not.toMatch(/(^|[^.\w])phase\s*\(/);
  102. // channel / future 同样改写成 __host.*(docs/dynamic-workflow/authoring.md「Streams」)。
  103. expect(code).not.toMatch(/(^|[^.\w])(channel|future)\s*\(/);
  104. // 留白改写成 __host.hole(docs/dynamic-workflow/authoring.md「Holes」)。
  105. expect(code).not.toMatch(/(^|[^.\w])hole\s*[(<]/);
  106. const b = assertLowered(source);
  107. expect(a.code).toBe(b.code);
  108. expect(a.siteIds).toEqual(b.siteIds);
  109. });
  110. }
  111. });
  112. describe("lowering edge cases", () => {
  113. it("packs world-read arguments positionally into an array literal", () => {
  114. // Boundary A 的 `worldRead(siteId, op, args)`:实参进**数组字面量**,按位置、不加解释
  115. // (spec 的 "lowering never switches on op")。这是"加一个 world-read 原语在 lowering
  116. // 里零改动"的那条契约——多参 op(files.grep / git.diff)走的正是同一条路径。
  117. const source = readFileSync(join(loweringDir, "files-read-glob.ts"), "utf8");
  118. const { code } = assertLowered(source);
  119. expect(code).toContain(`__host.worldRead("world-read#1", "glob", ["src/**/*.ts"])`);
  120. expect(code).toContain(`__host.worldRead("world-read#2", "read", [first])`);
  121. });
  122. it("packs multi-argument and optional world-read arguments positionally", () => {
  123. // 可选实参**缺席就是更短的数组**,不是一个 undefined 洞:`inputHash({op, args})` 是
  124. // journal 键,`["TODO"]` 与 `["TODO", undefined]` 必须是两个不同的键,否则一次
  125. // "加了 glob 的 grep" 会命中一次"没加 glob 的 grep"的记录。
  126. const source = readFileSync(join(loweringDir, "git-and-grep.ts"), "utf8");
  127. const { code } = assertLowered(source);
  128. expect(code).toContain(`__host.worldRead("world-read#1", "grep", ["TODO"])`);
  129. expect(code).toContain(`__host.worldRead("world-read#2", "grep", ["TODO", "*.ts"])`);
  130. expect(code).toContain(`__host.worldRead("world-read#3", "git-changed-files", [])`);
  131. expect(code).toContain(`__host.worldRead("world-read#4", "git-changed-files", ["main"])`);
  132. expect(code).toContain(`__host.worldRead("world-read#5", "git-diff", [])`);
  133. expect(code).toContain(`__host.worldRead("world-read#6", "git-diff", ["main", "src/a.ts"])`);
  134. expect(code).toContain(`__host.worldRead("world-read#7", "git-status", [])`);
  135. expect(code).toContain(`__host.worldRead("world-read#8", "git-log", [])`);
  136. expect(code).toContain(`__host.worldRead("world-read#9", "git-log", [5])`);
  137. });
  138. it("lowers report(item) to __host.report(siteId, item) and log to __host.log", () => {
  139. // report 与 log 的分野在这一趟里最容易写错:两者都是**顶层无容器**的 facade 函数,
  140. // 但 report 有站点(走 siteMap,按 ts.Node 身份命中),log 没有(走 checker 名字识别)。
  141. const { code, siteIds } = assertLowered(
  142. `log("start");\nreport({ a: 1 });\nreport("plain");\nlog("done");\nreturn 1;\n`,
  143. );
  144. expect(siteIds).toEqual(["report#1", "report#2"]);
  145. expect(code).toContain(`__host.report("report#1", { a: 1 })`);
  146. expect(code).toContain(`__host.report("report#2", "plain")`);
  147. expect(code).toContain(`__host.log("start")`);
  148. expect(code).toContain(`__host.log("done")`);
  149. // 反向:log 绝不能被铸成 report 站点。
  150. expect(code).not.toContain(`"report#3"`);
  151. });
  152. it("interleaves report site ids into the global discovery order", () => {
  153. // siteIds 按全局 `order` 排(序列化的归并键),而 per-kind 计数器各自独立——所以
  154. // 插一个 report 会挪动 siteIds 的**顺序**,但不会挪动任何 ask#N / actor#N 的**名字**。
  155. const { siteIds } = assertLowered(
  156. `const a = agent("a");\nreport("before");\nconst x = await a.ask<string>("1");\nreport(x);\nconst y = await a.ask<string>("2");\nreturn x + y;\n`,
  157. );
  158. expect(siteIds).toEqual(["actor#1", "report#1", "ask#1", "report#2", "ask#2"]);
  159. });
  160. it("routes git.log to a world read and the top-level log to __host.log", () => {
  161. // 撞名两侧在同一份降级产物里各归其位。这是注册表按**声明容器**建键的可执行证明:
  162. // 裸名字方案要么给每条 log 铸一个 world-read 站点,要么把 git.log 的站点整个丢掉。
  163. const { code, siteIds } = assertLowered(
  164. `log("start");\nconst c = await git.log(3);\nlog("done");\nreturn c.length;\n`,
  165. );
  166. expect(siteIds).toEqual(["world-read#1"]);
  167. expect(code).toContain(`__host.worldRead("world-read#1", "git-log", [3])`);
  168. expect(code).toContain(`__host.log("start")`);
  169. expect(code).toContain(`__host.log("done")`);
  170. // 反向:没有第二个 world-read 站点,两条 log 都没被误铸成站点。
  171. expect(code).not.toContain(`"world-read#2"`);
  172. });
  173. it("keeps a multi-argument facade call's arguments in source order", () => {
  174. // 用 ask 的 receiver + 实参组合造一个"多个被访问的表达式"的降级:这里钉的是
  175. // visitExpr 对参数列表的遍历不打乱顺序,world-read 的数组打包共用同一段代码。
  176. const { code } = assertLowered(
  177. `const p = agent("p");\nconst paths = await files.glob("a");\n` +
  178. `const out = await p.ask<string>(paths.join(","));\nreturn out;\n`,
  179. );
  180. expect(code).toContain(`__host.worldRead("world-read#1", "glob", ["a"])`);
  181. expect(code).toContain(`__host.ask("ask#1", p, paths.join(","))`);
  182. });
  183. it("preserves the optional-chain short-circuit on ?.ask (identifier receiver)", () => {
  184. // Bug 回归:`p?.ask(x)` 原先被无条件降级成 __host.ask(siteId, p, x),丢掉 `?.` 的短路。
  185. // p 为 undefined 时引擎会把 undefined 接收者判成 UnknownActor 并失败整个 run,而作者
  186. // 程序的语义是「跳过这次 ask,结果 undefined」。
  187. const { code } = assertLowered(
  188. `const flag = "x".length > 1;\nconst p = flag ? agent("a") : undefined;\n` +
  189. `const r = await p?.ask<string>("q");\nreturn r ?? "skipped";\n`,
  190. );
  191. expect(code).toContain(
  192. `p === null || p === undefined ? undefined : __host.ask("ask#1", p, "q")`,
  193. );
  194. });
  195. it("evaluates a non-identifier optional receiver exactly once via a hoisted temp", () => {
  196. const { code } = assertLowered(
  197. `const box = { p: "x".length > 1 ? agent("a") : undefined };\n` +
  198. `const r = await box.p?.ask<string>("q");\nreturn r ?? "skipped";\n`,
  199. );
  200. expect(code).toContain(`var _a`);
  201. expect(code).toContain(
  202. `(_a = box.p) === null || _a === undefined ? undefined : __host.ask("ask#1", _a, "q")`,
  203. );
  204. });
  205. it("optional-chain ask runtime semantics: nullish receiver skips the host call, args unevaluated", async () => {
  206. // 执行降级产物本身(AsyncFunction + stub host)钉住运行期语义:接收者为 nullish 时
  207. // __host.ask 不被调用、实参表达式不被求值,脚本落到 `?? "skipped"` 分支。
  208. const { code } = assertLowered(
  209. `let argEvaluated = false;\nfunction instr(): string { argEvaluated = true; return "q"; }\n` +
  210. `const p = "x".length > 1 ? agent("a") : undefined;\n` +
  211. `const wrap: { p?: Agent } = {};\n` +
  212. `const r1 = await p?.ask<string>(instr());\n` +
  213. `const r2 = await wrap.p?.ask<string>(instr());\n` +
  214. `return { argEvaluated, r1: r1 ?? "skipped", r2: r2 ?? "skipped" };\n`,
  215. );
  216. const askCalls: unknown[][] = [];
  217. const host = {
  218. createActor: () => "actor-handle",
  219. ask: (...args: unknown[]) => {
  220. askCalls.push(args);
  221. return Promise.resolve("answered");
  222. },
  223. };
  224. const run = new AsyncFunction(HOST_BINDING, code) as (h: unknown) => Promise<unknown>;
  225. // "x".length > 1 为假:p 是 undefined,wrap.p 也是 undefined —— 两个 ask 都必须短路。
  226. await expect(run(host)).resolves.toEqual({ argEvaluated: false, r1: "skipped", r2: "skipped" });
  227. expect(askCalls).toEqual([]);
  228. });
  229. it("optional-chain ask runtime semantics: a present receiver still reaches __host.ask", async () => {
  230. const { code } = assertLowered(
  231. `const p = "xy".length > 1 ? agent("a") : undefined;\n` +
  232. `const r = await p?.ask<string>("q");\nreturn r ?? "skipped";\n`,
  233. );
  234. const askCalls: unknown[][] = [];
  235. const host = {
  236. createActor: () => "actor-handle",
  237. ask: (...args: unknown[]) => {
  238. askCalls.push(args);
  239. return Promise.resolve("answered");
  240. },
  241. };
  242. const run = new AsyncFunction(HOST_BINDING, code) as (h: unknown) => Promise<unknown>;
  243. await expect(run(host)).resolves.toBe("answered");
  244. expect(askCalls).toEqual([["ask#1", "actor-handle", "q"]]);
  245. });
  246. it("a script with no facade calls lowers to plain stripped JS (no __host)", () => {
  247. const source = readFileSync(join(loweringDir, "no-facade.ts"), "utf8");
  248. const { code, siteIds } = assertLowered(source);
  249. expect(siteIds).toEqual([]);
  250. expect(code).not.toContain(HOST_BINDING);
  251. });
  252. it("lowers phase() markers to __host.enterPhase(name) and keeps them out of siteIds", async () => {
  253. // 标记无站点、无 journal 行,但控制流经过它这件事要让引擎看见(
  254. // docs/execution-engine.md「From script to sandbox input: lowering」):改写成 __host.enterPhase(name),名字去两端
  255. // 空白(与分析器铸造阶段 id 的键同一)。沙箱里绝不能残留自由标识符 `phase`。
  256. const { code, siteIds } = assertLowered(
  257. `phase("start");\nlog("hi");\nphase(" end ");\nreturn 1;\n`,
  258. );
  259. expect(siteIds).toEqual([]);
  260. expect(code).not.toContain("void 0;");
  261. expect(code).not.toMatch(/(^|[^.\w])phase\s*\(/);
  262. const logged: string[] = [];
  263. const entered: string[] = [];
  264. const run = new AsyncFunction(HOST_BINDING, code) as (host: unknown) => Promise<unknown>;
  265. await expect(
  266. run({ log: (m: string) => logged.push(m), enterPhase: (n: string) => entered.push(n) }),
  267. ).resolves.toBe(1);
  268. expect(logged).toEqual(["hi"]);
  269. expect(entered).toEqual(["start", "end"]);
  270. });
  271. it("leaves siteIds byte-identical with and without markers (site-id stability)", () => {
  272. // site-id stability(docs/analysis.md 的 "Sites")做成可执行
  273. // 断言:标记不占任何计数器,所以在一个脚本里撒满 phase() 之后,lowering 打桩的 site id
  274. // 清单必须逐字节不变——journal 键就是这份清单,挪一个名字就是让一次 resume 认错记录。
  275. const sites =
  276. `const a = agent("a");\n` +
  277. `const paths = await files.glob("*.ts");\n` +
  278. `const x = await a.ask<string>("go");\n` +
  279. `report(x);\n` +
  280. `return paths.length;\n`;
  281. const marked =
  282. `phase("preflight");\n` +
  283. `const a = agent("a");\n` +
  284. `const paths = await files.glob("*.ts");\n` +
  285. `phase("work");\n` +
  286. `const x = await a.ask<string>("go");\n` +
  287. `report(x);\n` +
  288. `phase("wrap-up");\n` +
  289. `return paths.length;\n`;
  290. const bare = assertLowered(sites);
  291. expect(bare.siteIds).toEqual(["actor#1", "world-read#1", "ask#1", "report#1"]);
  292. expect(assertLowered(marked).siteIds).toEqual(bare.siteIds);
  293. });
  294. it("does not lower a dirty script (typecheck error) — no output", () => {
  295. // `agent` 期望 string 名字,传 number 触发类型错误;lowering 只跑在干净程序上。
  296. const result = lowerWorkflowScript(`const a = agent(123);\nawait a.ask("x");\n`);
  297. expect(result.ok).toBe(false);
  298. expect(result.lowered).toBeUndefined();
  299. expect(result.diagnostics.length).toBeGreaterThan(0);
  300. });
  301. it("does not lower a facade-siting violation — no output", () => {
  302. // 取 ask 的引用(method extraction)破坏站点身份,facade-siting 拒绝。
  303. const result = lowerWorkflowScript(`const p = agent("p");\nconst f = p.ask;\nawait f("x");\n`);
  304. expect(result.ok).toBe(false);
  305. expect(result.lowered).toBeUndefined();
  306. });
  307. });