workflow-driver.test.ts 52 KB

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