cold-event-merge.test.ts 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. SessionEventType,
  4. type EventId,
  5. type MessageWithParts,
  6. type SessionEvent,
  7. type SessionId,
  8. type TraceId,
  9. type TurnId,
  10. } from "@zcode/contracts";
  11. import { ProductProjection } from "../src/zcode-protocol-v4/product-projection.js";
  12. import { buildColdFileChangeSummaries } from "../src/zcode-protocol-v4/cold-file-change-summaries.js";
  13. import * as coldEventMerge from "../src/zcode-protocol-v4/cold-event-merge.js";
  14. import { synthesizeEventsFromMessages } from "../src/zcode-protocol-v4/transcript-hydration.js";
  15. const { loadPersistedConversationMaterialization, mergeColdConversationEvents } = coldEventMerge;
  16. function userMessage(id: string, text: string, created: number, turnId: string): MessageWithParts {
  17. return {
  18. info: {
  19. id: id as never,
  20. sessionID: "s1" as never,
  21. role: "user",
  22. time: { created },
  23. agent: "default",
  24. model: { providerID: "p" as never, modelID: "m" as never },
  25. anchor: { turnId: turnId as never, origin: "realUser" },
  26. },
  27. parts: [
  28. {
  29. id: `${id}-text` as never,
  30. sessionID: "s1" as never,
  31. messageID: id as never,
  32. type: "text",
  33. text,
  34. },
  35. ],
  36. };
  37. }
  38. function assistantMessage(
  39. id: string,
  40. parentId: string,
  41. text: string,
  42. created: number,
  43. turnId: string,
  44. ): MessageWithParts {
  45. return {
  46. info: {
  47. id: id as never,
  48. sessionID: "s1" as never,
  49. role: "assistant",
  50. time: { created, completed: created + 1 },
  51. parentID: parentId as never,
  52. modelID: "m" as never,
  53. providerID: "p" as never,
  54. mode: "default",
  55. agent: "default",
  56. path: { cwd: "/", root: "/" },
  57. cost: 0,
  58. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  59. anchor: { turnId: turnId as never },
  60. },
  61. parts: [
  62. {
  63. id: `${id}-text` as never,
  64. sessionID: "s1" as never,
  65. messageID: id as never,
  66. type: "text",
  67. text,
  68. },
  69. ],
  70. };
  71. }
  72. function event(
  73. sequenceNumber: number,
  74. type: SessionEvent["type"],
  75. payload: unknown,
  76. turnId?: string,
  77. ): SessionEvent {
  78. return {
  79. id: `live-${sequenceNumber}` as EventId,
  80. sessionId: "s1" as SessionId,
  81. ...(turnId ? { turnId: turnId as TurnId } : {}),
  82. type,
  83. timestamp: new Date(10_000 + sequenceNumber),
  84. traceId: "trace-live" as TraceId,
  85. sequenceNumber,
  86. payload,
  87. };
  88. }
  89. function reduce(events: readonly SessionEvent[]): ProductProjection {
  90. const projection = new ProductProjection("s1", "cold-merge");
  91. for (const item of events) projection.applyEvent(item);
  92. return projection;
  93. }
  94. const HOOK_LIFECYCLE_EVENT_TYPES_FOR_TEST = new Set<SessionEvent["type"]>([
  95. SessionEventType.HookRunStarted,
  96. SessionEventType.HookRunProgress,
  97. SessionEventType.HookRunCompleted,
  98. SessionEventType.HookRunFailed,
  99. SessionEventType.HookRunBlocked,
  100. ]);
  101. describe("cold conversation three-source merge", () => {
  102. it("preserves a Highspeed fallback marker across cold transcript recovery", () => {
  103. const turnId = "runtime-turn-highspeed-fallback";
  104. const user = userMessage("u-highspeed-fallback", "accelerated prompt", 1_000, turnId);
  105. user.info.metadata = {
  106. conversationInputIntent: {
  107. sourceCommandId: "command-highspeed-fallback",
  108. queueItemId: "queue-highspeed-fallback",
  109. clientId: "desktop",
  110. kind: "sendText",
  111. text: "accelerated prompt",
  112. attachments: [],
  113. delivery: { requested: "startNow", admitted: "startNow" },
  114. order: { admissionSeq: 1 },
  115. steer: { state: "notRequested" },
  116. dispatch: { state: "drained" },
  117. admittedAt: 1_000,
  118. highspeed: {
  119. schemaVersion: 1,
  120. cardId: "hsc-cold-fallback",
  121. taskId: "s1",
  122. provider: "builtin:bigmodel-coding-plan",
  123. model: "GLM-5.3",
  124. issuedAt: 900,
  125. expiresAt: 1_100,
  126. regularTps: 80,
  127. },
  128. },
  129. };
  130. const fallback = event(
  131. 1,
  132. SessionEventType.TurnExecutionModelFallback,
  133. {
  134. inputId: "command-highspeed-fallback",
  135. reason: "highspeed_card_expired",
  136. fromModelSelection: { providerId: "account:bigmodel-highspeed-card", modelId: "GLM-5.3" },
  137. toModelSelection: { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3" },
  138. },
  139. turnId,
  140. );
  141. const merged = mergeColdConversationEvents({
  142. memoryEvents: [fallback],
  143. messages: [
  144. user,
  145. assistantMessage("a-highspeed-fallback", user.info.id, "continued", 1_200, turnId),
  146. ],
  147. sessionId: "s1",
  148. });
  149. expect(merged.events).toContainEqual(
  150. expect.objectContaining({
  151. id: fallback.id,
  152. payload: fallback.payload,
  153. type: SessionEventType.TurnExecutionModelFallback,
  154. }),
  155. );
  156. const row = reduce(merged.events)
  157. .getSnapshot()
  158. .rows.window.find((row) => row.kind === "userInput");
  159. expect(row).toMatchObject({
  160. sourceCommandId: "command-highspeed-fallback",
  161. highspeed: { fallbackAt: fallback.timestamp.getTime() },
  162. });
  163. expect(row?.highspeed).not.toHaveProperty("shareExcludedReason");
  164. });
  165. it("preserves SendMessage resumed subagent lifecycle that the transcript cannot synthesize", () => {
  166. const foregroundTurnId = "runtime-turn-foreground-agent";
  167. const turnId = "runtime-turn-send-message-resume";
  168. const foreground = assistantMessage(
  169. "a-foreground",
  170. "u-foreground",
  171. "",
  172. 1_100,
  173. foregroundTurnId,
  174. );
  175. foreground.parts = [
  176. {
  177. id: "a-foreground-tool" as never,
  178. sessionID: "s1" as never,
  179. messageID: "a-foreground" as never,
  180. type: "tool",
  181. callID: "call-agent",
  182. tool: "Agent",
  183. state: {
  184. status: "completed",
  185. input: {
  186. description: "前台任务",
  187. prompt: "完成前台任务",
  188. subagent_type: "general-purpose",
  189. },
  190. output: JSON.stringify({
  191. status: "completed",
  192. agentId: "agent-resume",
  193. agentType: "general-purpose",
  194. childSessionId: "sess-child-resume",
  195. description: "前台任务",
  196. content: [{ type: "text", text: "前台完成" }],
  197. }),
  198. title: "Agent 前台任务",
  199. metadata: {},
  200. time: { start: 1_001, end: 1_100 },
  201. },
  202. },
  203. ];
  204. const messages = [
  205. userMessage("u-foreground", "run the foreground agent", 1_000, foregroundTurnId),
  206. foreground,
  207. userMessage("u-resume", "resume the stopped agent", 2_000, turnId),
  208. assistantMessage("a-resume", "u-resume", "resumed", 2_100, turnId),
  209. ];
  210. const baseEvents = [
  211. event(1, SessionEventType.TurnStarted, { messageId: "u-resume" }, turnId),
  212. event(
  213. 2,
  214. SessionEventType.SubagentSpawned,
  215. {
  216. agentId: "agent-resume",
  217. agentType: "general-purpose",
  218. background: true,
  219. childSessionId: "sess-child-resume",
  220. description: "恢复到后台",
  221. parentToolCallId: "call-send-message",
  222. resumed: true,
  223. status: "running",
  224. },
  225. turnId,
  226. ),
  227. event(3, SessionEventType.TurnComplete, { status: "success" }, turnId),
  228. ];
  229. const running = mergeColdConversationEvents({
  230. memoryEvents: baseEvents,
  231. messages,
  232. sessionId: "s1",
  233. });
  234. expect(running.events.some((item) => item.type === SessionEventType.SubagentSpawned)).toBe(
  235. true,
  236. );
  237. const runningSnapshot = reduce(running.events).getSnapshot();
  238. expect(
  239. runningSnapshot.rows.window.filter(
  240. (row) => row.kind === "subagent" && row.entityId === "agent-resume",
  241. ),
  242. ).toHaveLength(1);
  243. expect(runningSnapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  244. childSessionId: "sess-child-resume",
  245. parentToolCallId: "call-agent",
  246. status: "running",
  247. });
  248. expect(runningSnapshot).toMatchObject({
  249. backgroundWorks: [
  250. expect.objectContaining({
  251. workId: "agent-resume",
  252. childSessionId: "sess-child-resume",
  253. status: "running",
  254. }),
  255. ],
  256. subagents: {
  257. running: [expect.objectContaining({ childSessionId: "sess-child-resume" })],
  258. },
  259. });
  260. const terminal = mergeColdConversationEvents({
  261. memoryEvents: [
  262. ...baseEvents,
  263. event(4, SessionEventType.BackgroundTaskCompleted, {
  264. taskId: "agent-resume",
  265. toolName: "Agent",
  266. taskKind: "subagent",
  267. childSessionId: "sess-child-resume",
  268. status: "cancelled",
  269. cancellable: false,
  270. }),
  271. event(5, SessionEventType.SubagentStopped, {
  272. agentId: "agent-resume",
  273. agentType: "general-purpose",
  274. background: true,
  275. childSessionId: "sess-child-resume",
  276. parentToolCallId: "call-send-message",
  277. status: "cancelled",
  278. }),
  279. ],
  280. messages,
  281. sessionId: "s1",
  282. });
  283. const terminalSnapshot = reduce(terminal.events).getSnapshot();
  284. expect(terminalSnapshot.backgroundWorks[0]).toMatchObject({
  285. workId: "agent-resume",
  286. status: "cancelled",
  287. });
  288. expect(terminalSnapshot.subagents).toMatchObject({ running: [], endedTotal: 1 });
  289. });
  290. it("rebuilds every ModelComplete file change from durable workspace checkpoint artifacts", async () => {
  291. const messages = [
  292. userMessage("u-file", "write the fixture", 1_000, "runtime-turn-file"),
  293. assistantMessage("a-file", "u-file", "done", 1_100, "runtime-turn-file"),
  294. ];
  295. const checkpoints = [
  296. event(
  297. 1,
  298. SessionEventType.CheckpointCreated,
  299. {
  300. checkpointId: "checkpoint-new-file",
  301. messageId: "u-file",
  302. targetMessageId: "u-file",
  303. scope: "workspace",
  304. snapshotRef: "artifact://checkpoint-new-file",
  305. },
  306. "runtime-turn-file",
  307. ),
  308. event(
  309. 2,
  310. SessionEventType.CheckpointCreated,
  311. {
  312. checkpointId: "checkpoint-edited-file",
  313. messageId: "u-file",
  314. targetMessageId: "u-file",
  315. scope: "workspace",
  316. snapshotRef: "artifact://checkpoint-edited-file",
  317. },
  318. "runtime-turn-file",
  319. ),
  320. ];
  321. const artifactsByRef = new Map([
  322. [
  323. "artifact://checkpoint-new-file",
  324. {
  325. version: 1,
  326. kind: "workspace_file_before_change",
  327. createdAt: "2026-07-16T00:00:00.000Z",
  328. toolCallId: "tool-write-new-file",
  329. toolName: "Write",
  330. files: [
  331. {
  332. path: "/work/summary.txt",
  333. existedBefore: false,
  334. beforeContent: null,
  335. afterContent: "line-1\nline-2\n",
  336. afterContentLength: 14,
  337. structuredPatch: [],
  338. },
  339. ],
  340. },
  341. ],
  342. [
  343. "artifact://checkpoint-edited-file",
  344. {
  345. version: 1,
  346. kind: "workspace_file_before_change",
  347. createdAt: "2026-07-16T00:00:01.000Z",
  348. toolCallId: "tool-edit-existing-file",
  349. toolName: "Edit",
  350. files: [
  351. {
  352. path: "/work/existing.txt",
  353. existedBefore: true,
  354. beforeContent: "old line\n",
  355. afterContent: "new line\n",
  356. afterContentLength: 9,
  357. structuredPatch: [],
  358. },
  359. ],
  360. },
  361. ],
  362. ]);
  363. const readArtifact = vi.fn(async (snapshotRef: string) => {
  364. const artifact = artifactsByRef.get(snapshotRef);
  365. if (!artifact) throw new Error(`missing fixture: ${snapshotRef}`);
  366. return JSON.stringify(artifact);
  367. });
  368. const fileChangeSummariesByMessageId = await buildColdFileChangeSummaries({
  369. events: checkpoints,
  370. messageIds: messages.map((message) => String(message.info.id)),
  371. readArtifact,
  372. });
  373. const merged = mergeColdConversationEvents({
  374. fileChangeSummariesByMessageId,
  375. memoryEvents: checkpoints,
  376. messages,
  377. sessionId: "s1",
  378. });
  379. const modelComplete = merged.events.find(
  380. (item) => item.type === SessionEventType.ModelComplete,
  381. );
  382. const header = reduce(merged.events)
  383. .getSnapshot()
  384. .rows.window.find((row) => row.kind === "turnHeader");
  385. expect(readArtifact.mock.calls.map(([snapshotRef]) => snapshotRef)).toEqual([
  386. "artifact://checkpoint-new-file",
  387. "artifact://checkpoint-edited-file",
  388. ]);
  389. expect((modelComplete?.payload as { fileChanges?: unknown }).fileChanges).toEqual({
  390. additions: 3,
  391. deletions: 1,
  392. files: 2,
  393. items: [
  394. {
  395. path: "/work/existing.txt",
  396. additions: 1,
  397. deletions: 1,
  398. writeCount: 1,
  399. toolNames: ["Edit"],
  400. },
  401. {
  402. path: "/work/summary.txt",
  403. additions: 2,
  404. deletions: 0,
  405. writeCount: 1,
  406. toolNames: ["Write"],
  407. },
  408. ],
  409. });
  410. expect(header).toMatchObject({
  411. fileChanges: { additions: 3, deletions: 1, files: 2, state: "active" },
  412. });
  413. });
  414. it("omits target authority when no persisted store read was performed", async () => {
  415. const memoryGoal = {
  416. sessionID: "s1",
  417. targetID: "target-memory",
  418. objective: "keep memory authority",
  419. summaryTitle: null,
  420. status: "active",
  421. tokenBudget: null,
  422. tokensUsed: 0,
  423. timeUsedSeconds: 0,
  424. time: { created: 1, updated: 2 },
  425. };
  426. const memoryEvents = [
  427. event(1, SessionEventType.TargetChanged, {
  428. action: "set",
  429. source: "runtime",
  430. target: memoryGoal,
  431. }),
  432. ];
  433. const source = await loadPersistedConversationMaterialization({
  434. memoryEvents,
  435. sessionId: "s1",
  436. });
  437. expect(Object.prototype.hasOwnProperty.call(source, "target")).toBe(false);
  438. const merged = mergeColdConversationEvents({
  439. goalVerificationEntries: source.goalVerificationEntries,
  440. memoryEvents: source.memoryEvents,
  441. messages: source.messages,
  442. sessionId: "s1",
  443. ...(Object.prototype.hasOwnProperty.call(source, "target") ? { target: source.target } : {}),
  444. });
  445. expect(reduce(merged.events).getSnapshot().goal).toMatchObject({
  446. objective: "keep memory authority",
  447. });
  448. expect(merged.usedDurableTranscript).toBe(false);
  449. });
  450. it("persisted source filters the reverted branch and reads the cold goal", async () => {
  451. const oldUser = userMessage("u-old", "old question", 1_000, "turn-old");
  452. const oldAssistant = assistantMessage("a-old", "u-old", "old answer", 1_100, "turn-old");
  453. const rewindNotice = userMessage("u-rewind", "new question", 2_000, "turn-new");
  454. const newAssistant = assistantMessage("a-new", "u-rewind", "new answer", 2_100, "turn-new");
  455. const target = {
  456. sessionID: "s1",
  457. targetID: "target-1",
  458. objective: "ship the fix",
  459. summaryTitle: null,
  460. status: "paused",
  461. tokenBudget: null,
  462. tokensUsed: 7,
  463. timeUsedSeconds: 3,
  464. time: { created: 1, updated: 2 },
  465. };
  466. const getSession = vi.fn(async () => ({
  467. id: "s1",
  468. revert: {
  469. kind: "conversation_rewind",
  470. targetMessageID: "u-old",
  471. createdMessageID: "u-rewind",
  472. keptMessageIDs: [],
  473. },
  474. }));
  475. const messages = vi.fn(async () => [oldUser, oldAssistant, rewindNotice, newAssistant]);
  476. const readTarget = vi.fn(async () => target);
  477. const sessionEntries = vi.fn(async () => []);
  478. const loaded = await loadPersistedConversationMaterialization({
  479. memoryEvents: [],
  480. sessionId: "s1",
  481. store: { getSession, messages, readTarget, sessionEntries },
  482. });
  483. expect(loaded.messages.map((message: MessageWithParts) => String(message.info.id))).toEqual([
  484. "u-rewind",
  485. "a-new",
  486. ]);
  487. expect(loaded.target).toEqual(target);
  488. expect(getSession).toHaveBeenCalledWith("s1");
  489. expect(readTarget).toHaveBeenCalledWith({ sessionID: "s1" });
  490. });
  491. it("识别 shared_context transcript 并带出导入会话标题", async () => {
  492. const context = userMessage("shared-context", "# imported", 1_000, "shared-context-turn");
  493. context.info.synthetic = true;
  494. context.info.source = "shared_context";
  495. context.info.visibility = "model-only";
  496. context.info.semantics = {
  497. origin: "import",
  498. kind: "shared_context",
  499. source: "conversation_share",
  500. uiVisibility: "hidden",
  501. providerVisibility: "visible",
  502. transcriptVisibility: "visible",
  503. };
  504. const loaded = await loadPersistedConversationMaterialization({
  505. memoryEvents: [],
  506. sessionId: "s1",
  507. store: {
  508. getSession: async () => ({ title: "导入的分享标题" }),
  509. messages: async () => [context],
  510. readTarget: async () => null,
  511. },
  512. });
  513. // 分享导入已使用统一 metadata;冷恢复仍须保留标题,不能要求废弃的平铺字段。
  514. expect(loaded.sharedContextImport).toEqual({ title: "导入的分享标题" });
  515. });
  516. it("keeps an explicitly persisted null target as durable authority", async () => {
  517. const loaded = await loadPersistedConversationMaterialization({
  518. memoryEvents: [],
  519. sessionId: "s1",
  520. store: {
  521. getSession: async () => null,
  522. messages: async () => [],
  523. readTarget: async () => null,
  524. },
  525. });
  526. expect(Object.prototype.hasOwnProperty.call(loaded, "target")).toBe(true);
  527. expect(loaded.target).toBeNull();
  528. const merged = mergeColdConversationEvents({
  529. memoryEvents: [
  530. event(1, SessionEventType.TargetChanged, {
  531. action: "set",
  532. source: "runtime",
  533. target: {
  534. sessionID: "s1",
  535. targetID: "stale",
  536. objective: "stale memory target",
  537. summaryTitle: null,
  538. status: "active",
  539. tokenBudget: null,
  540. tokensUsed: 0,
  541. timeUsedSeconds: 0,
  542. time: { created: 1, updated: 2 },
  543. },
  544. }),
  545. ],
  546. messages: [],
  547. sessionId: "s1",
  548. target: loaded.target,
  549. });
  550. expect(reduce(merged.events).getSnapshot().goal).toBeNull();
  551. expect(merged.usedDurableTranscript).toBe(true);
  552. });
  553. it("materializes the persisted cold goal before verifier lifecycle", () => {
  554. const target = {
  555. sessionID: "s1",
  556. targetID: "target-1",
  557. objective: "ship the fix",
  558. summaryTitle: null,
  559. status: "paused",
  560. tokenBudget: null,
  561. tokensUsed: 7,
  562. timeUsedSeconds: 3,
  563. time: { created: 1, updated: 2 },
  564. };
  565. const merged = mergeColdConversationEvents({
  566. memoryEvents: [
  567. event(1, SessionEventType.TargetChanged, {
  568. action: "set",
  569. source: "runtime",
  570. target: { ...target, objective: "stale memory goal", status: "active" },
  571. }),
  572. ],
  573. messages: [],
  574. sessionId: "s1",
  575. target,
  576. } as Parameters<typeof mergeColdConversationEvents>[0]);
  577. expect(reduce(merged.events).getSnapshot().goal).toMatchObject({
  578. objective: "ship the fix",
  579. status: "paused",
  580. });
  581. expect(merged.usedDurableTranscript).toBe(true);
  582. });
  583. it("uses transcript as completed正文 authority while retaining queue-only memory state", () => {
  584. const messages = [
  585. userMessage("u1", "question", 1_000, "turn-1"),
  586. assistantMessage("a1", "u1", "durable answer", 1_100, "turn-1"),
  587. ];
  588. const memoryEvents = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  589. memoryEvents.push(
  590. event(
  591. memoryEvents.length + 1,
  592. SessionEventType.TurnSteerQueued,
  593. {
  594. pendingInputId: "queue-1",
  595. input: "follow up",
  596. inputPreview: "follow up",
  597. inputSize: 9,
  598. targetTurnId: "turn-live",
  599. queueLength: 1,
  600. delivery: "queue",
  601. },
  602. "turn-live",
  603. ),
  604. );
  605. const merged = mergeColdConversationEvents({
  606. memoryEvents,
  607. messages,
  608. sessionId: "s1",
  609. });
  610. const snapshot = reduce(merged.events).getSnapshot();
  611. expect(
  612. snapshot.rows.window
  613. .filter((row) => row.kind === "assistantText")
  614. .map((row) => (row.kind === "assistantText" ? row.text : "")),
  615. ).toEqual(["durable answer"]);
  616. expect(snapshot.queue.items.map((item) => item.queueItemId)).toEqual(["queue-1"]);
  617. expect(merged.events.map((item) => item.sequenceNumber)).toEqual(
  618. merged.events.map((_, index) => index + 1),
  619. );
  620. expect(merged.diagnostics).toEqual(
  621. expect.arrayContaining([
  622. expect.objectContaining({ code: "cold_merge.durable_event_suppressed" }),
  623. ]),
  624. );
  625. });
  626. it("keeps the whole unfinished memory turn after durable completed history", () => {
  627. const messages = [
  628. userMessage("u1", "question", 1_000, "turn-1"),
  629. assistantMessage("a1", "u1", "answer", 1_100, "turn-1"),
  630. ];
  631. const completedMemory = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  632. const next = completedMemory.length + 1;
  633. const memoryEvents = [
  634. ...completedMemory,
  635. event(
  636. next,
  637. SessionEventType.TurnStarted,
  638. { turnNumber: 2, input: "live question", messageId: "u2-live" },
  639. "turn-2",
  640. ),
  641. event(
  642. next + 1,
  643. SessionEventType.ModelStreaming,
  644. {
  645. assistantMessageId: "a2-live",
  646. delta: "",
  647. done: false,
  648. kind: "text_start",
  649. },
  650. "turn-2",
  651. ),
  652. event(
  653. next + 2,
  654. SessionEventType.ModelStreaming,
  655. {
  656. assistantMessageId: "a2-live",
  657. delta: "partial",
  658. done: false,
  659. kind: "text_delta",
  660. },
  661. "turn-2",
  662. ),
  663. ];
  664. const merged = mergeColdConversationEvents({
  665. memoryEvents,
  666. messages,
  667. sessionId: "s1",
  668. });
  669. const snapshot = reduce(merged.events).getSnapshot();
  670. const assistantRows = snapshot.rows.window.filter((row) => row.kind === "assistantText");
  671. expect(assistantRows.map((row) => (row.kind === "assistantText" ? row.text : ""))).toEqual([
  672. "answer",
  673. "partial",
  674. ]);
  675. expect(assistantRows.at(-1)).toEqual(expect.objectContaining({ state: "streaming" }));
  676. expect(snapshot.control.phase).toBe("running");
  677. });
  678. it("never deduplicates an unanchored legacy turn by equal input text", () => {
  679. const messages = [
  680. userMessage("u1", "same question", 1_000, "turn-1"),
  681. assistantMessage("a1", "u1", "first answer", 1_100, "turn-1"),
  682. ];
  683. const memoryEvents = [
  684. event(1, SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 }),
  685. // legacy TurnStarted: 文本与 durable u1 相同,但无 messageId/turn anchor,
  686. // 它可能是另一次真实提交,不得按文本查重。
  687. event(2, SessionEventType.TurnStarted, { turnNumber: 2, input: "same question" }, "legacy-2"),
  688. event(
  689. 3,
  690. SessionEventType.TurnComplete,
  691. {
  692. response: "",
  693. tokenCount: 0,
  694. toolCallCount: 0,
  695. duration: 1,
  696. resultType: "success",
  697. },
  698. "legacy-2",
  699. ),
  700. ];
  701. const merged = mergeColdConversationEvents({ memoryEvents, messages, sessionId: "s1" });
  702. const userRows = reduce(merged.events)
  703. .getSnapshot()
  704. .rows.window.filter((row) => row.kind === "userInput");
  705. expect(userRows.map((row) => (row.kind === "userInput" ? row.text : ""))).toEqual([
  706. "same question",
  707. "same question",
  708. ]);
  709. expect(merged.diagnostics).toEqual(
  710. expect.arrayContaining([
  711. expect.objectContaining({ code: "cold_merge.ambiguous_legacy_turn_preserved", count: 1 }),
  712. ]),
  713. );
  714. });
  715. it("deduplicates a goal boundary only when session_entry or timeline part really exists", () => {
  716. const messages = [
  717. userMessage("u1", "question", 1_000, "turn-1"),
  718. assistantMessage("a1", "u1", "answer", 1_100, "turn-1"),
  719. ];
  720. const memoryGoal = event(
  721. 1,
  722. SessionEventType.TargetCompletionVerification,
  723. {
  724. targetId: "target-1",
  725. goalIteration: 1,
  726. verificationId: "verify-1",
  727. status: "completed",
  728. },
  729. "turn-1",
  730. );
  731. const goalVerificationEntries = [
  732. {
  733. payload: {
  734. targetId: "target-1",
  735. goalIteration: 1,
  736. verificationId: "verify-1",
  737. status: "completed",
  738. anchorAssistantMessageId: "a1",
  739. },
  740. sequenceNumber: 1,
  741. timeCreated: 1_200,
  742. },
  743. ];
  744. const withDurableBoundary = mergeColdConversationEvents({
  745. memoryEvents: [memoryGoal],
  746. messages,
  747. sessionId: "s1",
  748. goalVerificationEntries,
  749. });
  750. const withoutDurableBoundary = mergeColdConversationEvents({
  751. memoryEvents: [memoryGoal],
  752. messages,
  753. sessionId: "s1",
  754. });
  755. const markerCount = (events: readonly SessionEvent[]) =>
  756. reduce(events)
  757. .getSnapshot()
  758. .rows.window.filter(
  759. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  760. ).length;
  761. expect(markerCount(withDurableBoundary.events)).toBe(1);
  762. expect(markerCount(withoutDurableBoundary.events)).toBe(1);
  763. expect(withoutDurableBoundary.diagnostics).toEqual(
  764. expect.arrayContaining([
  765. expect.objectContaining({ code: "cold_merge.memory_boundary_preserved", count: 1 }),
  766. ]),
  767. );
  768. });
  769. it("replays the full lifecycle of a still-pending edited queue item", () => {
  770. const initial = event(
  771. 1,
  772. SessionEventType.TurnSteerQueued,
  773. {
  774. pendingInputId: "queue-edit",
  775. input: "original",
  776. inputPreview: "original",
  777. inputSize: 8,
  778. targetTurnId: "turn-live",
  779. queueLength: 1,
  780. delivery: "guide",
  781. intent: {
  782. sourceCommandId: "cmd-mobile-1",
  783. queueItemId: "queue-edit",
  784. clientId: "mobile-client",
  785. kind: "sendText",
  786. admissionSeq: 7,
  787. admittedAt: 12_345,
  788. requestedDelivery: "guide",
  789. admittedDelivery: "guide",
  790. queuePosition: 0,
  791. attachmentRefs: [
  792. {
  793. ref: "artifact://attachment-1",
  794. fileName: "note.txt",
  795. mime: "text/plain",
  796. bytes: 12,
  797. },
  798. ],
  799. },
  800. },
  801. "turn-live",
  802. );
  803. const legacyEdit = event(
  804. 2,
  805. SessionEventType.TurnSteerQueued,
  806. {
  807. pendingInputId: "queue-edit",
  808. input: "edited",
  809. inputPreview: "edited",
  810. inputSize: 6,
  811. targetTurnId: "turn-live",
  812. queueLength: 1,
  813. },
  814. "turn-live",
  815. );
  816. const deliveryChanged = event(
  817. 3,
  818. SessionEventType.TurnSteerDeliveryChanged,
  819. {
  820. pendingInputId: "queue-edit",
  821. targetTurnId: "turn-live",
  822. requestedDelivery: "guide",
  823. admittedDelivery: "queue",
  824. fallbackReasonCode: "guide.noToolBoundary",
  825. },
  826. "turn-live",
  827. );
  828. const merged = mergeColdConversationEvents({
  829. memoryEvents: [initial, legacyEdit, deliveryChanged],
  830. messages: [],
  831. sessionId: "s1",
  832. });
  833. const item = reduce(merged.events).getSnapshot().queue.items[0];
  834. expect(item).toEqual(
  835. expect.objectContaining({
  836. queueItemId: "queue-edit",
  837. text: "edited",
  838. sourceCommandId: "cmd-mobile-1",
  839. clientId: "mobile-client",
  840. attachments: [
  841. expect.objectContaining({ ref: "artifact://attachment-1", fileName: "note.txt" }),
  842. ],
  843. delivery: {
  844. requested: "guide",
  845. admitted: "queue",
  846. fallbackReasonCode: "guide.noToolBoundary",
  847. },
  848. order: { admissionSeq: 7, queuePosition: 0 },
  849. admittedAt: 12_345,
  850. }),
  851. );
  852. });
  853. it("inserts an anchored memory boundary at its durable product-turn tail", () => {
  854. const messages = [
  855. userMessage("u1", "first question", 1_000, "runtime-turn-1"),
  856. assistantMessage("a1", "u1", "first answer", 1_100, "runtime-turn-1"),
  857. userMessage("u2", "second question", 2_000, "runtime-turn-2"),
  858. assistantMessage("a2", "u2", "second answer", 2_100, "runtime-turn-2"),
  859. ];
  860. const unfinishedStart = event(
  861. 1,
  862. SessionEventType.TurnStarted,
  863. { turnNumber: 3, input: "live third question", messageId: "u3-live" },
  864. "runtime-turn-3",
  865. );
  866. const anchoredBoundary = event(
  867. 2,
  868. SessionEventType.TargetCompletionVerification,
  869. {
  870. targetId: "target-1",
  871. goalIteration: 1,
  872. verificationId: "verify-1",
  873. status: "completed",
  874. verification: { passed: true, reason: "done" },
  875. anchorAssistantMessageId: "a1",
  876. },
  877. "runtime-turn-3",
  878. );
  879. const unfinishedStream = event(
  880. 3,
  881. SessionEventType.ModelStreaming,
  882. {
  883. assistantMessageId: "a3-live",
  884. delta: "partial third answer",
  885. done: false,
  886. kind: "text_delta",
  887. },
  888. "runtime-turn-3",
  889. );
  890. const merged = mergeColdConversationEvents({
  891. memoryEvents: [unfinishedStart, anchoredBoundary, unfinishedStream],
  892. messages,
  893. sessionId: "s1",
  894. });
  895. const rows = reduce(merged.events).getSnapshot().rows.window;
  896. const firstAnswerIndex = rows.findIndex(
  897. (row) => row.kind === "assistantText" && row.text === "first answer",
  898. );
  899. const markerIndex = rows.findIndex(
  900. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  901. );
  902. const secondQuestionIndex = rows.findIndex(
  903. (row) => row.kind === "userInput" && row.text === "second question",
  904. );
  905. expect(firstAnswerIndex).toBeGreaterThanOrEqual(0);
  906. expect(markerIndex).toBeGreaterThan(firstAnswerIndex);
  907. expect(markerIndex).toBeLessThan(secondQuestionIndex);
  908. expect(rows[markerIndex]?.turnId).toBe(rows[firstAnswerIndex]?.turnId);
  909. expect(rows[markerIndex]?.turnId).not.toBe(rows[secondQuestionIndex]?.turnId);
  910. const unfinishedStartIndex = merged.events.findIndex(
  911. (item) => item.type === SessionEventType.TurnStarted && item.turnId === "runtime-turn-3",
  912. );
  913. const secondDurableStartIndex = merged.events.findIndex(
  914. (item) =>
  915. item.type === SessionEventType.TurnStarted &&
  916. (item.payload as { messageId?: string }).messageId === "u2",
  917. );
  918. const unfinishedStreamIndex = merged.events.findIndex(
  919. (item) => item.type === SessionEventType.ModelStreaming && item.turnId === "runtime-turn-3",
  920. );
  921. expect(unfinishedStartIndex).toBeGreaterThan(secondDurableStartIndex);
  922. expect(unfinishedStreamIndex).toBeGreaterThan(unfinishedStartIndex);
  923. });
  924. it("HK10 preserves Hook lifecycle and anchors resume SessionStart to the next durable turn", () => {
  925. const descriptor = {
  926. clientVisible: true,
  927. sourceKind: "user",
  928. sourcePath: "/Users/example/.zcode/cli/config.json",
  929. executionType: "process",
  930. executionMode: "foreground",
  931. commandDisplay: 'echo ""',
  932. timeoutMs: 5_000,
  933. };
  934. const hookEvents = [
  935. event(
  936. 1,
  937. SessionEventType.HookRunStarted,
  938. {
  939. descriptor,
  940. hookEventName: "SessionStart",
  941. hookIndex: 0,
  942. hookCount: 1,
  943. hookInvocationId: "startup-hook",
  944. hookRunId: "startup-run",
  945. startedAt: 10_001,
  946. },
  947. "runtime-turn-before-product-mapping",
  948. ),
  949. event(
  950. 2,
  951. SessionEventType.HookRunCompleted,
  952. {
  953. descriptor,
  954. durationMs: 1,
  955. hookEventName: "SessionStart",
  956. hookIndex: 0,
  957. hookCount: 1,
  958. hookInvocationId: "startup-hook",
  959. hookRunId: "startup-run",
  960. outcome: "success",
  961. startedAt: 10_001,
  962. },
  963. "runtime-turn-before-product-mapping",
  964. ),
  965. event(3, SessionEventType.TurnStarted, { turnNumber: 2, input: "next" }, "runtime-turn-2"),
  966. event(
  967. 4,
  968. SessionEventType.HookRunStarted,
  969. {
  970. descriptor,
  971. hookEventName: "PreToolUse",
  972. hookIndex: 0,
  973. hookCount: 1,
  974. hookInvocationId: "tool-hook",
  975. hookRunId: "tool-run",
  976. startedAt: 10_004,
  977. toolCallId: "tool-1",
  978. toolName: "Write",
  979. },
  980. "runtime-turn-2",
  981. ),
  982. event(
  983. 5,
  984. SessionEventType.HookRunCompleted,
  985. {
  986. descriptor,
  987. durationMs: 1,
  988. hookEventName: "PreToolUse",
  989. hookIndex: 0,
  990. hookCount: 1,
  991. hookInvocationId: "tool-hook",
  992. hookRunId: "tool-run",
  993. outcome: "success",
  994. startedAt: 10_004,
  995. toolCallId: "tool-1",
  996. toolName: "Write",
  997. },
  998. "runtime-turn-2",
  999. ),
  1000. event(6, SessionEventType.HookRunProgress, { hookRunId: "progress-run" }),
  1001. event(7, SessionEventType.HookRunFailed, { hookRunId: "failed-run" }),
  1002. event(8, SessionEventType.HookRunBlocked, { hookRunId: "blocked-run" }),
  1003. ];
  1004. const merged = mergeColdConversationEvents({
  1005. memoryEvents: hookEvents,
  1006. messages: [
  1007. userMessage("u1", "run", 1_000, "runtime-turn-1"),
  1008. assistantMessage("a1", "u1", "done", 1_100, "runtime-turn-1"),
  1009. userMessage("u2", "next", 11_000, "runtime-turn-2"),
  1010. assistantMessage("a2", "u2", "next done", 11_100, "runtime-turn-2"),
  1011. ],
  1012. sessionId: "s1",
  1013. });
  1014. const snapshot = reduce(merged.events).getSnapshot();
  1015. const hookEventTypes = new Set([
  1016. SessionEventType.HookRunStarted,
  1017. SessionEventType.HookRunProgress,
  1018. SessionEventType.HookRunCompleted,
  1019. SessionEventType.HookRunFailed,
  1020. SessionEventType.HookRunBlocked,
  1021. ]);
  1022. expect(merged.events.filter((item) => hookEventTypes.has(item.type))).toHaveLength(7);
  1023. expect(
  1024. merged.diagnostics.find(
  1025. (diagnostic) => String(diagnostic.code) === "cold_merge.non_product_event_suppressed",
  1026. ),
  1027. ).toBeUndefined();
  1028. expect(
  1029. merged.diagnostics.some(
  1030. (diagnostic) => diagnostic.code === "cold_merge.unclassified_event_preserved",
  1031. ),
  1032. ).toBe(false);
  1033. const hookRows = snapshot.rows.window.filter((row) => row.kind === "hookInvocation");
  1034. expect(hookRows).toHaveLength(2);
  1035. expect(hookRows.map((row) => row.turnId)).toEqual(["runtime-turn-2", "runtime-turn-2"]);
  1036. expect(snapshot.rows.window.map((row) => row.turnId)).not.toContain("session-hooks:s1");
  1037. });
  1038. it("HK10 maps completed Hook runtime turns through durable anchors during cold recovery", () => {
  1039. const descriptor = {
  1040. clientVisible: true,
  1041. sourceKind: "user",
  1042. sourcePath: "/Users/example/.zcode/cli/config.json",
  1043. executionType: "process",
  1044. executionMode: "foreground",
  1045. commandDisplay: 'echo ""',
  1046. timeoutMs: 5_000,
  1047. };
  1048. const lifecycle = (
  1049. sequenceNumber: number,
  1050. hookEventName: "SessionStart" | "UserPromptSubmit" | "PreToolUse",
  1051. hookInvocationId: string,
  1052. runtimeTurnId: string,
  1053. ) => [
  1054. event(
  1055. sequenceNumber,
  1056. SessionEventType.HookRunStarted,
  1057. {
  1058. descriptor,
  1059. hookEventName,
  1060. hookIndex: 0,
  1061. hookCount: 1,
  1062. hookInvocationId,
  1063. hookRunId: `${hookInvocationId}-run`,
  1064. startedAt: 10_000 + sequenceNumber,
  1065. },
  1066. runtimeTurnId,
  1067. ),
  1068. event(
  1069. sequenceNumber + 1,
  1070. SessionEventType.HookRunCompleted,
  1071. {
  1072. descriptor,
  1073. durationMs: 1,
  1074. hookEventName,
  1075. hookIndex: 0,
  1076. hookCount: 1,
  1077. hookInvocationId,
  1078. hookRunId: `${hookInvocationId}-run`,
  1079. outcome: "success",
  1080. startedAt: 10_000 + sequenceNumber,
  1081. },
  1082. runtimeTurnId,
  1083. ),
  1084. ];
  1085. const memoryEvents = [
  1086. ...lifecycle(1, "SessionStart", "startup-hook", "runtime-before-first-turn"),
  1087. event(
  1088. 3,
  1089. SessionEventType.TurnStarted,
  1090. { turnNumber: 1, input: "first", messageId: "u1" },
  1091. "runtime-turn-1",
  1092. ),
  1093. ...lifecycle(4, "UserPromptSubmit", "prompt-hook", "runtime-turn-1"),
  1094. event(6, SessionEventType.TurnComplete, { resultType: "success" }, "runtime-turn-1"),
  1095. event(
  1096. 7,
  1097. SessionEventType.TurnStarted,
  1098. { turnNumber: 2, input: "second", messageId: "u2" },
  1099. "runtime-turn-2",
  1100. ),
  1101. ...lifecycle(8, "PreToolUse", "tool-hook", "runtime-turn-2"),
  1102. event(10, SessionEventType.TurnComplete, { resultType: "success" }, "runtime-turn-2"),
  1103. ];
  1104. const merged = mergeColdConversationEvents({
  1105. memoryEvents,
  1106. messages: [
  1107. userMessage("u1", "first", 1_000, "runtime-turn-1"),
  1108. assistantMessage("a1", "u1", "first done", 1_100, "runtime-turn-1"),
  1109. userMessage("u2", "second", 2_000, "runtime-turn-2"),
  1110. assistantMessage("a2", "u2", "second done", 2_100, "runtime-turn-2"),
  1111. ],
  1112. sessionId: "s1",
  1113. });
  1114. const hookEvents = merged.events.filter((item) =>
  1115. HOOK_LIFECYCLE_EVENT_TYPES_FOR_TEST.has(item.type),
  1116. );
  1117. expect(
  1118. hookEvents
  1119. .filter((item) => item.type === SessionEventType.HookRunStarted)
  1120. .map((item) => item.turnId),
  1121. ).toEqual(["hydrate-turn-1", "hydrate-turn-1", "hydrate-turn-2"]);
  1122. const hookRows = reduce(merged.events)
  1123. .getSnapshot()
  1124. .rows.window.filter((row) => row.kind === "hookInvocation");
  1125. expect(hookRows.map((row) => [row.hookEventName, row.turnId])).toEqual([
  1126. ["SessionStart", "u1"],
  1127. ["UserPromptSubmit", "u1"],
  1128. ["PreToolUse", "u2"],
  1129. ]);
  1130. expect(hookRows.map((row) => row.turnId)).not.toContain("runtime-turn-1");
  1131. expect(hookRows.map((row) => row.turnId)).not.toContain("runtime-turn-2");
  1132. });
  1133. it("HK10 keeps Hook invocations on queue-drained product turns sharing one runtime anchor", () => {
  1134. const descriptor = {
  1135. clientVisible: true,
  1136. sourceKind: "user",
  1137. sourcePath: "/Users/example/.zcode/cli/config.json",
  1138. executionType: "process",
  1139. executionMode: "foreground",
  1140. commandDisplay: 'echo ""',
  1141. timeoutMs: 5_000,
  1142. };
  1143. const lifecycle = (sequenceNumber: number, hookInvocationId: string, runtimeTurnId: string) => [
  1144. event(
  1145. sequenceNumber,
  1146. SessionEventType.HookRunStarted,
  1147. {
  1148. descriptor,
  1149. hookEventName: "UserPromptSubmit",
  1150. hookIndex: 0,
  1151. hookCount: 1,
  1152. hookInvocationId,
  1153. hookRunId: `${hookInvocationId}-run`,
  1154. startedAt: 10_000 + sequenceNumber,
  1155. },
  1156. runtimeTurnId,
  1157. ),
  1158. event(
  1159. sequenceNumber + 1,
  1160. SessionEventType.HookRunCompleted,
  1161. {
  1162. descriptor,
  1163. durationMs: 1,
  1164. hookEventName: "UserPromptSubmit",
  1165. hookIndex: 0,
  1166. hookCount: 1,
  1167. hookInvocationId,
  1168. hookRunId: `${hookInvocationId}-run`,
  1169. outcome: "success",
  1170. startedAt: 10_000 + sequenceNumber,
  1171. },
  1172. runtimeTurnId,
  1173. ),
  1174. ];
  1175. const runtimeTurnId = "runtime-turn-shared";
  1176. const [firstStarted, firstCompleted] = lifecycle(2, "first-prompt-hook", runtimeTurnId);
  1177. const memoryEvents = [
  1178. event(
  1179. 1,
  1180. SessionEventType.TurnStarted,
  1181. { turnNumber: 1, input: "first", messageId: "u1" },
  1182. runtimeTurnId,
  1183. ),
  1184. firstStarted!,
  1185. event(
  1186. 3,
  1187. SessionEventType.TurnSteerDrained,
  1188. {
  1189. pendingInputIds: ["queue-2"],
  1190. injectedMessageIds: ["u2"],
  1191. drainedInputs: [
  1192. {
  1193. delivery: "queue",
  1194. messageId: "u2",
  1195. pendingInputId: "queue-2",
  1196. text: "second",
  1197. },
  1198. ],
  1199. targetTurnId: runtimeTurnId,
  1200. },
  1201. runtimeTurnId,
  1202. ),
  1203. event(
  1204. 4,
  1205. SessionEventType.SessionInputPromoted,
  1206. {
  1207. pendingInputId: "queue-2",
  1208. sourceCommandId: "command-2",
  1209. messageId: "u2",
  1210. },
  1211. runtimeTurnId,
  1212. ),
  1213. { ...firstCompleted!, sequenceNumber: 5 },
  1214. ...lifecycle(6, "second-prompt-hook", runtimeTurnId),
  1215. event(
  1216. 8,
  1217. SessionEventType.TurnComplete,
  1218. {
  1219. response: "",
  1220. tokenCount: 0,
  1221. toolCallCount: 0,
  1222. duration: 10,
  1223. resultType: "success",
  1224. },
  1225. runtimeTurnId,
  1226. ),
  1227. ];
  1228. const merged = mergeColdConversationEvents({
  1229. memoryEvents,
  1230. messages: [
  1231. userMessage("u1", "first", 1_000, runtimeTurnId),
  1232. assistantMessage("a1", "u1", "first done", 1_100, runtimeTurnId),
  1233. userMessage("u2", "second", 2_000, runtimeTurnId),
  1234. assistantMessage("a2", "u2", "second done", 2_100, runtimeTurnId),
  1235. ],
  1236. sessionId: "s1",
  1237. });
  1238. expect(
  1239. merged.events
  1240. .filter((item) => item.type === SessionEventType.HookRunStarted)
  1241. .map((item) => item.turnId),
  1242. ).toEqual(["hydrate-turn-1", "hydrate-turn-2"]);
  1243. const hookRows = reduce(merged.events)
  1244. .getSnapshot()
  1245. .rows.window.filter((row) => row.kind === "hookInvocation");
  1246. expect(hookRows.map((row) => [row.hookInvocationId, row.turnId])).toEqual([
  1247. ["first-prompt-hook", "u1"],
  1248. ["second-prompt-hook", "u2"],
  1249. ]);
  1250. expect(hookRows.map((row) => row.turnId)).not.toContain(runtimeTurnId);
  1251. });
  1252. it("HK17 does not anchor a SessionStart summary onto a model-only compact turn during cold merge", () => {
  1253. // Bug 根因:首条输入即 /compact 时,SessionStart Hook 真实执行且事件携带 compact 的
  1254. // runtime turnId。cold 归属把 pending SessionStart 绑到「下一个 TurnStarted」;compact
  1255. // 维护 turn 也是 TurnStarted(inputVisibility=model-only),旧逻辑会把摘要错误归位到
  1256. // compact marker 轮。维护 turn 没有资格承载摘要,必须跳过等下一条真实 turn。
  1257. const descriptor = {
  1258. clientVisible: true,
  1259. sourceKind: "user",
  1260. sourcePath: "/Users/example/.zcode/cli/config.json",
  1261. executionType: "process",
  1262. executionMode: "foreground",
  1263. commandDisplay: 'echo ""',
  1264. timeoutMs: 5_000,
  1265. };
  1266. const memoryEvents = [
  1267. event(
  1268. 1,
  1269. SessionEventType.HookRunStarted,
  1270. {
  1271. descriptor,
  1272. hookEventName: "SessionStart",
  1273. hookIndex: 0,
  1274. hookCount: 1,
  1275. hookInvocationId: "startup-hook",
  1276. hookRunId: "startup-run",
  1277. startedAt: 10_001,
  1278. },
  1279. "runtime-turn-compact",
  1280. ),
  1281. event(
  1282. 2,
  1283. SessionEventType.HookRunCompleted,
  1284. {
  1285. descriptor,
  1286. durationMs: 1,
  1287. hookEventName: "SessionStart",
  1288. hookIndex: 0,
  1289. hookCount: 1,
  1290. hookInvocationId: "startup-hook",
  1291. hookRunId: "startup-run",
  1292. outcome: "success",
  1293. startedAt: 10_001,
  1294. },
  1295. "runtime-turn-compact",
  1296. ),
  1297. // compact 维护 turn:inputVisibility=model-only;durable transcript 里没有对应 user message。
  1298. event(
  1299. 3,
  1300. SessionEventType.TurnStarted,
  1301. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  1302. "runtime-turn-compact",
  1303. ),
  1304. event(
  1305. 4,
  1306. SessionEventType.CompactCompleted,
  1307. {
  1308. operationId: "op-1",
  1309. messageId: "msg-compact",
  1310. status: "completed",
  1311. trigger: "manual",
  1312. display: "separator",
  1313. },
  1314. "runtime-turn-compact",
  1315. ),
  1316. event(
  1317. 5,
  1318. SessionEventType.TurnComplete,
  1319. {
  1320. response: "compacted",
  1321. tokenCount: 1,
  1322. toolCallCount: 0,
  1323. duration: 100,
  1324. resultType: "success",
  1325. },
  1326. "runtime-turn-compact",
  1327. ),
  1328. event(6, SessionEventType.TurnStarted, { turnNumber: 2, input: "next" }, "runtime-turn-2"),
  1329. ];
  1330. const merged = mergeColdConversationEvents({
  1331. memoryEvents,
  1332. messages: [userMessage("u2", "next", 11_000, "runtime-turn-2")],
  1333. sessionId: "s1",
  1334. });
  1335. // turn-2 尚未完成:memory 事件是权威,Hook lifecycle 以 supplement 顺序进入
  1336. // ProductProjection;compact 维护 turn 期间不得收口,最终归属由投影裁决。
  1337. const hookRows = reduce(merged.events)
  1338. .getSnapshot()
  1339. .rows.window.filter((row) => row.kind === "hookInvocation");
  1340. expect(hookRows).toHaveLength(1);
  1341. expect(hookRows[0]).toMatchObject({
  1342. hookEventName: "SessionStart",
  1343. turnId: "runtime-turn-2",
  1344. executions: [expect.objectContaining({ didExecute: true })],
  1345. });
  1346. // compact 维护 turn 上没有任何 Hook row。
  1347. expect(hookRows.map((row) => row.turnId)).not.toContain("runtime-turn-compact");
  1348. });
  1349. it("keeps the edit lock of a pending queue item and drops it once the item is discarded", () => {
  1350. // 冷合并只读当前进程的内存事件,与 runtime 锁表同源;项出队后锁事件随之丢弃,
  1351. // 不能让已结算项的旧锁回到投影(docs/ui/composer-edit-mode.md)。
  1352. const queued = event(
  1353. 1,
  1354. SessionEventType.TurnSteerQueued,
  1355. {
  1356. pendingInputId: "queue-locked",
  1357. input: "edit me",
  1358. inputPreview: "edit me",
  1359. inputSize: 7,
  1360. targetTurnId: "turn-live",
  1361. queueLength: 1,
  1362. delivery: "queue",
  1363. },
  1364. "turn-live",
  1365. );
  1366. const locked = event(2, SessionEventType.TurnSteerEditLockChanged, {
  1367. pendingInputId: "queue-locked",
  1368. targetTurnId: "turn-live",
  1369. editLock: { editorId: "editor-a", clientId: "desktop" },
  1370. });
  1371. const discarded = event(3, SessionEventType.TurnSteerDiscarded, {
  1372. pendingInputIds: ["queue-locked"],
  1373. reason: "session_resumed",
  1374. targetTurnId: "turn-live",
  1375. });
  1376. const pending = mergeColdConversationEvents({
  1377. memoryEvents: [queued, locked],
  1378. messages: [],
  1379. sessionId: "s1",
  1380. });
  1381. expect(reduce(pending.events).getSnapshot().queue.items).toMatchObject([
  1382. { queueItemId: "queue-locked", editLock: { editorId: "editor-a", clientId: "desktop" } },
  1383. ]);
  1384. const settled = mergeColdConversationEvents({
  1385. memoryEvents: [queued, locked, discarded],
  1386. messages: [],
  1387. sessionId: "s1",
  1388. });
  1389. expect(reduce(settled.events).getSnapshot().queue.items).toEqual([]);
  1390. expect(
  1391. settled.events.some((item) => item.type === SessionEventType.TurnSteerEditLockChanged),
  1392. ).toBe(false);
  1393. });
  1394. it("treats SessionInputPromoted as a known queue terminal during cold merge", () => {
  1395. const queued = event(
  1396. 1,
  1397. SessionEventType.TurnSteerQueued,
  1398. {
  1399. pendingInputId: "queue-promoted",
  1400. input: "send now",
  1401. inputPreview: "send now",
  1402. inputSize: 8,
  1403. targetTurnId: "turn-live",
  1404. queueLength: 1,
  1405. delivery: "queue",
  1406. },
  1407. "turn-live",
  1408. );
  1409. const promoted = event(2, SessionEventType.SessionInputPromoted, {
  1410. pendingInputId: "queue-promoted",
  1411. sourceCommandId: "command-promoted",
  1412. messageId: "message-promoted",
  1413. });
  1414. const merged = mergeColdConversationEvents({
  1415. memoryEvents: [queued, promoted],
  1416. messages: [],
  1417. sessionId: "s1",
  1418. });
  1419. const snapshot = reduce(merged.events).getSnapshot();
  1420. expect(snapshot.queue.items).toEqual([]);
  1421. expect(
  1422. merged.diagnostics.some(
  1423. (diagnostic) => diagnostic.code === "cold_merge.unclassified_event_preserved",
  1424. ),
  1425. ).toBe(false);
  1426. expect(
  1427. merged.events.some(
  1428. (item) =>
  1429. item.type === SessionEventType.TurnSteerQueued ||
  1430. item.type === SessionEventType.SessionInputPromoted,
  1431. ),
  1432. ).toBe(false);
  1433. });
  1434. });