session-fork-target-cwd.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // stable fork 到同一 workspace 下的受管 worktree(forkAssistant.targetCwd,docs/git/worktree.md §8.2)。
  2. // 只验证 core 的 child 构建合同:cwd 取目标值、workspaceID 沿用父会话、权限迁移、
  3. // fork 分隔标记后追加 worktree_creation、不带目标时行为不变。
  4. import { describe, expect, it } from "vitest";
  5. import type {
  6. MessageId,
  7. MessagePart,
  8. MessageWithParts,
  9. SessionId,
  10. SessionInfo,
  11. SessionStorePort,
  12. } from "@zcode/contracts";
  13. import { forkStableConversationAtMessage } from "../src/runtime/methods/session-fork.js";
  14. const SESSION_ID = "sess_target_ws_parent" as SessionId;
  15. const WORKTREE_CREATION = {
  16. path: "/workspace/worktrees/3f2a/source",
  17. sha: "9e6d2f72d4",
  18. ref: null,
  19. output: "Preparing worktree (detached HEAD 9e6d2f7)\n",
  20. };
  21. const SOURCE_DIRECTORY = "/workspace/source";
  22. const TARGET_DIRECTORY = "/workspace/worktrees/3f2a/source";
  23. function textPart(messageId: MessageId, text: string): MessagePart {
  24. return {
  25. id: `part_${messageId}` as MessagePart["id"],
  26. sessionID: SESSION_ID,
  27. messageID: messageId,
  28. type: "text",
  29. text,
  30. };
  31. }
  32. const user: MessageWithParts = {
  33. info: {
  34. id: "msg_target_ws_user" as MessageId,
  35. sessionID: SESSION_ID,
  36. role: "user",
  37. time: { created: 1 },
  38. agent: "zcode-agent",
  39. modelSelection: { modelId: "glm-4-air" as never, providerId: "glm" as never },
  40. tools: {},
  41. },
  42. parts: [textPart("msg_target_ws_user" as MessageId, "question")],
  43. };
  44. const assistant: MessageWithParts = {
  45. info: {
  46. id: "msg_target_ws_assistant" as MessageId,
  47. sessionID: SESSION_ID,
  48. role: "assistant",
  49. time: { created: 2, completed: 3 },
  50. parentID: "msg_target_ws_user" as MessageId,
  51. agent: "zcode-agent",
  52. cost: 0,
  53. mode: "build",
  54. modelId: "glm-4-air" as never,
  55. path: { cwd: SOURCE_DIRECTORY, root: SOURCE_DIRECTORY },
  56. providerId: "glm" as never,
  57. tokens: { cache: { read: 0, write: 0 }, input: 0, output: 0, reasoning: 0, total: 0 },
  58. },
  59. parts: [textPart("msg_target_ws_assistant" as MessageId, "answer")],
  60. };
  61. const target = {
  62. productTurnId: "product-target-ws",
  63. transcriptTurnId: "turn-target-ws",
  64. orderedMessageIds: [String(user.info.id), String(assistant.info.id)],
  65. boundaryMessageId: String(assistant.info.id),
  66. };
  67. function parentSession(): SessionInfo {
  68. return {
  69. directory: SOURCE_DIRECTORY,
  70. id: SESSION_ID,
  71. path: SOURCE_DIRECTORY,
  72. projectID: "workspace-source",
  73. slug: "parent-target-ws",
  74. taskType: "interactive",
  75. permission: {
  76. version: 1,
  77. scope: "session",
  78. mode: "build",
  79. allow: [{ toolName: "Edit", ruleContent: `${SOURCE_DIRECTORY}/src/a.ts` }],
  80. deny: [{ toolName: "Bash", ruleContent: "rm:*" }],
  81. },
  82. time: { created: 1, updated: 1 },
  83. title: "parent",
  84. version: "test",
  85. } as SessionInfo;
  86. }
  87. function forkRuntime(parent: SessionInfo) {
  88. const bundles: Array<Parameters<NonNullable<SessionStorePort["commitForkBundle"]>>[0]> = [];
  89. const runtime = {
  90. appendEvent: async () => undefined,
  91. config: { agentName: "zcode-agent", mode: "build" },
  92. createEvent: (_type: unknown, payload: Record<string, unknown>) => ({ payload }),
  93. getSessionModelSelection: () => ({ modelId: "glm-4-air", providerId: "glm" }),
  94. rootTraceContext: { traceId: "trace_target_workspace" },
  95. sessionId: SESSION_ID,
  96. sessionStore: {
  97. async commitForkBundle(bundle) {
  98. bundles.push(bundle);
  99. return bundle.child as SessionInfo;
  100. },
  101. async getSession() {
  102. return parent;
  103. },
  104. async messages() {
  105. return [user, assistant];
  106. },
  107. } satisfies Partial<SessionStorePort>,
  108. workingDirectory: parent.directory,
  109. workspaceRoot: parent.directory,
  110. };
  111. return { bundles, runtime };
  112. }
  113. describe("stable fork 到受管 worktree cwd", () => {
  114. it("child 的 id/directory/path/projectID 取目标值,workspaceID 沿用父会话,allow 规则不跨目录", async () => {
  115. const parent = parentSession();
  116. const parentPermissionBefore = structuredClone(parent.permission);
  117. const { bundles, runtime } = forkRuntime(parent);
  118. const result = await forkStableConversationAtMessage.call(runtime as never, {
  119. forkedSessionId: "sess_target_ws_child" as SessionId,
  120. goalBoundary: { kind: "none" },
  121. sourceCommandId: "cmd-target-ws",
  122. target,
  123. targetCwd: {
  124. directory: TARGET_DIRECTORY,
  125. // bootstrap 按映射回源仓库的路径派生,与父项目共用权限记录(§6.6.3)。
  126. projectID: "workspace-source" as never,
  127. worktreeCreation: WORKTREE_CREATION,
  128. },
  129. });
  130. expect(result.forkedSessionId).toBe("sess_target_ws_child");
  131. // conversation-only:不回退、不恢复任何 checkpoint。
  132. expect(result.restoredFiles).toEqual([]);
  133. const child = bundles[0]!.child;
  134. expect(child).toMatchObject({
  135. id: "sess_target_ws_child",
  136. parentID: SESSION_ID,
  137. taskType: "fork",
  138. directory: TARGET_DIRECTORY,
  139. path: TARGET_DIRECTORY,
  140. projectID: "workspace-source",
  141. });
  142. expect(child.workspaceID).toBeUndefined();
  143. // allow 规则绑定父目录路径,不进入 child;deny 只会收紧,mode/scope/version 与路径无关。
  144. expect(child.permission).toEqual({
  145. version: 1,
  146. scope: "session",
  147. mode: "build",
  148. deny: [{ toolName: "Bash", ruleContent: "rm:*" }],
  149. });
  150. expect(parent.permission).toEqual(parentPermissionBefore);
  151. expect(bundles[0]!.commandFact.ack.result).toEqual({
  152. type: "forkAssistant",
  153. sessionId: "sess_target_ws_child",
  154. });
  155. const copiedTexts = bundles[0]!.messages.flatMap((message) =>
  156. message.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])),
  157. );
  158. expect(copiedTexts).toEqual(expect.arrayContaining(["question", "answer"]));
  159. expect(bundles[0]!.messages.every((message) => message.info.sessionID === child.id)).toBe(true);
  160. // fork 分隔标记之后追加 "已创建 worktree",与 session_fork 同一条宿主消息。
  161. const timelineParts = bundles[0]!.messages.flatMap((message) =>
  162. message.parts.flatMap((part) => (part.type === "timeline" ? [part] : [])),
  163. );
  164. expect(timelineParts.map((part) => part.timelineType)).toEqual([
  165. "session_fork",
  166. "worktree_creation",
  167. ]);
  168. expect(timelineParts[1]).toMatchObject({
  169. display: "worklog",
  170. worktreeCreation: WORKTREE_CREATION,
  171. });
  172. expect(timelineParts[0]!.messageID).toBe(timelineParts[1]!.messageID);
  173. });
  174. it("不带 targetCwd 时 child 原样沿用父会话目录身份与权限,不追加 worktree 标记", async () => {
  175. const parent = parentSession();
  176. const { bundles, runtime } = forkRuntime(parent);
  177. await forkStableConversationAtMessage.call(runtime as never, {
  178. goalBoundary: { kind: "none" },
  179. sourceCommandId: "cmd-parent-ws",
  180. target,
  181. });
  182. expect(bundles[0]!.child).toMatchObject({
  183. directory: SOURCE_DIRECTORY,
  184. path: SOURCE_DIRECTORY,
  185. projectID: "workspace-source",
  186. permission: parent.permission,
  187. });
  188. const timelineTypes = bundles[0]!.messages.flatMap((message) =>
  189. message.parts.flatMap((part) => (part.type === "timeline" ? [part.timelineType] : [])),
  190. );
  191. expect(timelineTypes).toEqual(["session_fork"]);
  192. });
  193. });