guarded-approval.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. CoreErrorType,
  4. createSessionId,
  5. createToolCallId,
  6. SessionEventType,
  7. type CollaborationMode,
  8. type ExecutionShellSelection,
  9. type PermissionBrokerResult,
  10. type PermissionBrokerPort,
  11. type PermissionBrokerRequest,
  12. type PermissionRuleset,
  13. type SessionEvent,
  14. } from "@zcode/contracts";
  15. import { createToolExecutor } from "../src/tool/executor.js";
  16. import { createToolRegistry } from "../src/tool/registry.js";
  17. import { bashToolEntry } from "../src/tool/handlers/bash.js";
  18. import { PermissionService } from "../src/permission/service.js";
  19. import { createManualPermissionBroker } from "../src/permission/broker.js";
  20. import type { ToolEntry, ToolExecutionContext } from "../src/tool/types.js";
  21. const POSIX: ExecutionShellSelection = {
  22. dialect: "posix",
  23. source: "auto-detected",
  24. display: { name: "bash" },
  25. };
  26. function harness(
  27. options: {
  28. mode?: CollaborationMode;
  29. answer?: (request: PermissionBrokerRequest) => Promise<PermissionBrokerResult>;
  30. noBroker?: boolean;
  31. deferredBroker?: PermissionBrokerPort;
  32. hookInput?: unknown;
  33. permissionHookInput?: unknown;
  34. timeoutMs?: number;
  35. validateInput?: ToolEntry["validateInput"];
  36. prepareApproval?: ToolEntry["prepareApproval"];
  37. resolvePermissionCapability?: ToolEntry["resolvePermissionCapability"];
  38. projectRules?: PermissionRuleset;
  39. onPublished?: (
  40. requestId: string,
  41. broker: ReturnType<typeof createManualPermissionBroker>,
  42. ) => void;
  43. } = {},
  44. ) {
  45. const registry = createToolRegistry();
  46. const handler = vi.fn(async (_input: unknown, _context: ToolExecutionContext) => ({
  47. stdout: "controlled handler result",
  48. stderr: "",
  49. exitCode: 0,
  50. interrupted: false,
  51. }));
  52. registry.register({
  53. ...bashToolEntry,
  54. handler,
  55. outputSchema: undefined,
  56. ...(options.validateInput ? { validateInput: options.validateInput } : {}),
  57. ...(options.prepareApproval ? { prepareApproval: options.prepareApproval } : {}),
  58. ...(options.resolvePermissionCapability
  59. ? { resolvePermissionCapability: options.resolvePermissionCapability }
  60. : {}),
  61. });
  62. const events: SessionEvent[] = [];
  63. const requests: PermissionBrokerRequest[] = [];
  64. const shell = structuredClone(POSIX);
  65. let mode = options.mode ?? "guarded";
  66. let cwd = "/workspace/original";
  67. const hooks = vi.fn(async (input: unknown) => ({
  68. additionalContexts: [],
  69. permissionBehavior:
  70. options.permissionHookInput === undefined ? ("allow" as const) : ("ask" as const),
  71. ...((input as { hookEventName?: string }).hookEventName === "PreToolUse" &&
  72. options.hookInput !== undefined
  73. ? { updatedInput: options.hookInput }
  74. : {}),
  75. ...((input as { hookEventName?: string }).hookEventName === "PermissionRequest" &&
  76. options.permissionHookInput !== undefined
  77. ? {
  78. permissionRequestResult: {
  79. behavior: "allow" as const,
  80. updatedInput: options.permissionHookInput,
  81. },
  82. }
  83. : {}),
  84. }));
  85. const saveProjectPermission = vi.fn();
  86. const broker = createManualPermissionBroker({
  87. onRequest: (request) => {
  88. requests.push(request);
  89. },
  90. });
  91. const executor = createToolExecutor({
  92. registry,
  93. getMode: () => mode,
  94. getWorkingDirectory: () => cwd,
  95. sessionId: createSessionId("guarded"),
  96. permissionService: new PermissionService(),
  97. permissionTimeoutMs: options.timeoutMs,
  98. sessionStore: {
  99. getSession: async () => ({ projectID: "guarded-project" }),
  100. getProjectPermission: async () => options.projectRules ?? { allow: [{ toolName: "Bash" }] },
  101. saveProjectPermission,
  102. } as never,
  103. hookRunner: { run: hooks },
  104. getBashShellSelection: () => shell,
  105. ...(!options.noBroker
  106. ? {
  107. permissionBroker:
  108. options.deferredBroker ??
  109. (options.answer
  110. ? {
  111. requestPermission: async (request: PermissionBrokerRequest) => {
  112. requests.push(request);
  113. return options.answer!(request);
  114. },
  115. }
  116. : broker),
  117. }
  118. : {}),
  119. emitEvent: async (event) => {
  120. events.push(event);
  121. if (event.type === SessionEventType.PermissionRequested) {
  122. options.onPublished?.(event.payload.requestId!, broker);
  123. }
  124. },
  125. });
  126. const execute = (command = "rm -rf build", signal?: AbortSignal) =>
  127. executor.execute(
  128. { id: createToolCallId("guarded"), name: "Bash", input: { command } },
  129. { signal },
  130. );
  131. return {
  132. setCwd: (next: string) => {
  133. cwd = next;
  134. },
  135. setMode: (next: CollaborationMode) => {
  136. mode = next;
  137. },
  138. executor,
  139. execute,
  140. handler,
  141. hooks,
  142. broker,
  143. requests,
  144. events,
  145. shell,
  146. saveProjectPermission,
  147. };
  148. }
  149. describe("Guarded executor authorization boundary", () => {
  150. describe.each([
  151. ["posix", "rm -r tree", "remove-critical-path"],
  152. ["git-bash", "rm first second", "remove-critical-path"],
  153. ["cmd", "rd /S tree", "cmd-remove-tree"],
  154. ["cmd", "erase /P file", "cmd-delete-files"],
  155. ["posix", "find . -type f -delete", "find-delete"],
  156. ["posix", "find -d . -type f -delete", "find-delete"],
  157. ["posix", "find -x . -type f -delete", "find-delete"],
  158. ["posix", "git clean -f", "git-clean-force"],
  159. ["git-bash", "robocopy src dst /MIR", "robocopy-delete"],
  160. ["posix", "rm first --help", "remove-critical-path"],
  161. ["cmd", "rd target/s/q", "cmd-remove-tree"],
  162. ["cmd", "rd/s/q target", "cmd-remove-tree"],
  163. ["cmd", "del/q target\\one.txt", "cmd-delete-files"],
  164. ["git-bash", "env MSYS2_ARG_CONV_EXCL=/MIR robocopy /c/src /c/dst /MIR", "robocopy-delete"],
  165. ] as const)("deletion lifecycle: %s / %s", (dialect, command, rule) => {
  166. it.each([
  167. ["guarded", "deny", false, 1],
  168. ["guarded", "allow", true, 1],
  169. ["yolo", "deny", true, 0],
  170. ] as const)("%s / %s", async (mode, decision, success, requests) => {
  171. const h = harness({ mode });
  172. h.shell.dialect = dialect;
  173. const pending = h.execute(command);
  174. if (requests) {
  175. await vi.waitFor(() => expect(h.broker.listPendingRequests()).toHaveLength(1));
  176. expect(h.handler).not.toHaveBeenCalled();
  177. expect(h.broker.resolvePermission(h.requests[0]!.requestId, {
  178. decision, reason: "Keep deletion fixture",
  179. })).toBe(true);
  180. }
  181. const result = await pending;
  182. expect(result.success).toBe(success);
  183. expect(h.requests).toHaveLength(requests);
  184. if (requests) {
  185. expect(h.requests[0]).toMatchObject({
  186. approvalMode: "user-once", ruleId: `safety.bash.${rule}`, input: { command },
  187. });
  188. expect(h.broker.resolvePermission(h.requests[0]!.requestId, { decision: "allow" })).toBe(false);
  189. }
  190. expect(h.handler).toHaveBeenCalledTimes(success ? 1 : 0);
  191. if (success) {
  192. expect(h.handler.mock.calls[0]?.[0]).toEqual({ command });
  193. expect(result.output).toMatchObject({ stdout: "controlled handler result" });
  194. } else expect(result.error?.message).toContain("Keep deletion fixture");
  195. expect(h.hooks).toHaveBeenCalled(); // PreToolUse allow 不能替代用户批准。
  196. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  197. expect(h.broker.listPendingRequests()).toEqual([]);
  198. });
  199. it("cancellation keeps files unexecuted and clears the real broker", async () => {
  200. const h = harness();
  201. h.shell.dialect = dialect;
  202. const controller = new AbortController();
  203. const result = h.execute(command, controller.signal);
  204. await vi.waitFor(() => expect(h.broker.listPendingRequests()).toHaveLength(1));
  205. controller.abort();
  206. expect((await result).success).toBe(false);
  207. expect(h.handler).not.toHaveBeenCalled();
  208. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  209. expect(h.broker.listPendingRequests()).toEqual([]);
  210. });
  211. });
  212. it.each([
  213. ["guarded", "deny", false, 1],
  214. ["guarded", "allow", true, 1],
  215. ["yolo", "deny", true, 0],
  216. ] as const)("glob force refspec: %s / %s", async (mode, decision, success, requests) => {
  217. const h = harness({ mode, answer: async () => ({ decision }) });
  218. const command = "git push origin +refs/heads/*:refs/heads/*";
  219. const result = await h.execute(command);
  220. expect(result.success).toBe(success);
  221. expect(h.requests).toHaveLength(requests);
  222. if (requests) {
  223. expect(h.requests[0]).toMatchObject({
  224. approvalMode: "user-once",
  225. ruleId: "safety.bash.git-push-force",
  226. input: { command },
  227. });
  228. }
  229. expect(h.handler).toHaveBeenCalledTimes(success ? 1 : 0);
  230. if (success) expect(h.handler.mock.calls[0]?.[0]).toEqual({ command });
  231. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  232. expect(h.broker.listPendingRequests()).toEqual([]);
  233. });
  234. it("单次确认不会被工具预览的 proceed 放行", async () => {
  235. const prepareApproval = vi.fn(() => ({ gate: "proceed" as const }));
  236. const h = harness({ prepareApproval, answer: async () => ({ decision: "deny" }) });
  237. expect((await h.execute()).success).toBe(false);
  238. expect(h.requests).toHaveLength(1);
  239. expect(prepareApproval).not.toHaveBeenCalled();
  240. expect(h.handler).not.toHaveBeenCalled();
  241. });
  242. it.each([
  243. ["guarded", "deny", false, 1],
  244. ["guarded", "allow", true, 1],
  245. ["yolo", "deny", true, 0],
  246. ] as const)("CMD REM-named redirection: %s / %s", async (mode, decision, success, requests) => {
  247. const h = harness({ mode, answer: async () => ({ decision }) });
  248. h.shell.dialect = "cmd";
  249. const command = ">rem git reset --hard";
  250. const result = await h.execute(command);
  251. expect(result.success).toBe(success);
  252. expect(h.requests).toHaveLength(requests);
  253. if (requests) {
  254. expect(h.requests[0]).toMatchObject({
  255. approvalMode: "user-once",
  256. ruleId: "safety.bash.git-reset-hard",
  257. input: { command },
  258. });
  259. }
  260. expect(h.handler).toHaveBeenCalledTimes(success ? 1 : 0);
  261. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  262. expect(h.broker.listPendingRequests()).toEqual([]);
  263. });
  264. it.each([
  265. ["guarded", "deny", false, 1],
  266. ["guarded", "allow", true, 1],
  267. ["yolo", "deny", true, 0],
  268. ] as const)("rm trailing help/version: %s / %s", async (mode, decision, success, requests) => {
  269. const h = harness({ mode, answer: async () => ({ decision, reason: "Keep fixture files" }) });
  270. const command = "rm -rf target --help --version";
  271. const result = await h.execute(command);
  272. expect(result.success).toBe(success);
  273. expect(h.requests).toHaveLength(requests);
  274. if (requests) {
  275. expect(h.requests[0]).toMatchObject({
  276. approvalMode: "user-once",
  277. ruleId: "safety.bash.remove-critical-path",
  278. input: { command },
  279. });
  280. }
  281. expect(h.handler).toHaveBeenCalledTimes(success ? 1 : 0);
  282. if (!success) expect(result.error?.message).toContain("Keep fixture files");
  283. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  284. expect(h.broker.listPendingRequests()).toEqual([]);
  285. });
  286. it.each([false, true])(
  287. "cancels while registration is pending (deferred=%s) without late publication",
  288. async (deferredRegistration) => {
  289. const registered = Promise.withResolvers<void>();
  290. const entered = Promise.withResolvers<void>();
  291. const deferredBroker = createManualPermissionBroker();
  292. const h = harness({
  293. deferredBroker: {
  294. requestPermission(request, options) {
  295. entered.resolve();
  296. const response = deferredRegistration
  297. ? registered.promise.then(() => deferredBroker.requestPermission(request, options))
  298. : deferredBroker.requestPermission(request, options);
  299. return Object.assign(response, {
  300. registered: registered.promise,
  301. });
  302. },
  303. },
  304. });
  305. const controller = new AbortController();
  306. let result: Awaited<ReturnType<typeof h.execute>> | undefined;
  307. const pending = h.execute(undefined, controller.signal).then((value) => {
  308. result = value;
  309. });
  310. await entered.promise;
  311. controller.abort();
  312. try {
  313. await vi.waitFor(() => expect(result?.error?.type).toBe(CoreErrorType.ToolCancelled));
  314. } finally {
  315. registered.resolve();
  316. await pending;
  317. }
  318. expect(
  319. h.events.filter((event) => event.type === SessionEventType.PermissionRequested),
  320. ).toHaveLength(0);
  321. expect(
  322. h.events.filter((event) => event.type === SessionEventType.PermissionResolved),
  323. ).toHaveLength(1);
  324. expect(deferredBroker.listPendingRequests()).toEqual([]);
  325. expect(h.handler).not.toHaveBeenCalled();
  326. },
  327. );
  328. it("ordinary project reapproval also closes the previous request before creating a new id", async () => {
  329. const h = harness({
  330. mode: "build",
  331. permissionHookInput: { command: "git reset --hard" },
  332. projectRules: { ask: [{ toolName: "Bash" }] },
  333. });
  334. const controller = new AbortController();
  335. const pending = h.execute("echo original", controller.signal);
  336. try {
  337. await vi.waitFor(() => expect(h.requests).toHaveLength(2));
  338. const [old, current] = h.requests;
  339. expect(current!.requestId).not.toBe(old!.requestId);
  340. expect(h.broker.resolvePermission(old!.requestId, { decision: "allow" })).toBe(false);
  341. h.broker.resolvePermission(current!.requestId, { decision: "allow" });
  342. expect((await pending).success).toBe(true);
  343. expect(h.handler).toHaveBeenCalledTimes(1);
  344. expect(
  345. h.events.filter((event) => event.type === SessionEventType.PermissionResolved),
  346. ).toHaveLength(2);
  347. } finally {
  348. controller.abort();
  349. await pending;
  350. }
  351. });
  352. // 2026-09-17 review:重判不能退回只含 runtimeScope/cwd 的缩减上下文,否则 guarded matcher 在该路径静默失效。
  353. it("hook rewrite recheck receives the same prepared context as the first decision", async () => {
  354. const contexts: unknown[] = [];
  355. const h = harness({
  356. mode: "build",
  357. permissionHookInput: { command: "git reset --hard" },
  358. projectRules: { ask: [{ toolName: "Bash" }] },
  359. resolvePermissionCapability: (input, context) => {
  360. contexts.push(context);
  361. return bashToolEntry.resolvePermissionCapability?.(input, context);
  362. },
  363. });
  364. const controller = new AbortController();
  365. const pending = h.execute("echo original", controller.signal);
  366. try {
  367. await vi.waitFor(() => expect(h.requests).toHaveLength(2));
  368. expect(contexts.length).toBeGreaterThanOrEqual(2);
  369. for (const context of contexts) {
  370. expect(context).toMatchObject({
  371. mode: "build",
  372. bashShellSelection: h.shell,
  373. workingDirectory: "/workspace/original",
  374. });
  375. }
  376. } finally {
  377. controller.abort();
  378. await pending;
  379. }
  380. });
  381. it("replaces a hook-approved edited input with a fresh user-only request", async () => {
  382. const h = harness({ permissionHookInput: { command: "rm -rf replacement" } });
  383. const pending = h.execute("echo harmless");
  384. await vi.waitFor(() => expect(h.requests).toHaveLength(2));
  385. const [original, guarded] = h.requests;
  386. expect(original?.approvalMode).toBeUndefined();
  387. expect(guarded).toMatchObject({
  388. approvalMode: "user-once",
  389. input: { command: "rm -rf replacement" },
  390. });
  391. expect(guarded?.requestId).not.toBe(original?.requestId);
  392. expect(h.broker.resolvePermission(original!.requestId, { decision: "allow" })).toBe(false);
  393. expect(h.broker.listPendingRequests()).toHaveLength(1);
  394. expect(h.handler).not.toHaveBeenCalled();
  395. h.broker.resolvePermission(guarded!.requestId, { decision: "deny" });
  396. expect((await pending).success).toBe(false);
  397. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  398. expect(h.broker.listPendingRequests()).toEqual([]);
  399. });
  400. it("reclassifies a PreToolUse edit before approval even with project allow", async () => {
  401. const h = harness({
  402. hookInput: { command: "rm -rf replacement" },
  403. answer: async () => ({ decision: "deny" }),
  404. });
  405. expect((await h.execute("echo harmless")).success).toBe(false);
  406. expect(h.requests[0]?.input).toEqual({ command: "rm -rf replacement" });
  407. expect(h.handler).not.toHaveBeenCalled();
  408. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  409. });
  410. it("does not let PreToolUse/PermissionRequest auto-allow a dangerous request", async () => {
  411. const h = harness();
  412. const pending = h.execute();
  413. await vi.waitFor(() => expect(h.requests).toHaveLength(1));
  414. expect(h.handler).not.toHaveBeenCalled();
  415. expect(h.requests[0]).toMatchObject({
  416. approvalMode: "user-once",
  417. ruleId: "safety.bash.remove-critical-path",
  418. });
  419. expect(
  420. h.hooks.mock.calls.some(
  421. ([input]) => (input as { hookEventName?: string }).hookEventName === "PermissionRequest",
  422. ),
  423. ).toBe(false);
  424. h.broker.resolvePermission(h.requests[0]!.requestId, {
  425. decision: "deny",
  426. reason: "Keep my files",
  427. });
  428. const result = await pending;
  429. expect(result.success).toBe(false);
  430. expect(result.error?.message).toContain("Keep my files");
  431. expect(h.handler).not.toHaveBeenCalled();
  432. expect(h.broker.listPendingRequests()).toEqual([]);
  433. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  434. });
  435. it("reuses the session shell selection and executes with the approved cwd exactly once", async () => {
  436. const h = harness();
  437. const pending = h.execute();
  438. await vi.waitFor(() => expect(h.requests).toHaveLength(1));
  439. h.setCwd("/workspace/changed");
  440. h.broker.resolvePermission(h.requests[0]!.requestId, { decision: "allow" });
  441. expect((await pending).success).toBe(true);
  442. expect(h.handler).toHaveBeenCalledTimes(1);
  443. expect(h.handler.mock.calls[0]?.[1].bashShellSelection).toBe(h.shell);
  444. expect(h.handler.mock.calls[0]?.[1]).toMatchObject({
  445. bashShellSelection: { dialect: "posix" },
  446. workingDirectory: "/workspace/original",
  447. });
  448. expect(h.broker.resolvePermission(h.requests[0]!.requestId, { decision: "allow" })).toBe(false);
  449. });
  450. it.each(["allow", "modify"] as const)(
  451. "executes a broker-approved dangerous edit once without reapproval: %s",
  452. async (decision) => {
  453. const modifiedInput = { command: "git reset --hard" };
  454. let responses = 0;
  455. const h = harness({
  456. answer: async () => {
  457. // 回归时有界失败,不让重复审批挂住测试或不断请求相同输入。
  458. if (++responses > 1) return { decision: "deny", reason: "Unexpected reapproval" };
  459. h.setMode("yolo");
  460. h.setCwd("/workspace/changed");
  461. return { decision, modifiedInput };
  462. },
  463. });
  464. expect((await h.execute()).success).toBe(true);
  465. expect(h.requests).toHaveLength(1);
  466. expect(h.requests[0]?.mode).toBe("guarded");
  467. expect(h.handler).toHaveBeenCalledTimes(1);
  468. expect(h.handler.mock.calls[0]?.[0]).toEqual(modifiedInput);
  469. expect(h.handler.mock.calls[0]?.[0]).not.toBe(modifiedInput);
  470. expect(Object.isFrozen(h.handler.mock.calls[0]?.[0])).toBe(true);
  471. expect(h.handler.mock.calls[0]?.[1].bashShellSelection).toBe(h.shell);
  472. expect(h.handler.mock.calls[0]?.[1]).toMatchObject({
  473. bashShellSelection: { dialect: "posix" },
  474. workingDirectory: "/workspace/original",
  475. });
  476. expect(h.events.filter((e) => e.type === SessionEventType.PermissionResolved)).toHaveLength(
  477. 1,
  478. );
  479. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  480. },
  481. );
  482. it.each([
  483. {
  484. decision: "allow",
  485. permissionUpdates: [{ type: "addRules", behavior: "allow", rules: [{ toolName: "Bash" }] }],
  486. },
  487. { decision: "invalid" },
  488. { decision: "allow", permissionUpdates: {} },
  489. {
  490. decision: "allow",
  491. sessionPermissionUpdates: [
  492. { type: "addRules", behavior: "allow", rules: [{ toolName: "Bash" }] },
  493. ],
  494. },
  495. { decision: "allow", reason: {} },
  496. { decision: "modify", modifiedInput: { command: 42 } },
  497. { decision: "allow", modifiedInput: { command: 42 } },
  498. {
  499. decision: "modify",
  500. modifiedInput: { command: "git reset --hard" },
  501. permissionUpdates: [{ type: "addRules", behavior: "allow", rules: [{ toolName: "Bash" }] }],
  502. },
  503. ])("rejects illegal/invalid/persistent responses without executing", async (answer) => {
  504. const h = harness({ answer: async () => answer as PermissionBrokerResult });
  505. expect((await h.execute()).success).toBe(false);
  506. expect(h.handler).not.toHaveBeenCalled();
  507. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  508. });
  509. it("times out and removes the pending request without executing or storing rules", async () => {
  510. const h = harness({ timeoutMs: 10 });
  511. expect((await h.execute()).error?.type).toBe(CoreErrorType.PermissionTimeout);
  512. expect(h.requests).toHaveLength(1);
  513. expect(h.broker.listPendingRequests()).toEqual([]);
  514. expect(h.handler).not.toHaveBeenCalled();
  515. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  516. expect(h.broker.resolvePermission(h.requests[0]!.requestId, { decision: "allow" })).toBe(false);
  517. });
  518. it("cleans pending on cancellation", async () => {
  519. const h = harness();
  520. const abort = new AbortController();
  521. const pending = h.execute(undefined, abort.signal);
  522. await vi.waitFor(() => expect(h.requests).toHaveLength(1));
  523. abort.abort();
  524. expect((await pending).error?.type).toBe(CoreErrorType.ToolCancelled);
  525. expect(h.broker.listPendingRequests()).toEqual([]);
  526. expect(h.handler).not.toHaveBeenCalled();
  527. });
  528. it("mode switching does not settle an existing request", async () => {
  529. const h = harness();
  530. const pending = h.execute();
  531. await vi.waitFor(() => expect(h.requests).toHaveLength(1));
  532. h.setMode("yolo");
  533. expect(h.handler).not.toHaveBeenCalled();
  534. h.broker.resolvePermission(h.requests[0]!.requestId, { decision: "deny" });
  535. expect((await pending).success).toBe(false);
  536. expect((await h.execute()).success).toBe(true);
  537. expect(h.requests).toHaveLength(1);
  538. });
  539. it("fails without an interactive broker", async () => {
  540. const h = harness({ noBroker: true });
  541. expect((await h.execute()).error?.type).toBe(CoreErrorType.ConfigurationError);
  542. expect(h.handler).not.toHaveBeenCalled();
  543. });
  544. it("original YOLO executes the same command with no new approval", async () => {
  545. const h = harness({ mode: "yolo" });
  546. expect((await h.execute()).success).toBe(true);
  547. expect(h.requests).toEqual([]);
  548. expect(h.handler).toHaveBeenCalledTimes(1);
  549. expect(h.handler.mock.calls[0]?.[1].bashShellSelection).toBe(h.shell);
  550. });
  551. it("registers the broker before publishing a request that can be answered immediately", async () => {
  552. let delivered = false;
  553. const h = harness({
  554. timeoutMs: 30,
  555. onPublished: (id, broker) => {
  556. delivered = broker.resolvePermission(id, { decision: "allow" });
  557. },
  558. });
  559. expect((await h.execute()).success).toBe(true);
  560. expect(delivered).toBe(true);
  561. expect(h.handler).toHaveBeenCalledTimes(1);
  562. expect(h.events.filter((e) => e.type === SessionEventType.PermissionResolved)).toHaveLength(1);
  563. });
  564. it.each([
  565. ["guarded", "hook"],
  566. ["guarded", "broker"],
  567. ["guarded", "permission-hook"],
  568. ["build", "hook"],
  569. ["build", "permission-hook"],
  570. ["yolo", "hook"],
  571. ["yolo", "permission-hook"],
  572. ] as const)("keeps semantic preflight before hooks only: %s / %s", async (mode, source) => {
  573. const modified = { command: "echo rewritten-input" };
  574. const validateInput = vi.fn((input: unknown) =>
  575. (input as { command: string }).command === modified.command
  576. ? { result: false, errorCode: 123, message: "Rejected by tool semantics" }
  577. : undefined,
  578. );
  579. const h = harness({
  580. mode,
  581. ...(source === "hook" ? { hookInput: modified } : {}),
  582. ...(source === "permission-hook" ? { permissionHookInput: modified } : {}),
  583. ...(source === "broker"
  584. ? { answer: async () => ({ decision: "modify" as const, modifiedInput: modified }) }
  585. : {}),
  586. validateInput,
  587. });
  588. const command = source === "broker" ? "rm -rf build" : "echo original-input";
  589. const result = await h.execute(command);
  590. expect(result.success).toBe(true);
  591. expect(validateInput).toHaveBeenCalledTimes(1);
  592. expect(validateInput.mock.calls[0]?.[0]).toEqual({ command });
  593. expect(h.handler).toHaveBeenCalledTimes(1);
  594. expect(h.handler.mock.calls[0]?.[0]).toEqual(modified);
  595. expect(h.broker.listPendingRequests()).toEqual([]);
  596. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  597. });
  598. it.each(["guarded", "build", "yolo"] as const)(
  599. "still rejects initial semantic failures before hooks in %s",
  600. async (mode) => {
  601. const validateInput = vi.fn(() => ({
  602. result: false,
  603. errorCode: 123,
  604. message: "Rejected by initial tool semantics",
  605. }));
  606. const h = harness({ mode, validateInput });
  607. const result = await h.execute();
  608. expect(result.success).toBe(false);
  609. expect(result.error?.message).toContain("Rejected by initial tool semantics");
  610. expect(validateInput).toHaveBeenCalledTimes(1);
  611. expect(h.hooks).not.toHaveBeenCalled();
  612. expect(h.requests).toEqual([]);
  613. expect(h.handler).not.toHaveBeenCalled();
  614. },
  615. );
  616. it.each(["hook", "broker", "permission-hook"] as const)(
  617. "still rejects schema-invalid input rewritten by %s",
  618. async (source) => {
  619. const modified = { timeout: 1000 };
  620. const h = harness({
  621. ...(source === "hook" ? { hookInput: modified } : {}),
  622. ...(source === "permission-hook" ? { permissionHookInput: modified } : {}),
  623. ...(source === "broker"
  624. ? { answer: async () => ({ decision: "modify" as const, modifiedInput: modified }) }
  625. : {}),
  626. });
  627. const result = await h.execute(source === "broker" ? "rm -rf build" : "echo original-input");
  628. expect(result.success).toBe(false);
  629. expect(result.error?.message).toContain("inputSchema validation");
  630. expect(h.handler).not.toHaveBeenCalled();
  631. expect(h.broker.listPendingRequests()).toEqual([]);
  632. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  633. },
  634. );
  635. it("preserves infrastructure errors without describing them as user denial", async () => {
  636. const h = harness({
  637. answer: async () => {
  638. throw new Error("transport unavailable");
  639. },
  640. });
  641. const result = await h.execute();
  642. expect(result.success).toBe(false);
  643. expect(result.error?.type).toBe(CoreErrorType.ToolExecutionFailed);
  644. expect(h.handler).not.toHaveBeenCalled();
  645. });
  646. });