@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,269 +0,0 @@
1
- /**
2
- * Shared fixtures for the external-directory handler-pipeline tests.
3
- *
4
- * Targets the collapsed external-directory gate (Phase 6 Step 5, #477).
5
- * Consumed by external-directory-integration.test.ts and
6
- * external-directory-session-dedup.test.ts.
7
- */
8
- import { vi } from "vitest";
9
-
10
- import { GateDecisionReporter } from "#src/decision-reporter";
11
- import type { GatePrompter } from "#src/gate-prompter";
12
- import { GateRunner } from "#src/handlers/gates/runner";
13
- import { SkillInputGatePipeline } from "#src/handlers/gates/skill-input-gate-pipeline";
14
- import { ToolCallGatePipeline } from "#src/handlers/gates/tool-call-gate-pipeline";
15
- import { PermissionGateHandler } from "#src/handlers/permission-gate-handler";
16
- import type { ScopedPermissionManager } from "#src/permission-manager";
17
- import type { SessionLogger } from "#src/session-logger";
18
- import type { PermissionCheckResult, PermissionState } from "#src/types";
19
- import { wildcardMatch } from "#src/wildcard-matcher";
20
-
21
- import {
22
- getDecisionEvents,
23
- makeEvents,
24
- makeSurfaceCheck,
25
- makeToolRegistry,
26
- } from "#test/helpers/handler-fixtures";
27
- import {
28
- makeRealResolver,
29
- makeRealSession,
30
- } from "#test/helpers/session-fixtures";
31
-
32
- // ── Shared constants ───────────────────────────────────────────────────────
33
-
34
- /** Working-directory used by the external-directory handler-pipeline tests. */
35
- export const EXT_DIR_CWD = "/test/project";
36
-
37
- /** An external path (outside {@link EXT_DIR_CWD}) used across the test suite. */
38
- export const EXTERNAL_PATH = "/outside/project/file.ts";
39
-
40
- /** All path-bearing tools subject to the external-directory gate. */
41
- export const ALL_PATH_BEARING_TOOLS = [
42
- "read",
43
- "write",
44
- "edit",
45
- "find",
46
- "grep",
47
- "ls",
48
- ];
49
-
50
- /** Path-bearing tools where the path is optional (no input → gate is skipped). */
51
- export const OPTIONAL_PATH_TOOLS = ["find", "grep", "ls"];
52
-
53
- /** Full tool set used as the default registry in external-directory tests. */
54
- export const ALL_TOOLS = [...ALL_PATH_BEARING_TOOLS, "bash"];
55
-
56
- // ── Setup builders ─────────────────────────────────────────────────────────
57
-
58
- /**
59
- * Builds a `checkPermission` mock for external-directory tests.
60
- *
61
- * Routes `external_directory` to `externalDirectoryState`, `path` to allow
62
- * with `source: "special"` (so the cross-cutting path gate is transparent),
63
- * and every other surface to `toolState` (default: allow).
64
- */
65
- export function makeExtDirCheck(
66
- externalDirectoryState: PermissionState,
67
- toolState: PermissionState = "allow",
68
- ) {
69
- return makeSurfaceCheck(
70
- {
71
- external_directory: { state: externalDirectoryState },
72
- path: { state: "allow", source: "special" },
73
- },
74
- { state: toolState },
75
- );
76
- }
77
-
78
- /** GatePrompter stub that approves with `state: "approved"`. */
79
- export function makeApprovingPrompter(): GatePrompter {
80
- return {
81
- canConfirm: vi.fn().mockReturnValue(true),
82
- prompt: vi
83
- .fn<GatePrompter["prompt"]>()
84
- .mockResolvedValue({ approved: true, state: "approved" }),
85
- };
86
- }
87
-
88
- /**
89
- * GatePrompter stub that denies.
90
- *
91
- * Pass `denialReason` to simulate a user who explains the refusal.
92
- */
93
- export function makeDenyingPrompter(denialReason?: string): GatePrompter {
94
- return {
95
- canConfirm: vi.fn().mockReturnValue(true),
96
- prompt: vi
97
- .fn<GatePrompter["prompt"]>()
98
- .mockResolvedValue(
99
- denialReason !== undefined
100
- ? { approved: false, state: "denied", denialReason }
101
- : { approved: false, state: "denied" },
102
- ),
103
- };
104
- }
105
-
106
- /** GatePrompter stub that reports no UI is available (`canConfirm: false`). */
107
- export function makeUnavailablePrompter(): GatePrompter {
108
- return {
109
- canConfirm: vi.fn().mockReturnValue(false),
110
- prompt: vi.fn<GatePrompter["prompt"]>(),
111
- };
112
- }
113
-
114
- // ── Query helpers ──────────────────────────────────────────────────────────
115
-
116
- /** Find the `external_directory` decision event from the events mock. */
117
- export function findExtDirDecision(events: ReturnType<typeof makeEvents>) {
118
- return getDecisionEvents(events).find(
119
- (d) => d.surface === "external_directory",
120
- );
121
- }
122
-
123
- /** Return the `permission_request.blocked` review-log entries from the logger mock. */
124
- export function blockReviewEntries(logger: SessionLogger) {
125
- return (logger.review as ReturnType<typeof vi.fn>).mock.calls.filter(
126
- ([eventName]: string[]) => eventName === "permission_request.blocked",
127
- );
128
- }
129
-
130
- // ── Session-dedup wiring ──────────────────────────────────────────────────
131
-
132
- /**
133
- * Installs the session-aware `check(intent)` mock on the permission manager.
134
- *
135
- * Returns `ask` for `external_directory` on first access; re-checks recorded
136
- * session rules on subsequent calls and returns `allow` (source: "session")
137
- * when a `wildcardMatch` covers the path.
138
- */
139
- export function makeExtDirDedupCheck(
140
- permissionManager: ScopedPermissionManager,
141
- ): void {
142
- vi.mocked(permissionManager.check).mockImplementation(
143
- (intent, rules): PermissionCheckResult => {
144
- const { surface } = intent;
145
- const pathValue =
146
- intent.kind === "path-values" ? (intent.values[0] ?? null) : null;
147
-
148
- if (surface === "external_directory") {
149
- if (pathValue && rules && rules.length > 0) {
150
- const match = rules.findLast(
151
- (r) =>
152
- r.surface === "external_directory" &&
153
- wildcardMatch(r.pattern, pathValue),
154
- );
155
- if (match) {
156
- return {
157
- state: "allow",
158
- toolName: surface,
159
- source: "session",
160
- origin: "session",
161
- matchedPattern: match.pattern,
162
- };
163
- }
164
- }
165
- return {
166
- state: "ask",
167
- toolName: surface,
168
- source: "special",
169
- origin: "global",
170
- };
171
- }
172
-
173
- return {
174
- state: "allow",
175
- toolName: surface,
176
- source: "tool",
177
- origin: "builtin",
178
- };
179
- },
180
- );
181
- }
182
-
183
- /** GatePrompter stub that approves for the session (`state: "approved_for_session"`). */
184
- function makeSessionApprovingPrompter(): GatePrompter {
185
- return {
186
- canConfirm: vi.fn().mockReturnValue(true),
187
- prompt: vi
188
- .fn<GatePrompter["prompt"]>()
189
- .mockResolvedValue({ approved: true, state: "approved_for_session" }),
190
- };
191
- }
192
-
193
- /**
194
- * Builds the fully-wired session-dedup handler with real collaborators.
195
- *
196
- * Unlike `makeHandler`, this wires `makeRealSession` + `makeRealResolver`
197
- * manually so the caller can access the raw `session` for shutdown tests.
198
- *
199
- * Returns `{ handler, prompter, session }`.
200
- */
201
- export function makeDedupWiring(prompter?: GatePrompter) {
202
- const { session, permissionManager, sessionRules, logger } =
203
- makeRealSession();
204
- const { resolver } = makeRealResolver(permissionManager, sessionRules);
205
- makeExtDirDedupCheck(permissionManager);
206
- const events = makeEvents();
207
- const reporter = new GateDecisionReporter(logger, events);
208
- const resolvedPrompter: GatePrompter =
209
- prompter ?? makeSessionApprovingPrompter();
210
- const runner = new GateRunner(
211
- resolver,
212
- sessionRules,
213
- resolvedPrompter,
214
- reporter,
215
- );
216
- const handler = new PermissionGateHandler(
217
- session,
218
- makeToolRegistry({
219
- getAll: vi
220
- .fn()
221
- .mockReturnValue([
222
- { name: "read" },
223
- { name: "write" },
224
- { name: "edit" },
225
- { name: "bash" },
226
- ]),
227
- }),
228
- new ToolCallGatePipeline(resolver, session),
229
- new SkillInputGatePipeline(resolver),
230
- runner,
231
- );
232
- return { handler, prompter: resolvedPrompter, session };
233
- }
234
-
235
- /**
236
- * Builds the session-dedup handler without exposing the raw session.
237
- *
238
- * Wraps `makeDedupWiring`; returns `{ handler, prompter }`.
239
- * Use `makeDedupWiring` when the test also needs `session.shutdown()`.
240
- */
241
- export function makeDeduplicatingHandler(prompter?: GatePrompter) {
242
- const { handler, prompter: resolvedPrompter } = makeDedupWiring(prompter);
243
- return { handler, prompter: resolvedPrompter };
244
- }
245
-
246
- // ── Event builders ─────────────────────────────────────────────────────────
247
-
248
- /**
249
- * Builds a tool-call event in the shape that external-directory-session-dedup
250
- * tests use — `toolName` field (not `name`); both are accepted by
251
- * `getToolNameFromValue`.
252
- */
253
- export function makeExtDirToolEvent(
254
- toolName: string,
255
- path: string,
256
- toolCallId = "tc-1",
257
- ) {
258
- return { type: "tool_call" as const, toolCallId, toolName, input: { path } };
259
- }
260
-
261
- /** Builds a bash tool-call event for external-directory session-dedup tests. */
262
- export function makeExtDirBashEvent(command: string, toolCallId = "tc-1") {
263
- return {
264
- type: "tool_call" as const,
265
- toolCallId,
266
- toolName: "bash",
267
- input: { command },
268
- };
269
- }
@@ -1,316 +0,0 @@
1
- /**
2
- * Shared gate-level test fixtures for gate descriptor and runner tests.
3
- */
4
- import { vi } from "vitest";
5
- import type { DecisionReporter } from "#src/decision-reporter";
6
- import type { DenialContext } from "#src/denial-messages";
7
- import type { GatePrompter } from "#src/gate-prompter";
8
- import type { GateDescriptor } from "#src/handlers/gates/descriptor";
9
- import { GateRunner } from "#src/handlers/gates/runner";
10
- import type { SkillInputGateInputs } from "#src/handlers/gates/skill-input-gate-pipeline";
11
- import type { ToolCallGateInputs } from "#src/handlers/gates/tool-call-gate-pipeline";
12
- import type { ToolCallContext } from "#src/handlers/gates/types";
13
- import { PathNormalizer } from "#src/path-normalizer";
14
- import type { ScopedPermissionResolver } from "#src/permission-resolver";
15
- import type { SessionApprovalRecorder } from "#src/session-approval-recorder";
16
- import type { SkillPromptEntry } from "#src/skill-prompt-sanitizer";
17
- import type { ToolPreviewFormatterOptions } from "#src/tool-preview-formatter";
18
- import type { PathRuleTokenMatcher, PermissionCheckResult } from "#src/types";
19
-
20
- import { makeCheckResult } from "#test/helpers/handler-fixtures";
21
-
22
- /**
23
- * Permission resolver mock with an optional default check result.
24
- *
25
- * Returns a plain object whose `resolve` is a `vi.fn` so callers retain full
26
- * mock access (`mockReturnValue`, `mockImplementation`, `mock.calls`).
27
- */
28
- export function makeResolver(defaultCheck?: PermissionCheckResult) {
29
- const resolve = vi.fn<ScopedPermissionResolver["resolve"]>();
30
- if (defaultCheck) {
31
- resolve.mockReturnValue(defaultCheck);
32
- }
33
- return { resolve };
34
- }
35
-
36
- /**
37
- * Gate descriptor factory with runner-test defaults.
38
- *
39
- * Uses deny as the default `denialContext` check result so tests that
40
- * verify block paths don't need to override the surface check.
41
- */
42
- export function makeDescriptor(
43
- overrides: Partial<GateDescriptor> = {},
44
- ): GateDescriptor {
45
- return {
46
- surface: "read",
47
- input: {},
48
- denialContext: {
49
- kind: "tool",
50
- check: makeCheckResult({ state: "deny", matchedPattern: "*" }),
51
- },
52
- promptDetails: {
53
- source: "tool_call",
54
- agentName: null,
55
- message: "Allow tool 'read'?",
56
- toolCallId: "tc-1",
57
- toolName: "read",
58
- },
59
- logContext: {
60
- source: "tool_call",
61
- toolCallId: "tc-1",
62
- toolName: "read",
63
- },
64
- decision: {
65
- surface: "read",
66
- value: "read",
67
- },
68
- ...overrides,
69
- };
70
- }
71
-
72
- /**
73
- * Reporter mock with independently inspectable vi.fn() stubs.
74
- */
75
- export function makeReporter(
76
- overrides: Partial<DecisionReporter> = {},
77
- ): DecisionReporter {
78
- return {
79
- writeReviewLog: vi.fn(),
80
- emitDecision: vi.fn(),
81
- ...overrides,
82
- };
83
- }
84
-
85
- /**
86
- * Gate runner factory for `GateRunner` unit tests.
87
- *
88
- * Builds one `GateRunner` from four role mocks and returns `{ runner, deps }`
89
- * so tests can both invoke `runner.run(...)` and assert on the individual
90
- * mock call records (`deps.reporter.*`, `deps.resolve`, etc.).
91
- */
92
- export function makeGateRunner(
93
- overrides: {
94
- resolveResult?: PermissionCheckResult;
95
- resolve?: ScopedPermissionResolver["resolve"];
96
- recordSessionApproval?: SessionApprovalRecorder["recordSessionApproval"];
97
- canConfirm?: GatePrompter["canConfirm"];
98
- prompt?: GatePrompter["prompt"];
99
- reporter?: Partial<DecisionReporter>;
100
- } = {},
101
- ) {
102
- const reporter = makeReporter(overrides.reporter);
103
- const resolve =
104
- overrides.resolve ??
105
- vi
106
- .fn<ScopedPermissionResolver["resolve"]>()
107
- .mockReturnValue(
108
- overrides.resolveResult ?? makeCheckResult({ matchedPattern: "*" }),
109
- );
110
- const recordSessionApproval =
111
- overrides.recordSessionApproval ??
112
- (vi.fn() as SessionApprovalRecorder["recordSessionApproval"]);
113
- const canConfirm =
114
- overrides.canConfirm ??
115
- (vi.fn().mockReturnValue(true) as GatePrompter["canConfirm"]);
116
- const prompt =
117
- overrides.prompt ??
118
- vi
119
- .fn<GatePrompter["prompt"]>()
120
- .mockResolvedValue({ approved: true, state: "approved" });
121
- const runner = new GateRunner(
122
- { resolve },
123
- { recordSessionApproval },
124
- { canConfirm, prompt },
125
- reporter,
126
- );
127
- return {
128
- runner,
129
- deps: {
130
- resolve,
131
- recordSessionApproval,
132
- canConfirm,
133
- prompt,
134
- reporter,
135
- },
136
- };
137
- }
138
-
139
- /**
140
- * Gate descriptor variant with write-surface defaults and a caller-supplied
141
- * denialContext.
142
- *
143
- * Use instead of `makeDescriptor` when the test exercises denial-message
144
- * formatting — the write surface and its matching promptDetails/logContext
145
- * keep the message helpers' field access consistent.
146
- */
147
- export function makeDenialDescriptor(
148
- denialContext: DenialContext,
149
- overrides: Partial<GateDescriptor> = {},
150
- ): GateDescriptor {
151
- return {
152
- surface: "write",
153
- input: {},
154
- denialContext,
155
- promptDetails: {
156
- source: "tool_call",
157
- agentName: null,
158
- message: "Allow tool 'write'?",
159
- toolCallId: "tc-1",
160
- toolName: "write",
161
- },
162
- logContext: {
163
- source: "tool_call",
164
- toolCallId: "tc-1",
165
- toolName: "write",
166
- },
167
- decision: {
168
- surface: "write",
169
- value: "write",
170
- },
171
- ...overrides,
172
- };
173
- }
174
-
175
- /**
176
- * Tool-call context factory with bash defaults.
177
- *
178
- * path.test.ts uses different defaults (toolName "read", path input) and
179
- * keeps a local wrapper; bash-path.test.ts uses this factory directly.
180
- */
181
- export function makeTcc(
182
- overrides: Partial<ToolCallContext> = {},
183
- ): ToolCallContext {
184
- return {
185
- toolName: "bash",
186
- agentName: null,
187
- input: { command: "cat .env" },
188
- toolCallId: "tc-1",
189
- cwd: "/test/project",
190
- ...overrides,
191
- };
192
- }
193
-
194
- /**
195
- * Resolver whose `resolve` dispatches on `input.path`, falling back to a
196
- * default result for any path not in the map.
197
- *
198
- * Use when a test needs different results for different path tokens without
199
- * writing a full `mockImplementation` block.
200
- *
201
- * Return type is intentionally unannotated so callers retain full `vi.fn()`
202
- * mock access (`mock.calls`, `toHaveBeenCalledWith`, etc.).
203
- */
204
- export function makePathDispatchResolver(
205
- byPath: Record<string, PermissionCheckResult>,
206
- defaultResult: PermissionCheckResult,
207
- ) {
208
- const resolve = vi.fn<ScopedPermissionResolver["resolve"]>();
209
- resolve.mockImplementation((intent) => {
210
- if (intent.kind === "tool") {
211
- const path = (intent.input as Record<string, unknown>).path;
212
- if (typeof path === "string" && path in byPath) {
213
- return byPath[path];
214
- }
215
- return defaultResult;
216
- }
217
- const values = intent.path.matchValues();
218
- for (const value of values) {
219
- if (value in byPath) return byPath[value];
220
- }
221
- return defaultResult;
222
- });
223
- return { resolve };
224
- }
225
-
226
- /**
227
- * Path-surface check result factory.
228
- *
229
- * Shared between bash-path.test.ts and path.test.ts; both use
230
- * toolName "path", source "special", origin "global" as defaults.
231
- */
232
- export function makeGateCheckResult(
233
- overrides: Partial<PermissionCheckResult> = {},
234
- ): PermissionCheckResult {
235
- return {
236
- toolName: "path",
237
- state: "allow",
238
- source: "special",
239
- origin: "global",
240
- ...overrides,
241
- };
242
- }
243
-
244
- /**
245
- * Mock of `ToolCallGateInputs` for `ToolCallGatePipeline` unit tests.
246
- *
247
- * Each method is a `vi.fn()` stub so callers retain full mock access
248
- * (`mock.calls`, `mockReturnValue`, etc.) on the returned object.
249
- * Pass `overrides` to replace individual stubs without rebuilding the whole
250
- * mock from scratch.
251
- */
252
- export function makeGateInputs(
253
- overrides: {
254
- getActiveSkillEntries?: () => SkillPromptEntry[];
255
- getInfrastructureReadDirs?: () => string[];
256
- getToolPreviewLimits?: () => ToolPreviewFormatterOptions;
257
- getPathNormalizer?: () => PathNormalizer;
258
- getPromotablePathTokenMatcher?: (
259
- agentName?: string,
260
- ) => PathRuleTokenMatcher;
261
- } = {},
262
- ): ToolCallGateInputs {
263
- return {
264
- getActiveSkillEntries:
265
- overrides.getActiveSkillEntries ??
266
- vi.fn<() => SkillPromptEntry[]>(() => []),
267
- getInfrastructureReadDirs:
268
- overrides.getInfrastructureReadDirs ?? vi.fn<() => string[]>(() => []),
269
- getToolPreviewLimits:
270
- overrides.getToolPreviewLimits ??
271
- vi.fn<() => ToolPreviewFormatterOptions>(() => ({
272
- toolInputPreviewMaxLength: 500,
273
- toolTextSummaryMaxLength: 100,
274
- toolInputLogPreviewMaxLength: 200,
275
- })),
276
- getPathNormalizer:
277
- overrides.getPathNormalizer ??
278
- vi.fn<() => PathNormalizer>(
279
- () => new PathNormalizer(process.platform, "/test/cwd"),
280
- ),
281
- getPromotablePathTokenMatcher:
282
- overrides.getPromotablePathTokenMatcher ??
283
- vi.fn<(agentName?: string) => PathRuleTokenMatcher>(() => () => false),
284
- };
285
- }
286
-
287
- /**
288
- * Mock of `SkillInputGateInputs` for `SkillInputGatePipeline` unit tests.
289
- *
290
- * Returns a plain object with a `checkPermission` `vi.fn()` stub so callers
291
- * retain full mock access (`mockReturnValue`, `mock.calls`, etc.).
292
- */
293
- export function makeSkillInputInputs(
294
- overrides: { checkPermission?: SkillInputGateInputs["checkPermission"] } = {},
295
- ): SkillInputGateInputs {
296
- return {
297
- checkPermission:
298
- overrides.checkPermission ??
299
- vi
300
- .fn<SkillInputGateInputs["checkPermission"]>()
301
- .mockReturnValue(makeCheckResult()),
302
- };
303
- }
304
-
305
- /**
306
- * Mock `GateNotifier` for `SkillInputGatePipeline` unit tests.
307
- *
308
- * Return type is intentionally unannotated so callers retain full `vi.fn()`
309
- * mock access (`mock.calls`, `toHaveBeenCalledWith`, etc.) — annotating with
310
- * `GateNotifier` would erase `Mock<...>` methods from the inferred type.
311
- */
312
- export function makeNotifier() {
313
- return {
314
- warn: vi.fn<(message: string) => void>(),
315
- };
316
- }