zcodeProtocolV4WorkflowRunsReducer.test.ts 114 KB

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