@gotgenes/pi-permission-system 18.1.1 → 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 (122) hide show
  1. package/CHANGELOG.md +16 -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/path-normalizer.ts +105 -2
  8. package/test/access-intent/access-path.test.ts +0 -277
  9. package/test/access-intent/bash/node-text.test.ts +0 -148
  10. package/test/access-intent/bash/parser.test.ts +0 -19
  11. package/test/access-intent/bash/program.test.ts +0 -673
  12. package/test/access-intent/bash/token-classification.test.ts +0 -363
  13. package/test/access-intent/bash/token-collection.test.ts +0 -300
  14. package/test/active-agent.test.ts +0 -155
  15. package/test/async-cache.test.ts +0 -48
  16. package/test/bash-arity.test.ts +0 -144
  17. package/test/bash-external-directory.test.ts +0 -1022
  18. package/test/builtin-tool-input-formatters.test.ts +0 -109
  19. package/test/canonicalize-path.test.ts +0 -119
  20. package/test/composition-root.test.ts +0 -698
  21. package/test/config-loader.test.ts +0 -740
  22. package/test/config-modal.test.ts +0 -320
  23. package/test/config-paths.test.ts +0 -83
  24. package/test/config-pipeline.test.ts +0 -90
  25. package/test/config-reporter.test.ts +0 -147
  26. package/test/config-store.test.ts +0 -466
  27. package/test/decision-audit.test.ts +0 -72
  28. package/test/decision-reporter.test.ts +0 -112
  29. package/test/denial-messages.test.ts +0 -714
  30. package/test/detect-permissive-bash-fallback.test.ts +0 -56
  31. package/test/expand-home.test.ts +0 -93
  32. package/test/extension-config.test.ts +0 -129
  33. package/test/extension-paths.test.ts +0 -108
  34. package/test/forwarded-permissions/io.test.ts +0 -251
  35. package/test/forwarding-manager.test.ts +0 -200
  36. package/test/handlers/before-agent-start.test.ts +0 -314
  37. package/test/handlers/external-directory-integration.test.ts +0 -515
  38. package/test/handlers/external-directory-session-dedup.test.ts +0 -175
  39. package/test/handlers/external-directory-symlink-acceptance.test.ts +0 -167
  40. package/test/handlers/gates/bash-command-metamorphic.test.ts +0 -88
  41. package/test/handlers/gates/bash-command.test.ts +0 -257
  42. package/test/handlers/gates/bash-external-directory.test.ts +0 -268
  43. package/test/handlers/gates/bash-path.test.ts +0 -346
  44. package/test/handlers/gates/candidate-check.test.ts +0 -52
  45. package/test/handlers/gates/external-directory-messages.test.ts +0 -85
  46. package/test/handlers/gates/external-directory-policy.test.ts +0 -134
  47. package/test/handlers/gates/external-directory.test.ts +0 -267
  48. package/test/handlers/gates/helpers.test.ts +0 -165
  49. package/test/handlers/gates/path.test.ts +0 -369
  50. package/test/handlers/gates/runner.test.ts +0 -408
  51. package/test/handlers/gates/skill-input-gate-pipeline.test.ts +0 -176
  52. package/test/handlers/gates/skill-input.test.ts +0 -128
  53. package/test/handlers/gates/skill-read.test.ts +0 -161
  54. package/test/handlers/gates/tool-call-gate-pipeline.test.ts +0 -356
  55. package/test/handlers/gates/tool.test.ts +0 -244
  56. package/test/handlers/input-events.test.ts +0 -168
  57. package/test/handlers/input.test.ts +0 -199
  58. package/test/handlers/lifecycle.test.ts +0 -221
  59. package/test/handlers/tool-call-boundary.test.ts +0 -145
  60. package/test/handlers/tool-call-events.test.ts +0 -277
  61. package/test/handlers/tool-call.test.ts +0 -395
  62. package/test/handlers/validate-requested-tool.test.ts +0 -92
  63. package/test/helpers/external-directory-fixtures.ts +0 -269
  64. package/test/helpers/gate-fixtures.ts +0 -316
  65. package/test/helpers/handler-fixtures.ts +0 -335
  66. package/test/helpers/make-fake-pi.ts +0 -100
  67. package/test/helpers/manager-harness.ts +0 -112
  68. package/test/helpers/session-fixtures.ts +0 -199
  69. package/test/input-normalizer.test.ts +0 -325
  70. package/test/logging.test.ts +0 -51
  71. package/test/mcp-targets.test.ts +0 -233
  72. package/test/node-modules-discovery.test.ts +0 -97
  73. package/test/normalize.test.ts +0 -247
  74. package/test/path-containment.test.ts +0 -161
  75. package/test/path-normalization.test.ts +0 -233
  76. package/test/path-normalizer.test.ts +0 -196
  77. package/test/path-surfaces.test.ts +0 -55
  78. package/test/pattern-suggest.test.ts +0 -248
  79. package/test/permission-dialog.test.ts +0 -205
  80. package/test/permission-event-rpc.test.ts +0 -560
  81. package/test/permission-events.test.ts +0 -400
  82. package/test/permission-forwarder.test.ts +0 -370
  83. package/test/permission-forwarding.test.ts +0 -315
  84. package/test/permission-gate.test.ts +0 -269
  85. package/test/permission-manager-unified.test.ts +0 -3714
  86. package/test/permission-merge.test.ts +0 -61
  87. package/test/permission-prompter.test.ts +0 -518
  88. package/test/permission-prompts.test.ts +0 -363
  89. package/test/permission-resolver.test.ts +0 -277
  90. package/test/permission-session.test.ts +0 -404
  91. package/test/permission-ui-prompt.test.ts +0 -146
  92. package/test/permissions-service.test.ts +0 -192
  93. package/test/pi-infrastructure-read.test.ts +0 -432
  94. package/test/policy-loader.test.ts +0 -561
  95. package/test/prompting-gateway.test.ts +0 -231
  96. package/test/rule.test.ts +0 -650
  97. package/test/safe-system-paths.test.ts +0 -46
  98. package/test/scope-merge.test.ts +0 -116
  99. package/test/service-lifecycle.test.ts +0 -163
  100. package/test/service.test.ts +0 -261
  101. package/test/session-approval.test.ts +0 -75
  102. package/test/session-logger.test.ts +0 -200
  103. package/test/session-rules.test.ts +0 -321
  104. package/test/session-start.test.ts +0 -112
  105. package/test/skill-prompt-sanitizer.test.ts +0 -418
  106. package/test/status.test.ts +0 -10
  107. package/test/subagent-context.test.ts +0 -372
  108. package/test/subagent-lifecycle-events.test.ts +0 -132
  109. package/test/subagent-registry.test.ts +0 -145
  110. package/test/synthesize.test.ts +0 -302
  111. package/test/system-prompt-sanitizer.test.ts +0 -382
  112. package/test/tool-access-extractor-registry.test.ts +0 -77
  113. package/test/tool-input-formatter-registry.test.ts +0 -75
  114. package/test/tool-input-path.test.ts +0 -84
  115. package/test/tool-input-preview.test.ts +0 -129
  116. package/test/tool-input-prompt-formatters.test.ts +0 -115
  117. package/test/tool-preview-formatter.test.ts +0 -458
  118. package/test/tool-registry.test.ts +0 -197
  119. package/test/value-guards.test.ts +0 -193
  120. package/test/wildcard-matcher.test.ts +0 -424
  121. package/test/yaml-frontmatter.test.ts +0 -91
  122. 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
- }