session-fork.test.ts 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126
  1. import { describe, expect, it } from "vitest";
  2. import type {
  3. SessionGoal,
  4. MessageId,
  5. MessagePart,
  6. MessageWithParts,
  7. ModelSelection,
  8. SessionEntryInfo,
  9. SessionInfo,
  10. SessionId,
  11. SessionStorePort,
  12. TraceContext,
  13. } from "@zcode/contracts";
  14. import { SESSION_ENTRY_MODEL_SELECTION } from "@zcode/contracts";
  15. import { HIGHSPEED_PROVIDER_IDS } from "@zcode/shared";
  16. import {
  17. activeSessionMessages,
  18. hydrateMessageHistoryFromSession,
  19. } from "../src/agent/session-history-hydrator.js";
  20. import { MessageHistoryImpl } from "../src/agent/message-history.js";
  21. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  22. import { cloneMessageForFork, clonePartForFork } from "../src/runtime/helpers/steering.js";
  23. import { buildRuntimeReminderMessage } from "../src/runtime/methods/runtime-reminder-persistence.js";
  24. import {
  25. activeForkTranscriptMessages,
  26. buildForkHistoryMessages,
  27. createForkedSession,
  28. copyGoalStateForFork,
  29. conversationHistoryBeforeInput,
  30. createForkIdentityMap,
  31. deriveForkedGoalStatusFromCopiedVerifications,
  32. buildAtomicForkNotice,
  33. createSelectionSideConversation,
  34. forkConversationBeforeMessage,
  35. forkStableConversationAtMessage,
  36. selectionSideChatHistoryMessages,
  37. stableForkHistoryMessages,
  38. } from "../src/runtime/methods/session-fork.js";
  39. import type {
  40. StableConversationForkChildMetadata,
  41. StableConversationForkTarget,
  42. } from "../src/runtime/types.js";
  43. const SESSION_ID = "sess_parent" as SessionId;
  44. function partId(id: string) {
  45. return `part_${id}` as MessagePart["id"];
  46. }
  47. function userMessage(id: MessageId, text: string, created: number): MessageWithParts {
  48. return {
  49. info: {
  50. id,
  51. sessionID: SESSION_ID,
  52. role: "user",
  53. time: { created },
  54. agent: "zcode-agent",
  55. modelSelection: {
  56. modelId: "glm-4-air" as never,
  57. providerId: "glm" as never,
  58. },
  59. tools: {},
  60. },
  61. parts: [
  62. {
  63. id: partId(id),
  64. sessionID: SESSION_ID,
  65. messageID: id,
  66. type: "text",
  67. text,
  68. },
  69. ],
  70. };
  71. }
  72. function compactSummaryMessage(id: MessageId, created: number): MessageWithParts {
  73. return {
  74. info: {
  75. id,
  76. sessionID: SESSION_ID,
  77. role: "user",
  78. time: { created },
  79. agent: "zcode-agent",
  80. modelSelection: {
  81. modelId: "glm-4-air" as never,
  82. providerId: "glm" as never,
  83. },
  84. summary: {
  85. body: "历史摘要",
  86. diffs: [],
  87. title: "Compact summary",
  88. },
  89. tools: {},
  90. },
  91. parts: [
  92. {
  93. id: partId(`${id}_text`),
  94. sessionID: SESSION_ID,
  95. messageID: id,
  96. type: "text",
  97. text: "compact summary context",
  98. synthetic: true,
  99. },
  100. {
  101. id: partId(`${id}_compaction`),
  102. sessionID: SESSION_ID,
  103. messageID: id,
  104. type: "compaction",
  105. auto: false,
  106. compactReason: "user_requested",
  107. operationId: "cmp_test",
  108. phase: "standalone_turn",
  109. trigger: "manual",
  110. } as MessagePart,
  111. ],
  112. };
  113. }
  114. function assistantMessage(
  115. id: MessageId,
  116. parentId: MessageId,
  117. text: string,
  118. created: number,
  119. ): MessageWithParts {
  120. return {
  121. info: {
  122. id,
  123. sessionID: SESSION_ID,
  124. role: "assistant",
  125. time: { created, completed: created + 1 },
  126. parentID: parentId,
  127. agent: "zcode-agent",
  128. cost: 0,
  129. mode: "build",
  130. modelId: "glm-4-air" as never,
  131. path: { cwd: "/tmp", root: "/tmp" },
  132. providerId: "glm" as never,
  133. tokens: {
  134. cache: { read: 0, write: 0 },
  135. input: 0,
  136. output: 0,
  137. reasoning: 0,
  138. total: 0,
  139. },
  140. },
  141. parts: [
  142. {
  143. id: partId(id),
  144. sessionID: SESSION_ID,
  145. messageID: id,
  146. type: "text",
  147. text,
  148. },
  149. ],
  150. };
  151. }
  152. function goalVerificationEntry(
  153. id: string,
  154. anchorAssistantMessageId: string,
  155. goalIteration: number,
  156. passed: boolean,
  157. ): SessionEntryInfo {
  158. return {
  159. id,
  160. sessionID: SESSION_ID,
  161. time: { created: goalIteration * 10, updated: goalIteration * 10 + 1 },
  162. type: "target_completion_verification",
  163. data: {
  164. eventId: `event_${id}`,
  165. payload: {
  166. anchorAssistantMessageId,
  167. goalIteration,
  168. status: "completed",
  169. targetId: "target_goal_1",
  170. verification: {
  171. nextAction: passed ? null : "继续",
  172. passed,
  173. reason: passed ? "done" : "not yet",
  174. },
  175. verificationId: `verify_${goalIteration}`,
  176. },
  177. sequenceNumber: goalIteration,
  178. traceId: `trace_${id}`,
  179. },
  180. };
  181. }
  182. describe("session fork history", () => {
  183. it("selection side chat 在生成中只复制稳定 user input 边界", () => {
  184. const stableUser = userMessage("msg_side_stable_user" as MessageId, "稳定问题", 1);
  185. const stableAssistant = assistantMessage(
  186. "msg_side_stable_assistant" as MessageId,
  187. stableUser.info.id,
  188. "稳定回答",
  189. 2,
  190. );
  191. const activeUser = userMessage("msg_side_active_user" as MessageId, "本轮问题", 3);
  192. activeUser.info.anchor = {
  193. turnId: "turn_side_active" as never,
  194. productTurnId: "product_side_active",
  195. orderedMessageIds: [activeUser.info.id],
  196. boundaryMessageId: activeUser.info.id,
  197. origin: "realUser",
  198. };
  199. const streamingAssistant = assistantMessage(
  200. "msg_side_streaming_assistant" as MessageId,
  201. activeUser.info.id,
  202. "流式片段",
  203. 4,
  204. );
  205. streamingAssistant.info.anchor = {
  206. ...activeUser.info.anchor,
  207. orderedMessageIds: [activeUser.info.id, streamingAssistant.info.id],
  208. boundaryMessageId: streamingAssistant.info.id,
  209. };
  210. expect(
  211. selectionSideChatHistoryMessages(
  212. [stableUser, stableAssistant, activeUser, streamingAssistant],
  213. "turn_side_active" as never,
  214. ).map((message) => message.info.id),
  215. ).toEqual([stableUser.info.id, stableAssistant.info.id, activeUser.info.id]);
  216. });
  217. it("selection side chat 原子创建隐藏 child,不复制 goal 或 fork notice", async () => {
  218. const user = userMessage("msg_side_user" as MessageId, "解释这里", 1);
  219. const assistant = assistantMessage(
  220. "msg_side_assistant" as MessageId,
  221. user.info.id,
  222. "父任务回答",
  223. 2,
  224. );
  225. const parentSession = {
  226. directory: "/workspace",
  227. id: SESSION_ID,
  228. path: "/workspace",
  229. permission: [{ permission: "bash", pattern: "*", action: "ask" }],
  230. projectID: "project-selection-side-chat",
  231. slug: "parent-selection-side-chat",
  232. taskType: "interactive",
  233. time: { created: 1, updated: 1 },
  234. title: "parent",
  235. version: "test",
  236. } as SessionInfo;
  237. let committedBundle: Parameters<NonNullable<SessionStorePort["commitForkBundle"]>>[0] | null =
  238. null;
  239. const parentEvents: unknown[] = [];
  240. const runtime = {
  241. activeTurn: null,
  242. appendEvent: async (event: unknown) => parentEvents.push(event),
  243. config: { agentName: "zcode-agent", mode: "build" },
  244. createEvent: (_type: unknown, payload: Record<string, unknown>) => ({ payload }),
  245. getSessionModelSelection: () => ({
  246. modelId: "glm-4-air",
  247. providerId: "glm",
  248. options: { reasoningLevel: "high" },
  249. }),
  250. rootTraceContext: { traceId: "trace_selection_side_chat" },
  251. sessionId: SESSION_ID,
  252. sessionStore: {
  253. async commitForkBundle(bundle) {
  254. committedBundle = bundle;
  255. return bundle.child as SessionInfo;
  256. },
  257. async getSession() {
  258. return parentSession;
  259. },
  260. async messages() {
  261. return [user, assistant];
  262. },
  263. } satisfies Partial<SessionStorePort>,
  264. workingDirectory: "/workspace",
  265. workspaceRoot: "/workspace",
  266. };
  267. const result = await createSelectionSideConversation.call(runtime as never, {
  268. sourceCommandId: "cmd-selection-side-chat",
  269. });
  270. expect(result.parentSessionId).toBe(SESSION_ID);
  271. expect(parentEvents).toEqual([]);
  272. expect(committedBundle!.child).toMatchObject({
  273. parentID: SESSION_ID,
  274. permission: parentSession.permission,
  275. taskType: "selection_side_chat",
  276. title: "Selection side chat",
  277. });
  278. expect(committedBundle!.goal).toBeUndefined();
  279. expect(committedBundle!.entries).toEqual([
  280. expect.objectContaining({
  281. sessionID: result.forkedSessionId,
  282. type: SESSION_ENTRY_MODEL_SELECTION,
  283. touchSession: false,
  284. data: {
  285. modelId: "glm-4-air",
  286. providerId: "glm",
  287. options: { reasoningLevel: "high" },
  288. },
  289. }),
  290. expect.objectContaining({
  291. type: "runtime/execution_state",
  292. data: { mode: "build", planEnabled: false },
  293. }),
  294. ]);
  295. expect(committedBundle!.commandFact.ack.result).toEqual({
  296. type: "createSelectionSideSession",
  297. sessionId: result.forkedSessionId,
  298. });
  299. expect(committedBundle!.messages).toHaveLength(3);
  300. expect(
  301. committedBundle!.messages.every(
  302. (message) =>
  303. message.info.visibility === "model-only" &&
  304. message.info.semantics?.uiVisibility === "hidden" &&
  305. message.info.semantics.providerVisibility === "visible",
  306. ),
  307. ).toBe(true);
  308. expect(committedBundle!.messages.at(-1)?.info.source).toBe("selection_side_chat");
  309. expect(JSON.stringify(committedBundle!.messages)).not.toContain("session_fork");
  310. // 直接恢复 producer 的原子 bundle,避免手写 metadata fixture 掩盖 fork 漏写字段。
  311. const persisted = JSON.parse(JSON.stringify(committedBundle!.messages)) as MessageWithParts[];
  312. const boundary = persisted.at(-1)!;
  313. expect(boundary.parts[0]).toMatchObject({
  314. type: "text",
  315. synthetic: true,
  316. metadata: {
  317. source: "selection_side_chat",
  318. runtimeMessage: { source: "selection_side_chat" },
  319. },
  320. });
  321. const boundaryText = boundary.parts[0]!.type === "text" ? boundary.parts[0]!.text : "";
  322. expect(boundaryText).toContain("Do not continue the parent's active work automatically");
  323. expect(boundaryText).not.toContain("<system-reminder>");
  324. const history = new MessageHistoryImpl();
  325. await hydrateMessageHistoryFromSession({ history, messages: persisted });
  326. expect(history.toRuntimeEntries().at(-1)).toEqual({
  327. kind: "attachment",
  328. content: boundaryText,
  329. metadata: { source: "selection_side_chat" },
  330. });
  331. history.addUser("child question", { source: "real_user" });
  332. for (const useMidConversationSystem of [true, false]) {
  333. const request = buildProviderRequestMessages({
  334. entries: history.toRuntimeEntries(),
  335. useMidConversationSystem,
  336. });
  337. expect(request.messages.slice(-2)).toEqual([
  338. { role: "user", content: `<system-reminder>\n${boundaryText}\n</system-reminder>` },
  339. { role: "user", content: "child question" },
  340. ]);
  341. expect(JSON.stringify(request.messages).split(boundaryText)).toHaveLength(2);
  342. }
  343. });
  344. const selectionSideChatGoalCases: ReadonlyArray<{
  345. label: string;
  346. passed?: boolean;
  347. status: SessionGoal["status"];
  348. }> = [
  349. { label: "active 无 verifier", status: "active" },
  350. { label: "failed verifier 后 paused", passed: false, status: "paused" },
  351. { label: "passed verifier 后 complete", passed: true, status: "complete" },
  352. ];
  353. it.each(selectionSideChatGoalCases)(
  354. "selection side chat 从 $label Goal 父任务创建时不继承 Goal 运行态",
  355. async ({ label, passed, status }) => {
  356. const user = userMessage(`msg_side_goal_user_${status}` as MessageId, "解释这里", 1);
  357. const assistant = assistantMessage(
  358. `msg_side_goal_assistant_${status}` as MessageId,
  359. user.info.id,
  360. "父任务回答",
  361. 2,
  362. );
  363. const targetId = `target_side_goal_${status}`;
  364. const verificationEntryId = `entry_side_goal_${status}`;
  365. const verificationId = `verify_side_goal_${status}`;
  366. const goal: SessionGoal = {
  367. activeInputId: status === "active" ? "input-side-goal" : null,
  368. activeRunLastSeenAtMs: status === "active" ? 2 : null,
  369. activeRunStartedAtMs: status === "active" ? 1 : null,
  370. objective: `Goal ${label}`,
  371. sessionID: SESSION_ID,
  372. status,
  373. summaryTitle: null,
  374. targetID: targetId,
  375. time: { created: 1, updated: 2 },
  376. timeUsedSeconds: 1,
  377. tokenBudget: null,
  378. tokensUsed: 1,
  379. };
  380. const anchor = {
  381. boundaryMessageId: assistant.info.id,
  382. goalBoundary: {
  383. kind: "snapshot" as const,
  384. target: goal,
  385. verificationEntryIds: passed === undefined ? [] : [verificationEntryId],
  386. },
  387. orderedMessageIds: [user.info.id, assistant.info.id],
  388. productTurnId: `product_side_goal_${status}`,
  389. turnId: `turn_side_goal_${status}` as never,
  390. };
  391. user.info.anchor = anchor;
  392. assistant.info.anchor = anchor;
  393. if (passed !== undefined) {
  394. assistant.parts.push({
  395. anchorMessageId: assistant.info.id,
  396. anchorTurnId: anchor.turnId,
  397. display: "separator",
  398. id: partId(`side_goal_timeline_${status}`),
  399. messageID: assistant.info.id,
  400. sessionID: SESSION_ID,
  401. status: "completed",
  402. targetId,
  403. timelineType: "goal_verification",
  404. type: "timeline",
  405. verificationId,
  406. } as MessagePart);
  407. }
  408. const parentSession = {
  409. directory: "/workspace",
  410. id: SESSION_ID,
  411. path: "/workspace",
  412. projectID: "project-selection-side-chat-goal",
  413. slug: `parent-selection-side-chat-${status}`,
  414. taskType: "interactive",
  415. time: { created: 1, updated: 2 },
  416. title: "parent goal",
  417. version: "test",
  418. } as SessionInfo;
  419. let sessionEntriesReadCount = 0;
  420. let committedBundle: Parameters<NonNullable<SessionStorePort["commitForkBundle"]>>[0] | null =
  421. null;
  422. const runtime = {
  423. activeTurn: null,
  424. appendEvent: async () => undefined,
  425. config: { agentName: "zcode-agent", mode: "build" },
  426. createEvent: () => ({ type: "session.forked" }),
  427. getSessionModelSelection: () => ({ modelId: "glm-4-air", providerId: "glm" }),
  428. rootTraceContext: { traceId: `trace_selection_side_chat_${status}` },
  429. sessionId: SESSION_ID,
  430. sessionStore: {
  431. async commitForkBundle(bundle) {
  432. committedBundle = bundle;
  433. return bundle.child as SessionInfo;
  434. },
  435. async getSession() {
  436. return parentSession;
  437. },
  438. async messages() {
  439. return [user, assistant];
  440. },
  441. async sessionEntries() {
  442. sessionEntriesReadCount += 1;
  443. return [];
  444. },
  445. } satisfies Partial<SessionStorePort>,
  446. workingDirectory: "/workspace",
  447. workspaceRoot: "/workspace",
  448. };
  449. await expect(
  450. createSelectionSideConversation.call(runtime as never, {
  451. sourceCommandId: `cmd-selection-side-chat-${status}`,
  452. }),
  453. ).resolves.toMatchObject({ parentSessionId: SESSION_ID });
  454. expect(sessionEntriesReadCount).toBe(0);
  455. expect(committedBundle!.goal).toBeUndefined();
  456. expect(committedBundle!.entries).toEqual([
  457. expect.objectContaining({
  458. sessionID: committedBundle!.child.id,
  459. type: SESSION_ENTRY_MODEL_SELECTION,
  460. touchSession: false,
  461. data: { modelId: "glm-4-air", providerId: "glm" },
  462. }),
  463. expect.objectContaining({
  464. type: "runtime/execution_state",
  465. data: { mode: "build", planEnabled: false },
  466. }),
  467. ]);
  468. const copiedParentMessages = committedBundle!.messages.slice(0, -1);
  469. expect(copiedParentMessages).toHaveLength(2);
  470. expect(
  471. copiedParentMessages.every((message) => message.info.anchor?.goalBoundary === undefined),
  472. ).toBe(true);
  473. expect(copiedParentMessages[0]?.parts).toEqual(
  474. expect.arrayContaining([expect.objectContaining({ text: "解释这里", type: "text" })]),
  475. );
  476. expect(JSON.stringify(copiedParentMessages)).not.toContain(targetId);
  477. expect(JSON.stringify(copiedParentMessages)).not.toContain(verificationEntryId);
  478. expect(user.info.anchor?.goalBoundary).toBe(anchor.goalBoundary);
  479. },
  480. );
  481. it("ForkIdentityMap 预分配 fork notice 全部 identity,builder 只能消费 plan", () => {
  482. const user = userMessage("msg_notice_parent_user" as MessageId, "notice", 1);
  483. const assistant = assistantMessage(
  484. "msg_notice_parent_assistant" as MessageId,
  485. user.info.id,
  486. "answer",
  487. 2,
  488. );
  489. const childSessionId = "sess_notice_plan_child" as SessionId;
  490. const identities = createForkIdentityMap({
  491. childSessionId,
  492. entries: [],
  493. goalSnapshots: [],
  494. messages: [user, assistant],
  495. parentSessionId: SESSION_ID,
  496. });
  497. const runtime = {
  498. config: { agentName: "zcode-agent", mode: "build" },
  499. getSessionModelSelection: () => ({ modelId: "glm-4-air", providerId: "glm" }),
  500. sessionId: SESSION_ID,
  501. workingDirectory: "/workspace",
  502. workspaceRoot: "/workspace",
  503. };
  504. const notices = buildAtomicForkNotice(runtime as never, {
  505. identities,
  506. sourceCommandId: "cmd-notice-plan",
  507. targetMessageId: assistant.info.id,
  508. });
  509. const hidden = notices[0]!;
  510. const notice = notices[1]!;
  511. const timeline = notice.parts[0];
  512. expect(identities.notice).toEqual({
  513. hiddenMessageId: expect.any(String),
  514. hiddenPartId: expect.any(String),
  515. messageId: expect.any(String),
  516. partId: expect.any(String),
  517. turnId: expect.any(String),
  518. productTurnId: expect.any(String),
  519. });
  520. expect(hidden.info.id).toBe(identities.notice.hiddenMessageId);
  521. expect(hidden.parts[0]?.id).toBe(identities.notice.hiddenPartId);
  522. expect(notice.info.id).toBe(identities.notice.messageId);
  523. expect(notice.parts[0]?.id).toBe(identities.notice.partId);
  524. expect(hidden.info.anchor).toMatchObject({
  525. turnId: identities.notice.turnId,
  526. productTurnId: identities.notice.productTurnId,
  527. orderedMessageIds: [identities.notice.hiddenMessageId, identities.notice.messageId],
  528. boundaryMessageId: identities.notice.messageId,
  529. });
  530. expect(notice.info.anchor).toEqual(hidden.info.anchor);
  531. expect(notice.info.role).toBe("assistant");
  532. if (notice.info.role !== "assistant" || timeline?.type !== "timeline") return;
  533. expect(notice.info.parentID).toBe(identities.notice.hiddenMessageId);
  534. expect(timeline.anchorMessageId).toBe(identities.messageIds.get(assistant.info.id));
  535. expect(timeline.anchorTurnId).toBe(identities.notice.turnId);
  536. // parent target 只允许保留在 forkOrigin/session_fork 的来源事实;所有 child-local 引用必须闭合。
  537. const childLocalRefs = {
  538. hiddenId: hidden.info.id,
  539. hiddenPartId: hidden.parts[0]?.id,
  540. hiddenPartMessageId: hidden.parts[0]?.messageID,
  541. noticeId: notice.info.id,
  542. noticePartId: notice.parts[0]?.id,
  543. noticePartMessageId: notice.parts[0]?.messageID,
  544. noticeParentId: notice.info.parentID,
  545. hiddenAnchor: hidden.info.anchor,
  546. noticeAnchor: notice.info.anchor,
  547. timelineAnchorMessageId: timeline.anchorMessageId,
  548. timelineAnchorTurnId: timeline.anchorTurnId,
  549. };
  550. expect(JSON.stringify(childLocalRefs)).not.toContain("msg_notice_parent_user");
  551. expect(JSON.stringify(childLocalRefs)).not.toContain("msg_notice_parent_assistant");
  552. const grandchildSessionId = "sess_notice_plan_grandchild" as SessionId;
  553. const forkAgainIdentities = createForkIdentityMap({
  554. childSessionId: grandchildSessionId,
  555. entries: [],
  556. goalSnapshots: [],
  557. messages: notices,
  558. parentSessionId: childSessionId,
  559. });
  560. const forkAgainNotices = buildAtomicForkNotice(
  561. { ...runtime, sessionId: childSessionId } as never,
  562. {
  563. identities: forkAgainIdentities,
  564. sourceCommandId: "cmd-notice-plan-again",
  565. targetMessageId: notice.info.id,
  566. },
  567. );
  568. const forkAgainHidden = forkAgainNotices[0]!;
  569. const forkAgainNotice = forkAgainNotices[1]!;
  570. const forkAgainTimeline = forkAgainNotice.parts[0];
  571. expect(forkAgainNotice.info.role).toBe("assistant");
  572. if (forkAgainNotice.info.role !== "assistant" || forkAgainTimeline?.type !== "timeline") return;
  573. const forkAgainLocalRefs = {
  574. hiddenId: forkAgainHidden.info.id,
  575. hiddenPartId: forkAgainHidden.parts[0]?.id,
  576. hiddenPartMessageId: forkAgainHidden.parts[0]?.messageID,
  577. hiddenPartSessionId: forkAgainHidden.parts[0]?.sessionID,
  578. noticeId: forkAgainNotice.info.id,
  579. noticePartId: forkAgainTimeline.id,
  580. noticePartMessageId: forkAgainTimeline.messageID,
  581. noticeParentId: forkAgainNotice.info.parentID,
  582. hiddenAnchor: forkAgainHidden.info.anchor,
  583. noticeAnchor: forkAgainNotice.info.anchor,
  584. timelineAnchorMessageId: forkAgainTimeline.anchorMessageId,
  585. timelineAnchorTurnId: forkAgainTimeline.anchorTurnId,
  586. };
  587. for (const parentLocalId of [
  588. identities.notice.hiddenMessageId,
  589. identities.notice.hiddenPartId,
  590. identities.notice.messageId,
  591. identities.notice.partId,
  592. identities.notice.turnId,
  593. ]) {
  594. expect(JSON.stringify(forkAgainLocalRefs)).not.toContain(parentLocalId);
  595. }
  596. });
  597. it("fork-before-input 的选型回退跳过停止后的中断标记", async () => {
  598. const user = userMessage("msg_marker_user" as MessageId, "first", 1);
  599. const assistant = assistantMessage(
  600. "msg_marker_assistant" as MessageId,
  601. user.info.id,
  602. "stopped answer",
  603. 2,
  604. );
  605. if (assistant.info.role !== "assistant") return;
  606. assistant.info.reasoningLevel = "max";
  607. const target = userMessage("msg_marker_target" as MessageId, "edit me", 4);
  608. const runtimeSelection = {
  609. modelId: "glm-4-air",
  610. providerId: "glm",
  611. options: { reasoningLevel: "high" },
  612. };
  613. // 停止后写的中断标记:只记 provider/model,不带 options。
  614. const marker = buildRuntimeReminderMessage(
  615. {
  616. config: { agentName: "zcode-agent" },
  617. getSessionModelSelection: () => runtimeSelection,
  618. sessionId: SESSION_ID,
  619. } as never,
  620. {
  621. message: { role: "user", content: "[Request interrupted by user]" },
  622. metadata: { source: "interrupt_marker" },
  623. },
  624. { created: 3 },
  625. )!;
  626. let committedBundle: Parameters<NonNullable<SessionStorePort["commitForkBundle"]>>[0] | null =
  627. null;
  628. const parentSession = {
  629. directory: "/workspace",
  630. id: SESSION_ID,
  631. path: "/workspace",
  632. projectID: "project-marker-fork",
  633. slug: "parent-marker-fork",
  634. taskType: "interactive",
  635. time: { created: 1, updated: 1 },
  636. title: "parent",
  637. version: "test",
  638. } as SessionInfo;
  639. const runtime = {
  640. appendEvent: async () => undefined,
  641. config: { agentName: "zcode-agent", mode: "build" },
  642. createEvent: (_type: unknown, payload: Record<string, unknown>) => ({ payload }),
  643. getSessionModelSelection: () => runtimeSelection,
  644. rootTraceContext: { traceId: "trace_marker_fork" },
  645. sessionId: SESSION_ID,
  646. sessionStore: {
  647. async commitForkBundle(bundle) {
  648. committedBundle = bundle;
  649. return bundle.child as SessionInfo;
  650. },
  651. async getSession() {
  652. return parentSession;
  653. },
  654. async messages() {
  655. return [user, assistant, marker, target];
  656. },
  657. } satisfies Partial<SessionStorePort>,
  658. workingDirectory: "/workspace",
  659. workspaceRoot: "/workspace",
  660. };
  661. await forkConversationBeforeMessage.call(runtime as never, {
  662. commandFact: {
  663. parentSessionId: SESSION_ID,
  664. sourceCommandId: "cmd-marker-fork",
  665. ack: {
  666. commandId: "cmd-marker-fork",
  667. status: "accepted",
  668. revisionAtDecision: 1,
  669. result: { type: "editUserQuery", disposition: "fork", sessionId: "sess_marker_child" },
  670. },
  671. metadata: {},
  672. },
  673. forkedSessionId: "sess_marker_child" as SessionId,
  674. goalBoundary: { kind: "none" },
  675. initialInput: {
  676. id: "queue_cmd-marker-fork",
  677. sessionID: "sess_marker_child" as SessionId,
  678. kind: "sendText",
  679. delivery: "startNow",
  680. payload: { text: "edited" },
  681. },
  682. sourceCommandId: "cmd-marker-fork",
  683. targetMessageId: target.info.id,
  684. targetProductTurnId: "turn-product",
  685. targetTranscriptTurnId: "turn-runtime",
  686. });
  687. // 取 fork 点之前最后一条对话消息(assistant)的选型,而不是中断标记或 runtime 当前值。
  688. expect(
  689. committedBundle!.entries.find((entry) => entry.type === SESSION_ENTRY_MODEL_SELECTION)?.data,
  690. ).toEqual({ modelId: "glm-4-air", providerId: "glm", options: { reasoningLevel: "max" } });
  691. });
  692. it("V4 stable fork 只通过 commitForkBundle 一次发布完整 child", async () => {
  693. const user = userMessage("msg_atomic_user" as MessageId, "fork me", 1);
  694. const assistant = assistantMessage(
  695. "msg_atomic_assistant" as MessageId,
  696. user.info.id,
  697. "stable answer",
  698. 2,
  699. );
  700. if (assistant.info.role !== "assistant") return;
  701. assistant.info.reasoningLevel = "max";
  702. assistant.info.mode = "edit";
  703. assistant.info.planEnabled = true;
  704. const parentSession = {
  705. directory: "/workspace",
  706. id: SESSION_ID,
  707. path: "/workspace",
  708. projectID: "project-atomic-stable",
  709. slug: "parent-atomic-stable",
  710. taskType: "interactive",
  711. time: { created: 1, updated: 1 },
  712. title: "parent",
  713. version: "test",
  714. } as SessionInfo;
  715. let committedBundle: Parameters<NonNullable<SessionStorePort["commitForkBundle"]>>[0] | null =
  716. null;
  717. let legacyCreateCount = 0;
  718. const runtime = {
  719. appendEvent: async () => undefined,
  720. config: { agentName: "zcode-agent", mode: "build" },
  721. createEvent: (_type: unknown, payload: Record<string, unknown>) => ({ payload }),
  722. getSessionModelSelection: () => ({
  723. modelId: "glm-4-air",
  724. providerId: "glm",
  725. options: { reasoningLevel: "high" },
  726. }),
  727. rootTraceContext: { traceId: "trace_atomic_stable" },
  728. sessionId: SESSION_ID,
  729. sessionStore: {
  730. async commitForkBundle(bundle) {
  731. committedBundle = bundle;
  732. return bundle.child as SessionInfo;
  733. },
  734. async createForkedSessionWithMetadata() {
  735. legacyCreateCount += 1;
  736. throw new Error("V4 stable fork touched legacy create path");
  737. },
  738. async getSession() {
  739. return parentSession;
  740. },
  741. async messages() {
  742. return [user, assistant];
  743. },
  744. } satisfies Partial<SessionStorePort>,
  745. workingDirectory: "/workspace",
  746. workspaceRoot: "/workspace",
  747. };
  748. const result = await forkStableConversationAtMessage.call(runtime as never, {
  749. forkedSessionId: "sess_atomic_stable_child" as SessionId,
  750. goalBoundary: { kind: "none" },
  751. sourceCommandId: "cmd-atomic-stable",
  752. target: {
  753. productTurnId: "product-atomic",
  754. transcriptTurnId: "turn-atomic",
  755. orderedMessageIds: [String(user.info.id), String(assistant.info.id)],
  756. boundaryMessageId: String(assistant.info.id),
  757. },
  758. });
  759. expect(result.forkedSessionId).toBe("sess_atomic_stable_child");
  760. expect(committedBundle!.entries).toContainEqual(
  761. expect.objectContaining({
  762. type: "runtime/execution_state",
  763. data: { mode: "edit", planEnabled: true },
  764. }),
  765. );
  766. expect(legacyCreateCount).toBe(0);
  767. expect(committedBundle!.messages).toHaveLength(4);
  768. expect(committedBundle!.messages.at(-1)!.info).toMatchObject({
  769. mode: "edit",
  770. planEnabled: true,
  771. });
  772. const modelSelectionEntry = committedBundle!.entries.find(
  773. (entry) => entry.type === SESSION_ENTRY_MODEL_SELECTION,
  774. );
  775. expect(modelSelectionEntry).toMatchObject({
  776. id: "sess_atomic_stable_child:runtime-model-selection",
  777. sessionID: "sess_atomic_stable_child",
  778. type: SESSION_ENTRY_MODEL_SELECTION,
  779. touchSession: false,
  780. data: {
  781. modelId: "glm-4-air",
  782. providerId: "glm",
  783. options: { reasoningLevel: "max" },
  784. },
  785. });
  786. const forkNoticeAssistant = committedBundle!.messages.at(-1)?.info;
  787. expect(forkNoticeAssistant).toMatchObject({
  788. role: "assistant",
  789. modelId: "glm-4-air",
  790. providerId: "glm",
  791. reasoningLevel: "max",
  792. });
  793. expect(committedBundle!.commandFact.ack.result).toEqual({
  794. type: "forkAssistant",
  795. sessionId: "sess_atomic_stable_child",
  796. });
  797. // 从真实 producer bundle 恢复,防止 notice 缺少 part metadata 后退化为普通 user 文本。
  798. const persisted = JSON.parse(JSON.stringify(committedBundle!.messages)) as MessageWithParts[];
  799. const boundary = persisted.at(-2)!;
  800. expect(boundary.info.semantics).toMatchObject({
  801. uiVisibility: "hidden",
  802. providerVisibility: "visible",
  803. transcriptVisibility: "hidden",
  804. });
  805. expect(boundary.parts[0]).toMatchObject({
  806. type: "text",
  807. synthetic: true,
  808. metadata: { source: "fork", runtimeMessage: { source: "conversation_fork" } },
  809. });
  810. const boundaryText = boundary.parts[0]!.type === "text" ? boundary.parts[0]!.text : "";
  811. expect(boundaryText).toContain("This session was forked from a previous session message.");
  812. expect(boundaryText).not.toContain("<system-reminder>");
  813. const history = new MessageHistoryImpl();
  814. await hydrateMessageHistoryFromSession({ history, messages: persisted });
  815. expect(history.toRuntimeEntries().at(-1)).toEqual({
  816. kind: "attachment",
  817. content: boundaryText,
  818. metadata: { source: "conversation_fork" },
  819. });
  820. history.addUser("child question", { source: "real_user" });
  821. for (const useMidConversationSystem of [true, false]) {
  822. const request = buildProviderRequestMessages({
  823. entries: history.toRuntimeEntries(),
  824. useMidConversationSystem,
  825. });
  826. expect(request.messages.slice(-2)).toEqual([
  827. { role: "user", content: `<system-reminder>\n${boundaryText}\n</system-reminder>` },
  828. { role: "user", content: "child question" },
  829. ]);
  830. expect(
  831. request.messages.filter(
  832. (message) =>
  833. typeof message.content === "string" && message.content.includes(boundaryText),
  834. ),
  835. ).toHaveLength(1);
  836. }
  837. });
  838. it("加速轮分叉不继承加速卡 Selection,child 回落父会话常驻模型", async () => {
  839. const user = userMessage("msg_highspeed_user" as MessageId, "加速中提问", 1);
  840. const assistant = assistantMessage(
  841. "msg_highspeed_assistant" as MessageId,
  842. user.info.id,
  843. "加速回答",
  844. 2,
  845. );
  846. if (user.info.role !== "user" || assistant.info.role !== "assistant") return;
  847. // 加速轮的 user/assistant 按 highspeed-card-spec §5 记录本轮真实执行模型(单轮执行事实)。
  848. user.info.modelSelection = {
  849. modelId: "glm-4.6" as never,
  850. providerId: HIGHSPEED_PROVIDER_IDS.zai as never,
  851. };
  852. assistant.info.providerId = HIGHSPEED_PROVIDER_IDS.zai as never;
  853. assistant.info.modelId = "glm-4.6" as never;
  854. assistant.info.reasoningLevel = "max";
  855. const parentSession = {
  856. directory: "/workspace",
  857. id: SESSION_ID,
  858. path: "/workspace",
  859. projectID: "project-highspeed-fork",
  860. slug: "parent-highspeed-fork",
  861. taskType: "interactive",
  862. time: { created: 1, updated: 1 },
  863. title: "parent",
  864. version: "test",
  865. } as SessionInfo;
  866. let committedBundle: Parameters<NonNullable<SessionStorePort["commitForkBundle"]>>[0] | null =
  867. null;
  868. const runtime = {
  869. appendEvent: async () => undefined,
  870. config: { agentName: "zcode-agent", mode: "build" },
  871. createEvent: (_type: unknown, payload: Record<string, unknown>) => ({ payload }),
  872. // 加速是 `selectionScope=execution`,从不改写常驻 Selection:它就是用户的原模型。
  873. getSessionModelSelection: () => ({
  874. modelId: "glm-4-air",
  875. providerId: "glm",
  876. options: { reasoningLevel: "high" },
  877. }),
  878. rootTraceContext: { traceId: "trace_highspeed_fork" },
  879. sessionId: SESSION_ID,
  880. sessionStore: {
  881. async commitForkBundle(bundle) {
  882. committedBundle = bundle;
  883. return bundle.child as SessionInfo;
  884. },
  885. async getSession() {
  886. return parentSession;
  887. },
  888. async messages() {
  889. return [user, assistant];
  890. },
  891. } satisfies Partial<SessionStorePort>,
  892. workingDirectory: "/workspace",
  893. workspaceRoot: "/workspace",
  894. };
  895. // 不带显式选型(回落历史/常驻)与调用方显式传入加速选型,child 结果必须一致。
  896. const explicitCases: (ModelSelection | undefined)[] = [
  897. undefined,
  898. { modelId: "glm-4.6" as never, providerId: HIGHSPEED_PROVIDER_IDS.zai as never },
  899. ];
  900. for (const [index, explicit] of explicitCases.entries()) {
  901. committedBundle = null;
  902. await forkStableConversationAtMessage.call(runtime as never, {
  903. forkedSessionId: `sess_highspeed_child_${index}` as SessionId,
  904. goalBoundary: { kind: "none" },
  905. sourceCommandId: `cmd-highspeed-fork-${index}`,
  906. ...(explicit ? { modelSelection: explicit } : {}),
  907. target: {
  908. productTurnId: "product-highspeed",
  909. transcriptTurnId: "turn-highspeed",
  910. orderedMessageIds: [String(user.info.id), String(assistant.info.id)],
  911. boundaryMessageId: String(assistant.info.id),
  912. },
  913. });
  914. // child 常驻在加速 Provider 上会让用户看到「原模型没带过来」,首轮还会 ModelRequestAuthMissing。
  915. expect(
  916. committedBundle!.entries.find((entry) => entry.type === SESSION_ENTRY_MODEL_SELECTION),
  917. ).toMatchObject({
  918. sessionID: `sess_highspeed_child_${index}`,
  919. data: { modelId: "glm-4-air", providerId: "glm", options: { reasoningLevel: "high" } },
  920. });
  921. expect(committedBundle!.messages.at(-1)!.info).toMatchObject({
  922. role: "assistant",
  923. modelId: "glm-4-air",
  924. providerId: "glm",
  925. });
  926. expect(JSON.stringify(committedBundle!.entries)).not.toContain(HIGHSPEED_PROVIDER_IDS.zai);
  927. }
  928. });
  929. it("fork-of-fork 只从 child-local anchor 构造 canonical target,不泄漏 parent id", () => {
  930. const user = userMessage("msg_parent_user" as MessageId, "fork twice", 1);
  931. const assistant = assistantMessage(
  932. "msg_parent_assistant" as MessageId,
  933. user.info.id,
  934. "stable answer",
  935. 2,
  936. );
  937. const parentOrderedIds = [user.info.id, assistant.info.id];
  938. user.info.anchor = {
  939. turnId: "turn_parent" as never,
  940. productTurnId: "product_parent",
  941. orderedMessageIds: parentOrderedIds,
  942. boundaryMessageId: assistant.info.id,
  943. };
  944. assistant.info.anchor = { ...user.info.anchor };
  945. const firstChildId = "sess_first_child" as SessionId;
  946. const messageIdMap = new Map<MessageId, MessageId>([
  947. [user.info.id, "msg_child_user" as MessageId],
  948. [assistant.info.id, "msg_child_assistant" as MessageId],
  949. ]);
  950. const turnIdMap = new Map([["turn_parent", "turn_child"]]);
  951. const productTurnIdMap = new Map([["product_parent", "product_child"]]);
  952. const cloned = [user, assistant].map((message) => ({
  953. info: cloneMessageForFork(message.info, {
  954. forkedSessionId: firstChildId,
  955. messageIdMap,
  956. nextMessageId: messageIdMap.get(message.info.id)!,
  957. turnIdMap,
  958. productTurnIdMap,
  959. strictLocalReferences: true,
  960. } as never),
  961. parts: [],
  962. }));
  963. const childAnchor = cloned[1]!.info.anchor!;
  964. expect(childAnchor.orderedMessageIds).toEqual(["msg_child_user", "msg_child_assistant"]);
  965. expect(childAnchor.boundaryMessageId).toBe("msg_child_assistant");
  966. expect(childAnchor.turnId).not.toBe("turn_parent");
  967. expect(childAnchor.productTurnId).not.toBe("product_parent");
  968. expect(() =>
  969. stableForkHistoryMessages(cloned, {
  970. productTurnId: childAnchor.productTurnId!,
  971. transcriptTurnId: String(childAnchor.turnId),
  972. orderedMessageIds: childAnchor.orderedMessageIds!.map(String),
  973. boundaryMessageId: String(childAnchor.boundaryMessageId),
  974. }),
  975. ).not.toThrow();
  976. });
  977. it("remaps compact leading announcement ids and drops ids outside the child transcript", () => {
  978. const summaryId = "msg_leading_summary" as MessageId;
  979. const leadingId = "msg_leading_announcement" as MessageId;
  980. const cloned = clonePartForFork(
  981. {
  982. id: partId("leading_compaction"),
  983. sessionID: SESSION_ID,
  984. messageID: summaryId,
  985. type: "compaction",
  986. auto: false,
  987. metadata: {
  988. compactLeadingMessageIds: [leadingId, "msg_parent_only" as MessageId],
  989. },
  990. } as MessagePart,
  991. {
  992. forkedSessionId: "ses_leading_child" as never,
  993. nextMessageId: "msg_child_summary" as MessageId,
  994. messageIdMap: new Map<MessageId, MessageId>([
  995. [summaryId, "msg_child_summary" as MessageId],
  996. [leadingId, "msg_child_announcement" as MessageId],
  997. ]),
  998. strictLocalReferences: true,
  999. },
  1000. );
  1001. // 旧版本 fork 原样复制 metadata;映射不到的声明只影响公告位置,不能阻断 fork。
  1002. expect(cloned).toMatchObject({
  1003. metadata: { compactLeadingMessageIds: ["msg_child_announcement"] },
  1004. });
  1005. });
  1006. it("stable fork golden remap 覆盖 message/part/turn/compact/goal/verifier 全部 child-local identity", async () => {
  1007. const user = userMessage("msg_golden_user" as MessageId, "golden", 1);
  1008. const assistant = assistantMessage(
  1009. "msg_golden_assistant" as MessageId,
  1010. user.info.id,
  1011. "golden answer",
  1012. 2,
  1013. );
  1014. const goal: SessionGoal = {
  1015. sessionID: SESSION_ID,
  1016. targetID: "target_golden_parent",
  1017. objective: "golden goal",
  1018. summaryTitle: null,
  1019. status: "active",
  1020. tokenBudget: null,
  1021. tokensUsed: 1,
  1022. timeUsedSeconds: 1,
  1023. activeInputId: "parent-active-input",
  1024. activeRunStartedAtMs: 10,
  1025. activeRunLastSeenAtMs: 11,
  1026. time: { created: 1, updated: 2 },
  1027. };
  1028. const anchor = {
  1029. turnId: "turn_golden_parent" as never,
  1030. productTurnId: "product_golden_parent",
  1031. orderedMessageIds: [user.info.id, assistant.info.id],
  1032. boundaryMessageId: assistant.info.id,
  1033. goalBoundary: {
  1034. kind: "snapshot" as const,
  1035. target: goal,
  1036. verificationEntryIds: ["entry_golden_parent"],
  1037. },
  1038. };
  1039. user.info.anchor = anchor;
  1040. assistant.info.anchor = anchor;
  1041. assistant.parts.push(
  1042. {
  1043. id: partId("golden_compaction"),
  1044. sessionID: SESSION_ID,
  1045. messageID: assistant.info.id,
  1046. type: "compaction",
  1047. auto: false,
  1048. tail_start_id: user.info.id,
  1049. summaryMessageId: assistant.info.id,
  1050. compactBoundary: {
  1051. boundaryId: "compact-golden",
  1052. trigger: "manual",
  1053. preCompactTokenCount: 10,
  1054. summarizedMessageCount: 2,
  1055. lastSummarizedMessageId: assistant.info.id,
  1056. preservedSegment: {
  1057. headMessageId: user.info.id,
  1058. anchorMessageId: assistant.info.id,
  1059. tailMessageId: assistant.info.id,
  1060. },
  1061. summaryMessageIds: [assistant.info.id],
  1062. traceId: "trace-golden" as never,
  1063. turnId: "turn_golden_parent" as never,
  1064. },
  1065. } as MessagePart,
  1066. {
  1067. id: partId("golden_compact_timeline"),
  1068. sessionID: SESSION_ID,
  1069. messageID: assistant.info.id,
  1070. type: "timeline",
  1071. timelineType: "context_compaction",
  1072. display: "separator",
  1073. status: "completed",
  1074. operationId: "compact-golden",
  1075. trigger: "manual",
  1076. anchorMessageId: assistant.info.id,
  1077. anchorTurnId: "turn_golden_parent" as never,
  1078. summaryMessageId: assistant.info.id,
  1079. } as MessagePart,
  1080. {
  1081. id: partId("golden_goal_timeline"),
  1082. sessionID: SESSION_ID,
  1083. messageID: assistant.info.id,
  1084. type: "timeline",
  1085. timelineType: "goal_verification",
  1086. display: "separator",
  1087. status: "completed",
  1088. targetId: goal.targetID,
  1089. verificationId: "verification_golden_parent",
  1090. anchorMessageId: assistant.info.id,
  1091. anchorTurnId: "turn_golden_parent" as never,
  1092. } as MessagePart,
  1093. {
  1094. id: partId("golden_tool"),
  1095. sessionID: SESSION_ID,
  1096. messageID: assistant.info.id,
  1097. type: "tool",
  1098. callID: "tool_call_golden_parent",
  1099. tool: "read",
  1100. state: {
  1101. status: "completed",
  1102. input: {},
  1103. output: "ok",
  1104. title: "read",
  1105. metadata: {},
  1106. time: { start: 1, end: 2 },
  1107. attachments: [
  1108. {
  1109. id: partId("golden_tool_attachment"),
  1110. sessionID: SESSION_ID,
  1111. messageID: assistant.info.id,
  1112. type: "file",
  1113. mime: "text/plain",
  1114. url: "data:text/plain,ok",
  1115. },
  1116. ],
  1117. },
  1118. } as MessagePart,
  1119. );
  1120. const verificationEntry = goalVerificationEntry(
  1121. "entry_golden_parent",
  1122. String(assistant.info.id),
  1123. 1,
  1124. false,
  1125. );
  1126. const verificationData = verificationEntry.data as {
  1127. payload: Record<string, unknown>;
  1128. };
  1129. verificationData.payload.targetId = goal.targetID;
  1130. verificationData.payload.verificationId = "verification_golden_parent";
  1131. verificationData.payload.anchorTurnId = "turn_golden_parent";
  1132. const childSessionId = "sess_golden_child" as SessionId;
  1133. let bundle: Parameters<NonNullable<SessionStorePort["commitForkBundle"]>>[0] | null = null;
  1134. const parentSession = {
  1135. directory: "/workspace",
  1136. id: SESSION_ID,
  1137. projectID: "project-golden",
  1138. slug: "parent-golden",
  1139. taskType: "interactive",
  1140. time: { created: 1, updated: 1 },
  1141. title: "parent",
  1142. version: "test",
  1143. } as SessionInfo;
  1144. const runtime = {
  1145. appendEvent: async () => undefined,
  1146. config: { agentName: "zcode-agent", mode: "build" },
  1147. createEvent: () => ({ type: "session.forked" }),
  1148. getSessionModelSelection: () => ({ modelId: "glm-4-air", providerId: "glm" }),
  1149. rootTraceContext: { traceId: "trace-golden" },
  1150. sessionId: SESSION_ID,
  1151. sessionStore: {
  1152. async commitForkBundle(value) {
  1153. bundle = value;
  1154. return value.child as SessionInfo;
  1155. },
  1156. async getSession() {
  1157. return parentSession;
  1158. },
  1159. async messages() {
  1160. return [user, assistant];
  1161. },
  1162. async sessionEntries() {
  1163. return [verificationEntry];
  1164. },
  1165. } satisfies Partial<SessionStorePort>,
  1166. workingDirectory: "/workspace",
  1167. workspaceRoot: "/workspace",
  1168. };
  1169. await forkStableConversationAtMessage.call(runtime as never, {
  1170. forkedSessionId: childSessionId,
  1171. goalBoundary: anchor.goalBoundary,
  1172. sourceCommandId: "cmd-golden",
  1173. target: {
  1174. productTurnId: anchor.productTurnId,
  1175. transcriptTurnId: String(anchor.turnId),
  1176. orderedMessageIds: anchor.orderedMessageIds.map(String),
  1177. boundaryMessageId: String(anchor.boundaryMessageId),
  1178. },
  1179. });
  1180. const copiedUser = bundle!.messages[0]!;
  1181. const copiedAssistant = bundle!.messages[1]!;
  1182. const copiedAnchor = copiedAssistant.info.anchor!;
  1183. const copiedCompaction = copiedAssistant.parts.find((part) => part.type === "compaction");
  1184. const copiedCompactTimeline = copiedAssistant.parts.find(
  1185. (part) => part.type === "timeline" && part.timelineType === "context_compaction",
  1186. );
  1187. const copiedGoalTimeline = copiedAssistant.parts.find(
  1188. (part) => part.type === "timeline" && part.timelineType === "goal_verification",
  1189. );
  1190. const copiedTool = copiedAssistant.parts.find((part) => part.type === "tool");
  1191. const copiedEntry = bundle!.entries[0]!;
  1192. const copiedEntryPayload = (copiedEntry.data as { payload: Record<string, unknown> }).payload;
  1193. expect(copiedUser.info.sessionID).toBe(childSessionId);
  1194. expect(copiedAssistant.info.sessionID).toBe(childSessionId);
  1195. expect(copiedAssistant.info.role).toBe("assistant");
  1196. if (copiedAssistant.info.role !== "assistant") return;
  1197. expect(copiedAssistant.info.parentID).toBe(copiedUser.info.id);
  1198. expect(copiedAnchor.orderedMessageIds).toEqual([copiedUser.info.id, copiedAssistant.info.id]);
  1199. expect(copiedAnchor.boundaryMessageId).toBe(copiedAssistant.info.id);
  1200. expect(copiedAnchor.turnId).not.toBe(anchor.turnId);
  1201. expect(copiedAnchor.productTurnId).not.toBe(anchor.productTurnId);
  1202. expect(copiedCompaction).toMatchObject({
  1203. sessionID: childSessionId,
  1204. messageID: copiedAssistant.info.id,
  1205. tail_start_id: copiedUser.info.id,
  1206. summaryMessageId: copiedAssistant.info.id,
  1207. compactBoundary: {
  1208. lastSummarizedMessageId: copiedAssistant.info.id,
  1209. preservedSegment: {
  1210. headMessageId: copiedUser.info.id,
  1211. anchorMessageId: copiedAssistant.info.id,
  1212. tailMessageId: copiedAssistant.info.id,
  1213. },
  1214. summaryMessageIds: [copiedAssistant.info.id],
  1215. turnId: copiedAnchor.turnId,
  1216. },
  1217. });
  1218. expect(copiedCompactTimeline).toMatchObject({
  1219. anchorMessageId: copiedAssistant.info.id,
  1220. anchorTurnId: copiedAnchor.turnId,
  1221. summaryMessageId: copiedAssistant.info.id,
  1222. });
  1223. expect(bundle!.goal?.source).toMatchObject({
  1224. sessionID: childSessionId,
  1225. activeInputId: null,
  1226. activeRunStartedAtMs: null,
  1227. activeRunLastSeenAtMs: null,
  1228. });
  1229. expect(bundle!.goal?.source.targetID).not.toBe(goal.targetID);
  1230. expect(copiedEntry.id).not.toBe(verificationEntry.id);
  1231. expect(copiedEntry.sessionID).toBe(childSessionId);
  1232. expect(copiedEntryPayload).toMatchObject({
  1233. targetId: bundle!.goal?.source.targetID,
  1234. anchorAssistantMessageId: copiedAssistant.info.id,
  1235. anchorTurnId: copiedAnchor.turnId,
  1236. });
  1237. expect(copiedEntryPayload.verificationId).not.toBe("verification_golden_parent");
  1238. expect(copiedGoalTimeline).toMatchObject({
  1239. targetId: bundle!.goal?.source.targetID,
  1240. verificationId: copiedEntryPayload.verificationId,
  1241. anchorMessageId: copiedAssistant.info.id,
  1242. anchorTurnId: copiedAnchor.turnId,
  1243. });
  1244. expect(copiedTool).toMatchObject({
  1245. sessionID: childSessionId,
  1246. messageID: copiedAssistant.info.id,
  1247. state: {
  1248. attachments: [
  1249. {
  1250. sessionID: childSessionId,
  1251. messageID: copiedAssistant.info.id,
  1252. },
  1253. ],
  1254. },
  1255. });
  1256. if (copiedTool?.type === "tool") {
  1257. expect(copiedTool.callID).not.toBe("tool_call_golden_parent");
  1258. if (copiedTool.state.status === "completed") {
  1259. expect(copiedTool.state.attachments?.[0]?.id).not.toBe(partId("golden_tool_attachment"));
  1260. }
  1261. }
  1262. expect(copiedAnchor.goalBoundary).toMatchObject({
  1263. kind: "snapshot",
  1264. target: {
  1265. sessionID: childSessionId,
  1266. targetID: bundle!.goal?.source.targetID,
  1267. },
  1268. verificationEntryIds: [copiedEntry.id],
  1269. });
  1270. });
  1271. it("fork child title uses generated source", async () => {
  1272. const createdSessions: unknown[] = [];
  1273. const runtime = {
  1274. rootTraceContext: { traceId: "trace_fork_title" },
  1275. sessionId: SESSION_ID,
  1276. sessionStore: {
  1277. createSession: async (input: unknown) => {
  1278. createdSessions.push(input);
  1279. },
  1280. },
  1281. };
  1282. const parentSession = {
  1283. directory: "/workspace",
  1284. id: SESSION_ID,
  1285. path: "/workspace",
  1286. projectID: "project_fork_title",
  1287. slug: "parent-title",
  1288. taskType: "interactive",
  1289. time: { created: 1, updated: 1 },
  1290. title: "执行下 pwd",
  1291. version: "test",
  1292. } as SessionInfo;
  1293. await createForkedSession(runtime as never, {
  1294. forkedSessionId: "sess_child_title" as SessionId,
  1295. parentSession,
  1296. });
  1297. expect(createdSessions[0]).toMatchObject({
  1298. id: "sess_child_title",
  1299. title: "Fork of 执行下 pwd",
  1300. titleSource: "generated",
  1301. });
  1302. });
  1303. it("stable fork child 与 sourceCommandId/target metadata 通过原子 store 能力一起创建", async () => {
  1304. const atomicCreates: Array<{
  1305. input: { id: SessionId };
  1306. metadata: StableConversationForkChildMetadata;
  1307. }> = [];
  1308. let legacyCreateCount = 0;
  1309. const target: StableConversationForkTarget = {
  1310. productTurnId: "product-1",
  1311. transcriptTurnId: "runtime-1",
  1312. orderedMessageIds: ["msg-user", "msg-final"],
  1313. boundaryMessageId: "msg-final",
  1314. };
  1315. const runtime = {
  1316. rootTraceContext: { traceId: "trace_atomic_fork" },
  1317. sessionId: SESSION_ID,
  1318. sessionStore: {
  1319. async createSession() {
  1320. legacyCreateCount += 1;
  1321. },
  1322. async createForkedSessionWithMetadata(
  1323. input: { id: SessionId },
  1324. metadata: StableConversationForkChildMetadata,
  1325. ) {
  1326. atomicCreates.push({ input, metadata });
  1327. // 原子 store 发现同 command fact 时会返回第一次创建的 child。
  1328. return { id: "sess_existing_child" as SessionId };
  1329. },
  1330. },
  1331. };
  1332. const parentSession = {
  1333. directory: "/workspace",
  1334. id: SESSION_ID,
  1335. path: "/workspace",
  1336. projectID: "project_atomic_fork",
  1337. slug: "parent",
  1338. taskType: "interactive",
  1339. time: { created: 1, updated: 1 },
  1340. title: "Parent",
  1341. version: "test",
  1342. } as SessionInfo;
  1343. const forkedSessionId = await createForkedSession(runtime as never, {
  1344. forkedSessionId: "sess_requested_child" as SessionId,
  1345. parentSession,
  1346. stableForkMetadata: {
  1347. forkTarget: target,
  1348. parentSessionId: SESSION_ID,
  1349. sourceCommandId: "command-fork-1",
  1350. },
  1351. });
  1352. expect(forkedSessionId).toBe("sess_existing_child");
  1353. expect(legacyCreateCount).toBe(0);
  1354. expect(atomicCreates).toEqual([
  1355. {
  1356. input: expect.objectContaining({
  1357. id: "sess_requested_child",
  1358. parentID: SESSION_ID,
  1359. }),
  1360. metadata: {
  1361. forkTarget: target,
  1362. parentSessionId: SESSION_ID,
  1363. sourceCommandId: "command-fork-1",
  1364. },
  1365. },
  1366. ]);
  1367. });
  1368. it("stable fork store 缺少原子 metadata 能力时在 child 创建前失败", async () => {
  1369. let legacyCreateCount = 0;
  1370. const runtime = {
  1371. rootTraceContext: { traceId: "trace_atomic_required" },
  1372. sessionId: SESSION_ID,
  1373. sessionStore: {
  1374. async createSession() {
  1375. legacyCreateCount += 1;
  1376. },
  1377. },
  1378. };
  1379. const parentSession = {
  1380. directory: "/workspace",
  1381. id: SESSION_ID,
  1382. projectID: "project_atomic_required",
  1383. slug: "parent",
  1384. taskType: "interactive",
  1385. time: { created: 1, updated: 1 },
  1386. title: "Parent",
  1387. version: "test",
  1388. } as SessionInfo;
  1389. await expect(
  1390. createForkedSession(runtime as never, {
  1391. parentSession,
  1392. stableForkMetadata: {
  1393. forkTarget: {
  1394. productTurnId: "product-1",
  1395. transcriptTurnId: "runtime-1",
  1396. orderedMessageIds: ["msg-final"],
  1397. boundaryMessageId: "msg-final",
  1398. },
  1399. parentSessionId: SESSION_ID,
  1400. sourceCommandId: "command-fork-1",
  1401. },
  1402. }),
  1403. ).rejects.toThrow(/atomic child metadata persistence/);
  1404. expect(legacyCreateCount).toBe(0);
  1405. });
  1406. it("stable fork 保留历史前缀并严格复制 resolver target segment,不向 boundary 后扩张", () => {
  1407. const firstUser = userMessage("msg_user_1" as MessageId, "第一轮", 1);
  1408. const firstAssistant = assistantMessage(
  1409. "msg_assistant_1" as MessageId,
  1410. firstUser.info.id,
  1411. "第一轮回复",
  1412. 2,
  1413. );
  1414. const targetUser = userMessage("msg_user_2" as MessageId, "目标轮", 3);
  1415. const earlyAssistant = assistantMessage(
  1416. "msg_assistant_2a" as MessageId,
  1417. targetUser.info.id,
  1418. "工具前",
  1419. 4,
  1420. );
  1421. const finalAssistant = assistantMessage(
  1422. "msg_assistant_2b" as MessageId,
  1423. targetUser.info.id,
  1424. "最终回复",
  1425. 5,
  1426. );
  1427. const sameParentButNotResolved = assistantMessage(
  1428. "msg_assistant_unresolved" as MessageId,
  1429. targetUser.info.id,
  1430. "不得自动扩张",
  1431. 6,
  1432. );
  1433. const activeMessages = [
  1434. firstUser,
  1435. firstAssistant,
  1436. targetUser,
  1437. earlyAssistant,
  1438. finalAssistant,
  1439. sameParentButNotResolved,
  1440. ];
  1441. const selected = stableForkHistoryMessages(activeMessages, {
  1442. productTurnId: "product-2",
  1443. transcriptTurnId: "runtime-2",
  1444. orderedMessageIds: ["msg_user_2", "msg_assistant_2a", "msg_assistant_2b"],
  1445. boundaryMessageId: "msg_assistant_2b",
  1446. });
  1447. expect(selected.map((message) => message.info.id)).toEqual([
  1448. "msg_user_1",
  1449. "msg_assistant_1",
  1450. "msg_user_2",
  1451. "msg_assistant_2a",
  1452. "msg_assistant_2b",
  1453. ]);
  1454. });
  1455. it("stable fork 对缺失、乱序、重复或非 assistant boundary 明确拒绝", () => {
  1456. const user = userMessage("msg_user" as MessageId, "目标轮", 1);
  1457. const assistant = assistantMessage("msg_assistant" as MessageId, user.info.id, "回复", 2);
  1458. const base = {
  1459. productTurnId: "product-1",
  1460. transcriptTurnId: "runtime-1",
  1461. };
  1462. expect(() =>
  1463. stableForkHistoryMessages([user, assistant], {
  1464. ...base,
  1465. orderedMessageIds: ["msg_missing"],
  1466. boundaryMessageId: "msg_missing",
  1467. }),
  1468. ).toThrow(/active transcript segment/);
  1469. expect(() =>
  1470. stableForkHistoryMessages([user, assistant], {
  1471. ...base,
  1472. orderedMessageIds: ["msg_assistant", "msg_user"],
  1473. boundaryMessageId: "msg_user",
  1474. }),
  1475. ).toThrow(/contiguous active transcript segment/);
  1476. expect(() =>
  1477. stableForkHistoryMessages([user, assistant], {
  1478. ...base,
  1479. orderedMessageIds: ["msg_assistant", "msg_assistant"],
  1480. boundaryMessageId: "msg_assistant",
  1481. }),
  1482. ).toThrow(/duplicate message ids/);
  1483. expect(() =>
  1484. stableForkHistoryMessages([user], {
  1485. ...base,
  1486. orderedMessageIds: ["msg_user"],
  1487. boundaryMessageId: "msg_user",
  1488. }),
  1489. ).toThrow(/completed assistant message/);
  1490. });
  1491. it("compact-covered edit fork selects only the active prefix before target input, including root", () => {
  1492. const firstUser = userMessage("msg_user_1" as MessageId, "first", 1);
  1493. const firstAssistant = assistantMessage(
  1494. "msg_assistant_1" as MessageId,
  1495. firstUser.info.id,
  1496. "answer",
  1497. 2,
  1498. );
  1499. const editedInput = userMessage("msg_user_2" as MessageId, "edit me", 3);
  1500. const oldAnswer = assistantMessage(
  1501. "msg_assistant_2" as MessageId,
  1502. editedInput.info.id,
  1503. "old answer",
  1504. 4,
  1505. );
  1506. expect(
  1507. conversationHistoryBeforeInput(
  1508. [firstUser, firstAssistant, editedInput, oldAnswer],
  1509. editedInput.info.id,
  1510. ).map((message) => message.info.id),
  1511. ).toEqual([firstUser.info.id, firstAssistant.info.id]);
  1512. expect(conversationHistoryBeforeInput([firstUser, firstAssistant], firstUser.info.id)).toEqual(
  1513. [],
  1514. );
  1515. expect(() =>
  1516. conversationHistoryBeforeInput([firstUser, firstAssistant], "missing" as MessageId),
  1517. ).toThrow(/not found/);
  1518. });
  1519. it("bundle commit 是 point-of-no-return:parent fork event 失败不反转 accepted child", async () => {
  1520. const target = userMessage("msg_first_user" as MessageId, "edit me", 1);
  1521. const childSessionId = "sess_committed_child" as SessionId;
  1522. let committedBundle: Parameters<NonNullable<SessionStorePort["commitForkBundle"]>>[0] | null =
  1523. null;
  1524. const parentSession = {
  1525. directory: "/workspace",
  1526. id: SESSION_ID,
  1527. path: "/workspace",
  1528. projectID: "project-committed-child",
  1529. slug: "parent-committed-child",
  1530. taskType: "interactive",
  1531. time: { created: 1, updated: 1 },
  1532. title: "parent",
  1533. version: "test",
  1534. } as SessionInfo;
  1535. const runtime = {
  1536. appendEvent: async () => {
  1537. throw new Error("parent event store unavailable");
  1538. },
  1539. config: { agentName: "zcode-agent", mode: "build" },
  1540. createEvent: () => ({ type: "session.forked" }),
  1541. getSessionModelSelection: () => ({
  1542. modelId: "glm-4-air",
  1543. providerId: "glm",
  1544. }),
  1545. logger: { warn: () => undefined },
  1546. rootTraceContext: { traceId: "trace_committed_child" },
  1547. sessionId: SESSION_ID,
  1548. sessionStore: {
  1549. async commitForkBundle(bundle) {
  1550. committedBundle = bundle;
  1551. return bundle.child as SessionInfo;
  1552. },
  1553. async getSession() {
  1554. return parentSession;
  1555. },
  1556. async messages() {
  1557. return [target];
  1558. },
  1559. } satisfies Partial<SessionStorePort>,
  1560. workingDirectory: "/workspace",
  1561. workspaceRoot: "/workspace",
  1562. };
  1563. await expect(
  1564. forkConversationBeforeMessage.call(runtime as never, {
  1565. commandFact: {
  1566. parentSessionId: SESSION_ID,
  1567. sourceCommandId: "cmd-committed-child",
  1568. ack: {
  1569. commandId: "cmd-committed-child",
  1570. status: "accepted",
  1571. revisionAtDecision: 1,
  1572. result: {
  1573. type: "editUserQuery",
  1574. disposition: "fork",
  1575. sessionId: childSessionId,
  1576. },
  1577. },
  1578. metadata: {},
  1579. },
  1580. forkedSessionId: childSessionId,
  1581. goalBoundary: { kind: "none" },
  1582. initialInput: {
  1583. id: "queue_cmd-committed-child",
  1584. sessionID: childSessionId,
  1585. kind: "sendText",
  1586. delivery: "startNow",
  1587. payload: { text: "edited" },
  1588. },
  1589. sourceCommandId: "cmd-committed-child",
  1590. targetMessageId: target.info.id,
  1591. targetProductTurnId: "turn-product",
  1592. targetTranscriptTurnId: "turn-runtime",
  1593. }),
  1594. ).resolves.toMatchObject({ forkedSessionId: childSessionId });
  1595. const notice = committedBundle!.messages.find((message) => message.info.role === "assistant");
  1596. expect(notice?.info.role).toBe("assistant");
  1597. if (notice?.info.role !== "assistant") return;
  1598. expect(notice.info.parentID).not.toBe(notice.info.id);
  1599. expect(
  1600. committedBundle!.messages.some((message) => message.info.id === notice.info.parentID),
  1601. ).toBe(true);
  1602. });
  1603. it("duplicate bundle 后 core 全程使用 store 返回的 existing child id", async () => {
  1604. const target = userMessage("msg_duplicate_user" as MessageId, "edit me", 1);
  1605. const requestedChildId = "sess_requested_duplicate" as SessionId;
  1606. const existingChildId = "sess_existing_duplicate" as SessionId;
  1607. const eventPayloads: Array<Record<string, unknown>> = [];
  1608. const parentSession = {
  1609. directory: "/workspace",
  1610. id: SESSION_ID,
  1611. path: "/workspace",
  1612. projectID: "project-duplicate-child",
  1613. slug: "parent-duplicate-child",
  1614. taskType: "interactive",
  1615. time: { created: 1, updated: 1 },
  1616. title: "parent",
  1617. version: "test",
  1618. } as SessionInfo;
  1619. const runtime = {
  1620. appendEvent: async () => undefined,
  1621. config: { agentName: "zcode-agent", mode: "build" },
  1622. createEvent: (_type: unknown, payload: Record<string, unknown>) => {
  1623. eventPayloads.push(payload);
  1624. return { payload };
  1625. },
  1626. getSessionModelSelection: () => ({ modelId: "glm-4-air", providerId: "glm" }),
  1627. rootTraceContext: { traceId: "trace_duplicate_child" },
  1628. sessionId: SESSION_ID,
  1629. sessionStore: {
  1630. async commitForkBundle() {
  1631. return { ...parentSession, id: existingChildId, parentID: SESSION_ID };
  1632. },
  1633. async getSession() {
  1634. return parentSession;
  1635. },
  1636. async messages() {
  1637. return [target];
  1638. },
  1639. } satisfies Partial<SessionStorePort>,
  1640. workingDirectory: "/workspace",
  1641. workspaceRoot: "/workspace",
  1642. };
  1643. const result = await forkConversationBeforeMessage.call(runtime as never, {
  1644. commandFact: {
  1645. parentSessionId: SESSION_ID,
  1646. sourceCommandId: "cmd-duplicate-child",
  1647. ack: {
  1648. commandId: "cmd-duplicate-child",
  1649. status: "accepted",
  1650. revisionAtDecision: 1,
  1651. result: {
  1652. type: "editUserQuery",
  1653. disposition: "fork",
  1654. sessionId: requestedChildId,
  1655. },
  1656. },
  1657. metadata: {},
  1658. },
  1659. forkedSessionId: requestedChildId,
  1660. goalBoundary: { kind: "none" },
  1661. initialInput: {
  1662. id: "queue_cmd-duplicate-child",
  1663. sessionID: requestedChildId,
  1664. kind: "sendText",
  1665. delivery: "startNow",
  1666. payload: { text: "edited" },
  1667. },
  1668. sourceCommandId: "cmd-duplicate-child",
  1669. targetMessageId: target.info.id,
  1670. targetProductTurnId: "turn-product",
  1671. targetTranscriptTurnId: "turn-runtime",
  1672. });
  1673. expect(result.forkedSessionId).toBe(existingChildId);
  1674. expect(eventPayloads).toContainEqual(
  1675. expect.objectContaining({ forkedSessionId: existingChildId }),
  1676. );
  1677. });
  1678. it("fork transcript 不按 compact boundary 截掉可见 tool/worklog 历史", () => {
  1679. const user = userMessage("msg_user" as MessageId, "真实用户输入", 1);
  1680. const toolAssistant = assistantMessage(
  1681. "msg_tool_assistant" as MessageId,
  1682. user.info.id,
  1683. "我先读取文件。",
  1684. 2,
  1685. );
  1686. toolAssistant.parts.push({
  1687. id: partId("tool_read"),
  1688. sessionID: SESSION_ID,
  1689. messageID: toolAssistant.info.id,
  1690. type: "tool",
  1691. callID: "toolu_read",
  1692. tool: "Read",
  1693. state: {
  1694. status: "completed",
  1695. input: { file_path: "/tmp/demo.txt" },
  1696. output: "demo",
  1697. title: "Read",
  1698. },
  1699. } as MessagePart);
  1700. const compact = compactSummaryMessage("msg_compact" as MessageId, 3);
  1701. const finalAssistant = assistantMessage("msg_final" as MessageId, user.info.id, "最终回复", 4);
  1702. const parentMessages = [user, toolAssistant, compact, finalAssistant];
  1703. expect(activeSessionMessages(parentMessages).map((message) => message.info.id)).toEqual([
  1704. compact.info.id,
  1705. finalAssistant.info.id,
  1706. ]);
  1707. const forkSourceMessages = activeForkTranscriptMessages(parentMessages);
  1708. const targetIndex = forkSourceMessages.findIndex(
  1709. (message) => message.info.id === finalAssistant.info.id,
  1710. );
  1711. const forkHistoryMessages = buildForkHistoryMessages(
  1712. parentMessages,
  1713. forkSourceMessages,
  1714. targetIndex,
  1715. targetIndex + 1,
  1716. );
  1717. expect(forkHistoryMessages.map((message) => message.info.id)).toEqual([
  1718. user.info.id,
  1719. toolAssistant.info.id,
  1720. compact.info.id,
  1721. finalAssistant.info.id,
  1722. ]);
  1723. expect(
  1724. forkHistoryMessages
  1725. .flatMap((message) => message.parts)
  1726. .some((part) => part.type === "tool" && part.tool === "Read"),
  1727. ).toBe(true);
  1728. });
  1729. it("fork transcript 保留 rewind active branch 但不按 compact 截断", () => {
  1730. const firstUser = userMessage("msg_first_user" as MessageId, "第一轮", 1);
  1731. const rewoundUser = userMessage("msg_rewound_user" as MessageId, "被编辑的旧轮次", 2);
  1732. const rewoundAssistant = assistantMessage(
  1733. "msg_rewound_assistant" as MessageId,
  1734. rewoundUser.info.id,
  1735. "旧回复",
  1736. 3,
  1737. );
  1738. const editedUser = userMessage("msg_edited_user" as MessageId, "编辑后的新轮次", 4);
  1739. const editedCompact = compactSummaryMessage("msg_edited_compact" as MessageId, 5);
  1740. const editedAssistant = assistantMessage(
  1741. "msg_edited_assistant" as MessageId,
  1742. editedUser.info.id,
  1743. "新回复",
  1744. 6,
  1745. );
  1746. const forkSourceMessages = activeForkTranscriptMessages(
  1747. [firstUser, rewoundUser, rewoundAssistant, editedUser, editedCompact, editedAssistant],
  1748. {
  1749. rewindCreatedMessageId: editedUser.info.id,
  1750. rewindKeptMessageIds: [firstUser.info.id],
  1751. rewindTargetMessageId: rewoundUser.info.id,
  1752. },
  1753. );
  1754. expect(forkSourceMessages.map((message) => message.info.id)).toEqual([
  1755. firstUser.info.id,
  1756. editedUser.info.id,
  1757. editedCompact.info.id,
  1758. editedAssistant.info.id,
  1759. ]);
  1760. });
  1761. it("fork goal state 只复制 child 历史里的 verifier 并 remap anchor", async () => {
  1762. const forkedSessionId = "sess_child" as SessionId;
  1763. const parentTarget: SessionGoal = {
  1764. activeInputId: "input_parent",
  1765. activeRunLastSeenAtMs: 950,
  1766. activeRunStartedAtMs: 900,
  1767. objective: "完成四个 checkpoint",
  1768. sessionID: SESSION_ID,
  1769. status: "complete",
  1770. summaryTitle: "checkpoint goal",
  1771. targetID: "target_goal_1",
  1772. time: { created: 1, updated: 100 },
  1773. timeUsedSeconds: 12,
  1774. tokenBudget: 1000,
  1775. tokensUsed: 120,
  1776. };
  1777. const parentEntries = [
  1778. goalVerificationEntry("entry_1", "msg_checkpoint_1", 1, false),
  1779. goalVerificationEntry("entry_2", "msg_checkpoint_2", 2, false),
  1780. goalVerificationEntry("entry_3", "msg_checkpoint_3", 3, false),
  1781. ];
  1782. const savedEntries: SessionEntryInfo[] = [];
  1783. let clonedTarget: SessionGoal | null = null;
  1784. const store = {
  1785. async readTarget(input: { sessionID: SessionId }) {
  1786. return input.sessionID === SESSION_ID ? parentTarget : clonedTarget;
  1787. },
  1788. async sessionEntries() {
  1789. return parentEntries;
  1790. },
  1791. async saveSessionEntry(input: SessionEntryInfo) {
  1792. savedEntries.push(input);
  1793. },
  1794. async cloneTargetForFork(input: {
  1795. sessionID: SessionId;
  1796. source: SessionGoal;
  1797. status?: SessionGoal["status"];
  1798. }) {
  1799. clonedTarget = {
  1800. ...input.source,
  1801. activeInputId: null,
  1802. activeRunLastSeenAtMs: null,
  1803. activeRunStartedAtMs: null,
  1804. sessionID: input.sessionID,
  1805. status: input.status ?? input.source.status,
  1806. };
  1807. return clonedTarget;
  1808. },
  1809. } as unknown as SessionStorePort;
  1810. await copyGoalStateForFork.call(
  1811. {
  1812. logger: undefined,
  1813. sessionId: SESSION_ID,
  1814. sessionStore: store,
  1815. } as never,
  1816. {
  1817. forkedSessionId,
  1818. messageIdMap: new Map<MessageId, MessageId>([
  1819. ["msg_checkpoint_1" as MessageId, "msg_child_checkpoint_1" as MessageId],
  1820. ["msg_checkpoint_2" as MessageId, "msg_child_checkpoint_2" as MessageId],
  1821. ]),
  1822. traceContext: {} as TraceContext,
  1823. },
  1824. );
  1825. expect(clonedTarget).toMatchObject({
  1826. activeInputId: null,
  1827. activeRunLastSeenAtMs: null,
  1828. activeRunStartedAtMs: null,
  1829. sessionID: forkedSessionId,
  1830. status: "active",
  1831. targetID: parentTarget.targetID,
  1832. });
  1833. expect(savedEntries.map((entry) => entry.sessionID)).toEqual([
  1834. forkedSessionId,
  1835. forkedSessionId,
  1836. ]);
  1837. expect(
  1838. savedEntries.map(
  1839. (entry) =>
  1840. (entry.data as { payload: { anchorAssistantMessageId: string } }).payload
  1841. .anchorAssistantMessageId,
  1842. ),
  1843. ).toEqual(["msg_child_checkpoint_1", "msg_child_checkpoint_2"]);
  1844. });
  1845. it("stable fork 只使用 resolver 给出的 goal 快照与 verifier entry 边界", async () => {
  1846. const forkedSessionId = "sess_stable_goal_child" as SessionId;
  1847. const currentParentTarget: SessionGoal = {
  1848. activeInputId: "input_new",
  1849. activeRunLastSeenAtMs: 200,
  1850. activeRunStartedAtMs: 190,
  1851. objective: "fork 点之后的新目标",
  1852. sessionID: SESSION_ID,
  1853. status: "active",
  1854. targetID: "target_new",
  1855. time: { created: 180, updated: 200 },
  1856. timeUsedSeconds: 1,
  1857. tokensUsed: 1,
  1858. };
  1859. const forkPointTarget: SessionGoal = {
  1860. activeInputId: null,
  1861. activeRunLastSeenAtMs: null,
  1862. activeRunStartedAtMs: null,
  1863. objective: "fork 点目标快照",
  1864. sessionID: SESSION_ID,
  1865. status: "complete",
  1866. targetID: "target_at_fork",
  1867. time: { created: 1, updated: 80 },
  1868. timeUsedSeconds: 8,
  1869. tokensUsed: 80,
  1870. };
  1871. const entries = [
  1872. goalVerificationEntry("entry_before", "msg_checkpoint_1", 1, true),
  1873. goalVerificationEntry("entry_after", "msg_checkpoint_2", 2, false),
  1874. ];
  1875. // helper 默认 target_goal_1;fork 点快照测试需要两个 entry 都属于显式 target。
  1876. for (const entry of entries) {
  1877. const data = entry.data as { payload: Record<string, unknown> };
  1878. data.payload.targetId = "target_at_fork";
  1879. }
  1880. const savedEntries: SessionEntryInfo[] = [];
  1881. let clonedTarget: SessionGoal | null = null;
  1882. const store = {
  1883. async readTarget() {
  1884. return currentParentTarget;
  1885. },
  1886. async sessionEntries() {
  1887. return entries;
  1888. },
  1889. async saveSessionEntry(input: SessionEntryInfo) {
  1890. savedEntries.push(input);
  1891. },
  1892. async cloneTargetForFork(input: {
  1893. sessionID: SessionId;
  1894. source: SessionGoal;
  1895. status?: SessionGoal["status"];
  1896. }) {
  1897. clonedTarget = {
  1898. ...input.source,
  1899. sessionID: input.sessionID,
  1900. status: input.status ?? input.source.status,
  1901. };
  1902. return clonedTarget;
  1903. },
  1904. } as unknown as SessionStorePort;
  1905. await copyGoalStateForFork.call(
  1906. {
  1907. logger: undefined,
  1908. sessionId: SESSION_ID,
  1909. sessionStore: store,
  1910. } as never,
  1911. {
  1912. forkedSessionId,
  1913. goalBoundary: {
  1914. kind: "snapshot",
  1915. target: forkPointTarget,
  1916. verificationEntryIds: ["entry_before"],
  1917. },
  1918. messageIdMap: new Map<MessageId, MessageId>([
  1919. ["msg_checkpoint_1" as MessageId, "msg_child_checkpoint_1" as MessageId],
  1920. ]),
  1921. traceContext: {} as TraceContext,
  1922. },
  1923. );
  1924. expect(clonedTarget).toMatchObject({
  1925. objective: "fork 点目标快照",
  1926. sessionID: forkedSessionId,
  1927. status: "complete",
  1928. targetID: "target_at_fork",
  1929. });
  1930. expect(savedEntries).toHaveLength(1);
  1931. expect(savedEntries[0]?.id).not.toBe("entry_after");
  1932. });
  1933. it("stable fork goal boundary=none 时不复制 parent 当前 target", async () => {
  1934. let readTargetCount = 0;
  1935. let cloneTargetCount = 0;
  1936. const store = {
  1937. async readTarget() {
  1938. readTargetCount += 1;
  1939. return {};
  1940. },
  1941. async cloneTargetForFork() {
  1942. cloneTargetCount += 1;
  1943. },
  1944. } as unknown as SessionStorePort;
  1945. await copyGoalStateForFork.call(
  1946. {
  1947. logger: undefined,
  1948. sessionId: SESSION_ID,
  1949. sessionStore: store,
  1950. } as never,
  1951. {
  1952. forkedSessionId: "sess_no_goal_child" as SessionId,
  1953. goalBoundary: { kind: "none" },
  1954. messageIdMap: new Map(),
  1955. traceContext: {} as TraceContext,
  1956. },
  1957. );
  1958. expect(readTargetCount).toBe(0);
  1959. expect(cloneTargetCount).toBe(0);
  1960. });
  1961. it("stable fork verifier boundary 引用缺失 entry 时明确失败", async () => {
  1962. const target: SessionGoal = {
  1963. activeInputId: null,
  1964. activeRunLastSeenAtMs: null,
  1965. activeRunStartedAtMs: null,
  1966. objective: "目标",
  1967. sessionID: SESSION_ID,
  1968. status: "active",
  1969. targetID: "target_at_fork",
  1970. time: { created: 1, updated: 1 },
  1971. timeUsedSeconds: 0,
  1972. tokensUsed: 0,
  1973. };
  1974. const store = {
  1975. async sessionEntries() {
  1976. return [];
  1977. },
  1978. async saveSessionEntry() {},
  1979. async cloneTargetForFork() {},
  1980. } as unknown as SessionStorePort;
  1981. await expect(
  1982. copyGoalStateForFork.call(
  1983. {
  1984. logger: undefined,
  1985. sessionId: SESSION_ID,
  1986. sessionStore: store,
  1987. } as never,
  1988. {
  1989. forkedSessionId: "sess_missing_goal_entry" as SessionId,
  1990. goalBoundary: {
  1991. kind: "snapshot",
  1992. target,
  1993. verificationEntryIds: ["missing-entry"],
  1994. },
  1995. messageIdMap: new Map(),
  1996. traceContext: {} as TraceContext,
  1997. },
  1998. ),
  1999. ).rejects.toThrow(/references missing entries/);
  2000. });
  2001. it("fork goal status 只在 copied verifier passed 后保持 complete", () => {
  2002. expect(
  2003. deriveForkedGoalStatusFromCopiedVerifications("complete", [
  2004. {
  2005. goalIteration: 4,
  2006. status: "completed",
  2007. targetId: "target_goal_1",
  2008. verification: { nextAction: null, passed: true, reason: "done" },
  2009. verificationId: "verify_4",
  2010. },
  2011. ]),
  2012. ).toBe("complete");
  2013. expect(
  2014. deriveForkedGoalStatusFromCopiedVerifications("complete", [
  2015. {
  2016. goalIteration: 2,
  2017. status: "completed",
  2018. targetId: "target_goal_1",
  2019. verification: { nextAction: "继续", passed: false, reason: "not yet" },
  2020. verificationId: "verify_2",
  2021. },
  2022. ]),
  2023. ).toBe("active");
  2024. });
  2025. it("补回 compact active branch 中被隐藏的 assistant parent user", () => {
  2026. const user = userMessage("msg_user" as MessageId, "真实用户输入", 1);
  2027. const compact = compactSummaryMessage("msg_compact" as MessageId, 2);
  2028. const assistant = assistantMessage("msg_assistant" as MessageId, user.info.id, "最终回复", 3);
  2029. const parentMessages = [user, compact, assistant];
  2030. const forkSourceMessages = activeSessionMessages(parentMessages);
  2031. expect(forkSourceMessages.map((message) => message.info.id)).toEqual([
  2032. compact.info.id,
  2033. assistant.info.id,
  2034. ]);
  2035. const forkHistoryMessages = buildForkHistoryMessages(parentMessages, forkSourceMessages, 1, 2);
  2036. expect(forkHistoryMessages.map((message) => message.info.id)).toEqual([
  2037. user.info.id,
  2038. compact.info.id,
  2039. assistant.info.id,
  2040. ]);
  2041. expect(activeSessionMessages(forkHistoryMessages).map((message) => message.info.id)).toEqual([
  2042. compact.info.id,
  2043. assistant.info.id,
  2044. ]);
  2045. });
  2046. });