workflow-driver.test.ts 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. /**
  2. * 确定性集成测试(phase 1.5 步骤 7,CI 安全层):真实 AgentRuntime driver + 脚本化模型,跑通
  3. * dynamic-workflow 引擎↔真实 runtime 的 submit 桥接。见 docs/execution-engine.md「The driver (Boundary B)」「Typed asks and `submit_result`」。
  4. *
  5. * 本文件先立最小的 accept 路径,验证三值→二值裁决映射与 submit→turn-stop;其余场景(同 turn repair、
  6. * nudge、untyped、world-read)在后续 describe 里铺开。
  7. */
  8. import { describe, expect, it, vi } from "vitest";
  9. import { createTestAgentRuntime } from "./helpers/test-agent-runtime.js";
  10. import { setFlagsFromString } from "node:v8";
  11. import { runInNewContext } from "node:vm";
  12. import { mkdtemp, rm } from "node:fs/promises";
  13. import { tmpdir } from "node:os";
  14. import { join } from "node:path";
  15. import { createInMemorySessionEventStore, createSqliteSessionStore } from "@zcode/adapters/storage";
  16. import {
  17. SUBMIT_RESULT_TOOL_NAME,
  18. type ModelRequest,
  19. type SessionId,
  20. type SessionStorePort,
  21. } from "@zcode/contracts";
  22. import { AgentRuntime } from "@zcode/core";
  23. import {
  24. inputHash,
  25. InMemoryJournalStore,
  26. refToString,
  27. type ActorRef,
  28. type ActorSessionSeed,
  29. type WorkflowReportSink,
  30. } from "@zcode/dynamic-workflow";
  31. import { workflowActorToolPolicy } from "../src/app/workflow-actor-tools.js";
  32. import type { ActorTranscriptStore } from "../src/app/workflow-actor-transcript.js";
  33. import { createWorkflowEscalationRegistry } from "../src/app/workflow-escalation-registry.js";
  34. import {
  35. createAgentRuntimeWorkflowDriver,
  36. mintActorSessionId,
  37. } from "../src/app/workflow-driver.js";
  38. import {
  39. fakeFileSystemPort,
  40. runDriverScript,
  41. unsupportedExecutionPort,
  42. } from "./workflow-driver.helpers.js";
  43. const RUN = "run";
  44. describe("workflow driver — accept path", () => {
  45. it("bridges a valid submit through the real runtime and returns the artifact", async () => {
  46. const script = [
  47. "interface Summary { title: string; points: string[]; }",
  48. 'const worker = agent("worker", "You summarize repos.");',
  49. 'const s = await worker.ask<Summary>("Summarize the repo");',
  50. "log(`title: ${s.title}`);",
  51. "return s;",
  52. ].join("\n");
  53. const artifact = { title: "The Repo", points: ["a", "b"] };
  54. const { settlement, journal, events, modelCalls } = await runDriverScript(script, {
  55. caps: { maxConcurrency: 16 },
  56. actorScripts: {
  57. // actor#1@1 的持久 runtime:第一次模型请求即提交合法结果。
  58. "actor#1@1": [{ kind: "submit", result: artifact }],
  59. },
  60. });
  61. // 结算:脚本 return 的 artifact 原样冒出。
  62. expect(settlement).toEqual({ status: "completed", artifact });
  63. // journal:ask 节点 completed,带 actorSeq / inputHash / result / actor 归属。
  64. const node = journal.getNode(RUN, "ask#1", 1);
  65. expect(node?.status).toBe("completed");
  66. expect(node?.result).toEqual(artifact);
  67. expect(node?.actorSeq).toBe(0);
  68. expect(node?.inputHash).toBe(inputHash("Summarize the repo"));
  69. expect(node?.actorSiteId).toBe("actor#1");
  70. // stats 来自真实 turn 的 usage。accept 路径下 stats 晚于 settle 到达(真实 runtime 只在 turn
  71. // resolve、即 submit 之后才知道用量),引擎的 post-settle 回填把它写回已结算的 journal 节点。
  72. expect(node?.stats?.tokens ?? 0).toBeGreaterThan(0);
  73. expect(node?.stats?.turns).toBeGreaterThanOrEqual(1);
  74. // run 级用量也被累计(askStats 无条件累加 spentTokens),作为额外覆盖。
  75. const usageEvents = events.filter((e) => e.type === "usage-updated");
  76. const lastUsage = usageEvents.at(-1);
  77. expect(lastUsage?.type === "usage-updated" && lastUsage.spentTokens).toBeGreaterThan(0);
  78. // 单次模型请求即完成(无 repair、无 nudge)。
  79. expect(modelCalls["actor#1@1"]?.calls).toBe(1);
  80. // 事件流:run-started → actor-created → node-dispatched → node-settled(ok) → run-settled(completed)。
  81. const types = events.map((e) => e.type);
  82. expect(types[0]).toBe("run-started");
  83. expect(types).toContain("actor-created");
  84. expect(types).toContain("node-dispatched");
  85. const settled = events.filter((e) => e.type === "node-settled");
  86. expect(settled.at(-1)).toMatchObject({ outcome: "ok" });
  87. expect(types.at(-1)).toBe("run-settled");
  88. });
  89. });
  90. const TYPED_ASK_SCRIPT = [
  91. "interface Summary { title: string; points: string[]; }",
  92. 'const worker = agent("worker", "You summarize repos.");',
  93. 'const s = await worker.ask<Summary>("Summarize the repo");',
  94. "return s;",
  95. ].join("\n");
  96. describe("workflow driver — in-session repair (reject)", () => {
  97. it("rejects an invalid submit, retries within the same turn, then accepts", async () => {
  98. const valid = { title: "Repo", points: ["x"] };
  99. const { settlement, journal, events, modelCalls } = await runDriverScript(TYPED_ASK_SCRIPT, {
  100. actorScripts: {
  101. // 同一 turn 内:先提交非法(title 类型错、points 缺失)→ 引擎 reject → error tool_result
  102. // → 模型在会话内重试 → 提交合法 → accept。
  103. "actor#1@1": [
  104. { kind: "submit", result: { title: 42 } },
  105. { kind: "submit", result: valid },
  106. ],
  107. },
  108. });
  109. expect(settlement).toEqual({ status: "completed", artifact: valid });
  110. // repair 是真实的会话内 tool_result 重试:同一 turn 里发生了 2 次模型请求。
  111. expect(modelCalls["actor#1@1"]?.calls).toBe(2);
  112. // 引擎发过一次 node-repairing(携违规),最终 settled(ok)。
  113. const repairing = events.filter((e) => e.type === "node-repairing");
  114. expect(repairing.length).toBe(1);
  115. expect(journal.getNode(RUN, "ask#1", 1)?.status).toBe("completed");
  116. });
  117. it("fails the ask with ValidationFailed after the repair attempts are exhausted", async () => {
  118. // repair 次数上限 3:4 次非法提交耗尽后引擎 cancelAsk + settleFailed(ValidationFailed)。
  119. const invalid = { kind: "submit" as const, result: { title: 1 } };
  120. const { settlement, journal, events } = await runDriverScript(TYPED_ASK_SCRIPT, {
  121. actorScripts: { "actor#1@1": [invalid, invalid, invalid, invalid] },
  122. });
  123. // ask 拒绝跨 Boundary A 冒泡为脚本抛错 → run 失败。
  124. expect(settlement.status).toBe("errored");
  125. const node = journal.getNode(RUN, "ask#1", 1);
  126. expect(node?.status).toBe("failed");
  127. expect(node?.error?.code).toBe("ValidationFailed");
  128. // 3 次 repair 尝试后耗尽。
  129. expect(events.filter((e) => e.type === "node-repairing").length).toBe(3);
  130. });
  131. });
  132. describe("workflow driver — nudge", () => {
  133. it("nudges a turn that ended without a submit, then accepts on the fresh turn", async () => {
  134. const valid = { title: "Repo", points: ["x"] };
  135. const { settlement, events, modelCalls } = await runDriverScript(TYPED_ASK_SCRIPT, {
  136. actorScripts: {
  137. // 第一 turn 只发文本(不提交)→ 引擎 nudge → 全新 turn 提交合法 → accept。
  138. "actor#1@1": [
  139. { kind: "text", text: "Here is the summary." },
  140. { kind: "submit", result: valid },
  141. ],
  142. },
  143. });
  144. expect(settlement).toEqual({ status: "completed", artifact: valid });
  145. // nudge 是同一持久 runtime 上的一次全新 executeTurn:共 2 次模型请求。
  146. expect(modelCalls["actor#1@1"]?.calls).toBe(2);
  147. expect(events.filter((e) => e.type === "node-nudged").length).toBe(1);
  148. });
  149. it("fails with ResultNotSubmitted when nudge is exhausted", async () => {
  150. // nudge 预算 1:两次 turn 都不提交 → cancelAsk + settleFailed(ResultNotSubmitted)。
  151. const { settlement, journal, events } = await runDriverScript(TYPED_ASK_SCRIPT, {
  152. actorScripts: {
  153. "actor#1@1": [
  154. { kind: "text", text: "no submit 1" },
  155. { kind: "text", text: "no submit 2" },
  156. ],
  157. },
  158. });
  159. expect(settlement.status).toBe("errored");
  160. const node = journal.getNode(RUN, "ask#1", 1);
  161. expect(node?.status).toBe("failed");
  162. expect(node?.error?.code).toBe("ResultNotSubmitted");
  163. expect(events.filter((e) => e.type === "node-nudged").length).toBe(1);
  164. });
  165. });
  166. describe("workflow driver — untyped ask", () => {
  167. it("settles an untyped ask from the turn's final text (no submit_result)", async () => {
  168. const script = [
  169. 'const worker = agent("worker");',
  170. 'const answer = await worker.ask("What is 2 + 2?");',
  171. "return answer;",
  172. ].join("\n");
  173. const { settlement, journal } = await runDriverScript(script, {
  174. actorScripts: { "actor#1@1": [{ kind: "text", text: "The answer is 4." }] },
  175. });
  176. expect(settlement).toEqual({ status: "completed", artifact: "The answer is 4." });
  177. expect(journal.getNode(RUN, "ask#1", 1)?.result).toBe("The answer is 4.");
  178. });
  179. it("guards submit_result called on an untyped ask without hanging", async () => {
  180. // untyped ask 若被模型误调 submit_result:driver 本地拦截并回合成 rejection(不上报引擎、不悬挂),
  181. // 模型改用纯文本,untyped ask 据 final text 结算。
  182. const script = [
  183. 'const worker = agent("worker");',
  184. 'const answer = await worker.ask("Say hello.");',
  185. "return answer;",
  186. ].join("\n");
  187. const { settlement, modelCalls } = await runDriverScript(script, {
  188. actorScripts: {
  189. "actor#1@1": [
  190. { kind: "submit", result: { foo: "bar" } },
  191. { kind: "text", text: "hello there" },
  192. ],
  193. },
  194. });
  195. expect(settlement).toEqual({ status: "completed", artifact: "hello there" });
  196. // 拦截未悬挂:第一 turn 内 submit 被拒 → 模型再答文本 → 共 2 次模型请求。
  197. expect(modelCalls["actor#1@1"]?.calls).toBe(2);
  198. });
  199. });
  200. describe("workflow driver — lenient stringified submit", () => {
  201. it("accepts a submit whose result is a stringified JSON object and journals the parsed object", async () => {
  202. // 实盘发现:真实模型(GLM-5.3 经 Anthropic 兼容端点)常把 submit_result 的 result 传成 JSON
  203. // 字符串而非对象。引擎 schema-aware 地宽松解析(scheduler.normalizeSubmit),端到端应 accept
  204. // 并把解析后的对象落 journal。
  205. const artifact = { title: "The Repo", points: ["a", "b"] };
  206. const { settlement, journal, modelCalls } = await runDriverScript(TYPED_ASK_SCRIPT, {
  207. actorScripts: {
  208. // result 是 STRING(对象的 JSON 编码),而非对象本身。
  209. "actor#1@1": [{ kind: "submit", result: JSON.stringify(artifact) }],
  210. },
  211. });
  212. expect(settlement).toEqual({ status: "completed", artifact });
  213. // 单次模型请求即被 accept(无 repair)。
  214. expect(modelCalls["actor#1@1"]?.calls).toBe(1);
  215. const node = journal.getNode(RUN, "ask#1", 1);
  216. expect(node?.status).toBe("completed");
  217. // 落库的是解析后的对象,而非原始字符串。
  218. expect(node?.result).toEqual(artifact);
  219. expect(typeof node?.result).toBe("object");
  220. });
  221. });
  222. describe("workflow driver — actor tool surface", () => {
  223. // actor 的工具面此前被 runtime 工厂整个忽略——实盘 transcript 里裁判也拿到了
  224. // AskUserQuestion / CreateWorkflow。这里断言的是模型请求里**实际**带上的工具名,
  225. // 而不是配置字段,因为中间还叠着 core 的过滤与 embedded-search 分支。
  226. const PROFILE_SCRIPT = (persona: string) =>
  227. [
  228. "interface Verdict { approved: boolean; }",
  229. `const judge = ${persona};`,
  230. 'const v = await judge.ask<Verdict>("Approve it?");',
  231. "return v;",
  232. ].join("\n");
  233. /** 跑一次单 ask 的 typed 脚本并取回该 actor 第一次模型请求的工具名列表。 */
  234. async function toolNamesForPersona(persona: string): Promise<string[]> {
  235. const { settlement, modelCalls } = await runDriverScript(PROFILE_SCRIPT(persona), {
  236. actorScripts: { "actor#1@1": [{ kind: "submit", result: { approved: true } }] },
  237. });
  238. // 先确认 ask 真的跑通了:工具面若把 submit_result 滤掉,run 会失败而不是给出空列表。
  239. expect(settlement).toEqual({ status: "completed", artifact: { approved: true } });
  240. const names = modelCalls["actor#1@1"]?.toolNames[0];
  241. expect(names).toBeDefined();
  242. return names ?? [];
  243. }
  244. it("keeps the full working set for every actor, minus plan-mode and meta tools", async () => {
  245. const names = await toolNamesForPersona('agent("worker", "You do work.")');
  246. // 每个 actor 都照常干活(2026-09-12 起没有工具档位,docs/dynamic-workflow/authoring.md)。
  247. // AskUserQuestion 经父会话送达用户(docs/dynamic-workflow/launch.md「Permissions inside a run」)。
  248. for (const expected of ["Bash", "Edit", "Write", "AskUserQuestion", SUBMIT_RESULT_TOOL_NAME]) {
  249. expect(names).toContain(expected);
  250. }
  251. // plan 审批不属于子代理,CreateWorkflow 会递归提交工作流,ReadSessionContext 越界读父会话——
  252. // 全部减掉。
  253. for (const forbidden of [
  254. "EnterPlanMode",
  255. "ExitPlanMode",
  256. "CreateWorkflow",
  257. "ReadSessionContext",
  258. ]) {
  259. expect(names).not.toContain(forbidden);
  260. }
  261. });
  262. });
  263. describe("workflow driver — resume by replay", () => {
  264. it("short-circuits journaled nodes on resume with zero actor dispatches", async () => {
  265. const script = [
  266. "interface Verdict { approved: boolean; }",
  267. 'const paths = await files.glob("src/**/*.ts");',
  268. 'const v = await agent("reviewer").ask<Verdict>(`Review ${paths.length} files`);',
  269. "return { count: paths.length, approved: v.approved };",
  270. ].join("\n");
  271. const journal = new InMemoryJournalStore();
  272. const files = { glob: ["src/a.ts", "src/b.ts"] };
  273. const artifact = { count: 2, approved: true };
  274. // 首次运行:live 派发一次 ask,落 journal。
  275. const first = await runDriverScript(script, {
  276. journal,
  277. files,
  278. actorScripts: { "actor#1@1": [{ kind: "submit", result: { approved: true } }] },
  279. });
  280. expect(first.settlement).toEqual({ status: "completed", artifact });
  281. expect(first.modelCalls["actor#1@1"]?.calls).toBe(1);
  282. // 复用同一 journal 重跑同一脚本:所有节点命中 journal 短路,driver 不创建任何 actor 会话
  283. // (runtimeFactory 从不被调用 → modelCalls 为空),也不 startAsk。
  284. const resumed = await runDriverScript(script, {
  285. journal,
  286. files,
  287. // 若 resume 误触发 live 派发,脚本会因缺应答而挂起/失败——空脚本即断言「零派发」。
  288. actorScripts: {},
  289. });
  290. expect(resumed.settlement).toEqual({ status: "completed", artifact });
  291. expect(Object.keys(resumed.modelCalls)).toHaveLength(0);
  292. // Boundary C:resume 的 ask 结算事件带 cached 标志。
  293. const cachedSettles = resumed.events.filter(
  294. (e) => e.type === "node-settled" && e.cached === true,
  295. );
  296. expect(cachedSettles.length).toBeGreaterThan(0);
  297. });
  298. });
  299. describe("workflow driver — world reads", () => {
  300. it("executes glob/read via the fs port and threads results into a typed ask", async () => {
  301. const script = [
  302. "interface Verdict { approved: boolean; }",
  303. 'const paths = await files.glob("src/**/*.ts");',
  304. 'const first = paths[0] ?? "none";',
  305. "const text = await files.read(first);",
  306. 'const v = await agent("reviewer").ask<Verdict>(`Review ${first} (${text.length} bytes)`);',
  307. "return { count: paths.length, first, approved: v.approved };",
  308. ].join("\n");
  309. const { settlement, journal } = await runDriverScript(script, {
  310. files: { glob: ["src/a.ts", "src/b.ts"], read: "export const x = 1;\n" },
  311. actorScripts: { "actor#1@1": [{ kind: "submit", result: { approved: true } }] },
  312. });
  313. expect(settlement).toEqual({
  314. status: "completed",
  315. artifact: { count: 2, first: "src/a.ts", approved: true },
  316. });
  317. // world-read 落 journal,带结果。
  318. const glob = journal.getNode(RUN, "world-read#1", 1);
  319. expect(glob?.kind).toBe("world-read");
  320. expect(glob?.result).toEqual(["src/a.ts", "src/b.ts"]);
  321. const read = journal.getNode(RUN, "world-read#2", 1);
  322. expect(read?.result).toBe("export const x = 1;\n");
  323. });
  324. });
  325. describe("workflow driver — actor session ids", () => {
  326. /**
  327. * 会话 id 的两条性质(spec 的 Invariants:无碰撞、字符集安全无 `#`/`@`/`/`)。
  328. *
  329. * sanitize 是两步且顺序即契约:先把字面 `_` 转义成 `__`,再把 `[A-Za-z0-9.-]` 之外的字符
  330. * 映射成单个 `_`。没有转义那一步,`a_b` 与 `a#b` 会折叠成同一个串——这不是假想:它把
  331. * 「不碰撞」建立在「站点 id 词汇表里没有下划线」这个由分析器(而非本文件)拥有的前提上。
  332. */
  333. async function sessionIdsFor(runId: string): Promise<string[]> {
  334. const ids: string[] = [];
  335. await runDriverScript(['const a = await agent("w").ask("go");', "return a;"].join("\n"), {
  336. actorScripts: {},
  337. runId,
  338. runtimeFactory: ({ sessionId }) => {
  339. ids.push(sessionId);
  340. // 最小 stub:driver 只需要一个能 executeTurn 的对象;本用例只看会话 id。
  341. return {
  342. executeTurn: async () => ({ response: "ok", events: [], usage: undefined }),
  343. } as never;
  344. },
  345. });
  346. return ids;
  347. }
  348. it("会话 id 含 runId 且不含 # @ /", async () => {
  349. const ids = await sessionIdsFor("dwfrun-plain");
  350. expect(ids).toHaveLength(1);
  351. expect(ids[0]).toContain("dwfrun-plain");
  352. // refToString(actor) 是 `actor#1@1`——两个字符都必须已被折叠。
  353. expect(ids[0]).not.toMatch(/[#@/]/);
  354. });
  355. it("下划线转义使 sanitize 可逆到不碰撞:a_b 与 a#b 不折叠成同一个 id", async () => {
  356. const [underscore] = await sessionIdsFor("a_b");
  357. const [hash] = await sessionIdsFor("a#b");
  358. expect(underscore).toBeDefined();
  359. expect(hash).toBeDefined();
  360. // 朴素白名单方案下这两个会相等;转义先行使它们保持可区分。
  361. expect(underscore).not.toBe(hash);
  362. expect(underscore).toContain("a__b");
  363. expect(hash).toContain("a_b");
  364. });
  365. // 对抗性对子:站点 id 词汇表里的特殊字符(`#`/`@`)与字面下划线的每一种同形风险。
  366. // 朴素白名单(`_` 既在白名单里又当替换字符)会把每一对都折叠成同一个串——
  367. // 这三对就是那个方案的反例,也是转义先行这一步存在的全部理由。
  368. it("对抗性对子逐对不碰撞(actor#1 vs actor_1 等)", async () => {
  369. const pairs: readonly [string, string][] = [
  370. ["actor#1", "actor_1"],
  371. ["actor#1@2", "actor_1@2"],
  372. ["ask#3/2", "ask_3_2"],
  373. ];
  374. for (const [left, right] of pairs) {
  375. const [leftId] = await sessionIdsFor(left);
  376. const [rightId] = await sessionIdsFor(right);
  377. expect(leftId, `${left} vs ${right}`).not.toBe(rightId);
  378. // 且两者都字符集安全(会话 id 会进 URL / 文件路径 / 日志)。
  379. expect(leftId).not.toMatch(/[#@/]/);
  380. expect(rightId).not.toMatch(/[#@/]/);
  381. }
  382. });
  383. });
  384. describe("workflow driver — resume 会话身份互证", () => {
  385. const NOOP_SINK: WorkflowReportSink = {
  386. askSubmitAttempted: () => {},
  387. askTurnEnded: () => {},
  388. askProgress: () => {},
  389. askStats: () => {},
  390. askFailed: () => {},
  391. askWaiting: () => {},
  392. askExecuting: () => {},
  393. askMutating: () => {},
  394. concurrencyChanged: () => {},
  395. stopRun: () => {},
  396. runStalled: () => {},
  397. };
  398. function driverWith(journal: InMemoryJournalStore, onFactory?: () => void) {
  399. const makeDriver = createAgentRuntimeWorkflowDriver({
  400. journal,
  401. emit: () => {},
  402. escalationRegistry: createWorkflowEscalationRegistry(),
  403. fileSystemPort: fakeFileSystemPort({}),
  404. cwd: process.cwd(),
  405. runId: RUN,
  406. runtimeFactory: () => {
  407. onFactory?.();
  408. // 最小 stub:互证通过后 driver 只需要一个可持有的 runtime 对象。
  409. return {
  410. executeTurn: async () => ({ response: "ok", events: [], usage: undefined }),
  411. } as never;
  412. },
  413. });
  414. return makeDriver(NOOP_SINK);
  415. }
  416. it("journal 记录的 sessionId 与铸造结果不一致时大声失败,且不构造 runtime", async () => {
  417. // journal 的会话 id 是记录、铸造函数才是权威(spec 的 Invariants)。两者不一致意味着
  418. // 铸造规则漂移(改名/第二处实现),后果是重水化读错会话、详情页打开不存在的会话——
  419. // 离成因很远,所以必须在重挂的第一步大声失败,携结构化 mismatch(与哈希不匹配同形)。
  420. const journal = new InMemoryJournalStore();
  421. journal.createRun({
  422. runId: RUN,
  423. caps: { maxConcurrency: 16 },
  424. spentTokens: 0,
  425. status: "running",
  426. });
  427. journal.putActor({
  428. runId: RUN,
  429. siteId: "actor#1",
  430. ordinal: 1,
  431. sessionId: "sess_drifted-scheme",
  432. });
  433. let factoryCalls = 0;
  434. const driver = driverWith(journal, () => factoryCalls++);
  435. await expect(
  436. driver.createActorSession({ siteId: "actor#1", ordinal: 1 }, {}),
  437. ).rejects.toMatchObject({
  438. code: "DriverError",
  439. mismatch: {
  440. expected: "sess_drifted-scheme",
  441. got: mintActorSessionId(RUN, { siteId: "actor#1", ordinal: 1 }),
  442. },
  443. });
  444. expect(factoryCalls).toBe(0);
  445. });
  446. it("journal 记录与铸造结果一致时正常重挂(同一个会话 id)", async () => {
  447. const minted = mintActorSessionId(RUN, { siteId: "actor#1", ordinal: 1 });
  448. const journal = new InMemoryJournalStore();
  449. journal.createRun({
  450. runId: RUN,
  451. caps: { maxConcurrency: 16 },
  452. spentTokens: 0,
  453. status: "running",
  454. });
  455. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1, sessionId: minted });
  456. let factoryCalls = 0;
  457. const driver = driverWith(journal, () => factoryCalls++);
  458. await expect(driver.createActorSession({ siteId: "actor#1", ordinal: 1 }, {})).resolves.toEqual(
  459. {
  460. id: minted,
  461. },
  462. );
  463. expect(factoryCalls).toBe(1);
  464. });
  465. it("journal 无记录(全新 actor)时不做互证,正常建会话", async () => {
  466. const journal = new InMemoryJournalStore();
  467. journal.createRun({
  468. runId: RUN,
  469. caps: { maxConcurrency: 16 },
  470. spentTokens: 0,
  471. status: "running",
  472. });
  473. const driver = driverWith(journal);
  474. await expect(driver.createActorSession({ siteId: "actor#1", ordinal: 1 }, {})).resolves.toEqual(
  475. {
  476. id: mintActorSessionId(RUN, { siteId: "actor#1", ordinal: 1 }),
  477. },
  478. );
  479. });
  480. });
  481. // ————————————————————————————————————————————————————————————————
  482. // amend-resume 的 driver 半身:ask 边界记账 + 转录截断
  483. // 见 apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Amend-resume」「转录截断(driver)」两行。
  484. //
  485. // 这两族**必须走真库**:被测的正是「数的与抄的是不是同一批消息」,而消息只有接上真实
  486. // session store 才会真的落库。用一个只会返回固定数字的替身,等于把被测语义换成复制品。
  487. // ————————————————————————————————————————————————————————————————
  488. /** 一次性 sqlite session store(真实持久层),用完即删。 */
  489. async function withSessionStore(run: (store: SessionStorePort) => Promise<void>): Promise<void> {
  490. const root = await mkdtemp(join(tmpdir(), "zcode-dwf-transcript-"));
  491. const store = createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  492. try {
  493. await run(store as unknown as SessionStorePort);
  494. } finally {
  495. (store as unknown as { close(): void }).close();
  496. await rm(root, { force: true, recursive: true });
  497. }
  498. }
  499. /** 轮询等一个条件成立(fire-and-forget 的 startAsk 没有可 await 的句柄)。 */
  500. async function waitFor(predicate: () => boolean, timeoutMs = 10_000): Promise<void> {
  501. const deadline = Date.now() + timeoutMs;
  502. while (!predicate()) {
  503. if (Date.now() > deadline) throw new Error("waitFor 超时");
  504. await new Promise((resolve) => setTimeout(resolve, 10));
  505. }
  506. }
  507. const TWO_ASK_SCRIPT = [
  508. "interface A { text: string }",
  509. 'const w = agent("worker", "You work.");',
  510. 'const a = await w.ask<A>("first question");',
  511. 'const b = await w.ask<A>("second question");',
  512. "return `${a.text}/${b.text}`;",
  513. ].join("\n");
  514. const ACTOR_ONE: ActorRef = { siteId: "actor#1", ordinal: 1 };
  515. describe("workflow driver — ask 边界记账", () => {
  516. it("每个 ask 结算后写下该 actor 会话的消息数,第二个 ask 的边界更大", async () => {
  517. await withSessionStore(async (store) => {
  518. const runId = "dwfrun-boundary";
  519. const { settlement, journal } = await runDriverScript(TWO_ASK_SCRIPT, {
  520. runId,
  521. sessionStore: store,
  522. actorScripts: {
  523. "actor#1@1": [
  524. { kind: "submit", result: { text: "one" } },
  525. { kind: "submit", result: { text: "two" } },
  526. ],
  527. },
  528. });
  529. expect(settlement).toEqual({ status: "completed", artifact: "one/two" });
  530. const first = journal.getNode(runId, "ask#1", 1);
  531. const second = journal.getNode(runId, "ask#2", 1);
  532. // 边界是**同一个存取面**数出来的长度:driver 计数、种子复制与 core 的重水化都读
  533. // `sessionStore.messages`,三者口径必须一致,否则同一个 N 在两个读者眼里长度不同。
  534. const persisted = await store.messages({
  535. sessionID: mintActorSessionId(runId, ACTOR_ONE),
  536. });
  537. expect(second?.messageBoundary).toBe(persisted.length);
  538. expect(first?.messageBoundary).toBeGreaterThan(0);
  539. expect(second?.messageBoundary).toBeGreaterThan(first?.messageBoundary ?? 0);
  540. // 读改写(与 stats 回填同族):引擎写下的字段一个不许掉。
  541. expect(first).toMatchObject({
  542. status: "completed",
  543. actorSeq: 0,
  544. inputHash: inputHash("first question"),
  545. result: { text: "one" },
  546. });
  547. expect(first?.stats?.tokens).toBeGreaterThan(0);
  548. expect(second?.actorSeq).toBe(1);
  549. expect(second?.stats?.tokens).toBeGreaterThan(0);
  550. });
  551. }, 30_000);
  552. it("多 actor 各数各的会话(边界不串台)", async () => {
  553. await withSessionStore(async (store) => {
  554. const runId = "dwfrun-boundary-multi";
  555. const script = [
  556. "interface A { text: string }",
  557. 'const a = agent("a", "You are A.");',
  558. 'const b = agent("b", "You are B.");',
  559. 'const one = await a.ask<A>("a-first");',
  560. 'const other = await b.ask<A>("b-only");',
  561. 'const two = await a.ask<A>("a-second");',
  562. "return `${one.text}${other.text}${two.text}`;",
  563. ].join("\n");
  564. const answer: { kind: "submit"; result: { text: string } } = {
  565. kind: "submit",
  566. result: { text: "x" },
  567. };
  568. const { settlement, journal } = await runDriverScript(script, {
  569. runId,
  570. sessionStore: store,
  571. actorScripts: { "actor#1@1": [answer, answer], "actor#2@1": [answer] },
  572. });
  573. expect(settlement.status).toBe("completed");
  574. const aFirst = journal.getNode(runId, "ask#1", 1)?.messageBoundary;
  575. const bOnly = journal.getNode(runId, "ask#2", 1)?.messageBoundary;
  576. const aSecond = journal.getNode(runId, "ask#3", 1)?.messageBoundary;
  577. // b 只问过一次,所以它的边界必须停在自己那一轮上——而不是跟着 a 一起长。
  578. expect(bOnly).toBe(aFirst);
  579. expect(aSecond).toBe((aFirst ?? 0) * 2);
  580. const bPersisted = await store.messages({
  581. sessionID: mintActorSessionId(runId, { siteId: "actor#2", ordinal: 1 }),
  582. });
  583. expect(bOnly).toBe(bPersisted.length);
  584. });
  585. }, 30_000);
  586. it("无转录存取面时不写边界(既有装配原样不变)", async () => {
  587. const runId = "dwfrun-no-store";
  588. const { journal } = await runDriverScript(TWO_ASK_SCRIPT, {
  589. runId,
  590. actorScripts: {
  591. "actor#1@1": [
  592. { kind: "submit", result: { text: "one" } },
  593. { kind: "submit", result: { text: "two" } },
  594. ],
  595. },
  596. });
  597. // 缺席即缺席:不写 0,也不写猜的值。代价是这个 run 不能作修订前驱(service 侧的门会挡)。
  598. expect(journal.getNode(runId, "ask#1", 1)?.messageBoundary).toBeUndefined();
  599. expect(journal.getNode(runId, "ask#2", 1)?.status).toBe("completed");
  600. }, 30_000);
  601. });
  602. describe("workflow driver — 转录截断(会话种子)", () => {
  603. const NOOP_SINK: WorkflowReportSink = {
  604. askSubmitAttempted: () => {},
  605. askTurnEnded: () => {},
  606. askProgress: () => {},
  607. askStats: () => {},
  608. askFailed: () => {},
  609. askWaiting: () => {},
  610. askExecuting: () => {},
  611. askMutating: () => {},
  612. concurrencyChanged: () => {},
  613. stopRun: () => {},
  614. runStalled: () => {},
  615. };
  616. /** 跑一次源 run,留下一个真实转录 + 它的边界记账。 */
  617. async function recordSourceRun(
  618. store: SessionStorePort,
  619. runId: string,
  620. ): Promise<{ boundaries: number[]; sessionId: SessionId }> {
  621. const { settlement, journal } = await runDriverScript(TWO_ASK_SCRIPT, {
  622. runId,
  623. sessionStore: store,
  624. actorScripts: {
  625. "actor#1@1": [
  626. { kind: "submit", result: { text: "one" } },
  627. { kind: "submit", result: { text: "two" } },
  628. ],
  629. },
  630. });
  631. expect(settlement.status).toBe("completed");
  632. return {
  633. boundaries: [
  634. journal.getNode(runId, "ask#1", 1)?.messageBoundary ?? 0,
  635. journal.getNode(runId, "ask#2", 1)?.messageBoundary ?? 0,
  636. ],
  637. sessionId: mintActorSessionId(runId, ACTOR_ONE),
  638. };
  639. }
  640. /** 数写入次数的转录面(幂等用例的观察点:跳过复制 = 一次写都没发生)。 */
  641. function countingTranscriptStore(store: SessionStorePort): {
  642. store: ActorTranscriptStore;
  643. writes: { messages: number; parts: number };
  644. } {
  645. const writes = { messages: 0, parts: 0 };
  646. return {
  647. writes,
  648. store: {
  649. messages: (input) => store.messages(input),
  650. saveMessage: async (message) => {
  651. writes.messages++;
  652. await store.saveMessage(message);
  653. },
  654. savePart: async (part) => {
  655. writes.parts++;
  656. await store.savePart(part);
  657. },
  658. },
  659. };
  660. }
  661. /** 修订 run 的 driver:真 runtime(接真库)+ 记下工厂收到的种子与模型请求。 */
  662. function amendDriver(input: {
  663. journal: InMemoryJournalStore;
  664. runId: string;
  665. store: SessionStorePort;
  666. transcriptStore?: ActorTranscriptStore;
  667. }) {
  668. const seeds: (ActorSessionSeed | undefined)[] = [];
  669. const requests: ModelRequest[] = [];
  670. const fileSystemPort = fakeFileSystemPort({});
  671. const driver = createAgentRuntimeWorkflowDriver({
  672. journal: input.journal,
  673. emit: () => {},
  674. escalationRegistry: createWorkflowEscalationRegistry(),
  675. executionPort: unsupportedExecutionPort(),
  676. fileSystemPort,
  677. cwd: process.cwd(),
  678. runId: input.runId,
  679. actorTranscriptStore: input.transcriptStore ?? input.store,
  680. runtimeFactory: async ({ actor, persona, seed, sessionId, submitPort }) => {
  681. seeds.push(seed);
  682. const runtime = createTestAgentRuntime(
  683. sessionId,
  684. {
  685. systemPrompt: persona.system ?? "You are a workflow actor.",
  686. mode: "yolo",
  687. taskType: "workflow_child",
  688. subagents: { enabled: false },
  689. ...workflowActorToolPolicy(persona),
  690. },
  691. {
  692. eventStore: createInMemorySessionEventStore(),
  693. modelAdapter: {
  694. async generateText(request: ModelRequest) {
  695. requests.push(request);
  696. return {
  697. finishReason: "stop",
  698. model: "scripted",
  699. providerMetadata: undefined,
  700. text: "ok",
  701. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  702. };
  703. },
  704. } as never,
  705. workflowSubmitPort: submitPort,
  706. fileSystemPort,
  707. sessionStore: input.store,
  708. },
  709. );
  710. // 照生产(persistActorSession):会话行先落库,复制才有 FK 可依。
  711. await runtime.ensureSessionPersistedForExternalActivity(
  712. `workflow actor ${refToString(actor)}`,
  713. );
  714. return runtime;
  715. },
  716. })(NOOP_SINK);
  717. return { driver, requests, seeds };
  718. }
  719. function journalFor(runId: string): InMemoryJournalStore {
  720. const journal = new InMemoryJournalStore();
  721. journal.createRun({
  722. runId,
  723. caps: { maxConcurrency: 16 },
  724. spentTokens: 0,
  725. status: "running",
  726. });
  727. return journal;
  728. }
  729. it("按边界复制源会话前缀进新铸会话,且前驱转录一字不动", async () => {
  730. await withSessionStore(async (store) => {
  731. const source = await recordSourceRun(store, "dwfrun-src");
  732. const sourceMessages = await store.messages({ sessionID: source.sessionId });
  733. const amendRunId = "dwfrun-amend";
  734. const { driver, seeds } = amendDriver({
  735. journal: journalFor(amendRunId),
  736. runId: amendRunId,
  737. store,
  738. });
  739. // 第一条 ask 命中缓存、第二条分歧:种子 = 第一条 ask 的边界。
  740. const ref = await driver.createActorSession(
  741. ACTOR_ONE,
  742. { name: "worker" },
  743. {
  744. sourceSessionId: source.sessionId,
  745. messageCount: source.boundaries[0]!,
  746. resolvedModel: "anthropic/some-model",
  747. },
  748. );
  749. // 新会话 id 照常铸(mint 规则不变),不是源会话。
  750. expect(ref.id).toBe(mintActorSessionId(amendRunId, ACTOR_ONE));
  751. expect(ref.id).not.toBe(source.sessionId);
  752. const copied = await store.messages({ sessionID: ref.id as SessionId });
  753. expect(copied).toHaveLength(source.boundaries[0]!);
  754. expect(copied.map((m) => m.info.role)).toEqual(
  755. sourceMessages.slice(0, source.boundaries[0]!).map((m) => m.info.role),
  756. );
  757. // 每条都是**副本**:id 必须是新的,否则 upsert 会把前驱那一行搬进新会话。
  758. for (const [index, message] of copied.entries()) {
  759. expect(message.info.id).not.toBe(sourceMessages[index]!.info.id);
  760. expect(message.info.sessionID).toBe(ref.id);
  761. for (const part of message.parts) expect(part.sessionID).toBe(ref.id);
  762. }
  763. // 前驱只读:源会话还是原来那四条,一条不多不少、id 不变。
  764. const sourceAfter = await store.messages({ sessionID: source.sessionId });
  765. expect(sourceAfter.map((m) => m.info.id)).toEqual(sourceMessages.map((m) => m.info.id));
  766. // 种子原样交到 runtime 工厂手上——pin 承袭(launch 侧据它算 pinnedModel)的接缝。
  767. expect(seeds).toEqual([
  768. {
  769. sourceSessionId: source.sessionId,
  770. messageCount: source.boundaries[0]!,
  771. resolvedModel: "anthropic/some-model",
  772. },
  773. ]);
  774. });
  775. }, 40_000);
  776. it("复制来的转录进入 runtime 上下文:分歧后的第一次模型请求带着它", async () => {
  777. await withSessionStore(async (store) => {
  778. const source = await recordSourceRun(store, "dwfrun-src2");
  779. const amendRunId = "dwfrun-amend2";
  780. const { driver, requests } = amendDriver({
  781. journal: journalFor(amendRunId),
  782. runId: amendRunId,
  783. store,
  784. });
  785. const ref = await driver.createActorSession(
  786. ACTOR_ONE,
  787. { name: "worker" },
  788. {
  789. sourceSessionId: source.sessionId,
  790. messageCount: source.boundaries[0]!,
  791. },
  792. );
  793. // startAsk 是 fire-and-forget(Boundary B 契约),所以观察面是模型请求本身。
  794. driver.startAsk(
  795. ref,
  796. { siteId: "ask#1", ordinal: 1 },
  797. {
  798. instructions: "continue from where we left off",
  799. typed: false,
  800. },
  801. );
  802. await waitFor(() => requests.length > 0);
  803. const conversation = JSON.stringify(requests[0]?.messages ?? []);
  804. // 源转录的第一句问话必须在上下文里——全保真截断的全部意义。
  805. expect(conversation).toContain("first question");
  806. expect(conversation).toContain("continue from where we left off");
  807. // 边界之后的那一轮不在(截断,不是全量复制)。
  808. expect(conversation).not.toContain("second question");
  809. });
  810. }, 40_000);
  811. it("幂等:目标会话已有内容时不再复制(崩溃后重挂同一个会话 id)", async () => {
  812. await withSessionStore(async (store) => {
  813. const source = await recordSourceRun(store, "dwfrun-src3");
  814. const amendRunId = "dwfrun-amend3";
  815. const journal = journalFor(amendRunId);
  816. const seed: ActorSessionSeed = {
  817. sourceSessionId: source.sessionId,
  818. messageCount: source.boundaries[0]!,
  819. };
  820. const first = amendDriver({ journal, runId: amendRunId, store });
  821. const ref = await first.driver.createActorSession(ACTOR_ONE, { name: "worker" }, seed);
  822. const afterFirst = await store.messages({ sessionID: ref.id as SessionId });
  823. expect(afterFirst).toHaveLength(seed.messageCount);
  824. // 重挂:会话 id 由 (runId, actorRef) 纯确定,所以第二次铸出的是同一个,且已装着上一世
  825. // 「复制来的 + 新产的」内容。再抄一遍就是把上文翻倍——所以这一次必须一个字都不写。
  826. journal.putActor({ ...ACTOR_ONE, runId: amendRunId, sessionId: ref.id });
  827. const counting = countingTranscriptStore(store);
  828. const second = amendDriver({
  829. journal,
  830. runId: amendRunId,
  831. store,
  832. transcriptStore: counting.store,
  833. });
  834. await second.driver.createActorSession(ACTOR_ONE, { name: "worker" }, seed);
  835. expect(counting.writes).toEqual({ messages: 0, parts: 0 });
  836. const afterSecond = await store.messages({ sessionID: ref.id as SessionId });
  837. expect(afterSecond.map((m) => m.info.id)).toEqual(afterFirst.map((m) => m.info.id));
  838. });
  839. }, 40_000);
  840. it("源会话不存在或短于边界 → 结构化大声失败", async () => {
  841. await withSessionStore(async (store) => {
  842. const source = await recordSourceRun(store, "dwfrun-src4");
  843. const amendRunId = "dwfrun-amend4";
  844. const missing = amendDriver({ journal: journalFor(amendRunId), runId: amendRunId, store });
  845. await expect(
  846. missing.driver.createActorSession(
  847. ACTOR_ONE,
  848. { name: "worker" },
  849. {
  850. sourceSessionId: "sess_never-existed",
  851. messageCount: 2,
  852. },
  853. ),
  854. ).rejects.toMatchObject({ code: "DriverError", mismatch: { expected: "2", got: "0" } });
  855. const short = amendDriver({
  856. journal: journalFor("dwfrun-amend4b"),
  857. runId: "dwfrun-amend4b",
  858. store,
  859. });
  860. const tooFar = source.boundaries[1]! + 1;
  861. await expect(
  862. short.driver.createActorSession(
  863. ACTOR_ONE,
  864. { name: "worker" },
  865. {
  866. sourceSessionId: source.sessionId,
  867. messageCount: tooFar,
  868. },
  869. ),
  870. ).rejects.toMatchObject({
  871. code: "DriverError",
  872. mismatch: { expected: String(tooFar), got: String(source.boundaries[1]) },
  873. });
  874. });
  875. }, 40_000);
  876. it("无种子 → 全新空会话(byte-for-byte 今天的行为)", async () => {
  877. await withSessionStore(async (store) => {
  878. await recordSourceRun(store, "dwfrun-src5");
  879. const amendRunId = "dwfrun-fresh";
  880. const { driver, seeds } = amendDriver({
  881. journal: journalFor(amendRunId),
  882. runId: amendRunId,
  883. store,
  884. });
  885. const ref = await driver.createActorSession(ACTOR_ONE, { name: "worker" });
  886. expect(seeds).toEqual([undefined]);
  887. expect(await store.messages({ sessionID: ref.id as SessionId })).toHaveLength(0);
  888. });
  889. }, 40_000);
  890. });
  891. // ── ask 质量尾注(docs/dynamic-workflow/authoring.md「Each ask」)──
  892. //
  893. // 每个 ask 的指令后面都跟一段内容标准;typed 时 schema 尾注紧随其后。两段都在 scheduler 算完
  894. // inputHash 之后追加,所以缓存身份不变——这里顺带钉住 journal 里的 inputHash 与原始指令一致。
  895. describe("workflow driver — quality epilogue on every ask", () => {
  896. const STANDARD = "Standard for this result:";
  897. it("typed ask: instructions, then the standard, then the schema epilogue", async () => {
  898. const valid = { title: "Repo", points: ["x"] };
  899. const { modelCalls } = await runDriverScript(TYPED_ASK_SCRIPT, {
  900. actorScripts: { "actor#1@1": [{ kind: "submit", result: valid }] },
  901. });
  902. const prompt = modelCalls["actor#1@1"]?.prompts[0] ?? "";
  903. const instructions = prompt.indexOf("Summarize the repo");
  904. const standard = prompt.indexOf(STANDARD);
  905. const schema = prompt.indexOf("call the `submit_result` tool to submit your final result");
  906. expect(instructions).toBeGreaterThanOrEqual(0);
  907. expect(instructions).toBeLessThan(standard);
  908. expect(standard).toBeLessThan(schema);
  909. expect(prompt).toContain("A check counts as passed only if you ran it during this ask.");
  910. // 2026-09-08 追记:default 档还要求按 ask 点名的尺度跑检查,替身不算。
  911. expect(prompt).toContain("Run the check the ask names, at the scale it names.");
  912. expect(prompt).toContain("call `escalate` instead of inventing a value");
  913. // schema 没有 evidence / confidence 字段:两行不出现。
  914. expect(prompt).not.toContain("`evidence` field");
  915. expect(prompt).not.toContain("Rate `confidence`");
  916. });
  917. it("untyped ask: instructions then the standard, no schema epilogue", async () => {
  918. const script = [
  919. 'const worker = agent("worker");',
  920. 'const answer = await worker.ask("What is 2 + 2?");',
  921. "return answer;",
  922. ].join("\n");
  923. const { modelCalls, settlement } = await runDriverScript(script, {
  924. actorScripts: { "actor#1@1": [{ kind: "text", text: "4" }] },
  925. });
  926. expect(settlement.status).toBe("completed");
  927. const prompt = modelCalls["actor#1@1"]?.prompts[0] ?? "";
  928. expect(prompt.indexOf("What is 2 + 2?")).toBeLessThan(prompt.indexOf(STANDARD));
  929. expect(prompt).not.toContain("submit_result");
  930. });
  931. it("names the evidence and confidence fields when the schema declares them", async () => {
  932. const script = [
  933. "interface Finding { where: string; evidence: string; confidence: number; }",
  934. 'const worker = agent("worker");',
  935. 'const f = await worker.ask<Finding>("Find the bug");',
  936. "return f;",
  937. ].join("\n");
  938. const { modelCalls } = await runDriverScript(script, {
  939. actorScripts: {
  940. "actor#1@1": [
  941. { kind: "submit", result: { where: "a.ts:1", evidence: "read it", confidence: 0.5 } },
  942. ],
  943. },
  944. });
  945. const prompt = modelCalls["actor#1@1"]?.prompts[0] ?? "";
  946. expect(prompt).toContain("Put each finding's citation in its `evidence` field.");
  947. expect(prompt).toContain("Rate `confidence` honestly");
  948. });
  949. it("nudge prompts carry no epilogue and the journaled inputHash ignores it", async () => {
  950. const valid = { title: "Repo", points: ["x"] };
  951. const { modelCalls, journal } = await runDriverScript(TYPED_ASK_SCRIPT, {
  952. actorScripts: {
  953. "actor#1@1": [
  954. { kind: "text", text: "no submit yet" },
  955. { kind: "submit", result: valid },
  956. ],
  957. },
  958. });
  959. const prompts = modelCalls["actor#1@1"]?.prompts ?? [];
  960. expect(prompts.length).toBe(2);
  961. expect(prompts[0]).toContain(STANDARD);
  962. expect(prompts[1]).not.toContain(STANDARD);
  963. expect(prompts[1]).toContain("You ended your turn without submitting a result.");
  964. // 缓存身份 = 原始指令的哈希,与尾注无关。
  965. expect(journal.getNode(RUN, "ask#1", 1)?.inputHash).toBe(inputHash("Summarize the repo"));
  966. });
  967. // docs/dynamic-workflow/transcript-and-notifications.md:GUI 要把尾注折起来,边界由 driver 标记——
  968. // 它是拼这段文本的人。边界随用户消息 metadata 落库(全文仍在 text part 里,模型历史与
  969. // 转录复制不变);nudge 轮整条都是引擎文本,边界为 0。
  970. it("marks where the epilogue starts on the persisted user message; nudge is all epilogue", async () => {
  971. await withSessionStore(async (store) => {
  972. const runId = "dwfrun-epilogue-fold";
  973. const valid = { title: "Repo", points: ["x"] };
  974. await runDriverScript(TYPED_ASK_SCRIPT, {
  975. runId,
  976. sessionStore: store,
  977. actorScripts: {
  978. "actor#1@1": [
  979. { kind: "text", text: "no submit yet" },
  980. { kind: "submit", result: valid },
  981. ],
  982. },
  983. });
  984. const persisted = await store.messages({ sessionID: mintActorSessionId(runId, ACTOR_ONE) });
  985. const users = persisted.filter((message) => message.info.role === "user");
  986. expect(users.length).toBe(2);
  987. const askText = users[0]?.parts.find((part) => part.type === "text");
  988. expect(askText?.type === "text" ? askText.text : "").toContain(STANDARD);
  989. expect(users[0]?.info.metadata?.epilogueStart).toBe("Summarize the repo".length);
  990. expect(users[1]?.info.metadata?.epilogueStart).toBe(0);
  991. });
  992. }, 30_000);
  993. });
  994. // ————————————————————————————————————————————————————————————————
  995. // run 结算后的 actor runtime 收口(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)
  996. // 引擎在 run-settled 之后恰好调一次 driver.dispose;driver 对每个 actor runtime 跑 app 关会话的
  997. // 同一条链(closeBrowserSession),有在飞 turn 的会话等它落地再关。
  998. // ————————————————————————————————————————————————————————————————
  999. describe("workflow driver — 结算后释放 actor runtime", () => {
  1000. const NOOP_SINK: WorkflowReportSink = {
  1001. askSubmitAttempted: () => {},
  1002. askTurnEnded: () => {},
  1003. askProgress: () => {},
  1004. askStats: () => {},
  1005. askFailed: () => {},
  1006. askWaiting: () => {},
  1007. askExecuting: () => {},
  1008. askMutating: () => {},
  1009. concurrencyChanged: () => {},
  1010. stopRun: () => {},
  1011. runStalled: () => {},
  1012. };
  1013. /** 桩 runtime:executeTurn 在 abort 时 reject(模拟被取消的在飞 turn),closeBrowserSession 可被 spy。 */
  1014. function stubRuntime(close: () => Promise<void> = async () => {}) {
  1015. const closeBrowserSession = vi.fn(close);
  1016. const executeTurn = vi.fn(
  1017. (_input: string, _b: unknown, opts?: { abortSignal?: AbortSignal }) =>
  1018. new Promise((_resolve, reject) => {
  1019. opts?.abortSignal?.addEventListener(
  1020. "abort",
  1021. () => reject(new Error("workflow ask cancelled")),
  1022. {
  1023. once: true,
  1024. },
  1025. );
  1026. }),
  1027. );
  1028. return { closeBrowserSession, executeTurn };
  1029. }
  1030. function driverWith(
  1031. runtimes: Record<string, ReturnType<typeof stubRuntime>>,
  1032. logger?: { warn: (message: string, context?: Record<string, unknown>) => void },
  1033. ) {
  1034. const journal = new InMemoryJournalStore();
  1035. journal.createRun({
  1036. runId: RUN,
  1037. caps: { maxConcurrency: 16 },
  1038. spentTokens: 0,
  1039. status: "running",
  1040. });
  1041. const makeDriver = createAgentRuntimeWorkflowDriver({
  1042. journal,
  1043. emit: () => {},
  1044. escalationRegistry: createWorkflowEscalationRegistry(),
  1045. fileSystemPort: fakeFileSystemPort({}),
  1046. cwd: process.cwd(),
  1047. runId: RUN,
  1048. ...(logger === undefined ? {} : { logger: logger as never }),
  1049. runtimeFactory: ({ actor }) => runtimes[refToString(actor)] as never,
  1050. });
  1051. return makeDriver(NOOP_SINK);
  1052. }
  1053. const A1: ActorRef = { siteId: "actor#1", ordinal: 1 };
  1054. const A2: ActorRef = { siteId: "actor#2", ordinal: 1 };
  1055. const flushMicrotasks = async () => {
  1056. for (let i = 0; i < 8; i++) await Promise.resolve();
  1057. };
  1058. it("无在飞 turn 的会话立即关;有在飞 turn 的会话等 turn 落地后才关", async () => {
  1059. const idle = stubRuntime();
  1060. const busy = stubRuntime();
  1061. const driver = driverWith({ "actor#1@1": idle, "actor#2@1": busy });
  1062. await driver.createActorSession(A1, {});
  1063. const s2 = await driver.createActorSession(A2, {});
  1064. const instance = { siteId: "ask#1", ordinal: 1 };
  1065. driver.startAsk(s2, instance, { instructions: "go", typed: false });
  1066. expect(busy.executeTurn).toHaveBeenCalledTimes(1);
  1067. // 引擎结算:先 cancelAsk(在飞 ask 中止),再 dispose——与 engine.cancel / complete 的顺序一致。
  1068. driver.cancelAsk(instance);
  1069. driver.dispose?.();
  1070. expect(idle.closeBrowserSession).not.toHaveBeenCalled(); // 经 Promise.resolve().then 排队
  1071. await flushMicrotasks();
  1072. expect(idle.closeBrowserSession).toHaveBeenCalledTimes(1);
  1073. expect(busy.closeBrowserSession).toHaveBeenCalledTimes(1);
  1074. });
  1075. it("在飞 turn 未落地前不关它的 runtime(等待是载荷性的:askStats 在 settle 之后才到)", async () => {
  1076. const busy = stubRuntime();
  1077. // 这个桩的 turn 不响应 abort:模拟一条仍在收尾的 turn。
  1078. busy.executeTurn.mockImplementation(() => new Promise(() => {}));
  1079. const driver = driverWith({ "actor#1@1": busy });
  1080. const s1 = await driver.createActorSession(A1, {});
  1081. driver.startAsk(s1, { siteId: "ask#1", ordinal: 1 }, { instructions: "go", typed: false });
  1082. driver.dispose?.();
  1083. await flushMicrotasks();
  1084. expect(busy.closeBrowserSession).not.toHaveBeenCalled();
  1085. });
  1086. it("幂等:dispose 两次,每个 runtime 只关一次", async () => {
  1087. const r = stubRuntime();
  1088. const driver = driverWith({ "actor#1@1": r });
  1089. await driver.createActorSession(A1, {});
  1090. driver.dispose?.();
  1091. driver.dispose?.();
  1092. await flushMicrotasks();
  1093. expect(r.closeBrowserSession).toHaveBeenCalledTimes(1);
  1094. });
  1095. it("关闭失败只 warn(带 sessionId),结算不因它抛", async () => {
  1096. const r = stubRuntime(async () => {
  1097. throw new Error("browser backend gone");
  1098. });
  1099. const warns: Array<{ message: string; context?: Record<string, unknown> }> = [];
  1100. const driver = driverWith(
  1101. { "actor#1@1": r },
  1102. { warn: (message, context) => warns.push({ message, context }) },
  1103. );
  1104. await driver.createActorSession(A1, {});
  1105. expect(() => driver.dispose?.()).not.toThrow();
  1106. await flushMicrotasks();
  1107. expect(warns).toHaveLength(1);
  1108. expect(warns[0]?.context).toMatchObject({
  1109. errorMessage: "browser backend gone",
  1110. event: "dynamic_workflow.actor_runtime.close_failed",
  1111. sessionId: mintActorSessionId(RUN, A1),
  1112. });
  1113. });
  1114. it("真实管线:run 结算后每个 actor runtime 关闭链恰好一次,且 runtime 可被 GC 回收", async () => {
  1115. const script = [
  1116. "interface A { text: string }",
  1117. 'const w1 = agent("w1", "You work.");',
  1118. 'const w2 = agent("w2", "You also work.");',
  1119. 'const [a, b] = await Promise.all([w1.ask<A>("first"), w2.ask<A>("second")]);',
  1120. "return `${a.text}/${b.text}`;",
  1121. ].join("\n");
  1122. // 计数器不用 vi.spyOn:spy 注册表是模块级的,会把被 spy 的实例根住,GC 断言就废了。
  1123. // 包装器只挂在实例自己身上,不从外部引用 runtime。
  1124. const closes = new Map<string, number>();
  1125. const refs = new Map<string, WeakRef<object>>();
  1126. const { settlement } = await runDriverScript(script, {
  1127. actorScripts: {
  1128. "actor#1@1": [{ kind: "submit", result: { text: "A" } }],
  1129. "actor#2@1": [{ kind: "submit", result: { text: "B" } }],
  1130. },
  1131. onRuntimeCreated: (runtime, key) => {
  1132. closes.set(key, 0);
  1133. const original = runtime.closeBrowserSession.bind(runtime);
  1134. (runtime as { closeBrowserSession: () => Promise<void> }).closeBrowserSession = () => {
  1135. closes.set(key, (closes.get(key) ?? 0) + 1);
  1136. return original();
  1137. };
  1138. refs.set(key, new WeakRef(runtime));
  1139. },
  1140. });
  1141. expect(settlement).toEqual({ status: "completed", artifact: "A/B" });
  1142. expect([...closes.keys()].sort()).toEqual(["actor#1@1", "actor#2@1"]);
  1143. // 关闭链在 turn 落地后才跑(accept 路径 stats 晚于 settle,turn 的收尾还要等持久化):轮询等它。
  1144. await waitFor(() => [...closes.values()].every((count) => count >= 1));
  1145. for (const [key, count] of closes) expect(count, key).toBe(1);
  1146. // GC 可回收性:强制 full GC 后,没有任何根再握着 actor runtime。
  1147. setFlagsFromString("--expose-gc");
  1148. const gc = runInNewContext("gc") as () => void;
  1149. for (
  1150. let round = 0;
  1151. round < 3 && [...refs.values()].some((ref) => ref.deref() !== undefined);
  1152. round++
  1153. ) {
  1154. await new Promise((resolve) => setTimeout(resolve, 0));
  1155. gc();
  1156. }
  1157. for (const [key, ref] of refs) expect(ref.deref(), `${key} 仍被某个根引用`).toBeUndefined();
  1158. });
  1159. });