runtime-memory-permission.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import { describe, expect, it } from "vitest";
  2. import { createSessionId, SessionEventType } from "@zcode/contracts";
  3. import type { PermissionDecisionResult } from "../src/permission/service.js";
  4. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  5. import { resolveProjectMemoryRoot } from "../src/memory/project-root.js";
  6. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  7. import { applyMemoryFilePermission } from "../src/tool/executor/memory-file-permission.js";
  8. import { createTestSessionEventStore } from "./test-event-store.js";
  9. import { MemoryFileSystem } from "./memory-test-utils.js";
  10. import { createTestModelFactory } from "./test-runtime-model.js";
  11. const MEMORY_ROOT = "/storage/memories/projects/project-0123456789abcdef/memory";
  12. describe("project Memory foreground permission", () => {
  13. it("allows only contained lowercase Markdown Write/Edit after generic policy", () => {
  14. expect(apply({ file_path: `${MEMORY_ROOT}/user-preference.md` }).decision).toBe("allow");
  15. expect(
  16. apply({ file_path: `${MEMORY_ROOT}/nested/project-context.md` }, { toolName: "Edit" })
  17. .decision,
  18. ).toBe("allow");
  19. expect(apply({ file_path: `${MEMORY_ROOT}/user-preference.MD` })).toMatchObject({
  20. decision: "ask",
  21. ruleId: "mode.build.sideEffect",
  22. });
  23. expect(apply({ file_path: `${MEMORY_ROOT}-other/user-preference.md` })).toMatchObject({
  24. decision: "ask",
  25. ruleId: "mode.build.sideEffect",
  26. });
  27. });
  28. it.each([
  29. ".git",
  30. "hooks",
  31. ".husky",
  32. ".githooks",
  33. "node_modules",
  34. ".vscode",
  35. ".idea",
  36. "head",
  37. "config",
  38. "objects",
  39. "refs",
  40. ".claude",
  41. "skills",
  42. "commands",
  43. "agents",
  44. ".cargo",
  45. ".devcontainer",
  46. ".yarn",
  47. ".mvn",
  48. ])("does not auto-allow the sensitive %s path segment", (segment) => {
  49. expect(apply({ file_path: `${MEMORY_ROOT}/${segment}/fact.md` })).toMatchObject({
  50. decision: "ask",
  51. ruleId: "mode.build.sideEffect",
  52. });
  53. });
  54. it("normalizes only the baseline-sensitive segment disguises", () => {
  55. for (const segment of [".GIT", ".git.", ".git ", ".g\u200cit", ".git:stream"]) {
  56. expect(apply({ file_path: `${MEMORY_ROOT}/${segment}/fact.md` }).decision).toBe("ask");
  57. }
  58. expect(apply({ file_path: `${MEMORY_ROOT}/.git-notes/fact.md` }).decision).toBe("allow");
  59. });
  60. it("preserves explicit ask/deny while overriding only generic and plan policy", () => {
  61. expect(
  62. apply({ file_path: `${MEMORY_ROOT}/fact.md` }, { decision: askDecision("rule.project.ask") }),
  63. ).toMatchObject({ decision: "ask", ruleId: "rule.project.ask" });
  64. expect(
  65. apply(
  66. { file_path: `${MEMORY_ROOT}/fact.md` },
  67. { decision: denyDecision("rule.project.deny") },
  68. ),
  69. ).toMatchObject({ decision: "deny", ruleId: "rule.project.deny" });
  70. expect(
  71. apply(
  72. { file_path: `${MEMORY_ROOT}/fact.md` },
  73. { decision: denyDecision("mode.plan.nonReadOnly") },
  74. ),
  75. ).toMatchObject({ decision: "allow", ruleId: "memory.file.markdown" });
  76. });
  77. it("applies the same file permission to a custom user root outside the workspace", () => {
  78. const userRoot = "/storage/agent-memory/reviewer";
  79. expect(apply({ file_path: `${userRoot}/preference.md` }, { rootDir: userRoot })).toMatchObject({
  80. decision: "allow",
  81. ruleId: "memory.file.markdown",
  82. });
  83. });
  84. it("applies the permission at the real Write execution boundary", async () => {
  85. const fileSystemPort = new MemoryFileSystem({});
  86. const workspaceIdentity = "project-boundary";
  87. const sessionId = createSessionId("memory-permission-write-boundary");
  88. const target = `${resolveProjectMemoryRoot({
  89. cliStorageRoot: "/storage",
  90. workspaceIdentity,
  91. workspacePath: "/workspace",
  92. })}/runtime-boundary.md`;
  93. const requestedContent = [
  94. "---",
  95. "name: runtime-boundary",
  96. "description: Durable fact written through the runtime boundary",
  97. "metadata:",
  98. " type: project",
  99. "---",
  100. "",
  101. "Durable fact.",
  102. ].join("\n");
  103. let modelCallCount = 0;
  104. let secondRequest = "";
  105. const runtime = createTestAgentRuntime(
  106. sessionId,
  107. {
  108. memory: {
  109. cliStorageRoot: "/storage",
  110. enabled: true,
  111. use: true,
  112. workspaceIdentity,
  113. },
  114. workingDirectory: "/workspace",
  115. },
  116. {
  117. eventStore: createTestSessionEventStore(),
  118. fileSystemPort,
  119. permissionBroker: {
  120. requestPermission() {
  121. throw new Error("Memory boundary unexpectedly requested permission");
  122. },
  123. },
  124. modelFactory: createTestModelFactory({
  125. async generateText(request) {
  126. modelCallCount++;
  127. if (modelCallCount === 1) {
  128. return {
  129. finishReason: "tool-calls",
  130. text: "",
  131. toolCalls: [
  132. {
  133. id: "write-memory",
  134. name: "Write",
  135. input: { content: requestedContent, file_path: target },
  136. },
  137. ],
  138. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  139. };
  140. }
  141. secondRequest = JSON.stringify(request.messages);
  142. return {
  143. finishReason: "stop",
  144. text: "done",
  145. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  146. };
  147. },
  148. } as never),
  149. },
  150. );
  151. await runtime.executeTurn("save the durable fact");
  152. expect(fileSystemPort.files[target]).toBe(
  153. requestedContent.replace(
  154. " type: project",
  155. ` node_type: memory\n type: project\n originSessionId: ${sessionId}`,
  156. ),
  157. );
  158. expect(secondRequest).not.toContain("requires approval");
  159. });
  160. it.each([
  161. {
  162. brokerCalls: 0,
  163. caseName: "allows a safe Memory target",
  164. expectedContent: "hook-updated content",
  165. sessionName: "memory-permission-hook-safe-write",
  166. targetSuffix: "hook-updated.md",
  167. },
  168. {
  169. brokerCalls: 1,
  170. caseName: "reprompts for a sensitive Memory target",
  171. expectedContent: "hook-updated content",
  172. sessionName: "memory-permission-hook-sensitive-write",
  173. targetSuffix: "skills/hook-updated.md",
  174. },
  175. ])(
  176. "rechecks modified PermissionRequest input and $caseName",
  177. async ({ brokerCalls, expectedContent, sessionName, targetSuffix }) => {
  178. const sessionId = createSessionId(sessionName);
  179. const eventStore = createTestSessionEventStore();
  180. const fileSystemPort = new MemoryFileSystem({});
  181. const target = `${resolveProjectMemoryRoot({
  182. cliStorageRoot: "/storage",
  183. workspacePath: "/workspace",
  184. })}/${targetSuffix}`;
  185. let brokerCallCount = 0;
  186. let brokerAnswerCount = 0;
  187. let hookCallCount = 0;
  188. let modelCallCount = 0;
  189. const hookRunner = createInMemoryHookRunner({
  190. hooks: [
  191. {
  192. event: "PermissionRequest",
  193. matcher: "Write",
  194. callback: async (input) => {
  195. hookCallCount += 1;
  196. return {
  197. hookSpecificOutput: {
  198. decision: {
  199. behavior: "allow",
  200. updatedInput: { content: "hook-updated content", file_path: target },
  201. },
  202. hookEventName: input.hookEventName,
  203. },
  204. };
  205. },
  206. },
  207. ],
  208. });
  209. const runtime = createTestAgentRuntime(
  210. sessionId,
  211. {
  212. memory: {
  213. cliStorageRoot: "/storage",
  214. enabled: true,
  215. use: true,
  216. },
  217. workingDirectory: "/workspace",
  218. },
  219. {
  220. eventStore,
  221. fileSystemPort,
  222. hookRunner,
  223. permissionBroker: {
  224. requestPermission(_request, requestOptions) {
  225. brokerCallCount += 1;
  226. // 契约更新(docs/design/v2/permission-responder-race.md):初始 ask 总会
  227. // 并发武装 broker(第 1 次调用),hook 决定胜出后它被 abort、不产生应答;
  228. // 只有敏感目标 recheck 的重新提问(第 2 次调用)才真正消费用户应答。
  229. if (brokerCallCount === 1) {
  230. return new Promise((_, reject) => {
  231. requestOptions?.signal?.addEventListener(
  232. "abort",
  233. () => reject(new Error("aborted by race")),
  234. { once: true },
  235. );
  236. });
  237. }
  238. brokerAnswerCount += 1;
  239. return Promise.resolve({ decision: "allow" as const });
  240. },
  241. },
  242. modelFactory: createTestModelFactory({
  243. async generateText(request) {
  244. modelCallCount += 1;
  245. if (modelCallCount === 1) {
  246. return {
  247. finishReason: "tool-calls",
  248. text: "",
  249. toolCalls: [
  250. {
  251. id: "write-hook-updated-memory",
  252. name: "Write",
  253. input: { content: "ordinary write", file_path: "/workspace/ordinary.md" },
  254. },
  255. ],
  256. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  257. };
  258. }
  259. return {
  260. finishReason: "stop",
  261. text: "done",
  262. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  263. };
  264. },
  265. } as never),
  266. },
  267. );
  268. await runtime.executeTurn("write an ordinary project note");
  269. const events = await eventStore.getEvents(sessionId);
  270. expect(
  271. events.filter((event) => event.type === SessionEventType.PermissionRequested),
  272. ).toHaveLength(1 + brokerCalls);
  273. expect(hookCallCount).toBe(1);
  274. expect(brokerAnswerCount).toBe(brokerCalls);
  275. expect(fileSystemPort.files[target]).toBe(expectedContent);
  276. },
  277. );
  278. });
  279. describe("project Memory permission vs alwaysAsk", () => {
  280. it("keeps an alwaysAsk decision even for a contained Markdown memory file", () => {
  281. // memory 放行是"降级到 allow"的分支;alwaysAsk 的确认不能被它抹掉。
  282. // 今天 Write/Edit 都没声明 alwaysAsk,所以这是防回归而不是修现网 bug。
  283. expect(
  284. apply(
  285. { file_path: `${MEMORY_ROOT}/user-preference.md` },
  286. { decision: { ...askDecision("tool.alwaysAsk"), alwaysAsk: true } },
  287. ),
  288. ).toMatchObject({ decision: "ask", ruleId: "tool.alwaysAsk" });
  289. });
  290. });
  291. function apply(
  292. executionInput: unknown,
  293. options: {
  294. decision?: PermissionDecisionResult;
  295. rootDir?: string;
  296. toolName?: string;
  297. } = {},
  298. ): PermissionDecisionResult {
  299. return applyMemoryFilePermission({
  300. decision: options.decision ?? askDecision("mode.build.sideEffect"),
  301. executionInput,
  302. memoryRoot: options.rootDir ?? MEMORY_ROOT,
  303. toolName: options.toolName ?? "Write",
  304. workingDirectory: "/workspace",
  305. workspaceRoot: "/workspace",
  306. });
  307. }
  308. function allowDecision(ruleId: string): PermissionDecisionResult {
  309. return decision("allow", ruleId);
  310. }
  311. function askDecision(ruleId: string): PermissionDecisionResult {
  312. return decision("ask", ruleId);
  313. }
  314. function denyDecision(ruleId: string): PermissionDecisionResult {
  315. return decision("deny", ruleId);
  316. }
  317. function decision(
  318. value: PermissionDecisionResult["decision"],
  319. ruleId: string,
  320. ): PermissionDecisionResult {
  321. return {
  322. allowed: value === "allow",
  323. decision: value,
  324. escalated: value === "ask",
  325. mode: "build",
  326. riskLevel: "medium",
  327. ruleId,
  328. sideEffectScope: "workspace",
  329. };
  330. }