lowering.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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}: every site id appears exactly once in the right __host.* call`, () => {
  80. const source = readFileSync(join(dir, name), "utf8");
  81. const { code, siteIds } = assertLowered(source);
  82. // siteIds 去重后 == 原列表(每个站点唯一)。
  83. expect(new Set(siteIds).size).toBe(siteIds.length);
  84. for (const id of siteIds) {
  85. const quoted = new RegExp(`["']${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']`, "g");
  86. const hits = code.match(quoted) ?? [];
  87. expect(hits.length, `site id ${id} must appear exactly once`).toBe(1);
  88. expect(code, `site id ${id} must sit in ${hostCallFor(id)}`).toContain(
  89. `${hostCallFor(id)}"${id}"`,
  90. );
  91. }
  92. });
  93. it(`${name}: lowers to type-stripped JS (parses as JS, no facade globals)`, () => {
  94. const source = readFileSync(join(dir, name), "utf8");
  95. const { code } = assertLowered(source);
  96. // 把输出当 JS 解析:TS 语法(interface / 类型注解 / <T> 类型实参)会让 AsyncFunction 抛错。
  97. expect(() => new AsyncFunction(HOST_BINDING, code)).not.toThrow();
  98. expect(code).not.toContain("interface ");
  99. expect(code).not.toContain("__host.ask<");
  100. // facade 全局名不应作为自由标识符残留——都改写成了 __host.*(phase 改写成 enterPhase)。
  101. expect(code).not.toMatch(/(^|[^.\w])files\.(glob|read|grep)\s*\(/);
  102. expect(code).not.toMatch(/(^|[^.\w])git\.(changedFiles|diff|status|log)\s*\(/);
  103. expect(code).not.toMatch(/(^|[^.\w])phase\s*\(/);
  104. // channel / future 同样改写成 __host.*(docs/dynamic-workflow/authoring.md「Streams」)。
  105. expect(code).not.toMatch(/(^|[^.\w])(channel|future)\s*\(/);
  106. // 留白改写成 __host.hole(docs/dynamic-workflow/authoring.md「Holes」)。
  107. expect(code).not.toMatch(/(^|[^.\w])hole\s*[(<]/);
  108. });
  109. it(`${name}: is deterministic (lowering twice yields identical bytes)`, () => {
  110. const source = readFileSync(join(dir, name), "utf8");
  111. const a = assertLowered(source);
  112. const b = assertLowered(source);
  113. expect(a.code).toBe(b.code);
  114. expect(a.siteIds).toEqual(b.siteIds);
  115. });
  116. }
  117. });
  118. describe("lowering edge cases", () => {
  119. it("packs world-read arguments positionally into an array literal", () => {
  120. // Boundary A 的 `worldRead(siteId, op, args)`:实参进**数组字面量**,按位置、不加解释
  121. // (spec 的 "lowering never switches on op")。这是"加一个 world-read 原语在 lowering
  122. // 里零改动"的那条契约——多参 op(files.grep / git.diff)走的正是同一条路径。
  123. const source = readFileSync(join(loweringDir, "files-read-glob.ts"), "utf8");
  124. const { code } = assertLowered(source);
  125. expect(code).toContain(`__host.worldRead("world-read#1", "glob", ["src/**/*.ts"])`);
  126. expect(code).toContain(`__host.worldRead("world-read#2", "read", [first])`);
  127. });
  128. it("packs multi-argument and optional world-read arguments positionally", () => {
  129. // 可选实参**缺席就是更短的数组**,不是一个 undefined 洞:`inputHash({op, args})` 是
  130. // journal 键,`["TODO"]` 与 `["TODO", undefined]` 必须是两个不同的键,否则一次
  131. // "加了 glob 的 grep" 会命中一次"没加 glob 的 grep"的记录。
  132. const source = readFileSync(join(loweringDir, "git-and-grep.ts"), "utf8");
  133. const { code } = assertLowered(source);
  134. expect(code).toContain(`__host.worldRead("world-read#1", "grep", ["TODO"])`);
  135. expect(code).toContain(`__host.worldRead("world-read#2", "grep", ["TODO", "*.ts"])`);
  136. expect(code).toContain(`__host.worldRead("world-read#3", "git-changed-files", [])`);
  137. expect(code).toContain(`__host.worldRead("world-read#4", "git-changed-files", ["main"])`);
  138. expect(code).toContain(`__host.worldRead("world-read#5", "git-diff", [])`);
  139. expect(code).toContain(`__host.worldRead("world-read#6", "git-diff", ["main", "src/a.ts"])`);
  140. expect(code).toContain(`__host.worldRead("world-read#7", "git-status", [])`);
  141. expect(code).toContain(`__host.worldRead("world-read#8", "git-log", [])`);
  142. expect(code).toContain(`__host.worldRead("world-read#9", "git-log", [5])`);
  143. });
  144. it("lowers report(item) to __host.report(siteId, item) and log to __host.log", () => {
  145. // report 与 log 的分野在这一趟里最容易写错:两者都是**顶层无容器**的 facade 函数,
  146. // 但 report 有站点(走 siteMap,按 ts.Node 身份命中),log 没有(走 checker 名字识别)。
  147. const { code, siteIds } = assertLowered(
  148. `log("start");\nreport({ a: 1 });\nreport("plain");\nlog("done");\nreturn 1;\n`,
  149. );
  150. expect(siteIds).toEqual(["report#1", "report#2"]);
  151. expect(code).toContain(`__host.report("report#1", { a: 1 })`);
  152. expect(code).toContain(`__host.report("report#2", "plain")`);
  153. expect(code).toContain(`__host.log("start")`);
  154. expect(code).toContain(`__host.log("done")`);
  155. // 反向:log 绝不能被铸成 report 站点。
  156. expect(code).not.toContain(`"report#3"`);
  157. });
  158. it("interleaves report site ids into the global discovery order", () => {
  159. // siteIds 按全局 `order` 排(序列化的归并键),而 per-kind 计数器各自独立——所以
  160. // 插一个 report 会挪动 siteIds 的**顺序**,但不会挪动任何 ask#N / actor#N 的**名字**。
  161. const { siteIds } = assertLowered(
  162. `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`,
  163. );
  164. expect(siteIds).toEqual(["actor#1", "report#1", "ask#1", "report#2", "ask#2"]);
  165. });
  166. it("routes git.log to a world read and the top-level log to __host.log", () => {
  167. // 撞名两侧在同一份降级产物里各归其位。这是注册表按**声明容器**建键的可执行证明:
  168. // 裸名字方案要么给每条 log 铸一个 world-read 站点,要么把 git.log 的站点整个丢掉。
  169. const { code, siteIds } = assertLowered(
  170. `log("start");\nconst c = await git.log(3);\nlog("done");\nreturn c.length;\n`,
  171. );
  172. expect(siteIds).toEqual(["world-read#1"]);
  173. expect(code).toContain(`__host.worldRead("world-read#1", "git-log", [3])`);
  174. expect(code).toContain(`__host.log("start")`);
  175. expect(code).toContain(`__host.log("done")`);
  176. // 反向:没有第二个 world-read 站点,两条 log 都没被误铸成站点。
  177. expect(code).not.toContain(`"world-read#2"`);
  178. });
  179. it("keeps a multi-argument facade call's arguments in source order", () => {
  180. // 用 ask 的 receiver + 实参组合造一个"多个被访问的表达式"的降级:这里钉的是
  181. // visitExpr 对参数列表的遍历不打乱顺序,world-read 的数组打包共用同一段代码。
  182. const { code } = assertLowered(
  183. `const p = agent("p");\nconst paths = await files.glob("a");\n` +
  184. `const out = await p.ask<string>(paths.join(","));\nreturn out;\n`,
  185. );
  186. expect(code).toContain(`__host.worldRead("world-read#1", "glob", ["a"])`);
  187. expect(code).toContain(`__host.ask("ask#1", p, paths.join(","))`);
  188. });
  189. it("preserves the optional-chain short-circuit on ?.ask (identifier receiver)", () => {
  190. // Bug 回归:`p?.ask(x)` 原先被无条件降级成 __host.ask(siteId, p, x),丢掉 `?.` 的短路。
  191. // p 为 undefined 时引擎会把 undefined 接收者判成 UnknownActor 并失败整个 run,而作者
  192. // 程序的语义是「跳过这次 ask,结果 undefined」。
  193. const { code } = assertLowered(
  194. `const flag = "x".length > 1;\nconst p = flag ? agent("a") : undefined;\n` +
  195. `const r = await p?.ask<string>("q");\nreturn r ?? "skipped";\n`,
  196. );
  197. expect(code).toContain(
  198. `p === null || p === undefined ? undefined : __host.ask("ask#1", p, "q")`,
  199. );
  200. });
  201. it("evaluates a non-identifier optional receiver exactly once via a hoisted temp", () => {
  202. const { code } = assertLowered(
  203. `const box = { p: "x".length > 1 ? agent("a") : undefined };\n` +
  204. `const r = await box.p?.ask<string>("q");\nreturn r ?? "skipped";\n`,
  205. );
  206. expect(code).toContain(`var _a`);
  207. expect(code).toContain(
  208. `(_a = box.p) === null || _a === undefined ? undefined : __host.ask("ask#1", _a, "q")`,
  209. );
  210. });
  211. it("optional-chain ask runtime semantics: nullish receiver skips the host call, args unevaluated", async () => {
  212. // 执行降级产物本身(AsyncFunction + stub host)钉住运行期语义:接收者为 nullish 时
  213. // __host.ask 不被调用、实参表达式不被求值,脚本落到 `?? "skipped"` 分支。
  214. const { code } = assertLowered(
  215. `let argEvaluated = false;\nfunction instr(): string { argEvaluated = true; return "q"; }\n` +
  216. `const p = "x".length > 1 ? agent("a") : undefined;\n` +
  217. `const wrap: { p?: Agent } = {};\n` +
  218. `const r1 = await p?.ask<string>(instr());\n` +
  219. `const r2 = await wrap.p?.ask<string>(instr());\n` +
  220. `return { argEvaluated, r1: r1 ?? "skipped", r2: r2 ?? "skipped" };\n`,
  221. );
  222. const askCalls: unknown[][] = [];
  223. const host = {
  224. createActor: () => "actor-handle",
  225. ask: (...args: unknown[]) => {
  226. askCalls.push(args);
  227. return Promise.resolve("answered");
  228. },
  229. };
  230. const run = new AsyncFunction(HOST_BINDING, code) as (h: unknown) => Promise<unknown>;
  231. // "x".length > 1 为假:p 是 undefined,wrap.p 也是 undefined —— 两个 ask 都必须短路。
  232. await expect(run(host)).resolves.toEqual({ argEvaluated: false, r1: "skipped", r2: "skipped" });
  233. expect(askCalls).toEqual([]);
  234. });
  235. it("optional-chain ask runtime semantics: a present receiver still reaches __host.ask", async () => {
  236. const { code } = assertLowered(
  237. `const p = "xy".length > 1 ? agent("a") : undefined;\n` +
  238. `const r = await p?.ask<string>("q");\nreturn r ?? "skipped";\n`,
  239. );
  240. const askCalls: unknown[][] = [];
  241. const host = {
  242. createActor: () => "actor-handle",
  243. ask: (...args: unknown[]) => {
  244. askCalls.push(args);
  245. return Promise.resolve("answered");
  246. },
  247. };
  248. const run = new AsyncFunction(HOST_BINDING, code) as (h: unknown) => Promise<unknown>;
  249. await expect(run(host)).resolves.toBe("answered");
  250. expect(askCalls).toEqual([["ask#1", "actor-handle", "q"]]);
  251. });
  252. it("a script with no facade calls lowers to plain stripped JS (no __host)", () => {
  253. const source = readFileSync(join(loweringDir, "no-facade.ts"), "utf8");
  254. const { code, siteIds } = assertLowered(source);
  255. expect(siteIds).toEqual([]);
  256. expect(code).not.toContain(HOST_BINDING);
  257. });
  258. it("lowers phase() markers to __host.enterPhase(name) and keeps them out of siteIds", async () => {
  259. // 标记无站点、无 journal 行,但控制流经过它这件事要让引擎看见(
  260. // docs/execution-engine.md「From script to sandbox input: lowering」):改写成 __host.enterPhase(name),名字去两端
  261. // 空白(与分析器铸造阶段 id 的键同一)。沙箱里绝不能残留自由标识符 `phase`。
  262. const { code, siteIds } = assertLowered(
  263. `phase("start");\nlog("hi");\nphase(" end ");\nreturn 1;\n`,
  264. );
  265. expect(siteIds).toEqual([]);
  266. expect(code).not.toContain("void 0;");
  267. expect(code).not.toMatch(/(^|[^.\w])phase\s*\(/);
  268. const logged: string[] = [];
  269. const entered: string[] = [];
  270. const run = new AsyncFunction(HOST_BINDING, code) as (host: unknown) => Promise<unknown>;
  271. await expect(
  272. run({ log: (m: string) => logged.push(m), enterPhase: (n: string) => entered.push(n) }),
  273. ).resolves.toBe(1);
  274. expect(logged).toEqual(["hi"]);
  275. expect(entered).toEqual(["start", "end"]);
  276. });
  277. it("leaves siteIds byte-identical with and without markers (site-id stability)", () => {
  278. // site-id stability(docs/analysis.md 的 "Sites")做成可执行
  279. // 断言:标记不占任何计数器,所以在一个脚本里撒满 phase() 之后,lowering 打桩的 site id
  280. // 清单必须逐字节不变——journal 键就是这份清单,挪一个名字就是让一次 resume 认错记录。
  281. const sites =
  282. `const a = agent("a");\n` +
  283. `const paths = await files.glob("*.ts");\n` +
  284. `const x = await a.ask<string>("go");\n` +
  285. `report(x);\n` +
  286. `return paths.length;\n`;
  287. const marked =
  288. `phase("preflight");\n` +
  289. `const a = agent("a");\n` +
  290. `const paths = await files.glob("*.ts");\n` +
  291. `phase("work");\n` +
  292. `const x = await a.ask<string>("go");\n` +
  293. `report(x);\n` +
  294. `phase("wrap-up");\n` +
  295. `return paths.length;\n`;
  296. const bare = assertLowered(sites);
  297. expect(bare.siteIds).toEqual(["actor#1", "world-read#1", "ask#1", "report#1"]);
  298. expect(assertLowered(marked).siteIds).toEqual(bare.siteIds);
  299. });
  300. it("does not lower a dirty script (typecheck error) — no output", () => {
  301. // `agent` 期望 string 名字,传 number 触发类型错误;lowering 只跑在干净程序上。
  302. const result = lowerWorkflowScript(`const a = agent(123);\nawait a.ask("x");\n`);
  303. expect(result.ok).toBe(false);
  304. expect(result.lowered).toBeUndefined();
  305. expect(result.diagnostics.length).toBeGreaterThan(0);
  306. });
  307. it("does not lower a facade-siting violation — no output", () => {
  308. // 取 ask 的引用(method extraction)破坏站点身份,facade-siting 拒绝。
  309. const result = lowerWorkflowScript(`const p = agent("p");\nconst f = p.ask;\nawait f("x");\n`);
  310. expect(result.ok).toBe(false);
  311. expect(result.lowered).toBeUndefined();
  312. });
  313. });