@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,698 +0,0 @@
1
- /**
2
- * Composition-root tests for `piPermissionSystemExtension(pi)`.
3
- *
4
- * These run the real factory via the `makeFakePi()` harness and assert the
5
- * wiring contracts that unit tests cannot see: handler-registration
6
- * completeness, shared-instance contracts across factory invocations, teardown,
7
- * service↔gate registry sharing, and `ready`-after-publish ordering.
8
- *
9
- * Every test runs the factory, which mutates two process-global `Symbol.for()`
10
- * slots and reads `PI_CODING_AGENT_DIR`. The shared `beforeEach`/`afterEach`
11
- * isolate the agent dir to a tmpdir and clear both global slots so factory runs
12
- * do not leak across tests.
13
- */
14
- import {
15
- mkdirSync,
16
- mkdtempSync,
17
- readdirSync,
18
- readFileSync,
19
- rmSync,
20
- writeFileSync,
21
- } from "node:fs";
22
- import { tmpdir } from "node:os";
23
- import { dirname, join } from "node:path";
24
-
25
- import {
26
- createEventBus,
27
- type ExtensionAPI,
28
- } from "@earendil-works/pi-coding-agent";
29
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
30
-
31
- import { getGlobalConfigPath } from "#src/config-paths";
32
- import { DEFAULT_EXTENSION_CONFIG } from "#src/extension-config";
33
- import piPermissionSystemExtension from "#src/index";
34
- import {
35
- PERMISSIONS_READY_CHANNEL,
36
- PERMISSIONS_RPC_CHECK_CHANNEL,
37
- } from "#src/permission-events";
38
- import {
39
- createPermissionForwardingLocation,
40
- type ForwardedPermissionRequest,
41
- } from "#src/permission-forwarding";
42
- import { getPermissionsService } from "#src/service";
43
- import { SUBAGENT_CHILD_SESSION_CREATED } from "#src/subagent-lifecycle-events";
44
- import { getSubagentSessionRegistry } from "#src/subagent-registry";
45
- import { makeFakePi } from "#test/helpers/make-fake-pi";
46
-
47
- const SERVICE_KEY = Symbol.for("@gotgenes/pi-permission-system:service");
48
- const SUBAGENT_REGISTRY_KEY = Symbol.for(
49
- "@gotgenes/pi-permission-system:subagent-registry",
50
- );
51
-
52
- /** The six events the factory must register a handler for. */
53
- const EXPECTED_HANDLERS = [
54
- "before_agent_start",
55
- "input",
56
- "resources_discover",
57
- "session_shutdown",
58
- "session_start",
59
- "tool_call",
60
- ];
61
-
62
- let agentDir: string;
63
-
64
- beforeEach(() => {
65
- agentDir = mkdtempSync(join(tmpdir(), "pi-perm-comp-root-"));
66
- vi.stubEnv("PI_CODING_AGENT_DIR", agentDir);
67
- });
68
-
69
- afterEach(() => {
70
- // Drop both process-global slots so factory runs do not leak across tests.
71
- const store = globalThis as Record<symbol, unknown>;
72
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete -- Symbol-keyed global property
73
- delete store[SERVICE_KEY];
74
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete -- Symbol-keyed global property
75
- delete store[SUBAGENT_REGISTRY_KEY];
76
- vi.unstubAllEnvs();
77
- rmSync(agentDir, { recursive: true, force: true });
78
- });
79
-
80
- // ── Shared helpers ──────────────────────────────────────────────────────────
81
-
82
- /** Write the global config file under the stubbed agent dir. */
83
- function writeGlobalConfig(config: Record<string, unknown>): void {
84
- const globalConfigPath = getGlobalConfigPath(agentDir);
85
- mkdirSync(dirname(globalConfigPath), { recursive: true });
86
- writeFileSync(
87
- globalConfigPath,
88
- `${JSON.stringify({ ...DEFAULT_EXTENSION_CONFIG, ...config }, null, 2)}\n`,
89
- "utf8",
90
- );
91
- }
92
-
93
- /** Build a minimal subagent `ctx` (no UI) for driving tool-call gates. */
94
- function makeChildCtx(cwd: string, sessionId: string): unknown {
95
- return {
96
- cwd,
97
- hasUI: false,
98
- sessionManager: {
99
- getEntries: (): unknown[] => [],
100
- getSessionId: (): string => sessionId,
101
- getSessionDir: (): string => cwd,
102
- },
103
- ui: {
104
- notify: (): void => {},
105
- setStatus: (): void => {},
106
- select: async (): Promise<string | undefined> => undefined,
107
- input: async (): Promise<string | undefined> => undefined,
108
- },
109
- };
110
- }
111
-
112
- /**
113
- * Build a UI-present `ctx` that records the titles passed to `ui.select`, and
114
- * approves every prompt. The ask-prompt message (which embeds the tool-input
115
- * preview) is the first line of the select title.
116
- */
117
- function makeUiCtx(cwd: string, capturedTitles: string[]): { ctx: unknown } {
118
- const ctx = {
119
- cwd,
120
- hasUI: true,
121
- sessionManager: {
122
- getEntries: (): unknown[] => [],
123
- getSessionId: (): string => "ui-session",
124
- getSessionDir: (): string => cwd,
125
- },
126
- ui: {
127
- notify: (): void => {},
128
- setStatus: (): void => {},
129
- select: async (title: string): Promise<string | undefined> => {
130
- capturedTitles.push(title);
131
- return "Yes";
132
- },
133
- input: async (): Promise<string | undefined> => undefined,
134
- },
135
- };
136
- return { ctx };
137
- }
138
-
139
- const sleep = (ms: number): Promise<void> =>
140
- new Promise((resolve) => setTimeout(resolve, ms));
141
-
142
- /** Drive the registered `session_start` handler with a ctx. */
143
- function fireSessionStart(
144
- pi: ReturnType<typeof makeFakePi>,
145
- ctx: unknown,
146
- ): Promise<unknown> {
147
- return pi.fire("session_start", { reason: "start" }, ctx);
148
- }
149
-
150
- /**
151
- * Simulate the parent UI session responding to a forwarded permission request.
152
- *
153
- * Polls the parent's requests directory for the child's request file, then
154
- * writes an approval response so the child's forwarding poll resolves quickly
155
- * instead of waiting out the 10-minute timeout.
156
- */
157
- async function approveForwardedRequest(
158
- forwardingDir: string,
159
- parentSessionId: string,
160
- ): Promise<ForwardedPermissionRequest> {
161
- const location = createPermissionForwardingLocation(
162
- forwardingDir,
163
- parentSessionId,
164
- );
165
- const deadline = Date.now() + 2000;
166
- while (Date.now() < deadline) {
167
- let files: string[] = [];
168
- try {
169
- files = readdirSync(location.requestsDir).filter((f) =>
170
- f.endsWith(".json"),
171
- );
172
- } catch {
173
- files = [];
174
- }
175
- const requestFile = files[0];
176
- if (requestFile) {
177
- const request = JSON.parse(
178
- readFileSync(join(location.requestsDir, requestFile), "utf8"),
179
- ) as ForwardedPermissionRequest;
180
- mkdirSync(location.responsesDir, { recursive: true });
181
- writeFileSync(
182
- join(location.responsesDir, `${request.id}.json`),
183
- JSON.stringify({
184
- approved: true,
185
- state: "approved",
186
- responderSessionId: parentSessionId,
187
- respondedAt: Date.now(),
188
- }),
189
- "utf8",
190
- );
191
- return request;
192
- }
193
- await sleep(5);
194
- }
195
- throw new Error("Timed out waiting for the forwarded permission request");
196
- }
197
-
198
- describe("event-handler registration completeness", () => {
199
- it("registers a handler for every required event exactly once", () => {
200
- const pi = makeFakePi();
201
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
202
-
203
- expect([...pi.handlers.keys()].sort()).toEqual(EXPECTED_HANDLERS);
204
- });
205
- });
206
-
207
- describe("subagent registry sharing across factory instances", () => {
208
- // The #296 regression class: two factory invocations on *different* event
209
- // buses must still resolve the same process-global SubagentSessionRegistry,
210
- // so a child registered via the parent's bus detects itself as a subagent and
211
- // forwards (rather than blocking) an external-directory `ask`.
212
- it("lets a child instance forward an ask it received via the parent's bus", async () => {
213
- writeGlobalConfig({
214
- permission: { "*": "allow", external_directory: "ask" },
215
- });
216
-
217
- const childCwd = mkdtempSync(join(tmpdir(), "pi-perm-child-cwd-"));
218
- const externalDir = mkdtempSync(join(tmpdir(), "pi-perm-external-"));
219
- const forwardingDir = join(agentDir, "sessions", "permission-forwarding");
220
- const parentSessionId = "parent-session-1";
221
- const childSessionId = "child-session-1";
222
-
223
- // Two factory instances, each wired to its own event bus (as in production:
224
- // every session's ResourceLoader creates a separate bus).
225
- const parentBus = createEventBus();
226
- const childBus = createEventBus();
227
- piPermissionSystemExtension(
228
- makeFakePi({ events: parentBus }) as unknown as ExtensionAPI,
229
- );
230
- const childPi = makeFakePi({
231
- events: childBus,
232
- toolNames: ["read"],
233
- });
234
- piPermissionSystemExtension(childPi as unknown as ExtensionAPI);
235
-
236
- // The child session is announced on the *parent's* bus only; the parent's
237
- // lifecycle subscription writes it into the shared global registry.
238
- parentBus.emit(SUBAGENT_CHILD_SESSION_CREATED, {
239
- sessionId: childSessionId,
240
- parentSessionId,
241
- });
242
-
243
- // The child fires an external-directory read with no UI. With the shared
244
- // registry it detects itself as a subagent and forwards; the simulated
245
- // parent approves.
246
- const firePromise = childPi.fire(
247
- "tool_call",
248
- {
249
- toolName: "read",
250
- toolCallId: "child-external-read",
251
- input: { path: join(externalDir, "secret.txt") },
252
- },
253
- makeChildCtx(childCwd, childSessionId),
254
- );
255
-
256
- const request = await approveForwardedRequest(
257
- forwardingDir,
258
- parentSessionId,
259
- );
260
- expect(request.targetSessionId).toBe(parentSessionId);
261
- expect(request.requesterSessionId).toBe(childSessionId);
262
- // The child persists the original display fields so the parent emits a
263
- // non-degraded `permissions:ui_prompt` event (forwarded non-degradation).
264
- expect(request.source).toBe("tool_call");
265
- expect(request.surface).toBe("read");
266
- expect(request.value).toBe(join(externalDir, "secret.txt"));
267
-
268
- const result = (await firePromise) as { block?: true };
269
- expect(result.block).toBeUndefined();
270
-
271
- rmSync(childCwd, { recursive: true, force: true });
272
- rmSync(externalDir, { recursive: true, force: true });
273
- });
274
- });
275
-
276
- describe("shutdown teardown chain", () => {
277
- it("unpublishes the service and unsubscribes the lifecycle on shutdown", async () => {
278
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-teardown-cwd-"));
279
- const pi = makeFakePi();
280
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
281
-
282
- // The service is published at session_start, not at factory init.
283
- await fireSessionStart(pi, makeChildCtx(cwd, "top-session"));
284
- expect(getPermissionsService()).toBeDefined();
285
-
286
- await pi.fire("session_shutdown");
287
-
288
- // Service slot cleared.
289
- expect(getPermissionsService()).toBeUndefined();
290
-
291
- // Lifecycle unsubscribed: a post-shutdown session-created must not register.
292
- pi.events.emit(SUBAGENT_CHILD_SESSION_CREATED, {
293
- sessionId: "late-child",
294
- parentSessionId: "p-late",
295
- });
296
- expect(getSubagentSessionRegistry().has("late-child")).toBe(false);
297
-
298
- rmSync(cwd, { recursive: true, force: true });
299
- });
300
- });
301
-
302
- describe("service and gate share one formatter registry", () => {
303
- // A formatter registered through the published service must be consulted by
304
- // the live gate handler — proving both reference the same
305
- // ToolInputFormatterRegistry instance the factory created once.
306
- it("surfaces a service-registered formatter in the gate's ask prompt", async () => {
307
- writeGlobalConfig({
308
- permission: { "*": "allow", demo: "ask" },
309
- });
310
-
311
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-ui-cwd-"));
312
- const pi = makeFakePi({ toolNames: ["demo"] });
313
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
314
-
315
- const capturedTitles: string[] = [];
316
- const { ctx } = makeUiCtx(cwd, capturedTitles);
317
- // The service is published at session_start; publish before resolving it.
318
- await fireSessionStart(pi, ctx);
319
-
320
- const previewMarker = "PREVIEW::shared-registry-proof";
321
- getPermissionsService()!.registerToolInputFormatter(
322
- "demo",
323
- () => previewMarker,
324
- );
325
- const result = (await pi.fire(
326
- "tool_call",
327
- { toolName: "demo", toolCallId: "demo-ask", input: { foo: "bar" } },
328
- ctx,
329
- )) as { block?: true };
330
-
331
- // The gate prompted (not blocked) and the prompt embedded the formatter's
332
- // preview — so the gate consulted the same registry the service wrote to.
333
- expect(result.block).toBeUndefined();
334
- expect(capturedTitles.some((t) => t.includes(previewMarker))).toBe(true);
335
-
336
- rmSync(cwd, { recursive: true, force: true });
337
- });
338
- });
339
-
340
- describe("service and gate share one access extractor registry", () => {
341
- // An extractor registered through the published service must be consulted by
342
- // the live gate handler — proving both reference the same
343
- // ToolAccessExtractorRegistry instance the factory created once (#352).
344
- it("path-gates a custom-shaped tool via a service-registered extractor", async () => {
345
- writeGlobalConfig({
346
- permission: { "*": "allow", path: { "*.env": "deny" } },
347
- });
348
-
349
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-ext-cwd-"));
350
- const pi = makeFakePi({ toolNames: ["ffgrep"] });
351
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
352
-
353
- const { ctx } = makeUiCtx(cwd, []);
354
- await fireSessionStart(pi, ctx);
355
-
356
- // ffgrep carries its path under a non-standard key; without the extractor
357
- // the default input.path convention would miss it.
358
- getPermissionsService()!.registerToolAccessExtractor("ffgrep", (input) =>
359
- typeof input.target === "string" ? input.target : undefined,
360
- );
361
-
362
- const result = (await pi.fire(
363
- "tool_call",
364
- { toolName: "ffgrep", toolCallId: "ff-1", input: { target: ".env" } },
365
- ctx,
366
- )) as { block?: true };
367
-
368
- // The path deny fired — so the gate extracted ffgrep's path through the
369
- // same registry the service wrote to.
370
- expect(result.block).toBe(true);
371
-
372
- rmSync(cwd, { recursive: true, force: true });
373
- });
374
- });
375
-
376
- describe("ready emitted after service publication", () => {
377
- // Ordering contracts exist only at the composition root: a consumer reacting
378
- // to permissions:ready must be able to resolve the service immediately. The
379
- // service is published and ready fires at session_start (not factory init).
380
- it("publishes the service before emitting permissions:ready", async () => {
381
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-ready-cwd-"));
382
- const seen: string[] = [];
383
- const pi = makeFakePi();
384
- pi.events.on(PERMISSIONS_READY_CHANNEL, () => {
385
- seen.push(getPermissionsService() ? "present" : "missing");
386
- });
387
-
388
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
389
-
390
- // ready is not emitted at load; only after session_start publishes.
391
- expect(seen).toEqual([]);
392
-
393
- await fireSessionStart(pi, makeChildCtx(cwd, "top-session"));
394
-
395
- expect(seen).toEqual(["present"]);
396
-
397
- rmSync(cwd, { recursive: true, force: true });
398
- });
399
- });
400
-
401
- describe("single source of truth for session state", () => {
402
- // Regression guard for the split-brain bug: before the fix, the gate path
403
- // recorded session approvals into a private SessionRules instance that the
404
- // RPC check and the service never saw. After the fix, both readers use the
405
- // same SessionRules the gate writes into.
406
- it("gate session-approval is visible to the RPC check and the service", async () => {
407
- writeGlobalConfig({
408
- permission: { "*": "allow", demo: "ask" },
409
- });
410
-
411
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-sot-cwd-"));
412
- const pi = makeFakePi({ toolNames: ["demo"] });
413
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
414
-
415
- // UI ctx that approves the gate prompt for this session (options[1]).
416
- const ctx = {
417
- cwd,
418
- hasUI: true,
419
- sessionManager: {
420
- getEntries: (): unknown[] => [],
421
- getSessionId: (): string => "sot-session",
422
- getSessionDir: (): string => cwd,
423
- },
424
- ui: {
425
- notify: (): void => {},
426
- setStatus: (): void => {},
427
- // Return the second option label-agnostically — always the
428
- // "for this session" choice regardless of the exact label text.
429
- select: async (
430
- _title: string,
431
- options: string[],
432
- ): Promise<string | undefined> => options[1],
433
- input: async (): Promise<string | undefined> => undefined,
434
- },
435
- };
436
-
437
- await fireSessionStart(pi, ctx);
438
-
439
- // Drive a tool_call on "demo"; the gate prompts and the mock selects
440
- // options[1], recording a session-scoped approval.
441
- await pi.fire(
442
- "tool_call",
443
- {
444
- toolName: "demo",
445
- toolCallId: "demo-for-session",
446
- input: { foo: "bar" },
447
- },
448
- ctx,
449
- );
450
-
451
- // RPC check — the deprecated channel must now reflect the session approval.
452
- // eslint-disable-next-line @typescript-eslint/no-deprecated -- intentionally testing the deprecated RPC channel's session-rules visibility
453
- const rpcCheckChannel: string = PERMISSIONS_RPC_CHECK_CHANNEL;
454
- const requestId = "sot-rpc-1";
455
- const replyPromise = new Promise<unknown>((resolve) => {
456
- const unsub = pi.events.on(
457
- `${rpcCheckChannel}:reply:${requestId}`,
458
- (data) => {
459
- unsub();
460
- resolve(data);
461
- },
462
- );
463
- });
464
- pi.events.emit(rpcCheckChannel, { requestId, surface: "demo" });
465
- const reply = (await replyPromise) as {
466
- success: boolean;
467
- data?: { result: string };
468
- };
469
-
470
- expect(reply.success).toBe(true);
471
- // Before the fix this was "ask" — the RPC channel read an empty SessionRules.
472
- expect(reply.data?.result).toBe("allow");
473
-
474
- // Service accessor must also see the session approval.
475
- const serviceResult = getPermissionsService()!.checkPermission("demo");
476
- expect(serviceResult.state).toBe("allow");
477
-
478
- rmSync(cwd, { recursive: true, force: true });
479
- });
480
- });
481
-
482
- describe("service path queries evaluate the supplied path (#503)", () => {
483
- // Before #503 the service path query dropped the value (buildInputForSurface
484
- // returned {} for the `path` surface), so the query collapsed to ["*"] and a
485
- // path-specific rule never fired. The query now builds an AccessPath, so the
486
- // supplied path flows through the resolver → manager and matches `path` rules
487
- // end-to-end.
488
- it("resolves a path-surface query against a deny rule on the supplied path", async () => {
489
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-svc-path-cwd-"));
490
- const target = join(cwd, "secrets.env");
491
- writeGlobalConfig({ permission: { path: { [target]: "deny" } } });
492
-
493
- const pi = makeFakePi({ events: createEventBus() });
494
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
495
- await fireSessionStart(pi, makeChildCtx(cwd, "svc-path-session"));
496
-
497
- const result = getPermissionsService()!.checkPermission("path", target);
498
- expect(result.state).toBe("deny");
499
-
500
- rmSync(cwd, { recursive: true, force: true });
501
- });
502
- });
503
-
504
- describe("bash bare-filename path gating (#509)", () => {
505
- // Before #509 a bash bare-filename argument (`cat id_rsa`) bypassed the
506
- // `path` surface entirely: the broad classifier only accepted tokens
507
- // starting with `.`, containing `/`, containing `..`, or a Windows
508
- // drive-letter absolute path. The same file accessed via a prefixed path
509
- // (`cat ./id_rsa`) or the `read` tool was already gated. Rule-driven
510
- // promotion closes the gap for a bare token matching a specific, non-`*`
511
- // `path` deny/ask rule — the literal repro from the issue.
512
-
513
- async function fireBashToolCall(
514
- pi: ReturnType<typeof makeFakePi>,
515
- ctx: unknown,
516
- command: string,
517
- ): Promise<{ block?: true; reason?: string }> {
518
- return (await pi.fire(
519
- "tool_call",
520
- { name: "bash", input: { command }, toolCallId: "tc-1" },
521
- ctx,
522
- )) as { block?: true; reason?: string };
523
- }
524
-
525
- it("denies a bare filename matching a specific path deny rule", async () => {
526
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-bare-token-cwd-"));
527
- writeGlobalConfig({
528
- permission: { "*": "allow", path: { id_rsa: "deny" } },
529
- });
530
-
531
- const pi = makeFakePi({ events: createEventBus() });
532
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
533
- const ctx = makeChildCtx(cwd, "bare-token-session-deny");
534
- await fireSessionStart(pi, ctx);
535
-
536
- const result = await fireBashToolCall(pi, ctx, "cat id_rsa");
537
- expect(result.block).toBe(true);
538
-
539
- rmSync(cwd, { recursive: true, force: true });
540
- });
541
-
542
- it("denies a bare filename matching a wildcard path deny rule", async () => {
543
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-bare-token-cwd-"));
544
- writeGlobalConfig({
545
- permission: { "*": "allow", path: { "*.pem": "deny" } },
546
- });
547
-
548
- const pi = makeFakePi({ events: createEventBus() });
549
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
550
- const ctx = makeChildCtx(cwd, "bare-token-session-wildcard");
551
- await fireSessionStart(pi, ctx);
552
-
553
- const result = await fireBashToolCall(pi, ctx, "cat key.pem");
554
- expect(result.block).toBe(true);
555
-
556
- rmSync(cwd, { recursive: true, force: true });
557
- });
558
-
559
- it("leaves a bare token that does not match any path rule unaffected", async () => {
560
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-bare-token-cwd-"));
561
- writeGlobalConfig({
562
- permission: { "*": "allow", path: { id_rsa: "deny" } },
563
- });
564
-
565
- const pi = makeFakePi({ events: createEventBus() });
566
- piPermissionSystemExtension(pi as unknown as ExtensionAPI);
567
- const ctx = makeChildCtx(cwd, "bare-token-session-unaffected");
568
- await fireSessionStart(pi, ctx);
569
-
570
- const result = await fireBashToolCall(pi, ctx, "git status");
571
- expect(result.block).toBeUndefined();
572
-
573
- rmSync(cwd, { recursive: true, force: true });
574
- });
575
- });
576
-
577
- describe("multi-instance global service interplay", () => {
578
- // The fix (#302) scopes the process-global service slot to the publishing
579
- // instance. The parent publishes at its session_start; an in-process child
580
- // (registered by session id) skips publishing, and its identity-scoped
581
- // teardown is a no-op — so the parent's service is the one that resolves
582
- // throughout the child's lifecycle and survives the child's shutdown.
583
- it("keeps the parent's service published across the child's lifecycle", async () => {
584
- const parentCwd = mkdtempSync(join(tmpdir(), "pi-perm-parent-cwd-"));
585
- const childCwd = mkdtempSync(join(tmpdir(), "pi-perm-child-cwd-"));
586
- const childSessionId = "child-session-mi";
587
-
588
- const parentPi = makeFakePi({ events: createEventBus() });
589
- piPermissionSystemExtension(parentPi as unknown as ExtensionAPI);
590
- const childPi = makeFakePi({ events: createEventBus() });
591
- piPermissionSystemExtension(childPi as unknown as ExtensionAPI);
592
-
593
- // The parent is not a registered child, so it publishes its service.
594
- await fireSessionStart(
595
- parentPi,
596
- makeChildCtx(parentCwd, "parent-session-mi"),
597
- );
598
- const parentService = getPermissionsService();
599
- expect(parentService).toBeDefined();
600
-
601
- // The child is registered in the shared global registry before its own
602
- // session_start, so it detects itself and skips publishing.
603
- getSubagentSessionRegistry().register(childSessionId, {
604
- parentSessionId: "parent-session-mi",
605
- });
606
- await fireSessionStart(childPi, makeChildCtx(childCwd, childSessionId));
607
-
608
- // Mid-run: the slot resolves the parent's service, never the child's.
609
- expect(getPermissionsService()).toBe(parentService);
610
-
611
- // The child's shutdown is a no-op for the slot it never owned.
612
- await childPi.fire("session_shutdown");
613
- expect(getPermissionsService()).toBe(parentService);
614
-
615
- rmSync(parentCwd, { recursive: true, force: true });
616
- rmSync(childCwd, { recursive: true, force: true });
617
- });
618
- });
619
-
620
- describe("session approvals do not leak across same-cwd session switches", () => {
621
- // Pi caches the extension *import* (the jiti module, factory function) for
622
- // same-cwd `/new` / `/resume` / `/fork` / `/import` switches
623
- // (earendil-works/pi#5905). The factory is still re-invoked per switch, and
624
- // `session_shutdown` still fires — so a session-scoped "allow for this
625
- // session" grant must not survive into the next session.
626
- //
627
- // Two factory invocations against the same cwd model the cached-import
628
- // switch: invocation #1 records an approval and shuts down; invocation #2 is
629
- // the re-invoked cached factory. The new session must start with an empty
630
- // SessionRules. Two independent mechanisms keep it empty, and the grant only
631
- // leaks if *both* break together: `session_shutdown` clears the first
632
- // instance's rules, and the re-invoked factory builds a fresh SessionRules
633
- // (no module-scoped state bridges the switch — the per-session reset the
634
- // fresh-jiti load used to provide is gone once the import is cached).
635
-
636
- /** A UI ctx that approves the gate's "for this session" option (options[1]). */
637
- function makeSessionApprovingCtx(cwd: string, sessionId: string): unknown {
638
- return {
639
- cwd,
640
- hasUI: true,
641
- sessionManager: {
642
- getEntries: (): unknown[] => [],
643
- getSessionId: (): string => sessionId,
644
- getSessionDir: (): string => cwd,
645
- },
646
- ui: {
647
- notify: (): void => {},
648
- setStatus: (): void => {},
649
- select: async (
650
- _title: string,
651
- options: string[],
652
- ): Promise<string | undefined> => options[1],
653
- input: async (): Promise<string | undefined> => undefined,
654
- },
655
- };
656
- }
657
-
658
- it("starts the next same-cwd session with an empty session ruleset", async () => {
659
- writeGlobalConfig({
660
- permission: { "*": "allow", demo: "ask" },
661
- });
662
-
663
- const cwd = mkdtempSync(join(tmpdir(), "pi-perm-switch-cwd-"));
664
-
665
- // ── Session #1: approve `demo` for the session, then shut down ──────────
666
- const firstPi = makeFakePi({ toolNames: ["demo"] });
667
- piPermissionSystemExtension(firstPi as unknown as ExtensionAPI);
668
-
669
- const firstCtx = makeSessionApprovingCtx(cwd, "switch-session-1");
670
- await fireSessionStart(firstPi, firstCtx);
671
-
672
- // The gate prompts and the mock selects options[1], recording a
673
- // session-scoped approval the service can read back.
674
- await firstPi.fire(
675
- "tool_call",
676
- { toolName: "demo", toolCallId: "demo-approve", input: { foo: "bar" } },
677
- firstCtx,
678
- );
679
- expect(getPermissionsService()!.checkPermission("demo").state).toBe(
680
- "allow",
681
- );
682
-
683
- // The switch tears down the old session before the new one starts.
684
- await firstPi.fire("session_shutdown");
685
-
686
- // ── Session #2: the re-invoked cached factory, same cwd ────────────────
687
- const secondPi = makeFakePi({ toolNames: ["demo"] });
688
- piPermissionSystemExtension(secondPi as unknown as ExtensionAPI);
689
-
690
- await fireSessionStart(secondPi, makeChildCtx(cwd, "switch-session-2"));
691
-
692
- // The previous session's approval must not be visible: `demo` is back to
693
- // its configured `ask`, not the carried-over `allow`.
694
- expect(getPermissionsService()!.checkPermission("demo").state).toBe("ask");
695
-
696
- rmSync(cwd, { recursive: true, force: true });
697
- });
698
- });