session-fork.test.ts 87 KB

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