workflow-driver.test.ts 54 KB

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