stable-fork-target.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { MessageWithParts, SessionGoal, SessionStorePort } from "@zcode/contracts";
  3. import { getConversationModelOnlyTurnTriggerSource } from "@zcode/shared";
  4. import { ProductProjection } from "../src/zcode-protocol-v4/product-projection.js";
  5. import { synthesizeEventsFromMessages } from "../src/zcode-protocol-v4/transcript-hydration.js";
  6. import { resolveStableForkTargetFromTranscript } from "../src/zcode-protocol-v4/stable-fork-target.js";
  7. function message(info: Record<string, unknown>): MessageWithParts {
  8. return { info: { sessionID: "s1", ...info }, parts: [] } as unknown as MessageWithParts;
  9. }
  10. function store(target: SessionGoal | null = null): SessionStorePort {
  11. return {
  12. readTarget: vi.fn().mockResolvedValue(target),
  13. saveMessage: vi.fn(),
  14. sessionEntries: vi.fn().mockResolvedValue([]),
  15. } as unknown as SessionStorePort;
  16. }
  17. const candidate = {
  18. productTurnId: "product-1",
  19. transcriptTurnId: "runtime-1",
  20. startMessageId: "user-1",
  21. boundaryMessageId: "assistant-2",
  22. };
  23. describe("resolveStableForkTargetFromTranscript", () => {
  24. it.each([
  25. ["background_task", "task_notification_steer"],
  26. ["subagent_message", "subagent_reply_steer"],
  27. ])("FX14:%s 轮内通知冷恢复保留原轮与持久 fork anchor", async (source, inputPresentation) => {
  28. const messages = [
  29. message({ id: "user-1", role: "user", time: { created: 1 } }),
  30. message({
  31. id: "assistant-1",
  32. role: "assistant",
  33. parentID: "user-1",
  34. time: { created: 2, completed: 3 },
  35. }),
  36. message({
  37. id: "notification",
  38. role: "user",
  39. time: { created: 4 },
  40. source,
  41. synthetic: true,
  42. visibility: "model-only",
  43. metadata: { inputPresentation },
  44. }),
  45. message({
  46. id: "assistant-2",
  47. role: "assistant",
  48. parentID: "user-1",
  49. time: { created: 5, completed: 6 },
  50. anchor: {
  51. turnId: "runtime-1",
  52. productTurnId: "user-1",
  53. orderedMessageIds: ["user-1", "assistant-1", "notification", "assistant-2"],
  54. boundaryMessageId: "assistant-2",
  55. goalBoundary: { kind: "none" },
  56. },
  57. }),
  58. ];
  59. for (const entry of messages) {
  60. entry.parts = [
  61. {
  62. id: `${entry.info.id}-text`,
  63. sessionID: "s1",
  64. messageID: entry.info.id,
  65. type: "text",
  66. text: entry.info.id,
  67. },
  68. ] as MessageWithParts["parts"];
  69. }
  70. const projection = new ProductProjection("s1", "cold");
  71. projection.beginHydrationReplay();
  72. for (const event of synthesizeEventsFromMessages(messages, { sessionId: "s1" })) {
  73. projection.applyHydrationEvent(event);
  74. }
  75. projection.completeHydrationReplay();
  76. const rows = projection.getSnapshot().rows.window;
  77. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(1);
  78. expect(rows.filter((row) => row.kind === "turnHeader")).toHaveLength(1);
  79. const assistant = rows.find((row) => row.kind === "assistantText" && row.actions?.canFork);
  80. expect(assistant?.productTurnId).toBe("user-1");
  81. const resolved = projection.resolveStableForkCandidate(assistant!.rowId);
  82. expect(resolved.ok).toBe(true);
  83. if (!resolved.ok) throw new Error(resolved.reasonCode);
  84. expect(resolved.candidate.boundaryMessageId).toBe("assistant-2");
  85. const sessionStore = store();
  86. await expect(
  87. resolveStableForkTargetFromTranscript({
  88. candidate: resolved.candidate,
  89. messages,
  90. store: sessionStore,
  91. }),
  92. ).resolves.toMatchObject({
  93. ok: true,
  94. target: {
  95. productTurnId: "user-1",
  96. orderedMessageIds: messages.map((entry) => entry.info.id),
  97. },
  98. });
  99. expect(sessionStore.saveMessage).not.toHaveBeenCalled();
  100. });
  101. it.each([
  102. ["task_notification_steer", "background_task", null],
  103. ["subagent_reply_steer", "subagent_message", null],
  104. ["task_notification", "background_task", "background_task"],
  105. ["subagent_reply", "subagent_message", "subagent_message"],
  106. [undefined, "background_task", "background_task"],
  107. ["future-presentation", "background_task", "background_task"],
  108. [undefined, "goal-continuation", "goal-continuation"],
  109. ])("FX14:持久标记 %s 的轮边界兼容", (inputPresentation, source, expected) => {
  110. const info = { role: "user", synthetic: true, visibility: "model-only", source };
  111. const metadata = { inputPresentation };
  112. expect(getConversationModelOnlyTurnTriggerSource({ info: { ...info, metadata } })).toBe(
  113. expected,
  114. );
  115. expect(
  116. getConversationModelOnlyTurnTriggerSource({ info, parts: [{ type: "text", metadata }] }),
  117. ).toBe(expected);
  118. });
  119. it("FX14:message 标记优先于 part,轮内 legacy 通知文本不能另开轮", () => {
  120. expect(
  121. getConversationModelOnlyTurnTriggerSource({
  122. info: {
  123. role: "user",
  124. synthetic: true,
  125. visibility: "model-only",
  126. metadata: { inputPresentation: "task_notification_steer" },
  127. },
  128. parts: [{ type: "text", text: "<task-notification>done</task-notification>" }],
  129. }),
  130. ).toBeNull();
  131. expect(
  132. getConversationModelOnlyTurnTriggerSource({
  133. info: {
  134. role: "user",
  135. source: "background_task",
  136. metadata: { inputPresentation: "task_notification" },
  137. },
  138. parts: [{ type: "text", metadata: { inputPresentation: "task_notification_steer" } }],
  139. }),
  140. ).toBe("background_task");
  141. });
  142. it("E10/FX08:fallback 按 user→tool→final assistant raw 顺序固定 logical turn 并补写 anchor", async () => {
  143. const sessionStore = store();
  144. const messages = [
  145. message({ id: "user-1", role: "user", anchor: { turnId: "runtime-1" } }),
  146. message({ id: "assistant-1", role: "assistant", parentID: "user-1" }),
  147. message({ id: "tool-1", role: "user", synthetic: true }),
  148. message({
  149. id: "assistant-2",
  150. role: "assistant",
  151. parentID: "user-1",
  152. anchor: { turnId: "runtime-1" },
  153. }),
  154. message({ id: "user-2", role: "user" }),
  155. ];
  156. await expect(
  157. resolveStableForkTargetFromTranscript({ candidate, messages, store: sessionStore }),
  158. ).resolves.toEqual({
  159. ok: true,
  160. target: {
  161. productTurnId: "product-1",
  162. transcriptTurnId: "runtime-1",
  163. orderedMessageIds: ["user-1", "assistant-1", "tool-1", "assistant-2"],
  164. boundaryMessageId: "assistant-2",
  165. },
  166. goalBoundary: { kind: "none" },
  167. });
  168. expect(sessionStore.saveMessage).toHaveBeenCalledWith(
  169. expect.objectContaining({
  170. id: "assistant-2",
  171. anchor: expect.objectContaining({
  172. productTurnId: "product-1",
  173. boundaryMessageId: "assistant-2",
  174. orderedMessageIds: ["user-1", "assistant-1", "tool-1", "assistant-2"],
  175. goalBoundary: { kind: "none" },
  176. }),
  177. }),
  178. );
  179. });
  180. it("持久 anchor 优先;边界损坏或 fallback 含第二个 real user 时拒绝 ambiguous", async () => {
  181. const sessionStore = store();
  182. const persisted = [
  183. message({ id: "user-1", role: "user" }),
  184. message({
  185. id: "assistant-2",
  186. role: "assistant",
  187. parentID: "user-1",
  188. anchor: {
  189. turnId: "runtime-1",
  190. productTurnId: "product-1",
  191. orderedMessageIds: ["user-1", "assistant-2"],
  192. boundaryMessageId: "assistant-2",
  193. },
  194. }),
  195. ];
  196. await expect(
  197. resolveStableForkTargetFromTranscript({
  198. candidate,
  199. messages: persisted,
  200. store: sessionStore,
  201. }),
  202. ).resolves.toMatchObject({ ok: true, goalBoundary: { kind: "none" } });
  203. expect(sessionStore.saveMessage).toHaveBeenCalledWith(
  204. expect.objectContaining({
  205. anchor: expect.objectContaining({ goalBoundary: { kind: "none" } }),
  206. }),
  207. );
  208. vi.mocked(sessionStore.saveMessage).mockClear();
  209. const ambiguous = [
  210. message({ id: "user-1", role: "user" }),
  211. message({ id: "user-x", role: "user" }),
  212. message({ id: "assistant-2", role: "assistant", parentID: "user-1" }),
  213. ];
  214. await expect(
  215. resolveStableForkTargetFromTranscript({
  216. candidate,
  217. messages: ambiguous,
  218. store: sessionStore,
  219. }),
  220. ).resolves.toEqual({ ok: false, reasonCode: "guard.forkTargetAmbiguous" });
  221. });
  222. it("新数据可由 candidate 补 productTurnId,并返回持久 goal snapshot", async () => {
  223. const sessionStore = store();
  224. const goal: SessionGoal = {
  225. sessionID: "s1" as never,
  226. targetID: "target-1",
  227. objective: "goal at fork",
  228. summaryTitle: null,
  229. status: "active",
  230. tokenBudget: null,
  231. tokensUsed: 8,
  232. timeUsedSeconds: 2,
  233. time: { created: 1, updated: 2 },
  234. };
  235. const messages = [
  236. message({ id: "user-1", role: "user" }),
  237. message({
  238. id: "assistant-2",
  239. role: "assistant",
  240. parentID: "user-1",
  241. anchor: {
  242. turnId: "runtime-1",
  243. orderedMessageIds: ["user-1", "assistant-2"],
  244. boundaryMessageId: "assistant-2",
  245. goalBoundary: {
  246. kind: "snapshot",
  247. target: goal,
  248. verificationEntryIds: ["verify-1"],
  249. },
  250. },
  251. }),
  252. ];
  253. await expect(
  254. resolveStableForkTargetFromTranscript({ candidate, messages, store: sessionStore }),
  255. ).resolves.toEqual({
  256. ok: true,
  257. target: {
  258. productTurnId: "product-1",
  259. transcriptTurnId: "runtime-1",
  260. orderedMessageIds: ["user-1", "assistant-2"],
  261. boundaryMessageId: "assistant-2",
  262. },
  263. goalBoundary: {
  264. kind: "snapshot",
  265. target: goal,
  266. verificationEntryIds: ["verify-1"],
  267. },
  268. });
  269. expect(sessionStore.saveMessage).toHaveBeenCalledWith(
  270. expect.objectContaining({
  271. anchor: expect.objectContaining({ productTurnId: "product-1" }),
  272. }),
  273. );
  274. });
  275. it("legacy boundary 在 parent 当前仍有 goal 时拒绝冒充 fork 点快照", async () => {
  276. const currentGoal = {
  277. sessionID: "s1",
  278. targetID: "target-current",
  279. objective: "future goal",
  280. summaryTitle: null,
  281. status: "complete",
  282. tokenBudget: null,
  283. tokensUsed: 20,
  284. timeUsedSeconds: 10,
  285. time: { created: 1, updated: 20 },
  286. } as SessionGoal;
  287. const messages = [
  288. message({ id: "user-1", role: "user" }),
  289. message({ id: "assistant-2", role: "assistant", parentID: "user-1" }),
  290. ];
  291. await expect(
  292. resolveStableForkTargetFromTranscript({ candidate, messages, store: store(currentGoal) }),
  293. ).resolves.toEqual({ ok: false, reasonCode: "guard.forkTargetAmbiguous" });
  294. });
  295. });