@gotgenes/pi-permission-system 18.1.1 → 18.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/docs/configuration.md +11 -0
  3. package/package.json +1 -2
  4. package/src/access-intent/access-path.ts +29 -4
  5. package/src/access-intent/bash/bash-path-resolver.ts +39 -18
  6. package/src/access-intent/bash/msys-bash-tokens.ts +64 -0
  7. package/src/extension-config.ts +7 -0
  8. package/src/forwarded-permissions/permission-forwarder.ts +6 -3
  9. package/src/handlers/gates/helpers.ts +1 -1
  10. package/src/handlers/gates/runner.ts +22 -0
  11. package/src/index.ts +10 -6
  12. package/src/path-normalizer.ts +105 -2
  13. package/src/permission-manager.ts +21 -1
  14. package/src/permission-prompter.ts +10 -16
  15. package/src/prompting-gateway.ts +13 -17
  16. package/src/rule.ts +21 -1
  17. package/src/status.ts +1 -1
  18. package/src/yolo-mode.ts +0 -30
  19. package/test/access-intent/access-path.test.ts +0 -277
  20. package/test/access-intent/bash/node-text.test.ts +0 -148
  21. package/test/access-intent/bash/parser.test.ts +0 -19
  22. package/test/access-intent/bash/program.test.ts +0 -673
  23. package/test/access-intent/bash/token-classification.test.ts +0 -363
  24. package/test/access-intent/bash/token-collection.test.ts +0 -300
  25. package/test/active-agent.test.ts +0 -155
  26. package/test/async-cache.test.ts +0 -48
  27. package/test/bash-arity.test.ts +0 -144
  28. package/test/bash-external-directory.test.ts +0 -1022
  29. package/test/builtin-tool-input-formatters.test.ts +0 -109
  30. package/test/canonicalize-path.test.ts +0 -119
  31. package/test/composition-root.test.ts +0 -698
  32. package/test/config-loader.test.ts +0 -740
  33. package/test/config-modal.test.ts +0 -320
  34. package/test/config-paths.test.ts +0 -83
  35. package/test/config-pipeline.test.ts +0 -90
  36. package/test/config-reporter.test.ts +0 -147
  37. package/test/config-store.test.ts +0 -466
  38. package/test/decision-audit.test.ts +0 -72
  39. package/test/decision-reporter.test.ts +0 -112
  40. package/test/denial-messages.test.ts +0 -714
  41. package/test/detect-permissive-bash-fallback.test.ts +0 -56
  42. package/test/expand-home.test.ts +0 -93
  43. package/test/extension-config.test.ts +0 -129
  44. package/test/extension-paths.test.ts +0 -108
  45. package/test/forwarded-permissions/io.test.ts +0 -251
  46. package/test/forwarding-manager.test.ts +0 -200
  47. package/test/handlers/before-agent-start.test.ts +0 -314
  48. package/test/handlers/external-directory-integration.test.ts +0 -515
  49. package/test/handlers/external-directory-session-dedup.test.ts +0 -175
  50. package/test/handlers/external-directory-symlink-acceptance.test.ts +0 -167
  51. package/test/handlers/gates/bash-command-metamorphic.test.ts +0 -88
  52. package/test/handlers/gates/bash-command.test.ts +0 -257
  53. package/test/handlers/gates/bash-external-directory.test.ts +0 -268
  54. package/test/handlers/gates/bash-path.test.ts +0 -346
  55. package/test/handlers/gates/candidate-check.test.ts +0 -52
  56. package/test/handlers/gates/external-directory-messages.test.ts +0 -85
  57. package/test/handlers/gates/external-directory-policy.test.ts +0 -134
  58. package/test/handlers/gates/external-directory.test.ts +0 -267
  59. package/test/handlers/gates/helpers.test.ts +0 -165
  60. package/test/handlers/gates/path.test.ts +0 -369
  61. package/test/handlers/gates/runner.test.ts +0 -408
  62. package/test/handlers/gates/skill-input-gate-pipeline.test.ts +0 -176
  63. package/test/handlers/gates/skill-input.test.ts +0 -128
  64. package/test/handlers/gates/skill-read.test.ts +0 -161
  65. package/test/handlers/gates/tool-call-gate-pipeline.test.ts +0 -356
  66. package/test/handlers/gates/tool.test.ts +0 -244
  67. package/test/handlers/input-events.test.ts +0 -168
  68. package/test/handlers/input.test.ts +0 -199
  69. package/test/handlers/lifecycle.test.ts +0 -221
  70. package/test/handlers/tool-call-boundary.test.ts +0 -145
  71. package/test/handlers/tool-call-events.test.ts +0 -277
  72. package/test/handlers/tool-call.test.ts +0 -395
  73. package/test/handlers/validate-requested-tool.test.ts +0 -92
  74. package/test/helpers/external-directory-fixtures.ts +0 -269
  75. package/test/helpers/gate-fixtures.ts +0 -316
  76. package/test/helpers/handler-fixtures.ts +0 -335
  77. package/test/helpers/make-fake-pi.ts +0 -100
  78. package/test/helpers/manager-harness.ts +0 -112
  79. package/test/helpers/session-fixtures.ts +0 -199
  80. package/test/input-normalizer.test.ts +0 -325
  81. package/test/logging.test.ts +0 -51
  82. package/test/mcp-targets.test.ts +0 -233
  83. package/test/node-modules-discovery.test.ts +0 -97
  84. package/test/normalize.test.ts +0 -247
  85. package/test/path-containment.test.ts +0 -161
  86. package/test/path-normalization.test.ts +0 -233
  87. package/test/path-normalizer.test.ts +0 -196
  88. package/test/path-surfaces.test.ts +0 -55
  89. package/test/pattern-suggest.test.ts +0 -248
  90. package/test/permission-dialog.test.ts +0 -205
  91. package/test/permission-event-rpc.test.ts +0 -560
  92. package/test/permission-events.test.ts +0 -400
  93. package/test/permission-forwarder.test.ts +0 -370
  94. package/test/permission-forwarding.test.ts +0 -315
  95. package/test/permission-gate.test.ts +0 -269
  96. package/test/permission-manager-unified.test.ts +0 -3714
  97. package/test/permission-merge.test.ts +0 -61
  98. package/test/permission-prompter.test.ts +0 -518
  99. package/test/permission-prompts.test.ts +0 -363
  100. package/test/permission-resolver.test.ts +0 -277
  101. package/test/permission-session.test.ts +0 -404
  102. package/test/permission-ui-prompt.test.ts +0 -146
  103. package/test/permissions-service.test.ts +0 -192
  104. package/test/pi-infrastructure-read.test.ts +0 -432
  105. package/test/policy-loader.test.ts +0 -561
  106. package/test/prompting-gateway.test.ts +0 -231
  107. package/test/rule.test.ts +0 -650
  108. package/test/safe-system-paths.test.ts +0 -46
  109. package/test/scope-merge.test.ts +0 -116
  110. package/test/service-lifecycle.test.ts +0 -163
  111. package/test/service.test.ts +0 -261
  112. package/test/session-approval.test.ts +0 -75
  113. package/test/session-logger.test.ts +0 -200
  114. package/test/session-rules.test.ts +0 -321
  115. package/test/session-start.test.ts +0 -112
  116. package/test/skill-prompt-sanitizer.test.ts +0 -418
  117. package/test/status.test.ts +0 -10
  118. package/test/subagent-context.test.ts +0 -372
  119. package/test/subagent-lifecycle-events.test.ts +0 -132
  120. package/test/subagent-registry.test.ts +0 -145
  121. package/test/synthesize.test.ts +0 -302
  122. package/test/system-prompt-sanitizer.test.ts +0 -382
  123. package/test/tool-access-extractor-registry.test.ts +0 -77
  124. package/test/tool-input-formatter-registry.test.ts +0 -75
  125. package/test/tool-input-path.test.ts +0 -84
  126. package/test/tool-input-preview.test.ts +0 -129
  127. package/test/tool-input-prompt-formatters.test.ts +0 -115
  128. package/test/tool-preview-formatter.test.ts +0 -458
  129. package/test/tool-registry.test.ts +0 -197
  130. package/test/value-guards.test.ts +0 -193
  131. package/test/wildcard-matcher.test.ts +0 -424
  132. package/test/yaml-frontmatter.test.ts +0 -91
  133. package/test/yolo-mode.test.ts +0 -188
@@ -1,221 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
-
3
- import { SessionLifecycleHandler } from "#src/handlers/lifecycle";
4
- import type { ServiceLifecycle } from "#src/service-lifecycle";
5
-
6
- import { makeCtx } from "#test/helpers/handler-fixtures";
7
- import {
8
- makeLogger,
9
- makeRealResolver,
10
- makeRealSession,
11
- } from "#test/helpers/session-fixtures";
12
-
13
- // ── status stub ────────────────────────────────────────────────────────────
14
- vi.mock("../../src/status", () => ({
15
- PERMISSION_SYSTEM_STATUS_KEY: "permission-system",
16
- syncPermissionSystemStatus: vi.fn(),
17
- getPermissionSystemStatus: vi.fn(),
18
- }));
19
-
20
- // ── helpers ────────────────────────────────────────────────────────────────
21
-
22
- function makeSetup(opts?: { configIssues?: string[] }) {
23
- const { session, permissionManager, sessionRules, forwarding, configStore } =
24
- makeRealSession();
25
- const { resolver } = makeRealResolver(permissionManager, sessionRules);
26
- if (opts?.configIssues) {
27
- vi.mocked(permissionManager.getConfigIssues).mockReturnValue(
28
- opts.configIssues,
29
- );
30
- }
31
- const serviceLifecycle: ServiceLifecycle = {
32
- activate: vi.fn<ServiceLifecycle["activate"]>(),
33
- teardown: vi.fn<ServiceLifecycle["teardown"]>(),
34
- };
35
- // Use a session-independent logger so assertions verify direct injection,
36
- // not reach-through to session.logger.
37
- const logger = makeLogger();
38
- const audit = { writeSummary: vi.fn<(logger: unknown) => void>() };
39
- const handler = new SessionLifecycleHandler(
40
- session,
41
- resolver,
42
- serviceLifecycle,
43
- logger,
44
- audit,
45
- );
46
- return {
47
- handler,
48
- session,
49
- resolver,
50
- permissionManager,
51
- logger,
52
- forwarding,
53
- configStore,
54
- serviceLifecycle,
55
- audit,
56
- };
57
- }
58
-
59
- // ── handleSessionStart ─────────────────────────────────────────────────────
60
-
61
- describe("handleSessionStart", () => {
62
- it("refreshes config with ctx", async () => {
63
- const ctx = makeCtx();
64
- const { handler, configStore } = makeSetup();
65
- await handler.handleSessionStart({ reason: "startup" }, ctx);
66
- expect(configStore.refresh).toHaveBeenCalledWith(ctx);
67
- });
68
-
69
- it("calls resetForNewSession with ctx", async () => {
70
- const ctx = makeCtx();
71
- const { handler, session } = makeSetup();
72
- const spy = vi.spyOn(session, "resetForNewSession");
73
- await handler.handleSessionStart({ reason: "startup" }, ctx);
74
- expect(spy).toHaveBeenCalledWith(ctx);
75
- });
76
-
77
- it("logs resolved config paths", async () => {
78
- const { handler, configStore } = makeSetup();
79
- await handler.handleSessionStart({ reason: "startup" }, makeCtx());
80
- expect(configStore.logResolvedPaths).toHaveBeenCalledOnce();
81
- });
82
-
83
- it("resolves agent name from ctx", async () => {
84
- const ctx = makeCtx();
85
- const { handler, session } = makeSetup();
86
- const spy = vi.spyOn(session, "resolveAgentName");
87
- await handler.handleSessionStart({ reason: "startup" }, ctx);
88
- expect(spy).toHaveBeenCalledWith(ctx);
89
- });
90
-
91
- it("notifies each policy issue", async () => {
92
- const { handler, logger } = makeSetup({
93
- configIssues: ["issue A", "issue B"],
94
- });
95
- await handler.handleSessionStart({ reason: "startup" }, makeCtx());
96
- expect(logger.warn).toHaveBeenCalledWith("issue A");
97
- expect(logger.warn).toHaveBeenCalledWith("issue B");
98
- });
99
-
100
- it("does not warn when there are no policy issues", async () => {
101
- const { handler, logger } = makeSetup();
102
- await handler.handleSessionStart({ reason: "startup" }, makeCtx());
103
- expect(logger.warn).not.toHaveBeenCalled();
104
- });
105
-
106
- it("writes lifecycle.reload debug log when reason is reload", async () => {
107
- const ctx = makeCtx({ cwd: "/proj" });
108
- const { handler, logger } = makeSetup();
109
- await handler.handleSessionStart({ reason: "reload" }, ctx);
110
- expect(logger.debug).toHaveBeenCalledWith("lifecycle.reload", {
111
- triggeredBy: "session_start",
112
- reason: "reload",
113
- cwd: "/proj",
114
- });
115
- });
116
-
117
- it("does not write lifecycle.reload debug log for non-reload reasons", async () => {
118
- const { handler, logger } = makeSetup();
119
- await handler.handleSessionStart({ reason: "startup" }, makeCtx());
120
- expect(logger.debug).not.toHaveBeenCalled();
121
- });
122
-
123
- it("activates the service for the session with ctx", async () => {
124
- const ctx = makeCtx();
125
- const { handler, serviceLifecycle } = makeSetup();
126
- await handler.handleSessionStart({ reason: "startup" }, ctx);
127
- expect(serviceLifecycle.activate).toHaveBeenCalledWith(ctx);
128
- });
129
-
130
- it("calls refreshConfig before resetForNewSession", async () => {
131
- const callOrder: string[] = [];
132
- const { handler, session, configStore } = makeSetup();
133
- vi.spyOn(configStore, "refresh").mockImplementation(() => {
134
- callOrder.push("refreshConfig");
135
- });
136
- vi.spyOn(session, "resetForNewSession").mockImplementation(() => {
137
- callOrder.push("resetForNewSession");
138
- });
139
- await handler.handleSessionStart({ reason: "startup" }, makeCtx());
140
- expect(callOrder).toEqual(["refreshConfig", "resetForNewSession"]);
141
- });
142
- });
143
-
144
- // ── handleResourcesDiscover ────────────────────────────────────────────────
145
-
146
- describe("handleResourcesDiscover", () => {
147
- it("does nothing when reason is not reload", async () => {
148
- const { handler, session } = makeSetup();
149
- const spy = vi.spyOn(session, "reload");
150
- await handler.handleResourcesDiscover({ reason: "startup" });
151
- expect(spy).not.toHaveBeenCalled();
152
- });
153
-
154
- it("calls reload on the session on reload", async () => {
155
- const { handler, session } = makeSetup();
156
- const spy = vi.spyOn(session, "reload");
157
- await handler.handleResourcesDiscover({ reason: "reload" });
158
- expect(spy).toHaveBeenCalledOnce();
159
- });
160
-
161
- it("writes lifecycle.reload debug log on reload", async () => {
162
- const ctx = makeCtx({ cwd: "/proj" });
163
- const { handler, session, logger } = makeSetup();
164
- session.activate(ctx);
165
- await handler.handleResourcesDiscover({ reason: "reload" });
166
- expect(logger.debug).toHaveBeenCalledWith("lifecycle.reload", {
167
- triggeredBy: "resources_discover",
168
- reason: "reload",
169
- cwd: "/proj",
170
- });
171
- });
172
-
173
- it("logs cwd as null when runtimeContext is null on reload", async () => {
174
- const { handler, logger } = makeSetup();
175
- await handler.handleResourcesDiscover({ reason: "reload" });
176
- expect(logger.debug).toHaveBeenCalledWith("lifecycle.reload", {
177
- triggeredBy: "resources_discover",
178
- reason: "reload",
179
- cwd: null,
180
- });
181
- });
182
- });
183
-
184
- // ── handleSessionShutdown ──────────────────────────────────────────────────
185
-
186
- describe("handleSessionShutdown", () => {
187
- it("clears UI status when runtime context is present", async () => {
188
- const ctx = makeCtx();
189
- const { handler, session } = makeSetup();
190
- session.activate(ctx);
191
- await handler.handleSessionShutdown();
192
- expect(ctx.ui.setStatus).toHaveBeenCalledWith(
193
- "permission-system",
194
- undefined,
195
- );
196
- });
197
-
198
- it("does not throw when runtime context is null", async () => {
199
- const { handler } = makeSetup();
200
- await expect(handler.handleSessionShutdown()).resolves.not.toThrow();
201
- });
202
-
203
- it("calls shutdown on the session", async () => {
204
- const { handler, session } = makeSetup();
205
- const spy = vi.spyOn(session, "shutdown");
206
- await handler.handleSessionShutdown();
207
- expect(spy).toHaveBeenCalledOnce();
208
- });
209
-
210
- it("calls serviceLifecycle.teardown", async () => {
211
- const { handler, serviceLifecycle } = makeSetup();
212
- await handler.handleSessionShutdown();
213
- expect(serviceLifecycle.teardown).toHaveBeenCalledOnce();
214
- });
215
-
216
- it("writes the decision-audit summary to the logger", async () => {
217
- const { handler, audit, logger } = makeSetup();
218
- await handler.handleSessionShutdown();
219
- expect(audit.writeSummary).toHaveBeenCalledWith(logger);
220
- });
221
- });
@@ -1,145 +0,0 @@
1
- /**
2
- * The fail-closed boundary is the only tool_call handler the SDK sees.
3
- *
4
- * The SDK's emitToolCall (@earendil-works/pi-coding-agent dist/core/extensions/
5
- * runner.js) awaits the registered handler with NO try/catch — unlike
6
- * emitUserBash directly below it, which catches and continues. So a thrown
7
- * gate would otherwise yield no block and the command would run ungated with
8
- * no trace. This boundary must absorb the throw and fail closed.
9
- */
10
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
11
- import { describe, expect, it, vi } from "vitest";
12
- import type { GateOutcome } from "#src/handlers/gates/types";
13
- import { createFailClosedToolCall } from "#src/handlers/tool-call-boundary";
14
-
15
- import { makeReporter } from "#test/helpers/gate-fixtures";
16
- import { makeCtx, makeToolCallEvent } from "#test/helpers/handler-fixtures";
17
-
18
- function makeAudit() {
19
- return {
20
- recordDecision: vi.fn<(action: "allow" | "block") => void>(),
21
- recordError: vi.fn<() => void>(),
22
- };
23
- }
24
-
25
- function makeTracer() {
26
- return {
27
- debug: vi.fn<(event: string, details?: Record<string, unknown>) => void>(),
28
- };
29
- }
30
-
31
- function gateReturning(outcome: GateOutcome) {
32
- return vi
33
- .fn<(event: unknown, ctx: ExtensionContext) => Promise<GateOutcome>>()
34
- .mockResolvedValue(outcome);
35
- }
36
-
37
- describe("createFailClosedToolCall", () => {
38
- it("translates an allow outcome to the empty SDK shape", async () => {
39
- const audit = makeAudit();
40
- const reporter = makeReporter();
41
- const boundary = createFailClosedToolCall(
42
- gateReturning({ action: "allow" }),
43
- reporter,
44
- audit,
45
- makeTracer(),
46
- );
47
-
48
- const result = await boundary(makeToolCallEvent("read"), makeCtx());
49
-
50
- expect(result).toEqual({});
51
- expect(audit.recordDecision).toHaveBeenCalledWith("allow");
52
- expect(audit.recordError).not.toHaveBeenCalled();
53
- expect(reporter.writeReviewLog).not.toHaveBeenCalled();
54
- });
55
-
56
- it("translates a block outcome to the SDK block shape with the reason", async () => {
57
- const audit = makeAudit();
58
- const reporter = makeReporter();
59
- const boundary = createFailClosedToolCall(
60
- gateReturning({ action: "block", reason: "denied by policy" }),
61
- reporter,
62
- audit,
63
- makeTracer(),
64
- );
65
-
66
- const result = await boundary(makeToolCallEvent("read"), makeCtx());
67
-
68
- expect(result).toEqual({ block: true, reason: "denied by policy" });
69
- expect(audit.recordDecision).toHaveBeenCalledWith("block");
70
- });
71
-
72
- it("writes a per-call decision trace with the tool name and action", async () => {
73
- const tracer = makeTracer();
74
- const boundary = createFailClosedToolCall(
75
- gateReturning({ action: "allow" }),
76
- makeReporter(),
77
- makeAudit(),
78
- tracer,
79
- );
80
-
81
- await boundary(makeToolCallEvent("bash"), makeCtx());
82
-
83
- expect(tracer.debug).toHaveBeenCalledWith(
84
- "permission.decision",
85
- expect.objectContaining({ toolName: "bash", action: "allow" }),
86
- );
87
- });
88
-
89
- it("blocks fail-closed when the gate throws, recording an error and a review-log entry", async () => {
90
- const audit = makeAudit();
91
- const reporter = makeReporter();
92
- const gate = vi
93
- .fn<(event: unknown, ctx: ExtensionContext) => Promise<GateOutcome>>()
94
- .mockRejectedValue(new Error("parser init failed"));
95
- const boundary = createFailClosedToolCall(
96
- gate,
97
- reporter,
98
- audit,
99
- makeTracer(),
100
- );
101
-
102
- const event = makeToolCallEvent("bash", {
103
- input: { command: "cd /repo && git push" },
104
- });
105
- const result = await boundary(event, makeCtx());
106
-
107
- expect((result as { block?: true }).block).toBe(true);
108
- expect(audit.recordError).toHaveBeenCalledTimes(1);
109
- expect(audit.recordDecision).not.toHaveBeenCalled();
110
- expect(reporter.writeReviewLog).toHaveBeenCalledWith(
111
- "permission_request.blocked",
112
- expect.objectContaining({
113
- toolName: "bash",
114
- command: "cd /repo && git push",
115
- resolution: "gate_error",
116
- error: "parser init failed",
117
- }),
118
- );
119
- });
120
-
121
- it("does not throw when the event is malformed and the gate throws", async () => {
122
- const audit = makeAudit();
123
- const reporter = makeReporter();
124
- const gate = vi
125
- .fn<(event: unknown, ctx: ExtensionContext) => Promise<GateOutcome>>()
126
- .mockRejectedValue("non-error rejection");
127
- const boundary = createFailClosedToolCall(
128
- gate,
129
- reporter,
130
- audit,
131
- makeTracer(),
132
- );
133
-
134
- const result = await boundary(undefined, makeCtx());
135
-
136
- expect((result as { block?: true }).block).toBe(true);
137
- expect(reporter.writeReviewLog).toHaveBeenCalledWith(
138
- "permission_request.blocked",
139
- expect.objectContaining({
140
- resolution: "gate_error",
141
- error: "non-error rejection",
142
- }),
143
- );
144
- });
145
- });
@@ -1,277 +0,0 @@
1
- /**
2
- * Tests that handleToolCall emits permissions:decision events at every
3
- * gate resolution and fast-path site.
4
- */
5
- import { describe, expect, it, vi } from "vitest";
6
-
7
- import type { GatePrompter } from "#src/gate-prompter";
8
- import {
9
- getDecisionEvents,
10
- makeCheckResult,
11
- makeCtx,
12
- makeHandler,
13
- makeToolCallEvent,
14
- } from "#test/helpers/handler-fixtures";
15
-
16
- // ── policy_allow path ──────────────────────────────────────────────────────
17
-
18
- describe("handleToolCall decision events — policy_allow", () => {
19
- it("emits allow with policy_allow when checkPermission returns allow", async () => {
20
- const { handler, events } = makeHandler({
21
- session: {
22
- checkPermission: vi.fn().mockReturnValue(
23
- makeCheckResult({
24
- state: "allow",
25
- origin: "global",
26
- matchedPattern: "*",
27
- }),
28
- ),
29
- },
30
- });
31
-
32
- await handler.handleToolCall(makeToolCallEvent("read"), makeCtx());
33
-
34
- const decisions = getDecisionEvents(events);
35
- expect(decisions).toHaveLength(1);
36
- expect(decisions[0]).toMatchObject({
37
- surface: "read",
38
- result: "allow",
39
- resolution: "policy_allow",
40
- origin: "global",
41
- matchedPattern: "*",
42
- });
43
- });
44
- });
45
-
46
- // ── policy_deny path ───────────────────────────────────────────────────────
47
-
48
- describe("handleToolCall decision events — policy_deny", () => {
49
- it("emits deny with policy_deny when checkPermission returns deny", async () => {
50
- const { handler, events } = makeHandler({
51
- session: {
52
- checkPermission: vi.fn().mockReturnValue(
53
- makeCheckResult({
54
- state: "deny",
55
- origin: "project",
56
- matchedPattern: "read",
57
- }),
58
- ),
59
- },
60
- });
61
-
62
- await handler.handleToolCall(makeToolCallEvent("read"), makeCtx());
63
-
64
- const decisions = getDecisionEvents(events);
65
- expect(decisions).toHaveLength(1);
66
- expect(decisions[0]).toMatchObject({
67
- surface: "read",
68
- result: "deny",
69
- resolution: "policy_deny",
70
- });
71
- });
72
- });
73
-
74
- // ── session_approved fast path ─────────────────────────────────────────────
75
-
76
- describe("handleToolCall decision events — session_approved", () => {
77
- it("emits allow with session_approved when checkPermission returns source:session", async () => {
78
- const { handler, events } = makeHandler({
79
- session: {
80
- checkPermission: vi.fn().mockReturnValue(
81
- makeCheckResult({
82
- state: "allow",
83
- source: "session",
84
- matchedPattern: "git *",
85
- }),
86
- ),
87
- },
88
- });
89
-
90
- await handler.handleToolCall(
91
- makeToolCallEvent("bash", { input: { command: "git status" } }),
92
- makeCtx(),
93
- );
94
-
95
- const decisions = getDecisionEvents(events);
96
- expect(decisions).toHaveLength(1);
97
- expect(decisions[0]).toMatchObject({
98
- surface: "bash",
99
- result: "allow",
100
- resolution: "session_approved",
101
- });
102
- });
103
- });
104
-
105
- // ── user_approved path ─────────────────────────────────────────────────────
106
-
107
- describe("handleToolCall decision events — user_approved", () => {
108
- it("emits allow with user_approved when state=ask and user approves once", async () => {
109
- const { handler, events } = makeHandler({
110
- session: {
111
- checkPermission: vi
112
- .fn()
113
- .mockReturnValue(makeCheckResult({ state: "ask" })),
114
- },
115
- prompter: {
116
- canConfirm: vi.fn().mockReturnValue(true),
117
- prompt: vi
118
- .fn<GatePrompter["prompt"]>()
119
- .mockResolvedValue({ approved: true, state: "approved" }),
120
- },
121
- });
122
-
123
- await handler.handleToolCall(makeToolCallEvent("read"), makeCtx());
124
-
125
- const decisions = getDecisionEvents(events);
126
- expect(decisions).toHaveLength(1);
127
- expect(decisions[0]).toMatchObject({
128
- result: "allow",
129
- resolution: "user_approved",
130
- });
131
- });
132
-
133
- it("emits allow with user_approved_for_session when user approves for session", async () => {
134
- const { handler, events } = makeHandler({
135
- session: {
136
- checkPermission: vi
137
- .fn()
138
- .mockReturnValue(makeCheckResult({ state: "ask" })),
139
- },
140
- prompter: {
141
- canConfirm: vi.fn().mockReturnValue(true),
142
- prompt: vi.fn<GatePrompter["prompt"]>().mockResolvedValue({
143
- approved: true,
144
- state: "approved_for_session",
145
- }),
146
- },
147
- });
148
-
149
- await handler.handleToolCall(makeToolCallEvent("read"), makeCtx());
150
-
151
- const decisions = getDecisionEvents(events);
152
- expect(decisions).toHaveLength(1);
153
- expect(decisions[0]).toMatchObject({
154
- result: "allow",
155
- resolution: "user_approved_for_session",
156
- });
157
- });
158
- });
159
-
160
- // ── user_denied path ───────────────────────────────────────────────────────
161
-
162
- describe("handleToolCall decision events — user_denied", () => {
163
- it("emits deny with user_denied when state=ask and user denies", async () => {
164
- const { handler, events } = makeHandler({
165
- session: {
166
- checkPermission: vi
167
- .fn()
168
- .mockReturnValue(makeCheckResult({ state: "ask" })),
169
- },
170
- prompter: {
171
- canConfirm: vi.fn().mockReturnValue(true),
172
- prompt: vi
173
- .fn<GatePrompter["prompt"]>()
174
- .mockResolvedValue({ approved: false, state: "denied" }),
175
- },
176
- });
177
-
178
- await handler.handleToolCall(makeToolCallEvent("read"), makeCtx());
179
-
180
- const decisions = getDecisionEvents(events);
181
- expect(decisions).toHaveLength(1);
182
- expect(decisions[0]).toMatchObject({
183
- result: "deny",
184
- resolution: "user_denied",
185
- });
186
- });
187
- });
188
-
189
- // ── confirmation_unavailable path ──────────────────────────────────────────
190
-
191
- describe("handleToolCall decision events — confirmation_unavailable", () => {
192
- it("emits deny with confirmation_unavailable when state=ask but no UI", async () => {
193
- const { handler, events } = makeHandler({
194
- session: {
195
- checkPermission: vi
196
- .fn()
197
- .mockReturnValue(makeCheckResult({ state: "ask" })),
198
- },
199
- prompter: {
200
- canConfirm: vi.fn().mockReturnValue(false),
201
- prompt: vi.fn<GatePrompter["prompt"]>(),
202
- },
203
- });
204
-
205
- await handler.handleToolCall(
206
- makeToolCallEvent("read"),
207
- makeCtx({ hasUI: false }),
208
- );
209
-
210
- const decisions = getDecisionEvents(events);
211
- expect(decisions).toHaveLength(1);
212
- expect(decisions[0]).toMatchObject({
213
- result: "deny",
214
- resolution: "confirmation_unavailable",
215
- });
216
- });
217
- });
218
-
219
- // ── infrastructure_auto_allowed path ──────────────────────────────────────
220
-
221
- describe("handleToolCall decision events — infrastructure_auto_allowed", () => {
222
- it("emits allow with infrastructure_auto_allowed for Pi infra reads", async () => {
223
- const infraDir = "/test/agent";
224
- const { handler, events } = makeHandler({
225
- session: {
226
- checkPermission: vi.fn().mockReturnValue(makeCheckResult()),
227
- getInfrastructureReadDirs: vi.fn().mockReturnValue([infraDir]),
228
- },
229
- });
230
-
231
- const event = makeToolCallEvent("read", {
232
- input: { path: `${infraDir}/some-file.json` },
233
- });
234
- await handler.handleToolCall(event, makeCtx());
235
-
236
- const decisions = getDecisionEvents(events);
237
- const infraEvents = decisions.filter(
238
- (e) => e.resolution === "infrastructure_auto_allowed",
239
- );
240
- expect(infraEvents).toHaveLength(1);
241
- expect(infraEvents[0]).toMatchObject({
242
- result: "allow",
243
- resolution: "infrastructure_auto_allowed",
244
- });
245
- });
246
- });
247
-
248
- // ── auto_approved path (yolo mode) ───────────────────────────────────
249
-
250
- describe("handleToolCall decision events — auto_approved", () => {
251
- it("emits allow with auto_approved when prompt returns autoApproved:true", async () => {
252
- const { handler, events } = makeHandler({
253
- session: {
254
- checkPermission: vi
255
- .fn()
256
- .mockReturnValue(makeCheckResult({ state: "ask" })),
257
- },
258
- prompter: {
259
- canConfirm: vi.fn().mockReturnValue(true),
260
- prompt: vi.fn<GatePrompter["prompt"]>().mockResolvedValue({
261
- approved: true,
262
- state: "approved",
263
- autoApproved: true,
264
- }),
265
- },
266
- });
267
-
268
- await handler.handleToolCall(makeToolCallEvent("read"), makeCtx());
269
-
270
- const decisions = getDecisionEvents(events);
271
- expect(decisions).toHaveLength(1);
272
- expect(decisions[0]).toMatchObject({
273
- result: "allow",
274
- resolution: "auto_approved",
275
- });
276
- });
277
- });