product-projection-session-locks.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // fork / 文件撤销的 session 锁走 availability,不写进行级 actions
  2. // (docs/v4-refactor/02-projection.md「会话锁与行级资格」)。
  3. //
  4. // 钉住五件事:
  5. // 1. 轮开始/结束、compact 开始/结束只翻转 availability,历史行不 upsert(长会话不再 fan-out);
  6. // 命令校验仍按“行级资格 && session 锁”拒绝。
  7. // 2. 空闲时的 pending interaction(workspaceHookReview)同样锁文件撤销。
  8. // 3. availability 从归约后的完整状态派生:同一事件里 pendingInteractions 与 control 由不同 patch
  9. // 改写(带待处理权限请求时取消),结果不能读到另一半的旧值。
  10. // 4. cold batch hydration 结束时 availability 收敛到最终状态。
  11. // 5. availability 按值比较:值不变的事件不发 availability patch,即使它改了 availability 的输入
  12. // (运行中出现权限请求)。否则每个事件多发一条 state.updated 并递增 revision。
  13. import { describe, expect, it } from "vitest";
  14. import {
  15. SessionEventType,
  16. type EventId,
  17. type SessionEvent,
  18. type SessionEventType as SessionEventTypeUnion,
  19. type SessionId,
  20. type TraceId,
  21. type TurnId,
  22. } from "@zcode/contracts";
  23. import type {
  24. ActionAvailability,
  25. ConversationDelta,
  26. ConversationRow,
  27. ConversationRowTarget,
  28. } from "@zcode/shared/zcode-protocol-v4";
  29. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  30. const BASE_TIMESTAMP_MS = 1_700_000_000_000;
  31. const USAGE = { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 };
  32. const LIVE_TURN_ID = "turn-live";
  33. const ALLOWED: ActionAvailability = { allowed: true };
  34. const COMPACT_LOCK: ActionAvailability = { allowed: false, reasonCode: "compactOperationLock" };
  35. const REWIND_LOCK: ActionAvailability = { allowed: false, reasonCode: "fileRewindUnavailable" };
  36. const ACTION_UNAVAILABLE = {
  37. ok: false,
  38. status: "rejected",
  39. reasonCode: "guard.actionUnavailable",
  40. } as const;
  41. class EventLog {
  42. private seq = 0;
  43. readonly events: SessionEvent[] = [];
  44. push(type: SessionEventTypeUnion, payload: unknown, turnId?: string): SessionEvent {
  45. this.seq += 1;
  46. const event: SessionEvent = {
  47. id: `event-${this.seq}` as EventId,
  48. sessionId: "session-1" as SessionId,
  49. turnId: turnId as TurnId | undefined,
  50. type,
  51. timestamp: new Date(BASE_TIMESTAMP_MS + this.seq * 1000),
  52. traceId: "trace-1" as TraceId,
  53. sequenceNumber: this.seq,
  54. payload,
  55. };
  56. this.events.push(event);
  57. return event;
  58. }
  59. }
  60. function pushStartedTurn(log: EventLog, turnId: string, turn: number): void {
  61. log.push(
  62. SessionEventType.TurnStarted,
  63. { turnNumber: turn, input: `问题 ${turn}`, messageId: `message-user-${turn}` },
  64. turnId,
  65. );
  66. log.push(
  67. SessionEventType.ModelStreaming,
  68. {
  69. kind: "text_start",
  70. delta: "",
  71. done: false,
  72. assistantMessageId: `message-assistant-${turn}`,
  73. },
  74. turnId,
  75. );
  76. log.push(
  77. SessionEventType.ModelStreaming,
  78. { kind: "text_delta", delta: `回答 ${turn}`, done: false },
  79. turnId,
  80. );
  81. }
  82. function pushTurnEnd(log: EventLog, turnId: string, turn: number): void {
  83. log.push(
  84. SessionEventType.ModelComplete,
  85. {
  86. content: `回答 ${turn}`,
  87. stopReason: "end_turn",
  88. querySource: "main_turn",
  89. contextWindow: 200_000,
  90. usage: USAGE,
  91. fileChanges: {
  92. files: 1,
  93. additions: 2,
  94. deletions: 1,
  95. items: [{ path: `/work/${turn}.ts`, additions: 2, deletions: 1, writeCount: 1 }],
  96. },
  97. },
  98. turnId,
  99. );
  100. log.push(
  101. SessionEventType.TurnComplete,
  102. {
  103. response: `回答 ${turn}`,
  104. tokenCount: 1,
  105. toolCallCount: 0,
  106. duration: 1,
  107. resultType: "success",
  108. },
  109. turnId,
  110. );
  111. }
  112. /** 每轮都改过文件、都成功结束:历史 assistant 带 canFork,历史 turnHeader 带 canRewindFiles。 */
  113. function historyLog(turns: number): EventLog {
  114. const log = new EventLog();
  115. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  116. for (let turn = 1; turn <= turns; turn += 1) {
  117. pushStartedTurn(log, `turn-${turn}`, turn);
  118. pushTurnEnd(log, `turn-${turn}`, turn);
  119. }
  120. return log;
  121. }
  122. function replay(events: readonly SessionEvent[]): ProductProjection {
  123. const projection = new ProductProjection("session-1", "epoch-1");
  124. for (const event of events) projection.applyEvent(event);
  125. return projection;
  126. }
  127. function compactEvent(log: EventLog, type: "started" | "completed"): SessionEvent {
  128. const base = {
  129. operationId: "compact-1",
  130. messageId: "message-compact",
  131. trigger: "manual",
  132. display: "separator",
  133. };
  134. return type === "started"
  135. ? log.push(SessionEventType.CompactStarted, { ...base, status: "started" })
  136. : log.push(SessionEventType.CompactCompleted, {
  137. ...base,
  138. status: "completed",
  139. preCompactTokenCount: 150,
  140. postCompactTokenCount: 50,
  141. });
  142. }
  143. function targetOf(row: ConversationRow): ConversationRowTarget {
  144. return { rowId: row.rowId, entityId: row.entityId! };
  145. }
  146. /** 历史行 = live 轮开始前已存在的行(行的 turnId 是产品轮 id,不是 runtime turnId)。 */
  147. function rowIdsOf(projection: ProductProjection): ReadonlySet<number> {
  148. return new Set(projection.getSnapshot().rows.window.map((row) => row.rowId));
  149. }
  150. function historyRows(
  151. projection: ProductProjection,
  152. historyRowIds: ReadonlySet<number>,
  153. kind: "turnHeader" | "assistantText",
  154. ): ConversationRow[] {
  155. return projection
  156. .getSnapshot()
  157. .rows.window.filter((row) => row.kind === kind && historyRowIds.has(row.rowId));
  158. }
  159. /** 本事件里被 upsert 的历史行。 */
  160. function upsertedHistoryRowIds(
  161. deltas: readonly ConversationDelta[],
  162. historyRowIds: ReadonlySet<number>,
  163. ): number[] {
  164. return deltas.flatMap((delta) =>
  165. delta.op === "row.upserted" && historyRowIds.has(delta.row.rowId) ? [delta.row.rowId] : [],
  166. );
  167. }
  168. function availabilityPatches(deltas: readonly ConversationDelta[]): ConversationDelta[] {
  169. return deltas.filter(
  170. (delta) => delta.op === "state.updated" && delta.patch.availability !== undefined,
  171. );
  172. }
  173. function expectLocks(
  174. projection: ProductProjection,
  175. fork: ActionAvailability,
  176. rewindFiles: ActionAvailability,
  177. ): void {
  178. const { availability } = projection.getSnapshot();
  179. expect(availability.fork).toEqual(fork);
  180. expect(availability.rewindFiles).toEqual(rewindFiles);
  181. }
  182. /** 行级资格不随 session 锁翻转:每个历史轮的 assistant 仍 canFork、turnHeader 仍 canRewindFiles。 */
  183. function expectHistoryRowEligibility(
  184. projection: ProductProjection,
  185. historyRowIds: ReadonlySet<number>,
  186. turns: number,
  187. ): void {
  188. const assistants = historyRows(projection, historyRowIds, "assistantText");
  189. const headers = historyRows(projection, historyRowIds, "turnHeader");
  190. expect(assistants).toHaveLength(turns);
  191. expect(headers).toHaveLength(turns);
  192. expect(assistants.every((row) => row.actions?.canFork === true)).toBe(true);
  193. expect(headers.every((row) => row.actions?.canRewindFiles === true)).toBe(true);
  194. }
  195. describe("fork / 文件撤销的 session 锁走 availability", () => {
  196. it("轮开始/结束、compact 开始/结束只翻转 availability,历史行不 upsert", () => {
  197. const turns = 30;
  198. const log = historyLog(turns);
  199. const projection = replay(log.events);
  200. const history = rowIdsOf(projection);
  201. expectHistoryRowEligibility(projection, history, turns);
  202. expectLocks(projection, ALLOWED, ALLOWED);
  203. const header = historyRows(projection, history, "turnHeader")[0]!;
  204. const assistant = historyRows(projection, history, "assistantText")[0]!;
  205. const latestAssistant = historyRows(projection, history, "assistantText").at(-1)!;
  206. const latestHistoryRowIds = new Set(
  207. projection
  208. .getSnapshot()
  209. .rows.window.filter(
  210. (row) =>
  211. row.turnId === latestAssistant.turnId &&
  212. (row.kind === "userInput" || row.kind === "assistantText"),
  213. )
  214. .map((row) => row.rowId),
  215. );
  216. // 新轮开始:只有 canEdit / canRetry 从上一轮交给新轮(各一行),其余历史行不动。
  217. pushStartedTurn(log, LIVE_TURN_ID, turns + 1);
  218. const startEvents = log.events.slice(-3);
  219. const startUpserts = startEvents.flatMap((event) =>
  220. upsertedHistoryRowIds(projection.applyEvent(event), history),
  221. );
  222. expect(startUpserts.every((rowId) => latestHistoryRowIds.has(rowId))).toBe(true);
  223. expectHistoryRowEligibility(projection, history, turns);
  224. expectLocks(projection, ALLOWED, REWIND_LOCK);
  225. expect(projection.resolveRowActionTarget(targetOf(header), "applyFileRewind")).toEqual(
  226. ACTION_UNAVAILABLE,
  227. );
  228. expect(projection.resolveRowActionTarget(targetOf(assistant), "forkAssistant")).toMatchObject({
  229. ok: true,
  230. });
  231. pushTurnEnd(log, LIVE_TURN_ID, turns + 1);
  232. for (const event of log.events.slice(-2)) {
  233. expect(upsertedHistoryRowIds(projection.applyEvent(event), history)).toEqual([]);
  234. }
  235. expectLocks(projection, ALLOWED, ALLOWED);
  236. expect(projection.resolveRowActionTarget(targetOf(header), "applyFileRewind")).toMatchObject({
  237. ok: true,
  238. });
  239. const compactStartDeltas = projection.applyEvent(compactEvent(log, "started"));
  240. expect(upsertedHistoryRowIds(compactStartDeltas, history)).toEqual([]);
  241. expect(compactStartDeltas).toContainEqual({
  242. op: "state.updated",
  243. patch: expect.objectContaining({
  244. availability: expect.objectContaining({ fork: COMPACT_LOCK, rewindFiles: COMPACT_LOCK }),
  245. }),
  246. });
  247. expectHistoryRowEligibility(projection, history, turns);
  248. expectLocks(projection, COMPACT_LOCK, COMPACT_LOCK);
  249. expect(projection.resolveRowActionTarget(targetOf(header), "applyFileRewind")).toEqual(
  250. ACTION_UNAVAILABLE,
  251. );
  252. expect(projection.resolveRowActionTarget(targetOf(assistant), "forkAssistant")).toEqual(
  253. ACTION_UNAVAILABLE,
  254. );
  255. expect(
  256. upsertedHistoryRowIds(projection.applyEvent(compactEvent(log, "completed")), history),
  257. ).toEqual([]);
  258. expectHistoryRowEligibility(projection, history, turns);
  259. expectLocks(projection, ALLOWED, ALLOWED);
  260. expect(projection.resolveRowActionTarget(targetOf(assistant), "forkAssistant")).toMatchObject({
  261. ok: true,
  262. });
  263. });
  264. it("空闲时待审核的 workspace Hook 锁文件撤销,审核结束后解锁", () => {
  265. const log = historyLog(2);
  266. const projection = replay(log.events);
  267. const history = rowIdsOf(projection);
  268. const header = historyRows(projection, history, "turnHeader")[0]!;
  269. const request = {
  270. kind: "workspaceHookReview",
  271. reviewFlowId: "flow-1",
  272. generation: 1,
  273. interactionId: "interaction-hook",
  274. sessionId: "session-1",
  275. taskId: "session-1",
  276. runId: "run-1",
  277. workspaceIdentity: "local:/workspace",
  278. workspaceLabel: "workspace",
  279. bundleDigest: "a".repeat(64),
  280. createdAt: BASE_TIMESTAMP_MS + 1_000,
  281. deadlineAt: BASE_TIMESTAMP_MS + 601_000,
  282. sourceFiles: [],
  283. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  284. items: [
  285. {
  286. reviewItemId: "item-0",
  287. event: "SessionStart",
  288. matcher: "startup",
  289. type: "command",
  290. displayName: "SessionStart · startup",
  291. displayCommand: "echo project",
  292. sourcePath: ".zcode/config.json",
  293. resolvedTimeoutMs: 60_000,
  294. resolvedMaxOutputBytes: 32_768,
  295. executionMode: "foreground",
  296. configuredEnabled: true,
  297. editable: true,
  298. trustState: "pending_trust",
  299. },
  300. ],
  301. warningCode: "workspace_hooks_execute_code",
  302. } as const;
  303. const requested = projection.applyEvent(
  304. log.push(SessionEventType.WorkspaceHookReviewRequested, { request }),
  305. );
  306. expect(projection.getSnapshot().pendingInteractions).toHaveLength(1);
  307. expect(upsertedHistoryRowIds(requested, history)).toEqual([]);
  308. expect(projection.getSnapshot().control.activeWorks).toEqual([]);
  309. expectLocks(projection, ALLOWED, REWIND_LOCK);
  310. expect(projection.resolveRowActionTarget(targetOf(header), "applyFileRewind")).toEqual(
  311. ACTION_UNAVAILABLE,
  312. );
  313. projection.applyEvent(
  314. log.push(SessionEventType.WorkspaceHookReviewSettled, {
  315. interactionId: "interaction-hook",
  316. state: "resolved",
  317. }),
  318. );
  319. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  320. expectLocks(projection, ALLOWED, ALLOWED);
  321. });
  322. it("带待处理权限请求时取消本轮:同一事件清空 pendingInteractions 与 activeWorks 后解锁", () => {
  323. const log = historyLog(1);
  324. pushStartedTurn(log, LIVE_TURN_ID, 2);
  325. log.push(
  326. SessionEventType.ToolCallScheduled,
  327. {
  328. toolCallId: "tc-live",
  329. toolName: "bash",
  330. input: { command: "ls" },
  331. schedule: { parallelGroups: [["tc-live"]], executionOrder: ["tc-live"] },
  332. },
  333. LIVE_TURN_ID,
  334. );
  335. log.push(
  336. SessionEventType.PermissionRequested,
  337. {
  338. requestId: "req-live",
  339. toolCallId: "tc-live",
  340. toolName: "bash",
  341. riskLevel: "medium",
  342. reason: "Run shell command",
  343. input: { command: "ls" },
  344. },
  345. LIVE_TURN_ID,
  346. );
  347. const projection = replay(log.events);
  348. expect(projection.getSnapshot().pendingInteractions).toHaveLength(1);
  349. expectLocks(projection, ALLOWED, REWIND_LOCK);
  350. projection.applyEvent(
  351. log.push(
  352. SessionEventType.TurnComplete,
  353. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "cancelled" },
  354. LIVE_TURN_ID,
  355. ),
  356. );
  357. const snapshot = projection.getSnapshot();
  358. expect(snapshot.pendingInteractions).toEqual([]);
  359. expect(snapshot.control.activeWorks).toEqual([]);
  360. expectLocks(projection, ALLOWED, ALLOWED);
  361. });
  362. it("availability 值不变的事件不发 availability patch,即使改了它的输入", () => {
  363. const log = historyLog(1);
  364. const projection = replay(log.events);
  365. // 新轮开始:文件撤销被锁,availability 变化,恰好发一次。
  366. pushStartedTurn(log, LIVE_TURN_ID, 2);
  367. const startDeltas = log.events.slice(-3).flatMap((event) => projection.applyEvent(event));
  368. expect(availabilityPatches(startDeltas)).toHaveLength(1);
  369. expectLocks(projection, ALLOWED, REWIND_LOCK);
  370. // 运行中的工具生命周期与权限请求:后者改写 pendingInteractions,但 rewindFiles 已因
  371. // active work 锁定(同一 reasonCode),availability 值不变。
  372. const unchangedFrom = log.events.length;
  373. log.push(
  374. SessionEventType.ToolCallScheduled,
  375. {
  376. toolCallId: "tc-read",
  377. toolName: "Read",
  378. input: { file_path: "/work/a.ts" },
  379. schedule: { parallelGroups: [["tc-read"]], executionOrder: ["tc-read"] },
  380. },
  381. LIVE_TURN_ID,
  382. );
  383. log.push(
  384. SessionEventType.ToolCallStarted,
  385. { toolCallId: "tc-read", toolName: "Read", startedAt: new Date(BASE_TIMESTAMP_MS) },
  386. LIVE_TURN_ID,
  387. );
  388. log.push(
  389. SessionEventType.ToolCallResult,
  390. { toolCallId: "tc-read", result: { success: true, content: "ok" }, duration: 10 },
  391. LIVE_TURN_ID,
  392. );
  393. log.push(
  394. SessionEventType.ToolCallScheduled,
  395. {
  396. toolCallId: "tc-bash",
  397. toolName: "bash",
  398. input: { command: "ls" },
  399. schedule: { parallelGroups: [["tc-bash"]], executionOrder: ["tc-bash"] },
  400. },
  401. LIVE_TURN_ID,
  402. );
  403. log.push(
  404. SessionEventType.PermissionRequested,
  405. {
  406. requestId: "req-bash",
  407. toolCallId: "tc-bash",
  408. toolName: "bash",
  409. riskLevel: "medium",
  410. reason: "Run shell command",
  411. input: { command: "ls" },
  412. },
  413. LIVE_TURN_ID,
  414. );
  415. const unchangedDeltas = log.events
  416. .slice(unchangedFrom)
  417. .flatMap((event) => projection.applyEvent(event));
  418. expect(projection.getSnapshot().pendingInteractions).toHaveLength(1);
  419. expect(unchangedDeltas.some((delta) => delta.op === "row.upserted")).toBe(true);
  420. expect(availabilityPatches(unchangedDeltas)).toEqual([]);
  421. expectLocks(projection, ALLOWED, REWIND_LOCK);
  422. });
  423. it("cold batch hydration 结束时 availability 收敛到最终状态,行级资格不受锁影响", () => {
  424. const turns = 3;
  425. const log = historyLog(turns);
  426. compactEvent(log, "started");
  427. const projection = new ProductProjection("session-1", "epoch-1");
  428. projection.beginHydrationReplay();
  429. for (const event of log.events) projection.applyHydrationEvent(event);
  430. projection.completeHydrationReplay();
  431. expect(projection.getSnapshot().control.activeWorks).toEqual([
  432. expect.objectContaining({ kind: "compact" }),
  433. ]);
  434. expectLocks(projection, COMPACT_LOCK, COMPACT_LOCK);
  435. expectHistoryRowEligibility(projection, rowIdsOf(projection), turns);
  436. });
  437. });