hole-sites.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. import { describe, expect, it } from "vitest";
  2. import { createWorkflowProgram } from "../src/compiler/compile.js";
  3. import { collectSites } from "../src/analysis/sites.js";
  4. import { collectHoleDiagnostics, HOLE_CODE } from "../src/analysis/hole-sites.js";
  5. import { holePrefixOf, holeSiteId, isHoleSiteId } from "../src/analysis/hole-id.js";
  6. import { FACADE_SITING_CODE } from "../src/analysis/facade-misuse.js";
  7. import {
  8. analyzeWorkflowScript,
  9. checkSiteStability,
  10. collectPhaseNames,
  11. collectSitePhases,
  12. lowerWorkflow,
  13. lowerWorkflowScript,
  14. MAIN_LANE,
  15. spliceHoleBody,
  16. } from "../src/index.js";
  17. // 留白的编译面(docs/dynamic-workflow/authoring.md「Holes」,docs/analysis.md「Sites」):站点收集
  18. // (名字键 id、一层前缀计数器、tail、三个重载)、规则 9012、图投影(步 / 阶段 / fill / holes)、
  19. // lowering(holeBodies 与站点处的求值器)、以及补全服务的两件纯文本工具。
  20. // 留白 id 是名字键(hole-id.ts):测试里按名字取,不写死哈希。
  21. const GROUP = holeSiteId("决定分组");
  22. const ORDER = holeSiteId("决定顺序");
  23. const VERDICT = holeSiteId("评判");
  24. const DECIDE = holeSiteId("决定");
  25. const OUTER = holeSiteId("外");
  26. const INNER = holeSiteId("内");
  27. describe("hole ids (name key)", () => {
  28. it("is hole# plus eight hex digits of the trimmed name, the same at any depth", () => {
  29. expect(GROUP).toMatch(/^hole#[0-9a-f]{8}$/u);
  30. expect(holeSiteId(" 决定分组 ")).toBe(GROUP);
  31. expect(holeSiteId("决定分组 ")).toBe(GROUP);
  32. expect(ORDER).not.toBe(GROUP);
  33. expect(isHoleSiteId(GROUP)).toBe(true);
  34. expect(isHoleSiteId("hole#1")).toBe(false);
  35. expect(isHoleSiteId(`${GROUP}/ask#1`)).toBe(false);
  36. expect(holePrefixOf(`${GROUP}/ask#1`)).toBe(GROUP);
  37. expect(holePrefixOf(GROUP)).toBeUndefined();
  38. expect(holePrefixOf("ask#1")).toBeUndefined();
  39. });
  40. it("reports two different names that hash to one id as 9012 instead of guessing", () => {
  41. // 离线搜到的一对 FNV-1a 32 位撞车名(k32728 / k261234 → 0x92c402be)。
  42. expect(holeSiteId("k32728")).toBe(holeSiteId("k261234"));
  43. const { diagnostics } = sitesOf(
  44. `const a = await hole<string>("k32728");
  45. const b = await hole<string>("k261234");
  46. return a + b;`,
  47. );
  48. expect(diagnostics).toHaveLength(1);
  49. expect(diagnostics[0]?.code).toBe(HOLE_CODE);
  50. expect(diagnostics[0]?.line).toBe(2);
  51. expect(diagnostics[0]?.message).toContain("same site id");
  52. });
  53. });
  54. const sitesOf = (scriptText: string) => {
  55. const workflow = createWorkflowProgram(scriptText);
  56. const table = collectSites(workflow);
  57. return { diagnostics: collectHoleDiagnostics(workflow, table), table, workflow };
  58. };
  59. const OPEN = [
  60. `interface Plan { groups: string[][] }`,
  61. `const survey = await agent("勘察员").ask<string>("摸底");`,
  62. `const plan = await hole<Plan>("决定分组", \`最慢的是 \${survey}\`);`,
  63. `return agent("执行者").ask<string>(\`按 \${plan.groups.length} 组执行\`);`,
  64. ].join("\n");
  65. const FILLED = [
  66. `interface Plan { groups: string[][] }`,
  67. `const survey = await agent("勘察员").ask<string>("摸底");`,
  68. `const plan = await hole<Plan>("决定分组", \`最慢的是 \${survey}\`, async () => {`,
  69. ` phase("分组");`,
  70. ` return await agent("分组员").ask<Plan>(\`分组 \${survey}\`);`,
  71. `});`,
  72. `return agent("执行者").ask<string>(\`按 \${plan.groups.length} 组执行\`);`,
  73. ].join("\n");
  74. describe("hole site collection", () => {
  75. it("collects an open hole keyed by its name, consuming the global order", () => {
  76. const { diagnostics, table } = sitesOf(OPEN);
  77. expect(diagnostics).toEqual([]);
  78. expect(table.holes).toHaveLength(1);
  79. const [site] = table.holes;
  80. expect(site?.id).toBe(GROUP);
  81. expect(site?.fill).toBeUndefined();
  82. expect(site?.name).toBe("决定分组");
  83. expect(site?.typeText).toBe("Plan");
  84. expect(site?.prompt).toBeDefined();
  85. expect(site?.body).toBeUndefined();
  86. expect(site?.tail).toBe(false);
  87. expect(site?.order).toBe(2);
  88. // 留白之后的站点照常编号:留白不是另一套计数器的起点。
  89. expect(table.asks.map((s) => s.id)).toEqual(["ask#1", "ask#2"]);
  90. expect(table.actors.map((s) => s.id)).toEqual(["actor#1", "actor#2"]);
  91. });
  92. it("prefixes every id minted inside a body and leaves the outer ids untouched", () => {
  93. const outer = sitesOf(OPEN).table;
  94. const { diagnostics, table } = sitesOf(FILLED);
  95. expect(diagnostics).toEqual([]);
  96. expect(table.holes[0]?.body).toBeDefined();
  97. expect(table.asks.map((s) => s.id)).toEqual(["ask#1", `${GROUP}/ask#1`, "ask#2"]);
  98. expect(table.actors.map((s) => s.id)).toEqual(["actor#1", `${GROUP}/actor#1`, "actor#2"]);
  99. // 站点 id 稳定性规则延伸到「加函数体」:体外每个 id 逐字不变。
  100. const ids = (t: typeof table) =>
  101. [...t.asks, ...t.actors, ...t.holes].map((s) => s.id).filter((id) => !id.includes("/"));
  102. expect(ids(table)).toEqual(ids(outer));
  103. // 函数体里的 return 不是顶层 return。
  104. expect(table.topLevelReturns).toHaveLength(1);
  105. // 体内的标记照常收集(它没有 id)。
  106. expect(table.phases.map((m) => m.name)).toEqual(["分组"]);
  107. });
  108. it("nests: a hole inside a body keeps a flat name-key id, records its enclosing hole in fill, and its body opens a third counter set", () => {
  109. const { diagnostics, table } = sitesOf(
  110. [
  111. `const plan = await hole<string>("外", "p", async () => {`,
  112. ` const inner = await hole<string>("内", "q", async () => {`,
  113. ` return await agent("a").ask<string>("x");`,
  114. ` });`,
  115. ` return inner;`,
  116. `});`,
  117. `return plan;`,
  118. ].join("\n"),
  119. );
  120. expect(diagnostics).toEqual([]);
  121. expect(table.holes.map((s) => [s.id, s.fill])).toEqual([
  122. [OUTER, undefined],
  123. [INNER, OUTER],
  124. ]);
  125. // 前缀只有一层:内层留白体内的站点带内层的 id,不带外层的。
  126. expect(table.asks.map((s) => s.id)).toEqual([`${INNER}/ask#1`]);
  127. });
  128. it("marks the tail form and distinguishes the three overloads", () => {
  129. const tail = sitesOf(`return await hole<string>("评判", "p");`).table.holes[0];
  130. expect(tail?.tail).toBe(true);
  131. expect(tail?.prompt).toBeDefined();
  132. const bodyOnly = sitesOf(`return await hole<string>("评判", async () => "x");`).table.holes[0];
  133. expect(bodyOnly?.prompt).toBeUndefined();
  134. expect(bodyOnly?.body).toBeDefined();
  135. const inHelper = sitesOf(
  136. `async function f(): Promise<string> { return await hole<string>("评判"); }\nreturn await f();`,
  137. ).table.holes[0];
  138. expect(inHelper?.tail).toBe(false);
  139. expect(inHelper?.prompt).toBeUndefined();
  140. });
  141. it("ignores a script-local function named hole (identity by declaration)", () => {
  142. const { table } = sitesOf(
  143. `async function hole(n: string): Promise<string> { return n; }\nreturn await hole("x");`,
  144. );
  145. expect(table.holes).toEqual([]);
  146. });
  147. });
  148. describe("hole diagnostics (9012)", () => {
  149. const codes = (scriptText: string) => sitesOf(scriptText).diagnostics.map((d) => d.code);
  150. const messages = (scriptText: string) => sitesOf(scriptText).diagnostics.map((d) => d.message);
  151. it("requires an explicit type argument", () => {
  152. const { diagnostics } = sitesOf(`const x = await hole("决定", "p");\nreturn x;`);
  153. expect(diagnostics).toHaveLength(1);
  154. expect(diagnostics[0]?.code).toBe(HOLE_CODE);
  155. expect(diagnostics[0]?.message).toContain("explicit type argument");
  156. expect(diagnostics[0]?.line).toBe(1);
  157. });
  158. it("requires a non-empty literal name of at most 128 characters", () => {
  159. expect(messages(`const n = "x";\nconst v = await hole<string>(n);\nreturn v;`)[0]).toContain(
  160. "string literal",
  161. );
  162. expect(messages(`const v = await hole<string>("");\nreturn v;`)[0]).toContain("no name");
  163. expect(
  164. messages(`const v = await hole<string>("${"名".repeat(129)}");\nreturn v;`)[0],
  165. ).toContain("128");
  166. expect(codes(`const v = await hole<string>("${"名".repeat(128)}");\nreturn v;`)).toEqual([]);
  167. });
  168. it("rejects a name shared by two holes, and a name shared with a phase marker", () => {
  169. const twice = sitesOf(
  170. `const a = await hole<string>("决定");\nconst b = await hole<string>("决定");\nreturn a + b;`,
  171. ).diagnostics;
  172. expect(twice).toHaveLength(1);
  173. expect(twice[0]?.line).toBe(2); // 报在后一个上
  174. expect(twice[0]?.message).toContain("two holes are named");
  175. const marker = sitesOf(
  176. `phase("决定");\nconst a = await hole<string>("决定");\nreturn a;`,
  177. ).diagnostics;
  178. expect(marker).toHaveLength(1);
  179. expect(marker[0]?.line).toBe(2);
  180. expect(marker[0]?.message).toContain("phase(");
  181. // 嵌套补全里的名字也算:体内的标记与外面的留白撞名。
  182. const nested = sitesOf(
  183. `const a = await hole<string>("决定", async () => {\n phase("决定");\n return "x";\n});\nreturn a;`,
  184. ).diagnostics;
  185. expect(nested).toHaveLength(1);
  186. });
  187. it("requires the call to be awaited where it is called", () => {
  188. expect(messages(`const p = hole<string>("决定");\nreturn await p;`)[0]).toContain(
  189. "must be awaited",
  190. );
  191. expect(messages(`return hole<string>("决定");`)[0]).toContain("must be awaited");
  192. expect(codes(`return await hole<string>("决定");`)).toEqual([]);
  193. });
  194. it("rejects a hole inside an array-method callback, allows for...of and plain loops", () => {
  195. expect(
  196. messages(
  197. `const xs = [1, 2];\nconst ys = await Promise.all(xs.map(async (x) => await hole<string>(\`h\${x}\`)));\nreturn ys;`,
  198. ),
  199. ).toEqual([expect.stringContaining("string literal"), expect.stringContaining("fan-out")]);
  200. // 未提升的候选也算:forEach 的回调里没有别的站点,留白本身就是它到达的第一个站点。
  201. expect(
  202. messages(`[1, 2].forEach(async () => {\n await hole<string>("决定");\n});\nreturn 1;`)[0],
  203. ).toContain("fan-out");
  204. // for...of 带 await 是顺序的:第一轮停在留白,补全后每轮跑函数体(authoring.md「Holes」)。
  205. expect(codes(`for (const x of [1, 2]) {\n await hole<string>("决定");\n}\nreturn 1;`)).toEqual(
  206. [],
  207. );
  208. expect(
  209. codes(`for (let i = 0; i < 2; i += 1) {\n await hole<string>("决定");\n}\nreturn 1;`),
  210. ).toEqual([]);
  211. });
  212. it("rejects a body that reads a binding declared after the hole, allows hoisted and body-local ones", () => {
  213. const late = sitesOf(
  214. [
  215. `const v = await hole<string>("决定", async () => {`,
  216. ` return later + fn();`,
  217. `});`,
  218. `const later = "x";`,
  219. `function fn(): string { return "y"; }`,
  220. `return v;`,
  221. ].join("\n"),
  222. ).diagnostics;
  223. expect(late).toHaveLength(1);
  224. expect(late[0]?.message).toContain('"later"');
  225. expect(late[0]?.line).toBe(2);
  226. expect(
  227. codes(
  228. [
  229. `const before = "b";`,
  230. `const v = await hole<string>("决定", async () => {`,
  231. ` const local = before;`,
  232. ` return local;`,
  233. `});`,
  234. `return v;`,
  235. ].join("\n"),
  236. ),
  237. ).toEqual([]);
  238. });
  239. it("requires the body to be an inline function literal", () => {
  240. expect(
  241. messages(
  242. `const body = async () => "x";\nconst v = await hole<string>("决定", body);\nreturn v;`,
  243. )[0],
  244. ).toContain("inline");
  245. expect(
  246. messages(
  247. `const body = async () => "x";\nconst v = await hole<string>("决定", "p", body);\nreturn v;`,
  248. )[0],
  249. ).toContain("inline");
  250. });
  251. it("is wired into analyze and lower (ok: false, graphs withheld, nothing lowered)", () => {
  252. const script = `const v = await hole<string>("决定");\nconst w = await hole<string>("决定");\nreturn v + w;`;
  253. const analyzed = analyzeWorkflowScript(script);
  254. expect(analyzed.ok).toBe(false);
  255. expect(analyzed.diagnostics.map((d) => d.code)).toEqual([HOLE_CODE]);
  256. expect(analyzed.graph).toBeUndefined();
  257. const lowered = lowerWorkflowScript(script);
  258. expect(lowered.ok).toBe(false);
  259. expect(lowered.lowered).toBeUndefined();
  260. });
  261. it("leaves aliasing the facade function to facade-siting (9001)", () => {
  262. const analyzed = analyzeWorkflowScript(`const h = hole;\nreturn await h<string>("决定");`);
  263. expect(analyzed.diagnostics.map((d) => d.code)).toContain(FACADE_SITING_CODE);
  264. });
  265. });
  266. describe("holes in the graphs", () => {
  267. it("draws an open hole as a step in the main lane with its prompt as a sink and a memberless phase", () => {
  268. const analyzed = analyzeWorkflowScript(OPEN);
  269. expect(analyzed.ok).toBe(true);
  270. const node = analyzed.graph?.nodes.find((n) => n.id === GROUP);
  271. expect(node?.kind).toBe("hole");
  272. expect(node?.label).toBe("决定分组");
  273. expect(node?.artifactType).toBe("Plan");
  274. expect(analyzed.graph?.edges).toContainEqual({
  275. exact: true,
  276. from: "ask#1",
  277. kind: "data",
  278. to: GROUP,
  279. type: "string",
  280. });
  281. expect(analyzed.graph?.edges).toContainEqual({
  282. exact: true,
  283. from: GROUP,
  284. kind: "data",
  285. to: "ask#2",
  286. type: "Plan",
  287. });
  288. const step = analyzed.causality?.steps.find((s) => s.id === GROUP);
  289. expect(step?.kind).toBe("hole");
  290. expect(step?.lane).toBe(MAIN_LANE);
  291. expect(step?.fill).toBeUndefined();
  292. expect(analyzed.causality?.lanes[0]?.id).toBe(MAIN_LANE);
  293. // 留白是一个阶段:控制流投影的阶段表里有它、没有成员;因果图的阶段表(按成员)没有它。
  294. expect(analyzed.flow?.phases?.map((p) => p.id)).toEqual(["unphased", GROUP]);
  295. expect(analyzed.flow?.nodes.filter((n) => n.kind === "issue" && n.phase === GROUP)).toEqual([]);
  296. expect(analyzed.causality?.phases?.map((p) => p.id)).toEqual(["unphased"]);
  297. expect(analyzed.flow?.holes).toEqual([
  298. { name: "决定分组", phase: "unphased", siteId: GROUP, type: "Plan" },
  299. ]);
  300. });
  301. it("marks the tail form on the display's holes", () => {
  302. const analyzed = analyzeWorkflowScript(`return await hole<string>("评判");`);
  303. expect(analyzed.flow?.holes).toEqual([
  304. { name: "评判", phase: "unphased", siteId: VERDICT, tail: true, type: "string" },
  305. ]);
  306. expect(analyzed.causality?.sink?.fedBy).toEqual([VERDICT]);
  307. });
  308. it("gives a filled hole no step, a phase that claims the body up to its first marker, and fill on what the fill wrote", () => {
  309. const analyzed = analyzeWorkflowScript(FILLED);
  310. expect(analyzed.ok).toBe(true);
  311. expect(analyzed.graph?.nodes.some((n) => n.id === GROUP)).toBe(false);
  312. expect(analyzed.flow?.holes).toBeUndefined();
  313. // 函数体以标记开头:留白自己的阶段没有成员,但它有 mark 节点,所以仍在阶段表里(接龙的每一步
  314. // 名字因此留在侧栏);顶层留白的阶段不带 fill,体内的阶段带 fill 指回它。
  315. expect(analyzed.flow?.phases).toEqual([
  316. { id: "unphased" },
  317. { id: GROUP, loc: { column: 20, line: 3 }, name: "决定分组" },
  318. { fill: GROUP, id: "phase#1", loc: { column: 3, line: 4 }, name: "分组" },
  319. ]);
  320. // 因果图的阶段表按成员:空的留白阶段不在里面。
  321. expect(analyzed.causality?.phases?.map((p) => p.id)).toEqual(["unphased", "phase#1"]);
  322. const bodyAsk = analyzed.causality?.steps.find((s) => s.id === `${GROUP}/ask#1`);
  323. expect(bodyAsk?.fill).toBe(GROUP);
  324. expect(bodyAsk?.phase).toBe("phase#1");
  325. expect(bodyAsk?.lane).toBe(`${GROUP}/actor#1`);
  326. expect(analyzed.causality?.steps.find((s) => s.id === "ask#2")?.fill).toBeUndefined();
  327. // 没有标记的函数体:留白自己的阶段认领体内的 ask,站在它的名字下。
  328. const noMarker = analyzeWorkflowScript(FILLED.replace(` phase("分组");\n`, ""));
  329. expect(noMarker.flow?.phases).toEqual([
  330. { id: "unphased" },
  331. { id: GROUP, loc: { column: 20, line: 3 }, name: "决定分组" },
  332. ]);
  333. expect(noMarker.causality?.steps.find((s) => s.id === `${GROUP}/ask#1`)?.phase).toBe(GROUP);
  334. });
  335. it("stamps body sites with the hole's name in the site-phase table, and lists phases with the open-hole index", () => {
  336. const script = [
  337. `phase("摸底");`,
  338. `const survey = await agent("勘察员").ask<string>("摸底");`,
  339. `const plan = await hole<string>("决定分组", \`\${survey}\`, async () => {`,
  340. ` return await agent("分组员").ask<string>("分组");`,
  341. `});`,
  342. `const order = await hole<string>("决定顺序");`,
  343. `phase("执行");`,
  344. `return agent("执行者").ask<string>(\`\${plan}\${order}\`);`,
  345. ].join("\n");
  346. const analyzed = analyzeWorkflowScript(script);
  347. expect(analyzed.ok).toBe(true);
  348. const phases = collectSitePhases(analyzed.core!);
  349. expect(phases.get(`${GROUP}/ask#1`)).toBe("决定分组");
  350. expect(phases.get(ORDER)).toBe("摸底"); // 开放的留白站在「摸底」里
  351. expect(collectPhaseNames(analyzed.flow)).toEqual({
  352. holes: [2],
  353. phaseNames: ["摸底", "决定分组", "决定顺序", "执行"],
  354. });
  355. expect(collectPhaseNames(undefined)).toEqual({ holes: [], phaseNames: [] });
  356. });
  357. });
  358. describe("hole lowering", () => {
  359. const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor as new (
  360. ...args: string[]
  361. ) => (...args: unknown[]) => Promise<unknown>;
  362. it("emits the evaluator at the site and the body as text in holeBodies", () => {
  363. const result = lowerWorkflowScript(FILLED);
  364. expect(result.ok).toBe(true);
  365. const lowered = result.lowered!;
  366. expect(lowered.siteIds).toEqual([
  367. "ask#1",
  368. "actor#1",
  369. GROUP,
  370. `${GROUP}/ask#1`,
  371. `${GROUP}/actor#1`,
  372. "ask#2",
  373. "actor#2",
  374. ]);
  375. expect(lowered.code).toContain(
  376. `__host.hole("${GROUP}", "决定分组", \`最慢的是 \${survey}\`, __src => eval(__src), async () => {`,
  377. );
  378. const body = lowered.holeBodies[GROUP];
  379. expect(body?.startsWith("(async () => {\n")).toBe(true);
  380. expect(body?.endsWith("\n})")).toBe(true);
  381. expect(body).toContain(
  382. `__host.ask("${GROUP}/ask#1", __host.createActor("${GROUP}/actor#1", "分组员")`,
  383. );
  384. expect(body).not.toContain("<Plan>");
  385. // 开放的留白:提示缺席退回 void 0,没有函数体也没有 holeBodies 条目。
  386. const open = lowerWorkflowScript(`const v = await hole<string>("决定");\nreturn v;`).lowered!;
  387. expect(open.code).toContain(`__host.hole("${DECIDE}", "决定", void 0, __src => eval(__src))`);
  388. expect(open.holeBodies).toEqual({});
  389. });
  390. it("evaluates a fill's text at the site: the body closes over the bindings there", async () => {
  391. // 模拟 cell:__host.hole 在站点处拿到求值器,用 holeBodies 的文本求出函数并调用;函数体里
  392. // 引用的 `survey` 是留白之前的 const——只有站点处的直接 eval 能看见它。
  393. const lowered = lowerWorkflowScript(FILLED).lowered!;
  394. const calls: string[] = [];
  395. const host = {
  396. ask: async (id: string, actor: string, text: string) => {
  397. calls.push(`${id}:${actor}:${text}`);
  398. return id === "ask#1" ? "S" : { groups: [["a"]] };
  399. },
  400. createActor: (id: string) => id,
  401. enterPhase: () => undefined,
  402. hole: async (
  403. id: string,
  404. _n: string,
  405. _p: unknown,
  406. evaluate: (src: string) => () => Promise<unknown>,
  407. ) => {
  408. return evaluate(lowered.holeBodies[id] as string)();
  409. },
  410. };
  411. // 把已补全的调用改成开放形式(去掉第五实参),让文本路径真的跑起来。
  412. const unfilledCode = lowered.code.replace(/, async \(\) => \{[\s\S]*?\n\}\);/, ");");
  413. const result = await new AsyncFunction("__host", unfilledCode)(host);
  414. expect(result).toEqual({ groups: [["a"]] });
  415. expect(calls).toEqual([
  416. "ask#1:actor#1:摸底",
  417. `${GROUP}/ask#1:${GROUP}/actor#1:分组 S`,
  418. "ask#2:actor#2:按 1 组执行",
  419. ]);
  420. });
  421. });
  422. describe("spliceHoleBody / checkSiteStability", () => {
  423. const BODY = `phase("分组");\nreturn await agent("分组员").ask<Plan>(\`分组 \${survey}\`);`;
  424. it("splices the body after the last argument, indented under the call", () => {
  425. const { table } = sitesOf(OPEN);
  426. const spliced = spliceHoleBody(OPEN, table, GROUP, BODY);
  427. expect(spliced).toBeDefined();
  428. expect(spliced?.text).toBe(FILLED);
  429. expect(spliced?.insertedAtLine).toBe(4);
  430. expect(spliced?.insertedLines).toBe(3);
  431. // 拼出来的脚本编译干净,且函数体的站点带前缀。
  432. const after = sitesOf(spliced!.text);
  433. expect(after.diagnostics).toEqual([]);
  434. expect(after.table.asks.map((s) => s.id)).toEqual(["ask#1", `${GROUP}/ask#1`, "ask#2"]);
  435. });
  436. it("indents by the call's own indentation plus two", () => {
  437. const script = `if (true) {\n const v = await hole<string>("决定");\n log(v);\n}\nreturn 1;`;
  438. const { table } = sitesOf(script);
  439. const spliced = spliceHoleBody(script, table, DECIDE, `return "x";`);
  440. expect(spliced?.text).toBe(
  441. `if (true) {\n const v = await hole<string>("决定", async () => {\n return "x";\n });\n log(v);\n}\nreturn 1;`,
  442. );
  443. expect(spliced?.insertedAtLine).toBe(3);
  444. expect(spliced?.insertedLines).toBe(2);
  445. });
  446. it("keeps a trailing comma and a multi-line call intact (prettier-style call site)", () => {
  447. // 2026-09-28 首次实测:主代理写了带尾随逗号的多行调用,旧的「右括号前插入」得到 `, , async`。
  448. const script = [
  449. `const v = await hole<string>(`,
  450. ` "决定",`,
  451. ` \`提示\`,`,
  452. `);`,
  453. `log(v);`,
  454. `return 1;`,
  455. ].join("\n");
  456. const { table, diagnostics } = sitesOf(script);
  457. expect(diagnostics).toEqual([]);
  458. const spliced = spliceHoleBody(script, table, DECIDE, `return "x";`);
  459. expect(spliced?.text).toBe(
  460. [
  461. `const v = await hole<string>(`,
  462. ` "决定",`,
  463. ` \`提示\`, async () => {`,
  464. ` return "x";`,
  465. `},`,
  466. `);`,
  467. `log(v);`,
  468. `return 1;`,
  469. ].join("\n"),
  470. );
  471. expect(spliced?.insertedAtLine).toBe(4);
  472. expect(spliced?.insertedLines).toBe(2);
  473. const after = sitesOf(spliced!.text);
  474. expect(after.diagnostics).toEqual([]);
  475. expect(
  476. checkSiteStability(
  477. table,
  478. after.table,
  479. DECIDE,
  480. spliced!.insertedAtLine,
  481. spliced!.insertedLines,
  482. ),
  483. ).toEqual({ ok: true });
  484. });
  485. it("refuses an unknown hole and an already filled one", () => {
  486. expect(spliceHoleBody(OPEN, sitesOf(OPEN).table, holeSiteId("nope"), BODY)).toBeUndefined();
  487. expect(spliceHoleBody(FILLED, sitesOf(FILLED).table, GROUP, BODY)).toBeUndefined();
  488. });
  489. it("accepts a fill that shifts every later site by the inserted lines and adds only prefixed ids", () => {
  490. const before = sitesOf(OPEN).table;
  491. const spliced = spliceHoleBody(OPEN, before, GROUP, BODY)!;
  492. const after = sitesOf(spliced.text).table;
  493. expect(
  494. checkSiteStability(before, after, GROUP, spliced.insertedAtLine, spliced.insertedLines),
  495. ).toEqual({ ok: true });
  496. });
  497. it("rejects a vanished id, a moved id and an unprefixed new id", () => {
  498. const before = sitesOf(OPEN).table;
  499. const vanished = sitesOf(
  500. OPEN.replace(
  501. `return agent("执行者").ask<string>(\`按 \${plan.groups.length} 组执行\`);`,
  502. `return 1;`,
  503. ),
  504. ).table;
  505. expect(checkSiteStability(before, vanished, GROUP, 4, 3)).toMatchObject({
  506. ok: false,
  507. detail: expect.stringContaining("ask#2 vanished"),
  508. });
  509. const moved = sitesOf(`\n${OPEN}`).table;
  510. expect(checkSiteStability(before, moved, GROUP, 4, 3)).toMatchObject({
  511. ok: false,
  512. detail: expect.stringContaining("ask#1 moved"),
  513. });
  514. const extra = sitesOf(`${OPEN}\nawait agent("x").ask<string>("y");`).table;
  515. expect(checkSiteStability(before, extra, GROUP, 99, 0)).toMatchObject({
  516. ok: false,
  517. detail: expect.stringContaining("ask#3 appeared"),
  518. });
  519. // 体外新出现的留白也算「补全之外」:它的 fill 链通不到被补全的留白。
  520. const strayHole = sitesOf(`${OPEN}\nawait hole<string>("别处");`).table;
  521. expect(checkSiteStability(before, strayHole, GROUP, 99, 0)).toMatchObject({
  522. ok: false,
  523. detail: expect.stringContaining("appeared outside"),
  524. });
  525. });
  526. it("lowers the spliced script with the fill's body text byte-identical to a direct compile", () => {
  527. const spliced = spliceHoleBody(OPEN, sitesOf(OPEN).table, GROUP, BODY)!;
  528. const workflow = createWorkflowProgram(spliced.text);
  529. const lowered = lowerWorkflow(workflow, collectSites(workflow));
  530. expect(lowered.holeBodies).toEqual(lowerWorkflowScript(FILLED).lowered?.holeBodies);
  531. });
  532. });
  533. // 递归留白(docs/analysis.md「Sites」):一个补全体里再留一个留白,补全它就是对**有效脚本**再拼接
  534. // 一次。内层留白的 id 仍是它自己的名字键(不带外层前缀,深度不长 id),归属记在 fill 上。五件事
  535. // 逐一证明:站点表、拼接、稳定性、lowering 的两层 holeBodies、阶段表里的位置。
  536. describe("recursive holes", () => {
  537. const OUTER_OPEN = [
  538. `interface Plan { groups: string[][] }`,
  539. `interface Order { first: string }`,
  540. `const survey = await agent("勘察员").ask<string>("摸底");`,
  541. `const plan = await hole<Plan>("决定分组", \`\${survey}\`);`,
  542. `return agent("执行者").ask<string>(\`\${plan.groups.length}\`);`,
  543. ].join("\n");
  544. const OUTER_BODY = [
  545. `const draft = await agent("分组员").ask<Plan>(\`分组 \${survey}\`);`,
  546. `const order = await hole<Order>("决定顺序", \`\${draft.groups.length} 组\`);`,
  547. `return { groups: [[order.first], ...draft.groups] };`,
  548. ].join("\n");
  549. const INNER_BODY = `return await agent("排序员").ask<Order>(\`排 \${draft.groups.length} 组\`);`;
  550. const outerFilled = () => {
  551. const spliced = spliceHoleBody(OUTER_OPEN, sitesOf(OUTER_OPEN).table, GROUP, OUTER_BODY)!;
  552. return { ...spliced, table: sitesOf(spliced.text).table };
  553. };
  554. const bothFilled = () => {
  555. const first = outerFilled();
  556. const spliced = spliceHoleBody(first.text, first.table, ORDER, INNER_BODY)!;
  557. return { ...spliced, before: first.table, table: sitesOf(spliced.text).table };
  558. };
  559. it("(1) lists the inner hole with its own flat id and its enclosing hole, open, and splices into the inner call", () => {
  560. const first = outerFilled();
  561. expect(sitesOf(first.text).diagnostics).toEqual([]);
  562. expect(first.table.holes.map((h) => [h.id, h.fill, h.body === undefined])).toEqual([
  563. [GROUP, undefined, false],
  564. [ORDER, GROUP, true],
  565. ]);
  566. const second = bothFilled();
  567. expect(sitesOf(second.text).diagnostics).toEqual([]);
  568. // 拼进了内层调用:内层调用现在带函数体,且体内的站点带内层留白自己的一层前缀。
  569. expect(second.text).toContain(
  570. `const order = await hole<Order>("决定顺序", \`\${draft.groups.length} 组\`, async () => {`,
  571. );
  572. expect(second.text).toContain(`\n return await agent("排序员")`);
  573. expect(second.table.holes.map((h) => [h.id, h.fill, h.body === undefined])).toEqual([
  574. [GROUP, undefined, false],
  575. [ORDER, GROUP, false],
  576. ]);
  577. expect(second.table.asks.map((s) => s.id)).toEqual([
  578. "ask#1",
  579. `${GROUP}/ask#1`,
  580. `${ORDER}/ask#1`,
  581. "ask#2",
  582. ]);
  583. expect(second.table.actors.map((s) => s.id)).toEqual([
  584. "actor#1",
  585. `${GROUP}/actor#1`,
  586. `${ORDER}/actor#1`,
  587. "actor#2",
  588. ]);
  589. // 内层调用的缩进(外层体 2 格)+ 2:内层函数体 4 格,右括号回到 2 格。
  590. expect(second.text).toContain(`\n });\n return { groups`);
  591. });
  592. it("(2) checkSiteStability accepts the inner fill and rejects a renumbering", () => {
  593. const second = bothFilled();
  594. expect(
  595. checkSiteStability(
  596. second.before,
  597. second.table,
  598. ORDER,
  599. second.insertedAtLine,
  600. second.insertedLines,
  601. ),
  602. ).toEqual({ ok: true });
  603. // 重新编号:在有效脚本前面多插一个 ask,外层与外层体的 id 全部错位。
  604. const renumbered = sitesOf(`await agent("x").ask<string>("y");\n${second.text}`).table;
  605. const verdict = checkSiteStability(
  606. second.before,
  607. renumbered,
  608. ORDER,
  609. second.insertedAtLine,
  610. second.insertedLines,
  611. );
  612. expect(verdict.ok).toBe(false);
  613. // 外层体的 id(`<GROUP>/…`)必须原样存在:把它们改掉也被拒。
  614. const dropped = sitesOf(
  615. second.text.replace(
  616. `const draft = await agent("分组员").ask<Plan>(\`分组 \${survey}\`);`,
  617. `const draft = { groups: [["a"]] } as Plan;`,
  618. ),
  619. ).table;
  620. expect(
  621. checkSiteStability(
  622. second.before,
  623. dropped,
  624. ORDER,
  625. second.insertedAtLine,
  626. second.insertedLines,
  627. ),
  628. ).toMatchObject({
  629. detail: expect.stringContaining(`${GROUP}/ask#1 vanished`),
  630. ok: false,
  631. });
  632. });
  633. it("(3) lowers the inner open hole inside the outer body's text, then both bodies once both are filled", () => {
  634. const first = lowerWorkflowScript(outerFilled().text).lowered!;
  635. expect(Object.keys(first.holeBodies)).toEqual([GROUP]);
  636. expect(first.holeBodies[GROUP]).toContain(
  637. `__host.hole("${ORDER}", "决定顺序", \`\${draft.groups.length} 组\`, __src => eval(__src))`,
  638. );
  639. expect(first.siteIds).toEqual([
  640. "ask#1",
  641. "actor#1",
  642. GROUP,
  643. `${GROUP}/ask#1`,
  644. `${GROUP}/actor#1`,
  645. ORDER,
  646. "ask#2",
  647. "actor#2",
  648. ]);
  649. const second = lowerWorkflowScript(bothFilled().text).lowered!;
  650. expect(Object.keys(second.holeBodies).sort()).toEqual([GROUP, ORDER].sort());
  651. const inner = second.holeBodies[ORDER]!;
  652. expect(inner.startsWith("(async () => {\n")).toBe(true);
  653. expect(inner).toContain(
  654. `__host.ask("${ORDER}/ask#1", __host.createActor("${ORDER}/actor#1", "排序员")`,
  655. );
  656. // 外层文本现在把内层函数体内联为第五实参,且与单独打印的内层文本同一份改写。
  657. const outer = second.holeBodies[GROUP]!;
  658. expect(outer).toContain(
  659. `__host.hole("${ORDER}", "决定顺序", \`\${draft.groups.length} 组\`, __src => eval(__src), async () => {`,
  660. );
  661. expect(outer).toContain(
  662. `__host.ask("${ORDER}/ask#1", __host.createActor("${ORDER}/actor#1", "排序员")`,
  663. );
  664. expect(second.siteIds).toContain(`${ORDER}/ask#1`);
  665. });
  666. it("(4) projects the three states: outer open, inner open, both filled", () => {
  667. const open = analyzeWorkflowScript(OUTER_OPEN);
  668. expect(open.flow?.holes).toEqual([
  669. { name: "决定分组", phase: "unphased", siteId: GROUP, type: "Plan" },
  670. ]);
  671. const innerOpen = analyzeWorkflowScript(outerFilled().text);
  672. expect(innerOpen.ok).toBe(true);
  673. expect(innerOpen.flow?.holes).toEqual([
  674. { name: "决定顺序", phase: GROUP, siteId: ORDER, type: "Order" },
  675. ]);
  676. // 顶层留白自己的阶段不带 fill;体内的留白阶段带外层的 id——嵌套关系只在这里。
  677. expect(innerOpen.flow?.phases?.map((p) => [p.id, p.fill])).toEqual([
  678. ["unphased", undefined],
  679. [GROUP, undefined],
  680. [ORDER, GROUP],
  681. ]);
  682. expect(innerOpen.causality?.steps.find((s) => s.id === ORDER)).toMatchObject({
  683. fill: GROUP,
  684. kind: "hole",
  685. lane: MAIN_LANE,
  686. phase: GROUP,
  687. });
  688. const filled = analyzeWorkflowScript(bothFilled().text);
  689. expect(filled.ok).toBe(true);
  690. expect(filled.flow?.holes).toBeUndefined();
  691. expect(filled.causality?.steps.find((s) => s.id === ORDER)).toBeUndefined();
  692. expect(filled.causality?.steps.find((s) => s.id === `${ORDER}/ask#1`)).toMatchObject({
  693. fill: ORDER,
  694. phase: ORDER,
  695. });
  696. expect(filled.causality?.steps.find((s) => s.id === `${GROUP}/ask#1`)).toMatchObject({
  697. fill: GROUP,
  698. phase: GROUP,
  699. });
  700. expect(filled.causality?.phases?.map((p) => [p.id, p.fill])).toEqual([
  701. ["unphased", undefined],
  702. [GROUP, undefined],
  703. [ORDER, GROUP],
  704. ]);
  705. expect(collectSitePhases(filled.core!).get(`${ORDER}/ask#1`)).toBe("决定顺序");
  706. });
  707. it("(5) collectPhaseNames places the inner hole by name with its index", () => {
  708. expect(collectPhaseNames(analyzeWorkflowScript(outerFilled().text).flow)).toEqual({
  709. holes: [1],
  710. phaseNames: ["决定分组", "决定顺序"],
  711. });
  712. expect(collectPhaseNames(analyzeWorkflowScript(bothFilled().text).flow)).toEqual({
  713. holes: [],
  714. phaseNames: ["决定分组", "决定顺序"],
  715. });
  716. });
  717. });
  718. // 修复原因:id 曾逐层拼接(`hole#1/hole#1/…`,每层 7 个字符),接龙八九步就顶到协议的 64 字符
  719. // id 上界。名字键之后深度不再进 id:这里把一条尾巴留白的接龙长到 20 步,每一步都走真实的
  720. // 拼接 + 稳定性复核 + 全量分析,最后看最长的 id 与第一步时一样短。
  721. describe("a tail chain twenty fills deep", () => {
  722. const STEPS = 20;
  723. const stepName = (k: number) => `第${k}步`;
  724. const SEED = [
  725. `phase("盘点");`,
  726. `const s0 = await agent("勘察员").ask<string>("看一眼");`,
  727. `return await hole<string>("${stepName(1)}", \`起点 \${s0}\`);`,
  728. ].join("\n");
  729. const body = (k: number) =>
  730. k === STEPS
  731. ? `return s${k - 1};`
  732. : [
  733. `phase("做${stepName(k)}");`,
  734. `const s${k} = await agent("写手${k}").ask<string>(\`接着 \${s${k - 1}}\`);`,
  735. `return await hole<string>("${stepName(k + 1)}", \`进度 ${k}\`);`,
  736. ].join("\n");
  737. const grow = () => {
  738. let text = SEED;
  739. const lengths: number[] = [];
  740. for (let k = 1; k <= STEPS; k += 1) {
  741. const before = sitesOf(text);
  742. const id = holeSiteId(stepName(k));
  743. const spliced = spliceHoleBody(text, before.table, id, body(k));
  744. expect(spliced, `step ${k}`).toBeDefined();
  745. const after = sitesOf(spliced!.text);
  746. expect(after.diagnostics, `step ${k}`).toEqual([]);
  747. expect(
  748. checkSiteStability(
  749. before.table,
  750. after.table,
  751. id,
  752. spliced!.insertedAtLine,
  753. spliced!.insertedLines,
  754. ),
  755. `step ${k}`,
  756. ).toEqual({ ok: true });
  757. const all = [...after.table.asks, ...after.table.actors, ...after.table.holes].map(
  758. (s) => s.id,
  759. );
  760. lengths.push(Math.max(...all.map((sid) => sid.length)));
  761. text = spliced!.text;
  762. }
  763. return { lengths, text };
  764. };
  765. it("keeps every fill stable and every id as short at step 20 as at step 1", () => {
  766. const { lengths, text } = grow();
  767. // 最长的 id 是 `hole#xxxxxxxx/actor#1` 这一类:21 个字符,与深度无关。
  768. expect(new Set(lengths)).toEqual(new Set([lengths[0]]));
  769. expect(lengths[0]).toBeLessThanOrEqual(24);
  770. const analyzed = analyzeWorkflowScript(text);
  771. expect(analyzed.ok).toBe(true);
  772. // 每一步的名字都还在阶段表里:接龙的步名不会从侧栏消失。
  773. const names = collectPhaseNames(analyzed.flow).phaseNames;
  774. for (let k = 1; k <= STEPS; k += 1) expect(names).toContain(stepName(k));
  775. expect(collectPhaseNames(analyzed.flow).holes).toEqual([]);
  776. });
  777. it("records each step's enclosing step in fill, so nesting survives without being spelled in the id", () => {
  778. const { text } = grow();
  779. const { table } = sitesOf(text);
  780. for (let k = 2; k <= STEPS; k += 1) {
  781. const hole = table.holes.find((h) => h.id === holeSiteId(stepName(k)));
  782. expect(hole?.fill, `step ${k}`).toBe(holeSiteId(stepName(k - 1)));
  783. }
  784. expect(table.holes.find((h) => h.id === holeSiteId(stepName(1)))?.fill).toBeUndefined();
  785. // 最里层函数体的站点只带最里层留白自己的一层前缀。
  786. const lowered = lowerWorkflowScript(text).lowered!;
  787. expect(lowered.siteIds).toContain(`${holeSiteId(stepName(19))}/ask#1`);
  788. expect(Object.keys(lowered.holeBodies)).toHaveLength(STEPS);
  789. });
  790. });