session-fork.test.ts 68 KB

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