cold-event-merge.test.ts 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  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 loadPersistedConversationMaterialization = (coldEventMerge as Record<string, unknown>)
  479. .loadPersistedConversationMaterialization;
  480. expect(loadPersistedConversationMaterialization).toBeTypeOf("function");
  481. if (typeof loadPersistedConversationMaterialization !== "function") return;
  482. const loaded = await loadPersistedConversationMaterialization({
  483. memoryEvents: [],
  484. sessionId: "s1",
  485. store: { getSession, messages, readTarget, sessionEntries },
  486. });
  487. expect(loaded.messages.map((message: MessageWithParts) => String(message.info.id))).toEqual([
  488. "u-rewind",
  489. "a-new",
  490. ]);
  491. expect(loaded.target).toEqual(target);
  492. expect(getSession).toHaveBeenCalledWith("s1");
  493. expect(readTarget).toHaveBeenCalledWith({ sessionID: "s1" });
  494. });
  495. it("识别 shared_context transcript 并带出导入会话标题", async () => {
  496. const context = userMessage("shared-context", "# imported", 1_000, "shared-context-turn");
  497. context.info.synthetic = true;
  498. context.info.source = "shared_context";
  499. context.info.visibility = "model-only";
  500. context.info.semantics = {
  501. origin: "import",
  502. kind: "shared_context",
  503. source: "conversation_share",
  504. uiVisibility: "hidden",
  505. providerVisibility: "visible",
  506. transcriptVisibility: "visible",
  507. };
  508. const loaded = await loadPersistedConversationMaterialization({
  509. memoryEvents: [],
  510. sessionId: "s1",
  511. store: {
  512. getSession: async () => ({ title: "导入的分享标题" }),
  513. messages: async () => [context],
  514. readTarget: async () => null,
  515. },
  516. });
  517. // 分享导入已使用统一 metadata;冷恢复仍须保留标题,不能要求废弃的平铺字段。
  518. expect(loaded.sharedContextImport).toEqual({ title: "导入的分享标题" });
  519. });
  520. it("keeps an explicitly persisted null target as durable authority", async () => {
  521. const loaded = await loadPersistedConversationMaterialization({
  522. memoryEvents: [],
  523. sessionId: "s1",
  524. store: {
  525. getSession: async () => null,
  526. messages: async () => [],
  527. readTarget: async () => null,
  528. },
  529. });
  530. expect(Object.prototype.hasOwnProperty.call(loaded, "target")).toBe(true);
  531. expect(loaded.target).toBeNull();
  532. const merged = mergeColdConversationEvents({
  533. memoryEvents: [
  534. event(1, SessionEventType.TargetChanged, {
  535. action: "set",
  536. source: "runtime",
  537. target: {
  538. sessionID: "s1",
  539. targetID: "stale",
  540. objective: "stale memory target",
  541. summaryTitle: null,
  542. status: "active",
  543. tokenBudget: null,
  544. tokensUsed: 0,
  545. timeUsedSeconds: 0,
  546. time: { created: 1, updated: 2 },
  547. },
  548. }),
  549. ],
  550. messages: [],
  551. sessionId: "s1",
  552. target: loaded.target,
  553. });
  554. expect(reduce(merged.events).getSnapshot().goal).toBeNull();
  555. expect(merged.usedDurableTranscript).toBe(true);
  556. });
  557. it("materializes the persisted cold goal before verifier lifecycle", () => {
  558. const target = {
  559. sessionID: "s1",
  560. targetID: "target-1",
  561. objective: "ship the fix",
  562. summaryTitle: null,
  563. status: "paused",
  564. tokenBudget: null,
  565. tokensUsed: 7,
  566. timeUsedSeconds: 3,
  567. time: { created: 1, updated: 2 },
  568. };
  569. const merged = mergeColdConversationEvents({
  570. memoryEvents: [
  571. event(1, SessionEventType.TargetChanged, {
  572. action: "set",
  573. source: "runtime",
  574. target: { ...target, objective: "stale memory goal", status: "active" },
  575. }),
  576. ],
  577. messages: [],
  578. sessionId: "s1",
  579. target,
  580. } as Parameters<typeof mergeColdConversationEvents>[0]);
  581. expect(reduce(merged.events).getSnapshot().goal).toMatchObject({
  582. objective: "ship the fix",
  583. status: "paused",
  584. });
  585. expect(merged.usedDurableTranscript).toBe(true);
  586. });
  587. it("uses transcript as completed正文 authority while retaining queue-only memory state", () => {
  588. const messages = [
  589. userMessage("u1", "question", 1_000, "turn-1"),
  590. assistantMessage("a1", "u1", "durable answer", 1_100, "turn-1"),
  591. ];
  592. const memoryEvents = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  593. memoryEvents.push(
  594. event(
  595. memoryEvents.length + 1,
  596. SessionEventType.TurnSteerQueued,
  597. {
  598. pendingInputId: "queue-1",
  599. input: "follow up",
  600. inputPreview: "follow up",
  601. inputSize: 9,
  602. targetTurnId: "turn-live",
  603. queueLength: 1,
  604. delivery: "queue",
  605. },
  606. "turn-live",
  607. ),
  608. );
  609. const merged = mergeColdConversationEvents({
  610. memoryEvents,
  611. messages,
  612. sessionId: "s1",
  613. });
  614. const snapshot = reduce(merged.events).getSnapshot();
  615. expect(
  616. snapshot.rows.window
  617. .filter((row) => row.kind === "assistantText")
  618. .map((row) => (row.kind === "assistantText" ? row.text : "")),
  619. ).toEqual(["durable answer"]);
  620. expect(snapshot.queue.items.map((item) => item.queueItemId)).toEqual(["queue-1"]);
  621. expect(merged.events.map((item) => item.sequenceNumber)).toEqual(
  622. merged.events.map((_, index) => index + 1),
  623. );
  624. expect(merged.diagnostics).toEqual(
  625. expect.arrayContaining([
  626. expect.objectContaining({ code: "cold_merge.durable_event_suppressed" }),
  627. ]),
  628. );
  629. });
  630. it("keeps the whole unfinished memory turn after durable completed history", () => {
  631. const messages = [
  632. userMessage("u1", "question", 1_000, "turn-1"),
  633. assistantMessage("a1", "u1", "answer", 1_100, "turn-1"),
  634. ];
  635. const completedMemory = synthesizeEventsFromMessages(messages, { sessionId: "s1" });
  636. const next = completedMemory.length + 1;
  637. const memoryEvents = [
  638. ...completedMemory,
  639. event(
  640. next,
  641. SessionEventType.TurnStarted,
  642. { turnNumber: 2, input: "live question", messageId: "u2-live" },
  643. "turn-2",
  644. ),
  645. event(
  646. next + 1,
  647. SessionEventType.ModelStreaming,
  648. {
  649. assistantMessageId: "a2-live",
  650. delta: "",
  651. done: false,
  652. kind: "text_start",
  653. },
  654. "turn-2",
  655. ),
  656. event(
  657. next + 2,
  658. SessionEventType.ModelStreaming,
  659. {
  660. assistantMessageId: "a2-live",
  661. delta: "partial",
  662. done: false,
  663. kind: "text_delta",
  664. },
  665. "turn-2",
  666. ),
  667. ];
  668. const merged = mergeColdConversationEvents({
  669. memoryEvents,
  670. messages,
  671. sessionId: "s1",
  672. });
  673. const snapshot = reduce(merged.events).getSnapshot();
  674. const assistantRows = snapshot.rows.window.filter((row) => row.kind === "assistantText");
  675. expect(assistantRows.map((row) => (row.kind === "assistantText" ? row.text : ""))).toEqual([
  676. "answer",
  677. "partial",
  678. ]);
  679. expect(assistantRows.at(-1)).toEqual(expect.objectContaining({ state: "streaming" }));
  680. expect(snapshot.control.phase).toBe("running");
  681. });
  682. it("never deduplicates an unanchored legacy turn by equal input text", () => {
  683. const messages = [
  684. userMessage("u1", "same question", 1_000, "turn-1"),
  685. assistantMessage("a1", "u1", "first answer", 1_100, "turn-1"),
  686. ];
  687. const memoryEvents = [
  688. event(1, SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 }),
  689. // legacy TurnStarted: 文本与 durable u1 相同,但无 messageId/turn anchor,
  690. // 它可能是另一次真实提交,不得按文本查重。
  691. event(2, SessionEventType.TurnStarted, { turnNumber: 2, input: "same question" }, "legacy-2"),
  692. event(
  693. 3,
  694. SessionEventType.TurnComplete,
  695. {
  696. response: "",
  697. tokenCount: 0,
  698. toolCallCount: 0,
  699. duration: 1,
  700. resultType: "success",
  701. },
  702. "legacy-2",
  703. ),
  704. ];
  705. const merged = mergeColdConversationEvents({ memoryEvents, messages, sessionId: "s1" });
  706. const userRows = reduce(merged.events)
  707. .getSnapshot()
  708. .rows.window.filter((row) => row.kind === "userInput");
  709. expect(userRows.map((row) => (row.kind === "userInput" ? row.text : ""))).toEqual([
  710. "same question",
  711. "same question",
  712. ]);
  713. expect(merged.diagnostics).toEqual(
  714. expect.arrayContaining([
  715. expect.objectContaining({ code: "cold_merge.ambiguous_legacy_turn_preserved", count: 1 }),
  716. ]),
  717. );
  718. });
  719. it("deduplicates a goal boundary only when session_entry or timeline part really exists", () => {
  720. const messages = [
  721. userMessage("u1", "question", 1_000, "turn-1"),
  722. assistantMessage("a1", "u1", "answer", 1_100, "turn-1"),
  723. ];
  724. const memoryGoal = event(
  725. 1,
  726. SessionEventType.TargetCompletionVerification,
  727. {
  728. targetId: "target-1",
  729. goalIteration: 1,
  730. verificationId: "verify-1",
  731. status: "completed",
  732. },
  733. "turn-1",
  734. );
  735. const goalVerificationEntries = [
  736. {
  737. payload: {
  738. targetId: "target-1",
  739. goalIteration: 1,
  740. verificationId: "verify-1",
  741. status: "completed",
  742. anchorAssistantMessageId: "a1",
  743. },
  744. sequenceNumber: 1,
  745. timeCreated: 1_200,
  746. },
  747. ];
  748. const withDurableBoundary = mergeColdConversationEvents({
  749. memoryEvents: [memoryGoal],
  750. messages,
  751. sessionId: "s1",
  752. goalVerificationEntries,
  753. });
  754. const withoutDurableBoundary = mergeColdConversationEvents({
  755. memoryEvents: [memoryGoal],
  756. messages,
  757. sessionId: "s1",
  758. });
  759. const markerCount = (events: readonly SessionEvent[]) =>
  760. reduce(events)
  761. .getSnapshot()
  762. .rows.window.filter(
  763. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  764. ).length;
  765. expect(markerCount(withDurableBoundary.events)).toBe(1);
  766. expect(markerCount(withoutDurableBoundary.events)).toBe(1);
  767. expect(withoutDurableBoundary.diagnostics).toEqual(
  768. expect.arrayContaining([
  769. expect.objectContaining({ code: "cold_merge.memory_boundary_preserved", count: 1 }),
  770. ]),
  771. );
  772. });
  773. it("replays the full lifecycle of a still-pending edited queue item", () => {
  774. const initial = event(
  775. 1,
  776. SessionEventType.TurnSteerQueued,
  777. {
  778. pendingInputId: "queue-edit",
  779. input: "original",
  780. inputPreview: "original",
  781. inputSize: 8,
  782. targetTurnId: "turn-live",
  783. queueLength: 1,
  784. delivery: "guide",
  785. intent: {
  786. sourceCommandId: "cmd-mobile-1",
  787. queueItemId: "queue-edit",
  788. clientId: "mobile-client",
  789. kind: "sendText",
  790. admissionSeq: 7,
  791. admittedAt: 12_345,
  792. requestedDelivery: "guide",
  793. admittedDelivery: "guide",
  794. queuePosition: 0,
  795. attachmentRefs: [
  796. {
  797. ref: "artifact://attachment-1",
  798. fileName: "note.txt",
  799. mime: "text/plain",
  800. bytes: 12,
  801. },
  802. ],
  803. },
  804. },
  805. "turn-live",
  806. );
  807. const legacyEdit = event(
  808. 2,
  809. SessionEventType.TurnSteerQueued,
  810. {
  811. pendingInputId: "queue-edit",
  812. input: "edited",
  813. inputPreview: "edited",
  814. inputSize: 6,
  815. targetTurnId: "turn-live",
  816. queueLength: 1,
  817. },
  818. "turn-live",
  819. );
  820. const deliveryChanged = event(
  821. 3,
  822. SessionEventType.TurnSteerDeliveryChanged,
  823. {
  824. pendingInputId: "queue-edit",
  825. targetTurnId: "turn-live",
  826. requestedDelivery: "guide",
  827. admittedDelivery: "queue",
  828. fallbackReasonCode: "guide.noToolBoundary",
  829. },
  830. "turn-live",
  831. );
  832. const merged = mergeColdConversationEvents({
  833. memoryEvents: [initial, legacyEdit, deliveryChanged],
  834. messages: [],
  835. sessionId: "s1",
  836. });
  837. const item = reduce(merged.events).getSnapshot().queue.items[0];
  838. expect(item).toEqual(
  839. expect.objectContaining({
  840. queueItemId: "queue-edit",
  841. text: "edited",
  842. sourceCommandId: "cmd-mobile-1",
  843. clientId: "mobile-client",
  844. attachments: [
  845. expect.objectContaining({ ref: "artifact://attachment-1", fileName: "note.txt" }),
  846. ],
  847. delivery: {
  848. requested: "guide",
  849. admitted: "queue",
  850. fallbackReasonCode: "guide.noToolBoundary",
  851. },
  852. order: { admissionSeq: 7, queuePosition: 0 },
  853. admittedAt: 12_345,
  854. }),
  855. );
  856. });
  857. it("inserts an anchored memory boundary at its durable product-turn tail", () => {
  858. const messages = [
  859. userMessage("u1", "first question", 1_000, "runtime-turn-1"),
  860. assistantMessage("a1", "u1", "first answer", 1_100, "runtime-turn-1"),
  861. userMessage("u2", "second question", 2_000, "runtime-turn-2"),
  862. assistantMessage("a2", "u2", "second answer", 2_100, "runtime-turn-2"),
  863. ];
  864. const unfinishedStart = event(
  865. 1,
  866. SessionEventType.TurnStarted,
  867. { turnNumber: 3, input: "live third question", messageId: "u3-live" },
  868. "runtime-turn-3",
  869. );
  870. const anchoredBoundary = event(
  871. 2,
  872. SessionEventType.TargetCompletionVerification,
  873. {
  874. targetId: "target-1",
  875. goalIteration: 1,
  876. verificationId: "verify-1",
  877. status: "completed",
  878. verification: { passed: true, reason: "done" },
  879. anchorAssistantMessageId: "a1",
  880. },
  881. "runtime-turn-3",
  882. );
  883. const unfinishedStream = event(
  884. 3,
  885. SessionEventType.ModelStreaming,
  886. {
  887. assistantMessageId: "a3-live",
  888. delta: "partial third answer",
  889. done: false,
  890. kind: "text_delta",
  891. },
  892. "runtime-turn-3",
  893. );
  894. const merged = mergeColdConversationEvents({
  895. memoryEvents: [unfinishedStart, anchoredBoundary, unfinishedStream],
  896. messages,
  897. sessionId: "s1",
  898. });
  899. const rows = reduce(merged.events).getSnapshot().rows.window;
  900. const firstAnswerIndex = rows.findIndex(
  901. (row) => row.kind === "assistantText" && row.text === "first answer",
  902. );
  903. const markerIndex = rows.findIndex(
  904. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  905. );
  906. const secondQuestionIndex = rows.findIndex(
  907. (row) => row.kind === "userInput" && row.text === "second question",
  908. );
  909. expect(firstAnswerIndex).toBeGreaterThanOrEqual(0);
  910. expect(markerIndex).toBeGreaterThan(firstAnswerIndex);
  911. expect(markerIndex).toBeLessThan(secondQuestionIndex);
  912. expect(rows[markerIndex]?.turnId).toBe(rows[firstAnswerIndex]?.turnId);
  913. expect(rows[markerIndex]?.turnId).not.toBe(rows[secondQuestionIndex]?.turnId);
  914. const unfinishedStartIndex = merged.events.findIndex(
  915. (item) => item.type === SessionEventType.TurnStarted && item.turnId === "runtime-turn-3",
  916. );
  917. const secondDurableStartIndex = merged.events.findIndex(
  918. (item) =>
  919. item.type === SessionEventType.TurnStarted &&
  920. (item.payload as { messageId?: string }).messageId === "u2",
  921. );
  922. const unfinishedStreamIndex = merged.events.findIndex(
  923. (item) => item.type === SessionEventType.ModelStreaming && item.turnId === "runtime-turn-3",
  924. );
  925. expect(unfinishedStartIndex).toBeGreaterThan(secondDurableStartIndex);
  926. expect(unfinishedStreamIndex).toBeGreaterThan(unfinishedStartIndex);
  927. });
  928. it("HK10 preserves Hook lifecycle and anchors resume SessionStart to the next durable turn", () => {
  929. const descriptor = {
  930. clientVisible: true,
  931. sourceKind: "user",
  932. sourcePath: "/Users/example/.zcode/cli/config.json",
  933. executionType: "process",
  934. executionMode: "foreground",
  935. commandDisplay: 'echo ""',
  936. timeoutMs: 5_000,
  937. };
  938. const hookEvents = [
  939. event(
  940. 1,
  941. SessionEventType.HookRunStarted,
  942. {
  943. descriptor,
  944. hookEventName: "SessionStart",
  945. hookIndex: 0,
  946. hookCount: 1,
  947. hookInvocationId: "startup-hook",
  948. hookRunId: "startup-run",
  949. startedAt: 10_001,
  950. },
  951. "runtime-turn-before-product-mapping",
  952. ),
  953. event(
  954. 2,
  955. SessionEventType.HookRunCompleted,
  956. {
  957. descriptor,
  958. durationMs: 1,
  959. hookEventName: "SessionStart",
  960. hookIndex: 0,
  961. hookCount: 1,
  962. hookInvocationId: "startup-hook",
  963. hookRunId: "startup-run",
  964. outcome: "success",
  965. startedAt: 10_001,
  966. },
  967. "runtime-turn-before-product-mapping",
  968. ),
  969. event(3, SessionEventType.TurnStarted, { turnNumber: 2, input: "next" }, "runtime-turn-2"),
  970. event(
  971. 4,
  972. SessionEventType.HookRunStarted,
  973. {
  974. descriptor,
  975. hookEventName: "PreToolUse",
  976. hookIndex: 0,
  977. hookCount: 1,
  978. hookInvocationId: "tool-hook",
  979. hookRunId: "tool-run",
  980. startedAt: 10_004,
  981. toolCallId: "tool-1",
  982. toolName: "Write",
  983. },
  984. "runtime-turn-2",
  985. ),
  986. event(
  987. 5,
  988. SessionEventType.HookRunCompleted,
  989. {
  990. descriptor,
  991. durationMs: 1,
  992. hookEventName: "PreToolUse",
  993. hookIndex: 0,
  994. hookCount: 1,
  995. hookInvocationId: "tool-hook",
  996. hookRunId: "tool-run",
  997. outcome: "success",
  998. startedAt: 10_004,
  999. toolCallId: "tool-1",
  1000. toolName: "Write",
  1001. },
  1002. "runtime-turn-2",
  1003. ),
  1004. event(6, SessionEventType.HookRunProgress, { hookRunId: "progress-run" }),
  1005. event(7, SessionEventType.HookRunFailed, { hookRunId: "failed-run" }),
  1006. event(8, SessionEventType.HookRunBlocked, { hookRunId: "blocked-run" }),
  1007. ];
  1008. const merged = mergeColdConversationEvents({
  1009. memoryEvents: hookEvents,
  1010. messages: [
  1011. userMessage("u1", "run", 1_000, "runtime-turn-1"),
  1012. assistantMessage("a1", "u1", "done", 1_100, "runtime-turn-1"),
  1013. userMessage("u2", "next", 11_000, "runtime-turn-2"),
  1014. assistantMessage("a2", "u2", "next done", 11_100, "runtime-turn-2"),
  1015. ],
  1016. sessionId: "s1",
  1017. });
  1018. const snapshot = reduce(merged.events).getSnapshot();
  1019. const hookEventTypes = new Set([
  1020. SessionEventType.HookRunStarted,
  1021. SessionEventType.HookRunProgress,
  1022. SessionEventType.HookRunCompleted,
  1023. SessionEventType.HookRunFailed,
  1024. SessionEventType.HookRunBlocked,
  1025. ]);
  1026. expect(merged.events.filter((item) => hookEventTypes.has(item.type))).toHaveLength(7);
  1027. expect(
  1028. merged.diagnostics.find(
  1029. (diagnostic) => String(diagnostic.code) === "cold_merge.non_product_event_suppressed",
  1030. ),
  1031. ).toBeUndefined();
  1032. expect(
  1033. merged.diagnostics.some(
  1034. (diagnostic) => diagnostic.code === "cold_merge.unclassified_event_preserved",
  1035. ),
  1036. ).toBe(false);
  1037. const hookRows = snapshot.rows.window.filter((row) => row.kind === "hookInvocation");
  1038. expect(hookRows).toHaveLength(2);
  1039. expect(hookRows.map((row) => row.turnId)).toEqual(["runtime-turn-2", "runtime-turn-2"]);
  1040. expect(snapshot.rows.window.map((row) => row.turnId)).not.toContain("session-hooks:s1");
  1041. });
  1042. it("HK10 maps completed Hook runtime turns through durable anchors during cold recovery", () => {
  1043. const descriptor = {
  1044. clientVisible: true,
  1045. sourceKind: "user",
  1046. sourcePath: "/Users/example/.zcode/cli/config.json",
  1047. executionType: "process",
  1048. executionMode: "foreground",
  1049. commandDisplay: 'echo ""',
  1050. timeoutMs: 5_000,
  1051. };
  1052. const lifecycle = (
  1053. sequenceNumber: number,
  1054. hookEventName: "SessionStart" | "UserPromptSubmit" | "PreToolUse",
  1055. hookInvocationId: string,
  1056. runtimeTurnId: string,
  1057. ) => [
  1058. event(
  1059. sequenceNumber,
  1060. SessionEventType.HookRunStarted,
  1061. {
  1062. descriptor,
  1063. hookEventName,
  1064. hookIndex: 0,
  1065. hookCount: 1,
  1066. hookInvocationId,
  1067. hookRunId: `${hookInvocationId}-run`,
  1068. startedAt: 10_000 + sequenceNumber,
  1069. },
  1070. runtimeTurnId,
  1071. ),
  1072. event(
  1073. sequenceNumber + 1,
  1074. SessionEventType.HookRunCompleted,
  1075. {
  1076. descriptor,
  1077. durationMs: 1,
  1078. hookEventName,
  1079. hookIndex: 0,
  1080. hookCount: 1,
  1081. hookInvocationId,
  1082. hookRunId: `${hookInvocationId}-run`,
  1083. outcome: "success",
  1084. startedAt: 10_000 + sequenceNumber,
  1085. },
  1086. runtimeTurnId,
  1087. ),
  1088. ];
  1089. const memoryEvents = [
  1090. ...lifecycle(1, "SessionStart", "startup-hook", "runtime-before-first-turn"),
  1091. event(
  1092. 3,
  1093. SessionEventType.TurnStarted,
  1094. { turnNumber: 1, input: "first", messageId: "u1" },
  1095. "runtime-turn-1",
  1096. ),
  1097. ...lifecycle(4, "UserPromptSubmit", "prompt-hook", "runtime-turn-1"),
  1098. event(6, SessionEventType.TurnComplete, { resultType: "success" }, "runtime-turn-1"),
  1099. event(
  1100. 7,
  1101. SessionEventType.TurnStarted,
  1102. { turnNumber: 2, input: "second", messageId: "u2" },
  1103. "runtime-turn-2",
  1104. ),
  1105. ...lifecycle(8, "PreToolUse", "tool-hook", "runtime-turn-2"),
  1106. event(10, SessionEventType.TurnComplete, { resultType: "success" }, "runtime-turn-2"),
  1107. ];
  1108. const merged = mergeColdConversationEvents({
  1109. memoryEvents,
  1110. messages: [
  1111. userMessage("u1", "first", 1_000, "runtime-turn-1"),
  1112. assistantMessage("a1", "u1", "first done", 1_100, "runtime-turn-1"),
  1113. userMessage("u2", "second", 2_000, "runtime-turn-2"),
  1114. assistantMessage("a2", "u2", "second done", 2_100, "runtime-turn-2"),
  1115. ],
  1116. sessionId: "s1",
  1117. });
  1118. const hookEvents = merged.events.filter((item) =>
  1119. HOOK_LIFECYCLE_EVENT_TYPES_FOR_TEST.has(item.type),
  1120. );
  1121. expect(
  1122. hookEvents
  1123. .filter((item) => item.type === SessionEventType.HookRunStarted)
  1124. .map((item) => item.turnId),
  1125. ).toEqual(["hydrate-turn-1", "hydrate-turn-1", "hydrate-turn-2"]);
  1126. const hookRows = reduce(merged.events)
  1127. .getSnapshot()
  1128. .rows.window.filter((row) => row.kind === "hookInvocation");
  1129. expect(hookRows.map((row) => [row.hookEventName, row.turnId])).toEqual([
  1130. ["SessionStart", "u1"],
  1131. ["UserPromptSubmit", "u1"],
  1132. ["PreToolUse", "u2"],
  1133. ]);
  1134. expect(hookRows.map((row) => row.turnId)).not.toContain("runtime-turn-1");
  1135. expect(hookRows.map((row) => row.turnId)).not.toContain("runtime-turn-2");
  1136. });
  1137. it("HK10 keeps Hook invocations on queue-drained product turns sharing one runtime anchor", () => {
  1138. const descriptor = {
  1139. clientVisible: true,
  1140. sourceKind: "user",
  1141. sourcePath: "/Users/example/.zcode/cli/config.json",
  1142. executionType: "process",
  1143. executionMode: "foreground",
  1144. commandDisplay: 'echo ""',
  1145. timeoutMs: 5_000,
  1146. };
  1147. const lifecycle = (sequenceNumber: number, hookInvocationId: string, runtimeTurnId: string) => [
  1148. event(
  1149. sequenceNumber,
  1150. SessionEventType.HookRunStarted,
  1151. {
  1152. descriptor,
  1153. hookEventName: "UserPromptSubmit",
  1154. hookIndex: 0,
  1155. hookCount: 1,
  1156. hookInvocationId,
  1157. hookRunId: `${hookInvocationId}-run`,
  1158. startedAt: 10_000 + sequenceNumber,
  1159. },
  1160. runtimeTurnId,
  1161. ),
  1162. event(
  1163. sequenceNumber + 1,
  1164. SessionEventType.HookRunCompleted,
  1165. {
  1166. descriptor,
  1167. durationMs: 1,
  1168. hookEventName: "UserPromptSubmit",
  1169. hookIndex: 0,
  1170. hookCount: 1,
  1171. hookInvocationId,
  1172. hookRunId: `${hookInvocationId}-run`,
  1173. outcome: "success",
  1174. startedAt: 10_000 + sequenceNumber,
  1175. },
  1176. runtimeTurnId,
  1177. ),
  1178. ];
  1179. const runtimeTurnId = "runtime-turn-shared";
  1180. const [firstStarted, firstCompleted] = lifecycle(2, "first-prompt-hook", runtimeTurnId);
  1181. const memoryEvents = [
  1182. event(
  1183. 1,
  1184. SessionEventType.TurnStarted,
  1185. { turnNumber: 1, input: "first", messageId: "u1" },
  1186. runtimeTurnId,
  1187. ),
  1188. firstStarted!,
  1189. event(
  1190. 3,
  1191. SessionEventType.TurnSteerDrained,
  1192. {
  1193. pendingInputIds: ["queue-2"],
  1194. injectedMessageIds: ["u2"],
  1195. drainedInputs: [
  1196. {
  1197. delivery: "queue",
  1198. messageId: "u2",
  1199. pendingInputId: "queue-2",
  1200. text: "second",
  1201. },
  1202. ],
  1203. targetTurnId: runtimeTurnId,
  1204. },
  1205. runtimeTurnId,
  1206. ),
  1207. event(
  1208. 4,
  1209. SessionEventType.SessionInputPromoted,
  1210. {
  1211. pendingInputId: "queue-2",
  1212. sourceCommandId: "command-2",
  1213. messageId: "u2",
  1214. },
  1215. runtimeTurnId,
  1216. ),
  1217. { ...firstCompleted!, sequenceNumber: 5 },
  1218. ...lifecycle(6, "second-prompt-hook", runtimeTurnId),
  1219. event(
  1220. 8,
  1221. SessionEventType.TurnComplete,
  1222. {
  1223. response: "",
  1224. tokenCount: 0,
  1225. toolCallCount: 0,
  1226. duration: 10,
  1227. resultType: "success",
  1228. },
  1229. runtimeTurnId,
  1230. ),
  1231. ];
  1232. const merged = mergeColdConversationEvents({
  1233. memoryEvents,
  1234. messages: [
  1235. userMessage("u1", "first", 1_000, runtimeTurnId),
  1236. assistantMessage("a1", "u1", "first done", 1_100, runtimeTurnId),
  1237. userMessage("u2", "second", 2_000, runtimeTurnId),
  1238. assistantMessage("a2", "u2", "second done", 2_100, runtimeTurnId),
  1239. ],
  1240. sessionId: "s1",
  1241. });
  1242. expect(
  1243. merged.events
  1244. .filter((item) => item.type === SessionEventType.HookRunStarted)
  1245. .map((item) => item.turnId),
  1246. ).toEqual(["hydrate-turn-1", "hydrate-turn-2"]);
  1247. const hookRows = reduce(merged.events)
  1248. .getSnapshot()
  1249. .rows.window.filter((row) => row.kind === "hookInvocation");
  1250. expect(hookRows.map((row) => [row.hookInvocationId, row.turnId])).toEqual([
  1251. ["first-prompt-hook", "u1"],
  1252. ["second-prompt-hook", "u2"],
  1253. ]);
  1254. expect(hookRows.map((row) => row.turnId)).not.toContain(runtimeTurnId);
  1255. });
  1256. it("HK17 does not anchor a SessionStart summary onto a model-only compact turn during cold merge", () => {
  1257. // Bug 根因:首条输入即 /compact 时,SessionStart Hook 真实执行且事件携带 compact 的
  1258. // runtime turnId。cold 归属把 pending SessionStart 绑到「下一个 TurnStarted」;compact
  1259. // 维护 turn 也是 TurnStarted(inputVisibility=model-only),旧逻辑会把摘要错误归位到
  1260. // compact marker 轮。维护 turn 没有资格承载摘要,必须跳过等下一条真实 turn。
  1261. const descriptor = {
  1262. clientVisible: true,
  1263. sourceKind: "user",
  1264. sourcePath: "/Users/example/.zcode/cli/config.json",
  1265. executionType: "process",
  1266. executionMode: "foreground",
  1267. commandDisplay: 'echo ""',
  1268. timeoutMs: 5_000,
  1269. };
  1270. const memoryEvents = [
  1271. event(
  1272. 1,
  1273. SessionEventType.HookRunStarted,
  1274. {
  1275. descriptor,
  1276. hookEventName: "SessionStart",
  1277. hookIndex: 0,
  1278. hookCount: 1,
  1279. hookInvocationId: "startup-hook",
  1280. hookRunId: "startup-run",
  1281. startedAt: 10_001,
  1282. },
  1283. "runtime-turn-compact",
  1284. ),
  1285. event(
  1286. 2,
  1287. SessionEventType.HookRunCompleted,
  1288. {
  1289. descriptor,
  1290. durationMs: 1,
  1291. hookEventName: "SessionStart",
  1292. hookIndex: 0,
  1293. hookCount: 1,
  1294. hookInvocationId: "startup-hook",
  1295. hookRunId: "startup-run",
  1296. outcome: "success",
  1297. startedAt: 10_001,
  1298. },
  1299. "runtime-turn-compact",
  1300. ),
  1301. // compact 维护 turn:inputVisibility=model-only;durable transcript 里没有对应 user message。
  1302. event(
  1303. 3,
  1304. SessionEventType.TurnStarted,
  1305. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  1306. "runtime-turn-compact",
  1307. ),
  1308. event(
  1309. 4,
  1310. SessionEventType.CompactCompleted,
  1311. {
  1312. operationId: "op-1",
  1313. messageId: "msg-compact",
  1314. status: "completed",
  1315. trigger: "manual",
  1316. display: "separator",
  1317. },
  1318. "runtime-turn-compact",
  1319. ),
  1320. event(
  1321. 5,
  1322. SessionEventType.TurnComplete,
  1323. {
  1324. response: "compacted",
  1325. tokenCount: 1,
  1326. toolCallCount: 0,
  1327. duration: 100,
  1328. resultType: "success",
  1329. },
  1330. "runtime-turn-compact",
  1331. ),
  1332. event(6, SessionEventType.TurnStarted, { turnNumber: 2, input: "next" }, "runtime-turn-2"),
  1333. ];
  1334. const merged = mergeColdConversationEvents({
  1335. memoryEvents,
  1336. messages: [userMessage("u2", "next", 11_000, "runtime-turn-2")],
  1337. sessionId: "s1",
  1338. });
  1339. // turn-2 尚未完成:memory 事件是权威,Hook lifecycle 以 supplement 顺序进入
  1340. // ProductProjection;compact 维护 turn 期间不得收口,最终归属由投影裁决。
  1341. const hookRows = reduce(merged.events)
  1342. .getSnapshot()
  1343. .rows.window.filter((row) => row.kind === "hookInvocation");
  1344. expect(hookRows).toHaveLength(1);
  1345. expect(hookRows[0]).toMatchObject({
  1346. hookEventName: "SessionStart",
  1347. turnId: "runtime-turn-2",
  1348. executions: [expect.objectContaining({ didExecute: true })],
  1349. });
  1350. // compact 维护 turn 上没有任何 Hook row。
  1351. expect(hookRows.map((row) => row.turnId)).not.toContain("runtime-turn-compact");
  1352. });
  1353. it("treats SessionInputPromoted as a known queue terminal during cold merge", () => {
  1354. const queued = event(
  1355. 1,
  1356. SessionEventType.TurnSteerQueued,
  1357. {
  1358. pendingInputId: "queue-promoted",
  1359. input: "send now",
  1360. inputPreview: "send now",
  1361. inputSize: 8,
  1362. targetTurnId: "turn-live",
  1363. queueLength: 1,
  1364. delivery: "queue",
  1365. },
  1366. "turn-live",
  1367. );
  1368. const promoted = event(2, SessionEventType.SessionInputPromoted, {
  1369. pendingInputId: "queue-promoted",
  1370. sourceCommandId: "command-promoted",
  1371. messageId: "message-promoted",
  1372. });
  1373. const merged = mergeColdConversationEvents({
  1374. memoryEvents: [queued, promoted],
  1375. messages: [],
  1376. sessionId: "s1",
  1377. });
  1378. const snapshot = reduce(merged.events).getSnapshot();
  1379. expect(snapshot.queue.items).toEqual([]);
  1380. expect(
  1381. merged.diagnostics.some(
  1382. (diagnostic) => diagnostic.code === "cold_merge.unclassified_event_preserved",
  1383. ),
  1384. ).toBe(false);
  1385. expect(
  1386. merged.events.some(
  1387. (item) =>
  1388. item.type === SessionEventType.TurnSteerQueued ||
  1389. item.type === SessionEventType.SessionInputPromoted,
  1390. ),
  1391. ).toBe(false);
  1392. });
  1393. });