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

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