@gotgenes/pi-permission-system 18.1.0 → 18.1.2

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 (132) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/docs/assets/logo.png +0 -0
  3. package/docs/assets/logo.svg +213 -0
  4. package/docs/configuration.md +700 -0
  5. package/docs/cross-extension-api.md +525 -0
  6. package/docs/guides/permission-frontmatter-for-subagent-extensions.md +201 -0
  7. package/docs/guides/upstream-issue-template.md +113 -0
  8. package/docs/migration/legacy-to-flat.md +365 -0
  9. package/docs/opencode-compatibility.md +213 -0
  10. package/docs/session-approvals.md +68 -0
  11. package/docs/subagent-integration.md +102 -0
  12. package/docs/troubleshooting.md +53 -0
  13. package/package.json +5 -2
  14. package/src/access-intent/access-path.ts +29 -4
  15. package/src/access-intent/bash/bash-path-resolver.ts +39 -18
  16. package/src/access-intent/bash/msys-bash-tokens.ts +64 -0
  17. package/src/path-normalizer.ts +105 -2
  18. package/test/access-intent/access-path.test.ts +0 -277
  19. package/test/access-intent/bash/node-text.test.ts +0 -148
  20. package/test/access-intent/bash/parser.test.ts +0 -19
  21. package/test/access-intent/bash/program.test.ts +0 -673
  22. package/test/access-intent/bash/token-classification.test.ts +0 -363
  23. package/test/access-intent/bash/token-collection.test.ts +0 -300
  24. package/test/active-agent.test.ts +0 -155
  25. package/test/async-cache.test.ts +0 -48
  26. package/test/bash-arity.test.ts +0 -144
  27. package/test/bash-external-directory.test.ts +0 -1022
  28. package/test/builtin-tool-input-formatters.test.ts +0 -109
  29. package/test/canonicalize-path.test.ts +0 -119
  30. package/test/composition-root.test.ts +0 -698
  31. package/test/config-loader.test.ts +0 -740
  32. package/test/config-modal.test.ts +0 -320
  33. package/test/config-paths.test.ts +0 -83
  34. package/test/config-pipeline.test.ts +0 -90
  35. package/test/config-reporter.test.ts +0 -147
  36. package/test/config-store.test.ts +0 -466
  37. package/test/decision-audit.test.ts +0 -72
  38. package/test/decision-reporter.test.ts +0 -112
  39. package/test/denial-messages.test.ts +0 -714
  40. package/test/detect-permissive-bash-fallback.test.ts +0 -56
  41. package/test/expand-home.test.ts +0 -93
  42. package/test/extension-config.test.ts +0 -129
  43. package/test/extension-paths.test.ts +0 -108
  44. package/test/forwarded-permissions/io.test.ts +0 -251
  45. package/test/forwarding-manager.test.ts +0 -200
  46. package/test/handlers/before-agent-start.test.ts +0 -314
  47. package/test/handlers/external-directory-integration.test.ts +0 -515
  48. package/test/handlers/external-directory-session-dedup.test.ts +0 -175
  49. package/test/handlers/external-directory-symlink-acceptance.test.ts +0 -167
  50. package/test/handlers/gates/bash-command-metamorphic.test.ts +0 -88
  51. package/test/handlers/gates/bash-command.test.ts +0 -257
  52. package/test/handlers/gates/bash-external-directory.test.ts +0 -268
  53. package/test/handlers/gates/bash-path.test.ts +0 -346
  54. package/test/handlers/gates/candidate-check.test.ts +0 -52
  55. package/test/handlers/gates/external-directory-messages.test.ts +0 -85
  56. package/test/handlers/gates/external-directory-policy.test.ts +0 -134
  57. package/test/handlers/gates/external-directory.test.ts +0 -267
  58. package/test/handlers/gates/helpers.test.ts +0 -165
  59. package/test/handlers/gates/path.test.ts +0 -369
  60. package/test/handlers/gates/runner.test.ts +0 -408
  61. package/test/handlers/gates/skill-input-gate-pipeline.test.ts +0 -176
  62. package/test/handlers/gates/skill-input.test.ts +0 -128
  63. package/test/handlers/gates/skill-read.test.ts +0 -161
  64. package/test/handlers/gates/tool-call-gate-pipeline.test.ts +0 -356
  65. package/test/handlers/gates/tool.test.ts +0 -244
  66. package/test/handlers/input-events.test.ts +0 -168
  67. package/test/handlers/input.test.ts +0 -199
  68. package/test/handlers/lifecycle.test.ts +0 -221
  69. package/test/handlers/tool-call-boundary.test.ts +0 -145
  70. package/test/handlers/tool-call-events.test.ts +0 -277
  71. package/test/handlers/tool-call.test.ts +0 -395
  72. package/test/handlers/validate-requested-tool.test.ts +0 -92
  73. package/test/helpers/external-directory-fixtures.ts +0 -269
  74. package/test/helpers/gate-fixtures.ts +0 -316
  75. package/test/helpers/handler-fixtures.ts +0 -335
  76. package/test/helpers/make-fake-pi.ts +0 -100
  77. package/test/helpers/manager-harness.ts +0 -112
  78. package/test/helpers/session-fixtures.ts +0 -199
  79. package/test/input-normalizer.test.ts +0 -325
  80. package/test/logging.test.ts +0 -51
  81. package/test/mcp-targets.test.ts +0 -233
  82. package/test/node-modules-discovery.test.ts +0 -97
  83. package/test/normalize.test.ts +0 -247
  84. package/test/path-containment.test.ts +0 -161
  85. package/test/path-normalization.test.ts +0 -233
  86. package/test/path-normalizer.test.ts +0 -196
  87. package/test/path-surfaces.test.ts +0 -55
  88. package/test/pattern-suggest.test.ts +0 -248
  89. package/test/permission-dialog.test.ts +0 -205
  90. package/test/permission-event-rpc.test.ts +0 -560
  91. package/test/permission-events.test.ts +0 -400
  92. package/test/permission-forwarder.test.ts +0 -370
  93. package/test/permission-forwarding.test.ts +0 -315
  94. package/test/permission-gate.test.ts +0 -269
  95. package/test/permission-manager-unified.test.ts +0 -3714
  96. package/test/permission-merge.test.ts +0 -61
  97. package/test/permission-prompter.test.ts +0 -518
  98. package/test/permission-prompts.test.ts +0 -363
  99. package/test/permission-resolver.test.ts +0 -277
  100. package/test/permission-session.test.ts +0 -404
  101. package/test/permission-ui-prompt.test.ts +0 -146
  102. package/test/permissions-service.test.ts +0 -192
  103. package/test/pi-infrastructure-read.test.ts +0 -432
  104. package/test/policy-loader.test.ts +0 -561
  105. package/test/prompting-gateway.test.ts +0 -231
  106. package/test/rule.test.ts +0 -650
  107. package/test/safe-system-paths.test.ts +0 -46
  108. package/test/scope-merge.test.ts +0 -116
  109. package/test/service-lifecycle.test.ts +0 -163
  110. package/test/service.test.ts +0 -261
  111. package/test/session-approval.test.ts +0 -75
  112. package/test/session-logger.test.ts +0 -200
  113. package/test/session-rules.test.ts +0 -321
  114. package/test/session-start.test.ts +0 -112
  115. package/test/skill-prompt-sanitizer.test.ts +0 -418
  116. package/test/status.test.ts +0 -10
  117. package/test/subagent-context.test.ts +0 -372
  118. package/test/subagent-lifecycle-events.test.ts +0 -132
  119. package/test/subagent-registry.test.ts +0 -145
  120. package/test/synthesize.test.ts +0 -302
  121. package/test/system-prompt-sanitizer.test.ts +0 -382
  122. package/test/tool-access-extractor-registry.test.ts +0 -77
  123. package/test/tool-input-formatter-registry.test.ts +0 -75
  124. package/test/tool-input-path.test.ts +0 -84
  125. package/test/tool-input-preview.test.ts +0 -129
  126. package/test/tool-input-prompt-formatters.test.ts +0 -115
  127. package/test/tool-preview-formatter.test.ts +0 -458
  128. package/test/tool-registry.test.ts +0 -197
  129. package/test/value-guards.test.ts +0 -193
  130. package/test/wildcard-matcher.test.ts +0 -424
  131. package/test/yaml-frontmatter.test.ts +0 -91
  132. package/test/yolo-mode.test.ts +0 -188
@@ -1,335 +0,0 @@
1
- /**
2
- * Shared handler-level test fixtures for PermissionGateHandler tests.
3
- *
4
- * `makeHandler` builds a real PermissionSession + PermissionResolver and wires
5
- * them into the handler and pipelines exactly as `index.ts` does.
6
- * Call-site overrides for permission results flow through
7
- * `permissionManager.check`; session state overrides are applied
8
- * via vi.spyOn on the real session instance.
9
- */
10
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
11
- import { vi } from "vitest";
12
-
13
- import type { ResolvedAccessIntent } from "#src/access-intent/access-intent";
14
- import { GateDecisionReporter } from "#src/decision-reporter";
15
- import type { GatePrompter } from "#src/gate-prompter";
16
- import { GateRunner } from "#src/handlers/gates/runner";
17
- import {
18
- type SkillInputGateInputs,
19
- SkillInputGatePipeline,
20
- } from "#src/handlers/gates/skill-input-gate-pipeline";
21
- import {
22
- type ToolCallGateInputs,
23
- ToolCallGatePipeline,
24
- } from "#src/handlers/gates/tool-call-gate-pipeline";
25
- import { PermissionGateHandler } from "#src/handlers/permission-gate-handler";
26
- import type { PermissionDecisionEvent } from "#src/permission-events";
27
- import { PERMISSIONS_DECISION_CHANNEL } from "#src/permission-events";
28
- import type { Rule } from "#src/rule";
29
- import { SessionRules } from "#src/session-rules";
30
- import type { ToolRegistry } from "#src/tool-registry";
31
- import type { PermissionCheckResult, PermissionState } from "#src/types";
32
- import {
33
- makeRealResolver,
34
- makeRealSession,
35
- } from "#test/helpers/session-fixtures";
36
-
37
- // ── MockGateHandlerSession ────────────────────────────────────────────────
38
-
39
- /**
40
- * Mock type for gate-pipeline inputs (ToolCallGateInputs + SkillInputGateInputs).
41
- *
42
- * Used by `makeSurfaceCheck`, `makeBashCommandCheck`, and the `session`
43
- * override bag in `makeHandler`. The `GateHandlerSession` role (activate +
44
- * resolveAgentName) is now satisfied by the real `PermissionSession`; this
45
- * type covers only the pipeline input surface.
46
- *
47
- * The 4-arg `checkPermission` is a superset of `SkillInputGateInputs` —
48
- * it routes through `permissionManager.checkPermission` in production.
49
- */
50
- export type MockGateHandlerSession = ToolCallGateInputs &
51
- SkillInputGateInputs & {
52
- /** 4-arg form so surface-check mocks can receive optional rules. */
53
- checkPermission(
54
- surface: string,
55
- input: unknown,
56
- agentName?: string,
57
- rules?: Rule[],
58
- ): PermissionCheckResult;
59
- };
60
-
61
- // ── Small utility factories ───────────────────────────────────────────────
62
-
63
- export function makeEvents() {
64
- return {
65
- emit: vi.fn(),
66
- on: vi.fn().mockReturnValue(() => undefined),
67
- };
68
- }
69
-
70
- export function makeCtx(
71
- overrides: Partial<ExtensionContext> = {},
72
- ): ExtensionContext {
73
- return {
74
- cwd: "/test/project",
75
- hasUI: true,
76
- ui: {
77
- setStatus: vi.fn(),
78
- notify: vi.fn(),
79
- select: vi.fn(),
80
- input: vi.fn(),
81
- },
82
- sessionManager: {
83
- getEntries: vi.fn().mockReturnValue([]),
84
- getSessionDir: vi.fn().mockReturnValue("/sessions/test"),
85
- addEntry: vi.fn(),
86
- },
87
- ...overrides,
88
- } as unknown as ExtensionContext;
89
- }
90
-
91
- export function makeToolCallEvent(
92
- toolName: string,
93
- extraFields: Record<string, unknown> = {},
94
- ) {
95
- return {
96
- type: "tool_call",
97
- toolCallId: "tc-1",
98
- name: toolName,
99
- input: {},
100
- ...extraFields,
101
- };
102
- }
103
-
104
- /**
105
- * Neutral-default check-result builder.
106
- *
107
- * Pass exactly the fields the original fixture hard-coded so divergent
108
- * defaults across test files are preserved at their call sites.
109
- */
110
- export function makeCheckResult(
111
- overrides: Partial<PermissionCheckResult> = {},
112
- ): PermissionCheckResult {
113
- return {
114
- state: "allow",
115
- toolName: "read",
116
- source: "tool",
117
- origin: "builtin",
118
- ...overrides,
119
- };
120
- }
121
-
122
- export function makeToolRegistry(
123
- overrides: Partial<ToolRegistry> = {},
124
- ): ToolRegistry {
125
- return {
126
- getAll: vi.fn().mockReturnValue([{ name: "read" }, { name: "bash" }]),
127
- getActive: vi.fn().mockReturnValue(["read", "bash"]),
128
- setActive: vi.fn(),
129
- ...overrides,
130
- };
131
- }
132
-
133
- // ── Surface-check factories ────────────────────────────────────────────────
134
-
135
- /**
136
- * Surface-dispatching `checkPermission` mock.
137
- *
138
- * Returns the matching per-surface result or `defaultResult`.
139
- * Pass the returned function as `session.checkPermission` in a `makeHandler`
140
- * override bag — it is applied to `permissionManager.checkPermission`.
141
- *
142
- * Return type is intentionally unannotated so callers retain full `vi.fn()`
143
- * mock access (`mock.calls`, `toHaveBeenCalledWith`, etc.).
144
- */
145
- export function makeSurfaceCheck(
146
- bySurface: Record<
147
- string,
148
- Partial<PermissionCheckResult> & { state: PermissionState }
149
- >,
150
- defaultResult: Partial<PermissionCheckResult> & { state: PermissionState } = {
151
- state: "allow",
152
- },
153
- ) {
154
- return vi
155
- .fn<MockGateHandlerSession["checkPermission"]>()
156
- .mockImplementation((surface): PermissionCheckResult => {
157
- const base = bySurface[surface] ?? defaultResult;
158
- return {
159
- toolName: surface,
160
- source: "tool",
161
- origin: "builtin",
162
- ...base,
163
- };
164
- });
165
- }
166
-
167
- /**
168
- * Bash-surface `checkPermission` mock that dispatches on a command regex.
169
- *
170
- * Pass the returned function as `session.checkPermission` in a `makeHandler`
171
- * override bag — it is applied to `permissionManager.checkPermission`.
172
- *
173
- * Return type is intentionally unannotated so callers retain full `vi.fn()`
174
- * mock access.
175
- */
176
- export function makeBashCommandCheck(opts: {
177
- deny: RegExp;
178
- denyMatched: string;
179
- allowMatched?: string;
180
- }) {
181
- return vi
182
- .fn<MockGateHandlerSession["checkPermission"]>()
183
- .mockImplementation((surface, input): PermissionCheckResult => {
184
- if (surface === "bash") {
185
- const command = (input as { command?: string }).command ?? "";
186
- return opts.deny.test(command)
187
- ? makeCheckResult({
188
- state: "deny",
189
- source: "bash",
190
- command,
191
- matchedPattern: opts.denyMatched,
192
- })
193
- : makeCheckResult({
194
- state: "allow",
195
- source: "bash",
196
- command,
197
- matchedPattern: opts.allowMatched,
198
- });
199
- }
200
- return makeCheckResult({ state: "allow" });
201
- });
202
- }
203
-
204
- // ── makeHandler ────────────────────────────────────────────────────────────
205
-
206
- /**
207
- * Constructs a PermissionGateHandler wired with real collaborators.
208
- *
209
- * The `session` override bag maps to the real collaborators:
210
- * - `checkPermission` → applied to `permissionManager.checkPermission`
211
- * - `getActiveSkillEntries`, `getInfrastructureReadDirs`, `getToolPreviewLimits`
212
- * → applied as vi.spyOn overrides on the real session
213
- * - `resolveAgentName` → applied as a vi.spyOn override on the real session
214
- *
215
- * Returns `{ handler, events, session, toolRegistry, prompter, recorder,
216
- * permissionManager, forwarding }` so each test file can destructure only
217
- * what it needs.
218
- * `session.activate` is not a mock — use `forwarding.start` to assert it
219
- * was called.
220
- */
221
- export function makeHandler(overrides?: {
222
- session?: Partial<MockGateHandlerSession> & {
223
- resolveAgentName?: (
224
- ctx: ExtensionContext,
225
- systemPrompt?: string,
226
- ) => string | null;
227
- };
228
- /** Override the GatePrompter passed to GateRunner. Defaults to an allow-all stub. */
229
- prompter?: GatePrompter;
230
- toolRegistry?: Partial<ToolRegistry>;
231
- /** Sugar: builds the `getAll` mock from a list of tool names. */
232
- tools?: string[];
233
- }) {
234
- const { session, permissionManager, sessionRules, forwarding, logger } =
235
- makeRealSession();
236
- const { resolver } = makeRealResolver(permissionManager, sessionRules);
237
-
238
- // Apply session override bag to the real collaborators.
239
- const so = overrides?.session;
240
- const surfaceCheck = so?.checkPermission;
241
- if (surfaceCheck) {
242
- // Route the unified check(intent) through the surface dispatcher so
243
- // makeSurfaceCheck / makeBashCommandCheck overrides apply to all gate
244
- // paths via the single manager entry point (#478).
245
- vi.mocked(permissionManager.check).mockImplementation(
246
- (intent: ResolvedAccessIntent, sessionRules) => {
247
- if (intent.kind === "path-values") {
248
- return surfaceCheck(
249
- intent.surface,
250
- { path: intent.values[0] ?? "*" },
251
- intent.agentName,
252
- sessionRules,
253
- );
254
- }
255
- return surfaceCheck(
256
- intent.surface,
257
- intent.input,
258
- intent.agentName,
259
- sessionRules,
260
- );
261
- },
262
- );
263
- }
264
- if (so?.getActiveSkillEntries) {
265
- vi.spyOn(session, "getActiveSkillEntries").mockImplementation(
266
- so.getActiveSkillEntries,
267
- );
268
- }
269
- if (so?.getInfrastructureReadDirs) {
270
- vi.spyOn(session, "getInfrastructureReadDirs").mockImplementation(
271
- so.getInfrastructureReadDirs,
272
- );
273
- }
274
- if (so?.getToolPreviewLimits) {
275
- vi.spyOn(session, "getToolPreviewLimits").mockImplementation(
276
- so.getToolPreviewLimits,
277
- );
278
- }
279
- if (so?.resolveAgentName) {
280
- vi.spyOn(session, "resolveAgentName").mockImplementation(
281
- so.resolveAgentName,
282
- );
283
- }
284
-
285
- const events = makeEvents();
286
- const toolRegistry =
287
- overrides?.tools !== undefined
288
- ? makeToolRegistry({
289
- getAll: vi
290
- .fn()
291
- .mockReturnValue(overrides.tools.map((name) => ({ name }))),
292
- })
293
- : makeToolRegistry(overrides?.toolRegistry);
294
-
295
- const recorder = new SessionRules();
296
- const pipeline = new ToolCallGatePipeline(resolver, session);
297
- const skillInputPipeline = new SkillInputGatePipeline(resolver);
298
- const reporter = new GateDecisionReporter(logger, events);
299
- const prompter: GatePrompter = overrides?.prompter ?? {
300
- canConfirm: vi.fn().mockReturnValue(true),
301
- prompt: vi
302
- .fn<GatePrompter["prompt"]>()
303
- .mockResolvedValue({ approved: true, state: "approved" }),
304
- };
305
- const runner = new GateRunner(resolver, recorder, prompter, reporter);
306
- const handler = new PermissionGateHandler(
307
- session,
308
- toolRegistry,
309
- pipeline,
310
- skillInputPipeline,
311
- runner,
312
- );
313
- return {
314
- handler,
315
- events,
316
- session,
317
- logger,
318
- toolRegistry,
319
- prompter,
320
- recorder,
321
- permissionManager,
322
- forwarding,
323
- };
324
- }
325
-
326
- // ── Decision-event helper ─────────────────────────────────────────────────
327
-
328
- /** Extract all permissions:decision payloads from the events.emit mock. */
329
- export function getDecisionEvents(
330
- events: ReturnType<typeof makeEvents>,
331
- ): PermissionDecisionEvent[] {
332
- return events.emit.mock.calls
333
- .filter(([channel]) => channel === PERMISSIONS_DECISION_CHANNEL)
334
- .map(([, payload]) => payload as PermissionDecisionEvent);
335
- }
@@ -1,100 +0,0 @@
1
- /**
2
- * `makeFakePi()` — a composition-root test harness.
3
- *
4
- * Lets a test run the real `piPermissionSystemExtension(pi)` factory and then
5
- * introspect and drive the result. Unlike the per-handler unit fixtures in
6
- * `handler-fixtures.ts` (which inject collaborators), this harness exercises the
7
- * factory itself — the wiring layer where registration completeness, shared-
8
- * instance contracts, teardown, and event ordering live.
9
- *
10
- * It provides:
11
- * - `events` — a real `createEventBus()` so cross-extension pub/sub and RPC
12
- * behave as in production (tests can inject a shared bus to model parent/child
13
- * instances).
14
- * - `handlers` — every `pi.on(event, handler)` registration, keyed by event
15
- * name, so a test can assert completeness and fire handlers.
16
- * - `commands` — every `pi.registerCommand(name, …)` registration.
17
- * - `fire(event, input, ctx)` — drive a registered handler; resolves to its
18
- * (possibly async) result.
19
- *
20
- * The harness object is cast to `ExtensionAPI` at the call to the factory; the
21
- * `FakePi` interface itself stays narrow (ISP — only what the factory touches).
22
- */
23
- import { createEventBus, type EventBus } from "@earendil-works/pi-coding-agent";
24
- import { vi } from "vitest";
25
-
26
- /** A handler recorded by `pi.on(...)`, kept generic over event/result shapes. */
27
- export type RecordedHandler = (event: unknown, ctx: unknown) => unknown;
28
-
29
- export interface FakePi {
30
- /** Real event bus so cross-extension pub/sub and RPC behave as in production. */
31
- events: EventBus;
32
- /** Every `pi.on(event, handler)` registration, keyed by event name. */
33
- handlers: Map<string, RecordedHandler>;
34
- /** Every `pi.registerCommand(name, …)` registration, keyed by command name. */
35
- commands: Map<string, unknown>;
36
- /**
37
- * Drive a registered handler; resolves to its (possibly async) result.
38
- *
39
- * Throws if no handler is registered for `event` so a typo in a test surfaces
40
- * loudly instead of silently resolving to `undefined`.
41
- */
42
- fire(event: string, input?: unknown, ctx?: unknown): Promise<unknown>;
43
- /** Minimal tool registry — returns the configured tool names. */
44
- getAllTools(): { name: string }[];
45
- /** Active tool names (`pi.getActiveTools()` shape — bare strings). */
46
- getActiveTools(): string[];
47
- setActiveTools(names: string[]): void;
48
- }
49
-
50
- export interface MakeFakePiOptions {
51
- /** Inject a shared bus to model parent/child instances; defaults to a fresh bus. */
52
- events?: EventBus;
53
- /** Tool names returned by `getAllTools()`; defaults to a small set. */
54
- toolNames?: readonly string[];
55
- }
56
-
57
- const DEFAULT_TOOL_NAMES = ["read", "write", "edit", "bash", "ls", "grep"];
58
-
59
- /**
60
- * Build a fake `ExtensionAPI` for composition-root tests.
61
- *
62
- * The returned object is structurally a `FakePi`; pass it to the factory as
63
- * `piPermissionSystemExtension(pi as unknown as ExtensionAPI)`.
64
- */
65
- export function makeFakePi(options: MakeFakePiOptions = {}): FakePi {
66
- const events = options.events ?? createEventBus();
67
- const toolNames = options.toolNames ?? DEFAULT_TOOL_NAMES;
68
- const handlers = new Map<string, RecordedHandler>();
69
- const commands = new Map<string, unknown>();
70
-
71
- return {
72
- events,
73
- handlers,
74
- commands,
75
- fire(event, input, ctx): Promise<unknown> {
76
- const handler = handlers.get(event);
77
- if (!handler) {
78
- throw new Error(`No handler registered for event "${event}"`);
79
- }
80
- return Promise.resolve(handler(input, ctx));
81
- },
82
- getAllTools(): { name: string }[] {
83
- return toolNames.map((name) => ({ name }));
84
- },
85
- getActiveTools(): string[] {
86
- return [...toolNames];
87
- },
88
- setActiveTools: vi.fn(),
89
- // ── ExtensionAPI methods the factory touches (recorded) ────────────────
90
- on(event: string, handler: RecordedHandler): void {
91
- handlers.set(event, handler);
92
- },
93
- registerCommand(name: string, optionsArg: unknown): void {
94
- commands.set(name, optionsArg);
95
- },
96
- // ── ExtensionAPI methods present for the cast but unused by the factory ─
97
- registerProvider: vi.fn(),
98
- exec: vi.fn(),
99
- } as FakePi & Record<string, unknown>;
100
- }
@@ -1,112 +0,0 @@
1
- /**
2
- * Filesystem-backed PermissionManager harness for integration tests.
3
- *
4
- * Writes a real config file and agents directory to a temp directory so
5
- * PermissionManager can load them without mocking the file system.
6
- */
7
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
8
- import { tmpdir } from "node:os";
9
- import { join } from "node:path";
10
-
11
- import { PermissionManager } from "#src/permission-manager";
12
- import type { ScopeConfig } from "#src/types";
13
-
14
- export type CreateManagerOptions = {
15
- mcpServerNames?: readonly string[];
16
- };
17
-
18
- export type CreateManagerWithProjectOptions = CreateManagerOptions & {
19
- projectConfig?: ScopeConfig;
20
- projectAgentFiles?: Record<string, string>;
21
- };
22
-
23
- export function createManager(
24
- config: ScopeConfig,
25
- agentFiles: Record<string, string> = {},
26
- options: CreateManagerOptions = {},
27
- ) {
28
- const baseDir = mkdtempSync(join(tmpdir(), "pi-permission-system-test-"));
29
- const globalConfigPath = join(baseDir, "pi-permissions.jsonc");
30
- const agentsDir = join(baseDir, "agents");
31
-
32
- mkdirSync(agentsDir, { recursive: true });
33
- writeFileSync(
34
- globalConfigPath,
35
- `${JSON.stringify(config, null, 2)}\n`,
36
- "utf8",
37
- );
38
-
39
- for (const [name, content] of Object.entries(agentFiles)) {
40
- writeFileSync(join(agentsDir, `${name}.md`), content, "utf8");
41
- }
42
-
43
- const manager = new PermissionManager({
44
- globalConfigPath,
45
- agentsDir,
46
- mcpServerNames: options.mcpServerNames,
47
- });
48
-
49
- return {
50
- manager,
51
- globalConfigPath,
52
- cleanup: (): void => {
53
- rmSync(baseDir, { recursive: true, force: true });
54
- },
55
- };
56
- }
57
-
58
- export function createManagerWithProject(
59
- config: ScopeConfig,
60
- agentFiles: Record<string, string> = {},
61
- options: CreateManagerWithProjectOptions = {},
62
- ) {
63
- const baseDir = mkdtempSync(
64
- join(tmpdir(), "pi-permission-system-proj-test-"),
65
- );
66
- const globalConfigPath = join(baseDir, "pi-permissions.jsonc");
67
- const agentsDir = join(baseDir, "agents");
68
- const projectRoot = join(baseDir, "project");
69
- const projectGlobalConfigPath = join(projectRoot, "pi-permissions.jsonc");
70
- const projectAgentsDir = join(projectRoot, "agents");
71
-
72
- mkdirSync(agentsDir, { recursive: true });
73
- mkdirSync(projectAgentsDir, { recursive: true });
74
-
75
- writeFileSync(
76
- globalConfigPath,
77
- `${JSON.stringify(config, null, 2)}\n`,
78
- "utf8",
79
- );
80
- if (options.projectConfig) {
81
- writeFileSync(
82
- projectGlobalConfigPath,
83
- `${JSON.stringify(options.projectConfig, null, 2)}\n`,
84
- "utf8",
85
- );
86
- }
87
-
88
- for (const [name, content] of Object.entries(agentFiles)) {
89
- writeFileSync(join(agentsDir, `${name}.md`), content, "utf8");
90
- }
91
-
92
- for (const [name, content] of Object.entries(
93
- options.projectAgentFiles ?? {},
94
- )) {
95
- writeFileSync(join(projectAgentsDir, `${name}.md`), content, "utf8");
96
- }
97
-
98
- const manager = new PermissionManager({
99
- globalConfigPath,
100
- agentsDir,
101
- projectGlobalConfigPath,
102
- projectAgentsDir,
103
- mcpServerNames: options.mcpServerNames,
104
- });
105
-
106
- return {
107
- manager,
108
- cleanup: (): void => {
109
- rmSync(baseDir, { recursive: true, force: true });
110
- },
111
- };
112
- }