zcodeProtocolV4WorkflowRunsReducer.test.ts 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660
  1. // workflowRuns 的纯归约(workflow-runs-reducer.ts)。
  2. // 这份归约此前长在 bootstrap 的 v4 product-projection 里,抽出来给 TUI 镜像共用
  3. // (docs/dynamic-workflow/launch.md「The inline card」)。
  4. //
  5. // 桌面/协议侧的等价性由 bootstrap 的 product-projection*.test.ts 背书(断言未改);
  6. // 本文件钉的是 reducer 自己的契约:逐事件归约、有界化、淘汰、revision 单调、派生 actor 状态、
  7. // 幂等重放。所有 case 都只调纯函数,不涉及投影、时钟或 I/O。
  8. import { describe, expect, it } from "vitest";
  9. import {
  10. WORKFLOW_RUNS_LIMITS,
  11. reduceWorkflowRunsState,
  12. workflowRunsStateSchema,
  13. type WorkflowRunProgressEnvelope,
  14. type WorkflowRunsState,
  15. } from "../src/zcode-protocol-v4/index.js";
  16. const RUN_ID = "dwfrun-1";
  17. /** 逐条归约一串事件;null(无变化)时保持上一态,与投影"不产 delta"同义。 */
  18. function reduceAll(
  19. envelopes: readonly WorkflowRunProgressEnvelope[],
  20. initial?: WorkflowRunsState,
  21. ): WorkflowRunsState | undefined {
  22. let state = initial;
  23. for (const envelope of envelopes) {
  24. state = reduceWorkflowRunsState(state, envelope) ?? state;
  25. }
  26. return state;
  27. }
  28. /**
  29. * 归约一条**预期确实产生变化**的事件。
  30. *
  31. * reducer 的 `previous` 收 `| undefined` 而返回 `| null`,链式调用因此不能直接接——这是刻意的:
  32. * "无变化"必须被调用方显式处理,不能顺手当成空态传下去(那会把状态整片抹掉)。
  33. */
  34. function step(
  35. state: WorkflowRunsState | undefined,
  36. envelope: WorkflowRunProgressEnvelope,
  37. ): WorkflowRunsState {
  38. const next = reduceWorkflowRunsState(state, envelope);
  39. if (next === null) throw new Error(`事件本应产生变化却返回 null:${envelope.eventType}`);
  40. return next;
  41. }
  42. /** 事件信封工厂:sequence 按调用序自增,模拟 journal 的单调分配。 */
  43. function progressLog(runId = RUN_ID) {
  44. let sequence = -1;
  45. return function progress(
  46. eventType: string,
  47. payload: Record<string, unknown> = {},
  48. extra: Partial<WorkflowRunProgressEnvelope> = {},
  49. ): WorkflowRunProgressEnvelope {
  50. sequence += 1;
  51. return { runId, toolCallId: "tc-1", sequence, eventType, payload, ...extra };
  52. };
  53. }
  54. const started = (caps: Record<string, unknown> = { maxConcurrency: 4 }) => ({
  55. caps,
  56. runId: RUN_ID,
  57. });
  58. describe("reduceWorkflowRunsState:逐事件归约", () => {
  59. it("run-started 建条目:running + 零用量,产出过 strict schema", () => {
  60. const progress = progressLog();
  61. const state = reduceWorkflowRunsState(
  62. undefined,
  63. progress("run-started", started({ maxConcurrency: 2 })),
  64. );
  65. expect(state).toEqual({
  66. revision: 1,
  67. runs: [
  68. {
  69. runId: RUN_ID,
  70. toolCallId: "tc-1",
  71. status: "running",
  72. usage: { spentTokens: 0, nodesUsed: 0 },
  73. actors: [],
  74. nodes: [],
  75. lastEventSequence: 0,
  76. },
  77. ],
  78. });
  79. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  80. });
  81. it("节点相位按 (siteId, ordinal) upsert:四条事件一个条目", () => {
  82. const progress = progressLog();
  83. const state = reduceAll([
  84. progress("run-started", started()),
  85. progress("node-queued", {
  86. instance: { siteId: "ask#1", ordinal: 1 },
  87. kind: "ask",
  88. actor: { siteId: "actor#1", ordinal: 1 },
  89. }),
  90. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  91. progress("node-repairing", { instance: { siteId: "ask#1", ordinal: 1 }, attempt: 1 }),
  92. progress("node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" }),
  93. ]);
  94. expect(state?.runs[0]?.nodes).toEqual([
  95. {
  96. siteId: "ask#1",
  97. ordinal: 1,
  98. // kind 只在 queued 上携带,后续相位从上一条继承。
  99. kind: "ask",
  100. phase: "settled",
  101. outcome: "ok",
  102. // actor 归属同理继承——dispatched/settled 不重复带 actor。
  103. actorSiteId: "actor#1",
  104. actorOrdinal: 1,
  105. },
  106. ]);
  107. });
  108. it("cached 命中直接发 node-settled(不经 queued),kind 缺省而条目仍成立", () => {
  109. // engine.ts:228/232 —— resume 的完结命中短路,kind 因此不可观察。
  110. const progress = progressLog();
  111. const state = reduceAll([
  112. progress("run-started", started()),
  113. progress("node-settled", {
  114. instance: { siteId: "world-read#1", ordinal: 1 },
  115. outcome: "ok",
  116. cached: true,
  117. }),
  118. ]);
  119. expect(state?.runs[0]?.nodes).toEqual([
  120. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok", cached: true },
  121. ]);
  122. });
  123. it("用量:spentTokens 直接取 usage-updated 载荷,nodesUsed 按首次派发计步", () => {
  124. // docs/dynamic-workflow/authoring.md:事件携带已花总量(与 dwf_run.spent_tokens 同步写入)。
  125. const progress = progressLog();
  126. const dispatched = (siteId: string) => [
  127. progress("node-queued", {
  128. instance: { siteId, ordinal: 1 },
  129. kind: "ask",
  130. actor: { siteId: "actor#1", ordinal: 1 },
  131. }),
  132. progress("node-dispatched", { instance: { siteId, ordinal: 1 } }),
  133. ];
  134. const state = reduceAll([
  135. progress("run-started", started()),
  136. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 } }),
  137. ...dispatched("ask#1"),
  138. progress("usage-updated", { spentTokens: 1_234 }),
  139. ...dispatched("ask#2"),
  140. ...dispatched("ask#3"),
  141. progress("usage-updated", { spentTokens: 2_000 }),
  142. ]);
  143. expect(state?.runs[0]?.usage).toEqual({ spentTokens: 2_000, nodesUsed: 3 });
  144. });
  145. it("步数幂等:同一实例的 node-dispatched 重放不重复计步;usage-updated 缺载荷时保持已知值", () => {
  146. const progress = progressLog();
  147. const state = reduceAll([
  148. progress("run-started", started()),
  149. progress("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" }),
  150. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  151. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  152. progress("node-executing", { instance: { siteId: "ask#1", ordinal: 1 } }),
  153. progress("usage-updated", { spentTokens: 9 }),
  154. progress("usage-updated", {}),
  155. ]);
  156. expect(state?.runs[0]?.usage).toEqual({ spentTokens: 9, nodesUsed: 1 });
  157. });
  158. it("run-settled 落终态与错误文案,且错误按上限截断", () => {
  159. const progress = progressLog();
  160. const long = "长".repeat(WORKFLOW_RUNS_LIMITS.maxErrorLength + 50);
  161. const state = reduceAll([
  162. progress("run-started", started()),
  163. progress("run-settled", {
  164. status: "errored",
  165. error: { code: "ReportCapExceeded", message: long },
  166. }),
  167. ]);
  168. expect(state?.runs[0]?.status).toBe("errored");
  169. expect(state?.runs[0]?.error).toHaveLength(WORKFLOW_RUNS_LIMITS.maxErrorLength);
  170. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  171. });
  172. // 修复原因(2026-09-15):闭集之外的词过去「一律忽略」,2026-09-14 之前 journal 里的
  173. // run-settled{cancelled|failed} 冷回放后把 run 留在 running。结算到了 run 就不能再活着。
  174. it("run-settled 的未知 status → errored 落终态,文案说明是哪个词,不亮 Resume", () => {
  175. const progress = progressLog();
  176. const state = reduceAll([
  177. progress("run-started", started()),
  178. progress("run-settled", { status: "exploded" }),
  179. ]);
  180. expect(state?.runs[0]?.status).toBe("errored");
  181. expect(state?.runs[0]?.error).toContain("exploded");
  182. expect(state?.runs[0]?.resumable).toBeUndefined();
  183. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  184. });
  185. it.each(["cancelled", "failed"] as const)(
  186. "旧词表 run-settled{%s}(2026-09-14 之前的 journal)→ errored,保留事件自带的文案",
  187. (status) => {
  188. const progress = progressLog();
  189. const state = reduceAll([
  190. progress("run-started", started()),
  191. progress("run-settled", { status, error: { code: "DriverError", message: "old words" } }),
  192. ]);
  193. expect(state?.runs[0]?.status).toBe("errored");
  194. expect(state?.runs[0]?.error).toBe("old words");
  195. },
  196. );
  197. it("同 runId 再收 run-started:清掉上一世的 error 与 stopReason", () => {
  198. const progress = progressLog();
  199. const state = reduceAll([
  200. progress("run-started", started()),
  201. progress("run-settled", {
  202. status: "stopped",
  203. stopReason: "interrupted",
  204. error: { code: "Interrupted", message: "owner exited" },
  205. }),
  206. progress("run-started", started()),
  207. ]);
  208. expect(state?.runs).toHaveLength(1);
  209. expect(state?.runs[0]).toMatchObject({ runId: RUN_ID, status: "running" });
  210. expect(state?.runs[0]?.error).toBeUndefined();
  211. // 上一世的停止原因同属结算残影。
  212. expect(state?.runs[0]?.stopReason).toBeUndefined();
  213. });
  214. it("log / compaction 不进图,但仍抬 lastEventSequence(事件日志需要知道有新内容)", () => {
  215. const progress = progressLog();
  216. const state = reduceAll([
  217. progress("run-started", started()),
  218. progress("log", { message: "开始" }),
  219. ]);
  220. expect(state?.runs[0]?.nodes).toEqual([]);
  221. expect(state?.runs[0]?.actors).toEqual([]);
  222. expect(state?.runs[0]?.lastEventSequence).toBe(1);
  223. });
  224. it("缺 runId 或 eventType 的信封整条无效,返回 null", () => {
  225. expect(
  226. reduceWorkflowRunsState(undefined, { eventType: "run-started", sequence: 0 }),
  227. ).toBeNull();
  228. expect(reduceWorkflowRunsState(undefined, { runId: RUN_ID, sequence: 0 })).toBeNull();
  229. });
  230. it("无法定位的 instance / actor 不建条目,只抬水位", () => {
  231. const progress = progressLog();
  232. const state = reduceAll([
  233. progress("run-started", started()),
  234. // ordinal 缺席 → 无法定位。
  235. progress("node-queued", { instance: { siteId: "ask#1" }, kind: "ask" }),
  236. progress("actor-created", { actor: { ordinal: 1 }, name: "planner" }),
  237. ]);
  238. expect(state?.runs[0]?.nodes).toEqual([]);
  239. expect(state?.runs[0]?.actors).toEqual([]);
  240. expect(state?.runs[0]?.lastEventSequence).toBe(2);
  241. });
  242. // Bugfix 2026-09-04:脚本把文件路径拼成 131 字的子代理名,reducer 原样透传,而线上 schema 把
  243. // `actor.name` 钉在 128——于是父会话之后的每一帧(online / recovery / initial)都被渲染端拒收,
  244. // 订阅以 fault.subscription.recoveryFailed 失效。生产者必须先按 schema 界裁剪。
  245. it("子代理名超过线上上界时按上界裁剪,归约结果始终通过 schema", () => {
  246. const progress = progressLog();
  247. const longName = `reader-${"sections-x.tex+".repeat(12)}`;
  248. expect(longName.length).toBeGreaterThan(WORKFLOW_RUNS_LIMITS.maxActorNameLength);
  249. const state = reduceAll([
  250. progress("run-started", started()),
  251. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 6 }, name: longName }),
  252. progress("escalation-raised", {
  253. qid: "q-1",
  254. question: "路径读不到",
  255. actor: { siteId: "actor#1", ordinal: 6 },
  256. actorName: longName,
  257. }),
  258. ]);
  259. const run = state?.runs[0];
  260. expect(run?.actors[0]?.name).toBe(longName.slice(0, WORKFLOW_RUNS_LIMITS.maxActorNameLength));
  261. expect(run?.pendingQuestions?.[0]?.actorName).toBe(
  262. longName.slice(0, WORKFLOW_RUNS_LIMITS.maxActorNameLength),
  263. );
  264. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  265. });
  266. it("首见事件不是 run-started 时条目落 pending(引擎事件流被截断的中途接入)", () => {
  267. const state = reduceWorkflowRunsState(undefined, {
  268. runId: RUN_ID,
  269. sequence: 7,
  270. eventType: "log",
  271. payload: { message: "中途接入" },
  272. });
  273. expect(state?.runs[0]).toMatchObject({ status: "pending", lastEventSequence: 7 });
  274. expect(state?.runs[0]).not.toHaveProperty("toolCallId");
  275. });
  276. it("toolCallId 只在首次出现时补齐,之后不被后续事件改写", () => {
  277. const first = step(undefined, {
  278. runId: RUN_ID,
  279. sequence: 0,
  280. eventType: "run-started",
  281. payload: started(),
  282. });
  283. expect(first.runs[0]).not.toHaveProperty("toolCallId");
  284. const withTool = step(first, {
  285. runId: RUN_ID,
  286. toolCallId: "tc-late",
  287. sequence: 1,
  288. eventType: "log",
  289. payload: {},
  290. });
  291. expect(withTool.runs[0]?.toolCallId).toBe("tc-late");
  292. const relabeled = step(withTool, {
  293. runId: RUN_ID,
  294. toolCallId: "tc-other",
  295. sequence: 2,
  296. eventType: "log",
  297. payload: {},
  298. });
  299. expect(relabeled.runs[0]?.toolCallId).toBe("tc-late");
  300. });
  301. });
  302. // lineage 的两端(docs/dynamic-workflow/presentation.md「The run card」):`run-started` 带 resumedFrom,
  303. // `run-settled` 只在 superseded 时带 supersededBy;reducer 只搬运,两者都过 strict schema。
  304. describe("reduceWorkflowRunsState:lineage", () => {
  305. it("run-started 的 resumedFrom 与 run-settled 的 supersededBy 都进状态", () => {
  306. const progress = progressLog();
  307. const state = reduceAll([
  308. progress("run-started", { ...started(), resumedFrom: "dwfrun-prev" }),
  309. progress("run-settled", {
  310. status: "stopped",
  311. stopReason: "superseded",
  312. supersededBy: "dwfrun-next",
  313. }),
  314. ]);
  315. expect(state?.runs[0]).toMatchObject({
  316. status: "stopped",
  317. stopReason: "superseded",
  318. resumedFrom: "dwfrun-prev",
  319. supersededBy: "dwfrun-next",
  320. });
  321. // 被替代的 run 不可恢复:CLI 不发 resumable,这里也没有。
  322. expect(state?.runs[0]?.resumable).toBeUndefined();
  323. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  324. });
  325. it("supersededBy 只随 superseded 搬运;没有 lineage 的 run 两个键都缺席", () => {
  326. const progress = progressLog();
  327. const state = reduceAll([
  328. progress("run-started", started()),
  329. progress("run-settled", { status: "stopped", stopReason: "user", supersededBy: "dwfrun-x" }),
  330. ]);
  331. expect(state?.runs[0]?.supersededBy).toBeUndefined();
  332. expect(state?.runs[0]?.resumedFrom).toBeUndefined();
  333. });
  334. });
  335. // resumable 状态位(docs/dynamic-workflow/presentation.md「Cold replay」):CLI 在 run-settled
  336. // 载荷上按 resume 门裁定,reducer 只搬运——为真才在场,UI 与 TUI 绝不按 status 重推导。
  337. describe("reduceWorkflowRunsState:resumable 状态位", () => {
  338. it("run-settled 携 resumable: true → 状态位在场,且过 strict schema", () => {
  339. const progress = progressLog();
  340. const state = reduceAll([
  341. progress("run-started", started()),
  342. progress("run-settled", {
  343. status: "stopped",
  344. stopReason: "interrupted",
  345. error: { code: "Interrupted", message: "owning process exited" },
  346. resumable: true,
  347. }),
  348. ]);
  349. expect(state?.runs[0]).toMatchObject({
  350. status: "stopped",
  351. stopReason: "interrupted",
  352. resumable: true,
  353. });
  354. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  355. });
  356. it("run-settled 不携该位(或携 false)→ 键缺席,哪怕 status 是 stopped", () => {
  357. const progress = progressLog();
  358. const stopped = reduceAll([
  359. progress("run-started", started()),
  360. progress("run-settled", { status: "stopped", stopReason: "user" }),
  361. ]);
  362. expect(stopped?.runs[0]?.resumable).toBeUndefined();
  363. const explicit = reduceAll([
  364. progress("run-started", started()),
  365. progress("run-settled", { status: "errored", resumable: false }),
  366. ]);
  367. expect(explicit?.runs[0]?.resumable).toBeUndefined();
  368. });
  369. // 停止原因(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md):只在 stopped 上搬运,闭集之外与其余
  370. // 终态上的 stopReason 一律丢弃——reducer 不替 CLI 编原因。
  371. it("run-settled 的 stopReason 只在 stopped 上搬运,且只收四个值", () => {
  372. const progress = progressLog();
  373. for (const stopReason of ["user", "model", "provider", "interrupted"] as const) {
  374. const state = reduceAll([
  375. progress("run-started", started()),
  376. progress("run-settled", { status: "stopped", stopReason, resumable: true }),
  377. ]);
  378. expect(state?.runs[0]).toMatchObject({ status: "stopped", stopReason });
  379. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  380. }
  381. const bogus = reduceAll([
  382. progress("run-started", started()),
  383. progress("run-settled", { status: "stopped", stopReason: "crash" }),
  384. ]);
  385. expect(bogus?.runs[0]?.status).toBe("stopped");
  386. expect(bogus?.runs[0]?.stopReason).toBeUndefined();
  387. const errored = reduceAll([
  388. progress("run-started", started()),
  389. progress("run-settled", { status: "errored", stopReason: "user" }),
  390. ]);
  391. expect(errored?.runs[0]?.stopReason).toBeUndefined();
  392. });
  393. it("run-stalled 是纯观察事件:不改 run 的任何状态键", () => {
  394. const progress = progressLog();
  395. const before = reduceAll([progress("run-started", started())]);
  396. const after = reduceAll(
  397. [progress("run-stalled", { sinceMs: 1_200_000, reason: "rate_limited", cap: 2 })],
  398. before,
  399. );
  400. expect(after?.runs[0]?.status).toBe("running");
  401. expect(workflowRunsStateSchema.safeParse(after).success).toBe(true);
  402. });
  403. it("同 runId 再收 run-started(resume 开跑)→ 上一世的 resumable 随 error 一起清掉", () => {
  404. const progress = progressLog();
  405. const state = reduceAll([
  406. progress("run-started", started()),
  407. progress("run-settled", { status: "stopped", stopReason: "user", resumable: true }),
  408. progress("run-started", started()),
  409. ]);
  410. expect(state?.runs[0]).toMatchObject({ status: "running" });
  411. expect(state?.runs[0]?.resumable).toBeUndefined();
  412. });
  413. });
  414. describe("reduceWorkflowRunsState:派生 actor 状态", () => {
  415. it("actor 状态由自己名下节点的相位派生(有在飞节点 → running)", () => {
  416. // Boundary C 除 actor-created 外不发 actor 生命周期事件,所以状态只能派生。
  417. const progress = progressLog();
  418. const created = reduceAll([
  419. progress("run-started", started()),
  420. progress(
  421. "actor-created",
  422. { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" },
  423. { actorSessionId: "sess_dwf-1-actor.1" },
  424. ),
  425. ]);
  426. expect(created?.runs[0]?.actors).toEqual([
  427. {
  428. siteId: "actor#1",
  429. ordinal: 1,
  430. name: "planner",
  431. sessionId: "sess_dwf-1-actor.1",
  432. // 建了还没被 ask、run 未终态:等待中(决策 39)。
  433. status: "waiting",
  434. },
  435. ]);
  436. const dispatched = reduceAll(
  437. [
  438. progress("node-queued", {
  439. instance: { siteId: "ask#1", ordinal: 1 },
  440. kind: "ask",
  441. actor: { siteId: "actor#1", ordinal: 1 },
  442. }),
  443. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  444. ],
  445. created,
  446. );
  447. // dispatched 只是「会话就绪、首个请求尚未准入」:仍是等待;真正在跑由 node-executing 说。
  448. expect(dispatched?.runs[0]?.actors[0]?.status).toBe("waiting");
  449. const executing = reduceAll(
  450. [progress("node-executing", { instance: { siteId: "ask#1", ordinal: 1 } })],
  451. dispatched,
  452. );
  453. expect(executing?.runs[0]?.actors[0]?.status).toBe("running");
  454. const settled = reduceAll(
  455. [progress("node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" })],
  456. executing,
  457. );
  458. expect(settled?.runs[0]?.actors[0]?.status).toBe("completed");
  459. });
  460. it("executing / repairing / nudged 算在跑;queued / dispatched / waiting 算在等", () => {
  461. const progress = progressLog();
  462. const base = reduceAll([
  463. progress("run-started", started()),
  464. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 } }),
  465. progress("node-queued", {
  466. instance: { siteId: "ask#1", ordinal: 1 },
  467. kind: "ask",
  468. actor: { siteId: "actor#1", ordinal: 1 },
  469. }),
  470. ]);
  471. expect(base?.runs[0]?.actors[0]?.status).toBe("waiting");
  472. for (const phase of ["executing", "repairing", "nudged"] as const) {
  473. const busy = reduceAll(
  474. [progress(`node-${phase}`, { instance: { siteId: "ask#1", ordinal: 1 } })],
  475. base,
  476. );
  477. expect(busy?.runs[0]?.actors[0]?.status).toBe("running");
  478. }
  479. for (const phase of ["dispatched", "waiting"] as const) {
  480. const idle = reduceAll(
  481. [progress(`node-${phase}`, { instance: { siteId: "ask#1", ordinal: 1 } })],
  482. base,
  483. );
  484. expect(idle?.runs[0]?.actors[0]?.status).toBe("waiting");
  485. }
  486. });
  487. it("失败的 ask 也是「干完了」:completed 不区分 outcome(结果在节点上)", () => {
  488. const progress = progressLog();
  489. const state = reduceAll([
  490. progress("run-started", started()),
  491. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 } }),
  492. progress("node-queued", {
  493. instance: { siteId: "ask#1", ordinal: 1 },
  494. kind: "ask",
  495. actor: { siteId: "actor#1", ordinal: 1 },
  496. }),
  497. progress("node-executing", { instance: { siteId: "ask#1", ordinal: 1 } }),
  498. progress("node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "failed" }),
  499. ]);
  500. expect(state?.runs[0]?.actors[0]?.status).toBe("completed");
  501. });
  502. it("run 终态让每个 actor 都变 completed——包括建了却从未被 ask 的、和节点还挂在 queued 上的", () => {
  503. const progress = progressLog();
  504. const running = reduceAll([
  505. progress("run-started", started()),
  506. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 } }),
  507. progress("actor-created", { actor: { siteId: "actor#2", ordinal: 1 } }),
  508. progress("node-queued", {
  509. instance: { siteId: "ask#1", ordinal: 1 },
  510. kind: "ask",
  511. actor: { siteId: "actor#1", ordinal: 1 },
  512. }),
  513. ]);
  514. expect(running?.runs[0]?.actors.map((actor) => actor.status)).toEqual(["waiting", "waiting"]);
  515. for (const status of ["completed", "errored", "stopped"] as const) {
  516. const settled = reduceAll([progress("run-settled", { status })], running);
  517. expect(settled?.runs[0]?.actors.map((actor) => actor.status)).toEqual([
  518. "completed",
  519. "completed",
  520. ]);
  521. }
  522. });
  523. it("无 actor 归属的节点(world-read)不会把任何 actor 点亮", () => {
  524. const progress = progressLog();
  525. const state = reduceAll([
  526. progress("run-started", started()),
  527. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 } }),
  528. progress("node-executing", { instance: { siteId: "world-read#1", ordinal: 1 } }),
  529. ]);
  530. expect(state?.runs[0]?.actors[0]?.status).toBe("waiting");
  531. });
  532. it("同 siteId 的不同 ordinal 是不同 actor:一个在飞不点亮另一个", () => {
  533. const progress = progressLog();
  534. const state = reduceAll([
  535. progress("run-started", started()),
  536. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 } }),
  537. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 2 } }),
  538. progress("node-executing", {
  539. instance: { siteId: "ask#1", ordinal: 1 },
  540. actor: { siteId: "actor#1", ordinal: 2 },
  541. }),
  542. ]);
  543. expect(state?.runs[0]?.actors.map((actor) => [actor.ordinal, actor.status])).toEqual([
  544. [1, "waiting"],
  545. [2, "running"],
  546. ]);
  547. });
  548. it("派生键有分隔符:(a,12) 与 (a1,2) 是两个 actor,不互相点亮", () => {
  549. // 这一对是**裸拼接会撞车**的最小反例:"a"+12 与 "a1"+2 都等于 "a12"。
  550. // 归约用 `${siteId}\0${ordinal}` 做键(搬移时保留原实现的 NUL 分隔符语义,只把源码里的
  551. // 裸 NUL 字节写成转义 `\0`——同一个运行时字符。上面那条同 siteId 用例换成任何分隔符、
  552. // 甚至不加分隔符都能过,所以真正钉住分隔符存在的是这一条)。
  553. const progress = progressLog();
  554. const state = reduceAll([
  555. progress("run-started", started()),
  556. progress("actor-created", { actor: { siteId: "a", ordinal: 12 } }),
  557. progress("actor-created", { actor: { siteId: "a1", ordinal: 2 } }),
  558. // 只有 ("a1", 2) 名下有在跑节点。
  559. progress("node-executing", {
  560. instance: { siteId: "ask#1", ordinal: 1 },
  561. actor: { siteId: "a1", ordinal: 2 },
  562. }),
  563. ]);
  564. expect(
  565. state?.runs[0]?.actors.map((actor) => [actor.siteId, actor.ordinal, actor.status]),
  566. ).toEqual([
  567. ["a", 12, "waiting"],
  568. ["a1", 2, "running"],
  569. ]);
  570. });
  571. });
  572. describe("reduceWorkflowRunsState:有界化与淘汰", () => {
  573. it("nodes 触上限置 truncated 且不再增长,但已在表内的实例仍可更新相位", () => {
  574. const progress = progressLog();
  575. let state: WorkflowRunsState | undefined = step(undefined, progress("run-started", started()));
  576. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxNodes + 5; ordinal += 1) {
  577. state = reduceAll(
  578. [progress("node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" })],
  579. state,
  580. );
  581. }
  582. expect(state?.runs[0]?.nodes).toHaveLength(WORKFLOW_RUNS_LIMITS.maxNodes);
  583. expect(state?.runs[0]?.truncated).toBe(true);
  584. // 超界只拒绝**新**实例:把在跑的实例冻结在 queued 上比少列一个更误导人。
  585. const updated = reduceAll(
  586. [progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } })],
  587. state,
  588. );
  589. expect(updated?.runs[0]?.nodes[0]?.phase).toBe("dispatched");
  590. expect(workflowRunsStateSchema.safeParse(updated).success).toBe(true);
  591. });
  592. it("actors 触上限同样置 truncated,且 truncated 一旦置位不再回落", () => {
  593. const progress = progressLog();
  594. let state: WorkflowRunsState | undefined = step(undefined, progress("run-started", started()));
  595. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxActors + 2; ordinal += 1) {
  596. state = reduceAll(
  597. [progress("actor-created", { actor: { siteId: "actor#1", ordinal } })],
  598. state,
  599. );
  600. }
  601. expect(state?.runs[0]?.actors).toHaveLength(WORKFLOW_RUNS_LIMITS.maxActors);
  602. expect(state?.runs[0]?.truncated).toBe(true);
  603. const later = reduceAll(
  604. [progress("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" })],
  605. state,
  606. );
  607. expect(later?.runs[0]?.truncated).toBe(true);
  608. });
  609. it("runs ≤ maxRuns 且按最旧淘汰(终态事实仍在 journal)", () => {
  610. let state: WorkflowRunsState | undefined;
  611. const total = WORKFLOW_RUNS_LIMITS.maxRuns + 3;
  612. for (let index = 0; index < total; index += 1) {
  613. state = step(state, {
  614. runId: `dwfrun-${index}`,
  615. sequence: 0,
  616. eventType: "run-started",
  617. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  618. });
  619. }
  620. expect(state?.runs).toHaveLength(WORKFLOW_RUNS_LIMITS.maxRuns);
  621. expect(state?.runs.map((run) => run.runId)).toEqual(
  622. Array.from({ length: WORKFLOW_RUNS_LIMITS.maxRuns }, (_, offset) => `dwfrun-${offset + 3}`),
  623. );
  624. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  625. });
  626. it("被淘汰的 run 再来事件时作为新条目回到队尾(不复活旧事实)", () => {
  627. let state: WorkflowRunsState | undefined;
  628. for (let index = 0; index < WORKFLOW_RUNS_LIMITS.maxRuns + 1; index += 1) {
  629. state = step(state, {
  630. runId: `dwfrun-${index}`,
  631. sequence: 0,
  632. eventType: "run-started",
  633. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  634. });
  635. }
  636. expect(state?.runs.map((run) => run.runId)).not.toContain("dwfrun-0");
  637. const revived = reduceWorkflowRunsState(state, {
  638. runId: "dwfrun-0",
  639. sequence: 9,
  640. eventType: "log",
  641. payload: { message: "迟到的日志" },
  642. });
  643. expect(revived?.runs.at(-1)).toMatchObject({
  644. runId: "dwfrun-0",
  645. status: "pending",
  646. lastEventSequence: 9,
  647. });
  648. expect(revived?.runs).toHaveLength(WORKFLOW_RUNS_LIMITS.maxRuns);
  649. });
  650. });
  651. describe("reduceWorkflowRunsState:revision 与 sequence 单调", () => {
  652. it("每次有效变化抬一格 revision", () => {
  653. const progress = progressLog();
  654. const first = step(undefined, progress("run-started", started()));
  655. expect(first.revision).toBe(1);
  656. const second = step(
  657. first,
  658. progress("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" }),
  659. );
  660. expect(second.revision).toBe(2);
  661. const third = step(
  662. second,
  663. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  664. );
  665. expect(third.revision).toBe(3);
  666. expect(third.runs[0]?.lastEventSequence).toBe(2);
  667. });
  668. it("revision 承接传入态:非零起点继续抬,不重置", () => {
  669. const seeded: WorkflowRunsState = { revision: 41, runs: [] };
  670. const next = reduceWorkflowRunsState(seeded, {
  671. runId: RUN_ID,
  672. sequence: 0,
  673. eventType: "run-started",
  674. payload: started(),
  675. });
  676. expect(next?.revision).toBe(42);
  677. });
  678. it("lastEventSequence 单调:迟到/乱序事件仍归约内容,但水位不回退", () => {
  679. // 界之下**照单全收**:冷物化会把 journal 重放与在线事件喂进同一个归约,在线事件先给一条
  680. // run 开了头的话,它整段前缀就全在水位之下——丢掉就等于卡片空着。收紧只发生在溢出过的
  681. // run 上,见下一条。
  682. const state = reduceAll([
  683. { runId: RUN_ID, sequence: 5, eventType: "run-started", payload: started() },
  684. {
  685. runId: RUN_ID,
  686. sequence: 2,
  687. eventType: "node-queued",
  688. payload: { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" },
  689. },
  690. ]);
  691. expect(state?.runs[0]?.lastEventSequence).toBe(5);
  692. expect(state?.runs[0]?.nodes).toHaveLength(1);
  693. });
  694. it("溢出过的 run 才收紧:水位之下的事件开不出新条目,但照常更新已有的", () => {
  695. // 理由在 admitsNewEntry:腾位让表会变短,一个空出来的位子可能把一条早已计进
  696. // nodesUnlisted 的实例放回来,那条实例就既列又计。
  697. const progress = progressLog();
  698. const seeded = reduceAll([
  699. progress("run-started", started()),
  700. progress("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" }),
  701. ])!;
  702. const overflowed: WorkflowRunsState = {
  703. ...seeded,
  704. runs: [{ ...seeded.runs[0]!, truncated: true }],
  705. };
  706. const late = (eventType: string, siteId: string) => ({
  707. runId: RUN_ID,
  708. sequence: 1,
  709. eventType,
  710. payload: { instance: { siteId, ordinal: 1 }, kind: "ask" },
  711. });
  712. const updated = reduceWorkflowRunsState(overflowed, late("node-executing", "ask#1"))!;
  713. expect(updated.runs[0]?.nodes.map((node) => node.phase)).toEqual(["executing"]);
  714. const ignored = reduceWorkflowRunsState(updated, late("node-queued", "ask#2"));
  715. expect(ignored).toBeNull();
  716. });
  717. it("sequence 缺席按 0 处理,且不会把已有水位拉低", () => {
  718. const state = reduceAll([
  719. { runId: RUN_ID, sequence: 3, eventType: "run-started", payload: started() },
  720. { runId: RUN_ID, eventType: "log", payload: {} },
  721. ]);
  722. expect(state?.runs[0]?.lastEventSequence).toBe(3);
  723. });
  724. });
  725. describe("reduceWorkflowRunsState:幂等重放", () => {
  726. it("同一条事件重放返回 null:不抬 revision、不改状态", () => {
  727. const progress = progressLog();
  728. const settle = progress("node-settled", {
  729. instance: { siteId: "ask#1", ordinal: 1 },
  730. outcome: "ok",
  731. });
  732. const state = reduceAll([progress("run-started", started()), settle]);
  733. expect(reduceWorkflowRunsState(state, settle)).toBeNull();
  734. });
  735. it("每一条事件在它自己刚归约完之后立刻重放都是 no-op(逐步幂等)", () => {
  736. // 幂等的作用域是"刚到的那条":journal 有序投递,重传只会重传队尾。
  737. const progress = progressLog();
  738. const events = [
  739. progress("run-started", started()),
  740. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" }),
  741. progress("node-queued", {
  742. instance: { siteId: "ask#1", ordinal: 1 },
  743. kind: "ask",
  744. actor: { siteId: "actor#1", ordinal: 1 },
  745. }),
  746. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  747. progress("usage-updated", { spentTokens: 12 }),
  748. progress("run-settled", { status: "completed" }),
  749. ];
  750. let state: WorkflowRunsState | undefined;
  751. for (const event of events) {
  752. state = reduceWorkflowRunsState(state, event) ?? state;
  753. expect(reduceWorkflowRunsState(state, event)).toBeNull();
  754. }
  755. expect(state?.revision).toBe(events.length);
  756. });
  757. it("整串事件从终态再跑一遍不是 no-op:run-started 就是重开一世(记录在案)", () => {
  758. // 幂等**不**延伸到乱序/整串重放:run-started 会清结算残影并把 run 拉回 running,
  759. // node-queued 也没有相位单调守卫,会把已 dispatched 的节点拉回 queued。
  760. // journal 有序投递让这两条不会在生产上发生;这里钉住它们,免得日后误以为有守卫。
  761. const progress = progressLog();
  762. const events = [
  763. progress("run-started", started()),
  764. progress("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" }),
  765. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  766. progress("run-settled", { status: "completed" }),
  767. ];
  768. const once = reduceAll(events)!;
  769. expect(once.runs[0]?.status).toBe("completed");
  770. const replayed = reduceAll(events, once)!;
  771. expect(replayed.runs[0]?.status).toBe("completed");
  772. expect(replayed.revision).toBe(once.revision + events.length);
  773. // 水位是唯一有单调守卫的量:整串重放也不会让它回退。
  774. expect(replayed.runs[0]?.lastEventSequence).toBe(once.runs[0]?.lastEventSequence);
  775. });
  776. });
  777. // ── 升级问答(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)──────────────────────────────
  778. // 两个事件维护同一张「现在还欠谁一个答案」的表:raised 加、resolved 减。身份是 qid(全局唯一、
  779. // 跨 run),不是站点实例——升级没有 site 身份,不写 dwf_node 行、不占 maxNodes。
  780. describe("reduceWorkflowRunsState:升级问答", () => {
  781. const ASKED_AT = 1_756_000_000_000;
  782. const raised = (overrides: Record<string, unknown> = {}) => ({
  783. qid: "dwfq-dwfrun1-1",
  784. actor: { siteId: "actor#1", ordinal: 1 },
  785. actorName: "poet",
  786. question: "评分上限是 95,但通过门槛是 96,这个门是不是坏了?",
  787. askedAt: ASKED_AT,
  788. ...overrides,
  789. });
  790. it("escalation-raised 建一条停驻问题(qid 为键,actor 身份、名字与提问时刻随事件带上)", () => {
  791. const progress = progressLog();
  792. const state = reduceAll([
  793. progress("run-started", started()),
  794. progress("escalation-raised", raised({ context: "已经试过 4 轮,最高分 95。" })),
  795. ]);
  796. expect(state?.runs[0]?.pendingQuestions).toEqual([
  797. {
  798. qid: "dwfq-dwfrun1-1",
  799. actorSiteId: "actor#1",
  800. actorOrdinal: 1,
  801. actorName: "poet",
  802. question: "评分上限是 95,但通过门槛是 96,这个门是不是坏了?",
  803. context: "已经试过 4 轮,最高分 95。",
  804. // 提问时刻只能由事件携带——本模块是纯归约,没有时钟可用。
  805. askedAt: ASKED_AT,
  806. },
  807. ]);
  808. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  809. });
  810. it("askedAt 缺席(老 journal 重放出的事件)时字段整个不落,其余照常成条", () => {
  811. // 事件侧 askedAt 是必填的,但老开发机上的 journal 可能重放出加字段之前的事件。
  812. // 缺席不是错误:渲染侧据此不显示等待时长,而不是编一个"刚刚"出来。
  813. const progress = progressLog();
  814. const { askedAt: _legacy, ...preAmendment } = raised();
  815. const state = reduceAll([
  816. progress("run-started", started()),
  817. progress("escalation-raised", preAmendment),
  818. ]);
  819. const pending = state?.runs[0]?.pendingQuestions?.[0];
  820. expect(pending).not.toHaveProperty("askedAt");
  821. expect(pending?.question).toBe("评分上限是 95,但通过门槛是 96,这个门是不是坏了?");
  822. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  823. });
  824. it("askedAt 不是有限数时按缺席处理,不把 NaN / Infinity 落进状态", () => {
  825. const progress = progressLog();
  826. const state = reduceAll([
  827. progress("run-started", started()),
  828. progress("escalation-raised", raised({ qid: "dwfq-nan", askedAt: Number.NaN })),
  829. progress("escalation-raised", raised({ qid: "dwfq-inf", askedAt: Number.POSITIVE_INFINITY })),
  830. progress("escalation-raised", raised({ qid: "dwfq-str", askedAt: "刚刚" })),
  831. ]);
  832. for (const pending of state?.runs[0]?.pendingQuestions ?? []) {
  833. expect(pending).not.toHaveProperty("askedAt");
  834. }
  835. // JSON 承载不了 NaN/Infinity,落进去会让整帧 patch 在协议线上变成 null。
  836. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  837. });
  838. it("匿名 actor 与无补充说明时字段整个缺席,不落空串", () => {
  839. // 事件侧刻意不合成兜底标签(engine/types.ts 的 actorName 注释),归约也不替它编一个:
  840. // 「无名」的渲染是消费者的决定。
  841. const progress = progressLog();
  842. const { actorName: _anonymous, ...anonymous } = raised();
  843. const state = reduceAll([
  844. progress("run-started", started()),
  845. progress("escalation-raised", anonymous),
  846. ]);
  847. const pending = state?.runs[0]?.pendingQuestions?.[0];
  848. expect(pending).not.toHaveProperty("actorName");
  849. expect(pending).not.toHaveProperty("context");
  850. expect(pending?.qid).toBe("dwfq-dwfrun1-1");
  851. });
  852. it("actor ref 读不动时**仍然**建条目:身份是 qid,actor 只是属性", () => {
  853. // 与 node/actor 那三张表刻意不同(那里无法定位即不建条目):为了一个残缺的 ref 把问题
  854. // 藏起来,恰好毁掉「被卡住的问题必须可见」这个唯一的兜底价值。
  855. const progress = progressLog();
  856. const state = reduceAll([
  857. progress("run-started", started()),
  858. progress("escalation-raised", raised({ actor: { siteId: "actor#1" } })),
  859. ]);
  860. const pending = state?.runs[0]?.pendingQuestions?.[0];
  861. expect(pending?.qid).toBe("dwfq-dwfrun1-1");
  862. expect(pending).not.toHaveProperty("actorSiteId");
  863. expect(pending).not.toHaveProperty("actorOrdinal");
  864. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  865. });
  866. it("缺 qid 或 question 的事件不建条目,只抬水位", () => {
  867. const progress = progressLog();
  868. const { qid: _noQid, ...withoutQid } = raised();
  869. const { question: _noQuestion, ...withoutQuestion } = raised();
  870. const state = reduceAll([
  871. progress("run-started", started()),
  872. progress("escalation-raised", withoutQid),
  873. progress("escalation-raised", withoutQuestion),
  874. ]);
  875. expect(state?.runs[0]?.pendingQuestions).toBeUndefined();
  876. expect(state?.runs[0]?.lastEventSequence).toBe(2);
  877. });
  878. it("升级不进图也不动 actor 状态:不写节点、不计步(等待不是工作量)", () => {
  879. const progress = progressLog();
  880. const state = reduceAll([
  881. progress("run-started", started()),
  882. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "poet" }),
  883. progress("node-queued", {
  884. instance: { siteId: "ask#1", ordinal: 1 },
  885. kind: "ask",
  886. actor: { siteId: "actor#1", ordinal: 1 },
  887. }),
  888. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  889. progress("node-executing", { instance: { siteId: "ask#1", ordinal: 1 } }),
  890. progress("escalation-raised", raised()),
  891. ]);
  892. expect(state?.runs[0]?.nodes).toHaveLength(1);
  893. // 那一次 ask 派发计了一步;升级本身不再加。
  894. expect(state?.runs[0]?.usage.nodesUsed).toBe(1);
  895. // 提问的 actor 仍然在跑——它那次 ask 还是 executing 的,停驻不等于空闲。
  896. expect(state?.runs[0]?.actors[0]?.status).toBe("running");
  897. });
  898. it("同一条 raised 重放是 no-op(按 qid upsert,不是 push)", () => {
  899. const progress = progressLog();
  900. const event = progress("escalation-raised", raised());
  901. const state = reduceAll([progress("run-started", started()), event]);
  902. expect(state?.runs[0]?.pendingQuestions).toHaveLength(1);
  903. expect(reduceWorkflowRunsState(state, event)).toBeNull();
  904. });
  905. it("escalation-resolved 划掉对应那条,最后一条走后整个键缺席(不留空数组)", () => {
  906. const progress = progressLog();
  907. const state = reduceAll([
  908. progress("run-started", started()),
  909. progress("escalation-raised", raised()),
  910. progress("escalation-resolved", { qid: "dwfq-dwfrun1-1", answer: "门确实坏了,跳过它。" }),
  911. ]);
  912. // 「零条 ⇒ 键缺席」是协议约定:侧栏据此整区不渲染,而不是留一节空壳。
  913. expect(state?.runs[0]).not.toHaveProperty("pendingQuestions");
  914. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  915. });
  916. it("多个问题并存时 resolve 只动对应那条(一轮里可以并行发出几个 escalate)", () => {
  917. const progress = progressLog();
  918. const state = reduceAll([
  919. progress("run-started", started()),
  920. progress("escalation-raised", raised({ qid: "dwfq-a" })),
  921. progress(
  922. "escalation-raised",
  923. raised({ qid: "dwfq-b", actorName: "critic", question: "用哪版风格指南?" }),
  924. ),
  925. progress("escalation-raised", raised({ qid: "dwfq-c" })),
  926. progress("escalation-resolved", { qid: "dwfq-b", answer: "用 v2。" }),
  927. ]);
  928. expect(state?.runs[0]?.pendingQuestions?.map((pending) => pending.qid)).toEqual([
  929. "dwfq-a",
  930. "dwfq-c",
  931. ]);
  932. });
  933. it("resolve 一个不在表里的 qid 不动那张表,只抬水位(与 log 同族)", () => {
  934. // qid 全局唯一(跨 run),所以一条串错 run 的 resolved 事件必然找不到条目。它仍然是一条
  935. // 到达过的事件,水位照抬——「无变化」只对**内容**成立(幂等的那一条见下一例)。
  936. const progress = progressLog();
  937. const state = reduceAll([
  938. progress("run-started", started()),
  939. progress("escalation-raised", raised()),
  940. ]);
  941. const next = reduceWorkflowRunsState(state, {
  942. runId: RUN_ID,
  943. toolCallId: "tc-1",
  944. sequence: 9,
  945. eventType: "escalation-resolved",
  946. payload: { qid: "dwfq-别的-run", answer: "无关" },
  947. });
  948. expect(next?.runs[0]?.pendingQuestions?.map((pending) => pending.qid)).toEqual([
  949. "dwfq-dwfrun1-1",
  950. ]);
  951. expect(next?.runs[0]?.lastEventSequence).toBe(9);
  952. });
  953. it("同一条 resolved 重放是 no-op:不抬 revision、不改状态", () => {
  954. // 重放同一条事件时 sequence 也一样,水位不动,于是整条 run 逐字节相同 → null。
  955. // 这才是「幂等」真正落地的地方(journal 有序投递,重传只会重传队尾)。
  956. const progress = progressLog();
  957. const parked = reduceAll([
  958. progress("run-started", started()),
  959. progress("escalation-raised", raised()),
  960. ]);
  961. const resolve = progress("escalation-resolved", {
  962. qid: "dwfq-dwfrun1-1",
  963. answer: "门确实坏了,跳过它。",
  964. });
  965. const state = reduceAll([resolve], parked);
  966. expect(state?.runs[0]).not.toHaveProperty("pendingQuestions");
  967. expect(reduceWorkflowRunsState(state, resolve)).toBeNull();
  968. });
  969. it("run 从没有过停驻问题时,resolved 不凭空造出一个空数组", () => {
  970. const progress = progressLog();
  971. const state = reduceAll([
  972. progress("run-started", started()),
  973. progress("escalation-resolved", { qid: "dwfq-dwfrun1-1", answer: "…" }),
  974. ]);
  975. expect(state?.runs[0]).not.toHaveProperty("pendingQuestions");
  976. });
  977. it.each(["completed", "errored", "stopped"] as const)(
  978. "run-settled(%s)清空停驻问题:终态 run 没有在听的人",
  979. (status) => {
  980. // 真相是进程内的停驻 deferred。cancel 时它们随 cancelAsk 被拒,进程亡故则整张注册表
  981. // 消失——`resolved` 事件永远不会来。留着等于摆出一个不可能被作答的问题。
  982. const progress = progressLog();
  983. const state = reduceAll([
  984. progress("run-started", started()),
  985. progress("escalation-raised", raised()),
  986. progress("run-settled", { status }),
  987. ]);
  988. expect(state?.runs[0]?.status).toBe(status);
  989. expect(state?.runs[0]).not.toHaveProperty("pendingQuestions");
  990. },
  991. );
  992. it("停止后重新开始,可以用新 qid 建立停驻问题", () => {
  993. // 新的一世里那个 ask 会重跑、actor 重新提问、得一个新 qid;旧的留着只会是永远等不到
  994. // 答案、也再没有人在等它的残影。
  995. const progress = progressLog();
  996. const state = reduceAll([
  997. progress("run-started", started()),
  998. progress("escalation-raised", raised()),
  999. progress("run-settled", { status: "stopped", stopReason: "user" }),
  1000. progress("run-started", started()),
  1001. progress("escalation-raised", raised({ qid: "dwfq-dwfrun1-2" })),
  1002. ]);
  1003. expect(state?.runs[0]?.status).toBe("running");
  1004. expect(state?.runs[0]?.pendingQuestions?.map((pending) => pending.qid)).toEqual([
  1005. "dwfq-dwfrun1-2",
  1006. ]);
  1007. });
  1008. it("触上限置 truncated 且不再增长,但表内已有的 qid 仍可被更新与划掉", () => {
  1009. const progress = progressLog();
  1010. let state: WorkflowRunsState | undefined = step(undefined, progress("run-started", started()));
  1011. for (let index = 1; index <= WORKFLOW_RUNS_LIMITS.maxPendingQuestions + 3; index += 1) {
  1012. state = reduceAll([progress("escalation-raised", raised({ qid: `dwfq-${index}` }))], state);
  1013. }
  1014. expect(state?.runs[0]?.pendingQuestions).toHaveLength(WORKFLOW_RUNS_LIMITS.maxPendingQuestions);
  1015. expect(state?.runs[0]?.truncated).toBe(true);
  1016. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  1017. const resolved = reduceAll(
  1018. [progress("escalation-resolved", { qid: "dwfq-1", answer: "好" })],
  1019. state,
  1020. );
  1021. expect(resolved?.runs[0]?.pendingQuestions).toHaveLength(
  1022. WORKFLOW_RUNS_LIMITS.maxPendingQuestions - 1,
  1023. );
  1024. });
  1025. it("超长问题按上限截断,产出仍过 strict schema", () => {
  1026. const progress = progressLog();
  1027. const long = "问".repeat(WORKFLOW_RUNS_LIMITS.maxQuestionLength + 50);
  1028. const state = reduceAll([
  1029. progress("run-started", started()),
  1030. progress("escalation-raised", raised({ question: long, context: long })),
  1031. ]);
  1032. const pending = state?.runs[0]?.pendingQuestions?.[0];
  1033. expect(pending?.question).toHaveLength(WORKFLOW_RUNS_LIMITS.maxQuestionLength);
  1034. // 省略号让截断在 UI 上可见(与 report 预览同一个习语)。
  1035. expect(pending?.question.endsWith("…")).toBe(true);
  1036. expect(pending?.context).toHaveLength(WORKFLOW_RUNS_LIMITS.maxQuestionLength);
  1037. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  1038. });
  1039. });
  1040. describe("reduceWorkflowRunsState:纯度", () => {
  1041. it("不改动传入态(新态是新对象,旧态逐字节不变)", () => {
  1042. const progress = progressLog();
  1043. const before = reduceAll([progress("run-started", started())])!;
  1044. const frozen = JSON.parse(JSON.stringify(before)) as WorkflowRunsState;
  1045. const after = reduceWorkflowRunsState(
  1046. before,
  1047. progress("node-queued", {
  1048. instance: { siteId: "ask#1", ordinal: 1 },
  1049. kind: "ask",
  1050. }),
  1051. );
  1052. expect(before).toEqual(frozen);
  1053. expect(after).not.toBe(before);
  1054. expect(after?.runs[0]).not.toBe(before.runs[0]);
  1055. });
  1056. it("payload 非 record 时退化成空 payload,不抛", () => {
  1057. const state = reduceWorkflowRunsState(undefined, {
  1058. runId: RUN_ID,
  1059. sequence: 0,
  1060. eventType: "run-started",
  1061. payload: undefined,
  1062. });
  1063. expect(state?.runs[0]).toMatchObject({
  1064. status: "running",
  1065. usage: { spentTokens: 0, nodesUsed: 0 },
  1066. });
  1067. });
  1068. });
  1069. // ── 自适应并发(docs/dynamic-workflow/concurrency.md「Protocol and UI」):node-waiting / node-executing /
  1070. // concurrency-changed 三条观察事件。它们与 escalation 同族——引擎不据其决策,只是 driver /
  1071. // 治理器观察到的事实经 record() 落下来;归约侧同样只做"记下它",不推导任何时钟。
  1072. describe("reduceWorkflowRunsState:自适应并发", () => {
  1073. const ASK = { siteId: "ask#1", ordinal: 1 };
  1074. const ACTOR = { siteId: "actor#1", ordinal: 1 };
  1075. function dispatchedState() {
  1076. const progress = progressLog();
  1077. const state = reduceAll([
  1078. progress("run-started", started()),
  1079. progress("actor-created", { actor: ACTOR, name: "planner" }),
  1080. progress("node-queued", { instance: ASK, kind: "ask", actor: ACTOR, actorSeq: 1 }),
  1081. progress("node-dispatched", { instance: ASK }),
  1082. ]);
  1083. return { progress, state };
  1084. }
  1085. it("node-executing:相位 executing、actor running,过 strict schema", () => {
  1086. const { progress, state } = dispatchedState();
  1087. const next = step(state, progress("node-executing", { instance: ASK }));
  1088. expect(next.runs[0]?.nodes[0]).toEqual({
  1089. siteId: "ask#1",
  1090. ordinal: 1,
  1091. kind: "ask",
  1092. phase: "executing",
  1093. actorSiteId: "actor#1",
  1094. actorOrdinal: 1,
  1095. });
  1096. expect(next.runs[0]?.actors[0]?.status).toBe("running");
  1097. expect(() => workflowRunsStateSchema.parse(next)).not.toThrow();
  1098. });
  1099. it("node-waiting(slot / backoff):相位 waiting、actor waiting;载荷细节不进状态(只在事件日志)", () => {
  1100. const { progress, state } = dispatchedState();
  1101. for (const payload of [
  1102. { instance: ASK, cause: "slot" },
  1103. {
  1104. instance: ASK,
  1105. cause: "backoff",
  1106. reason: "rate_limited",
  1107. attempt: 2,
  1108. delayMs: 20_000,
  1109. retryAfterMs: 20_000,
  1110. },
  1111. ]) {
  1112. const next = step(
  1113. step(state, progress("node-executing", { instance: ASK })),
  1114. progress("node-waiting", payload),
  1115. );
  1116. expect(next.runs[0]?.nodes[0]).toEqual({
  1117. siteId: "ask#1",
  1118. ordinal: 1,
  1119. kind: "ask",
  1120. phase: "waiting",
  1121. actorSiteId: "actor#1",
  1122. actorOrdinal: 1,
  1123. });
  1124. expect(next.runs[0]?.actors[0]?.status).toBe("waiting");
  1125. expect(() => workflowRunsStateSchema.parse(next)).not.toThrow();
  1126. }
  1127. });
  1128. it("waiting → executing → settled:来回切换后结算,actor 走 waiting → running → completed", () => {
  1129. const { progress, state } = dispatchedState();
  1130. const waiting = step(state, progress("node-waiting", { instance: ASK, cause: "slot" }));
  1131. expect(waiting.runs[0]?.actors[0]?.status).toBe("waiting");
  1132. const executing = step(waiting, progress("node-executing", { instance: ASK }));
  1133. expect(executing.runs[0]?.nodes[0]).toMatchObject({ phase: "executing" });
  1134. expect(executing.runs[0]?.actors[0]?.status).toBe("running");
  1135. const settled = step(executing, progress("node-settled", { instance: ASK, outcome: "ok" }));
  1136. expect(settled.runs[0]?.nodes[0]).toMatchObject({ phase: "settled", outcome: "ok" });
  1137. expect(settled.runs[0]?.actors[0]?.status).toBe("completed");
  1138. });
  1139. it("concurrency-changed:cap=next,ceiling 取见过的最大 previous/next,cooldownMs 与 key 透传", () => {
  1140. const { progress, state } = dispatchedState();
  1141. const next = step(
  1142. state,
  1143. progress("concurrency-changed", {
  1144. key: "anthropic/claude-x",
  1145. previous: 14,
  1146. next: 7,
  1147. reason: "rate_limited",
  1148. cooldownMs: 20_000,
  1149. }),
  1150. );
  1151. expect(next.runs[0]?.concurrency).toEqual({
  1152. key: "anthropic/claude-x",
  1153. cap: 7,
  1154. ceiling: 14,
  1155. cooldownMs: 20_000,
  1156. });
  1157. expect(() => workflowRunsStateSchema.parse(next)).not.toThrow();
  1158. });
  1159. it("ceiling 只升不降:后续 recovered 事件把 cap 抬回去时 ceiling 不变;无 Retry-After 的减半不带 cooldownMs", () => {
  1160. const { progress, state } = dispatchedState();
  1161. const halved = step(
  1162. state,
  1163. progress("concurrency-changed", { key: "k", previous: 14, next: 7, reason: "rate_limited" }),
  1164. );
  1165. expect(halved.runs[0]?.concurrency).toEqual({ key: "k", cap: 7, ceiling: 14 });
  1166. const recovered = step(
  1167. halved,
  1168. progress("concurrency-changed", { key: "k", previous: 7, next: 8, reason: "recovered" }),
  1169. );
  1170. expect(recovered.runs[0]?.concurrency).toEqual({ key: "k", cap: 8, ceiling: 14 });
  1171. });
  1172. it("idle_reset 清掉冷却:桶回到天花板不是冷却", () => {
  1173. const { progress, state } = dispatchedState();
  1174. const cooled = step(
  1175. state,
  1176. progress("concurrency-changed", {
  1177. key: "k",
  1178. previous: 14,
  1179. next: 7,
  1180. reason: "rate_limited",
  1181. cooldownMs: 60_000,
  1182. }),
  1183. );
  1184. const reset = step(
  1185. cooled,
  1186. progress("concurrency-changed", {
  1187. key: "k",
  1188. previous: 7,
  1189. next: 14,
  1190. reason: "idle_reset",
  1191. cooldownMs: 1,
  1192. }),
  1193. );
  1194. expect(reset.runs[0]?.concurrency).toEqual({ key: "k", cap: 14, ceiling: 14 });
  1195. });
  1196. it("run-settled 摘掉 cooldownMs、保留 cap/ceiling(历史事实)", () => {
  1197. const { progress, state } = dispatchedState();
  1198. const cooled = step(
  1199. state,
  1200. progress("concurrency-changed", {
  1201. previous: 14,
  1202. next: 7,
  1203. reason: "provider_overloaded",
  1204. cooldownMs: 60_000,
  1205. }),
  1206. );
  1207. const settled = step(cooled, progress("run-settled", { status: "completed" }));
  1208. expect(settled.runs[0]?.concurrency).toEqual({ cap: 7, ceiling: 14 });
  1209. });
  1210. it("concurrency-changed 不碰 nodes / actors,next 读不动时只抬水位", () => {
  1211. const { progress, state } = dispatchedState();
  1212. const before = state!.runs[0]!;
  1213. const next = step(
  1214. state,
  1215. progress("concurrency-changed", { previous: 14, next: 7, reason: "rate_limited" }),
  1216. );
  1217. expect(next.runs[0]?.nodes).toEqual(before.nodes);
  1218. expect(next.runs[0]?.actors).toEqual(before.actors);
  1219. const malformed = step(next, progress("concurrency-changed", { previous: 7, next: "x" }));
  1220. expect(malformed.runs[0]?.concurrency).toEqual(next.runs[0]?.concurrency);
  1221. expect(malformed.runs[0]?.lastEventSequence).toBeGreaterThan(next.runs[0]!.lastEventSequence);
  1222. });
  1223. it("幂等:同一条 node-waiting / concurrency-changed 重放得到 null", () => {
  1224. const { progress, state } = dispatchedState();
  1225. const waitingEvent = progress("node-waiting", { instance: ASK, cause: "slot" });
  1226. const once = step(state, waitingEvent);
  1227. expect(reduceWorkflowRunsState(once, waitingEvent)).toBeNull();
  1228. const changeEvent = progress("concurrency-changed", {
  1229. previous: 14,
  1230. next: 7,
  1231. reason: "rate_limited",
  1232. cooldownMs: 5_000,
  1233. });
  1234. const changed = step(once, changeEvent);
  1235. expect(reduceWorkflowRunsState(changed, changeEvent)).toBeNull();
  1236. });
  1237. // ── 本 run 自己的那条界(docs/dynamic-workflow/concurrency.md「Two bounds on a run」)──
  1238. // `run-started` 载荷带引擎的 `caps.maxConcurrency` 与 CLI 铸载荷那一刻的默认并发 D
  1239. // (线上键名 `concurrencyCeiling` 早于「默认并发」,为兼容旧端保留)。两条界互不相干:治理器
  1240. // 压共享桶,用户调这一条——高于或低于 D 都行。
  1241. const LIMITED = { ...started({ maxConcurrency: 3 }), concurrencyCeiling: 8 };
  1242. it("run-started:maxConcurrency 低于默认时落 limit,共享 cap 从默认起步", () => {
  1243. const progress = progressLog();
  1244. const state = step(undefined, progress("run-started", LIMITED));
  1245. expect(state.runs[0]?.concurrency).toEqual({ cap: 8, ceiling: 8, limit: 3 });
  1246. expect(() => workflowRunsStateSchema.parse(state)).not.toThrow();
  1247. });
  1248. it.each([
  1249. ["跑在默认上", { ...started({ maxConcurrency: 8 }), concurrencyCeiling: 8 }],
  1250. ["老 CLI 不发默认", started({ maxConcurrency: 3 })],
  1251. ["maxConcurrency 读不动", { ...started({ maxConcurrency: 0 }), concurrencyCeiling: 8 }],
  1252. ["天花板读不动", { ...started({ maxConcurrency: 3 }), concurrencyCeiling: "8" }],
  1253. ["caps 整块读不动", { caps: "nope", concurrencyCeiling: 8, runId: RUN_ID }],
  1254. ])("%s:整个 concurrency 键缺席(没有可显示的东西)", (_case, payload) => {
  1255. const state = step(undefined, progressLog()("run-started", payload));
  1256. expect(state.runs[0]).not.toHaveProperty("concurrency");
  1257. });
  1258. it("run-started:maxConcurrency 高于默认同样落 limit——默认是起点不是上限", () => {
  1259. const progress = progressLog();
  1260. const state = step(
  1261. undefined,
  1262. progress("run-started", { ...started({ maxConcurrency: 20 }), concurrencyCeiling: 8 }),
  1263. );
  1264. expect(state.runs[0]?.concurrency).toEqual({ cap: 8, ceiling: 8, limit: 20 });
  1265. expect(() => workflowRunsStateSchema.parse(state)).not.toThrow();
  1266. });
  1267. it("默认已知时 concurrency.ceiling 就是 D:共享桶长到 D 之上也不抬它", () => {
  1268. const progress = progressLog();
  1269. const state = step(
  1270. undefined,
  1271. progress("run-started", { ...started({ maxConcurrency: 20 }), concurrencyCeiling: 8 }),
  1272. );
  1273. const grown = step(
  1274. state,
  1275. progress("concurrency-changed", { key: "k", previous: 11, next: 12, reason: "recovered" }),
  1276. );
  1277. expect(grown.runs[0]?.concurrency).toEqual({ key: "k", cap: 12, ceiling: 8, limit: 20 });
  1278. const lowered = step(
  1279. grown,
  1280. progress("concurrency-changed", { key: "k", previous: 12, next: 9, reason: "limit_lowered" }),
  1281. );
  1282. expect(lowered.runs[0]?.concurrency).toEqual({ key: "k", cap: 9, ceiling: 8, limit: 20 });
  1283. // 默认跑的 run 同理:水位不再是「见过的最大 cap」。
  1284. const plain = progressLog();
  1285. const atDefault = step(
  1286. undefined,
  1287. plain("run-started", { ...started({ maxConcurrency: 8 }), concurrencyCeiling: 8 }),
  1288. );
  1289. const cut = step(
  1290. atDefault,
  1291. plain("concurrency-changed", { key: "k", previous: 14, next: 10, reason: "rate_limited" }),
  1292. );
  1293. expect(cut.runs[0]?.concurrency).toEqual({ key: "k", cap: 10, ceiling: 8 });
  1294. });
  1295. it("concurrency-changed 照搬 limit:共享桶的涨落改不了用户定的界", () => {
  1296. const progress = progressLog();
  1297. const state = step(undefined, progress("run-started", LIMITED));
  1298. const cut = step(
  1299. state,
  1300. progress("concurrency-changed", { previous: 8, next: 6, reason: "rate_limited" }),
  1301. );
  1302. expect(cut.runs[0]?.concurrency).toEqual({ cap: 6, ceiling: 8, limit: 3 });
  1303. // 终态只摘冷却;两条界都是「这次 run 跑在什么并发下」的历史事实,照留。
  1304. const settled = step(cut, progress("run-settled", { status: "completed" }));
  1305. expect(settled.runs[0]?.concurrency).toEqual({ cap: 6, ceiling: 8, limit: 3 });
  1306. });
  1307. it("resume 再发一条 run-started:不拿天花板盖掉进程里已经学到的 cap", () => {
  1308. const progress = progressLog();
  1309. const first = step(undefined, progress("run-started", LIMITED));
  1310. const throttled = step(
  1311. first,
  1312. progress("concurrency-changed", { key: "k", previous: 8, next: 2, reason: "rate_limited" }),
  1313. );
  1314. expect(throttled.runs[0]?.concurrency).toEqual({ key: "k", cap: 2, ceiling: 8, limit: 3 });
  1315. const resumed = step(throttled, progress("run-started", LIMITED));
  1316. expect(resumed.runs[0]?.concurrency).toEqual({ key: "k", cap: 2, ceiling: 8, limit: 3 });
  1317. });
  1318. // 天花板单独记一份(docs/dynamic-workflow/concurrency.md「Protocol state」):「配置」弹层的步进器
  1319. // 停在这里,而跑在天花板上的 run 没有 `concurrency` 可挂。
  1320. it("run-started 记下 concurrencyCeiling,不论本 run 是否低于它", () => {
  1321. const progress = progressLog();
  1322. const atCeiling = step(
  1323. undefined,
  1324. progress("run-started", { ...started({ maxConcurrency: 8 }), concurrencyCeiling: 8 }),
  1325. );
  1326. expect(atCeiling.runs[0]?.concurrencyCeiling).toBe(8);
  1327. expect(atCeiling.runs[0]).not.toHaveProperty("concurrency");
  1328. const limited = step(undefined, progressLog()("run-started", LIMITED));
  1329. expect(limited.runs[0]?.concurrencyCeiling).toBe(8);
  1330. expect(() => workflowRunsStateSchema.parse(atCeiling)).not.toThrow();
  1331. });
  1332. it.each([
  1333. ["老 CLI 不发天花板", started({ maxConcurrency: 3 })],
  1334. ["天花板读不动", { ...started({ maxConcurrency: 3 }), concurrencyCeiling: "8" }],
  1335. ["天花板越界", { ...started({ maxConcurrency: 3 }), concurrencyCeiling: 100_000 }],
  1336. ])("%s:没有 concurrencyCeiling 键;已知值被后来读不出的载荷沿用", (_case, payload) => {
  1337. const fresh = step(undefined, progressLog()("run-started", payload));
  1338. expect(fresh.runs[0]).not.toHaveProperty("concurrencyCeiling");
  1339. const progress = progressLog();
  1340. const known = step(undefined, progress("run-started", LIMITED));
  1341. const again = step(known, progress("run-started", payload));
  1342. expect(again.runs[0]?.concurrencyCeiling).toBe(8);
  1343. });
  1344. // ── 在飞改界(docs/dynamic-workflow/concurrency.md)──────────────────────────────────
  1345. // 只改 `max_concurrency` 的修订就地生效:不停这次 run、不另起一次,引擎改完 caps 发
  1346. // `run-caps-changed`。载荷与 `run-started` 同形(`caps` + CLI 拼进来的 `concurrencyCeiling`),
  1347. // 所以归约必须与 `run-started` 得出同一份状态——同一个数经两条路进来不能有两份读数。
  1348. /** `run-caps-changed` 的载荷;`ceiling: null` = 这条载荷不带天花板(与 run-started 同一种老 CLI)。 */
  1349. const capsChanged = (maxConcurrency: unknown, previous = 3, ceiling: unknown = 8) => ({
  1350. runId: RUN_ID,
  1351. caps: { maxConcurrency },
  1352. previous: { maxConcurrency: previous },
  1353. ...(ceiling === null ? {} : { concurrencyCeiling: ceiling }),
  1354. });
  1355. it("run-caps-changed:limit 就地改成新值,共享桶那一侧一个字不动", () => {
  1356. const progress = progressLog();
  1357. const state = step(undefined, progress("run-started", LIMITED));
  1358. const throttled = step(
  1359. state,
  1360. progress("concurrency-changed", { key: "k", previous: 8, next: 6, reason: "rate_limited" }),
  1361. );
  1362. const retuned = step(throttled, progress("run-caps-changed", capsChanged(2)));
  1363. expect(retuned.runs[0]?.concurrency).toEqual({ key: "k", cap: 6, ceiling: 8, limit: 2 });
  1364. expect(() => workflowRunsStateSchema.parse(retuned)).not.toThrow();
  1365. // 之后的共享桶涨落照旧不碰新界(与 run-started 带来的界同一条规则)。
  1366. const recovered = step(
  1367. retuned,
  1368. progress("concurrency-changed", { key: "k", previous: 6, next: 8, reason: "recovered" }),
  1369. );
  1370. expect(recovered.runs[0]?.concurrency).toEqual({ key: "k", cap: 8, ceiling: 8, limit: 2 });
  1371. });
  1372. it("run-caps-changed 抬到默认之上:同样落 limit", () => {
  1373. const progress = progressLog();
  1374. const state = step(undefined, progress("run-started", LIMITED));
  1375. const raised = step(state, progress("run-caps-changed", capsChanged(24)));
  1376. expect(raised.runs[0]?.concurrency).toEqual({ cap: 8, ceiling: 8, limit: 24 });
  1377. });
  1378. it("从默认之上调回默认:共享 cap 在 D 之上也算无话可说,整个 concurrency 键缺席", () => {
  1379. const progress = progressLog();
  1380. const state = step(
  1381. undefined,
  1382. progress("run-started", { ...started({ maxConcurrency: 20 }), concurrencyCeiling: 8 }),
  1383. );
  1384. const grown = step(
  1385. state,
  1386. progress("concurrency-changed", { key: "k", previous: 11, next: 12, reason: "recovered" }),
  1387. );
  1388. const back = step(grown, progress("run-caps-changed", capsChanged(8, 20)));
  1389. expect(back.runs[0]).not.toHaveProperty("concurrency");
  1390. expect(back.runs[0]?.concurrencyCeiling).toBe(8);
  1391. });
  1392. it("run-caps-changed 也能给一个从未被压低的 run 立一条界:共享 cap 从默认起步", () => {
  1393. const progress = progressLog();
  1394. const atCeiling = step(
  1395. undefined,
  1396. progress("run-started", { ...started({ maxConcurrency: 8 }), concurrencyCeiling: 8 }),
  1397. );
  1398. expect(atCeiling.runs[0]).not.toHaveProperty("concurrency");
  1399. const limited = step(atCeiling, progress("run-caps-changed", capsChanged(3, 8)));
  1400. expect(limited.runs[0]?.concurrency).toEqual({ cap: 8, ceiling: 8, limit: 3 });
  1401. });
  1402. it("调回默认:limit 摘掉;共享桶无话可说时整个 concurrency 键随之缺席", () => {
  1403. const progress = progressLog();
  1404. const state = step(undefined, progress("run-started", LIMITED));
  1405. expect(state.runs[0]?.concurrency).toEqual({ cap: 8, ceiling: 8, limit: 3 });
  1406. const lifted = step(state, progress("run-caps-changed", capsChanged(8)));
  1407. // 与一个从没被压低过的 run 逐字节相同(天花板另记在 concurrencyCeiling 上)。
  1408. expect(lifted.runs[0]).not.toHaveProperty("concurrency");
  1409. expect(lifted.runs[0]?.concurrencyCeiling).toBe(8);
  1410. });
  1411. it.each([
  1412. ["共享桶被压低", { key: "k", previous: 8, next: 6, reason: "rate_limited" }, { cap: 6 }],
  1413. [
  1414. "还在冷却",
  1415. { key: "k", previous: 8, next: 8, reason: "rate_limited", cooldownMs: 30_000 },
  1416. { cap: 8, cooldownMs: 30_000 },
  1417. ],
  1418. ])("调回默认但%s:只摘 limit,共享桶那一侧留着", (_case, changed, expected) => {
  1419. const progress = progressLog();
  1420. const state = step(undefined, progress("run-started", LIMITED));
  1421. const shared = step(state, progress("concurrency-changed", changed));
  1422. const lifted = step(shared, progress("run-caps-changed", capsChanged(8)));
  1423. expect(lifted.runs[0]?.concurrency).toEqual({ key: "k", ceiling: 8, ...expected });
  1424. });
  1425. it.each([
  1426. ["caps 整块读不动", { runId: RUN_ID, caps: "nope", concurrencyCeiling: 8 }],
  1427. ["maxConcurrency 读不动", capsChanged("2")],
  1428. ["maxConcurrency 非正", capsChanged(0)],
  1429. ])("%s:界一个字不改(只抬水位,与 concurrency-changed 同一条兜底)", (_case, payload) => {
  1430. const progress = progressLog();
  1431. const state = step(undefined, progress("run-started", LIMITED));
  1432. const after = step(state, progress("run-caps-changed", payload));
  1433. expect(after.runs[0]?.concurrency).toEqual({ cap: 8, ceiling: 8, limit: 3 });
  1434. expect(after.runs[0]?.concurrencyCeiling).toBe(8);
  1435. });
  1436. it("载荷不带天花板:退回本 run 已知的那个(天花板是整条 run 恒定的进程事实)", () => {
  1437. const progress = progressLog();
  1438. const state = step(undefined, progress("run-started", LIMITED));
  1439. const retuned = step(state, progress("run-caps-changed", capsChanged(2, 3, null)));
  1440. expect(retuned.runs[0]?.concurrency).toEqual({ cap: 8, ceiling: 8, limit: 2 });
  1441. // 天花板从未知过(老 CLI 的 run):判不出这个数是否被压低,界一个字不改。
  1442. const blind = progressLog();
  1443. const unknown = step(undefined, blind("run-started", started({ maxConcurrency: 3 })));
  1444. const after = step(unknown, blind("run-caps-changed", capsChanged(2, 3, null)));
  1445. expect(after.runs[0]).not.toHaveProperty("concurrency");
  1446. expect(after.runs[0]).not.toHaveProperty("concurrencyCeiling");
  1447. });
  1448. it("run-caps-changed 记下载荷里的天花板(与 run-started 同一条)", () => {
  1449. const progress = progressLog();
  1450. const state = step(undefined, progress("run-started", started({ maxConcurrency: 3 })));
  1451. expect(state.runs[0]).not.toHaveProperty("concurrencyCeiling");
  1452. const retuned = step(state, progress("run-caps-changed", capsChanged(2)));
  1453. expect(retuned.runs[0]?.concurrencyCeiling).toBe(8);
  1454. expect(retuned.runs[0]?.concurrency).toEqual({ cap: 8, ceiling: 8, limit: 2 });
  1455. });
  1456. it("幂等:同一条 run-caps-changed 重放得到 null", () => {
  1457. const progress = progressLog();
  1458. const state = step(undefined, progress("run-started", LIMITED));
  1459. const event = progress("run-caps-changed", capsChanged(2));
  1460. const retuned = step(state, event);
  1461. expect(reduceWorkflowRunsState(retuned, event)).toBeNull();
  1462. });
  1463. });
  1464. // ── 子代理模型(docs/dynamic-workflow/launch.md)─────────────────────────────────────────
  1465. // `CreateWorkflow` / `AmendWorkflow` 的 `subagent_model` 落到 `run-started` 载荷的
  1466. // `subagentModel`(规范串 `providerId/modelId`,可带 `$reasoningLevel` 后缀)。与
  1467. // `concurrency.limit` 同族:用户给这次 run 定下的条件,整条 run 不动。主代理始终留在会话模型上,
  1468. // 所以这个键说的只是子代理那一侧。
  1469. describe("reduceWorkflowRunsState:子代理模型", () => {
  1470. const withModel = (subagentModel: unknown) => ({ ...started(), subagentModel });
  1471. it("run-started 带 subagentModel 时记下它,产出过 strict schema", () => {
  1472. const state = step(undefined, progressLog()("run-started", withModel("zhipu/glm-5.3-flash")));
  1473. expect(state.runs[0]?.subagentModel).toBe("zhipu/glm-5.3-flash");
  1474. expect(() => workflowRunsStateSchema.parse(state)).not.toThrow();
  1475. });
  1476. it("带推理档后缀的规范串原样留着:档位是模型选择的一部分,不是可丢的修饰", () => {
  1477. const state = step(undefined, progressLog()("run-started", withModel("anthropic/opus-5$high")));
  1478. expect(state.runs[0]?.subagentModel).toBe("anthropic/opus-5$high");
  1479. });
  1480. it("两侧空白裁掉:显示的是模型 id,不是载荷的排版", () => {
  1481. const state = step(undefined, progressLog()("run-started", withModel(" zhipu/glm-5.3 ")));
  1482. expect(state.runs[0]?.subagentModel).toBe("zhipu/glm-5.3");
  1483. });
  1484. it("后续事件改不了它:整条 run 自始至终说的是同一个模型", () => {
  1485. const progress = progressLog();
  1486. const state = step(undefined, progress("run-started", withModel("zhipu/glm-5.3-flash")));
  1487. const used = step(state, progress("usage-updated", { spentTokens: 4_096 }));
  1488. const throttled = step(
  1489. used,
  1490. progress("concurrency-changed", { previous: 8, next: 4, reason: "rate_limited" }),
  1491. );
  1492. const settled = step(throttled, progress("run-settled", { status: "completed" }));
  1493. expect(settled.runs[0]?.subagentModel).toBe("zhipu/glm-5.3-flash");
  1494. });
  1495. it("重臂不带这个键时保留已知值,而不是让 run 看上去换回了会话模型", () => {
  1496. // 老 CLI 不发它;把已经显示出来的模型抹掉是退化里最坏的一种(读数变了,事实没变)。
  1497. const progress = progressLog();
  1498. const first = step(undefined, progress("run-started", withModel("zhipu/glm-5.3-flash")));
  1499. const resumed = step(first, progress("run-started", started()));
  1500. expect(resumed.runs[0]?.subagentModel).toBe("zhipu/glm-5.3-flash");
  1501. });
  1502. it.each([
  1503. ["缺席(子代理跟随会话模型)", started()],
  1504. ["空串", withModel("")],
  1505. ["只有空白", withModel(" ")],
  1506. ["不是字符串", withModel({ providerId: "zhipu", modelId: "glm-5.3-flash" })],
  1507. [
  1508. "超过线上上界(截断出来的模型 id 是假话)",
  1509. withModel(`zhipu/${"x".repeat(WORKFLOW_RUNS_LIMITS.maxSubagentModelLength)}`),
  1510. ],
  1511. ])("%s:整个键缺席,而不是一个 undefined 值", (_case, payload) => {
  1512. const state = step(undefined, progressLog()("run-started", payload));
  1513. expect(state.runs[0]).not.toHaveProperty("subagentModel");
  1514. expect(() => workflowRunsStateSchema.parse(state)).not.toThrow();
  1515. });
  1516. });
  1517. // ── 用户面产物(docs/dynamic-workflow/authoring.md「How the user sees them」)─────────────────
  1518. // ⚠ 术语:这里的 artifact 是脚本经 `artifact.*` 发布给**用户**看的产出,不是 resultPreview
  1519. // 背后那个「脚本顶层返回值」(引擎内部也叫 artifact,给模型看)。见 workflow-artifacts.ts。
  1520. //
  1521. // 三条归约规则,各有各的键:
  1522. // artifact-published ⇒ 按**产物 id** upsert(同 id 再发布 = 新版本覆盖同一张卡)
  1523. // artifact-failed ⇒ 不动状态(失败的发布不认领 id / 种类 / 版本,只进事件日志)
  1524. // report(artifactId) ⇒ 该 id 的 itemCount 加一(去重键仍是 (siteId, ordinal))
  1525. describe("reduceWorkflowRunsState:用户面产物", () => {
  1526. const PUBLISHED_AT = 1_756_100_000_000;
  1527. const record = (overrides: Record<string, unknown> = {}) => ({
  1528. id: "book",
  1529. kind: "file",
  1530. version: 1,
  1531. title: "注意力之书",
  1532. contentType: "application/pdf",
  1533. bytes: 4_194_304,
  1534. uri: "zcode-artifact://session-1/tool-result-abc",
  1535. sourcePath: "out/book.pdf",
  1536. publishedAt: PUBLISHED_AT,
  1537. ...overrides,
  1538. });
  1539. it("artifact-published 建一张卡,且只留最新版元数据(不带 uri / sourcePath / publishedAt)", () => {
  1540. const progress = progressLog();
  1541. const state = reduceAll([
  1542. progress("run-started", started()),
  1543. progress("artifact-published", {
  1544. instance: { siteId: "artifact#1", ordinal: 1 },
  1545. artifact: record(),
  1546. }),
  1547. ]);
  1548. // 裁剪是这个键的全部理由:高频状态帧只回答「有哪些、第几版、变了没有」。
  1549. expect(state?.runs[0]?.artifacts).toEqual([
  1550. {
  1551. id: "book",
  1552. kind: "file",
  1553. title: "注意力之书",
  1554. version: 1,
  1555. contentType: "application/pdf",
  1556. bytes: 4_194_304,
  1557. },
  1558. ]);
  1559. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  1560. });
  1561. it("交付物的 primary 进快照(UI 据它排先后与选形态);description 仍被裁掉", () => {
  1562. const progress = progressLog();
  1563. const state = reduceAll([
  1564. progress("run-started", started()),
  1565. progress("artifact-published", {
  1566. instance: { siteId: "artifact#1", ordinal: 1 },
  1567. artifact: record({ primary: true, description: "一本书" }),
  1568. }),
  1569. ]);
  1570. expect(state?.runs[0]?.artifacts).toEqual([
  1571. {
  1572. id: "book",
  1573. kind: "file",
  1574. title: "注意力之书",
  1575. version: 1,
  1576. contentType: "application/pdf",
  1577. bytes: 4_194_304,
  1578. primary: true,
  1579. },
  1580. ]);
  1581. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  1582. });
  1583. it("预置看板的声明也走 artifact-published:无 contentType / bytes,spec 不进快照", () => {
  1584. const progress = progressLog();
  1585. const state = reduceAll([
  1586. progress("run-started", started()),
  1587. progress("artifact-published", {
  1588. instance: { siteId: "artifact#1", ordinal: 1 },
  1589. artifact: {
  1590. id: "perf",
  1591. kind: "chart",
  1592. version: 1,
  1593. title: "每轮查询耗时",
  1594. spec: { x: { field: "round" }, y: { field: "queryMs" } },
  1595. publishedAt: PUBLISHED_AT,
  1596. },
  1597. }),
  1598. ]);
  1599. expect(state?.runs[0]?.artifacts).toEqual([
  1600. { id: "perf", kind: "chart", title: "每轮查询耗时", version: 1 },
  1601. ]);
  1602. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  1603. });
  1604. it("同 id 再发布 = 新版本覆盖同一张卡(按产物 id 去重,不是按站点实例)", () => {
  1605. const progress = progressLog();
  1606. const state = reduceAll([
  1607. progress("run-started", started()),
  1608. progress("artifact-published", {
  1609. instance: { siteId: "artifact#1", ordinal: 1 },
  1610. artifact: record(),
  1611. }),
  1612. // 第二次发布来自**另一个**站点实例——按实例去重会长出第二张卡,那是错的。
  1613. progress("artifact-published", {
  1614. instance: { siteId: "artifact#2", ordinal: 1 },
  1615. artifact: record({ version: 2, bytes: 5_000_000, title: "注意力之书(第二版)" }),
  1616. }),
  1617. ]);
  1618. expect(state?.runs[0]?.artifacts).toEqual([
  1619. {
  1620. id: "book",
  1621. kind: "file",
  1622. title: "注意力之书(第二版)",
  1623. version: 2,
  1624. contentType: "application/pdf",
  1625. bytes: 5_000_000,
  1626. },
  1627. ]);
  1628. });
  1629. it("新版本覆盖时**保留** itemCount:正在被喂数据的看板不能被清零", () => {
  1630. const progress = progressLog();
  1631. const state = reduceAll([
  1632. progress("run-started", started()),
  1633. progress("artifact-published", {
  1634. instance: { siteId: "artifact#1", ordinal: 1 },
  1635. artifact: { id: "perf", kind: "chart", version: 1, publishedAt: PUBLISHED_AT },
  1636. }),
  1637. progress("report", {
  1638. instance: { siteId: "report#1", ordinal: 1 },
  1639. item: { round: 1 },
  1640. artifactId: "perf",
  1641. }),
  1642. progress("report", {
  1643. instance: { siteId: "report#1", ordinal: 2 },
  1644. item: { round: 2 },
  1645. artifactId: "perf",
  1646. }),
  1647. // 同 spec 的重复声明在引擎侧是 no-op,但版本记录若真的再来一条,计数必须活下来:
  1648. // 清零会让刷新信号归零,看板从此不再增量取数。
  1649. progress("artifact-published", {
  1650. instance: { siteId: "artifact#1", ordinal: 2 },
  1651. artifact: { id: "perf", kind: "chart", version: 1, publishedAt: PUBLISHED_AT },
  1652. }),
  1653. ]);
  1654. expect(state?.runs[0]?.artifacts).toEqual([
  1655. { id: "perf", kind: "chart", version: 1, itemCount: 2 },
  1656. ]);
  1657. });
  1658. it("artifact-failed 不动任何状态:失败的发布不认领 id / 种类 / 版本", () => {
  1659. const progress = progressLog();
  1660. const started1 = step(undefined, progress("run-started", started()));
  1661. const failed = step(
  1662. started1,
  1663. progress("artifact-failed", {
  1664. instance: { siteId: "artifact#1", ordinal: 1 },
  1665. id: "book",
  1666. op: "file",
  1667. error: { code: "ArtifactSourceMissing", message: "out/book.pdf does not exist" },
  1668. }),
  1669. );
  1670. // 卡片整个不出现——为一件并不存在的交付物摆一张失败卡会让用户看见不存在的东西,
  1671. // 而脚本很可能已经 catch 住它、让子代理补写后重新发布成功了。
  1672. expect(failed.runs[0]?.artifacts).toBeUndefined();
  1673. // 但水位照抬:事件日志需要知道有新内容。
  1674. expect(failed.runs[0]?.lastEventSequence).toBeGreaterThan(started1.runs[0]!.lastEventSequence);
  1675. });
  1676. it("artifact-failed 也不擦掉同 id 已发布成功的旧版本(第 2 版失败,第 1 版仍在)", () => {
  1677. const progress = progressLog();
  1678. const state = reduceAll([
  1679. progress("run-started", started()),
  1680. progress("artifact-published", {
  1681. instance: { siteId: "artifact#1", ordinal: 1 },
  1682. artifact: record(),
  1683. }),
  1684. progress("artifact-failed", {
  1685. instance: { siteId: "artifact#1", ordinal: 2 },
  1686. id: "book",
  1687. op: "file",
  1688. error: { code: "ArtifactTooLarge", message: "too large" },
  1689. }),
  1690. ]);
  1691. expect(state?.runs[0]?.artifacts).toEqual([
  1692. {
  1693. id: "book",
  1694. kind: "file",
  1695. title: "注意力之书",
  1696. version: 1,
  1697. contentType: "application/pdf",
  1698. bytes: 4_194_304,
  1699. },
  1700. ]);
  1701. });
  1702. it("载荷读不动(缺 id / 种类不在闭集 / version 非正整数)时不建卡,只抬水位", () => {
  1703. const progress = progressLog();
  1704. const base = step(undefined, progress("run-started", started()));
  1705. for (const artifact of [
  1706. { kind: "file", version: 1 },
  1707. { id: "x", kind: "spreadsheet", version: 1 },
  1708. { id: "x", kind: "file", version: 0 },
  1709. { id: "x", kind: "file", version: 1.5 },
  1710. { id: "x", kind: "file" },
  1711. "not-a-record",
  1712. ]) {
  1713. const next = step(
  1714. base,
  1715. progress("artifact-published", {
  1716. instance: { siteId: "artifact#1", ordinal: 1 },
  1717. artifact,
  1718. }),
  1719. );
  1720. expect(next.runs[0]?.artifacts).toBeUndefined();
  1721. expect(next.runs[0]?.lastEventSequence).toBeGreaterThan(base.runs[0]!.lastEventSequence);
  1722. }
  1723. });
  1724. it("标签 report 计数:itemCount 随条目增长,条目本身照旧进 reports", () => {
  1725. const progress = progressLog();
  1726. const state = reduceAll([
  1727. progress("run-started", started()),
  1728. progress("artifact-published", {
  1729. instance: { siteId: "artifact#1", ordinal: 1 },
  1730. artifact: { id: "perf", kind: "chart", version: 1, publishedAt: PUBLISHED_AT },
  1731. }),
  1732. progress("report", {
  1733. instance: { siteId: "report#1", ordinal: 1 },
  1734. item: { round: 1 },
  1735. artifactId: "perf",
  1736. }),
  1737. progress("report", {
  1738. instance: { siteId: "report#1", ordinal: 2 },
  1739. item: { round: 2 },
  1740. artifactId: "perf",
  1741. }),
  1742. // 未打标签的条目照旧只进 Results 区,不碰任何产物。
  1743. progress("report", { instance: { siteId: "report#2", ordinal: 1 }, item: "plain" }),
  1744. ]);
  1745. expect(state?.runs[0]?.artifacts).toEqual([
  1746. { id: "perf", kind: "chart", version: 1, itemCount: 2 },
  1747. ]);
  1748. // 一条通道一套上限:打标签只是多一个去处,不是改道。
  1749. expect(state?.runs[0]?.reports).toEqual([
  1750. { siteId: "report#1", ordinal: 1, preview: '{\n "round": 1\n}', artifactId: "perf" },
  1751. { siteId: "report#1", ordinal: 2, preview: '{\n "round": 2\n}', artifactId: "perf" },
  1752. { siteId: "report#2", ordinal: 1, preview: "plain" },
  1753. ]);
  1754. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  1755. });
  1756. it("计数幂等:同一条标签 report 重放不重复计数(去重键与 reports 表同为 (siteId, ordinal))", () => {
  1757. const progress = progressLog();
  1758. const declared = reduceAll([
  1759. progress("run-started", started()),
  1760. progress("artifact-published", {
  1761. instance: { siteId: "artifact#1", ordinal: 1 },
  1762. artifact: { id: "perf", kind: "chart", version: 1, publishedAt: PUBLISHED_AT },
  1763. }),
  1764. ]);
  1765. const event = progress("report", {
  1766. instance: { siteId: "report#1", ordinal: 1 },
  1767. item: { round: 1 },
  1768. artifactId: "perf",
  1769. });
  1770. const once = step(declared, event);
  1771. expect(once.runs[0]?.artifacts?.[0]?.itemCount).toBe(1);
  1772. // 逐字节相同 ⇒ 顶层比对返回 null ⇒ 不抬 revision、不改状态。
  1773. expect(reduceWorkflowRunsState(once, event)).toBeNull();
  1774. expect(once.runs[0]?.artifacts?.[0]?.itemCount).toBe(1);
  1775. });
  1776. it("标签指向未在表里的 id 时忽略计数,条目仍进 reports(运行期已 failRun,这里只是防御)", () => {
  1777. const progress = progressLog();
  1778. const state = reduceAll([
  1779. progress("run-started", started()),
  1780. progress("artifact-published", {
  1781. instance: { siteId: "artifact#1", ordinal: 1 },
  1782. artifact: { id: "perf", kind: "chart", version: 1, publishedAt: PUBLISHED_AT },
  1783. }),
  1784. progress("report", {
  1785. instance: { siteId: "report#1", ordinal: 1 },
  1786. item: { round: 1 },
  1787. artifactId: "ghost",
  1788. }),
  1789. ]);
  1790. expect(state?.runs[0]?.artifacts).toEqual([{ id: "perf", kind: "chart", version: 1 }]);
  1791. expect(state?.runs[0]?.reports).toEqual([
  1792. { siteId: "report#1", ordinal: 1, preview: '{\n "round": 1\n}', artifactId: "ghost" },
  1793. ]);
  1794. });
  1795. it("一张产物都没有时标签 report 不凭空造出一个 artifacts 键", () => {
  1796. const progress = progressLog();
  1797. const state = reduceAll([
  1798. progress("run-started", started()),
  1799. progress("report", {
  1800. instance: { siteId: "report#1", ordinal: 1 },
  1801. item: 1,
  1802. artifactId: "perf",
  1803. }),
  1804. ]);
  1805. expect(state?.runs[0]?.artifacts).toBeUndefined();
  1806. expect(state?.runs[0]?.reports).toHaveLength(1);
  1807. });
  1808. it("零件时整个键缺席(不是空数组)——Artifacts 区据此整区不渲染", () => {
  1809. const progress = progressLog();
  1810. const state = reduceAll([progress("run-started", started()), progress("log", { text: "hi" })]);
  1811. expect(state?.runs[0]).not.toHaveProperty("artifacts");
  1812. });
  1813. it("触上限置 truncated 且不再增长,但表内已有的 id 仍可更新版本与计数", () => {
  1814. const progress = progressLog();
  1815. let state = step(undefined, progress("run-started", started()));
  1816. for (let index = 0; index < WORKFLOW_RUNS_LIMITS.maxArtifacts; index += 1) {
  1817. state = step(
  1818. state,
  1819. progress("artifact-published", {
  1820. instance: { siteId: `artifact#${index + 1}`, ordinal: 1 },
  1821. artifact: { id: `a${index}`, kind: "markdown", version: 1, publishedAt: PUBLISHED_AT },
  1822. }),
  1823. );
  1824. }
  1825. expect(state.runs[0]?.artifacts).toHaveLength(WORKFLOW_RUNS_LIMITS.maxArtifacts);
  1826. expect(state.runs[0]?.truncated).toBeUndefined();
  1827. const overflowed = step(
  1828. state,
  1829. progress("artifact-published", {
  1830. instance: { siteId: "artifact#33", ordinal: 1 },
  1831. artifact: { id: "a33", kind: "markdown", version: 1, publishedAt: PUBLISHED_AT },
  1832. }),
  1833. );
  1834. expect(overflowed.runs[0]?.artifacts).toHaveLength(WORKFLOW_RUNS_LIMITS.maxArtifacts);
  1835. expect(overflowed.runs[0]?.truncated).toBe(true);
  1836. // 拒新、仍更新已有:把一张卡的版本冻在第 1 版比少列一张卡更误导。
  1837. const updated = step(
  1838. overflowed,
  1839. progress("artifact-published", {
  1840. instance: { siteId: "artifact#1", ordinal: 2 },
  1841. artifact: { id: "a0", kind: "markdown", version: 2, publishedAt: PUBLISHED_AT },
  1842. }),
  1843. );
  1844. expect(updated.runs[0]?.artifacts?.[0]).toEqual({ id: "a0", kind: "markdown", version: 2 });
  1845. expect(workflowRunsStateSchema.parse(updated)).toEqual(updated);
  1846. });
  1847. it("产物不进图也不计步:nodes / actors / usage 一个字不动", () => {
  1848. const progress = progressLog();
  1849. const before = reduceAll([
  1850. progress("run-started", started()),
  1851. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "writer" }),
  1852. ]);
  1853. const after = step(
  1854. before,
  1855. progress("artifact-published", {
  1856. instance: { siteId: "artifact#1", ordinal: 1 },
  1857. artifact: record(),
  1858. }),
  1859. );
  1860. expect(after.runs[0]?.nodes).toEqual(before?.runs[0]?.nodes);
  1861. expect(after.runs[0]?.actors).toEqual(before?.runs[0]?.actors);
  1862. expect(after.runs[0]?.usage).toEqual(before?.runs[0]?.usage);
  1863. });
  1864. it("幂等:同一条 artifact-published / artifact-failed 重放得到 null", () => {
  1865. const progress = progressLog();
  1866. const base = step(undefined, progress("run-started", started()));
  1867. const publishEvent = progress("artifact-published", {
  1868. instance: { siteId: "artifact#1", ordinal: 1 },
  1869. artifact: record(),
  1870. });
  1871. const published = step(base, publishEvent);
  1872. expect(reduceWorkflowRunsState(published, publishEvent)).toBeNull();
  1873. // artifact-failed 不改任何**展示**状态,但仍抬水位(事件日志要知道有新内容),
  1874. // 所以它的第一次不是 null,重放才是。
  1875. const failEvent = progress("artifact-failed", {
  1876. instance: { siteId: "artifact#2", ordinal: 1 },
  1877. id: "gone",
  1878. op: "file",
  1879. error: { code: "ArtifactSourceMissing", message: "missing" },
  1880. });
  1881. const failedOnce = step(published, failEvent);
  1882. expect(reduceWorkflowRunsState(failedOnce, failEvent)).toBeNull();
  1883. });
  1884. });
  1885. // ── 阶段进入记录(docs/dynamic-workflow/presentation.md)──────────
  1886. describe("workflowRuns reducer · run-launched(声明阶段表)", () => {
  1887. it("run-launched 携 phaseNames → run.phaseNames 按声明序落位,裁到 maxPhases × maxPhaseNameLength", () => {
  1888. const progress = progressLog();
  1889. const long = "p".repeat(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength + 5);
  1890. const many = Array.from({ length: WORKFLOW_RUNS_LIMITS.maxPhases + 2 }, (_, i) => `s${i}`);
  1891. const state = step(
  1892. step(undefined, progress("run-started", started())),
  1893. progress("run-launched", { inputId: "in-1", phaseNames: ["plan", long, ...many] }),
  1894. );
  1895. const run = state.runs[0]!;
  1896. expect(run.phaseNames).toHaveLength(WORKFLOW_RUNS_LIMITS.maxPhases);
  1897. expect(run.phaseNames?.[0]).toBe("plan");
  1898. expect(run.phaseNames?.[1]).toBe("p".repeat(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength));
  1899. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  1900. });
  1901. it("没有 phaseNames(旧 CLI / 无标记脚本)或空表 → 只抬水位,不建键", () => {
  1902. const progress = progressLog();
  1903. const base = step(undefined, progress("run-started", started()));
  1904. const anchored = step(base, progress("run-launched", { inputId: "in-1" }));
  1905. expect(anchored.runs[0]?.phaseNames).toBeUndefined();
  1906. expect(anchored.runs[0]?.lastEventSequence).toBe(1);
  1907. const empty = step(anchored, progress("run-launched", { inputId: "in-1", phaseNames: [] }));
  1908. expect(empty.runs[0]?.phaseNames).toBeUndefined();
  1909. });
  1910. it("run-launched 携 phaseAlongside → 裁到被接受的名字表,越界 / 自指 / 重复 / 非整数丢掉", () => {
  1911. const progress = progressLog();
  1912. const state = step(
  1913. step(undefined, progress("run-started", started())),
  1914. progress("run-launched", {
  1915. inputId: "in-1",
  1916. phaseNames: ["A", "B", "C"],
  1917. // B 与 A 并行;其余每一项都该被丢掉:自指、越界、负数、小数、重复,以及名字表之外的第四行。
  1918. phaseAlongside: [[], [0, 1, 7, -1, 1.5, 0], [3], [0]],
  1919. }),
  1920. );
  1921. const run = state.runs[0]!;
  1922. // 表按被接受的名字表裁齐——下标指向的就是它,多出来的一行没有站可依。
  1923. expect(run.phaseAlongside).toEqual([[], [0], []]);
  1924. expect(workflowRunsStateSchema.safeParse(state).success).toBe(true);
  1925. });
  1926. it("phaseNames 不在场、或没有一项并行 → phaseAlongside 一起不建键", () => {
  1927. const progress = progressLog();
  1928. const base = step(undefined, progress("run-started", started()));
  1929. // 名字表被拒(缺席)时下标没有可指的表,整张表一起丢。
  1930. const nameless = step(
  1931. base,
  1932. progress("run-launched", { inputId: "in-1", phaseAlongside: [[1], [0]] }),
  1933. );
  1934. expect(nameless.runs[0]?.phaseNames).toBeUndefined();
  1935. expect(nameless.runs[0]?.phaseAlongside).toBeUndefined();
  1936. // 名字表立住但一项都不剩:缺席就是「这条轨道是一条直线」,不是一串空数组。
  1937. const straight = step(
  1938. base,
  1939. progress("run-launched", {
  1940. inputId: "in-1",
  1941. phaseNames: ["A", "B"],
  1942. phaseAlongside: [[], [1]],
  1943. }),
  1944. );
  1945. expect(straight.runs[0]?.phaseNames).toEqual(["A", "B"]);
  1946. expect(straight.runs[0]?.phaseAlongside).toBeUndefined();
  1947. });
  1948. it("resume 的 run-started 不清 phaseNames(同一世只记一次,重放幂等)", () => {
  1949. const progress = progressLog();
  1950. const launched = step(
  1951. step(undefined, progress("run-started", started())),
  1952. progress("run-launched", { inputId: "in-1", phaseNames: ["plan", "verify"] }),
  1953. );
  1954. const settled = step(
  1955. launched,
  1956. progress("run-settled", { status: "stopped", stopReason: "user" }),
  1957. );
  1958. const resumed = step(settled, progress("run-started", started()));
  1959. expect(resumed.runs[0]?.phaseNames).toEqual(["plan", "verify"]);
  1960. expect(
  1961. reduceWorkflowRunsState(
  1962. resumed,
  1963. progress(
  1964. "run-launched",
  1965. { inputId: "in-1", phaseNames: ["plan", "verify"] },
  1966. { sequence: 3 },
  1967. ),
  1968. ),
  1969. ).toBeNull();
  1970. });
  1971. });
  1972. describe("workflowRuns reducer · phase-entered", () => {
  1973. it("首进建条、再入取 max、currentPhase 跟最后一条;不碰 nodes", () => {
  1974. const progress = progressLog();
  1975. const state = reduceAll([
  1976. progress("run-started", started()),
  1977. progress("phase-entered", { name: "plan", ordinal: 1 }),
  1978. progress("phase-entered", { name: "verify", ordinal: 1 }),
  1979. progress("phase-entered", { name: "plan", ordinal: 2 }),
  1980. ]);
  1981. expect(state?.runs[0]?.phases).toEqual([
  1982. { name: "plan", rounds: 2 },
  1983. { name: "verify", rounds: 1 },
  1984. ]);
  1985. expect(state?.runs[0]?.currentPhase).toBe("plan");
  1986. expect(state?.runs[0]?.nodes).toEqual([]);
  1987. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  1988. });
  1989. it("重放幂等:resume 重跑的前缀逐条无变化(rounds 取 max,不是 +1)", () => {
  1990. const progress = progressLog();
  1991. const base = reduceAll([
  1992. progress("run-started", started()),
  1993. progress("phase-entered", { name: "plan", ordinal: 1 }),
  1994. progress("phase-entered", { name: "plan", ordinal: 2 }),
  1995. ]);
  1996. // 引擎在 resume 时从 1 数起再发一遍:rounds 不能变成 3、4。
  1997. const replayed = reduceAll(
  1998. [
  1999. progress("phase-entered", { name: "plan", ordinal: 1 }),
  2000. progress("phase-entered", { name: "plan", ordinal: 2 }),
  2001. ],
  2002. base,
  2003. );
  2004. expect(replayed?.runs[0]?.phases).toEqual([{ name: "plan", rounds: 2 }]);
  2005. });
  2006. it("从未进入过任何阶段时两键缺席;ordinal 缺席按 1 记;名字截到上界", () => {
  2007. const progress = progressLog();
  2008. const started1 = step(undefined, progress("run-started", started()));
  2009. expect(started1.runs[0]?.phases).toBeUndefined();
  2010. expect(started1.runs[0]?.currentPhase).toBeUndefined();
  2011. const long = "长".repeat(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength + 10);
  2012. const next = step(started1, progress("phase-entered", { name: long }));
  2013. expect(next.runs[0]?.phases).toEqual([
  2014. { name: "长".repeat(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength), rounds: 1 },
  2015. ]);
  2016. expect(workflowRunsStateSchema.parse(next)).toEqual(next);
  2017. });
  2018. it("触界:第 33 个不同阶段不建条但置 truncated,已有条目照常更新", () => {
  2019. const progress = progressLog();
  2020. const envelopes = [progress("run-started", started())];
  2021. for (let i = 0; i < WORKFLOW_RUNS_LIMITS.maxPhases; i += 1) {
  2022. envelopes.push(progress("phase-entered", { name: `p${i}`, ordinal: 1 }));
  2023. }
  2024. envelopes.push(progress("phase-entered", { name: "overflow", ordinal: 1 }));
  2025. envelopes.push(progress("phase-entered", { name: "p0", ordinal: 2 }));
  2026. const state = reduceAll(envelopes);
  2027. expect(state?.runs[0]?.phases).toHaveLength(WORKFLOW_RUNS_LIMITS.maxPhases);
  2028. expect(state?.runs[0]?.phases?.[0]).toEqual({ name: "p0", rounds: 2 });
  2029. expect(state?.runs[0]?.truncated).toBe(true);
  2030. // 当前阶段仍然跟着最后一条走——越界的阶段进不了表,但「控制流在哪」是事实。
  2031. expect(state?.runs[0]?.currentPhase).toBe("p0");
  2032. });
  2033. });
  2034. // ── 实例的出生阶段坐标(docs/dynamic-workflow/presentation.md)──────
  2035. // 静态因果图按阶段拷贝共享站点,运行时实例必须带同一个坐标,否则每张卡都认领全部实例
  2036. // (「所有子代理出现在所有阶段」)。引擎只在**出生事件**上打戳:actor-created / node-queued /
  2037. // node-settled { cached };其余节点事件不带,由本 reducer 沿用 actorSiteId 的先例向前携带。
  2038. describe("workflowRuns reducer · phaseName(实例的出生阶段)", () => {
  2039. it("actor 从 actor-created 取 phaseName", () => {
  2040. const progress = progressLog();
  2041. const state = reduceAll([
  2042. progress("run-started", started()),
  2043. progress("phase-entered", { name: "调查", ordinal: 1 }),
  2044. progress("actor-created", {
  2045. actor: { siteId: "actor#1", ordinal: 1 },
  2046. name: "reader",
  2047. phaseName: "调查",
  2048. }),
  2049. // 标记之前出生的实例不带戳(引擎的 currentPhase 当时是 undefined)。
  2050. progress("actor-created", { actor: { siteId: "actor#0", ordinal: 1 } }),
  2051. ]);
  2052. expect(state?.runs[0]?.actors).toEqual([
  2053. { siteId: "actor#1", ordinal: 1, name: "reader", phaseName: "调查", status: "waiting" },
  2054. { siteId: "actor#0", ordinal: 1, status: "waiting" },
  2055. ]);
  2056. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  2057. });
  2058. it("节点从 node-queued 取,并在 dispatched / executing / settled 上携带", () => {
  2059. const progress = progressLog();
  2060. const state = reduceAll([
  2061. progress("run-started", started()),
  2062. progress("node-queued", {
  2063. instance: { siteId: "ask#1", ordinal: 37 },
  2064. kind: "ask",
  2065. actor: { siteId: "actor#1", ordinal: 37 },
  2066. phaseName: "第三阶段",
  2067. }),
  2068. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 37 } }),
  2069. progress("node-executing", { instance: { siteId: "ask#1", ordinal: 37 } }),
  2070. progress("node-settled", { instance: { siteId: "ask#1", ordinal: 37 }, outcome: "ok" }),
  2071. ]);
  2072. expect(state?.runs[0]?.nodes).toEqual([
  2073. {
  2074. siteId: "ask#1",
  2075. ordinal: 37,
  2076. kind: "ask",
  2077. phase: "settled",
  2078. outcome: "ok",
  2079. actorSiteId: "actor#1",
  2080. actorOrdinal: 37,
  2081. phaseName: "第三阶段",
  2082. },
  2083. ]);
  2084. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  2085. });
  2086. it("cached settle 没有前序 queued,戳直接从这条事件取", () => {
  2087. const progress = progressLog();
  2088. const state = reduceAll([
  2089. progress("run-started", started()),
  2090. // resume / amend-resume 的完结命中短路:不经 node-queued,settled 就是它的出生事件。
  2091. progress("node-settled", {
  2092. instance: { siteId: "ask#1", ordinal: 2 },
  2093. actor: { siteId: "actor#1", ordinal: 2 },
  2094. outcome: "ok",
  2095. cached: true,
  2096. phaseName: "复核",
  2097. }),
  2098. ]);
  2099. expect(state?.runs[0]?.nodes).toEqual([
  2100. {
  2101. siteId: "ask#1",
  2102. ordinal: 2,
  2103. phase: "settled",
  2104. outcome: "ok",
  2105. cached: true,
  2106. actorSiteId: "actor#1",
  2107. actorOrdinal: 2,
  2108. phaseName: "复核",
  2109. },
  2110. ]);
  2111. });
  2112. it("名字截到上界(128),actor 与 node 同一条界", () => {
  2113. const progress = progressLog();
  2114. const long = "长".repeat(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength + 10);
  2115. const bounded = "长".repeat(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength);
  2116. const state = reduceAll([
  2117. progress("run-started", started()),
  2118. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, phaseName: long }),
  2119. progress("node-queued", {
  2120. instance: { siteId: "ask#1", ordinal: 1 },
  2121. kind: "ask",
  2122. phaseName: long,
  2123. }),
  2124. ]);
  2125. expect(state?.runs[0]?.actors[0]?.phaseName).toBe(bounded);
  2126. expect(state?.runs[0]?.nodes[0]?.phaseName).toBe(bounded);
  2127. // 截断后仍在界内:一个 138 字的阶段名不该让父会话之后的每一帧被渲染端拒收。
  2128. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  2129. });
  2130. it("旧载荷(无该键)归约结果逐字节不变:状态里不出现 phaseName", () => {
  2131. const progress = progressLog();
  2132. const state = reduceAll([
  2133. progress("run-started", started()),
  2134. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "reader" }),
  2135. progress("node-queued", {
  2136. instance: { siteId: "ask#1", ordinal: 1 },
  2137. kind: "ask",
  2138. actor: { siteId: "actor#1", ordinal: 1 },
  2139. }),
  2140. progress("node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" }),
  2141. ]);
  2142. // 投影按 JSON 逐字节比对快照判「有无变化」:一个 undefined 值的键也不许出现。
  2143. expect(JSON.stringify(state)).not.toContain("phaseName");
  2144. expect(state?.runs[0]?.actors).toEqual([
  2145. { siteId: "actor#1", ordinal: 1, name: "reader", status: "completed" },
  2146. ]);
  2147. expect(state?.runs[0]?.nodes).toEqual([
  2148. {
  2149. siteId: "ask#1",
  2150. ordinal: 1,
  2151. kind: "ask",
  2152. phase: "settled",
  2153. outcome: "ok",
  2154. actorSiteId: "actor#1",
  2155. actorOrdinal: 1,
  2156. },
  2157. ]);
  2158. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  2159. });
  2160. it("空串 / 非字符串戳不上线,也不擦掉已携带的戳", () => {
  2161. const progress = progressLog();
  2162. const state = reduceAll([
  2163. progress("run-started", started()),
  2164. progress("actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, phaseName: "" }),
  2165. progress("node-queued", {
  2166. instance: { siteId: "ask#1", ordinal: 1 },
  2167. kind: "ask",
  2168. phaseName: "调查",
  2169. }),
  2170. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 }, phaseName: 7 }),
  2171. ]);
  2172. expect(state?.runs[0]?.actors[0]).not.toHaveProperty("phaseName");
  2173. expect(state?.runs[0]?.nodes[0]?.phaseName).toBe("调查");
  2174. });
  2175. });
  2176. describe("run-launched:发起锚点事件只抬水位(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Token telemetry for subagents」)", () => {
  2177. it("run-started 之后的 run-launched 不改状态,只推进 lastEventSequence", () => {
  2178. const progress = progressLog();
  2179. const started = step(
  2180. undefined,
  2181. progress("run-started", { caps: { maxConcurrency: 2 }, runId: RUN_ID }),
  2182. );
  2183. const before = started.runs[0];
  2184. const after = step(
  2185. started,
  2186. progress("run-launched", { inputId: "launch-input-1", toolCallId: "tc-1" }),
  2187. );
  2188. expect(after.runs[0]).toEqual({ ...before, lastEventSequence: 1 });
  2189. expect(workflowRunsStateSchema.parse(after)).toEqual(after);
  2190. });
  2191. });
  2192. // ── 一次 ask 的进度读数(docs/dynamic-workflow/presentation.md「The run state the pane draws」)──
  2193. // 相位只说得出「在跑」,说不出在跑什么、跑到哪;这几个键是 GetWorkflowRun 那份态势报告的底料。
  2194. describe("workflowRuns reducer · node-progress(ask 的任务与进度读数)", () => {
  2195. const ASK = { siteId: "ask#1", ordinal: 1 };
  2196. const ACTOR = { siteId: "actor#1", ordinal: 1 };
  2197. /** 一个已派发的 ask:带任务摘要出生,随后 dispatched。 */
  2198. function assignedState(instructionsHead = "把 packages/shared 下的协议测试跑一遍并修掉红的") {
  2199. const progress = progressLog();
  2200. const state = reduceAll([
  2201. progress("run-started", started()),
  2202. progress("actor-created", { actor: ACTOR, name: "planner" }),
  2203. progress("node-queued", { instance: ASK, kind: "ask", actor: ACTOR, instructionsHead }),
  2204. progress("node-dispatched", { instance: ASK }),
  2205. ]);
  2206. return { progress, state };
  2207. }
  2208. it("node-queued 带 instructionsHead → 落到节点上,并被后续生命周期事件向前携带", () => {
  2209. const { progress, state } = assignedState();
  2210. expect(state?.runs[0]?.nodes[0]).toEqual({
  2211. siteId: "ask#1",
  2212. ordinal: 1,
  2213. kind: "ask",
  2214. phase: "dispatched",
  2215. actorSiteId: "actor#1",
  2216. actorOrdinal: 1,
  2217. instructionsHead: "把 packages/shared 下的协议测试跑一遍并修掉红的",
  2218. });
  2219. const settled = step(state, progress("node-settled", { instance: ASK, outcome: "ok" }));
  2220. expect(settled.runs[0]?.nodes[0]).toMatchObject({
  2221. phase: "settled",
  2222. instructionsHead: "把 packages/shared 下的协议测试跑一遍并修掉红的",
  2223. });
  2224. expect(workflowRunsStateSchema.parse(settled)).toEqual(settled);
  2225. });
  2226. it("node-progress 更新三个读数:不动相位、不计步、不动 actor 状态(一个轮次解析不是生命周期跃迁)", () => {
  2227. const { progress, state } = assignedState();
  2228. const executing = step(state, progress("node-executing", { instance: ASK }));
  2229. const before = executing.runs[0]!;
  2230. const next = step(
  2231. executing,
  2232. progress("node-progress", {
  2233. instance: ASK,
  2234. turn: 2,
  2235. toolCalls: 7,
  2236. lastTool: { name: "Bash", target: "pnpm exec vitest run packages/shared" },
  2237. }),
  2238. );
  2239. expect(next.runs[0]?.nodes[0]).toEqual({
  2240. siteId: "ask#1",
  2241. ordinal: 1,
  2242. kind: "ask",
  2243. phase: "executing",
  2244. actorSiteId: "actor#1",
  2245. actorOrdinal: 1,
  2246. instructionsHead: "把 packages/shared 下的协议测试跑一遍并修掉红的",
  2247. turn: 2,
  2248. toolCalls: 7,
  2249. lastTool: { name: "Bash", target: "pnpm exec vitest run packages/shared" },
  2250. });
  2251. // 只抬水位,别的 run 级事实一个字不动。
  2252. expect(next.runs[0]?.usage).toEqual(before.usage);
  2253. expect(next.runs[0]?.actors).toEqual(before.actors);
  2254. expect(next.runs[0]?.lastEventSequence).toBe(before.lastEventSequence + 1);
  2255. expect(workflowRunsStateSchema.parse(next)).toEqual(next);
  2256. });
  2257. it("读数被后续生命周期事件向前携带(不携带的话 node-progress 的下一条事件就把它擦了)", () => {
  2258. const { progress, state } = assignedState();
  2259. const withProgress = step(
  2260. step(state, progress("node-executing", { instance: ASK })),
  2261. progress("node-progress", {
  2262. instance: ASK,
  2263. turn: 3,
  2264. toolCalls: 12,
  2265. lastTool: { name: "Read" },
  2266. }),
  2267. );
  2268. const waiting = step(withProgress, progress("node-waiting", { instance: ASK, cause: "slot" }));
  2269. expect(waiting.runs[0]?.nodes[0]).toMatchObject({
  2270. phase: "waiting",
  2271. turn: 3,
  2272. toolCalls: 12,
  2273. lastTool: { name: "Read" },
  2274. });
  2275. const settled = step(waiting, progress("node-settled", { instance: ASK, outcome: "ok" }));
  2276. expect(settled.runs[0]?.nodes[0]).toMatchObject({ phase: "settled", turn: 3, toolCalls: 12 });
  2277. });
  2278. it("再次 node-queued(resume 重跑同一站点)清掉上一世的读数:新一次 ask 的轮次从 1 重新数", () => {
  2279. const { progress, state } = assignedState();
  2280. const withProgress = step(
  2281. state,
  2282. progress("node-progress", {
  2283. instance: ASK,
  2284. turn: 7,
  2285. toolCalls: 40,
  2286. lastTool: { name: "Bash" },
  2287. }),
  2288. );
  2289. const requeued = step(
  2290. withProgress,
  2291. progress("node-queued", {
  2292. instance: ASK,
  2293. kind: "ask",
  2294. actor: ACTOR,
  2295. instructionsHead: "改一版",
  2296. }),
  2297. );
  2298. const node = requeued.runs[0]?.nodes[0];
  2299. expect(node).toMatchObject({ phase: "queued", instructionsHead: "改一版" });
  2300. expect(node).not.toHaveProperty("turn");
  2301. expect(node).not.toHaveProperty("toolCalls");
  2302. expect(node).not.toHaveProperty("lastTool");
  2303. // 新一世的第一条进度就是第 1 轮:取 max 的话这里会显示 7,读面据此把一个刚开跑的 ask
  2304. // 当成跑了半天的。
  2305. const restarted = step(
  2306. requeued,
  2307. progress("node-progress", { instance: ASK, turn: 1, toolCalls: 0 }),
  2308. );
  2309. expect(restarted.runs[0]?.nodes[0]).toMatchObject({
  2310. instructionsHead: "改一版",
  2311. turn: 1,
  2312. toolCalls: 0,
  2313. });
  2314. expect(restarted.runs[0]?.nodes[0]).not.toHaveProperty("lastTool");
  2315. });
  2316. it("缓存命中的结算也是出生事件:读数清空,任务摘要留着(完结缓存按输入哈希命中,指令逐字相同)", () => {
  2317. // 这条钉的是「一步没走的节点不许显示上一世的读数」。走的是 resume 的完结命中短路
  2318. // (engine.ts:228/232):那条 node-settled 没有前序 queued,它自己就是出生事件。
  2319. const { progress, state } = assignedState();
  2320. const lived = step(
  2321. state,
  2322. progress("node-progress", {
  2323. instance: ASK,
  2324. turn: 9,
  2325. toolCalls: 40,
  2326. lastTool: { name: "Bash", target: "pnpm test" },
  2327. }),
  2328. );
  2329. const cached = step(
  2330. step(lived, progress("run-started", started())),
  2331. progress("node-settled", { instance: ASK, outcome: "ok", cached: true }),
  2332. );
  2333. const node = cached.runs[0]?.nodes[0];
  2334. expect(node).toMatchObject({
  2335. phase: "settled",
  2336. outcome: "ok",
  2337. cached: true,
  2338. instructionsHead: "把 packages/shared 下的协议测试跑一遍并修掉红的",
  2339. });
  2340. expect(node).not.toHaveProperty("turn");
  2341. expect(node).not.toHaveProperty("toolCalls");
  2342. expect(node).not.toHaveProperty("lastTool");
  2343. expect(workflowRunsStateSchema.parse(cached)).toEqual(cached);
  2344. });
  2345. it("queued → settled(cached) 之间没有任何进度事件时三键始终缺席(不是 0)", () => {
  2346. const progress = progressLog();
  2347. const state = reduceAll([
  2348. progress("run-started", started()),
  2349. progress("node-queued", {
  2350. instance: ASK,
  2351. kind: "ask",
  2352. actor: ACTOR,
  2353. instructionsHead: "查一遍",
  2354. }),
  2355. progress("node-settled", { instance: ASK, outcome: "ok", cached: true }),
  2356. ]);
  2357. const node = state?.runs[0]?.nodes[0];
  2358. expect(node).toEqual({
  2359. siteId: "ask#1",
  2360. ordinal: 1,
  2361. kind: "ask",
  2362. phase: "settled",
  2363. outcome: "ok",
  2364. cached: true,
  2365. actorSiteId: "actor#1",
  2366. actorOrdinal: 1,
  2367. instructionsHead: "查一遍",
  2368. });
  2369. });
  2370. it("没有 cached 的普通 node-settled 照常携带读数(结算不是出生,跑过的账要留下)", () => {
  2371. const { progress, state } = assignedState();
  2372. const lived = step(
  2373. state,
  2374. progress("node-progress", {
  2375. instance: ASK,
  2376. turn: 5,
  2377. toolCalls: 18,
  2378. lastTool: { name: "Edit" },
  2379. }),
  2380. );
  2381. const settled = step(lived, progress("node-settled", { instance: ASK, outcome: "ok" }));
  2382. expect(settled.runs[0]?.nodes[0]).toMatchObject({
  2383. phase: "settled",
  2384. turn: 5,
  2385. toolCalls: 18,
  2386. lastTool: { name: "Edit" },
  2387. });
  2388. });
  2389. it("指向表里没有的实例时不建条目,只抬水位(与其他节点事件对未知实例同族)", () => {
  2390. const { progress, state } = assignedState();
  2391. const before = state!.runs[0]!;
  2392. const next = step(
  2393. state,
  2394. progress("node-progress", {
  2395. instance: { siteId: "ask#9", ordinal: 9 },
  2396. turn: 1,
  2397. toolCalls: 0,
  2398. }),
  2399. );
  2400. expect(next.runs[0]?.nodes).toEqual(before.nodes);
  2401. expect(next.runs[0]?.lastEventSequence).toBe(before.lastEventSequence + 1);
  2402. });
  2403. it("instance 读不动、或三个读数一个都读不出来时,节点逐字节不变", () => {
  2404. const { progress, state } = assignedState();
  2405. const before = state!.runs[0]!.nodes;
  2406. for (const payload of [
  2407. { instance: { ordinal: 1 } },
  2408. { instance: ASK },
  2409. { instance: ASK, turn: 0 },
  2410. { instance: ASK, turn: 1.5 },
  2411. { instance: ASK, turn: Number.NaN },
  2412. { instance: ASK, toolCalls: -1 },
  2413. { instance: ASK, lastTool: { name: "" } },
  2414. { instance: ASK, lastTool: "Bash" },
  2415. ]) {
  2416. const next = step(state, progress("node-progress", payload));
  2417. expect(next.runs[0]?.nodes).toEqual(before);
  2418. }
  2419. });
  2420. it("读不出的单个字段保持已知值,读得出的照常覆盖(后来者覆盖,不是取 max)", () => {
  2421. const { progress, state } = assignedState();
  2422. const first = step(
  2423. state,
  2424. progress("node-progress", {
  2425. instance: ASK,
  2426. turn: 4,
  2427. toolCalls: 11,
  2428. lastTool: { name: "Edit", target: "packages/shared/src/index.ts" },
  2429. }),
  2430. );
  2431. // 只带 toolCalls 的一条:turn 与 lastTool 保持,不被擦掉。
  2432. const second = step(first, progress("node-progress", { instance: ASK, toolCalls: 12 }));
  2433. expect(second.runs[0]?.nodes[0]).toMatchObject({
  2434. turn: 4,
  2435. toolCalls: 12,
  2436. lastTool: { name: "Edit", target: "packages/shared/src/index.ts" },
  2437. });
  2438. // 取 max 会把这里冻在 4;后来者覆盖才让重跑的 ask 能退回 1。
  2439. const third = step(second, progress("node-progress", { instance: ASK, turn: 1, toolCalls: 0 }));
  2440. expect(third.runs[0]?.nodes[0]).toMatchObject({ turn: 1, toolCalls: 0 });
  2441. });
  2442. it("三个字符串按线上界裁剪(生产侧已切,这里是第二道闸),产出仍过 strict schema", () => {
  2443. const limits = WORKFLOW_RUNS_LIMITS;
  2444. const progress = progressLog();
  2445. const state = reduceAll([
  2446. progress("run-started", started()),
  2447. progress("node-queued", {
  2448. instance: ASK,
  2449. kind: "ask",
  2450. instructionsHead: "指".repeat(limits.maxInstructionsHeadLength + 20),
  2451. }),
  2452. progress("node-progress", {
  2453. instance: ASK,
  2454. turn: 1,
  2455. toolCalls: 1,
  2456. lastTool: {
  2457. name: "T".repeat(limits.maxLastToolNameLength + 10),
  2458. target: "p".repeat(limits.maxLastToolTargetLength + 10),
  2459. },
  2460. }),
  2461. ]);
  2462. const node = state?.runs[0]?.nodes[0];
  2463. expect(node?.instructionsHead).toHaveLength(limits.maxInstructionsHeadLength);
  2464. expect(node?.lastTool?.name).toHaveLength(limits.maxLastToolNameLength);
  2465. expect(node?.lastTool?.target).toHaveLength(limits.maxLastToolTargetLength);
  2466. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  2467. });
  2468. it("幂等:同一条 node-progress 立刻重放只抬水位,内容不变", () => {
  2469. const { progress, state } = assignedState();
  2470. const payload = { instance: ASK, turn: 2, toolCalls: 3, lastTool: { name: "Read" } };
  2471. const first = step(state, progress("node-progress", payload));
  2472. const second = step(first, progress("node-progress", payload));
  2473. expect(second.runs[0]?.nodes).toEqual(first.runs[0]?.nodes);
  2474. // 同一条事件(同 sequence)重放才是真的无变化:水位不动,reducer 返回 null。
  2475. const replay = reduceWorkflowRunsState(first, {
  2476. runId: RUN_ID,
  2477. toolCallId: "tc-1",
  2478. sequence: first.runs[0]!.lastEventSequence,
  2479. eventType: "node-progress",
  2480. payload,
  2481. });
  2482. expect(replay).toBeNull();
  2483. });
  2484. it("更新的 CLI 发来的未知事件仍然落到 default:只抬水位,不建节点", () => {
  2485. const { progress, state } = assignedState();
  2486. const before = state!.runs[0]!;
  2487. const next = step(
  2488. state,
  2489. progress("node-heartbeat", { instance: { siteId: "ask#2", ordinal: 1 } }),
  2490. );
  2491. expect(next.runs[0]).toEqual({ ...before, lastEventSequence: before.lastEventSequence + 1 });
  2492. });
  2493. });