create-workflow-tool.test.ts 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  1. import { mkdtempSync, readFileSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import type {
  6. CreateWorkflowCausalityGraph,
  7. CreateWorkflowEdge,
  8. CreateWorkflowOutput,
  9. } from "@zcode/contracts";
  10. import type { ControlFlowGraph, HandoffGraph } from "@zcode/dynamic-workflow";
  11. import { createWorkflowToolEntry } from "../src/tool/handlers/create-workflow.js";
  12. import { boundCausalityGraph } from "../src/tool/handlers/create-workflow-graph-bounds.js";
  13. import {
  14. normalizeWorkflowMaxConcurrency,
  15. resolveCreateWorkflowInput,
  16. } from "../src/tool/handlers/create-workflow-source.js";
  17. import { saveSavedWorkflow } from "../src/tool/handlers/saved-workflows/index.js";
  18. import { registerBuiltInTools } from "../src/tool/handlers/index.js";
  19. import { analyzeScript } from "../src/tool/handlers/workflow-script-analysis.js";
  20. import type { ModelCatalogEntry, ModelCatalogPort } from "@zcode/contracts";
  21. import type { ToolExecutionContext, ToolHandlerFailure } from "../src/tool/types.js";
  22. import { createToolRegistry } from "../src/tool/registry.js";
  23. // Handler ignores context (pure typecheck, no I/O), so a bare stub is enough.
  24. const stubContext = {} as ToolExecutionContext;
  25. async function run(input: unknown): Promise<CreateWorkflowOutput> {
  26. return (await createWorkflowToolEntry.handler(input, stubContext)) as CreateWorkflowOutput;
  27. }
  28. /**
  29. * 分析器语料里的一个脚本(docs/dynamic-workflow/presentation.md 与
  30. * docs/dynamic-workflow/presentation.md 的验收样本)。
  31. */
  32. function fixture(name: string): string {
  33. return readFileSync(
  34. new URL(`../../dynamic-workflow/tests/graphs/${name}`, import.meta.url),
  35. "utf8",
  36. );
  37. }
  38. /** 分析器全图 → 裁剪层,与 handler 的两个调用点同一签名。 */
  39. function bound(script: string): CreateWorkflowCausalityGraph {
  40. const { causality, flow, handoff } = analyzeScript(script);
  41. expect(causality).toBeDefined();
  42. return boundCausalityGraph(causality!, flow, handoff);
  43. }
  44. type Edge = CreateWorkflowEdge;
  45. /** 前向(非 back)边的传递闭包,`from -> Set<to>`。 */
  46. function closure(edges: readonly Edge[]): Map<string, Set<string>> {
  47. const out = new Map<string, Set<string>>();
  48. const next = new Map<string, string[]>();
  49. const nodes = new Set<string>();
  50. for (const edge of edges) {
  51. if (edge.back === true) continue;
  52. nodes.add(edge.from);
  53. nodes.add(edge.to);
  54. next.set(edge.from, [...(next.get(edge.from) ?? []), edge.to]);
  55. }
  56. for (const start of nodes) {
  57. const reached = new Set<string>();
  58. const stack = [...(next.get(start) ?? [])];
  59. while (stack.length > 0) {
  60. const node = stack.pop() as string;
  61. if (reached.has(node)) continue;
  62. reached.add(node);
  63. stack.push(...(next.get(node) ?? []));
  64. }
  65. out.set(start, reached);
  66. }
  67. return out;
  68. }
  69. function closureEquals(a: Map<string, Set<string>>, b: Map<string, Set<string>>): boolean {
  70. const keys = new Set([...a.keys(), ...b.keys()]);
  71. for (const key of keys) {
  72. const x = a.get(key) ?? new Set();
  73. const y = b.get(key) ?? new Set();
  74. if (x.size !== y.size || [...x].some((id) => !y.has(id))) return false;
  75. }
  76. return true;
  77. }
  78. /** 前向边集不可约:去掉任何一条都改变闭包。 */
  79. function isIrredundant(edges: readonly Edge[]): boolean {
  80. const forward = edges.filter((edge) => edge.back !== true);
  81. const full = closure(forward);
  82. return forward.every(
  83. (edge) => !closureEquals(full, closure(forward.filter((other) => other !== edge))),
  84. );
  85. }
  86. /**
  87. * 载荷的引用完整性(spec「契约」):三层之间的桥全部落在列出的集合里。
  88. * - step 的车道 ∈ lanes;step 的 phase ∈ phases(词汇表在场时每个 step 都带)。
  89. * - participant 的 phase ∈ phases,或词汇表缺席时全部为 `unphased`;lane ∈ lanes;
  90. * steps ⊆ steps;每个 step 至多属于一张卡。
  91. * - handoff 两端 ∈ participants,无自环;phaseEdges 两端 ∈ phases;exits / sink 同理。
  92. * - phase 的 alongside ∈ phases,且不含自己(一个阶段不与自己并行)。
  93. * - phaseStreams 两端 ∈ phases、无自环、两端互为 alongside(docs/dynamic-workflow/presentation.md「Streams」)。
  94. */
  95. function expectReferentialIntegrity(graph: CreateWorkflowCausalityGraph): void {
  96. const laneIds = new Set(graph.lanes.map((lane) => lane.id));
  97. const stepIds = new Set(graph.steps.map((step) => step.id));
  98. const phaseIds = new Set((graph.phases ?? []).map((phase) => phase.id));
  99. const participantIds = new Set(graph.participants.map((participant) => participant.id));
  100. expect(participantIds.size).toBe(graph.participants.length);
  101. for (const step of graph.steps) {
  102. expect(laneIds.has(step.lane)).toBe(true);
  103. for (const lane of step.lanes ?? []) expect(laneIds.has(lane)).toBe(true);
  104. if (graph.phases === undefined) expect(Object.hasOwn(step, "phase")).toBe(false);
  105. else expect(phaseIds.has(step.phase!)).toBe(true);
  106. }
  107. const owner = new Map<string, string>();
  108. for (const participant of graph.participants) {
  109. if (graph.phases === undefined) expect(participant.phase).toBe("unphased");
  110. else expect(phaseIds.has(participant.phase)).toBe(true);
  111. expect(laneIds.has(participant.lane)).toBe(true);
  112. expect(participant.steps.length).toBeGreaterThan(0);
  113. for (const id of participant.steps) {
  114. expect(stepIds.has(id)).toBe(true);
  115. // 家族成员卡共享同一站点 step:成员之间的共享是合法的,跨车道 / 跨阶段的不是。
  116. const seen = owner.get(id);
  117. if (seen !== undefined) {
  118. const other = graph.participants.find((candidate) => candidate.id === seen)!;
  119. expect([other.phase, other.lane]).toEqual([participant.phase, participant.lane]);
  120. expect(participant.member).toBeDefined();
  121. } else owner.set(id, participant.id);
  122. }
  123. }
  124. for (const edge of graph.handoffs) {
  125. expect(participantIds.has(edge.from)).toBe(true);
  126. expect(participantIds.has(edge.to)).toBe(true);
  127. expect(edge.from).not.toBe(edge.to);
  128. }
  129. for (const edge of graph.phaseEdges ?? []) {
  130. expect(phaseIds.has(edge.from)).toBe(true);
  131. expect(phaseIds.has(edge.to)).toBe(true);
  132. expect(edge.from).not.toBe(edge.to);
  133. }
  134. for (const phase of graph.phases ?? []) {
  135. for (const id of phase.alongside ?? []) {
  136. expect(phaseIds.has(id)).toBe(true);
  137. expect(id).not.toBe(phase.id);
  138. }
  139. }
  140. const alongsideOf = new Map(
  141. (graph.phases ?? []).map((phase) => [phase.id, phase.alongside ?? []]),
  142. );
  143. for (const stream of graph.phaseStreams ?? []) {
  144. expect(phaseIds.has(stream.from)).toBe(true);
  145. expect(phaseIds.has(stream.to)).toBe(true);
  146. expect(stream.from).not.toBe(stream.to);
  147. expect(
  148. alongsideOf.get(stream.from)!.includes(stream.to) ||
  149. alongsideOf.get(stream.to)!.includes(stream.from),
  150. ).toBe(true);
  151. }
  152. if (graph.phases === undefined) expect(Object.hasOwn(graph, "phaseStreams")).toBe(false);
  153. for (const id of graph.exits ?? []) expect(phaseIds.has(id)).toBe(true);
  154. for (const id of graph.sink ?? []) expect(stepIds.has(id)).toBe(true);
  155. // 四个阶段字段同进同退。
  156. expect(Object.hasOwn(graph, "phaseEdges")).toBe(Object.hasOwn(graph, "phases"));
  157. expect(Object.hasOwn(graph, "exits")).toBe(Object.hasOwn(graph, "phases"));
  158. // step 级边与车道多重性已从载荷退场(handoff-stack)。
  159. expect(Object.hasOwn(graph, "edges")).toBe(false);
  160. for (const lane of graph.lanes) expect(Object.hasOwn(lane, "nesting")).toBe(false);
  161. }
  162. describe("CreateWorkflow tool", () => {
  163. it("is registered by default via registerBuiltInTools", () => {
  164. const registry = createToolRegistry();
  165. registerBuiltInTools(registry);
  166. expect(registry.has("CreateWorkflow")).toBe(true);
  167. });
  168. it("emits the bounded display graph for a clean script", async () => {
  169. const output = await run({
  170. script:
  171. 'interface R { done: boolean }\nconst r = await agent("a").ask<R>("do");\nreturn r.done;',
  172. });
  173. expect(output.ok).toBe(true);
  174. expect(output.diagnostics).toEqual([]);
  175. expect(output.response).toContain("NOT executed");
  176. expect(output.causalityGraph).toBeDefined();
  177. const graph = output.causalityGraph!;
  178. // One step, standing in the actor's lane, at its author-script (prelude-stripped,
  179. // 1-based) location; the returned artifact is fed by that step.
  180. expect(graph.steps).toHaveLength(1);
  181. expect(graph.steps[0]).toMatchObject({ kind: "ask", label: "a", lane: "actor#1", line: 2 });
  182. expect(graph.lanes.map((lane) => lane.id)).toEqual(["actor#1"]);
  183. expect(graph.lanes[0]?.name).toBe("a");
  184. expect(graph.sink).toEqual(["ask#1"]);
  185. expect(graph.truncated).toBeUndefined();
  186. // 第二层:一张子代理卡装着这一个 step,无交接。
  187. expect(graph.participants).toEqual([
  188. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  189. ]);
  190. expect(graph.handoffs).toEqual([]);
  191. // 分析器内部的词汇(region / certainty / 边种类)不进载荷(single-arrow-contract);
  192. // step 级边与 `nesting` 不再转发(handoff-stack)。
  193. expect(Object.hasOwn(graph, "regions")).toBe(false);
  194. expect(Object.hasOwn(graph, "edges")).toBe(false);
  195. for (const step of graph.steps) {
  196. expect(Object.hasOwn(step, "region")).toBe(false);
  197. expect(Object.hasOwn(step, "certainty")).toBe(false);
  198. }
  199. expect(Object.hasOwn(graph, "phases")).toBe(false);
  200. expectReferentialIntegrity(graph);
  201. });
  202. it("keeps every reference resolvable inside the bounded payload", async () => {
  203. const output = await run({
  204. script: [
  205. 'const a = await agent("a").ask<string>("x");',
  206. 'phase("work");',
  207. "for (let i = 0; i < 2; i++) {",
  208. ' const b = await agent("b").ask<string>(`y ${a}`);',
  209. " if (b.length > 0) {",
  210. ' phase("save");',
  211. ' await agent("c").ask<string>(`z ${b}`);',
  212. " }",
  213. "}",
  214. "return a;",
  215. ].join("\n"),
  216. });
  217. expect(output.ok).toBe(true);
  218. const graph = output.causalityGraph!;
  219. expect(graph.phases).toHaveLength(3);
  220. expect(graph.participants.length).toBeGreaterThan(0);
  221. expectReferentialIntegrity(graph);
  222. });
  223. it("bounds the display graph at the output contract and flags truncation", async () => {
  224. // 70 asks exceed the 64-step bound; the head of the script survives, cards and
  225. // hand-offs pointing at dropped steps go with them, truncated is flagged.
  226. const asks = Array.from(
  227. { length: 70 },
  228. (_, index) => `const r${index} = await agent("a${index}").ask<string>("m");`,
  229. );
  230. const output = await run({
  231. script: [...asks, `return r0;`].join("\n"),
  232. });
  233. expect(output.ok).toBe(true);
  234. const graph = output.causalityGraph!;
  235. expect(graph.truncated).toBe(true);
  236. // Lanes cap at 32 while steps cap at 64, so steps whose lane was dropped must go
  237. // too — otherwise the renderer gets a card with no row to sit in. Each surviving
  238. // actor is one card in the single implicit phase.
  239. expect(graph.lanes).toHaveLength(32);
  240. expect(graph.steps).toHaveLength(32);
  241. expect(graph.participants).toHaveLength(32);
  242. expect(graph.handoffs).toHaveLength(31);
  243. expectReferentialIntegrity(graph);
  244. });
  245. it("carries one hand-off shape: from, to, a back bit for loop back-edges, and types for the inspector", async () => {
  246. // 类型标签、种类、确定性都不进展示通道:分析器仍算它们(文本图/mermaid/精炼 fork 用),
  247. // 边只表示 runs after;`back` 是唯一的边级标记,只标循环回边;`types` 是检视器素材,
  248. // 不上箭头。
  249. const output = await run({
  250. script: [
  251. "interface Flaky { findings: string[] }",
  252. 'const f = await agent("a").ask<Flaky>("f");',
  253. "for (let i = 0; i < 2; i++) {",
  254. ' const u = await agent("b").ask<string>(`use ${f.findings[0]}`);',
  255. ' await agent("c").ask<string>(`check ${u}`);',
  256. "}",
  257. "return f;",
  258. ].join("\n"),
  259. });
  260. expect(output.ok).toBe(true);
  261. const graph = output.causalityGraph!;
  262. expect(graph.handoffs).toEqual([
  263. { from: "unphased:actor#1", to: "unphased:actor#2", types: ["Flaky"] },
  264. { from: "unphased:actor#2", to: "unphased:actor#3", types: ["string"] },
  265. { from: "unphased:actor#3", to: "unphased:actor#2", back: true },
  266. ]);
  267. });
  268. it("carries an interpolated actor name's static shape through the bounded payload", async () => {
  269. // 契约边界是可选字段消失的地方:namePattern / labelPattern 漏掉限长映射不会被
  270. // strict schema 抓住,只会让车道头静静地退回「未命名智能体」。
  271. const output = await run({
  272. script: [
  273. "const topics = [1, 2, 3];",
  274. "const drafts = await Promise.all(",
  275. " topics.map((i) => agent(`研究员${i}`).ask<string>(`draft ${i}`)),",
  276. ");",
  277. 'const editor = agent("主编");',
  278. "const final = await editor.ask<string>(`merge ${drafts.join()}`);",
  279. "return final;",
  280. ].join("\n"),
  281. });
  282. expect(output.ok).toBe(true);
  283. const graph = output.causalityGraph!;
  284. const byId = new Map(graph.lanes.map((lane) => [lane.id, lane]));
  285. expect(byId.get("actor#1")?.namePattern).toEqual({ head: "研究员" });
  286. // 形状**不写进 name**:`name` 的契约是作者原样写下的那个词。
  287. expect(Object.hasOwn(byId.get("actor#1")!, "name")).toBe(false);
  288. // 字面量名的车道逐字节不变——字段缺席,不是 undefined 值。
  289. expect(byId.get("actor#2")?.name).toBe("主编");
  290. expect(Object.hasOwn(byId.get("actor#2")!, "namePattern")).toBe(false);
  291. // 多重性不再挂在车道上(曾是 families → nesting):家族的成员数由参与者卡表达。
  292. expect(Object.hasOwn(byId.get("actor#1")!, "nesting")).toBe(false);
  293. expect(Object.hasOwn(byId.get("actor#1")!, "families")).toBe(false);
  294. expect(graph.participants.filter((p) => p.lane === "actor#1").map((p) => p.member)).toEqual([
  295. { index: 0, of: 3 },
  296. { index: 1, of: 3 },
  297. { index: 2, of: 3 },
  298. ]);
  299. // 内联 receiver 的卡片同样拿到形状;标识符 receiver 的卡片没有形状可言。
  300. const steps = new Map(graph.steps.map((step) => [step.id, step]));
  301. expect(steps.get("ask#1")).toMatchObject({ label: "ask", labelPattern: { head: "研究员" } });
  302. expect(Object.hasOwn(steps.get("ask#2")!, "labelPattern")).toBe(false);
  303. });
  304. it("carries the may-set copies' source through the bounded payload", async () => {
  305. // may-set 车道展开的拷贝要能一路活到工具输出:`source` 是可选字段,限长映射里漏掉它
  306. // 不会被 strict schema 抓住,只会让直播叠加静静地关联不上任何实例。
  307. const output = await run({
  308. script: [
  309. 'const fast = agent("fast");',
  310. 'const careful = agent("careful");',
  311. 'const brief = await agent("triage").ask<string>("classify this request");',
  312. "const answer = await (brief.length > 8 ? careful : fast).ask<string>(`handle ${brief}`);",
  313. "return answer;",
  314. ].join("\n"),
  315. });
  316. expect(output.ok).toBe(true);
  317. const graph = output.causalityGraph!;
  318. expect(graph.steps.map((step) => [step.id, step.lane, step.source])).toEqual([
  319. ["ask#1", "actor#3", undefined],
  320. ["ask#2~actor#1", "actor#1", "ask#2"],
  321. ["ask#2~actor#2", "actor#2", "ask#2"],
  322. ]);
  323. // 未展开的 step 逐字节不变:字段缺席,不是 undefined 值。
  324. expect(Object.hasOwn(graph.steps[0]!, "source")).toBe(false);
  325. // 拷贝保留全部候选车道(悬停线索),id 在 64 字符上限内。
  326. expect(graph.steps[1]).toMatchObject({ lanes: ["actor#1", "actor#2"] });
  327. for (const step of graph.steps) expect(step.id.length).toBeLessThanOrEqual(64);
  328. // source 指向的是被拷贝替换掉的站点,图里没有这个节点——sink 与卡只引用拷贝。
  329. const stepIds = new Set(graph.steps.map((step) => step.id));
  330. expect(stepIds.has("ask#2")).toBe(false);
  331. expect(graph.sink).toEqual(["ask#2~actor#1", "ask#2~actor#2"]);
  332. // 两份拷贝分属两张卡(各在自己的车道上),开局者 triage 排第一。
  333. expect(graph.participants.map((p) => [p.id, p.steps])).toEqual([
  334. ["unphased:actor#3", ["ask#1"]],
  335. ["unphased:actor#1", ["ask#2~actor#1"]],
  336. ["unphased:actor#2", ["ask#2~actor#2"]],
  337. ]);
  338. expect(graph.handoffs).toEqual([
  339. { from: "unphased:actor#3", to: "unphased:actor#1", types: ["string"] },
  340. { from: "unphased:actor#3", to: "unphased:actor#2", types: ["string"] },
  341. ]);
  342. });
  343. // —— 第二层:参与者卡与交接(docs/dynamic-workflow/presentation.md「The display contract」)————
  344. it("expands a literal fan-out into one member card each, all handing to the reviewer", async () => {
  345. const output = await run({ script: fixture("handoff-literal-members.ts") });
  346. expect(output.ok).toBe(true);
  347. const graph = output.causalityGraph!;
  348. expect(graph.participants).toEqual([
  349. {
  350. id: "phase#1:actor#1[0]",
  351. phase: "phase#1",
  352. lane: "actor#1",
  353. steps: ["ask#1"],
  354. member: { index: 0, of: 3 },
  355. },
  356. {
  357. id: "phase#1:actor#1[1]",
  358. phase: "phase#1",
  359. lane: "actor#1",
  360. steps: ["ask#1"],
  361. member: { index: 1, of: 3 },
  362. },
  363. {
  364. id: "phase#1:actor#1[2]",
  365. phase: "phase#1",
  366. lane: "actor#1",
  367. steps: ["ask#1"],
  368. member: { index: 2, of: 3 },
  369. },
  370. { id: "phase#1:actor#2", phase: "phase#1", lane: "actor#2", steps: ["ask#2"] },
  371. ]);
  372. expect(graph.handoffs).toEqual([
  373. { from: "phase#1:actor#1[0]", to: "phase#1:actor#2", types: ["Draft"] },
  374. { from: "phase#1:actor#1[1]", to: "phase#1:actor#2", types: ["Draft"] },
  375. { from: "phase#1:actor#1[2]", to: "phase#1:actor#2", types: ["Draft"] },
  376. ]);
  377. // 单卡的 `member` / `many` 缺席,不是 undefined 值。
  378. expect(Object.hasOwn(graph.participants[3]!, "member")).toBe(false);
  379. expect(Object.hasOwn(graph.participants[3]!, "many")).toBe(false);
  380. expectReferentialIntegrity(graph);
  381. });
  382. it("collapses a family of unknown cardinality into one `many` card", async () => {
  383. // 被 push 过的数组不是字面量长度;迭代 ask 结果同样不可知——都是一张 `many` 卡。
  384. const output = await run({ script: fixture("handoff-pushed-array-many.ts") });
  385. expect(output.ok).toBe(true);
  386. const graph = output.causalityGraph!;
  387. expect(graph.participants).toEqual([
  388. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"], many: true },
  389. { id: "unphased:actor#2", phase: "unphased", lane: "actor#2", steps: ["ask#2"] },
  390. { id: "unphased:actor#3", phase: "unphased", lane: "actor#3", steps: ["ask#3"], many: true },
  391. ]);
  392. expect(graph.handoffs).toEqual([
  393. { from: "unphased:actor#1", to: "unphased:actor#2", types: ["Draft"] },
  394. { from: "unphased:actor#2", to: "unphased:actor#3", types: ["string[]"] },
  395. ]);
  396. for (const participant of graph.participants)
  397. expect(Object.hasOwn(participant, "member")).toBe(false);
  398. expectReferentialIntegrity(graph);
  399. });
  400. it("puts every card in `unphased` when the script has no phase vocabulary", async () => {
  401. // 无阶段词汇:`phases` 缺席,卡的 phase 恒为 `unphased`(UI 合成一个同 id 的模块)。
  402. // 没有数据的接力(editor 的 ask 不提 draft)仍是交接;同车道自环消失。
  403. const output = await run({ script: fixture("handoff-unphased-baton.ts") });
  404. expect(output.ok).toBe(true);
  405. const graph = output.causalityGraph!;
  406. expect(Object.hasOwn(graph, "phases")).toBe(false);
  407. expect(graph.participants).toEqual([
  408. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1", "ask#2"] },
  409. { id: "unphased:actor#2", phase: "unphased", lane: "actor#2", steps: ["ask#3"] },
  410. ]);
  411. expect(graph.handoffs).toEqual([{ from: "unphased:actor#1", to: "unphased:actor#2" }]);
  412. expect(Object.hasOwn(graph.handoffs[0]!, "types")).toBe(false);
  413. expectReferentialIntegrity(graph);
  414. });
  415. it("matches the earth-v5 hand-off acceptance sample after bounding", () => {
  416. // spec「测试与验收」的 earth-v5 验收:五个阶段的参与者与交接,逐字节;P2 零交接。
  417. const graph = bound(fixture("handoff-earth-v5.ts"));
  418. expect(graph.truncated).toBeUndefined();
  419. expect(graph.phases?.map((phase) => phase.id)).toEqual([
  420. "phase#1",
  421. "phase#2",
  422. "phase#3",
  423. "phase#4",
  424. "phase#5",
  425. ]);
  426. const byPhase = (phase: string): string[] =>
  427. graph.participants.filter((p) => p.phase === phase).map((p) => p.id);
  428. expect(byPhase("phase#1")).toEqual(["phase#1:actor#1"]);
  429. expect(byPhase("phase#2")).toEqual([
  430. "phase#2:actor#2",
  431. "phase#2:actor#3[0]",
  432. "phase#2:actor#3[1]",
  433. "phase#2:actor#3[2]",
  434. "phase#2:actor#3[3]",
  435. "phase#2:actor#3[4]",
  436. ]);
  437. expect(byPhase("phase#3")).toEqual(["phase#3:workspace", "phase#3:actor#4"]);
  438. expect(byPhase("phase#4")).toEqual([
  439. "phase#4:workspace",
  440. "phase#4:actor#4",
  441. "phase#4:actor#5",
  442. "phase#4:actor#6",
  443. "phase#4:actor#7",
  444. "phase#4:actor#8",
  445. ]);
  446. expect(byPhase("phase#5")).toEqual(["phase#5:workspace"]);
  447. // 参与者数组顺序 = 阶段序内的交接序(折叠面自上而下)。
  448. expect(graph.participants.map((p) => p.id)).toEqual([
  449. ...byPhase("phase#1"),
  450. ...byPhase("phase#2"),
  451. ...byPhase("phase#3"),
  452. ...byPhase("phase#4"),
  453. ...byPhase("phase#5"),
  454. ]);
  455. const lanes = new Map(graph.lanes.map((lane) => [lane.id, lane.name]));
  456. expect(
  457. ["actor#1", "actor#2", "actor#4", "actor#5", "actor#6", "actor#7", "actor#8"].map((id) =>
  458. lanes.get(id),
  459. ),
  460. ).toEqual(["architect", "harness", "fixer", "jury-a", "jury-b", "jury-c", "polisher"]);
  461. const members = graph.participants.filter((p) => p.lane === "actor#3");
  462. expect(members.map((p) => p.member)).toEqual(
  463. Array.from({ length: 5 }, (_, index) => ({ index, of: 5 })),
  464. );
  465. expect(graph.handoffs).toEqual([
  466. { from: "phase#3:workspace", to: "phase#3:actor#4", types: ["WorldRunResult"] },
  467. { from: "phase#3:actor#4", to: "phase#3:workspace", back: true },
  468. { from: "phase#4:workspace", to: "phase#4:actor#4", types: ["WorldRunResult"] },
  469. { from: "phase#4:workspace", to: "phase#4:actor#5" },
  470. { from: "phase#4:workspace", to: "phase#4:actor#6" },
  471. { from: "phase#4:workspace", to: "phase#4:actor#7" },
  472. { from: "phase#4:actor#4", to: "phase#4:workspace" },
  473. { from: "phase#4:actor#4", to: "phase#4:actor#7", back: true },
  474. { from: "phase#4:actor#5", to: "phase#4:actor#8", types: ["JuryVerdict"] },
  475. { from: "phase#4:actor#6", to: "phase#4:actor#8", types: ["JuryVerdict"] },
  476. { from: "phase#4:actor#7", to: "phase#4:actor#8", types: ["JuryVerdict"] },
  477. { from: "phase#4:actor#8", to: "phase#4:workspace" },
  478. ]);
  479. expect(graph.handoffs.filter((edge) => edge.from.startsWith("phase#2:"))).toEqual([]);
  480. expectReferentialIntegrity(graph);
  481. });
  482. // —— 阶段词汇表的裁剪(docs/dynamic-workflow/presentation.md「The display contract」)————
  483. // 阶段层来自控制流图的阶段商(阶段之间能去哪),step 层是站点表。
  484. it("carries the phase vocabulary through the bounded payload", async () => {
  485. const output = await run({
  486. script: [
  487. 'phase("preflight");',
  488. 'const found = await files.glob("*.ts");',
  489. 'const plan = await agent("planner").ask<string>(`plan ${found.length}`);',
  490. 'phase("work");',
  491. "for (let i = 0; i < 3; i++) {",
  492. ' const r = await agent("worker").ask<string>(`do ${plan}`);',
  493. " if (r.length > 0) {",
  494. ' phase("checkpoint");',
  495. ' await agent("saver").ask<string>(`save ${r}`);',
  496. " }",
  497. "}",
  498. "return plan;",
  499. ].join("\n"),
  500. });
  501. expect(output.ok).toBe(true);
  502. const graph = output.causalityGraph!;
  503. expect(graph.truncated).toBeUndefined();
  504. // 阶段按名字首次出现的标记顺序编号,带作者原词与该标记的位置。
  505. expect(graph.phases).toEqual([
  506. { id: "phase#1", name: "preflight", line: 1, column: 1 },
  507. { id: "phase#2", name: "work", line: 4, column: 1 },
  508. { id: "phase#3", name: "checkpoint", line: 8, column: 5 },
  509. ]);
  510. // 划分是全的:词汇表在场时每个 step 恰有一个阶段。
  511. expect(graph.steps.map((step) => step.phase)).toEqual([
  512. "phase#1",
  513. "phase#1",
  514. "phase#2",
  515. "phase#3",
  516. ]);
  517. // 阶段边是控制流图的阶段商,与交接边同一形状:循环回边带 `back`,其余什么都不带。
  518. // 同阶段自环(work 里的循环)不发。
  519. expect(graph.phaseEdges).toEqual([
  520. { from: "phase#1", to: "phase#2" },
  521. { from: "phase#2", to: "phase#3" },
  522. { from: "phase#3", to: "phase#2", back: true },
  523. ]);
  524. // 循环退出后脚本正常完成:两个可能是最后一轮的阶段都通向返回物。
  525. expect(graph.exits).toEqual(["phase#2", "phase#3"]);
  526. // 第二层按阶段分卡:跨阶段的因果边(plan → worker)不是交接,交接只在阶段内。
  527. expect(graph.participants.map((p) => p.id)).toEqual([
  528. "phase#1:workspace",
  529. "phase#1:actor#1",
  530. "phase#2:actor#2",
  531. "phase#3:actor#3",
  532. ]);
  533. expect(graph.handoffs).toEqual([
  534. { from: "phase#1:workspace", to: "phase#1:actor#1", types: ["string[]"] },
  535. ]);
  536. expectReferentialIntegrity(graph);
  537. });
  538. it("carries the unphased fallback for steps before the first marker", async () => {
  539. const output = await run({
  540. script: [
  541. 'const a = await agent("x").ask<string>("q");',
  542. 'phase("later");',
  543. 'const b = await agent("y").ask<string>(`use ${a}`);',
  544. "return b;",
  545. ].join("\n"),
  546. });
  547. expect(output.ok).toBe(true);
  548. const graph = output.causalityGraph!;
  549. // 兜底阶段排在最前(它装的是首个标记之前的 step)且**无 name**:显示名由 UI 本地化,
  550. // 与 workspace / unknown 车道同一模式。
  551. expect(graph.phases?.[0]).toEqual({ id: "unphased" });
  552. expect(graph.phases?.[1]).toMatchObject({ id: "phase#1", name: "later" });
  553. expect(graph.steps.map((step) => step.phase)).toEqual(["unphased", "phase#1"]);
  554. // 词汇表在场时兜底阶段是表里的一员,卡照常归入它。
  555. expect(graph.participants.map((p) => [p.id, p.phase])).toEqual([
  556. ["unphased:actor#1", "unphased"],
  557. ["phase#1:actor#2", "phase#1"],
  558. ]);
  559. expectReferentialIntegrity(graph);
  560. });
  561. it("lists a marker-only phase: control passes through it even with no step", async () => {
  562. // 因果商图只认成员,看不见 prepare;控制流商看得见——它是两个 step 之间的一个位置。
  563. // 第二层没有它的卡:卡是「阶段里有 step 的车道」。
  564. const output = await run({ script: fixture("phase-empty-phase.ts") });
  565. expect(output.ok).toBe(true);
  566. const graph = output.causalityGraph!;
  567. expect(graph.phases?.map((phase) => phase.name)).toEqual(["scan", "prepare", "act"]);
  568. expect(graph.steps.map((step) => step.phase)).toEqual(["phase#1", "phase#3"]);
  569. expect(graph.phaseEdges).toEqual([
  570. { from: "phase#1", to: "phase#2" },
  571. { from: "phase#2", to: "phase#3" },
  572. ]);
  573. expect(graph.exits).toEqual(["phase#3"]);
  574. expect(graph.participants.some((p) => p.phase === "phase#2")).toBe(false);
  575. expectReferentialIntegrity(graph);
  576. });
  577. it("keeps a phase whose only member was truncated: it is still a control-flow position", async () => {
  578. // 71 asks 截到 64 → 后一个阶段的唯一成员被截走。阶段层不按成员收敛(阶段是控制流
  579. // 位置,不是成员的集合),所以它和通向它的边都留下;step 层照旧只剩 early 的成员,
  580. // late 的那张卡随它的 step 一起消失。
  581. const asks = Array.from(
  582. { length: 70 },
  583. (_, index) => `const r${index} = await a.ask<string>("m${index}");`,
  584. );
  585. const output = await run({
  586. script: [
  587. 'const a = agent("a");',
  588. 'phase("early");',
  589. ...asks,
  590. 'phase("late");',
  591. 'const last = await a.ask<string>("last");',
  592. "return last;",
  593. ].join("\n"),
  594. });
  595. expect(output.ok).toBe(true);
  596. const graph = output.causalityGraph!;
  597. expect(graph.truncated).toBe(true);
  598. expect(graph.steps).toHaveLength(64);
  599. expect(graph.phases).toEqual([
  600. { id: "phase#1", name: "early", line: 2, column: 1 },
  601. { id: "phase#2", name: "late", line: 73, column: 1 },
  602. ]);
  603. expect(graph.phaseEdges).toEqual([{ from: "phase#1", to: "phase#2" }]);
  604. expect(graph.exits).toEqual(["phase#2"]);
  605. for (const step of graph.steps) expect(step.phase).toBe("phase#1");
  606. expect(graph.participants.map((p) => [p.id, p.steps.length])).toEqual([
  607. ["phase#1:actor#1", 64],
  608. ]);
  609. expectReferentialIntegrity(graph);
  610. });
  611. it("degrades the whole vocabulary past 32 phases", async () => {
  612. // 超界整体降级:裁一半的阶段图会说谎(被裁阶段的成员没了家),宁可不说——四个字段
  613. // 全部缺席 + truncated,UI 自然退回无阶段画面。
  614. const marked = Array.from(
  615. { length: 33 },
  616. (_, index) => `phase("p${index}");\nconst r${index} = await a.ask<string>("m${index}");`,
  617. );
  618. const output = await run({
  619. script: ['const a = agent("a");', ...marked, "return r0;"].join("\n"),
  620. });
  621. expect(output.ok).toBe(true);
  622. const graph = output.causalityGraph!;
  623. expect(graph.truncated).toBe(true);
  624. expect(Object.hasOwn(graph, "phases")).toBe(false);
  625. expect(Object.hasOwn(graph, "phaseEdges")).toBe(false);
  626. expect(Object.hasOwn(graph, "exits")).toBe(false);
  627. // step 的 `phase` 必须一起消失:带着一个不在 phases 里的阶段 id 的卡片是悬空引用。
  628. expect(graph.steps).toHaveLength(33);
  629. for (const step of graph.steps) expect(Object.hasOwn(step, "phase")).toBe(false);
  630. expectReferentialIntegrity(graph);
  631. });
  632. it("never lets a step, a card, an edge or an exit name a phase the payload does not list", async () => {
  633. // 引用完整性优先于保留数量,和车道/边同一条规则——对每一种阶段结局都成立。
  634. const scripts = [
  635. // 词汇表在场,含兜底阶段与跨阶段回边。
  636. [
  637. 'const seed = await agent("seed").ask<string>("go");',
  638. 'phase("loop");',
  639. "for (let i = 0; i < 2; i++) {",
  640. ' const r = await agent("worker").ask<string>(`step ${seed}`);',
  641. " if (r.length > 0) {",
  642. ' phase("accept");',
  643. ' await agent("saver").ask<string>(`save ${r}`);',
  644. " }",
  645. "}",
  646. "return seed;",
  647. ].join("\n"),
  648. // 零标记:四个字段全缺席。
  649. 'const a = await agent("a").ask<string>("q");\nreturn a;',
  650. // 阶段内循环 + fan-out 家族 + 工作区卡。
  651. fixture("handoff-earth-v5.ts"),
  652. ];
  653. for (const script of scripts) {
  654. const output = await run({ script });
  655. expect(output.ok).toBe(true);
  656. expectReferentialIntegrity(output.causalityGraph!);
  657. }
  658. });
  659. it("emits an empty exits list when the script has no normal completion", async () => {
  660. // 组内可为空:无条件 throw 的脚本没有通向返回物的阶段,`exits` 在场但空,`abort` 终端
  661. // 没有节点所以那条边不出现,`truncated` 不能因此撒谎。
  662. const output = await run({
  663. script: 'phase("a");\nconst x = await agent("a").ask<string>("q");\nthrow new Error(x);',
  664. });
  665. expect(output.ok).toBe(true);
  666. const graph = output.causalityGraph!;
  667. expect(graph.phases).toHaveLength(1);
  668. expect(graph.phaseEdges).toEqual([]);
  669. expect(graph.exits).toEqual([]);
  670. expect(Object.hasOwn(graph, "truncated")).toBe(false);
  671. });
  672. it("ships an exception edge as an ordinary arrow and drops the abort terminal", async () => {
  673. // try 体里的 step may-throw 进 catch 阶段:那是真实的「可能接着跑」后继,不发则只靠异常
  674. // 进入的恢复阶段会悬空。catch 里的 throw 指向 abort,无节点可落,丢弃。
  675. const output = await run({
  676. script: [
  677. 'phase("attempt");',
  678. 'const plan = await agent("planner").ask<string>("plan");',
  679. 'let result = "";',
  680. "try {",
  681. ' result = await agent("worker").ask<string>(`do: ${plan}`);',
  682. "} catch {",
  683. ' phase("recover");',
  684. ' const salvage = await agent("salvage").ask<string>(`salvage: ${plan}`);',
  685. ' if (salvage === "") throw new Error("unrecoverable");',
  686. " result = salvage;",
  687. "}",
  688. "return result;",
  689. ].join("\n"),
  690. });
  691. expect(output.ok).toBe(true);
  692. const graph = output.causalityGraph!;
  693. expect(graph.phaseEdges).toEqual([{ from: "phase#1", to: "phase#2" }]);
  694. expect(graph.exits).toEqual(["phase#1", "phase#2"]);
  695. for (const edge of graph.phaseEdges ?? []) {
  696. for (const id of [edge.from, edge.to]) expect(["entry", "sink", "abort"]).not.toContain(id);
  697. }
  698. });
  699. // —— 阶段边的传递归约(spec Round 2:一种箭头只承诺 runs-after 的可达关系)————
  700. it("drops a phase skip edge the arm path already implies", async () => {
  701. // `if` 无 else:head → 后继的跳过边被 head → arm → 后继蕴含而消失。
  702. const output = await run({
  703. script: [
  704. 'phase("a");',
  705. 'const s1 = await agent("a").ask<string>("1");',
  706. "if (s1.length > 0) {",
  707. ' phase("b");',
  708. ' await agent("b").ask<string>(`2 ${s1}`);',
  709. "}",
  710. 'phase("c");',
  711. 'return agent("c").ask<string>(`3 ${s1}`);',
  712. ].join("\n"),
  713. });
  714. expect(output.ok).toBe(true);
  715. const graph = output.causalityGraph!;
  716. expect(graph.phaseEdges).toEqual([
  717. { from: "phase#1", to: "phase#2" },
  718. { from: "phase#2", to: "phase#3" },
  719. ]);
  720. });
  721. it("keeps both directions of interleaved phases (a; b; a): neither is a loop", async () => {
  722. const output = await run({
  723. script: [
  724. 'phase("a");',
  725. 'const s1 = await agent("a").ask<string>("1");',
  726. 'phase("b");',
  727. 'const s2 = await agent("b").ask<string>(`2 ${s1}`);',
  728. 'phase("a");',
  729. 'return agent("a2").ask<string>(`3 ${s2}`);',
  730. ].join("\n"),
  731. });
  732. expect(output.ok).toBe(true);
  733. const graph = output.causalityGraph!;
  734. expect(graph.phaseEdges).toEqual([
  735. { from: "phase#1", to: "phase#2" },
  736. { from: "phase#2", to: "phase#1" },
  737. ]);
  738. expect(graph.exits).toEqual(["phase#1"]);
  739. });
  740. it("keeps one back edge for a loop body spanning three phases with a continue", async () => {
  741. // B 里的 `continue` 回 A 被「B → C(前向)→ A(一跳回边)」见证而消失;两条互相见证的
  742. // 回边不会一起消失,所以 C → A 留下,环仍然闭合。
  743. const output = await run({
  744. script: [
  745. "for (let i = 0; i < 3; i++) {",
  746. ' phase("A");',
  747. ' const a = await agent("a").ask<string>("a");',
  748. ' phase("B");',
  749. ' const b = await agent("b").ask<string>(`b ${a}`);',
  750. " if (b.length > 0) continue;",
  751. ' phase("C");',
  752. ' await agent("c").ask<string>(`c ${b}`);',
  753. "}",
  754. "return 1;",
  755. ].join("\n"),
  756. });
  757. expect(output.ok).toBe(true);
  758. const graph = output.causalityGraph!;
  759. expect(graph.phaseEdges).toEqual([
  760. { from: "phase#1", to: "phase#2" },
  761. { from: "phase#2", to: "phase#3" },
  762. { from: "phase#3", to: "phase#1", back: true },
  763. ]);
  764. expect(graph.exits).toEqual(["phase#3"]);
  765. });
  766. it("keeps every edge of two independent choices that reuse the same two phase names", async () => {
  767. // Bug(spec「Untyped reduction」同一段):两组互不相干的 if/else 复用同一对阶段名,商图
  768. // 里 left ↔ right 就成了一对普通分支边。旧实现在**原图**上找见证,于是 `choose → left`
  769. // 被 `choose → right → left` 判成冗余而删掉,`left → next` 被 `left → right → next` 删
  770. // 掉——画面变成「条件分支总是走 right,left 是 right 的岔路」,一句假话。绕环走回来的路径
  771. // 对「控制能不能到那儿」不作断言,所以归约跑在缩点上,同一分量里的边一条都不能少。
  772. const output = await run({
  773. script: [
  774. 'phase("choose");',
  775. 'const s = await agent("a").ask<string>("1");',
  776. "if (s.length > 0) {",
  777. ' phase("left");',
  778. ' await agent("l").ask<string>(`l ${s}`);',
  779. "} else {",
  780. ' phase("right");',
  781. ' await agent("r").ask<string>(`r ${s}`);',
  782. "}",
  783. "if (s.length > 1) {",
  784. ' phase("left");',
  785. ' await agent("l2").ask<string>(`l2 ${s}`);',
  786. "} else {",
  787. ' phase("right");',
  788. ' await agent("r2").ask<string>(`r2 ${s}`);',
  789. "}",
  790. 'phase("next");',
  791. 'return agent("n").ask<string>(`n ${s}`);',
  792. ].join("\n"),
  793. });
  794. expect(output.ok).toBe(true);
  795. const graph = output.causalityGraph!;
  796. expect(graph.phases?.map((phase) => phase.name)).toEqual(["choose", "left", "right", "next"]);
  797. // left 与 right 互相可达,是一个分量:两条对穿边都在,且都**不是**回边(这不是循环,
  798. // 是两组选择各走各的边)。进出分量的四条边同样一条不少。
  799. expect(graph.phaseEdges).toEqual([
  800. { from: "phase#1", to: "phase#2" },
  801. { from: "phase#1", to: "phase#3" },
  802. { from: "phase#2", to: "phase#3" },
  803. { from: "phase#2", to: "phase#4" },
  804. { from: "phase#3", to: "phase#2" },
  805. { from: "phase#3", to: "phase#4" },
  806. ]);
  807. for (const edge of graph.phaseEdges ?? []) expect(Object.hasOwn(edge, "back")).toBe(false);
  808. expect(graph.exits).toEqual(["phase#4"]);
  809. expectReferentialIntegrity(graph);
  810. });
  811. it("still drops a spawner's pass-through edge over a fork/join: nothing there is on a cycle", async () => {
  812. // 缩点归约的另一半:无环处的删边一点不能放松。两个并发回调各开一个阶段,主线在 join
  813. // 之后进入收尾——`spawn → join` 被两条 strand 路径蕴含,照旧消失。三个阶段各自成分量,
  814. // 所以这里的见证仍然作数。
  815. const output = await run({
  816. script: [
  817. 'phase("spawn");',
  818. 'const seed = await agent("s").ask<string>("seed");',
  819. "const left = (async () => {",
  820. ' phase("left");',
  821. ' return agent("l").ask<string>(`l ${seed}`);',
  822. "})();",
  823. "const right = (async () => {",
  824. ' phase("right");',
  825. ' return agent("r").ask<string>(`r ${seed}`);',
  826. "})();",
  827. "const both = await Promise.all([left, right]);",
  828. 'phase("join");',
  829. 'return agent("j").ask<string>(`j ${both.join(",")}`);',
  830. ].join("\n"),
  831. });
  832. expect(output.ok).toBe(true);
  833. const graph = output.causalityGraph!;
  834. expect(graph.phases?.map((phase) => phase.name)).toEqual(["spawn", "left", "right", "join"]);
  835. expect(graph.phaseEdges).toEqual([
  836. { from: "phase#1", to: "phase#2" },
  837. { from: "phase#1", to: "phase#3" },
  838. { from: "phase#2", to: "phase#4" },
  839. { from: "phase#3", to: "phase#4" },
  840. ]);
  841. expectReferentialIntegrity(graph);
  842. });
  843. it("leaves a loop's back edge out of the components: the skip edge it spans still drops", async () => {
  844. // 分量只看前向边。回边说的是「下一轮」,把它算进分量会让整个循环体缩成一个点,循环体
  845. // 内部真正冗余的边就再也删不掉——这里 `A → C` 会跟着 `B → C` 一起留下来。
  846. const output = await run({
  847. script: [
  848. "for (let i = 0; i < 3; i++) {",
  849. ' phase("A");',
  850. ' const a = await agent("a").ask<string>("a");',
  851. " if (a.length > 0) {",
  852. ' phase("B");',
  853. ' await agent("b").ask<string>(`b ${a}`);',
  854. " }",
  855. "}",
  856. 'phase("C");',
  857. 'return agent("c").ask<string>("c");',
  858. ].join("\n"),
  859. });
  860. expect(output.ok).toBe(true);
  861. const graph = output.causalityGraph!;
  862. expect(graph.phaseEdges).toEqual([
  863. { from: "phase#1", to: "phase#2" },
  864. { from: "phase#2", to: "phase#1", back: true },
  865. { from: "phase#2", to: "phase#3" },
  866. ]);
  867. expect(graph.exits).toEqual(["phase#3"]);
  868. expectReferentialIntegrity(graph);
  869. });
  870. it("carries `alongside` for a phase entered while another phase's strands still ran", async () => {
  871. // 语料 strand-fanout-two-phases-join.ts,golden `phase phase#2 "B" alongside=phase#1`:
  872. // A 的 fan-out 没有被 await,B 的标记因此在 A 的子代理还在跑的时候就到了。这是**节点事实**
  873. // ——只挂在 B 上,且不得在两者之间变出一条边(控制并没有从 A 转移到 B 之外的地方)。
  874. const output = await run({ script: fixture("strand-fanout-two-phases-join.ts") });
  875. expect(output.ok).toBe(true);
  876. const graph = output.causalityGraph!;
  877. expect(graph.phases?.map((phase) => phase.name)).toEqual(["A", "B", "C"]);
  878. expect(graph.phases?.[1]).toMatchObject({ id: "phase#2", name: "B", alongside: ["phase#1"] });
  879. expect(Object.hasOwn(graph.phases![0]!, "alongside")).toBe(false);
  880. expect(Object.hasOwn(graph.phases![2]!, "alongside")).toBe(false);
  881. expectReferentialIntegrity(graph);
  882. });
  883. it("streams the channel between two stage futures, but not the writer after the join", async () => {
  884. // 语料 stream-pipeline.ts(docs/dynamic-workflow/presentation.md「Streams」):因果图阶段商有
  885. // phase#1 →data→ phase#2(facts channel)、phase#1 →data→ phase#3、phase#2 →seq→ phase#3。
  886. // 只有第一条连着两个互为 alongside 的阶段——写作者在 join 之后,是控制箭头的事。
  887. const output = await run({ script: fixture("stream-pipeline.ts") });
  888. expect(output.ok).toBe(true);
  889. const graph = output.causalityGraph!;
  890. expect(graph.phaseStreams).toEqual([{ from: "phase#1", to: "phase#2" }]);
  891. expectReferentialIntegrity(graph);
  892. });
  893. it("streams every hand-off of a five-stage pipeline, in order", () => {
  894. // 触发本设计的形状(testfield「2077 未来职业流水线」缩写):五个 stage future 由四条 channel
  895. // 串起来,控制流视图里五个阶段两两 alongside、phaseEdges 为空——流是它们之间唯一的关系。
  896. const graph = bound(`
  897. const FIELDS = ["pets", "sleep", "food"];
  898. const s1 = channel<string>("s1");
  899. const s2 = channel<string>("s2");
  900. const s3 = channel<string>("s3");
  901. const s4 = channel<string>("s4");
  902. const a = future(async () => {
  903. phase("Invent");
  904. try {
  905. await Promise.all(FIELDS.map(async (field) => s1.send(await agent(\`inventor-\${field}\`).ask<string>(field))));
  906. } finally { s1.close(); }
  907. });
  908. const b = future(async () => {
  909. phase("Post");
  910. try { for await (const job of s1) s2.send(await agent(\`poster-\${job}\`).ask<string>(job)); }
  911. finally { s2.close(); }
  912. });
  913. const c = future(async () => {
  914. phase("Tell");
  915. try { for await (const job of s2) s3.send(await agent(\`teller-\${job}\`).ask<string>(job)); }
  916. finally { s3.close(); }
  917. });
  918. const d = future(async () => {
  919. phase("Roast");
  920. try { for await (const job of s3) s4.send(await agent(\`roaster-\${job}\`).ask<string>(job)); }
  921. finally { s4.close(); }
  922. });
  923. const done: string[] = [];
  924. const e = future(async () => {
  925. phase("Bind");
  926. for await (const job of s4) done.push(await agent(\`binder-\${job}\`).ask<string>(job));
  927. });
  928. await Promise.all([a, b, c, d, e]);
  929. return done;
  930. `);
  931. expect(graph.phases?.map((phase) => phase.name)).toEqual([
  932. "Invent",
  933. "Post",
  934. "Tell",
  935. "Roast",
  936. "Bind",
  937. ]);
  938. expect(graph.phaseStreams).toEqual([
  939. { from: "phase#1", to: "phase#2" },
  940. { from: "phase#2", to: "phase#3" },
  941. { from: "phase#3", to: "phase#4" },
  942. { from: "phase#4", to: "phase#5" },
  943. ]);
  944. expectReferentialIntegrity(graph);
  945. });
  946. it("leaves two futures with no channel between them without streams", () => {
  947. // 两个互不相干的 future 照样 alongside(一条带),但没有 data 边就没有流:字段整个缺席。
  948. const graph = bound(`
  949. const web = future(async () => {
  950. phase("Read the web");
  951. return agent("web-reader").ask<string>("web");
  952. });
  953. const papers = future(async () => {
  954. phase("Read the papers");
  955. return agent("paper-reader").ask<string>("papers");
  956. });
  957. const [w, p] = await Promise.all([web, papers]);
  958. phase("Write");
  959. return agent("writer").ask<string>(\`\${w} \${p}\`);
  960. `);
  961. expect(graph.phases?.[1]?.alongside).toEqual(["phase#1"]);
  962. expect(Object.hasOwn(graph, "phaseStreams")).toBe(false);
  963. expectReferentialIntegrity(graph);
  964. });
  965. it("leaves the sequential control free of `alongside`", async () => {
  966. // 对照组 strand-fanout-awaited-per-phase.ts:同样三次 fan-out,但每个阶段都先 await 完
  967. // 自己的工作,没有东西跨过标记停着。缺席必须是**字段缺席**——UI 据缺席画一条直线。
  968. const output = await run({ script: fixture("strand-fanout-awaited-per-phase.ts") });
  969. expect(output.ok).toBe(true);
  970. const graph = output.causalityGraph!;
  971. expect(graph.phases?.map((phase) => phase.name)).toEqual(["A", "B", "C"]);
  972. for (const phase of graph.phases!) expect(Object.hasOwn(phase, "alongside")).toBe(false);
  973. expectReferentialIntegrity(graph);
  974. });
  975. it("matches the control-flow phase quotient of phase-jsonl-db up to reduction", async () => {
  976. // 端到端验收(spec「测试与验收」):载荷阶段边的前向闭包 = `.phase-flow.mmd` 去掉终端、
  977. // 自环与纯 loop 边后的闭包;载荷边集不可约;back 边是 mmd 里 loop 边的子集,且每条被
  978. // loop 边闭合的环仍被闭合(两端互相可达)。
  979. const output = await run({ script: fixture("phase-jsonl-db.ts") });
  980. expect(output.ok).toBe(true);
  981. const graph = output.causalityGraph!;
  982. const mmd = fixture("expected/phase-jsonl-db.phase-flow.mmd");
  983. const terminals = new Set(["entry", "sink", "abort"]);
  984. const forward: Edge[] = [];
  985. const loops: Edge[] = [];
  986. const exits = new Set<string>();
  987. for (const line of mmd.split("\n")) {
  988. const match = /^\s*(\S+) -->(?:\|"([^"]*)"\|)? (\S+)$/.exec(line);
  989. if (match === null) continue;
  990. const [, rawFrom, labels, rawTo] = match;
  991. const from = (rawFrom as string).replace("phase_", "phase#");
  992. const to = (rawTo as string).replace("phase_", "phase#");
  993. if (to === "sink") {
  994. exits.add(from);
  995. continue;
  996. }
  997. if (terminals.has(from) || terminals.has(to) || from === to) continue;
  998. const kinds = (labels ?? "next").split(", ").map((label) => label.replace(/ \(.*\)$/, ""));
  999. if (kinds.every((kind) => kind === "loop")) loops.push({ back: true, from, to });
  1000. else forward.push({ from, to });
  1001. }
  1002. expect(closureEquals(closure(graph.phaseEdges ?? []), closure(forward))).toBe(true);
  1003. expect(isIrredundant(graph.phaseEdges ?? [])).toBe(true);
  1004. const backs = (graph.phaseEdges ?? []).filter((edge) => edge.back === true);
  1005. expect(backs.length).toBeGreaterThan(0);
  1006. for (const edge of backs) {
  1007. expect(loops.some((loop) => loop.from === edge.from && loop.to === edge.to)).toBe(true);
  1008. }
  1009. // 每条 mmd 回边闭合的环在载荷(前向 ∪ back)里仍是环:两端互相可达。
  1010. const all = (graph.phaseEdges ?? []).map((edge) => ({ from: edge.from, to: edge.to }));
  1011. const reach = closure(all);
  1012. for (const loop of loops) {
  1013. expect(reach.get(loop.from)?.has(loop.to)).toBe(true);
  1014. expect(reach.get(loop.to)?.has(loop.from)).toBe(true);
  1015. }
  1016. expect(graph.exits).toEqual([...exits]);
  1017. // 六个阶段都在,成员划分是全的。
  1018. expect(graph.phases?.map((phase) => phase.name)).toEqual([
  1019. "preflight",
  1020. "attempt",
  1021. "gate",
  1022. "checkpoint",
  1023. "recover",
  1024. "wrap-up",
  1025. ]);
  1026. expectReferentialIntegrity(graph);
  1027. });
  1028. it("surfaces facade-misuse diagnostics with ok=false and no graph", async () => {
  1029. const output = await run({ script: "const spawn = agent;\nreturn 1;" });
  1030. expect(output.ok).toBe(false);
  1031. expect(output.causalityGraph).toBeUndefined();
  1032. expect(
  1033. output.diagnostics.some((diagnostic) =>
  1034. diagnostic.message.includes("may only be called directly"),
  1035. ),
  1036. ).toBe(true);
  1037. expect(output.response).toContain("NOT executed");
  1038. });
  1039. it("reports diagnostics for a type error with script-relative line", async () => {
  1040. const output = await run({ script: 'const x: number = "s";' });
  1041. expect(output.ok).toBe(false);
  1042. expect(output.causalityGraph).toBeUndefined();
  1043. expect(output.diagnostics.some((diagnostic) => diagnostic.line === 1)).toBe(true);
  1044. expect(output.response).toContain("L1:");
  1045. expect(output.response).toContain("NOT executed");
  1046. });
  1047. /**
  1048. * 占位文案真化:诊断路径的 NOTE 曾自述「the execution model is still under development」与
  1049. * 「only typechecks the script (placeholder for testing)」——引擎接线后两句都是谎言(干净脚本
  1050. * 会真启动一个后台 run)。这条路径上唯一为真的是「没执行」+「改完重交」,模型据此走自己的
  1051. * 改错重试回路,而不是以为整个工具还是个玩具。
  1052. */
  1053. it("诊断路径的 NOTE 只说没执行与改完重交,不再自述占位", async () => {
  1054. const output = await run({ script: 'const x: number = "s";' });
  1055. expect(output.ok).toBe(false);
  1056. expect(output.response).toContain("NOT executed");
  1057. expect(output.response).toContain("fix the errors above and resubmit");
  1058. expect(output.response).not.toContain("under development");
  1059. expect(output.response).not.toContain("placeholder");
  1060. expect(output.response).not.toContain("only typechecks");
  1061. });
  1062. it("rejects Node globals to enforce script purity", async () => {
  1063. const output = await run({ script: "process.exit(1);" });
  1064. expect(output.ok).toBe(false);
  1065. expect(
  1066. output.diagnostics.some((diagnostic) => diagnostic.message.includes("Cannot find name")),
  1067. ).toBe(true);
  1068. });
  1069. it("rejects input missing the script field", async () => {
  1070. await expect(run({ name: "no-script" })).rejects.toThrow();
  1071. });
  1072. it("keeps the facade out of its description and points at the skill instead", () => {
  1073. // 2026-09-21:facade 与写作规则搬进 dynamic-workflows 技能(docs/dynamic-workflow/authoring.md
  1074. // 「The authoring surface」),描述只剩几百 token。这里钉住两件事:d.ts 不再随每次请求重发,
  1075. // 描述点名了技能与 Skill 工具。路由信号仍在 workflow-routing-hints.test.ts。
  1076. const description = createWorkflowToolEntry.metadata.description ?? "";
  1077. expect(description).not.toContain("declare ");
  1078. expect(description).not.toContain("ask<T");
  1079. expect(description).toContain("`dynamic-workflows` skill");
  1080. expect(description).toContain("Skill tool");
  1081. // The description used to claim the tool "does NOT run anything" — stale since
  1082. // the engine got wired, and it pushed the model to Agent for explicit workflow
  1083. // requests.
  1084. expect(description).not.toContain("does NOT run anything");
  1085. });
  1086. });
  1087. // 并发上界(docs/dynamic-workflow/concurrency.md「Two bounds on a run」)的归一住在
  1088. // resolveInput 而不是 handler:确认窗必须显示将要生效的那个数,而窗在 handler 之前。
  1089. // 默认并发是起点不是上限,所以这里只向下取整到至少 1,高于默认的值原样放行。
  1090. describe("CreateWorkflow resolveInput — max_concurrency", () => {
  1091. /** 内联路径一次盘都不碰,所以 cwd 是什么无所谓;saved 用例自己造真目录。 */
  1092. const UNREAD_CWD = "/workspace/never-read";
  1093. async function resolved(input: unknown, cwd = UNREAD_CWD): Promise<Record<string, unknown>> {
  1094. const resolution = await resolveCreateWorkflowInput(input, cwd);
  1095. expect(resolution).toMatchObject({ result: true });
  1096. return (resolution as { input: unknown }).input as Record<string, unknown>;
  1097. }
  1098. it("leaves a request above the default byte-identical: there is no upper limit", async () => {
  1099. const input = { script: "return 1;", max_concurrency: 200 };
  1100. expect(await resolved(input)).toBe(input);
  1101. });
  1102. it("never invents the key for a call that did not set one", async () => {
  1103. expect(Object.hasOwn(await resolved({ script: "return 1;" }), "max_concurrency")).toBe(false);
  1104. });
  1105. it("carries the limit through the saved source, which rebuilds the input", async () => {
  1106. // saved 分支是从零拼一份新入参的,所以「字段被悄悄丢掉」是这条路径独有的失效形态。
  1107. const cwd = mkdtempSync(join(tmpdir(), "dwf-maxconc-"));
  1108. try {
  1109. saveSavedWorkflow({ cwd, name: "nightly", meta: { description: "d" }, script: "return 1;" });
  1110. const input = await resolved({ saved: { name: "nightly" }, max_concurrency: 32 }, cwd);
  1111. expect(input.max_concurrency).toBe(32);
  1112. expect(input.script).toBe("return 1;");
  1113. // 未设上界的 saved 调用同样不造空壳键。
  1114. expect(
  1115. Object.hasOwn(await resolved({ saved: { name: "nightly" } }, cwd), "max_concurrency"),
  1116. ).toBe(false);
  1117. } finally {
  1118. rmSync(cwd, { force: true, recursive: true });
  1119. }
  1120. });
  1121. it("floors to a whole number of at least one, and nothing more", () => {
  1122. // helper 是两个工具的共用入口:schema 之外的值(0、负数、小数)不该穿过去;大数原样过。
  1123. expect(normalizeWorkflowMaxConcurrency(0)).toBe(1);
  1124. expect(normalizeWorkflowMaxConcurrency(-3)).toBe(1);
  1125. expect(normalizeWorkflowMaxConcurrency(3.7)).toBe(3);
  1126. expect(normalizeWorkflowMaxConcurrency(500)).toBe(500);
  1127. });
  1128. });
  1129. // 子代理模型(docs/dynamic-workflow/launch.md「From call to run」)与并发上界同住 resolveInput,
  1130. // 理由也同一条:确认窗必须显示将要生效的那个模型,而解不出来的调用根本不该开窗。
  1131. describe("CreateWorkflow resolveInput — subagent_model", () => {
  1132. const UNREAD_CWD = "/workspace/never-read";
  1133. function catalogOf(...entries: ModelCatalogEntry[]): ModelCatalogPort {
  1134. return { listModels: () => entries };
  1135. }
  1136. function entry(
  1137. providerId: string,
  1138. modelId: string,
  1139. extra: Partial<ModelCatalogEntry> = {},
  1140. ): ModelCatalogEntry {
  1141. return { providerId, modelId, reasoningLevels: [], current: false, ...extra };
  1142. }
  1143. const CATALOG = catalogOf(
  1144. entry("bigmodel", "GLM-4.6", {
  1145. reasoningLevels: ["low", "high"],
  1146. defaultReasoningLevel: "high",
  1147. current: true,
  1148. }),
  1149. entry("openai", "gpt-5"),
  1150. );
  1151. async function resolved(
  1152. input: unknown,
  1153. catalog?: ModelCatalogPort,
  1154. cwd = UNREAD_CWD,
  1155. ): Promise<Record<string, unknown>> {
  1156. const resolution = await resolveCreateWorkflowInput(input, cwd, catalog);
  1157. expect(resolution).toMatchObject({ result: true });
  1158. return (resolution as { input: unknown }).input as Record<string, unknown>;
  1159. }
  1160. async function failed(input: unknown, catalog?: ModelCatalogPort): Promise<ToolHandlerFailure> {
  1161. const resolution = await resolveCreateWorkflowInput(input, UNREAD_CWD, catalog);
  1162. expect(resolution.result).toBe(false);
  1163. return resolution as ToolHandlerFailure;
  1164. }
  1165. it("rewrites the model the user named into the canonical picker form", async () => {
  1166. // 用户说的是裸名、大小写也不同;窗上与 handler 看到的必须是注册表的那一个。
  1167. expect(
  1168. (await resolved({ script: "return 1;", subagent_model: "glm-4.6" }, CATALOG)).subagent_model,
  1169. ).toBe("bigmodel/GLM-4.6$high");
  1170. });
  1171. it("leaves an already-canonical inline call byte-identical", async () => {
  1172. const input = { script: "return 1;", subagent_model: "openai/gpt-5" };
  1173. expect(await resolved(input, CATALOG)).toBe(input);
  1174. });
  1175. it("normalises a padded id rather than letting the window show the whitespace", async () => {
  1176. // schema 带 `.trim()`,所以「解析后与规范形相等」并不意味着原始入参就是规范形。
  1177. const input = { script: "return 1;", subagent_model: " openai/gpt-5 " };
  1178. const resolvedInput = await resolved(input, CATALOG);
  1179. expect(resolvedInput).not.toBe(input);
  1180. expect(resolvedInput.subagent_model).toBe("openai/gpt-5");
  1181. });
  1182. it("never invents the key for a call that did not choose a model", async () => {
  1183. const input = { script: "return 1;" };
  1184. expect(await resolved(input, CATALOG)).toBe(input);
  1185. expect(Object.hasOwn(await resolved(input, CATALOG), "subagent_model")).toBe(false);
  1186. });
  1187. it("fails before the confirmation window and lists the ids the model could have used", async () => {
  1188. // 裸名只在别的 provider 下有:边界挡回,窗不开,文案把「用户点名才写全称」说给模型听。
  1189. const crossing = await failed({ script: "return 1;", subagent_model: "gpt-5" }, CATALOG);
  1190. expect(crossing.message).toContain("session's provider (bigmodel)");
  1191. expect(crossing.message).toContain("openai/gpt-5");
  1192. expect(crossing.message).toContain("ask the user first");
  1193. const failure = await failed({ script: "return 1;", subagent_model: "gemini-3" }, CATALOG);
  1194. expect(failure.message).toContain("No configured model matches `gemini-3`");
  1195. expect(failure.message).toContain("bigmodel/GLM-4.6 [current]");
  1196. expect(failure.message).toContain("openai/gpt-5");
  1197. expect(failure.message).toContain("call ListModels");
  1198. });
  1199. it("refuses the field outright on a host with no model catalog", async () => {
  1200. // 静默放行会让一个宿主解不了的字符串一路传到子代理第一次开口时才炸。
  1201. const failure = await failed({ script: "return 1;", subagent_model: "gpt-5" }, undefined);
  1202. expect(failure.message).toBe("This host cannot choose a subagent model; omit subagent_model.");
  1203. // 没给字段的调用在同一台宿主上照常通过。
  1204. expect(
  1205. Object.hasOwn(await resolved({ script: "return 1;" }, undefined), "subagent_model"),
  1206. ).toBe(false);
  1207. });
  1208. it("carries the canonical model through the saved source, which rebuilds the input", async () => {
  1209. // saved 分支从零拼一份新入参,所以「字段被悄悄丢掉」是这条路径独有的失效形态。
  1210. const cwd = mkdtempSync(join(tmpdir(), "dwf-subagent-model-"));
  1211. try {
  1212. saveSavedWorkflow({ cwd, name: "nightly", meta: { description: "d" }, script: "return 1;" });
  1213. // 全称:`gpt-5` 不在会话的 provider(bigmodel)下,裸名会被 provider 边界挡回。
  1214. const input = await resolved(
  1215. { saved: { name: "nightly" }, subagent_model: "openai/GPT-5" },
  1216. CATALOG,
  1217. cwd,
  1218. );
  1219. expect(input.subagent_model).toBe("openai/gpt-5");
  1220. expect(input.script).toBe("return 1;");
  1221. expect(
  1222. Object.hasOwn(
  1223. await resolved({ saved: { name: "nightly" } }, CATALOG, cwd),
  1224. "subagent_model",
  1225. ),
  1226. ).toBe(false);
  1227. } finally {
  1228. rmSync(cwd, { force: true, recursive: true });
  1229. }
  1230. });
  1231. it("fails a saved call without touching the disk: nothing runs and no window opens", async () => {
  1232. // 解析排在读盘之前,所以一个连模型名都解不出来的调用不会先去扫一遍磁盘。
  1233. const failure = await failed(
  1234. { saved: { name: "nightly" }, subagent_model: "gemini-3" },
  1235. CATALOG,
  1236. );
  1237. expect(failure.message).toContain("No configured model matches");
  1238. expect(failure.message).not.toContain("saved workflow");
  1239. });
  1240. it("clamps the limit and canonicalises the model in the same rewrite", async () => {
  1241. const input = await resolved(
  1242. { script: "return 1;", max_concurrency: 3, subagent_model: "glm-4.6" },
  1243. CATALOG,
  1244. );
  1245. expect(input.max_concurrency).toBe(3);
  1246. expect(input.subagent_model).toBe("bigmodel/GLM-4.6$high");
  1247. });
  1248. });
  1249. // 裁剪层是**自卫**的,不是信任生产者的:这些图直接喂给 boundCausalityGraph,因为分析器
  1250. // 按构造产不出它们。「认领的阶段都已声明」是上游的语料性质,不是本层的输入契约——阶段 id
  1251. // 是自由字符串,悬空引用 .strict() 抓不到,只能在这里挡住。
  1252. describe("boundCausalityGraph — 对损坏输入的引用完整性", () => {
  1253. const step = (id: string, phase: string) => ({
  1254. id,
  1255. kind: "ask" as const,
  1256. label: id,
  1257. loc: { line: 1, column: 1 },
  1258. lane: "actor#1",
  1259. region: "seq#1",
  1260. certainty: "always" as const,
  1261. phase,
  1262. });
  1263. const base = {
  1264. lanes: [{ id: "actor#1", name: "a" }],
  1265. regions: [{ id: "seq#1", kind: "seq" as const }],
  1266. edges: [],
  1267. };
  1268. const flowWith = (phaseEdges: ControlFlowGraph["phaseEdges"]): ControlFlowGraph => ({
  1269. edges: [],
  1270. nodes: [],
  1271. phaseEdges,
  1272. phases: [{ id: "phase#1", name: "declared" }],
  1273. });
  1274. it("strips a phase the vocabulary does not list, keeping the listed ones", () => {
  1275. const bounded = boundCausalityGraph(
  1276. { ...base, steps: [step("ask#1", "phase#1"), step("ask#2", "phase#99")] },
  1277. flowWith([]),
  1278. );
  1279. // 声明过的阶段照常列出并保留成员;声称未声明阶段的那个 step 只丢 `phase` 字段,
  1280. // 卡片本身仍在图上(它的车道都还是好的)。
  1281. expect(bounded.phases).toEqual([{ id: "phase#1", name: "declared" }]);
  1282. expect(bounded.steps.map((s) => s.id)).toEqual(["ask#1", "ask#2"]);
  1283. expect(bounded.steps[0]?.phase).toBe("phase#1");
  1284. expect(Object.hasOwn(bounded.steps[1]!, "phase")).toBe(false);
  1285. });
  1286. it("keeps only listed ids in `alongside`, never itself and never twice", () => {
  1287. const bounded = boundCausalityGraph(
  1288. { ...base, steps: [step("ask#1", "phase#1"), step("ask#2", "phase#2")] },
  1289. {
  1290. edges: [],
  1291. nodes: [],
  1292. phaseEdges: [],
  1293. phases: [
  1294. { id: "phase#1", name: "A" },
  1295. { id: "phase#2", name: "B", alongside: ["phase#2", "phase#99", "phase#1", "phase#1"] },
  1296. ],
  1297. },
  1298. );
  1299. // 与边同一条引用完整性规则:自引用、未列出的阶段、重复项都丢掉,剩下空的就整个字段缺席。
  1300. expect(bounded.phases).toEqual([
  1301. { id: "phase#1", name: "A" },
  1302. { id: "phase#2", name: "B", alongside: ["phase#1"] },
  1303. ]);
  1304. expect(Object.hasOwn(bounded.phases![0]!, "alongside")).toBe(false);
  1305. // 而且它不是边:一条 phaseEdge 都不该因此长出来。
  1306. expect(bounded.phaseEdges).toEqual([]);
  1307. });
  1308. it("streams only data edges between listed phases that run alongside each other", () => {
  1309. const bounded = boundCausalityGraph(
  1310. {
  1311. ...base,
  1312. steps: [step("ask#1", "phase#1"), step("ask#2", "phase#2"), step("ask#3", "phase#3")],
  1313. phases: [
  1314. { id: "phase#1", name: "A" },
  1315. { id: "phase#2", name: "B" },
  1316. { id: "phase#3", name: "C" },
  1317. ],
  1318. phaseEdges: [
  1319. { certainty: "maybe", from: "phase#1", kind: "data", to: "phase#2" },
  1320. // 重复、自环、非 data、未列出的阶段、不 alongside 的一对:全都不是流。
  1321. { certainty: "always", from: "phase#1", kind: "data", to: "phase#2" },
  1322. { certainty: "maybe", from: "phase#2", kind: "data", to: "phase#2" },
  1323. { certainty: "maybe", from: "phase#1", kind: "seq", to: "phase#2" },
  1324. { certainty: "maybe", from: "phase#2", kind: "data", to: "phase#99" },
  1325. { certainty: "maybe", from: "phase#2", kind: "data", to: "phase#3" },
  1326. ],
  1327. },
  1328. {
  1329. edges: [],
  1330. nodes: [],
  1331. phaseEdges: [],
  1332. phases: [
  1333. { id: "phase#1", name: "A" },
  1334. { id: "phase#2", name: "B", alongside: ["phase#1"] },
  1335. { id: "phase#3", name: "C" },
  1336. ],
  1337. },
  1338. );
  1339. expect(bounded.phaseStreams).toEqual([{ from: "phase#1", to: "phase#2" }]);
  1340. // 流不是边:phaseEdges 只来自控制流视图。
  1341. expect(bounded.phaseEdges).toEqual([]);
  1342. });
  1343. it("drops the whole vocabulary when the streams exceed their bound", () => {
  1344. const ids = Array.from({ length: 17 }, (_, i) => `phase#${i + 1}`);
  1345. const bounded = boundCausalityGraph(
  1346. {
  1347. ...base,
  1348. steps: [step("ask#1", "phase#1")],
  1349. phases: ids.map((id) => ({ id, name: id })),
  1350. // 17 × 16 = 272 条互为 alongside 的有序对,全是 data 边:超过 128。
  1351. phaseEdges: ids.flatMap((from) =>
  1352. ids
  1353. .filter((to) => to !== from)
  1354. .map((to) => ({ certainty: "maybe" as const, from, kind: "data" as const, to })),
  1355. ),
  1356. },
  1357. {
  1358. edges: [],
  1359. nodes: [],
  1360. phaseEdges: [],
  1361. phases: ids.map((id) => ({ id, name: id, alongside: ids.filter((other) => other !== id) })),
  1362. },
  1363. );
  1364. expect(Object.hasOwn(bounded, "phases")).toBe(false);
  1365. expect(Object.hasOwn(bounded, "phaseStreams")).toBe(false);
  1366. expect(bounded.truncated).toBe(true);
  1367. });
  1368. it("drops edges that touch an unlisted phase or a terminal, and folds sink edges into exits", () => {
  1369. const bounded = boundCausalityGraph(
  1370. { ...base, steps: [step("ask#1", "phase#1")] },
  1371. flowWith([
  1372. { from: "entry", kind: "next", to: "phase#1" },
  1373. { from: "phase#1", kind: "next", to: "phase#99" },
  1374. { from: "phase#99", kind: "next", to: "phase#1" },
  1375. { from: "phase#1", kind: "loop", to: "phase#1" },
  1376. { from: "phase#1", kind: "throw", to: "abort" },
  1377. { from: "phase#1", kind: "jump", to: "sink", via: "return" },
  1378. ]),
  1379. );
  1380. // 端点过滤按**列出的**阶段;entry / abort 无节点;自环不发;sink 边变成 exits。
  1381. expect(bounded.phaseEdges).toEqual([]);
  1382. expect(bounded.exits).toEqual(["phase#1"]);
  1383. });
  1384. it("emits no vocabulary at all without a control-flow projection", () => {
  1385. // 阶段层的唯一来源是控制流图;因果图自己带的 phases 不再进载荷。全有或全无。
  1386. const bounded = boundCausalityGraph({
  1387. ...base,
  1388. steps: [step("ask#1", "phase#1")],
  1389. phases: [{ id: "phase#1", name: "declared" }],
  1390. phaseEdges: [],
  1391. });
  1392. expect(Object.hasOwn(bounded, "phases")).toBe(false);
  1393. expect(Object.hasOwn(bounded, "phaseEdges")).toBe(false);
  1394. expect(Object.hasOwn(bounded, "exits")).toBe(false);
  1395. for (const s of bounded.steps) expect(Object.hasOwn(s, "phase")).toBe(false);
  1396. expect(Object.hasOwn(bounded, "truncated")).toBe(false);
  1397. });
  1398. it("folds same-pair phase edges into one and marks back only when every fact was a back edge", () => {
  1399. const bounded = boundCausalityGraph(
  1400. { ...base, steps: [step("ask#1", "phase#1"), step("ask#2", "phase#2")] },
  1401. {
  1402. edges: [],
  1403. nodes: [],
  1404. phases: [
  1405. { id: "phase#1", name: "a" },
  1406. { id: "phase#2", name: "b" },
  1407. ],
  1408. phaseEdges: [
  1409. { from: "phase#1", kind: "loop", to: "phase#2" },
  1410. { from: "phase#1", kind: "next", to: "phase#2" },
  1411. { from: "phase#2", kind: "loop", to: "phase#1" },
  1412. ],
  1413. },
  1414. );
  1415. // phase#1 → phase#2 同时有前向事实与回边事实:按前向处理(排秩宁多一条约束);
  1416. // phase#2 → phase#1 只有回边事实:back。
  1417. expect(bounded.phaseEdges).toEqual([
  1418. { from: "phase#1", to: "phase#2" },
  1419. { from: "phase#2", to: "phase#1", back: true },
  1420. ]);
  1421. });
  1422. it("emits no cards and no hand-offs without a hand-off projection", () => {
  1423. // 第二层的唯一来源是分析器的交接图;缺席时两个必填数组为空,而不是 undefined。
  1424. const bounded = boundCausalityGraph({ ...base, steps: [step("ask#1", "phase#1")] });
  1425. expect(bounded.participants).toEqual([]);
  1426. expect(bounded.handoffs).toEqual([]);
  1427. expect(Object.hasOwn(bounded, "truncated")).toBe(false);
  1428. });
  1429. it("truncates participants in order to 64, dropping hand-offs that touch a cut card and types past 8", () => {
  1430. // 70 张成员卡共享同一个站点 step(分析器的 FANOUT_EXPAND_CAP 产不出这么多,所以手造)。
  1431. // 开局者活下来、尾巴被截;触及被截卡的交接随之消失;`types` 每边截到 8 个。
  1432. const handoff: HandoffGraph = {
  1433. participants: Array.from({ length: 70 }, (_, index) => ({
  1434. id: `unphased:actor#1[${index}]`,
  1435. phase: "unphased",
  1436. lane: "actor#1",
  1437. steps: ["ask#1"],
  1438. member: { index, of: 70 },
  1439. })),
  1440. handoffs: [
  1441. { from: "unphased:actor#1[0]", to: "unphased:actor#1[69]", types: ["Dropped"] },
  1442. {
  1443. from: "unphased:actor#1[0]",
  1444. to: "unphased:actor#1[1]",
  1445. types: Array.from({ length: 10 }, (_, index) => `T${index}`),
  1446. },
  1447. { from: "unphased:actor#1[65]", to: "unphased:actor#1[2]", back: true },
  1448. ],
  1449. };
  1450. const bounded = boundCausalityGraph(
  1451. { ...base, steps: [step("ask#1", "phase#1")] },
  1452. undefined,
  1453. handoff,
  1454. );
  1455. expect(bounded.truncated).toBe(true);
  1456. expect(bounded.participants.map((p) => p.id)).toEqual(
  1457. Array.from({ length: 64 }, (_, index) => `unphased:actor#1[${index}]`),
  1458. );
  1459. expect(bounded.participants[63]).toEqual({
  1460. id: "unphased:actor#1[63]",
  1461. phase: "unphased",
  1462. lane: "actor#1",
  1463. steps: ["ask#1"],
  1464. member: { index: 63, of: 70 },
  1465. });
  1466. expect(bounded.handoffs).toEqual([
  1467. {
  1468. from: "unphased:actor#1[0]",
  1469. to: "unphased:actor#1[1]",
  1470. types: ["T0", "T1", "T2", "T3", "T4", "T5", "T6", "T7"],
  1471. },
  1472. ]);
  1473. });
  1474. it("drops a card whose lane or every step was cut, and its hand-offs with it", () => {
  1475. // 卡的 step 收敛到存活的 step,一个都不剩的卡消失;车道不在场的卡消失;被截卡的 step
  1476. // 仍留在 `steps`(运行状态照常关联)。任一丢弃置 truncated。
  1477. const handoff: HandoffGraph = {
  1478. participants: [
  1479. {
  1480. id: "unphased:actor#1",
  1481. phase: "unphased",
  1482. lane: "actor#1",
  1483. steps: ["ask#1", "ask#ghost"],
  1484. },
  1485. { id: "unphased:actor#9", phase: "unphased", lane: "actor#9", steps: ["ask#1"] },
  1486. { id: "unphased:workspace", phase: "unphased", lane: "workspace", steps: ["ask#ghost"] },
  1487. ],
  1488. handoffs: [
  1489. { from: "unphased:actor#1", to: "unphased:actor#9" },
  1490. { from: "unphased:workspace", to: "unphased:actor#1", types: ["X"] },
  1491. ],
  1492. };
  1493. const bounded = boundCausalityGraph(
  1494. { ...base, lanes: [...base.lanes, { id: "workspace" }], steps: [step("ask#1", "phase#1")] },
  1495. undefined,
  1496. handoff,
  1497. );
  1498. expect(bounded.participants).toEqual([
  1499. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  1500. ]);
  1501. expect(bounded.handoffs).toEqual([]);
  1502. expect(bounded.truncated).toBe(true);
  1503. });
  1504. });