session-fork.test.ts 87 KB

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