engine.test.ts 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. InMemoryJournalStore,
  4. WorkflowEngine,
  5. WorkflowError,
  6. inputHash,
  7. refToString,
  8. type AskSpec,
  9. type Caps,
  10. type InstanceRef,
  11. type NodeKind,
  12. type NodeRecord,
  13. type PersonaSpec,
  14. type RunEvent,
  15. type StoredEvent,
  16. type ValidateFn,
  17. } from "../../src/engine/index.js";
  18. import { FakeDriver, flush } from "./fake-driver.js";
  19. import { REPORT_CAPS } from "../../src/facade/report-caps.js";
  20. import { validate } from "../../src/schema/validate.js";
  21. import type { JsonSchema } from "../../src/schema/types.js";
  22. const RUN = "run";
  23. function inst(siteId: string, ordinal = 1): InstanceRef {
  24. return { siteId, ordinal };
  25. }
  26. /** 一个基于 schema.required 的最小校验器(模拟真实 validator 的违规输出)。 */
  27. const requireFields: ValidateFn = (schema, value) => {
  28. const required = (schema as { required?: string[] } | undefined)?.required ?? [];
  29. const obj = (value ?? {}) as Record<string, unknown>;
  30. return required
  31. .filter((k) => obj[k] === undefined)
  32. .map((k) => ({ path: k, expected: "present", got: "undefined" }));
  33. };
  34. interface SetupOpts {
  35. journal?: InMemoryJournalStore;
  36. caps?: Caps;
  37. askSpecs?: Map<string, AskSpec>;
  38. validate?: ValidateFn;
  39. deferSessions?: boolean;
  40. name?: string;
  41. scriptText?: string;
  42. scriptHash?: string;
  43. parentSessionId?: string;
  44. cwd?: string;
  45. toolCallId?: string;
  46. resumedFrom?: string;
  47. /** 模拟 driver 侧的模型档位解析(会话创建时把解析结果写进 actor 记录)。 */
  48. resolveModel?: (persona: { model?: string }) => string;
  49. }
  50. function setup(opts: SetupOpts = {}) {
  51. const journal = opts.journal ?? new InMemoryJournalStore();
  52. const driver = new FakeDriver(journal, {
  53. deferSessions: opts.deferSessions,
  54. ...(opts.resolveModel === undefined ? {} : { resolveModel: opts.resolveModel, runId: RUN }),
  55. });
  56. const engine = new WorkflowEngine({
  57. runId: RUN,
  58. driver,
  59. caps: opts.caps ?? { maxConcurrency: 16 },
  60. // askSpecs 必须覆盖脚本里的每个 ask 站点(miss 是硬错误),fixture 默认把本文件
  61. // 用到的两个站点显式记为 untyped。
  62. askSpecs: opts.askSpecs ?? untypedSpecs("ask#1", "ask#2"),
  63. validate: opts.validate ?? (() => []),
  64. ...(opts.name === undefined ? {} : { name: opts.name }),
  65. ...(opts.scriptText === undefined ? {} : { scriptText: opts.scriptText }),
  66. ...(opts.scriptHash === undefined ? {} : { scriptHash: opts.scriptHash }),
  67. ...(opts.parentSessionId === undefined ? {} : { parentSessionId: opts.parentSessionId }),
  68. ...(opts.cwd === undefined ? {} : { cwd: opts.cwd }),
  69. ...(opts.toolCallId === undefined ? {} : { toolCallId: opts.toolCallId }),
  70. ...(opts.resumedFrom === undefined ? {} : { resumedFrom: opts.resumedFrom }),
  71. });
  72. return { journal, driver, engine };
  73. }
  74. /** 把若干 ask 站点显式记为 untyped(引擎不再把缺席当 untyped)。 */
  75. const untypedSpecs = (...siteIds: string[]): Map<string, AskSpec> =>
  76. new Map(siteIds.map((id) => [id, { typed: false } as AskSpec]));
  77. const typedSpecs = () =>
  78. new Map<string, AskSpec>([["ask#1", { typed: true, schema: { required: ["x"] } }]]);
  79. describe("WorkflowEngine — happy path", () => {
  80. it("dispatches, accepts a valid submit, and journals the node", async () => {
  81. const { engine, driver, journal } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  82. const actor = engine.createActor("actor#1", "planner");
  83. const p = engine.ask("ask#1", actor, "do it");
  84. await flush();
  85. expect(driver.startAskCount()).toBe(1);
  86. expect(driver.startAsks[0]?.message.typed).toBe(true);
  87. expect(driver.startAsks[0]?.message.schema).toEqual({ required: ["x"] });
  88. engine.askStats(inst("ask#1"), { tokens: 10, toolCalls: 1, turns: 1 });
  89. engine.askSubmitAttempted(inst("ask#1"), { x: 1 });
  90. expect(driver.submitResponses.at(-1)?.verdict.kind).toBe("accept");
  91. await expect(p).resolves.toEqual({ x: 1 });
  92. const node = journal.getNode(RUN, "ask#1", 1);
  93. expect(node?.status).toBe("completed");
  94. expect(node?.actorSeq).toBe(0);
  95. expect(node?.inputHash).toBe(inputHash("do it"));
  96. expect(node?.result).toEqual({ x: 1 });
  97. expect(node?.stats).toEqual({ tokens: 10, toolCalls: 1, turns: 1 });
  98. expect(node?.actorSiteId).toBe("actor#1");
  99. engine.complete("final artifact");
  100. await expect(engine.settled).resolves.toEqual({
  101. status: "completed",
  102. artifact: "final artifact",
  103. });
  104. expect(engine.status()).toBe("completed");
  105. });
  106. });
  107. describe("WorkflowEngine — validation + repair", () => {
  108. it("rejects invalid submits and fails after the 3 repair attempts are exhausted", async () => {
  109. const { engine, driver, journal } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  110. const actor = engine.createActor("actor#1");
  111. const p = engine.ask("ask#1", actor, "do it");
  112. await flush();
  113. // 4 次无效提交:前 3 次拒绝(repair),第 4 次预算耗尽 → 失败。
  114. for (let i = 0; i < 4; i++) engine.askSubmitAttempted(inst("ask#1"), {});
  115. const rejects = driver.submitResponses.filter((r) => r.verdict.kind === "reject");
  116. expect(rejects).toHaveLength(3);
  117. expect(driver.cancels).toContainEqual(inst("ask#1"));
  118. await expect(p).rejects.toMatchObject({ code: "ValidationFailed" });
  119. const err = await p.catch((e: unknown) => e as { violations?: unknown[] });
  120. expect(err.violations?.length).toBeGreaterThan(0);
  121. const node = journal.getNode(RUN, "ask#1", 1);
  122. expect(node?.status).toBe("failed");
  123. expect(node?.error?.code).toBe("ValidationFailed");
  124. });
  125. it("repairs successfully within the attempt limit", async () => {
  126. const { engine, driver } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  127. const actor = engine.createActor("actor#1");
  128. const p = engine.ask("ask#1", actor, "do it");
  129. await flush();
  130. engine.askSubmitAttempted(inst("ask#1"), {}); // reject
  131. engine.askSubmitAttempted(inst("ask#1"), { x: 7 }); // accept
  132. await expect(p).resolves.toEqual({ x: 7 });
  133. expect(driver.submitResponses.map((r) => r.verdict.kind)).toEqual(["reject", "accept"]);
  134. });
  135. });
  136. describe("WorkflowEngine — nudge policy", () => {
  137. it("nudges once when the turn ends without a submit, then accepts", async () => {
  138. const { engine, driver } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  139. const actor = engine.createActor("actor#1");
  140. const p = engine.ask("ask#1", actor, "do it");
  141. await flush();
  142. engine.askTurnEnded(inst("ask#1"), "not yet");
  143. expect(driver.submitResponses.at(-1)?.verdict.kind).toBe("nudge");
  144. engine.askSubmitAttempted(inst("ask#1"), { x: 1 });
  145. await expect(p).resolves.toEqual({ x: 1 });
  146. });
  147. it("fails with ResultNotSubmitted + final text when nudge is exhausted", async () => {
  148. const { engine, driver } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  149. const actor = engine.createActor("actor#1");
  150. const p = engine.ask("ask#1", actor, "do it");
  151. await flush();
  152. engine.askTurnEnded(inst("ask#1"), "text one"); // nudge
  153. engine.askTurnEnded(inst("ask#1"), "final words"); // exhausted → fail
  154. await expect(p).rejects.toMatchObject({ code: "ResultNotSubmitted", finalText: "final words" });
  155. expect(driver.cancels).toContainEqual(inst("ask#1"));
  156. });
  157. });
  158. describe("WorkflowEngine — untyped ask", () => {
  159. it("settles on turn end with the final text and offers no submit tool", async () => {
  160. const { engine, driver, journal } = setup(); // 站点显式记为 untyped
  161. const actor = engine.createActor("actor#1");
  162. const p = engine.ask("ask#1", actor, "summarize");
  163. await flush();
  164. expect(driver.startAsks[0]?.message.typed).toBe(false);
  165. engine.askTurnEnded(inst("ask#1"), "the answer");
  166. await expect(p).resolves.toBe("the answer");
  167. expect(journal.getNode(RUN, "ask#1", 1)?.result).toBe("the answer");
  168. });
  169. });
  170. describe("WorkflowEngine — per-actor FIFO", () => {
  171. it("serializes concurrent asks on one actor and journals actorSeq in admission order", async () => {
  172. const { engine, driver, journal } = setup();
  173. const actor = engine.createActor("actor#1");
  174. const p1 = engine.ask("ask#1", actor, "A");
  175. const p2 = engine.ask("ask#2", actor, "B");
  176. await flush();
  177. // 只有队首派发,第二个 ask 等待第一个结算。
  178. expect(driver.startAskCount()).toBe(1);
  179. expect(driver.startAsks[0]?.instance).toEqual(inst("ask#1"));
  180. engine.askTurnEnded(inst("ask#1"), "ra");
  181. await flush();
  182. expect(driver.startAskCount()).toBe(2);
  183. expect(driver.startAsks[1]?.instance).toEqual(inst("ask#2"));
  184. engine.askTurnEnded(inst("ask#2"), "rb");
  185. await expect(Promise.all([p1, p2])).resolves.toEqual(["ra", "rb"]);
  186. expect(journal.getNode(RUN, "ask#1", 1)?.actorSeq).toBe(0);
  187. expect(journal.getNode(RUN, "ask#2", 1)?.actorSeq).toBe(1);
  188. });
  189. });
  190. describe("WorkflowEngine — replay", () => {
  191. it("short-circuits journaled nodes with zero startAsk calls", async () => {
  192. const journal = new InMemoryJournalStore();
  193. journal.createRun({
  194. runId: RUN,
  195. caps: { maxConcurrency: 16 },
  196. spentTokens: 0,
  197. status: "running",
  198. });
  199. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  200. journal.putNode({
  201. runId: RUN,
  202. siteId: "ask#1",
  203. ordinal: 1,
  204. kind: "ask",
  205. actorSiteId: "actor#1",
  206. actorOrdinal: 1,
  207. actorSeq: 0,
  208. inputHash: inputHash("do it"),
  209. status: "completed",
  210. result: { x: 42 },
  211. });
  212. const { engine, driver } = setup({ journal });
  213. const actor = engine.createActor("actor#1");
  214. const p = engine.ask("ask#1", actor, "do it");
  215. await flush();
  216. expect(driver.startAskCount()).toBe(0);
  217. await expect(p).resolves.toEqual({ x: 42 });
  218. });
  219. it("fails the run loudly on an inputHash mismatch", async () => {
  220. const journal = new InMemoryJournalStore();
  221. journal.createRun({
  222. runId: RUN,
  223. caps: { maxConcurrency: 16 },
  224. spentTokens: 0,
  225. status: "running",
  226. });
  227. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  228. journal.putNode({
  229. runId: RUN,
  230. siteId: "ask#1",
  231. ordinal: 1,
  232. kind: "ask",
  233. actorSiteId: "actor#1",
  234. actorOrdinal: 1,
  235. actorSeq: 0,
  236. inputHash: "deadbeef", // 与重放时计算出的 hash 不符
  237. status: "completed",
  238. result: { x: 1 },
  239. });
  240. const { engine } = setup({ journal });
  241. const actor = engine.createActor("actor#1");
  242. const p = engine.ask("ask#1", actor, "do it");
  243. await expect(p).rejects.toMatchObject({ code: "InputHashMismatch" });
  244. await expect(engine.settled).resolves.toMatchObject({
  245. status: "errored",
  246. error: { code: "InputHashMismatch" },
  247. });
  248. // 两个哈希结构化随错误走(与 ScriptHashMismatch 同一个 mismatch 字段):一个只在
  249. // 两种哈希不匹配错误之一上出现的结构化字段,对读端就是个陷阱。
  250. const err = await p.catch((e: unknown) => e as WorkflowError);
  251. expect(err.mismatch).toEqual({ expected: "deadbeef", got: inputHash("do it") });
  252. // 落 journal 的可序列化形态同样带着它(failure_json 是 app 侧读的持久记录)。
  253. expect(err.toJSON()).toMatchObject({
  254. code: "InputHashMismatch",
  255. mismatch: { expected: "deadbeef", got: inputHash("do it") },
  256. });
  257. expect(journal.getRun(RUN)?.failure?.mismatch).toEqual({
  258. expected: "deadbeef",
  259. got: inputHash("do it"),
  260. });
  261. });
  262. it("enforces the recorded actorSeq via the hold rule when arrivals are scrambled", async () => {
  263. const journal = new InMemoryJournalStore();
  264. journal.createRun({
  265. runId: RUN,
  266. caps: { maxConcurrency: 16 },
  267. spentTokens: 0,
  268. status: "running",
  269. });
  270. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  271. // 记录顺序:ask#1@1 = seq0,ask#2@1 = seq1。
  272. journal.putNode({
  273. runId: RUN,
  274. siteId: "ask#1",
  275. ordinal: 1,
  276. kind: "ask",
  277. actorSiteId: "actor#1",
  278. actorOrdinal: 1,
  279. actorSeq: 0,
  280. inputHash: inputHash("A"),
  281. status: "completed",
  282. result: "r1",
  283. });
  284. journal.putNode({
  285. runId: RUN,
  286. siteId: "ask#2",
  287. ordinal: 1,
  288. kind: "ask",
  289. actorSiteId: "actor#1",
  290. actorOrdinal: 1,
  291. actorSeq: 1,
  292. inputHash: inputHash("B"),
  293. status: "completed",
  294. result: "r2",
  295. });
  296. const { engine, driver } = setup({ journal });
  297. const actor = engine.createActor("actor#1");
  298. // 到达顺序与记录相反:先 ask#2(seq1,应被 hold),后 ask#1(seq0,触发释放)。
  299. const pB = engine.ask("ask#2", actor, "B");
  300. const pA = engine.ask("ask#1", actor, "A");
  301. await expect(Promise.all([pA, pB])).resolves.toEqual(["r1", "r2"]);
  302. // 释放顺序遵循记录的 actorSeq,而非到达顺序。
  303. expect(driver.cachedSettleOrder()).toEqual(["ask#1@1", "ask#2@1"]);
  304. expect(driver.startAskCount()).toBe(0);
  305. });
  306. it("turns the same-site nondeterministic-ordinal gap into a loud inputHash failure (not wrong results)", async () => {
  307. // v1 局限的设计后盾:同站点、被非确定前驱门控的 ask,其 ordinal 依到达顺序而非确定。
  308. // journal 记录了 ask#1@1=「plan A」、ask#1@2=「plan B」;replay 若把两者次序调换,
  309. // 第一个到达者拿到 ordinal 1 却带「plan B」→ 与记录的 hash 不符 → run 大声失败,绝不给出错误结果。
  310. const journal = new InMemoryJournalStore();
  311. journal.createRun({
  312. runId: RUN,
  313. caps: { maxConcurrency: 16 },
  314. spentTokens: 0,
  315. status: "running",
  316. });
  317. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  318. journal.putNode({
  319. runId: RUN,
  320. siteId: "ask#1",
  321. ordinal: 1,
  322. kind: "ask",
  323. actorSiteId: "actor#1",
  324. actorOrdinal: 1,
  325. actorSeq: 0,
  326. inputHash: inputHash("plan A"),
  327. status: "completed",
  328. result: "A",
  329. });
  330. journal.putNode({
  331. runId: RUN,
  332. siteId: "ask#1",
  333. ordinal: 2,
  334. kind: "ask",
  335. actorSiteId: "actor#1",
  336. actorOrdinal: 1,
  337. actorSeq: 1,
  338. inputHash: inputHash("plan B"),
  339. status: "completed",
  340. result: "B",
  341. });
  342. const { engine } = setup({ journal });
  343. const actor = engine.createActor("actor#1");
  344. const pB = engine.ask("ask#1", actor, "plan B"); // 得到 ordinal 1,但记录的是 plan A → mismatch
  345. await expect(pB).rejects.toMatchObject({ code: "InputHashMismatch" });
  346. await expect(engine.settled).resolves.toMatchObject({
  347. status: "errored",
  348. error: { code: "InputHashMismatch" },
  349. });
  350. });
  351. });
  352. describe("WorkflowEngine — mid-run crash + resume", () => {
  353. it("resumes over the same journal, short-circuiting finished nodes and finishing the rest", async () => {
  354. const journal = new InMemoryJournalStore();
  355. // run1:结算 ask#1,随后"崩溃"(ask#2 未执行)。
  356. {
  357. const driver1 = new FakeDriver(journal);
  358. const e1 = new WorkflowEngine({
  359. runId: RUN,
  360. driver: driver1,
  361. caps: { maxConcurrency: 16 },
  362. askSpecs: untypedSpecs("ask#1", "ask#2"),
  363. validate: () => [],
  364. });
  365. const a = e1.createActor("actor#1");
  366. const p1 = e1.ask("ask#1", a, "A");
  367. await flush();
  368. e1.askTurnEnded(inst("ask#1"), "RA");
  369. await expect(p1).resolves.toBe("RA");
  370. }
  371. // run2:同一 journal 上重放。
  372. const driver2 = new FakeDriver(journal);
  373. const e2 = new WorkflowEngine({
  374. runId: RUN,
  375. driver: driver2,
  376. caps: { maxConcurrency: 16 },
  377. askSpecs: untypedSpecs("ask#1", "ask#2"),
  378. validate: () => [],
  379. });
  380. const a2 = e2.createActor("actor#1");
  381. const r1 = await e2.ask("ask#1", a2, "A"); // journal 命中
  382. expect(r1).toBe("RA");
  383. expect(driver2.startAskCount(inst("ask#1"))).toBe(0); // 未重新执行
  384. const p2 = e2.ask("ask#2", a2, "B"); // 新节点,实际派发
  385. await flush();
  386. expect(driver2.startAskCount(inst("ask#2"))).toBe(1);
  387. e2.askTurnEnded(inst("ask#2"), "RB");
  388. await expect(p2).resolves.toBe("RB");
  389. e2.complete("done");
  390. await expect(e2.settled).resolves.toMatchObject({ status: "completed", artifact: "done" });
  391. });
  392. it("re-dispatches a crash-mid-flight node (status running) live, enforcing its recorded actorSeq", async () => {
  393. const journal = new InMemoryJournalStore();
  394. journal.createRun({
  395. runId: RUN,
  396. caps: { maxConcurrency: 16 },
  397. spentTokens: 0,
  398. status: "running",
  399. });
  400. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  401. // ask#1 已完结(seq0),ask#2 崩溃于执行中(seq1, status running)。
  402. journal.putNode({
  403. runId: RUN,
  404. siteId: "ask#1",
  405. ordinal: 1,
  406. kind: "ask",
  407. actorSiteId: "actor#1",
  408. actorOrdinal: 1,
  409. actorSeq: 0,
  410. inputHash: inputHash("A"),
  411. status: "completed",
  412. result: "RA",
  413. });
  414. journal.putNode({
  415. runId: RUN,
  416. siteId: "ask#2",
  417. ordinal: 1,
  418. kind: "ask",
  419. actorSiteId: "actor#1",
  420. actorOrdinal: 1,
  421. actorSeq: 1,
  422. inputHash: inputHash("B"),
  423. status: "running",
  424. });
  425. const { engine, journal: j, driver } = setup({ journal });
  426. const actor = engine.createActor("actor#1");
  427. const p1 = engine.ask("ask#1", actor, "A"); // 完结命中,短路
  428. const p2 = engine.ask("ask#2", actor, "B"); // running → 重新 live 派发
  429. await flush();
  430. expect(await p1).toBe("RA");
  431. expect(driver.startAskCount(inst("ask#1"))).toBe(0); // 完结节点未重跑
  432. expect(driver.startAskCount(inst("ask#2"))).toBe(1); // running 节点重新 live 执行
  433. engine.askTurnEnded(inst("ask#2"), "RB");
  434. expect(await p2).toBe("RB");
  435. // running 记录被更新为 completed,且 actorSeq 保持记录值。
  436. expect(j.getNode(RUN, "ask#2", 1)?.status).toBe("completed");
  437. expect(j.getNode(RUN, "ask#2", 1)?.actorSeq).toBe(1);
  438. });
  439. it("re-creates the actor session via the driver even when the journal records a sessionId", async () => {
  440. // Bug 根因(resume 重派发在生产 driver 上必炸):registerActor 原先把 journal 里记录的
  441. // sessionId 预解析成 actor.sessionPromise,让 ensureSession 跳过 driver.createActorSession;
  442. // 而生产 driver 的 sessions map **只**在 createActorSession 里填充,startAsk 按 map 查会话
  443. // → 每个重新派发的 ask 都以 DriverError「未知会话」立即失败。纯 replay(零派发)与
  444. // fake driver(startAsk 不查 map)都测不出它,所以这里直接钉 createActorSession 的调用次数。
  445. // 会话身份是 driver 所有的(生产铸造函数按 (runId, actorRef) 纯确定),journal 值只是记录。
  446. const journal = new InMemoryJournalStore();
  447. journal.createRun({
  448. runId: RUN,
  449. caps: { maxConcurrency: 16 },
  450. spentTokens: 0,
  451. status: "running",
  452. });
  453. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1, sessionId: "session:actor#1@1" });
  454. journal.putNode({
  455. runId: RUN,
  456. siteId: "ask#1",
  457. ordinal: 1,
  458. kind: "ask",
  459. actorSiteId: "actor#1",
  460. actorOrdinal: 1,
  461. actorSeq: 0,
  462. inputHash: inputHash("A"),
  463. status: "running",
  464. });
  465. const { engine, journal: j, driver } = setup({ journal });
  466. const actor = engine.createActor("actor#1");
  467. const p = engine.ask("ask#1", actor, "A");
  468. await flush();
  469. // 关键断言:会话经 driver 重建(恰好一次),且派发用的是 driver 造出的会话。
  470. expect(driver.sessionCreations).toEqual([{ siteId: "actor#1", ordinal: 1 }]);
  471. expect(driver.startAskCount(inst("ask#1"))).toBe(1);
  472. expect(driver.startAsks[0]?.session.id).toBe("session:actor#1@1");
  473. engine.askTurnEnded(inst("ask#1"), "RA");
  474. await expect(p).resolves.toBe("RA");
  475. // ensureSession 的 putActor 把(生产上必然相同的)sessionId 重新记录回去。
  476. expect(j.getActor(RUN, "actor#1", 1)?.sessionId).toBe("session:actor#1@1");
  477. });
  478. it("restores the tokens already spent by the crashed run instead of starting from zero", async () => {
  479. // 回归:用量原先只在 createRun(0) 落库一次,askStats 的累加从不回写,
  480. // 于是 resume 出来的引擎从零开始计数,run 级用量跨生命周期不连续。
  481. const caps: Caps = { maxConcurrency: 16 };
  482. const journal = new InMemoryJournalStore();
  483. {
  484. const e1 = new WorkflowEngine({
  485. runId: RUN,
  486. driver: new FakeDriver(journal),
  487. caps,
  488. askSpecs: untypedSpecs("ask#1", "ask#2"),
  489. validate: () => [],
  490. });
  491. const a = e1.createActor("actor#1");
  492. const p = e1.ask("ask#1", a, "A");
  493. await flush();
  494. e1.askStats(inst("ask#1"), { tokens: 300, toolCalls: 1, turns: 1 });
  495. e1.askTurnEnded(inst("ask#1"), "RA");
  496. await expect(p).resolves.toBe("RA");
  497. }
  498. expect(journal.getRun(RUN)?.spentTokens).toBe(300);
  499. const driver2 = new FakeDriver(journal);
  500. const e2 = new WorkflowEngine({
  501. runId: RUN,
  502. driver: driver2,
  503. caps,
  504. askSpecs: untypedSpecs("ask#1", "ask#2"),
  505. validate: () => [],
  506. });
  507. const b = e2.createActor("actor#2");
  508. void e2.ask("ask#2", b, "B").catch(() => {});
  509. await flush();
  510. e2.askStats(inst("ask#2"), { tokens: 100, toolCalls: 0, turns: 1 });
  511. // 事件载荷与列值在同一同步步骤产生:resume 后继续累计,而不是从 0 重来。
  512. expect(driver2.events.at(-1)).toEqual({ type: "usage-updated", spentTokens: 400 });
  513. expect(journal.getRun(RUN)?.spentTokens).toBe(400);
  514. });
  515. });
  516. describe("WorkflowEngine — cancellation", () => {
  517. it("cancels in-flight asks, settles cancelled, and keeps finished journal entries", async () => {
  518. const { engine, driver, journal } = setup();
  519. const actor = engine.createActor("actor#1");
  520. const pDone = engine.ask("ask#1", actor, "A");
  521. await flush();
  522. engine.askTurnEnded(inst("ask#1"), "RA"); // 结算完成,落 journal
  523. await expect(pDone).resolves.toBe("RA");
  524. const pInFlight = engine.ask("ask#2", actor, "B");
  525. await flush();
  526. expect(driver.startAskCount(inst("ask#2"))).toBe(1);
  527. engine.stop("user");
  528. expect(driver.cancels).toContainEqual(inst("ask#2"));
  529. await expect(pInFlight).rejects.toMatchObject({ code: "Cancelled" });
  530. await expect(engine.settled).resolves.toEqual({ status: "stopped", reason: "user" });
  531. expect(journal.getRun(RUN)).toMatchObject({ status: "stopped", stopReason: "user" });
  532. expect(driver.events.at(-1)).toEqual({
  533. type: "run-settled",
  534. status: "stopped",
  535. stopReason: "user",
  536. });
  537. // 完结节点保留为 completed;在飞节点停在准入时的 running 记录(非"完结"结果),resume 可据此重跑。
  538. expect(journal.getNode(RUN, "ask#1", 1)?.status).toBe("completed");
  539. expect(journal.getNode(RUN, "ask#2", 1)?.status).toBe("running");
  540. });
  541. });
  542. describe("WorkflowEngine — complete() with in-flight asks", () => {
  543. // 脚本可以在 ask 仍在飞时返回(Promise.race 的输家、没有 await 的 ask)。complete 对它们的处置
  544. // 必须与 cancel 逐字节同形,否则 scheduler 永远握着节点、driver 侧 turn 继续烧 token、事件
  545. // 日志里一个 node-dispatched 永远等不到 node-settled。见 docs/execution-engine.md。
  546. it("aborts the in-flight ask like stop() does, then settles completed with the artifact", async () => {
  547. const { engine, driver, journal } = setup();
  548. const actor = engine.createActor("actor#1");
  549. const pDone = engine.ask("ask#1", actor, "A");
  550. await flush();
  551. engine.askTurnEnded(inst("ask#1"), "RA");
  552. await expect(pDone).resolves.toBe("RA");
  553. const pInFlight = engine.ask("ask#2", actor, "B");
  554. await flush();
  555. expect(driver.startAskCount(inst("ask#2"))).toBe(1);
  556. engine.complete("done");
  557. expect(driver.cancels).toContainEqual(inst("ask#2"));
  558. await expect(pInFlight).rejects.toMatchObject({ code: "Cancelled" });
  559. await expect(engine.settled).resolves.toEqual({ status: "completed", artifact: "done" });
  560. expect(engine.status()).toBe("completed");
  561. // 事件序列:在飞节点先 cancelled,再 run-settled(completed)。
  562. const types = driver.events.map((e) => e.type);
  563. const settledIdx = types.lastIndexOf("node-settled");
  564. const runIdx = types.lastIndexOf("run-settled");
  565. expect(driver.events[settledIdx]).toMatchObject({
  566. instance: inst("ask#2"),
  567. outcome: "cancelled",
  568. });
  569. expect(driver.events[runIdx]).toMatchObject({ status: "completed" });
  570. expect(settledIdx).toBeLessThan(runIdx);
  571. // journal 与 cancel 路径同形:完结节点 completed,在飞节点停在 running;run 带产物 completed。
  572. expect(journal.getNode(RUN, "ask#1", 1)?.status).toBe("completed");
  573. expect(journal.getNode(RUN, "ask#2", 1)?.status).toBe("running");
  574. expect(journal.getRun(RUN)?.status).toBe("completed");
  575. expect(journal.getRun(RUN)?.result).toBe("done");
  576. });
  577. it("does nothing extra when no ask is in flight (byte-for-byte the plain complete)", async () => {
  578. const { engine, driver } = setup();
  579. const actor = engine.createActor("actor#1");
  580. const p = engine.ask("ask#1", actor, "A");
  581. await flush();
  582. engine.askTurnEnded(inst("ask#1"), "RA");
  583. await expect(p).resolves.toBe("RA");
  584. engine.complete("done");
  585. expect(driver.cancels).toEqual([]);
  586. expect(driver.eventsOfType("node-settled").map((e) => e.outcome)).toEqual(["ok"]);
  587. await expect(engine.settled).resolves.toEqual({ status: "completed", artifact: "done" });
  588. });
  589. it("persists straggler stats after complete() to the usage row without emitting events", async () => {
  590. const { engine, driver, journal } = setup();
  591. const winner = engine.createActor("actor#1");
  592. const loser = engine.createActor("actor#2");
  593. const pWin = engine.ask("ask#1", winner, "fast");
  594. void engine.ask("ask#2", loser, "slow").catch(() => {});
  595. await flush();
  596. engine.askTurnEnded(inst("ask#1"), "won");
  597. await expect(pWin).resolves.toBe("won");
  598. engine.complete("won");
  599. const eventCount = driver.events.length;
  600. // 真实 actor 的用量在 turn 解析后才知道:最后的 stats 常晚于 complete 到达。
  601. // 记账要保留(用量行 + 节点回填都是 journal 行更新),事件流不能再追加——run-settled 是最后一条。
  602. engine.askStats(inst("ask#2"), { tokens: 7, toolCalls: 0, turns: 1 });
  603. expect(driver.events.length).toBe(eventCount);
  604. expect(journal.getRun(RUN)?.spentTokens).toBe(7);
  605. expect(journal.getNode(RUN, "ask#2", 1)?.stats).toEqual({ tokens: 7, toolCalls: 0, turns: 1 });
  606. });
  607. });
  608. describe("WorkflowEngine — driver dispose at settlement", () => {
  609. // 引擎契约:三条终态路径各调 driver.dispose 恰好一次,晚于 run-settled;first-wins 下不重复。
  610. async function withInFlightAsk() {
  611. const { engine, driver } = setup();
  612. const actor = engine.createActor("actor#1");
  613. const p = engine.ask("ask#1", actor, "A");
  614. void p.catch(() => {});
  615. await flush();
  616. expect(driver.disposeCalls).toBe(0);
  617. return { engine, driver };
  618. }
  619. function expectDisposedOnceAfterRunSettled(driver: FakeDriver): void {
  620. expect(driver.disposeCalls).toBe(1);
  621. const runSettledIdx = driver.events.findIndex((e) => e.type === "run-settled");
  622. expect(runSettledIdx).toBeGreaterThanOrEqual(0);
  623. expect(driver.eventsAtDispose).toBe(runSettledIdx + 1);
  624. }
  625. it("complete(): once, after run-settled, and not again on a later stop()/fail()", async () => {
  626. const { engine, driver } = await withInFlightAsk();
  627. engine.complete("done");
  628. expectDisposedOnceAfterRunSettled(driver);
  629. engine.stop("user");
  630. engine.fail(new WorkflowError("DriverError", "late"));
  631. expect(driver.disposeCalls).toBe(1);
  632. });
  633. it("stop(): once, after run-settled", async () => {
  634. const { engine, driver } = await withInFlightAsk();
  635. engine.stop("user");
  636. expectDisposedOnceAfterRunSettled(driver);
  637. engine.complete("late");
  638. expect(driver.disposeCalls).toBe(1);
  639. });
  640. it("fail(): once, after run-settled", async () => {
  641. const { engine, driver } = await withInFlightAsk();
  642. engine.fail(new WorkflowError("DriverError", "boom"));
  643. expectDisposedOnceAfterRunSettled(driver);
  644. expect(driver.disposeCalls).toBe(1);
  645. });
  646. it("a driver without dispose is fine (the hook is optional)", async () => {
  647. const journal = new InMemoryJournalStore();
  648. const driver = new FakeDriver(journal);
  649. (driver as { dispose?: () => void }).dispose = undefined;
  650. const engine = new WorkflowEngine({
  651. runId: RUN,
  652. driver,
  653. caps: { maxConcurrency: 16 },
  654. askSpecs: untypedSpecs("ask#1"),
  655. validate: () => [],
  656. });
  657. engine.complete("done");
  658. await expect(engine.settled).resolves.toEqual({ status: "completed", artifact: "done" });
  659. });
  660. });
  661. describe("WorkflowEngine — usage (no caps)", () => {
  662. it("never caps the node count: well past the old limit of 100 the run is still running", async () => {
  663. // docs/dynamic-workflow/authoring.md:节点上限整体移除,取消是唯一的停止手段。
  664. const { engine, driver, journal } = setup({ caps: { maxConcurrency: 200 } });
  665. for (let i = 1; i <= 120; i++) {
  666. const actor = engine.createActor(`actor#${i}`);
  667. void engine.ask("ask#1", actor, `job ${i}`).catch(() => {});
  668. }
  669. await flush();
  670. expect(journal.getRun(RUN)?.status).toBe("running");
  671. expect(driver.events.filter((e) => e.type === "node-dispatched")).toHaveLength(120);
  672. engine.stop("user");
  673. });
  674. it("emits usage-updated with the accumulated spentTokens and never fails the run on usage", async () => {
  675. const { engine, driver, journal } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  676. const actor = engine.createActor("actor#1");
  677. void engine.ask("ask#1", actor, "do it").catch(() => {});
  678. await flush();
  679. engine.askStats(inst("ask#1"), { tokens: 30, toolCalls: 0, turns: 1 });
  680. expect(driver.events.at(-1)).toEqual({ type: "usage-updated", spentTokens: 30 });
  681. expect(journal.getRun(RUN)?.spentTokens).toBe(30);
  682. engine.askStats(inst("ask#1"), { tokens: 80, toolCalls: 0, turns: 1 });
  683. expect(driver.events.at(-1)).toEqual({ type: "usage-updated", spentTokens: 110 });
  684. expect(journal.getRun(RUN)?.spentTokens).toBe(110);
  685. expect(journal.getRun(RUN)?.status).toBe("running");
  686. engine.stop("user");
  687. });
  688. });
  689. describe("WorkflowEngine — fail() (harness-driven run failure)", () => {
  690. it("settles failed, cancels in-flight asks, records failure_json, and is first-wins", async () => {
  691. const { engine, driver, journal } = setup();
  692. const actor = engine.createActor("actor#1");
  693. const p = engine.ask("ask#1", actor, "A");
  694. void p.catch(() => {}); // run 失败会 reject 该 ask
  695. await flush();
  696. expect(driver.startAskCount(inst("ask#1"))).toBe(1);
  697. // harness 把子进程抛出/崩溃/超时归为 run 失败。
  698. const boom = new WorkflowError("DriverError", "child crashed");
  699. engine.fail(boom);
  700. expect(driver.cancels).toContainEqual(inst("ask#1")); // 在飞 ask driver 侧取消
  701. await expect(p).rejects.toBe(boom); // 在飞 ask 以 run 错误 reject
  702. await expect(engine.settled).resolves.toEqual({ status: "errored", error: boom });
  703. expect(engine.status()).toBe("errored");
  704. const run = journal.getRun(RUN);
  705. expect(run?.status).toBe("errored");
  706. expect(run?.failure).toEqual({ code: "DriverError", message: "child crashed" });
  707. expect(run?.stopReason).toBeUndefined();
  708. // first-wins:后续 complete()/再次 fail()/stop() 均为 no-op。
  709. engine.complete("late");
  710. engine.fail(new WorkflowError("Cancelled", "ignored"));
  711. engine.stop("interrupted", new WorkflowError("Interrupted", "late"));
  712. await expect(engine.settled).resolves.toEqual({ status: "errored", error: boom });
  713. });
  714. it("createActorSession rejection surfaces the cause text in the DriverError (journal + reject)", async () => {
  715. // 2026-09-03 实机:直接启动的首个 actor 在建 session_task_link 时撞 FOREIGN KEY,run 只留下
  716. // 「创建 actor 会话失败」——cause 不进 toJSON、也无人记日志,无从诊断。这里钉住 message 必须
  717. // 带上 cause 的文本。
  718. const { engine, journal, driver } = setup({ deferSessions: true });
  719. const actor = engine.createActor("actor#1");
  720. const p = engine.ask("ask#1", actor, "A");
  721. driver.sessionDeferrals[0]!.reject(new Error("FOREIGN KEY constraint failed"));
  722. // 钉的是 cause 文本(可变部分)在场,不钉整句措辞。
  723. await expect(p).rejects.toMatchObject({
  724. code: "DriverError",
  725. message: expect.stringContaining("FOREIGN KEY constraint failed"),
  726. });
  727. expect(journal.getNode(RUN, "ask#1", 1)?.error).toMatchObject({
  728. code: "DriverError",
  729. message: expect.stringContaining("FOREIGN KEY constraint failed"),
  730. });
  731. });
  732. it("complete() first wins over a later fail()", async () => {
  733. const { engine } = setup();
  734. engine.complete("ok");
  735. engine.fail(new WorkflowError("DriverError", "too late"));
  736. await expect(engine.settled).resolves.toEqual({ status: "completed", artifact: "ok" });
  737. });
  738. it("createActor throws synchronously once the run has failed (harness can catch → fail())", async () => {
  739. const { engine } = setup();
  740. engine.fail(new WorkflowError("DriverError", "boom"));
  741. // 同步抛出(无 async 泄漏),harness 的 try/catch 能直接兜住并转成 fail()。
  742. expect(() => engine.createActor("actor#1")).toThrow();
  743. });
  744. });
  745. describe("WorkflowEngine — stats backfill after settle", () => {
  746. it("backfills stats onto a typed ask journaled at settle when askStats arrives after the submit", async () => {
  747. // typed-accept 路径(主导路径):submit 停 turn 并在 settle 时落库;真实 actor 的用量在
  748. // turn 解析后(submit 之后)才知道,故 askStats 在节点已离开 liveNodes 后才到达。引擎回填。
  749. const { engine, journal } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  750. const actor = engine.createActor("actor#1", "planner");
  751. const p = engine.ask("ask#1", actor, "do it");
  752. await flush();
  753. engine.askSubmitAttempted(inst("ask#1"), { x: 1 });
  754. await expect(p).resolves.toEqual({ x: 1 });
  755. const settled = journal.getNode(RUN, "ask#1", 1);
  756. expect(settled?.status).toBe("completed");
  757. expect(settled?.stats).toBeUndefined(); // settle 时 stats 尚未到达
  758. engine.askStats(inst("ask#1"), { tokens: 42, toolCalls: 2, turns: 1 });
  759. const node = journal.getNode(RUN, "ask#1", 1);
  760. expect(node?.stats).toEqual({ tokens: 42, toolCalls: 2, turns: 1 });
  761. // 只新增 stats,其余字段保持不变(status/result/actorSeq/inputHash/actor 身份)。
  762. expect(node?.status).toBe("completed");
  763. expect(node?.result).toEqual({ x: 1 });
  764. expect(node?.actorSeq).toBe(0);
  765. expect(node?.inputHash).toBe(inputHash("do it"));
  766. expect(node?.actorSiteId).toBe("actor#1");
  767. expect(node?.actorOrdinal).toBe(1);
  768. expect(node?.kind).toBe("ask");
  769. });
  770. it("is a no-op when the node was never journaled (defensive, best-effort)", async () => {
  771. // 从未准入的实例上报 stats:既无 live 节点也无 journal 记录,回填静默跳过(不抛错、不建记录)。
  772. const { engine, journal } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  773. engine.createActor("actor#1");
  774. engine.askStats(inst("ask#404"), { tokens: 5, toolCalls: 0, turns: 1 });
  775. expect(journal.getNode(RUN, "ask#404", 1)).toBeUndefined();
  776. });
  777. });
  778. describe("WorkflowEngine — run metadata", () => {
  779. it("persists supplied run metadata through createRun", async () => {
  780. // 前四个字段 RunRecord 早就声明了,但 createRun 从不填——于是 resume 的 script_hash
  781. // 校验没有比对对象。落库是那条校验唯一的前提。toolCallId 是 cancel & resume 特性
  782. // 追加的第五个:重启后工具卡 join 与 resume 通知锚点的唯一持久来源。
  783. const { journal } = setup({
  784. scriptText: 'await agent("a").ask("hi");',
  785. scriptHash: "hash-a",
  786. parentSessionId: "sess_parent",
  787. cwd: "/tmp/project",
  788. toolCallId: "call-abc",
  789. name: "nightly triage",
  790. resumedFrom: "run-predecessor",
  791. });
  792. expect(journal.getRun(RUN)).toMatchObject({
  793. runId: RUN,
  794. status: "running",
  795. scriptText: 'await agent("a").ask("hi");',
  796. scriptHash: "hash-a",
  797. parentSessionId: "sess_parent",
  798. cwd: "/tmp/project",
  799. toolCallId: "call-abc",
  800. name: "nightly triage",
  801. resumedFrom: "run-predecessor",
  802. });
  803. });
  804. it("omits the metadata fields entirely when the config carries none", async () => {
  805. // 缺省不得落成 undefined 键:存储实现按"字段缺席"与"字段为 null"区分(见契约测)。
  806. const { journal } = setup();
  807. const run = journal.getRun(RUN)!;
  808. expect("scriptText" in run).toBe(false);
  809. expect("scriptHash" in run).toBe(false);
  810. expect("parentSessionId" in run).toBe(false);
  811. expect("cwd" in run).toBe(false);
  812. // 未命名的 run 必须是**缺席的键**而不是 null/undefined 值:读侧据此走脚本首行兜底。
  813. expect("name" in run).toBe(false);
  814. expect("toolCallId" in run).toBe(false);
  815. // 绝大多数 run 不是修订:lineage 指针同样必须缺席,而不是落成空值
  816. // (docs/execution-engine.md)。
  817. expect("resumedFrom" in run).toBe(false);
  818. });
  819. });
  820. // 具名 actor 是修订续跑(amend-resume)缓存导入的身份键,而**任何** run 都是未来修订的
  821. // 潜在前驱——所以这条唯一性规则对所有 run 生效,不只是修订 run
  822. // (docs/execution-engine.md「Amend-resume」)。
  823. describe("WorkflowEngine — actor name uniqueness", () => {
  824. it("fails the run when a non-empty name repeats (both sites via the name argument)", async () => {
  825. const { engine, journal } = setup();
  826. engine.createActor("actor#1", "planner");
  827. // createActor 是同步表面(无 promise 可拒),所以与 assertRunning 同姿态:抛。
  828. expect(() => engine.createActor("actor#2", "planner")).toThrow(
  829. expect.objectContaining({ code: "DuplicateActorName" }),
  830. );
  831. await expect(engine.settled).resolves.toMatchObject({
  832. status: "errored",
  833. error: expect.objectContaining({ code: "DuplicateActorName" }),
  834. });
  835. expect(journal.getRun(RUN)?.failure?.code).toBe("DuplicateActorName");
  836. });
  837. it("compares the effective name, so persona.name collides with a plain name argument", async () => {
  838. // 有效名 = normalizePersona 后的 spec.name,persona.name 压过 name 实参。查重必须看
  839. // 那个值,否则「name 写 b、persona.name 写 a」能绕过规则并在前驱里造出两个 a。
  840. const { engine } = setup();
  841. engine.createActor("actor#1", "reviewer");
  842. expect(() => engine.createActor("actor#2", "second", { name: "reviewer" })).toThrow(
  843. expect.objectContaining({ code: "DuplicateActorName" }),
  844. );
  845. });
  846. it("does not collide when persona.name renames one of two identical name arguments", async () => {
  847. // 同一条规则的另一侧:name 实参相同但 persona.name 覆盖了其中一个,有效名就不同。
  848. const { engine, journal } = setup();
  849. engine.createActor("actor#1", "worker");
  850. engine.createActor("actor#2", "worker", { name: "worker-2" });
  851. expect(journal.getRun(RUN)?.status).toBe("running");
  852. expect(
  853. journal
  854. .listActors(RUN, { withPersona: true })
  855. .map((a) => a.persona?.name)
  856. .sort(),
  857. ).toEqual(["worker", "worker-2"]);
  858. });
  859. it("allows any number of anonymous actors (absent or empty names)", async () => {
  860. // 匿名合法且不查——代价已裁决:没有缓存资格。空串与缺席同属匿名。
  861. const { engine, journal } = setup();
  862. engine.createActor("actor#1");
  863. engine.createActor("actor#2");
  864. engine.createActor("actor#3", "");
  865. engine.createActor("actor#4", "", { name: "" });
  866. expect(journal.getRun(RUN)?.status).toBe("running");
  867. expect(journal.listActors(RUN, { withPersona: true })).toHaveLength(4);
  868. });
  869. it("allows distinct names", async () => {
  870. const { engine, journal } = setup();
  871. engine.createActor("actor#1", "planner");
  872. engine.createActor("actor#2", "reviewer");
  873. expect(journal.getRun(RUN)?.status).toBe("running");
  874. });
  875. it("does not false-positive on a byte-identical resume (fresh engine, names re-registered once)", async () => {
  876. // replay 安全性:查重表是纯内存的、随引擎实例而生。resume 在一个全新引擎里从头重跑
  877. // 同一串 createActor 调用,每个名字因此恰好被登记一次。这也是它不能落 journal 的理由。
  878. const journal = new InMemoryJournalStore();
  879. {
  880. const e1 = setup({ journal }).engine;
  881. e1.createActor("actor#1", "planner");
  882. e1.createActor("actor#2", "reviewer");
  883. e1.stop("user");
  884. }
  885. const { engine, journal: same } = setup({ journal });
  886. expect(() => {
  887. engine.createActor("actor#1", "planner");
  888. engine.createActor("actor#2", "reviewer");
  889. }).not.toThrow();
  890. expect(same.getRun(RUN)?.status).toBe("running");
  891. });
  892. });
  893. describe("WorkflowEngine — actor persona and resolved model", () => {
  894. // persona 对引擎是**纯透传数据**:引擎不解读它,但必须把它原样送到 driver、事件与 journal——
  895. // 它是冻结身份,resume 时按同一份重建。模型不在 persona 里(2026-09-11 起没有模型档位):
  896. // 子代理跑在哪个模型上是宿主事实,由 driver 写进 resolvedModel。
  897. it("carries the persona through to the driver, the actor-created event and the journal", async () => {
  898. const { engine, driver, journal } = setup();
  899. const actor = engine.createActor("actor#1", "judge", {
  900. system: "You judge.",
  901. });
  902. const p = engine.ask("ask#1", actor, "judge it");
  903. await flush();
  904. expect(driver.sessionPersonas[0]).toEqual({
  905. name: "judge",
  906. system: "You judge.",
  907. });
  908. const created = driver.events.find((e) => e.type === "actor-created");
  909. expect(created).toMatchObject({
  910. persona: { name: "judge", system: "You judge." },
  911. });
  912. expect(journal.getActor(RUN, "actor#1", 1)?.persona).toEqual({
  913. name: "judge",
  914. system: "You judge.",
  915. });
  916. engine.askTurnEnded(inst("ask#1"), "ok");
  917. await expect(p).resolves.toBe("ok");
  918. });
  919. // docs/dynamic-workflow/authoring.md「Choosing a model per subagent」:persona 可以点名一个模型。
  920. // 引擎只记这个名字、原样交给 driver——查绑定表与建会话都是宿主的事。
  921. it("carries a persona model name verbatim to the driver, the event and the journal", async () => {
  922. const { engine, driver, journal } = setup();
  923. const actor = engine.createActor("actor#1", "judge", {
  924. system: "You judge.",
  925. model: "GLM-5.3-Flash$high",
  926. });
  927. const p = engine.ask("ask#1", actor, "judge it");
  928. await flush();
  929. const expected = { name: "judge", system: "You judge.", model: "GLM-5.3-Flash$high" };
  930. expect(driver.sessionPersonas[0]).toEqual(expected);
  931. expect(driver.events.find((e) => e.type === "actor-created")).toMatchObject({
  932. persona: expected,
  933. });
  934. expect(journal.getActor(RUN, "actor#1", 1)?.persona).toEqual(expected);
  935. // 派发重复出生事实,persona 的模型名也在其中(读面收回表的子代理要带着它)。
  936. expect(driver.events.find((e) => e.type === "node-dispatched")).toMatchObject({
  937. actorName: "judge",
  938. actorPersonaModel: "GLM-5.3-Flash$high",
  939. });
  940. engine.askTurnEnded(inst("ask#1"), "ok");
  941. await expect(p).resolves.toBe("ok");
  942. });
  943. it("a dispatch of a persona without a model carries no actorPersonaModel", async () => {
  944. const { engine, driver } = setup();
  945. const actor = engine.createActor("actor#1", "judge", { system: "You judge." });
  946. const p = engine.ask("ask#1", actor, "judge it");
  947. await flush();
  948. const dispatched = driver.events.find((e) => e.type === "node-dispatched");
  949. expect(dispatched).toBeDefined();
  950. expect("actorPersonaModel" in dispatched!).toBe(false);
  951. engine.askTurnEnded(inst("ask#1"), "ok");
  952. await expect(p).resolves.toBe("ok");
  953. });
  954. it("keeps only the known string fields of an object persona off the wire", async () => {
  955. // 沙箱经类型断言塞进来的怪值不该一路搬进 journal 与宿主的建会话路径。
  956. const { engine, journal } = setup();
  957. engine.createActor("actor#1", "judge", {
  958. system: "You judge.",
  959. model: 42,
  960. tools: "none",
  961. } as unknown as PersonaSpec);
  962. expect(journal.getActor(RUN, "actor#1", 1)?.persona).toEqual({
  963. name: "judge",
  964. system: "You judge.",
  965. });
  966. });
  967. it("carries a string persona through unchanged (nothing invented)", async () => {
  968. const { engine, journal } = setup();
  969. engine.createActor("actor#1", "planner", "You plan.");
  970. const persona = journal.getActor(RUN, "actor#1", 1)?.persona;
  971. expect(persona).toEqual({ name: "planner", system: "You plan." });
  972. });
  973. it("does not clobber the driver-written resolvedModel when journaling the session", async () => {
  974. // resolvedModel 是 **driver 拥有**的字段:子代理跑在哪个模型上只有宿主知道,所以它在
  975. // createActorSession 内部才被写下。而 putActor 是整条记录的替换,引擎在会话创建返回后
  976. // 还要再写一次(补 sessionId)——那一次必须把它带过去,否则成本审计与 resume 的 pin
  977. // 依据在正常路径上就丢了。
  978. const { engine, journal } = setup({
  979. resolveModel: (persona) =>
  980. persona.name === "judge" ? "anthropic/haiku" : "anthropic/sonnet",
  981. });
  982. const actor = engine.createActor("actor#1", "judge", { system: "You judge." });
  983. const p = engine.ask("ask#1", actor, "judge it");
  984. await flush();
  985. const record = journal.getActor(RUN, "actor#1", 1);
  986. expect(record?.resolvedModel).toBe("anthropic/haiku");
  987. // 同一条记录上,引擎自己的字段照旧完整。
  988. expect(record?.sessionId).toBe("session:actor#1@1");
  989. expect(record?.persona).toEqual({ name: "judge", system: "You judge." });
  990. engine.askTurnEnded(inst("ask#1"), "ok");
  991. await expect(p).resolves.toBe("ok");
  992. });
  993. it("preserves a journaled resolvedModel across a replayed createActor", async () => {
  994. // resume 路径:同一个 (siteId, ordinal) 再次 createActor 时,引擎的 putActor 不得把上一次
  995. // run 解析出的模型抹掉——它正是「resume 重新附着到同一个模型」的依据。
  996. const journal = new InMemoryJournalStore();
  997. journal.createRun({
  998. runId: RUN,
  999. caps: { maxConcurrency: 16 },
  1000. spentTokens: 0,
  1001. status: "running",
  1002. });
  1003. journal.putActor({
  1004. runId: RUN,
  1005. siteId: "actor#1",
  1006. ordinal: 1,
  1007. sessionId: "session:actor#1@1",
  1008. resolvedModel: "anthropic/haiku",
  1009. });
  1010. const { engine } = setup({ journal });
  1011. engine.createActor("actor#1", "judge", { system: "You judge." });
  1012. expect(journal.getActor(RUN, "actor#1", 1)).toMatchObject({
  1013. sessionId: "session:actor#1@1",
  1014. resolvedModel: "anthropic/haiku",
  1015. persona: { name: "judge", system: "You judge." },
  1016. });
  1017. });
  1018. });
  1019. describe("WorkflowEngine — resume script identity", () => {
  1020. /** 造一个已存在的 run 记录(模拟前一次 run 留下的 journal)。 */
  1021. function seedRun(journal: InMemoryJournalStore, scriptHash?: string): void {
  1022. journal.createRun({
  1023. runId: RUN,
  1024. caps: { maxConcurrency: 16 },
  1025. spentTokens: 7,
  1026. status: "stopped",
  1027. stopReason: "user",
  1028. ...(scriptHash === undefined ? {} : { scriptHash }),
  1029. });
  1030. }
  1031. it("refuses to resume when the journaled scriptHash differs from the config's", () => {
  1032. // V1 的 resume 限制是「逐字节相同的脚本文本」。哈希不一致意味着调用方拿另一份脚本
  1033. // 复用了同一个 runId:拒绝这次 resume,而不是接受后再让 run 失败。
  1034. const journal = new InMemoryJournalStore();
  1035. seedRun(journal, "hash-old");
  1036. const driver = new FakeDriver(journal);
  1037. const construct = () =>
  1038. new WorkflowEngine({
  1039. runId: RUN,
  1040. driver,
  1041. caps: { maxConcurrency: 16 },
  1042. askSpecs: new Map(),
  1043. validate: () => [],
  1044. scriptHash: "hash-new",
  1045. });
  1046. expect(construct).toThrowError(expect.objectContaining({ code: "ScriptHashMismatch" }));
  1047. // 两个哈希必须结构化随错误走:排查 resume 被拒的人要看出是哪一侧变了,
  1048. // 而不是从 message 里正则抠值(流程判断不依赖错误文本)。
  1049. let thrown: WorkflowError | undefined;
  1050. try {
  1051. construct();
  1052. } catch (error) {
  1053. thrown = error as WorkflowError;
  1054. }
  1055. expect(thrown?.mismatch).toEqual({ expected: "hash-old", got: "hash-new" });
  1056. // 落 journal 的可序列化形态同样带着它(failure_json 是 app 侧读的持久记录)。
  1057. expect(thrown?.toJSON()).toMatchObject({
  1058. code: "ScriptHashMismatch",
  1059. mismatch: { expected: "hash-old", got: "hash-new" },
  1060. });
  1061. expect(WorkflowError.fromJSON(thrown!.toJSON()).mismatch).toEqual({
  1062. expected: "hash-old",
  1063. got: "hash-new",
  1064. });
  1065. // 既有 journal 记录不得被这次拒绝改写——它仍可用正确的脚本 resume。
  1066. expect(journal.getRun(RUN)).toMatchObject({
  1067. status: "stopped",
  1068. scriptHash: "hash-old",
  1069. spentTokens: 7,
  1070. });
  1071. // 拒绝发生在任何事件之前:没有 run-started,也没有 run-settled。
  1072. expect(driver.events).toEqual([]);
  1073. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })).toEqual([]);
  1074. });
  1075. it("resumes when the two hashes match", () => {
  1076. const journal = new InMemoryJournalStore();
  1077. seedRun(journal, "hash-same");
  1078. const driver = new FakeDriver(journal);
  1079. const engine = new WorkflowEngine({
  1080. runId: RUN,
  1081. driver,
  1082. caps: { maxConcurrency: 16 },
  1083. askSpecs: new Map(),
  1084. validate: () => [],
  1085. scriptHash: "hash-same",
  1086. });
  1087. expect(engine.status()).toBe("running");
  1088. expect(journal.getRun(RUN)?.spentTokens).toBe(7); // 预算仍从记录恢复
  1089. });
  1090. it("resumes when either side has no hash (records predating run metadata)", () => {
  1091. // 只有"两侧都有且不同"才拒绝:缺一侧就没有可比对的对象,此时不得凭空判定不匹配。
  1092. const withoutRecordHash = new InMemoryJournalStore();
  1093. seedRun(withoutRecordHash);
  1094. expect(
  1095. new WorkflowEngine({
  1096. runId: RUN,
  1097. driver: new FakeDriver(withoutRecordHash),
  1098. caps: { maxConcurrency: 16 },
  1099. askSpecs: new Map(),
  1100. validate: () => [],
  1101. scriptHash: "hash-new",
  1102. }).status(),
  1103. ).toBe("running");
  1104. const withoutConfigHash = new InMemoryJournalStore();
  1105. seedRun(withoutConfigHash, "hash-old");
  1106. expect(
  1107. new WorkflowEngine({
  1108. runId: RUN,
  1109. driver: new FakeDriver(withoutConfigHash),
  1110. caps: { maxConcurrency: 16 },
  1111. askSpecs: new Map(),
  1112. validate: () => [],
  1113. }).status(),
  1114. ).toBe("running");
  1115. });
  1116. });
  1117. describe("WorkflowEngine — askSpecs completeness", () => {
  1118. it("fails the run loudly instead of degrading an unlisted ask site to untyped", async () => {
  1119. // 站点表与 schema 合成来自同一次编译,所以 miss 只可能是接线错误。旧的
  1120. // `?? { typed: false }` 兜底会把 typed ask 静默降级:不注册 submit_result、
  1121. // 拿末轮文本当结果、schema 校验整个消失——「结果永远合法」的类型系统比没有更糟。
  1122. const { engine, driver } = setup({ askSpecs: typedSpecs(), validate: requireFields });
  1123. const actor = engine.createActor("actor#1");
  1124. const p = engine.ask("ask#2", actor, "unlisted site"); // askSpecs 里只有 ask#1
  1125. await expect(p).rejects.toMatchObject({ code: "MissingAskSpec" });
  1126. await flush();
  1127. // 关键断言:绝不曾以 untyped 形态派发出去。
  1128. expect(driver.startAsks).toEqual([]);
  1129. await expect(engine.settled).resolves.toMatchObject({
  1130. status: "errored",
  1131. error: { code: "MissingAskSpec" },
  1132. });
  1133. });
  1134. });
  1135. describe("WorkflowEngine — world reads", () => {
  1136. it("journals a world.run dispatch under kind world-run (effects are not reads)", async () => {
  1137. // docs/dynamic-workflow/authoring.md「Running commands: `world.run`」:op "run" 与其余 world-read
  1138. // 机制同构,但落 journal 的 kind 是 world-run——审计面不把效应伪装成读。
  1139. const { engine, driver, journal } = setup();
  1140. const p = engine.worldRead("world-read#1", "run", ["lean", ["a.lean"], { timeoutMs: 60000 }]);
  1141. expect(driver.worldReads[0]?.op).toBe("run");
  1142. driver.worldReads[0]?.deferred.resolve({ exitCode: 1, stdout: "", stderr: "boom" });
  1143. await expect(p).resolves.toEqual({ exitCode: 1, stdout: "", stderr: "boom" });
  1144. const node = journal.getNode(RUN, "world-read#1", 1);
  1145. expect(node?.kind).toBe("world-run");
  1146. expect(node?.inputHash).toBe(
  1147. inputHash({ op: "run", args: ["lean", ["a.lean"], { timeoutMs: 60000 }] }),
  1148. );
  1149. // 事件流的 node-queued 同样携带 world-run。
  1150. const queued = driver.events.find(
  1151. (event) => event.type === "node-queued" && event.instance.siteId === "world-read#1",
  1152. );
  1153. expect(queued !== undefined && queued.type === "node-queued" ? queued.kind : undefined).toBe(
  1154. "world-run",
  1155. );
  1156. });
  1157. it("dispatches a live world read, journals it, and resolves", async () => {
  1158. const { engine, driver, journal } = setup();
  1159. const p = engine.worldRead("world-read#1", "glob", ["src/**"]);
  1160. expect(driver.worldReads).toHaveLength(1);
  1161. // 实参按位置原样送到 driver(引擎不看 op、不校验元数)。
  1162. expect(driver.worldReads[0]?.args).toEqual(["src/**"]);
  1163. driver.worldReads[0]?.deferred.resolve(["a.ts", "b.ts"]);
  1164. await expect(p).resolves.toEqual(["a.ts", "b.ts"]);
  1165. const node = journal.getNode(RUN, "world-read#1", 1);
  1166. expect(node?.kind).toBe("world-read");
  1167. expect(node?.result).toEqual(["a.ts", "b.ts"]);
  1168. // inputHash 覆盖 {op, args}(此前是 {op, arg}):载荷形变是有意的,早于此的 journal
  1169. // 会在第一个 world-read 命中处以 InputHashMismatch 大声失败(见 engine.worldRead 的注释)。
  1170. expect(node?.inputHash).toBe(inputHash({ op: "glob", args: ["src/**"] }));
  1171. expect(node?.actorSeq).toBeUndefined();
  1172. });
  1173. it("hashes multi-argument world reads positionally (arg order is part of identity)", async () => {
  1174. const { engine, driver, journal } = setup();
  1175. // 用 glob 承载一个多参调用:引擎对 args 完全不解释,所以这条断言钉的是"位置数组进 hash",
  1176. // 而不是某个 op 的元数(元数归 driver)。
  1177. const p = engine.worldRead("world-read#1", "glob", ["a", "b"]);
  1178. expect(driver.worldReads[0]?.args).toEqual(["a", "b"]);
  1179. driver.worldReads[0]?.deferred.resolve(["hit"]);
  1180. await expect(p).resolves.toEqual(["hit"]);
  1181. expect(journal.getNode(RUN, "world-read#1", 1)?.inputHash).toBe(
  1182. inputHash({ op: "glob", args: ["a", "b"] }),
  1183. );
  1184. // 顺序敏感:交换实参就是另一次读取。
  1185. expect(inputHash({ op: "glob", args: ["a", "b"] })).not.toBe(
  1186. inputHash({ op: "glob", args: ["b", "a"] }),
  1187. );
  1188. });
  1189. it("short-circuits a journaled world read with zero driver calls", async () => {
  1190. const journal = new InMemoryJournalStore();
  1191. journal.createRun({
  1192. runId: RUN,
  1193. caps: { maxConcurrency: 16 },
  1194. spentTokens: 0,
  1195. status: "running",
  1196. });
  1197. journal.putNode({
  1198. runId: RUN,
  1199. siteId: "world-read#1",
  1200. ordinal: 1,
  1201. kind: "world-read",
  1202. inputHash: inputHash({ op: "glob", args: ["src/**"] }),
  1203. status: "completed",
  1204. result: ["x.ts"],
  1205. });
  1206. const { engine, driver } = setup({ journal });
  1207. const p = engine.worldRead("world-read#1", "glob", ["src/**"]);
  1208. expect(driver.worldReads).toHaveLength(0);
  1209. await expect(p).resolves.toEqual(["x.ts"]);
  1210. });
  1211. it("fails the run loudly when a journaled world read's args differ (arity/value change)", async () => {
  1212. const journal = new InMemoryJournalStore();
  1213. journal.createRun({
  1214. runId: RUN,
  1215. caps: { maxConcurrency: 16 },
  1216. spentTokens: 0,
  1217. status: "running",
  1218. });
  1219. journal.putNode({
  1220. runId: RUN,
  1221. siteId: "world-read#1",
  1222. ordinal: 1,
  1223. kind: "world-read",
  1224. inputHash: inputHash({ op: "glob", args: ["src/**"] }),
  1225. status: "completed",
  1226. result: ["x.ts"],
  1227. });
  1228. const { engine } = setup({ journal });
  1229. // 同 op、实参不同:纯度契约被破坏,整个 run 大声失败而不是返回旧结果。
  1230. await expect(
  1231. engine.worldRead("world-read#1", "glob", ["src/**", "extra"]),
  1232. ).rejects.toMatchObject({
  1233. code: "InputHashMismatch",
  1234. });
  1235. expect(journal.getRun(RUN)?.status).toBe("errored");
  1236. });
  1237. it("journals a multi-arg op's inputHash over {op, args} and short-circuits its replay", async () => {
  1238. // 多参 op 的完整往返:`files.grep(pattern, glob?)` 的 args 是位置数组,键就是
  1239. // `{op, args}`。第二段证明 replay 命中零 driver 调用——journal 化世界读取正是这样让
  1240. // resume 免疫于 run 与 resume 之间的磁盘变化。
  1241. const hits = [{ path: "src/a.ts", line: 12, text: "// TODO" }];
  1242. const journal = new InMemoryJournalStore();
  1243. journal.createRun({
  1244. runId: RUN,
  1245. caps: { maxConcurrency: 16 },
  1246. spentTokens: 0,
  1247. status: "running",
  1248. });
  1249. const live = setup({ journal });
  1250. const p = live.engine.worldRead("world-read#1", "grep", ["TODO", "*.ts"]);
  1251. expect(live.driver.worldReads[0]?.op).toBe("grep");
  1252. expect(live.driver.worldReads[0]?.args).toEqual(["TODO", "*.ts"]);
  1253. live.driver.worldReads[0]?.deferred.resolve(hits);
  1254. await expect(p).resolves.toEqual(hits);
  1255. expect(journal.getNode(RUN, "world-read#1", 1)?.inputHash).toBe(
  1256. inputHash({ op: "grep", args: ["TODO", "*.ts"] }),
  1257. );
  1258. // Replay over the same journal: hit, no dispatch.
  1259. const replay = setup({ journal });
  1260. const replayed = replay.engine.worldRead("world-read#1", "grep", ["TODO", "*.ts"]);
  1261. expect(replay.driver.worldReads).toHaveLength(0);
  1262. await expect(replayed).resolves.toEqual(hits);
  1263. });
  1264. it("distinguishes an omitted trailing optional from a present one (shorter args array)", async () => {
  1265. // `grep("TODO")` 与 `grep("TODO", "*.ts")` 必须是两个不同的 journal 键。lowering 在
  1266. // 缺省时打包**更短的数组**(不是 undefined 洞),而 canonicalJson 让长度进 hash,所以
  1267. // 这条性质是自动的——钉住它是因为一旦丢掉,一次"加了 glob 的 grep"会命中一次
  1268. // "没加 glob 的 grep"的记录,而故障点在 resume,离原因很远。
  1269. expect(inputHash({ op: "grep", args: ["TODO"] })).not.toBe(
  1270. inputHash({ op: "grep", args: ["TODO", "*.ts"] }),
  1271. );
  1272. const journal = new InMemoryJournalStore();
  1273. journal.createRun({
  1274. runId: RUN,
  1275. caps: { maxConcurrency: 16 },
  1276. spentTokens: 0,
  1277. status: "running",
  1278. });
  1279. journal.putNode({
  1280. runId: RUN,
  1281. siteId: "world-read#1",
  1282. ordinal: 1,
  1283. kind: "world-read",
  1284. inputHash: inputHash({ op: "grep", args: ["TODO"] }),
  1285. status: "completed",
  1286. result: [],
  1287. });
  1288. const { engine } = setup({ journal });
  1289. await expect(engine.worldRead("world-read#1", "grep", ["TODO", "*.ts"])).rejects.toMatchObject({
  1290. code: "InputHashMismatch",
  1291. });
  1292. });
  1293. it("settles the node failed on a driver WorldReadCapExceeded, keeping the run alive", async () => {
  1294. // 上限溢出是 **node 级**:脚本可以 catch 它并缩窄 pattern,所以 run 必须还活着,
  1295. // 而且这个码绝不能被折成 DriverError——两者的可操作性不同(见 WorkflowErrorCode 注释)。
  1296. const { engine, driver, journal } = setup();
  1297. const p = engine.worldRead("world-read#1", "grep", [".", undefined]);
  1298. driver.worldReads[0]?.deferred.reject(
  1299. new WorkflowError(
  1300. "WorldReadCapExceeded",
  1301. "grep 命中超过 2000 条;请缩窄 pattern 或加一个 glob",
  1302. ),
  1303. );
  1304. await expect(p).rejects.toMatchObject({ code: "WorldReadCapExceeded" });
  1305. const node = journal.getNode(RUN, "world-read#1", 1);
  1306. expect(node?.status).toBe("failed");
  1307. expect(node?.error?.code).toBe("WorldReadCapExceeded");
  1308. // run 未被这次拒绝拖死;脚本可以继续(这才是 node 级的意义)。
  1309. expect(journal.getRun(RUN)?.status).toBe("running");
  1310. });
  1311. it("replays a journaled cap failure as the same structured rejection", async () => {
  1312. // 失败节点也落 journal(replay 可靠性要求:脚本可能已经观察过这次拒绝并据此分支)。
  1313. const journal = new InMemoryJournalStore();
  1314. journal.createRun({
  1315. runId: RUN,
  1316. caps: { maxConcurrency: 16 },
  1317. spentTokens: 0,
  1318. status: "running",
  1319. });
  1320. journal.putNode({
  1321. runId: RUN,
  1322. siteId: "world-read#1",
  1323. ordinal: 1,
  1324. kind: "world-read",
  1325. inputHash: inputHash({ op: "git-diff", args: [] }),
  1326. status: "failed",
  1327. error: { code: "WorldReadCapExceeded", message: "git.diff 超过 512KB" },
  1328. });
  1329. const { engine, driver } = setup({ journal });
  1330. await expect(engine.worldRead("world-read#1", "git-diff", [])).rejects.toMatchObject({
  1331. code: "WorldReadCapExceeded",
  1332. });
  1333. expect(driver.worldReads).toHaveLength(0);
  1334. });
  1335. });
  1336. describe("WorkflowEngine — lenient submit decode (real-model stringifies tool args)", () => {
  1337. // 用真实子集校验器:这些场景要真正的类型判定(object/number/anyOf),fake 的 required-only
  1338. // 校验器表达不了。真实模型(实盘 GLM-5.3)常把 submit_result 的 result 传成 JSON 字符串而非对象,
  1339. // 引擎需 schema-aware 地宽松解析——见 scheduler.normalizeSubmit。
  1340. const realValidate: ValidateFn = (schema, value) => validate(schema as JsonSchema, value);
  1341. const objectSchema: JsonSchema = {
  1342. type: "object",
  1343. required: ["title", "bullet_points"],
  1344. properties: {
  1345. title: { type: "string" },
  1346. bullet_points: { type: "array", items: { type: "string" } },
  1347. },
  1348. };
  1349. const specs = (schema: JsonSchema) =>
  1350. new Map<string, AskSpec>([["ask#1", { typed: true, schema }]]);
  1351. it("parses a stringified JSON object submit and journals the parsed OBJECT, not the string", async () => {
  1352. const { engine, driver, journal } = setup({
  1353. askSpecs: specs(objectSchema),
  1354. validate: realValidate,
  1355. });
  1356. const actor = engine.createActor("actor#1");
  1357. const p = engine.ask("ask#1", actor, "do it");
  1358. await flush();
  1359. engine.askSubmitAttempted(inst("ask#1"), '{"title":"x","bullet_points":["a"]}');
  1360. expect(driver.submitResponses.at(-1)?.verdict.kind).toBe("accept");
  1361. await expect(p).resolves.toEqual({ title: "x", bullet_points: ["a"] });
  1362. const node = journal.getNode(RUN, "ask#1", 1);
  1363. expect(node?.status).toBe("completed");
  1364. // 落库的是解析后的对象,而非原始字符串。
  1365. expect(node?.result).toEqual({ title: "x", bullet_points: ["a"] });
  1366. expect(typeof node?.result).toBe("object");
  1367. });
  1368. it("repairs when a stringified submit parses to JSON of the wrong shape (not accepted)", async () => {
  1369. const { engine, driver, journal } = setup({
  1370. askSpecs: specs(objectSchema),
  1371. validate: realValidate,
  1372. });
  1373. const actor = engine.createActor("actor#1");
  1374. const p = engine.ask("ask#1", actor, "do it");
  1375. void p.catch(() => {}); // 最终会因 repair 耗尽而 reject
  1376. await flush();
  1377. engine.askSubmitAttempted(inst("ask#1"), '{"unexpected":1}'); // 解析出对象但缺 required 字段
  1378. const last = driver.submitResponses.at(-1)?.verdict;
  1379. expect(last?.kind).toBe("reject");
  1380. expect(last?.kind === "reject" && last.violations.length).toBeGreaterThan(0);
  1381. // 尚未结算:仍是准入时的 running 记录。
  1382. expect(journal.getNode(RUN, "ask#1", 1)?.status).toBe("running");
  1383. });
  1384. it("reports POST-parse violations when a stringified object misses a required field", async () => {
  1385. // bug:JSON.parse 成功但解析值仍不过时,repair 曾上报解析前违规(`$: expected object, got string`),
  1386. // 模型无从修起(再引号/双重编码/退化成 "{}"),3 次后 ValidationFailed 失败(dwfrun-60c20069)。
  1387. const { engine, driver } = setup({ askSpecs: specs(objectSchema), validate: realValidate });
  1388. const actor = engine.createActor("actor#1");
  1389. const p = engine.ask("ask#1", actor, "do it");
  1390. void p.catch(() => {});
  1391. await flush();
  1392. engine.askSubmitAttempted(inst("ask#1"), '{"title":"x"}'); // 解析出对象但缺 bullet_points
  1393. const last = driver.submitResponses.at(-1)?.verdict;
  1394. expect(last?.kind).toBe("reject");
  1395. // 违规必须指向解析后对象的路径,而不是根级「expected object, got string」。
  1396. expect(last?.kind === "reject" && last.violations).toContainEqual({
  1397. path: "$.bullet_points",
  1398. expected: "present",
  1399. got: "missing",
  1400. });
  1401. expect(
  1402. last?.kind === "reject" &&
  1403. last.violations.some((v) => v.path === "$" && v.expected === "object"),
  1404. ).toBe(false);
  1405. });
  1406. it("reports POST-parse violations on the nested path when a stringified array field has wrong item shape", async () => {
  1407. // 镜像实盘 Critique/gaps 失败(dwfrun-bc01726f):schema 要 string[],模型提交嵌套数组,
  1408. // 且整体被序列化成字符串。违规须落在嵌套路径 $.bullet_points[0],而不是根级 string。
  1409. const { engine, driver } = setup({ askSpecs: specs(objectSchema), validate: realValidate });
  1410. const actor = engine.createActor("actor#1");
  1411. const p = engine.ask("ask#1", actor, "do it");
  1412. void p.catch(() => {});
  1413. await flush();
  1414. engine.askSubmitAttempted(inst("ask#1"), '{"title":"x","bullet_points":[["a"]]}');
  1415. const last = driver.submitResponses.at(-1)?.verdict;
  1416. expect(last?.kind).toBe("reject");
  1417. expect(last?.kind === "reject" && last.violations).toContainEqual({
  1418. path: "$.bullet_points[0]",
  1419. expected: "string",
  1420. got: "array(1)",
  1421. });
  1422. expect(
  1423. last?.kind === "reject" &&
  1424. last.violations.some((v) => v.path === "$" && v.expected === "object"),
  1425. ).toBe(false);
  1426. });
  1427. it("repairs on a non-JSON string submit (JSON.parse throws → original violations)", async () => {
  1428. const { engine, driver, journal } = setup({
  1429. askSpecs: specs(objectSchema),
  1430. validate: realValidate,
  1431. });
  1432. const actor = engine.createActor("actor#1");
  1433. const p = engine.ask("ask#1", actor, "do it");
  1434. void p.catch(() => {});
  1435. await flush();
  1436. engine.askSubmitAttempted(inst("ask#1"), "hello"); // JSON.parse 抛出
  1437. const last = driver.submitResponses.at(-1)?.verdict;
  1438. expect(last?.kind).toBe("reject");
  1439. // 报的是原始 raw-value 违规(object 期望却拿到 string)。
  1440. expect(last?.kind === "reject" && last.violations.some((v) => v.expected === "object")).toBe(
  1441. true,
  1442. );
  1443. expect(journal.getNode(RUN, "ask#1", 1)?.status).toBe("running");
  1444. });
  1445. it("preserves a legitimately-string result: raw string that validates is NOT parsed", async () => {
  1446. // anyOf string|null 接受裸字符串 → 直接过 → 不解析。"42" 必须留 "42",绝不变成数字 42。
  1447. const stringSchema: JsonSchema = { anyOf: [{ type: "string" }, { type: "null" }] };
  1448. const { engine, driver, journal } = setup({
  1449. askSpecs: specs(stringSchema),
  1450. validate: realValidate,
  1451. });
  1452. const actor = engine.createActor("actor#1");
  1453. const p = engine.ask("ask#1", actor, "do it");
  1454. await flush();
  1455. engine.askSubmitAttempted(inst("ask#1"), "42");
  1456. expect(driver.submitResponses.at(-1)?.verdict.kind).toBe("accept");
  1457. await expect(p).resolves.toBe("42");
  1458. const node = journal.getNode(RUN, "ask#1", 1);
  1459. expect(node?.result).toBe("42");
  1460. expect(typeof node?.result).toBe("string");
  1461. });
  1462. it("parses a number-string when the schema expects a number", async () => {
  1463. const numberSchema: JsonSchema = { type: "number" };
  1464. const { engine, driver, journal } = setup({
  1465. askSpecs: specs(numberSchema),
  1466. validate: realValidate,
  1467. });
  1468. const actor = engine.createActor("actor#1");
  1469. const p = engine.ask("ask#1", actor, "do it");
  1470. await flush();
  1471. engine.askSubmitAttempted(inst("ask#1"), "42");
  1472. expect(driver.submitResponses.at(-1)?.verdict.kind).toBe("accept");
  1473. await expect(p).resolves.toBe(42);
  1474. const node = journal.getNode(RUN, "ask#1", 1);
  1475. expect(node?.result).toBe(42);
  1476. expect(typeof node?.result).toBe("number");
  1477. });
  1478. });
  1479. // report(execution-engine.md 的 "Progressive results"):即发即忘、无 driver 往返,但**落 journal**。
  1480. // 这一组钉住三件事:一次写的节点形状、replay 去重、两个上限。
  1481. describe("WorkflowEngine — report", () => {
  1482. it("journals one already-settled node and emits one event", () => {
  1483. const { engine, journal, driver } = setup();
  1484. engine.report("report#1", { finding: "dup impl", paths: ["a.ts", "b.ts"] });
  1485. const node = journal.getNode(RUN, "report#1", 1);
  1486. // 一次写、已结算、无 actor 字段、result 即 item——「两次写」规则唯一的例外。
  1487. expect(node).toMatchObject({
  1488. kind: "report",
  1489. status: "completed",
  1490. result: { finding: "dup impl", paths: ["a.ts", "b.ts"] },
  1491. });
  1492. expect(node?.inputHash).toBe(inputHash({ finding: "dup impl", paths: ["a.ts", "b.ts"] }));
  1493. expect(node !== undefined && "actorSeq" in node).toBe(false);
  1494. expect(driver.eventsOfType("report")).toEqual([
  1495. {
  1496. type: "report",
  1497. instance: inst("report#1"),
  1498. item: { finding: "dup impl", paths: ["a.ts", "b.ts"] },
  1499. },
  1500. ]);
  1501. });
  1502. it("assigns per-site ordinals so one site reported twice is two nodes", () => {
  1503. const { engine, journal, driver } = setup();
  1504. engine.report("report#1", "first");
  1505. engine.report("report#1", "second");
  1506. engine.report("report#2", "other-site");
  1507. expect(journal.getNode(RUN, "report#1", 1)?.result).toBe("first");
  1508. expect(journal.getNode(RUN, "report#1", 2)?.result).toBe("second");
  1509. expect(journal.getNode(RUN, "report#2", 1)?.result).toBe("other-site");
  1510. expect(driver.eventsOfType("report")).toHaveLength(3);
  1511. });
  1512. it("ignores reports after the run settles (like log)", () => {
  1513. const { engine, journal, driver } = setup();
  1514. engine.complete("done");
  1515. engine.report("report#1", "too late");
  1516. expect(journal.getNode(RUN, "report#1", 1)).toBeUndefined();
  1517. expect(driver.eventsOfType("report")).toEqual([]);
  1518. });
  1519. it("skips a journaled report on replay: no event, no re-append", () => {
  1520. // 脚本重跑,所以每个 report 调用都会再执行一次。已 journal 的 (siteId, ordinal) 静默跳过——
  1521. // 否则 resume 之后 Results 面板会把同一条发现显示两次,而那正是 report 要 journal 的理由。
  1522. const journal = new InMemoryJournalStore();
  1523. const first = setup({ journal });
  1524. first.engine.report("report#1", { n: 1 });
  1525. first.engine.report("report#1", { n: 2 });
  1526. first.engine.complete("ok");
  1527. const before = journal.listEvents(RUN, { types: "all", reportItems: "all" }).length;
  1528. const resumed = setup({ journal });
  1529. resumed.engine.report("report#1", { n: 1 });
  1530. resumed.engine.report("report#1", { n: 2 });
  1531. expect(resumed.driver.eventsOfType("report")).toEqual([]);
  1532. expect(journal.getRun(RUN)?.status).toBe("running");
  1533. expect(
  1534. journal.listNodes(RUN, { kinds: "all", withResult: true }).filter((n) => n.kind === "report"),
  1535. ).toHaveLength(2);
  1536. // resume 只多出一条 run-started,report 一条事件都没再 append。
  1537. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" }).length).toBe(before + 1);
  1538. });
  1539. it("fails the run with InputHashMismatch when a replayed item differs", () => {
  1540. // 这条比对是**防御性的**(一条报告派生自 journal 已钉住的值),但这里的偏移意味着整个
  1541. // replay 不可靠——Results 面板的读者绝不该在不知情的情况下看到那种东西。
  1542. const journal = new InMemoryJournalStore();
  1543. setup({ journal }).engine.report("report#1", { n: 1 });
  1544. const resumed = setup({ journal });
  1545. resumed.engine.report("report#1", { n: 999 });
  1546. return expect(resumed.engine.settled).resolves.toMatchObject({
  1547. status: "errored",
  1548. error: { code: "InputHashMismatch" },
  1549. });
  1550. });
  1551. it("hashes canonically, so key order in the item is not a mismatch", () => {
  1552. // inputHash 走 canonicalJson(键按 code point 排序),所以脚本里字面量键序变化不会
  1553. // 被当成纯度违约。这是"防御性而非承重"该有的松紧度。
  1554. const journal = new InMemoryJournalStore();
  1555. setup({ journal }).engine.report("report#1", { a: 1, b: 2 });
  1556. const resumed = setup({ journal });
  1557. resumed.engine.report("report#1", { b: 2, a: 1 });
  1558. expect(resumed.driver.eventsOfType("report")).toEqual([]);
  1559. expect(journal.getRun(RUN)?.status).toBe("running");
  1560. });
  1561. it("fails the run with ReportCapExceeded on the item past the cap (65,537th)", () => {
  1562. const { engine, journal } = setup();
  1563. expect(REPORT_CAPS.maxItemsPerRun).toBe(65_536);
  1564. for (let i = 0; i < REPORT_CAPS.maxItemsPerRun; i += 1) engine.report("report#1", i);
  1565. expect(journal.getRun(RUN)?.status).toBe("running");
  1566. engine.report("report#1", "one too many");
  1567. expect(journal.countNodes(RUN, "report")).toBe(REPORT_CAPS.maxItemsPerRun);
  1568. return expect(engine.settled).resolves.toMatchObject({
  1569. status: "errored",
  1570. error: { code: "ReportCapExceeded" },
  1571. });
  1572. });
  1573. it("fails the run with ReportCapExceeded on an oversized item, journaling nothing", () => {
  1574. const { engine, journal } = setup();
  1575. engine.report("report#1", "x".repeat(REPORT_CAPS.maxItemSerializedBytes));
  1576. // 上限先于落库:溢出的那条 item 一个字节都不该进 journal。
  1577. expect(journal.getNode(RUN, "report#1", 1)).toBeUndefined();
  1578. return expect(engine.settled).resolves.toMatchObject({
  1579. status: "errored",
  1580. error: { code: "ReportCapExceeded" },
  1581. });
  1582. });
  1583. it("accepts an item of exactly the per-item limit", () => {
  1584. const { engine, journal } = setup();
  1585. expect(REPORT_CAPS.maxItemSerializedBytes).toBe(1024 * 1024);
  1586. // JSON 的两个引号也算在字节里:正文少两个字节,序列化后恰好等于上限。
  1587. engine.report("report#1", "x".repeat(REPORT_CAPS.maxItemSerializedBytes - 2));
  1588. expect(journal.getNode(RUN, "report#1", 1)?.status).toBe("completed");
  1589. expect(journal.getRun(RUN)?.status).toBe("running");
  1590. });
  1591. it("fails the run with ReportCapExceeded when its reports would pass the per-run byte limit, counted across resume", () => {
  1592. // 一个真正攒满 1 GiB 的 run 在单测里造不起,所以让 journal 在 resume 时报一个接近上限的
  1593. // 字节和:这同时钉住两件事——计数从 sumResultBytes 恢复,以及上限按 run 累计、拦在落库之前。
  1594. const nearlyFull = REPORT_CAPS.maxBytesPerRun - 50;
  1595. class NearlyFullJournal extends InMemoryJournalStore {
  1596. override sumResultBytes(runId: string, kind: NodeKind): number {
  1597. return super.sumResultBytes(runId, kind) + nearlyFull;
  1598. }
  1599. }
  1600. const journal = new NearlyFullJournal();
  1601. const first = setup({ journal });
  1602. first.engine.report("report#1", "a"); // 3 字节,第一世不读 sumResultBytes
  1603. first.engine.stop("user");
  1604. const resumed = setup({ journal });
  1605. resumed.engine.report("report#1", "a"); // 命中,跳过
  1606. // 3 + nearlyFull + 42 = 上限 - 5:放得下。
  1607. resumed.engine.report("report#1", "x".repeat(40));
  1608. expect(journal.getRun(RUN)?.status).toBe("running");
  1609. // 再来 10 字节就超过:整个 run 失败,这一条不落库。
  1610. resumed.engine.report("report#1", "y".repeat(8));
  1611. expect(journal.countNodes(RUN, "report")).toBe(2);
  1612. return expect(resumed.engine.settled).resolves.toMatchObject({
  1613. status: "errored",
  1614. error: { code: "ReportCapExceeded", message: expect.stringContaining("limit per run") },
  1615. });
  1616. });
  1617. it("measures the cap in UTF-8 bytes, not characters", () => {
  1618. // 一份中文 findings 的字符数只有字节数的三分之一;按字符计会让上限形同虚设。
  1619. const { engine, journal } = setup();
  1620. // 每个字符 3 字节,加上 JSON 的两个引号:刚好越界。
  1621. const chars = Math.ceil(REPORT_CAPS.maxItemSerializedBytes / 3);
  1622. engine.report("report#1", "结".repeat(chars));
  1623. expect(journal.getNode(RUN, "report#1", 1)).toBeUndefined();
  1624. return expect(engine.settled).resolves.toMatchObject({
  1625. status: "errored",
  1626. error: { code: "ReportCapExceeded" },
  1627. });
  1628. });
  1629. it("restores the report count across resume so the cap is run-level", () => {
  1630. // 上限是 run 级的,所以计数必须跨 resume 连续——否则一个反复 resume 的 run 可以无限报告。
  1631. const journal = new InMemoryJournalStore();
  1632. const first = setup({ journal });
  1633. for (let i = 0; i < REPORT_CAPS.maxItemsPerRun; i += 1) first.engine.report("report#1", i);
  1634. first.engine.stop("user");
  1635. // resume:脚本重跑,前 65,536 条全部命中并跳过,下一条是**新**的——上限必须仍然拦住它。
  1636. const resumed = setup({ journal });
  1637. for (let i = 0; i < REPORT_CAPS.maxItemsPerRun; i += 1) resumed.engine.report("report#1", i);
  1638. expect(resumed.driver.eventsOfType("report")).toEqual([]);
  1639. resumed.engine.report("report#1", "one past the cap");
  1640. return expect(resumed.engine.settled).resolves.toMatchObject({
  1641. status: "errored",
  1642. error: { code: "ReportCapExceeded" },
  1643. });
  1644. });
  1645. it("fails the run loudly when the item is not a JSON value", () => {
  1646. // 运行期护栏(编译期的可序列化诊断是 suspenders)。canonicalJson 是全函数的——它会把
  1647. // undefined 静默折成 "null",那会把一条残缺的 item 悄悄落进 journal。所以探针用
  1648. // JSON.stringify:返回 undefined / 抛错都能被抓成一次大声的失败。
  1649. const { engine, journal } = setup();
  1650. engine.report("report#1", undefined);
  1651. expect(journal.getNode(RUN, "report#1", 1)).toBeUndefined();
  1652. return expect(engine.settled).resolves.toMatchObject({ status: "errored" });
  1653. });
  1654. it("fails the run loudly on a cyclic item instead of blowing the stack", () => {
  1655. // canonicalJson 遇到环会无限递归爆栈——那是一次崩溃而不是一次可读的失败,所以探针
  1656. // 必须先跑。这条用例就是那个顺序的证明。
  1657. const { engine, journal } = setup();
  1658. const cyclic: Record<string, unknown> = { name: "loop" };
  1659. cyclic.self = cyclic;
  1660. expect(() => engine.report("report#1", cyclic)).not.toThrow();
  1661. expect(journal.getNode(RUN, "report#1", 1)).toBeUndefined();
  1662. return expect(engine.settled).resolves.toMatchObject({
  1663. status: "errored",
  1664. error: { code: "DriverError" },
  1665. });
  1666. });
  1667. });
  1668. // enterPhase(docs/dynamic-workflow/presentation.md):控制流经过一个
  1669. // `phase("…")` 标记。与 log 同一副姿态——同步、无 driver 往返、结算后 no-op——但按名字计数。
  1670. describe("WorkflowEngine — enterPhase", () => {
  1671. it("emits phase-entered with a per-name ordinal and writes no journal row", () => {
  1672. const { engine, journal, driver } = setup();
  1673. engine.enterPhase("plan");
  1674. engine.enterPhase("verify");
  1675. engine.enterPhase("plan");
  1676. expect(driver.eventsOfType("phase-entered")).toEqual([
  1677. { type: "phase-entered", name: "plan", ordinal: 1 },
  1678. { type: "phase-entered", name: "verify", ordinal: 1 },
  1679. // 同名再入就是第二轮:分析器也把第二个同名标记读成回边。
  1680. { type: "phase-entered", name: "plan", ordinal: 2 },
  1681. ]);
  1682. // 标记不是站点:没有 dwf_node 行,也不消耗任何站点的序号。
  1683. expect(journal.listNodes(RUN, { kinds: "all", withResult: true })).toEqual([]);
  1684. });
  1685. it("trims the name, drops an empty one, and does not share ordinals with sites", () => {
  1686. const { engine, driver } = setup();
  1687. engine.enterPhase(" plan ");
  1688. engine.enterPhase(" ");
  1689. engine.report("report#1", "x");
  1690. engine.enterPhase("report#1");
  1691. expect(driver.eventsOfType("phase-entered")).toEqual([
  1692. { type: "phase-entered", name: "plan", ordinal: 1 },
  1693. // 一个恰好长得像 site id 的阶段名:它的计数从 1 起,report#1 的节点序号不受影响。
  1694. { type: "phase-entered", name: "report#1", ordinal: 1 },
  1695. ]);
  1696. });
  1697. it("is a no-op after the run settled", () => {
  1698. const { engine, driver } = setup();
  1699. engine.complete("done");
  1700. engine.enterPhase("late");
  1701. expect(driver.eventsOfType("phase-entered")).toEqual([]);
  1702. });
  1703. });
  1704. /**
  1705. * 一层薄包装:把 `appendEvent` 收到的**原始对象**留下引用(内存 journal 自己会 clone,
  1706. * 存进去的那份已经不是引擎传的那个)。用于钉住「journal 与 emit 拿到同一个对象」——
  1707. * bootstrap 的 createJournalSequenceCapture 正是按引用相等核对序号的。
  1708. */
  1709. class CapturingJournal extends InMemoryJournalStore {
  1710. readonly appended: RunEvent[] = [];
  1711. override appendEvent(runId: string, event: RunEvent): StoredEvent {
  1712. this.appended.push(event);
  1713. return super.appendEvent(runId, event);
  1714. }
  1715. }
  1716. // 出生阶段坐标(docs/dynamic-workflow/presentation.md):实例在**铸造
  1717. // ordinal 的那一刻**记下当时的阶段,出生事件带 `phaseName`。铸造点与事件发出点可以隔开
  1718. // (hold 规则),所以戳只能取自铸造那一刻。
  1719. describe("WorkflowEngine — 出生阶段坐标(phaseName)", () => {
  1720. it("stamps the actor and the nodes minted after a phase marker", async () => {
  1721. const { engine, driver } = setup();
  1722. engine.enterPhase("规划");
  1723. const actor = engine.createActor("actor#1", "planner");
  1724. void engine.ask("ask#1", actor, "do it");
  1725. void engine.worldRead("world-read#1", "glob", ["src/**"]);
  1726. await flush();
  1727. expect(driver.eventsOfType("actor-created")[0]).toMatchObject({ phaseName: "规划" });
  1728. // ask 与 world-read 走两条不同的准入路径(调度器 / 引擎自己),戳都出自同一个铸造点。
  1729. expect(
  1730. driver.eventsOfType("node-queued").map((e) => [refToString(e.instance), e.phaseName]),
  1731. ).toEqual([
  1732. ["ask#1@1", "规划"],
  1733. ["world-read#1@1", "规划"],
  1734. ]);
  1735. });
  1736. it("leaves instances born before any marker unstamped", async () => {
  1737. const { engine, driver } = setup();
  1738. const actor = engine.createActor("actor#1");
  1739. void engine.ask("ask#1", actor, "do it");
  1740. engine.enterPhase("规划");
  1741. await flush();
  1742. // 「无戳」是键整个缺席,不是 undefined:读端(schema / reducer)区分这两者。
  1743. expect(driver.eventsOfType("actor-created")[0]).not.toHaveProperty("phaseName");
  1744. expect(driver.eventsOfType("node-queued")[0]).not.toHaveProperty("phaseName");
  1745. });
  1746. it("carries the birth phase even when the queue event lands after a later marker", async () => {
  1747. const journal = new InMemoryJournalStore();
  1748. journal.createRun({
  1749. runId: RUN,
  1750. caps: { maxConcurrency: 16 },
  1751. spentTokens: 0,
  1752. status: "running",
  1753. });
  1754. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  1755. // 前一世只记下 seq0 = ask#2@1。本次重跑先发的 ask#1 是 fresh,被 hold 规则扣住,
  1756. // 直到 seq0 被释放才入队——那时控制流已经走到 B 了。
  1757. journal.putNode({
  1758. runId: RUN,
  1759. siteId: "ask#2",
  1760. ordinal: 1,
  1761. kind: "ask",
  1762. actorSiteId: "actor#1",
  1763. actorOrdinal: 1,
  1764. actorSeq: 0,
  1765. inputHash: inputHash("B"),
  1766. status: "completed",
  1767. result: "r2",
  1768. });
  1769. const { engine, driver } = setup({ journal });
  1770. const actor = engine.createActor("actor#1");
  1771. engine.enterPhase("A");
  1772. const pA = engine.ask("ask#1", actor, "A"); // ordinal 铸于 A,但没有入队
  1773. expect(driver.eventsOfType("node-queued")).toEqual([]);
  1774. engine.enterPhase("B");
  1775. const pB = engine.ask("ask#2", actor, "B"); // 命中 seq0 → 释放它,随后才轮到 ask#1
  1776. await flush();
  1777. const queued = driver.eventsOfType("node-queued");
  1778. expect(queued).toHaveLength(1);
  1779. expect(refToString(queued[0]!.instance)).toBe("ask#1@1");
  1780. // 事件晚于 B 的标记发出,戳仍是出生时的 A:戳取自铸造点,不是发出点。
  1781. expect(driver.events.indexOf(queued[0]!)).toBeGreaterThan(
  1782. driver.events.findIndex((e) => e.type === "phase-entered" && e.name === "B"),
  1783. );
  1784. expect(queued[0]!.phaseName).toBe("A");
  1785. // 同一次重跑里出生于 B 的命中节点,戳是 B。
  1786. expect(driver.eventsOfType("node-settled")[0]).toMatchObject({
  1787. cached: true,
  1788. phaseName: "B",
  1789. });
  1790. engine.askTurnEnded(inst("ask#1"), "RA");
  1791. await expect(Promise.all([pA, pB])).resolves.toEqual(["RA", "r2"]);
  1792. });
  1793. it("stamps a replay-cached node-settled with the phase current at that point of the re-run", async () => {
  1794. const journal = new InMemoryJournalStore();
  1795. journal.createRun({
  1796. runId: RUN,
  1797. caps: { maxConcurrency: 16 },
  1798. spentTokens: 0,
  1799. status: "running",
  1800. });
  1801. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  1802. journal.putNode({
  1803. runId: RUN,
  1804. siteId: "ask#1",
  1805. ordinal: 1,
  1806. kind: "ask",
  1807. actorSiteId: "actor#1",
  1808. actorOrdinal: 1,
  1809. actorSeq: 0,
  1810. inputHash: inputHash("A"),
  1811. status: "completed",
  1812. result: "r1",
  1813. });
  1814. const { engine, driver } = setup({ journal });
  1815. // 重跑沿同一轨迹重走标记,于是命中的节点在这一世拿到与前一世相同的戳。
  1816. engine.enterPhase("规划");
  1817. const actor = engine.createActor("actor#1");
  1818. await expect(engine.ask("ask#1", actor, "A")).resolves.toBe("r1");
  1819. expect(driver.startAskCount()).toBe(0);
  1820. expect(driver.eventsOfType("actor-created")[0]).toMatchObject({ phaseName: "规划" });
  1821. // 命中的节点没有 node-queued,这条 cached settle 就是它的出生事件。
  1822. expect(driver.eventsOfType("node-queued")).toEqual([]);
  1823. expect(driver.eventsOfType("node-settled")[0]).toMatchObject({
  1824. cached: true,
  1825. phaseName: "规划",
  1826. });
  1827. });
  1828. it("a replayed ask's cached node-settled repeats its birth facts and names no predecessor session", async () => {
  1829. // 普通 resume(没有导入缓存):命中的行是本 run 自己跑出来的,交换在本 run 的会话里,
  1830. // 所以不带 sourceSessionId;出生事实照带——读面据它把节点归到子代理名下
  1831. // (docs/execution-engine.md「Events」)。失败的行同样短路复现,也同样带。
  1832. const journal = new InMemoryJournalStore();
  1833. journal.createRun({
  1834. runId: RUN,
  1835. caps: { maxConcurrency: 16 },
  1836. spentTokens: 0,
  1837. status: "running",
  1838. });
  1839. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  1840. const row = (siteId: string, seq: number, instructions: string): NodeRecord => ({
  1841. runId: RUN,
  1842. siteId,
  1843. ordinal: 1,
  1844. kind: "ask",
  1845. actorSiteId: "actor#1",
  1846. actorOrdinal: 1,
  1847. actorSeq: seq,
  1848. inputHash: inputHash(instructions),
  1849. status: "completed",
  1850. result: `r-${siteId}`,
  1851. });
  1852. journal.putNode(row("ask#1", 0, "first task"));
  1853. journal.putNode({
  1854. ...row("ask#2", 1, "second task"),
  1855. status: "failed",
  1856. error: new WorkflowError("DriverError", "boom").toJSON(),
  1857. });
  1858. const { engine, driver } = setup({ journal });
  1859. const actor = engine.createActor("actor#1");
  1860. await expect(engine.ask("ask#1", actor, "first task")).resolves.toBe("r-ask#1");
  1861. await expect(engine.ask("ask#2", actor, "second task")).rejects.toMatchObject({
  1862. code: "DriverError",
  1863. });
  1864. expect(driver.startAskCount()).toBe(0);
  1865. const facts = { kind: "ask", actor: { siteId: "actor#1", ordinal: 1 } };
  1866. expect(driver.eventsOfType("node-settled")).toEqual([
  1867. {
  1868. type: "node-settled",
  1869. instance: { siteId: "ask#1", ordinal: 1 },
  1870. outcome: "ok",
  1871. cached: true,
  1872. ...facts,
  1873. actorSeq: 0,
  1874. instructionsHead: "first task",
  1875. },
  1876. {
  1877. type: "node-settled",
  1878. instance: { siteId: "ask#2", ordinal: 1 },
  1879. outcome: "failed",
  1880. cached: true,
  1881. error: expect.objectContaining({ code: "DriverError" }),
  1882. ...facts,
  1883. actorSeq: 1,
  1884. instructionsHead: "second task",
  1885. },
  1886. ]);
  1887. });
  1888. it("stamps an ask's node-dispatched with its own birth phases, not a live node-settled", async () => {
  1889. const { engine, driver } = setup();
  1890. engine.enterPhase("规划");
  1891. const actor = engine.createActor("actor#1");
  1892. const p = engine.ask("ask#1", actor, "do it");
  1893. await flush();
  1894. engine.askTurnEnded(inst("ask#1"), "RA");
  1895. await expect(p).resolves.toBe("RA");
  1896. // 派发重复出生事实,两个阶段名都在场(各自取自实例 / actor 的铸造点)。
  1897. expect(driver.eventsOfType("node-dispatched")[0]).toMatchObject({
  1898. phaseName: "规划",
  1899. actorPhaseName: "规划",
  1900. });
  1901. // 其余 node-* 事件仍不带(reducer 沿用 actorSiteId 的先例向前携带)。
  1902. expect(driver.eventsOfType("node-settled")[0]).not.toHaveProperty("phaseName");
  1903. });
  1904. it("dispatches with the birth phases even after the script walked into later phases", async () => {
  1905. // 派发被会话创建扣住,其间脚本走过两个标记:戳必须还是出生时的那个,不是当前阶段。
  1906. const { engine, driver } = setup({ deferSessions: true });
  1907. engine.enterPhase("A");
  1908. const actor = engine.createActor("actor#1", "planner");
  1909. const p = engine.ask("ask#1", actor, "do it");
  1910. await flush();
  1911. expect(driver.eventsOfType("node-dispatched")).toEqual([]);
  1912. engine.enterPhase("B");
  1913. engine.enterPhase("C");
  1914. driver.sessionDeferrals[0]!.resolve({ id: "session:actor#1@1" });
  1915. await flush();
  1916. const dispatched = driver.eventsOfType("node-dispatched");
  1917. expect(dispatched).toHaveLength(1);
  1918. expect(dispatched[0]).toMatchObject({ phaseName: "A", actorPhaseName: "A" });
  1919. // 派发确实晚于 C 的标记(否则上面的断言只是恰好成立)。
  1920. expect(driver.events.indexOf(dispatched[0]!)).toBeGreaterThan(
  1921. driver.events.findIndex((e) => e.type === "phase-entered" && e.name === "C"),
  1922. );
  1923. engine.askTurnEnded(inst("ask#1"), "RA");
  1924. await expect(p).resolves.toBe("RA");
  1925. });
  1926. it("leaves the dispatch of an unstamped instance and of a world read bare", async () => {
  1927. const { engine, driver } = setup();
  1928. const actor = engine.createActor("actor#1");
  1929. const p = engine.ask("ask#1", actor, "do it");
  1930. void engine.worldRead("world-read#1", "glob", ["src/**"]);
  1931. // 标记在两个实例出生之后:出生表里没有它们,两条派发都不该长出阶段名。
  1932. engine.enterPhase("规划");
  1933. await flush();
  1934. // world-read 同步派发,ask 要等一轮微任务建会话,所以世界读取在前。
  1935. const dispatched = driver.eventsOfType("node-dispatched");
  1936. expect(dispatched.map((e) => refToString(e.instance))).toEqual(["world-read#1@1", "ask#1@1"]);
  1937. for (const event of dispatched) {
  1938. expect(event).not.toHaveProperty("phaseName");
  1939. expect(event).not.toHaveProperty("actorPhaseName");
  1940. }
  1941. engine.askTurnEnded(inst("ask#1"), "RA");
  1942. await expect(p).resolves.toBe("RA");
  1943. });
  1944. it("hands the journal and the driver the same stamped object", async () => {
  1945. const journal = new CapturingJournal();
  1946. const { engine, driver } = setup({ journal });
  1947. engine.enterPhase("规划");
  1948. const actor = engine.createActor("actor#1");
  1949. void engine.ask("ask#1", actor, "do it");
  1950. await flush();
  1951. expect(journal.appended).toHaveLength(driver.events.length);
  1952. journal.appended.forEach((event, i) => {
  1953. expect(event).toBe(driver.events[i]);
  1954. });
  1955. // 被打戳的那条尤其要是同一个对象:打戳建的是新对象,两条路径必须共用它。
  1956. // 三条:actor-created、node-queued,以及重复出生事实的 node-dispatched。
  1957. expect(journal.appended.filter((e) => "phaseName" in e && e.phaseName === "规划")).toHaveLength(
  1958. 3,
  1959. );
  1960. });
  1961. });
  1962. /**
  1963. * 派发重复出生事实(docs/execution-engine.md「Events」的 `node-dispatched` 行):有界读面按
  1964. * 「开跑」而不是「排队」收实例进表,这条事件因此必须自足——实例的出生事实 + 它那个子代理的。
  1965. */
  1966. describe("WorkflowEngine — node-dispatched 重复出生事实", () => {
  1967. it("repeats exactly what the instance's node-queued and its actor-created carried", async () => {
  1968. const { engine, driver } = setup();
  1969. engine.enterPhase("规划");
  1970. const actor = engine.createActor("actor#1", "planner");
  1971. const p = engine.ask("ask#1", actor, " 写一份调研大纲 ");
  1972. await flush();
  1973. const created = driver.eventsOfType("actor-created")[0]!;
  1974. const queued = driver.eventsOfType("node-queued")[0]!;
  1975. const dispatched = driver.eventsOfType("node-dispatched")[0]!;
  1976. expect(dispatched).toEqual({
  1977. type: "node-dispatched",
  1978. instance: queued.instance,
  1979. kind: queued.kind,
  1980. actor: queued.actor,
  1981. actorName: created.name,
  1982. actorPhaseName: created.phaseName,
  1983. phaseName: queued.phaseName,
  1984. instructionsHead: queued.instructionsHead,
  1985. });
  1986. // 逐字相同,而不只是形状相同:指令开头是准入时刻算的那一份(去两端空白、无省略号)。
  1987. expect(dispatched.instructionsHead).toBe("写一份调研大纲");
  1988. expect(dispatched.actorName).toBe("planner");
  1989. engine.askTurnEnded(inst("ask#1"), "RA");
  1990. await expect(p).resolves.toBe("RA");
  1991. });
  1992. it("omits the name of an anonymous subagent and keeps a world read's dispatch bare", async () => {
  1993. const { engine, driver } = setup();
  1994. const actor = engine.createActor("actor#1");
  1995. const p = engine.ask("ask#1", actor, "do it");
  1996. void engine.worldRead("world-read#1", "glob", ["src/**"]);
  1997. await flush();
  1998. // 匿名 actor:`actor-created` 的 name 是空的(序列化后整个键不在),派发同样不许凭空造一个。
  1999. expect(driver.eventsOfType("actor-created")[0]!.name).toBeUndefined();
  2000. const [world, ask] = driver.eventsOfType("node-dispatched");
  2001. expect(ask).toEqual({
  2002. type: "node-dispatched",
  2003. instance: inst("ask#1"),
  2004. kind: "ask",
  2005. actor: { siteId: "actor#1", ordinal: 1 },
  2006. instructionsHead: "do it",
  2007. });
  2008. // world-read 的派发不带任何出生事实:它紧跟自己的 node-queued,也没有子代理。
  2009. expect(world).toEqual({ type: "node-dispatched", instance: inst("world-read#1") });
  2010. engine.askTurnEnded(inst("ask#1"), "RA");
  2011. await expect(p).resolves.toBe("RA");
  2012. });
  2013. it("carries the facts of the new life when a running row is re-queued on resume", async () => {
  2014. const journal = new InMemoryJournalStore();
  2015. journal.createRun({
  2016. runId: RUN,
  2017. caps: { maxConcurrency: 16 },
  2018. spentTokens: 0,
  2019. status: "running",
  2020. });
  2021. journal.putActor({ runId: RUN, siteId: "actor#1", ordinal: 1 });
  2022. // 上一世崩在执行中:这一行是 running,重跑要按记录的 actorSeq 重新派发。
  2023. journal.putNode({
  2024. runId: RUN,
  2025. siteId: "ask#1",
  2026. ordinal: 1,
  2027. kind: "ask",
  2028. actorSiteId: "actor#1",
  2029. actorOrdinal: 1,
  2030. actorSeq: 0,
  2031. inputHash: inputHash("do it"),
  2032. status: "running",
  2033. });
  2034. const { engine, driver } = setup({ journal });
  2035. engine.enterPhase("重跑");
  2036. const actor = engine.createActor("actor#1", "planner");
  2037. const p = engine.ask("ask#1", actor, "do it");
  2038. await flush();
  2039. // 新的一世重新出生一次,派发带的就是这一世的 node-queued 带的那一份。
  2040. const queued = driver.eventsOfType("node-queued")[0]!;
  2041. const dispatched = driver.eventsOfType("node-dispatched")[0]!;
  2042. expect(queued.phaseName).toBe("重跑");
  2043. expect(dispatched).toMatchObject({
  2044. kind: queued.kind,
  2045. actor: queued.actor,
  2046. actorName: "planner",
  2047. actorPhaseName: "重跑",
  2048. phaseName: "重跑",
  2049. instructionsHead: queued.instructionsHead,
  2050. });
  2051. engine.askTurnEnded(inst("ask#1"), "RA");
  2052. await expect(p).resolves.toBe("RA");
  2053. });
  2054. });
  2055. describe("run-launched:发起 run 那一轮的锚点(docs/execution-engine.md「Token telemetry for subagents」)", () => {
  2056. const make = (journal: InMemoryJournalStore) =>
  2057. new WorkflowEngine({
  2058. runId: RUN,
  2059. driver: new FakeDriver(journal),
  2060. caps: { maxConcurrency: 16 },
  2061. askSpecs: untypedSpecs("ask#1"),
  2062. validate: () => [],
  2063. toolCallId: "tool-1",
  2064. parentSessionId: "parent-1",
  2065. launch: { inputId: "launch-input-1" },
  2066. });
  2067. it("建 run 那一世紧跟首条 run-started 记一条 run-launched,携 inputId / toolCallId / parentSessionId", () => {
  2068. const journal = new InMemoryJournalStore();
  2069. make(journal);
  2070. expect(
  2071. journal
  2072. .listEvents(RUN, { types: "all", reportItems: "all" })
  2073. .map((stored) => stored.event.type),
  2074. ).toEqual(["run-started", "run-launched"]);
  2075. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]?.event).toEqual({
  2076. type: "run-launched",
  2077. inputId: "launch-input-1",
  2078. toolCallId: "tool-1",
  2079. parentSessionId: "parent-1",
  2080. });
  2081. });
  2082. it("同一 journal 上重放(resume)只再发 run-started,不再发第二条 run-launched", () => {
  2083. const journal = new InMemoryJournalStore();
  2084. make(journal);
  2085. make(journal);
  2086. expect(
  2087. journal
  2088. .listEvents(RUN, { types: "all", reportItems: "all" })
  2089. .map((stored) => stored.event.type),
  2090. ).toEqual(["run-started", "run-launched", "run-started"]);
  2091. });
  2092. it("没有 launch 入参就不记锚点(CLI / 旧宿主装配)", () => {
  2093. const journal = new InMemoryJournalStore();
  2094. new WorkflowEngine({
  2095. runId: RUN,
  2096. driver: new FakeDriver(journal),
  2097. caps: { maxConcurrency: 16 },
  2098. askSpecs: untypedSpecs("ask#1"),
  2099. validate: () => [],
  2100. });
  2101. expect(
  2102. journal
  2103. .listEvents(RUN, { types: "all", reportItems: "all" })
  2104. .map((stored) => stored.event.type),
  2105. ).toEqual(["run-started"]);
  2106. });
  2107. it("launch 携 phaseNames 时 run-launched 原样带上声明的阶段表(侧栏迷你轨道的站点来源)", () => {
  2108. const journal = new InMemoryJournalStore();
  2109. new WorkflowEngine({
  2110. runId: RUN,
  2111. driver: new FakeDriver(journal),
  2112. caps: { maxConcurrency: 16 },
  2113. askSpecs: untypedSpecs("ask#1"),
  2114. validate: () => [],
  2115. launch: { inputId: "launch-input-2", phaseNames: ["Research", "Write"] },
  2116. });
  2117. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]?.event).toEqual({
  2118. type: "run-launched",
  2119. inputId: "launch-input-2",
  2120. phaseNames: ["Research", "Write"],
  2121. });
  2122. });
  2123. // 本 run 的子代理模型(docs/dynamic-workflow/launch.md)与锚点、阶段表同车:零 SQL,只在建 run
  2124. // 那一世记进这条事件。引擎**不读它**——子代理会话的模型面整个在宿主侧(bootstrap 的
  2125. // workflow-actor-model.ts),宿主从事件头读回同一个规范串,resume 与两条读面都据此还原。
  2126. it("launch 携 subagentModel 时 run-launched 原样带上规范串(档位段在内),resume 不再记第二条", () => {
  2127. const journal = new InMemoryJournalStore();
  2128. const withModel = () =>
  2129. new WorkflowEngine({
  2130. runId: RUN,
  2131. driver: new FakeDriver(journal),
  2132. caps: { maxConcurrency: 16 },
  2133. askSpecs: untypedSpecs("ask#1"),
  2134. validate: () => [],
  2135. launch: { inputId: "launch-input-3", subagentModel: "zhipu/glm-5.3-flash$high" },
  2136. });
  2137. withModel();
  2138. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]?.event).toEqual({
  2139. type: "run-launched",
  2140. inputId: "launch-input-3",
  2141. // 档位段原样带着走:`$high` 是用户说出口的那一半,引擎逐字转录、不解析。
  2142. subagentModel: "zhipu/glm-5.3-flash$high",
  2143. });
  2144. // 续跑那一世不再记(与锚点同一道门):同一个 run 的子代理模型因此跨生命周期唯一。
  2145. withModel();
  2146. expect(
  2147. journal
  2148. .listEvents(RUN, { types: "all", reportItems: "all" })
  2149. .filter((stored) => stored.event.type === "run-launched"),
  2150. ).toHaveLength(1);
  2151. });
  2152. // 脚本点名的模型绑定表(docs/dynamic-workflow/launch.md「Models the script names」)与子代理模型
  2153. // 同车同规:提交方给出、建 run 那一世记一次、引擎不读;宿主建会话时按 persona 的名字查它。
  2154. it("launch 携 modelBindings 时 run-launched 原样带上整张表,resume 不再记第二条", () => {
  2155. const journal = new InMemoryJournalStore();
  2156. const bindings = {
  2157. "GLM-5.3-Flash": "zhipu/GLM-5.3-Flash$high",
  2158. "GLM-5.3$high": "zhipu/GLM-5.3$high",
  2159. };
  2160. const withBindings = () =>
  2161. new WorkflowEngine({
  2162. runId: RUN,
  2163. driver: new FakeDriver(journal),
  2164. caps: { maxConcurrency: 16 },
  2165. askSpecs: untypedSpecs("ask#1"),
  2166. validate: () => [],
  2167. launch: { inputId: "launch-input-4", modelBindings: bindings },
  2168. });
  2169. withBindings();
  2170. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]?.event).toEqual({
  2171. type: "run-launched",
  2172. inputId: "launch-input-4",
  2173. modelBindings: bindings,
  2174. });
  2175. withBindings();
  2176. expect(
  2177. journal
  2178. .listEvents(RUN, { types: "all", reportItems: "all" })
  2179. .filter((stored) => stored.event.type === "run-launched"),
  2180. ).toHaveLength(1);
  2181. });
  2182. it("launch 不带 modelBindings 时整个键缺席", () => {
  2183. const journal = new InMemoryJournalStore();
  2184. make(journal);
  2185. expect(
  2186. "modelBindings" in journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]!.event,
  2187. ).toBe(false);
  2188. });
  2189. it("launch 不带 subagentModel 时整个键缺席(缺席即子代理跑在会话模型上)", () => {
  2190. const journal = new InMemoryJournalStore();
  2191. make(journal);
  2192. // 落成值为 undefined 的键会让读侧把「没设」读成「设了一个空模型」,两者在 AmendWorkflow
  2193. // 的三态里是不同的意思。
  2194. expect(
  2195. "subagentModel" in journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]!.event,
  2196. ).toBe(false);
  2197. });
  2198. // 本 run 的脚本文件(docs/dynamic-workflow/launch.md「Script files」的 Provenance)与子代理
  2199. // 模型逐条同规:零 SQL、引擎不读、只在建 run 那一世记一次。宿主从事件头读回它交给模型面。
  2200. it("launch 携 scriptPath 时 run-launched 原样带上绝对路径,resume 不再记第二条", () => {
  2201. const journal = new InMemoryJournalStore();
  2202. const withPath = () =>
  2203. new WorkflowEngine({
  2204. runId: RUN,
  2205. driver: new FakeDriver(journal),
  2206. caps: { maxConcurrency: 16 },
  2207. askSpecs: untypedSpecs("ask#1"),
  2208. validate: () => [],
  2209. launch: {
  2210. inputId: "launch-input-4",
  2211. scriptPath: "/repo/.zcode/workflow-drafts/audit.dwf.ts",
  2212. },
  2213. });
  2214. withPath();
  2215. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]?.event).toEqual({
  2216. type: "run-launched",
  2217. inputId: "launch-input-4",
  2218. scriptPath: "/repo/.zcode/workflow-drafts/audit.dwf.ts",
  2219. });
  2220. // 续跑那一世不再记(与锚点、子代理模型同一道门):一个 run 的脚本文件跨生命周期唯一。
  2221. withPath();
  2222. expect(
  2223. journal
  2224. .listEvents(RUN, { types: "all", reportItems: "all" })
  2225. .filter((stored) => stored.event.type === "run-launched"),
  2226. ).toHaveLength(1);
  2227. });
  2228. it("launch 不带 scriptPath 时整个键缺席(缺席即这个 run 没有可编辑的脚本文件)", () => {
  2229. const journal = new InMemoryJournalStore();
  2230. make(journal);
  2231. // 与 subagentModel 同一条论证:落成值为 undefined 的键会让读侧把「没有文件」读成
  2232. // 「有文件但路径是空的」,而模型面据此决定说哪一句话。
  2233. expect(
  2234. "scriptPath" in journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]!.event,
  2235. ).toBe(false);
  2236. });
  2237. it("scriptPath 与子代理模型、阶段表同车时四者共存于同一条 run-launched", () => {
  2238. const journal = new InMemoryJournalStore();
  2239. new WorkflowEngine({
  2240. runId: RUN,
  2241. driver: new FakeDriver(journal),
  2242. caps: { maxConcurrency: 16 },
  2243. askSpecs: untypedSpecs("ask#1"),
  2244. validate: () => [],
  2245. launch: {
  2246. inputId: "launch-input-5",
  2247. phaseNames: ["Research"],
  2248. subagentModel: "zhipu/glm-5.3-flash$high",
  2249. scriptPath: "/repo/.zcode/workflow-drafts/audit.dwf.ts",
  2250. },
  2251. });
  2252. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]?.event).toEqual({
  2253. type: "run-launched",
  2254. inputId: "launch-input-5",
  2255. phaseNames: ["Research"],
  2256. subagentModel: "zhipu/glm-5.3-flash$high",
  2257. scriptPath: "/repo/.zcode/workflow-drafts/audit.dwf.ts",
  2258. });
  2259. });
  2260. it("phaseAlongside 与阶段表同车落 journal,缺席时键不出现(引擎两者都不读)", () => {
  2261. const journal = new InMemoryJournalStore();
  2262. new WorkflowEngine({
  2263. runId: RUN,
  2264. driver: new FakeDriver(journal),
  2265. caps: { maxConcurrency: 16 },
  2266. askSpecs: untypedSpecs("ask#1"),
  2267. validate: () => [],
  2268. launch: {
  2269. inputId: "launch-input-3",
  2270. phaseNames: ["A", "B", "C"],
  2271. phaseAlongside: [[], [0], []],
  2272. },
  2273. });
  2274. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]?.event).toEqual({
  2275. type: "run-launched",
  2276. inputId: "launch-input-3",
  2277. phaseNames: ["A", "B", "C"],
  2278. phaseAlongside: [[], [0], []],
  2279. });
  2280. const straight = new InMemoryJournalStore();
  2281. new WorkflowEngine({
  2282. runId: RUN,
  2283. driver: new FakeDriver(straight),
  2284. caps: { maxConcurrency: 16 },
  2285. askSpecs: untypedSpecs("ask#1"),
  2286. validate: () => [],
  2287. launch: { inputId: "launch-input-4", phaseNames: ["A"] },
  2288. });
  2289. expect(
  2290. Object.hasOwn(
  2291. straight.listEvents(RUN, { types: "all", reportItems: "all" })[1]!.event,
  2292. "phaseAlongside",
  2293. ),
  2294. ).toBe(false);
  2295. });
  2296. });
  2297. describe("用量沿 lineage 累计(docs/execution-engine.md「Usage across the lineage」)", () => {
  2298. const eventTypes = (journal: InMemoryJournalStore) =>
  2299. journal
  2300. .listEvents(RUN, { types: "all", reportItems: "all" })
  2301. .map((stored) => stored.event.type);
  2302. const make = (
  2303. journal: InMemoryJournalStore,
  2304. opts: { inheritedTokens?: number; launch?: { inputId: string } } = {},
  2305. ) => {
  2306. const driver = new FakeDriver(journal);
  2307. const engine = new WorkflowEngine({
  2308. runId: RUN,
  2309. driver,
  2310. caps: { maxConcurrency: 16 },
  2311. askSpecs: untypedSpecs("ask#1"),
  2312. validate: () => [],
  2313. resumedFrom: "run-a",
  2314. ...(opts.inheritedTokens === undefined ? {} : { inheritedTokens: opts.inheritedTokens }),
  2315. ...(opts.launch === undefined ? {} : { launch: opts.launch }),
  2316. });
  2317. return { driver, engine };
  2318. };
  2319. it("inheritedTokens 是新 run 的起点:行值即前驱总量,run-started 之后紧跟一条同值的 usage-updated", () => {
  2320. const journal = new InMemoryJournalStore();
  2321. const { driver } = make(journal, { inheritedTokens: 300 });
  2322. expect(journal.getRun(RUN)?.spentTokens).toBe(300);
  2323. expect(eventTypes(journal)).toEqual(["run-started", "usage-updated"]);
  2324. expect(journal.listEvents(RUN, { types: "all", reportItems: "all" })[1]?.event).toEqual({
  2325. type: "usage-updated",
  2326. spentTokens: 300,
  2327. });
  2328. // 投影靠 driver.emit 拿到同一条:run-started 把用量清零,这条紧跟着把继承值放回去。
  2329. expect(driver.events.at(-1)).toEqual({ type: "usage-updated", spentTokens: 300 });
  2330. });
  2331. it("带 launch 时顺序是 run-started → run-launched → usage-updated(锚点仍紧跟首条 run-started)", () => {
  2332. const journal = new InMemoryJournalStore();
  2333. make(journal, { inheritedTokens: 300, launch: { inputId: "launch-1" } });
  2334. expect(eventTypes(journal)).toEqual(["run-started", "run-launched", "usage-updated"]);
  2335. });
  2336. it("live turn 在继承值之上累加;事件载荷与行值始终相等", async () => {
  2337. const journal = new InMemoryJournalStore();
  2338. const { driver, engine } = make(journal, { inheritedTokens: 300 });
  2339. const actor = engine.createActor("actor#1");
  2340. void engine.ask("ask#1", actor, "do it").catch(() => {});
  2341. await flush();
  2342. engine.askStats(inst("ask#1"), { tokens: 50, toolCalls: 0, turns: 1 });
  2343. expect(driver.events.at(-1)).toEqual({ type: "usage-updated", spentTokens: 350 });
  2344. expect(journal.getRun(RUN)?.spentTokens).toBe(350);
  2345. engine.stop("user");
  2346. });
  2347. it("继承值为零或缺席时不发 post-start usage-updated(reset 已经说了零)", () => {
  2348. const zero = new InMemoryJournalStore();
  2349. make(zero, { inheritedTokens: 0 });
  2350. expect(eventTypes(zero)).toEqual(["run-started"]);
  2351. const absent = new InMemoryJournalStore();
  2352. make(absent);
  2353. expect(absent.getRun(RUN)?.spentTokens).toBe(0);
  2354. expect(eventTypes(absent)).toEqual(["run-started"]);
  2355. });
  2356. it("resume 恢复行值后同样紧跟一条 usage-updated,让第二世的投影不从零起显示", () => {
  2357. const journal = new InMemoryJournalStore();
  2358. journal.createRun({
  2359. runId: RUN,
  2360. caps: { maxConcurrency: 16 },
  2361. spentTokens: 7,
  2362. status: "stopped",
  2363. stopReason: "user",
  2364. });
  2365. const { driver } = make(journal);
  2366. expect(eventTypes(journal)).toEqual(["run-started", "usage-updated"]);
  2367. expect(driver.events).toEqual([
  2368. { type: "run-started", runId: RUN, caps: { maxConcurrency: 16 } },
  2369. { type: "usage-updated", spentTokens: 7 },
  2370. ]);
  2371. expect(journal.getRun(RUN)?.spentTokens).toBe(7);
  2372. });
  2373. });