session-fork.test.ts 68 KB

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