product-projection-cold-hydration.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. SessionEventType,
  4. type EventId,
  5. type SessionEvent,
  6. type SessionEventType as SessionEventTypeUnion,
  7. type SessionId,
  8. type TraceId,
  9. type TurnId,
  10. } from "@zcode/contracts";
  11. import type {
  12. ConversationDelta,
  13. ConversationRow,
  14. SubagentRow,
  15. } from "@zcode/shared/zcode-protocol-v4";
  16. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  17. interface ProductProjectionInternals {
  18. subagentRowIdByAgentId: Map<string, number>;
  19. materializeSubagentProjection(reduced: readonly ConversationDelta[]): ConversationDelta[];
  20. pruneRemovedSubagentIndexes(): void;
  21. prospectiveSubagentRow(
  22. row: ConversationRow,
  23. reduced: readonly ConversationDelta[],
  24. startIndex: number,
  25. ): SubagentRow | null;
  26. }
  27. function sessionEvent(
  28. sequenceNumber: number,
  29. type: SessionEventTypeUnion,
  30. payload: unknown,
  31. turnId?: string,
  32. ): SessionEvent {
  33. return {
  34. id: `cold-hydration-event-${sequenceNumber}` as EventId,
  35. sessionId: "cold-hydration-session" as SessionId,
  36. ...(turnId ? { turnId: turnId as TurnId } : {}),
  37. type,
  38. timestamp: new Date(1_700_000_000_000 + sequenceNumber),
  39. traceId: "cold-hydration-trace" as TraceId,
  40. sequenceNumber,
  41. payload,
  42. };
  43. }
  44. function spyOnSubagentMaterialization(projection: ProductProjection) {
  45. return vi.spyOn(
  46. projection as unknown as ProductProjectionInternals,
  47. "materializeSubagentProjection",
  48. );
  49. }
  50. describe("ProductProjection cold hydration subagent materialization", () => {
  51. it("cold batch 对 checkpoint 只推进 seq,live 路径仍保持原有 materialization", () => {
  52. const checkpoint = sessionEvent(1, SessionEventType.CheckpointCreated, {
  53. checkpointId: "checkpoint-1",
  54. messageId: "message-1",
  55. scope: "workspace",
  56. snapshotRef: "artifact://checkpoint-1",
  57. });
  58. const coldProjection = new ProductProjection("cold-hydration-session", "epoch-cold");
  59. const coldMaterialize = spyOnSubagentMaterialization(coldProjection);
  60. coldProjection.beginHydrationReplay();
  61. expect(coldProjection.applyHydrationEvent(checkpoint)).toEqual([]);
  62. expect(coldMaterialize).not.toHaveBeenCalled();
  63. expect(coldProjection.getSnapshot().seq).toBe(1);
  64. coldProjection.completeHydrationReplay();
  65. const liveProjection = new ProductProjection("cold-hydration-session", "epoch-live");
  66. const liveMaterialize = spyOnSubagentMaterialization(liveProjection);
  67. expect(liveProjection.applyEvent(checkpoint)).toEqual([]);
  68. expect(liveMaterialize).toHaveBeenCalledOnce();
  69. expect(liveProjection.getSnapshot().seq).toBe(1);
  70. });
  71. it("cold batch 只在 subagent 派生输入变化时重新 materialize", () => {
  72. const turnId = "turn-subagent";
  73. const projection = new ProductProjection("cold-hydration-session", "epoch-cold");
  74. const materialize = spyOnSubagentMaterialization(projection);
  75. projection.beginHydrationReplay();
  76. projection.applyHydrationEvent(
  77. sessionEvent(
  78. 1,
  79. SessionEventType.SubagentSpawned,
  80. {
  81. agentId: "agent-1",
  82. agentType: "Explore",
  83. childSessionId: "child-session-1",
  84. description: "检查代码",
  85. status: "running",
  86. },
  87. turnId,
  88. ),
  89. );
  90. expect(materialize).toHaveBeenCalledOnce();
  91. expect(projection.getSnapshot().subagents).toMatchObject({
  92. childSessionIds: ["child-session-1"],
  93. running: [{ childSessionId: "child-session-1", status: "running" }],
  94. });
  95. materialize.mockClear();
  96. projection.applyHydrationEvent(
  97. sessionEvent(
  98. 2,
  99. SessionEventType.BackgroundTaskStarted,
  100. {
  101. taskId: "agent-1",
  102. taskKind: "subagent",
  103. childSessionId: "child-session-1",
  104. description: "检查代码",
  105. status: "running",
  106. blocked: true,
  107. },
  108. turnId,
  109. ),
  110. );
  111. expect(materialize).toHaveBeenCalledOnce();
  112. expect(projection.getSnapshot().subagents?.running).toEqual([
  113. expect.objectContaining({ childSessionId: "child-session-1", status: "blocked" }),
  114. ]);
  115. materialize.mockClear();
  116. projection.applyHydrationEvent(
  117. sessionEvent(3, SessionEventType.CheckpointCreated, {
  118. checkpointId: "checkpoint-2",
  119. messageId: "message-1",
  120. scope: "workspace",
  121. snapshotRef: "artifact://checkpoint-2",
  122. }),
  123. );
  124. expect(materialize).not.toHaveBeenCalled();
  125. expect(projection.getSnapshot().subagents?.running).toEqual([
  126. expect.objectContaining({ childSessionId: "child-session-1", status: "blocked" }),
  127. ]);
  128. expect(projection.getSnapshot().seq).toBe(3);
  129. projection.completeHydrationReplay();
  130. });
  131. it("cold batch 与 strict replay 在 subagent 更新、等待和 rewind 后得到相同快照", () => {
  132. const firstTurnId = "turn-subagent-first";
  133. const secondTurnId = "turn-subagent-rewind";
  134. const thirdTurnId = "turn-subagent-rewind-again";
  135. const events = [
  136. sessionEvent(1, SessionEventType.SessionCreated, {
  137. mode: "default",
  138. contextWindow: 200_000,
  139. }),
  140. sessionEvent(
  141. 2,
  142. SessionEventType.TurnStarted,
  143. { turnNumber: 1, input: "检查两个子代理", messageId: "user-first" },
  144. firstTurnId,
  145. ),
  146. sessionEvent(
  147. 3,
  148. SessionEventType.SubagentSpawned,
  149. {
  150. agentId: "agent-ended",
  151. agentType: "Explore",
  152. childSessionId: "child-ended",
  153. description: "先检查历史",
  154. status: "running",
  155. },
  156. firstTurnId,
  157. ),
  158. sessionEvent(
  159. 4,
  160. SessionEventType.SubagentMessage,
  161. {
  162. agentId: "agent-ended",
  163. childSessionId: "child-ended",
  164. summaryText: "已完成扫描",
  165. },
  166. firstTurnId,
  167. ),
  168. sessionEvent(
  169. 5,
  170. SessionEventType.SubagentStopped,
  171. {
  172. agentId: "agent-ended",
  173. agentType: "Explore",
  174. childSessionId: "child-ended",
  175. status: "completed",
  176. summaryText: "历史检查完成",
  177. },
  178. firstTurnId,
  179. ),
  180. sessionEvent(
  181. 6,
  182. SessionEventType.SubagentSpawned,
  183. {
  184. agentId: "agent-waiting",
  185. agentType: "general-purpose",
  186. childSessionId: "child-waiting",
  187. description: "等待用户授权",
  188. status: "running",
  189. },
  190. firstTurnId,
  191. ),
  192. sessionEvent(
  193. 7,
  194. SessionEventType.PermissionRequested,
  195. {
  196. requestId: "permission-waiting",
  197. toolCallId: "tool-waiting",
  198. toolName: "Bash",
  199. riskLevel: "medium",
  200. reason: "需要运行命令",
  201. input: { command: "pwd" },
  202. origin: {
  203. kind: "subagent",
  204. agentId: "agent-waiting",
  205. agentType: "general-purpose",
  206. childSessionId: "child-waiting",
  207. description: "等待用户授权",
  208. parentSessionId: "cold-hydration-session",
  209. parentTurnId: firstTurnId,
  210. },
  211. },
  212. firstTurnId,
  213. ),
  214. sessionEvent(
  215. 8,
  216. SessionEventType.TurnComplete,
  217. {
  218. response: "done",
  219. tokenCount: 1,
  220. toolCallCount: 0,
  221. duration: 1,
  222. resultType: "success",
  223. },
  224. firstTurnId,
  225. ),
  226. sessionEvent(
  227. 9,
  228. SessionEventType.TurnStarted,
  229. { turnNumber: 2, input: "这一轮会被 rewind", messageId: "user-rewind" },
  230. secondTurnId,
  231. ),
  232. sessionEvent(
  233. 10,
  234. SessionEventType.ModelStreaming,
  235. {
  236. kind: "text_start",
  237. delta: "",
  238. done: false,
  239. assistantMessageId: "assistant-rewind",
  240. },
  241. secondTurnId,
  242. ),
  243. sessionEvent(
  244. 11,
  245. SessionEventType.SubagentSpawned,
  246. {
  247. agentId: "agent-rewind",
  248. agentType: "Explore",
  249. childSessionId: "child-rewind",
  250. description: "将被回滚",
  251. status: "running",
  252. },
  253. secondTurnId,
  254. ),
  255. sessionEvent(12, SessionEventType.RewindTriggered, {
  256. targetMessageId: "assistant-rewind",
  257. scope: "conversation",
  258. createdMessageId: "rewind-notice",
  259. }),
  260. sessionEvent(
  261. 13,
  262. SessionEventType.TurnStarted,
  263. { turnNumber: 3, input: "再次 rewind", messageId: "user-rewind-again" },
  264. thirdTurnId,
  265. ),
  266. sessionEvent(
  267. 14,
  268. SessionEventType.ModelStreaming,
  269. {
  270. kind: "text_start",
  271. delta: "",
  272. done: false,
  273. assistantMessageId: "assistant-rewind-again",
  274. },
  275. thirdTurnId,
  276. ),
  277. sessionEvent(
  278. 15,
  279. SessionEventType.SubagentSpawned,
  280. {
  281. agentId: "agent-rewind-again",
  282. agentType: "Explore",
  283. childSessionId: "child-rewind-again",
  284. description: "也会被回滚",
  285. status: "running",
  286. },
  287. thirdTurnId,
  288. ),
  289. sessionEvent(16, SessionEventType.RewindTriggered, {
  290. targetMessageId: "assistant-rewind-again",
  291. scope: "conversation",
  292. createdMessageId: "rewind-notice-again",
  293. }),
  294. ];
  295. const strictProjection = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  296. const coldProjection = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  297. const coldMaterialize = spyOnSubagentMaterialization(coldProjection);
  298. const strictPrune = vi.spyOn(
  299. strictProjection as unknown as ProductProjectionInternals,
  300. "pruneRemovedSubagentIndexes",
  301. );
  302. const coldPrune = vi.spyOn(
  303. coldProjection as unknown as ProductProjectionInternals,
  304. "pruneRemovedSubagentIndexes",
  305. );
  306. const materializingEventTypes = new Set<SessionEventTypeUnion>([
  307. SessionEventType.SubagentSpawned,
  308. SessionEventType.SubagentMessage,
  309. SessionEventType.SubagentStopped,
  310. SessionEventType.PermissionRequested,
  311. SessionEventType.RewindTriggered,
  312. ]);
  313. coldProjection.beginHydrationReplay();
  314. for (const event of events) {
  315. coldMaterialize.mockClear();
  316. strictProjection.applyEvent(event);
  317. coldProjection.applyHydrationEvent(event);
  318. if (materializingEventTypes.has(event.type)) {
  319. expect(coldMaterialize, event.type).toHaveBeenCalledOnce();
  320. }
  321. expect(coldProjection.getSnapshot().subagents, event.type).toEqual(
  322. strictProjection.getSnapshot().subagents,
  323. );
  324. }
  325. coldProjection.completeHydrationReplay();
  326. expect(coldProjection.getSnapshot()).toEqual(strictProjection.getSnapshot());
  327. expect(strictPrune).toHaveBeenCalledTimes(2);
  328. expect(coldPrune).toHaveBeenCalledTimes(2);
  329. expect(
  330. [
  331. ...(coldProjection as unknown as ProductProjectionInternals).subagentRowIdByAgentId.keys(),
  332. ].sort(),
  333. ).toEqual(["agent-ended", "agent-waiting"]);
  334. expect(coldProjection.getSnapshot().subagents).toMatchObject({
  335. childSessionIds: ["child-ended", "child-waiting"],
  336. running: [{ childSessionId: "child-waiting", status: "waiting" }],
  337. endedTotal: 1,
  338. });
  339. expect(
  340. coldProjection
  341. .getSnapshot()
  342. .rows.window.some(
  343. (row) => row.kind === "subagent" && row.childSessionId === "child-rewind",
  344. ),
  345. ).toBe(false);
  346. });
  347. it("重复 child 的最新行与 blocked 状态在 cold batch 和 strict replay 中保持等价", () => {
  348. const turnId = "turn-subagent-duplicates";
  349. const events = [
  350. sessionEvent(
  351. 1,
  352. SessionEventType.SubagentSpawned,
  353. {
  354. agentId: "agent-old",
  355. agentType: "Explore",
  356. childSessionId: "child-shared",
  357. description: "旧行",
  358. status: "running",
  359. },
  360. turnId,
  361. ),
  362. sessionEvent(
  363. 2,
  364. SessionEventType.SubagentSpawned,
  365. {
  366. agentId: "agent-new",
  367. agentType: "Explore",
  368. childSessionId: "child-shared",
  369. description: "新行",
  370. status: "running",
  371. },
  372. turnId,
  373. ),
  374. sessionEvent(
  375. 3,
  376. SessionEventType.BackgroundTaskStarted,
  377. {
  378. taskId: "agent-new",
  379. taskKind: "subagent",
  380. childSessionId: "child-shared",
  381. description: "新行",
  382. status: "running",
  383. blocked: true,
  384. },
  385. turnId,
  386. ),
  387. ];
  388. const strictProjection = new ProductProjection("cold-hydration-session", "epoch-duplicate");
  389. const coldProjection = new ProductProjection("cold-hydration-session", "epoch-duplicate");
  390. coldProjection.beginHydrationReplay();
  391. for (const event of events) {
  392. strictProjection.applyEvent(event);
  393. coldProjection.applyHydrationEvent(event);
  394. expect(coldProjection.getSnapshot().subagents, event.type).toEqual(
  395. strictProjection.getSnapshot().subagents,
  396. );
  397. }
  398. coldProjection.completeHydrationReplay();
  399. expect(coldProjection.getSnapshot().subagents).toMatchObject({
  400. childSessionIds: ["child-shared"],
  401. running: [
  402. expect.objectContaining({
  403. childSessionId: "child-shared",
  404. agentId: "agent-new",
  405. status: "blocked",
  406. }),
  407. ],
  408. endedTotal: 0,
  409. });
  410. expect(coldProjection.getSnapshot()).toEqual(strictProjection.getSnapshot());
  411. });
  412. it("subagent materialization 不遍历普通 conversation rows", () => {
  413. const projection = new ProductProjection("cold-hydration-session", "epoch-indexed");
  414. const prospectiveRow = vi.spyOn(
  415. projection as unknown as ProductProjectionInternals,
  416. "prospectiveSubagentRow",
  417. );
  418. let sequenceNumber = 0;
  419. projection.beginHydrationReplay();
  420. for (let turn = 1; turn <= 20; turn += 1) {
  421. projection.applyHydrationEvent(
  422. sessionEvent(
  423. (sequenceNumber += 1),
  424. SessionEventType.TurnStarted,
  425. { turnNumber: turn, input: `问题 ${turn}`, messageId: `user-indexed-${turn}` },
  426. `turn-indexed-${turn}`,
  427. ),
  428. );
  429. }
  430. expect(projection.getSnapshot().rows.window).toHaveLength(40);
  431. prospectiveRow.mockClear();
  432. projection.applyHydrationEvent(
  433. sessionEvent(
  434. (sequenceNumber += 1),
  435. SessionEventType.SubagentSpawned,
  436. {
  437. agentId: "agent-indexed",
  438. agentType: "Explore",
  439. childSessionId: "child-indexed",
  440. description: "只检查 subagent 行",
  441. status: "running",
  442. },
  443. "turn-indexed-20",
  444. ),
  445. );
  446. expect(prospectiveRow).toHaveBeenCalledOnce();
  447. projection.completeHydrationReplay();
  448. });
  449. });
  450. describe("ProductProjection cold hydration ask preview", () => {
  451. // 冷恢复的弹窗必须仍然带图:display 要经 applyHydrationEvent 存活,且与 live 路径一致。
  452. const display = {
  453. kind: "create_workflow",
  454. ok: true,
  455. errorCount: 0,
  456. diagnostics: [],
  457. causalityGraph: {
  458. steps: [
  459. {
  460. id: "ask#1",
  461. kind: "ask",
  462. label: "a",
  463. line: 2,
  464. column: 11,
  465. lane: "actor#1",
  466. },
  467. ],
  468. lanes: [{ id: "actor#1", name: "a" }],
  469. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  470. participants: [{ id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] }],
  471. handoffs: [],
  472. sink: ["ask#1"],
  473. },
  474. };
  475. function permissionEvents(): SessionEvent[] {
  476. const turnId = "turn-workflow";
  477. return [
  478. sessionEvent(1, SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 }),
  479. sessionEvent(2, SessionEventType.TurnStarted, { turnNumber: 1, input: "run it" }, turnId),
  480. sessionEvent(
  481. 3,
  482. SessionEventType.ToolCallScheduled,
  483. {
  484. toolCallId: "tc-1",
  485. toolName: "CreateWorkflow",
  486. input: { script: "return 1;" },
  487. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  488. },
  489. turnId,
  490. ),
  491. sessionEvent(
  492. 4,
  493. SessionEventType.PermissionRequested,
  494. {
  495. requestId: "req-1",
  496. toolCallId: "tc-1",
  497. toolName: "CreateWorkflow",
  498. riskLevel: "low",
  499. reason: "createWorkflow.runConfirmation",
  500. input: { script: "return 1;" },
  501. display,
  502. optionsPolicy: "session-always-allow",
  503. },
  504. turnId,
  505. ),
  506. ];
  507. }
  508. it("display 与选项列表经冷恢复存活,且与 live 投影一致", () => {
  509. const events = permissionEvents();
  510. const live = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  511. const cold = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  512. for (const event of events) live.applyEvent(event);
  513. cold.beginHydrationReplay();
  514. for (const event of events) cold.applyHydrationEvent(event);
  515. cold.completeHydrationReplay();
  516. const payload = cold.getSnapshot().pendingInteractions[0]?.payload;
  517. expect(payload).toMatchObject({ kind: "permission", display });
  518. // 第 4 轮:CreateWorkflow 的 v4 选项含 Refine;第 7 轮含会话免确认;冷恢复走同一
  519. // 合成函数,天然一致。
  520. expect(payload?.kind === "permission" && payload.options).toHaveLength(4);
  521. expect(
  522. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  523. ).toEqual(["allowOnce", "allowSession", "deny", "workflowRefine"]);
  524. expect(cold.getSnapshot().pendingInteractions).toEqual(live.getSnapshot().pendingInteractions);
  525. });
  526. });
  527. // ── 可复用工作流的两道窗在冷恢复上的等价(docs/dynamic-workflow/launch.md)──
  528. // 刷新一次页面就把 saved run 的脚本弄丢,等于让用户在一个空窗上批准一次执行;
  529. // 冷恢复与 live 走同一个合成函数,所以这里钉的是"没人给冷路径开第二条分支"。
  530. describe("ProductProjection cold hydration 可复用工作流的确认窗", () => {
  531. const script = 'const r = agent("检查员");\nreturn await r.ask<string>("检查一遍");';
  532. /** executor 的 resolveInput 产出的归一化入参:脚本已解析,来龙去脉在 saved 上。 */
  533. const savedRunInput = {
  534. name: "release-check",
  535. script,
  536. saved: {
  537. name: "release-check",
  538. args: { target: "packages/core", depth: 3, skipTests: false },
  539. path: "/repo/.zcode/workflows/release-check.dwf.ts",
  540. scope: "project",
  541. },
  542. };
  543. const saveInput = {
  544. name: "release-check",
  545. description: "对本仓库做一次发布前检查",
  546. script,
  547. path: "/repo/.zcode/workflows/release-check.dwf.ts",
  548. overwrite: true,
  549. scope: "project",
  550. };
  551. function gateEvents(toolName: string, input: unknown, reason: string): SessionEvent[] {
  552. const turnId = "turn-reusable-workflow";
  553. return [
  554. sessionEvent(1, SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 }),
  555. sessionEvent(2, SessionEventType.TurnStarted, { turnNumber: 1, input: "run it" }, turnId),
  556. sessionEvent(
  557. 3,
  558. SessionEventType.ToolCallScheduled,
  559. {
  560. toolCallId: "tc-1",
  561. toolName,
  562. input,
  563. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  564. },
  565. turnId,
  566. ),
  567. sessionEvent(
  568. 4,
  569. SessionEventType.PermissionRequested,
  570. {
  571. requestId: "req-1",
  572. toolCallId: "tc-1",
  573. toolName,
  574. riskLevel: "low",
  575. reason,
  576. input,
  577. optionsPolicy: "no-always-allow",
  578. },
  579. turnId,
  580. ),
  581. ];
  582. }
  583. function hydrate(events: readonly SessionEvent[]): {
  584. cold: ProductProjection;
  585. live: ProductProjection;
  586. } {
  587. const cold = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  588. const live = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  589. cold.beginHydrationReplay();
  590. for (const event of events) cold.applyHydrationEvent(event);
  591. cold.completeHydrationReplay();
  592. for (const event of events) live.applyEvent(event);
  593. return { cold, live };
  594. }
  595. it("saved run 的归一化入参经冷恢复存活,Refine 仍在,且与 live 一致", () => {
  596. const { cold, live } = hydrate(
  597. gateEvents("CreateWorkflow", savedRunInput, "createWorkflow.runConfirmation"),
  598. );
  599. const payload = cold.getSnapshot().pendingInteractions[0]?.payload;
  600. expect(payload?.kind).toBe("permission");
  601. // 脚本与实参袋都还在:冷恢复后的窗与热态是同一个窗。
  602. expect(payload?.kind === "permission" && payload.detail).toEqual(savedRunInput);
  603. expect(
  604. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  605. ).toEqual(["allowOnce", "deny", "workflowRefine"]);
  606. expect(cold.getSnapshot().pendingInteractions).toEqual(live.getSnapshot().pendingInteractions);
  607. });
  608. it("SaveWorkflow 的落点与覆盖判定经冷恢复存活,且照旧不带 display", () => {
  609. const { cold, live } = hydrate(
  610. gateEvents("SaveWorkflow", saveInput, "saveWorkflow.confirmation"),
  611. );
  612. const payload = cold.getSnapshot().pendingInteractions[0]?.payload;
  613. expect(payload?.kind === "permission" && payload.detail).toEqual(saveInput);
  614. expect(payload && "display" in payload).toBe(false);
  615. expect(
  616. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  617. ).toEqual(["allowOnce", "deny"]);
  618. expect(cold.getSnapshot().pendingInteractions).toEqual(live.getSnapshot().pendingInteractions);
  619. });
  620. });
  621. // ── dwf 运行态的冷恢复(docs/dynamic-workflow/presentation.md 的 Tests:漏一处即静默丢运行态)──
  622. // 两个必须同时成立的条件,缺任一 run 就会在刷新/重连后消失,而 run 本身仍在飞:
  623. // 1. cold 批量路径与 live 路径经**同一个** reducer(applyEventInternal),产出同一份状态;
  624. // 2. cold merge 把这类事件识别为 memory-only 权威(它不在 durable transcript 里)。
  625. describe("ProductProjection cold hydration workflowRuns", () => {
  626. function runProgress(sequenceNumber: number, eventType: string, payload: unknown): SessionEvent {
  627. return sessionEvent(sequenceNumber, SessionEventType.DynamicWorkflowRunProgress, {
  628. runId: "dwfrun-cold",
  629. toolCallId: "tc-cold",
  630. sequence: sequenceNumber - 1,
  631. eventType,
  632. payload,
  633. });
  634. }
  635. const events = [
  636. runProgress(1, "run-started", {
  637. runId: "dwfrun-cold",
  638. caps: { maxConcurrency: 2 },
  639. }),
  640. runProgress(2, "actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" }),
  641. runProgress(3, "node-queued", {
  642. instance: { siteId: "ask#1", ordinal: 1 },
  643. kind: "ask",
  644. actor: { siteId: "actor#1", ordinal: 1 },
  645. }),
  646. runProgress(4, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  647. ];
  648. it("cold 批量与 live 逐条产出同一份 workflowRuns(同一个 reducer 路径)", () => {
  649. const cold = new ProductProjection("cold-hydration-session", "epoch-cold");
  650. cold.beginHydrationReplay();
  651. for (const event of events) cold.applyHydrationEvent(event);
  652. cold.completeHydrationReplay();
  653. const live = new ProductProjection("cold-hydration-session", "epoch-live");
  654. for (const event of events) live.applyEvent(event);
  655. expect(cold.getSnapshot().workflowRuns).toEqual(live.getSnapshot().workflowRuns);
  656. expect(cold.getSnapshot().workflowRuns).toMatchObject({
  657. runs: [
  658. {
  659. runId: "dwfrun-cold",
  660. status: "running",
  661. // dispatched = 会话就绪、请求尚未准入 → actor 仍是 waiting(决策 39)。
  662. actors: [{ siteId: "actor#1", ordinal: 1, name: "planner", status: "waiting" }],
  663. nodes: [{ siteId: "ask#1", ordinal: 1, kind: "ask", phase: "dispatched" }],
  664. lastEventSequence: 3,
  665. },
  666. ],
  667. });
  668. });
  669. it("在飞 run 的运行态在冷恢复后存活(cold merge 视其为 memory-only 权威)", async () => {
  670. const merge = await import("../src/zcode-protocol-v4/cold-event-merge.js");
  671. const merged = merge.mergeColdConversationEvents({
  672. memoryEvents: events,
  673. messages: [],
  674. sessionId: "cold-hydration-session",
  675. });
  676. // 事件被保留,且**不进 unclassified 诊断**——落到那个分支意味着分类表漏了它,
  677. // 虽然事件仍被保留,但每次冷恢复都会刷一条"未知老事实"诊断。
  678. expect(
  679. merged.events.filter((event) => event.type === SessionEventType.DynamicWorkflowRunProgress),
  680. ).toHaveLength(events.length);
  681. expect(
  682. merged.diagnostics.find(
  683. (diagnostic) => diagnostic.code === "cold_merge.unclassified_event_preserved",
  684. ),
  685. ).toBeUndefined();
  686. const rebuilt = new ProductProjection("cold-hydration-session", "epoch-rebuilt");
  687. for (const event of merged.events) rebuilt.applyEvent(event);
  688. expect(rebuilt.getSnapshot().workflowRuns?.runs[0]).toMatchObject({
  689. runId: "dwfrun-cold",
  690. status: "running",
  691. nodes: [{ siteId: "ask#1", ordinal: 1, phase: "dispatched" }],
  692. });
  693. });
  694. });