create-workflow-tool.test.ts 72 KB

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