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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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: [
  471. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  472. ],
  473. handoffs: [],
  474. sink: ["ask#1"],
  475. },
  476. };
  477. function permissionEvents(): SessionEvent[] {
  478. const turnId = "turn-workflow";
  479. return [
  480. sessionEvent(1, SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 }),
  481. sessionEvent(2, SessionEventType.TurnStarted, { turnNumber: 1, input: "run it" }, turnId),
  482. sessionEvent(
  483. 3,
  484. SessionEventType.ToolCallScheduled,
  485. {
  486. toolCallId: "tc-1",
  487. toolName: "CreateWorkflow",
  488. input: { script: "return 1;" },
  489. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  490. },
  491. turnId,
  492. ),
  493. sessionEvent(
  494. 4,
  495. SessionEventType.PermissionRequested,
  496. {
  497. requestId: "req-1",
  498. toolCallId: "tc-1",
  499. toolName: "CreateWorkflow",
  500. riskLevel: "low",
  501. reason: "createWorkflow.runConfirmation",
  502. input: { script: "return 1;" },
  503. display,
  504. optionsPolicy: "session-always-allow",
  505. },
  506. turnId,
  507. ),
  508. ];
  509. }
  510. it("display 与选项列表经冷恢复存活,且与 live 投影一致", () => {
  511. const events = permissionEvents();
  512. const live = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  513. const cold = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  514. for (const event of events) live.applyEvent(event);
  515. cold.beginHydrationReplay();
  516. for (const event of events) cold.applyHydrationEvent(event);
  517. cold.completeHydrationReplay();
  518. const payload = cold.getSnapshot().pendingInteractions[0]?.payload;
  519. expect(payload).toMatchObject({ kind: "permission", display });
  520. // 第 4 轮:CreateWorkflow 的 v4 选项含 Refine;第 7 轮含会话免确认;冷恢复走同一
  521. // 合成函数,天然一致。
  522. expect(
  523. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  524. ).toEqual(["allowOnce", "allowSession", "deny", "workflowRefine"]);
  525. expect(cold.getSnapshot().pendingInteractions).toEqual(live.getSnapshot().pendingInteractions);
  526. });
  527. });
  528. // ── 可复用工作流的两道窗在冷恢复上的等价(docs/dynamic-workflow/launch.md)──
  529. // 刷新一次页面就把 saved run 的脚本弄丢,等于让用户在一个空窗上批准一次执行;
  530. // 冷恢复与 live 走同一个合成函数,所以这里钉的是"没人给冷路径开第二条分支"。
  531. describe("ProductProjection cold hydration 可复用工作流的确认窗", () => {
  532. const script = 'const r = agent("检查员");\nreturn await r.ask<string>("检查一遍");';
  533. /** executor 的 resolveInput 产出的归一化入参:脚本已解析,来龙去脉在 saved 上。 */
  534. const savedRunInput = {
  535. name: "release-check",
  536. script,
  537. saved: {
  538. name: "release-check",
  539. args: { target: "packages/core", depth: 3, skipTests: false },
  540. path: "/repo/.zcode/workflows/release-check.dwf.ts",
  541. scope: "project",
  542. },
  543. };
  544. const saveInput = {
  545. name: "release-check",
  546. description: "对本仓库做一次发布前检查",
  547. script,
  548. path: "/repo/.zcode/workflows/release-check.dwf.ts",
  549. overwrite: true,
  550. scope: "project",
  551. };
  552. function gateEvents(toolName: string, input: unknown, reason: string): SessionEvent[] {
  553. const turnId = "turn-reusable-workflow";
  554. return [
  555. sessionEvent(1, SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 }),
  556. sessionEvent(2, SessionEventType.TurnStarted, { turnNumber: 1, input: "run it" }, turnId),
  557. sessionEvent(
  558. 3,
  559. SessionEventType.ToolCallScheduled,
  560. {
  561. toolCallId: "tc-1",
  562. toolName,
  563. input,
  564. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  565. },
  566. turnId,
  567. ),
  568. sessionEvent(
  569. 4,
  570. SessionEventType.PermissionRequested,
  571. {
  572. requestId: "req-1",
  573. toolCallId: "tc-1",
  574. toolName,
  575. riskLevel: "low",
  576. reason,
  577. input,
  578. optionsPolicy: "no-always-allow",
  579. },
  580. turnId,
  581. ),
  582. ];
  583. }
  584. function hydrate(events: readonly SessionEvent[]): {
  585. cold: ProductProjection;
  586. live: ProductProjection;
  587. } {
  588. const cold = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  589. const live = new ProductProjection("cold-hydration-session", "epoch-equivalent");
  590. cold.beginHydrationReplay();
  591. for (const event of events) cold.applyHydrationEvent(event);
  592. cold.completeHydrationReplay();
  593. for (const event of events) live.applyEvent(event);
  594. return { cold, live };
  595. }
  596. it("saved run 的归一化入参经冷恢复存活,Refine 仍在,且与 live 一致", () => {
  597. const { cold, live } = hydrate(
  598. gateEvents("CreateWorkflow", savedRunInput, "createWorkflow.runConfirmation"),
  599. );
  600. const payload = cold.getSnapshot().pendingInteractions[0]?.payload;
  601. expect(payload?.kind).toBe("permission");
  602. // 脚本与实参袋都还在:冷恢复后的窗与热态是同一个窗。
  603. expect(payload?.kind === "permission" && payload.detail).toEqual(savedRunInput);
  604. expect(
  605. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  606. ).toEqual(["allowOnce", "deny", "workflowRefine"]);
  607. expect(cold.getSnapshot().pendingInteractions).toEqual(live.getSnapshot().pendingInteractions);
  608. });
  609. it("SaveWorkflow 的落点与覆盖判定经冷恢复存活,且照旧不带 display", () => {
  610. const { cold, live } = hydrate(
  611. gateEvents("SaveWorkflow", saveInput, "saveWorkflow.confirmation"),
  612. );
  613. const payload = cold.getSnapshot().pendingInteractions[0]?.payload;
  614. expect(payload?.kind === "permission" && payload.detail).toEqual(saveInput);
  615. expect(payload && "display" in payload).toBe(false);
  616. expect(
  617. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  618. ).toEqual(["allowOnce", "deny"]);
  619. expect(cold.getSnapshot().pendingInteractions).toEqual(live.getSnapshot().pendingInteractions);
  620. });
  621. });
  622. // ── dwf 运行态的冷恢复(docs/dynamic-workflow/presentation.md 的 Tests:漏一处即静默丢运行态)──
  623. // 两个必须同时成立的条件,缺任一 run 就会在刷新/重连后消失,而 run 本身仍在飞:
  624. // 1. cold 批量路径与 live 路径经**同一个** reducer(applyEventInternal),产出同一份状态;
  625. // 2. cold merge 把这类事件识别为 memory-only 权威(它不在 durable transcript 里)。
  626. describe("ProductProjection cold hydration workflowRuns", () => {
  627. function runProgress(sequenceNumber: number, eventType: string, payload: unknown): SessionEvent {
  628. return sessionEvent(sequenceNumber, SessionEventType.DynamicWorkflowRunProgress, {
  629. runId: "dwfrun-cold",
  630. toolCallId: "tc-cold",
  631. sequence: sequenceNumber - 1,
  632. eventType,
  633. payload,
  634. });
  635. }
  636. const events = [
  637. runProgress(1, "run-started", {
  638. runId: "dwfrun-cold",
  639. caps: { maxConcurrency: 2 },
  640. }),
  641. runProgress(2, "actor-created", { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" }),
  642. runProgress(3, "node-queued", {
  643. instance: { siteId: "ask#1", ordinal: 1 },
  644. kind: "ask",
  645. actor: { siteId: "actor#1", ordinal: 1 },
  646. }),
  647. runProgress(4, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } }),
  648. ];
  649. it("cold 批量与 live 逐条产出同一份 workflowRuns(同一个 reducer 路径)", () => {
  650. const cold = new ProductProjection("cold-hydration-session", "epoch-cold");
  651. cold.beginHydrationReplay();
  652. for (const event of events) cold.applyHydrationEvent(event);
  653. cold.completeHydrationReplay();
  654. const live = new ProductProjection("cold-hydration-session", "epoch-live");
  655. for (const event of events) live.applyEvent(event);
  656. expect(cold.getSnapshot().workflowRuns).toEqual(live.getSnapshot().workflowRuns);
  657. expect(cold.getSnapshot().workflowRuns).toMatchObject({
  658. runs: [
  659. {
  660. runId: "dwfrun-cold",
  661. status: "running",
  662. // dispatched = 会话就绪、请求尚未准入 → actor 仍是 waiting(决策 39)。
  663. actors: [{ siteId: "actor#1", ordinal: 1, name: "planner", status: "waiting" }],
  664. nodes: [{ siteId: "ask#1", ordinal: 1, kind: "ask", phase: "dispatched" }],
  665. lastEventSequence: 3,
  666. },
  667. ],
  668. });
  669. });
  670. it("在飞 run 的运行态在冷恢复后存活(cold merge 视其为 memory-only 权威)", async () => {
  671. const merge = await import("../src/zcode-protocol-v4/cold-event-merge.js");
  672. const merged = merge.mergeColdConversationEvents({
  673. memoryEvents: events,
  674. messages: [],
  675. sessionId: "cold-hydration-session",
  676. });
  677. // 事件被保留,且**不进 unclassified 诊断**——落到那个分支意味着分类表漏了它,
  678. // 虽然事件仍被保留,但每次冷恢复都会刷一条"未知老事实"诊断。
  679. expect(
  680. merged.events.filter((event) => event.type === SessionEventType.DynamicWorkflowRunProgress),
  681. ).toHaveLength(events.length);
  682. expect(
  683. merged.diagnostics.find(
  684. (diagnostic) => diagnostic.code === "cold_merge.unclassified_event_preserved",
  685. ),
  686. ).toBeUndefined();
  687. const rebuilt = new ProductProjection("cold-hydration-session", "epoch-rebuilt");
  688. for (const event of merged.events) rebuilt.applyEvent(event);
  689. expect(rebuilt.getSnapshot().workflowRuns?.runs[0]).toMatchObject({
  690. runId: "dwfrun-cold",
  691. status: "running",
  692. nodes: [{ siteId: "ask#1", ordinal: 1, phase: "dispatched" }],
  693. });
  694. });
  695. });