@gotgenes/pi-permission-system 18.2.0 → 19.0.1

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.
@@ -0,0 +1,204 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Single source of truth for the permission-system config file shape.
5
+ *
6
+ * These composable zod schemas drive two consumers:
7
+ * 1. Runtime validation in the config-file loader (`config-loader.ts`).
8
+ * 2. The published JSON Schema (`schemas/permissions.schema.json`), derived by
9
+ * `buildPermissionsJsonSchema()` and regenerated via `pnpm run gen:schema`.
10
+ *
11
+ * Edit the schemas here — never the generated JSON by hand. A parity test
12
+ * (`config-schema.test.ts`) fails if the committed JSON drifts from this source.
13
+ */
14
+
15
+ /** Canonical hosted location of the generated JSON Schema (monorepo raw path). */
16
+ export const PERMISSIONS_SCHEMA_URL =
17
+ "https://raw.githubusercontent.com/gotgenes/pi-packages/main/packages/pi-permission-system/schemas/permissions.schema.json";
18
+
19
+ const permissionStateSchema = z
20
+ .union([
21
+ z.literal("allow").meta({
22
+ description: "Permit the action silently with no user interaction.",
23
+ }),
24
+ z.literal("deny").meta({
25
+ description:
26
+ "Block the action with an error message. The agent is told not to retry.",
27
+ }),
28
+ z.literal("ask").meta({
29
+ description:
30
+ "Prompt the user for confirmation via the interactive UI before proceeding.",
31
+ }),
32
+ ])
33
+ .meta({
34
+ id: "permissionState",
35
+ description:
36
+ "A permission decision: allow (permit silently), deny (block with error), or ask (prompt the user for confirmation).",
37
+ });
38
+
39
+ const denyWithReasonSchema = z
40
+ .strictObject({
41
+ action: z.literal("deny").meta({
42
+ description: 'The permission decision — must be "deny".',
43
+ }),
44
+ reason: z.string().max(500).optional().meta({
45
+ description:
46
+ "Optional reason shown to the agent when this action is denied.",
47
+ }),
48
+ })
49
+ .meta({
50
+ id: "denyWithReason",
51
+ description:
52
+ "Deny with an optional custom reason shown to the agent when the action is blocked.",
53
+ });
54
+
55
+ const patternValueSchema = z.union([
56
+ permissionStateSchema,
57
+ denyWithReasonSchema,
58
+ ]);
59
+
60
+ const permissionMapSchema = z
61
+ .record(
62
+ z.string().min(1).meta({
63
+ description:
64
+ "A non-empty pattern string. Use * for wildcard matching. Prefix with ~/ or $HOME/ for home-relative paths.",
65
+ }),
66
+ patternValueSchema,
67
+ )
68
+ .meta({
69
+ id: "permissionMap",
70
+ description:
71
+ "A map of wildcard patterns to permission states. Last matching pattern wins.",
72
+ markdownDescription:
73
+ "A map of wildcard patterns to permission states.\n\nUse `*` for wildcard matching. When multiple patterns match, the **last matching rule wins** — put broad catch-alls first and specific overrides after them.\n\nPattern keys support home directory expansion:\n- `~/path` or `$HOME/path` — expanded to the OS home directory at match time.\n- `~` or `$HOME` alone — expands to the home directory itself.\n\nThe stored pattern is always shown in logs and approval dialogs as written (e.g. `~/dev/*`).",
74
+ });
75
+
76
+ const permissionSchema = z
77
+ .record(
78
+ z.string().min(1).meta({
79
+ description: "A surface name or the universal fallback key '*'.",
80
+ }),
81
+ z.union([permissionStateSchema, permissionMapSchema]),
82
+ )
83
+ .meta({
84
+ description:
85
+ "Flat permission policy. Each key is a surface name; values are a PermissionState string (catch-all) or a pattern→action map.",
86
+ markdownDescription:
87
+ 'Flat permission policy.\n\nEach top-level key is a surface name:\n- `"*"` — universal fallback (replaces `defaultPolicy.tools` from the legacy format)\n- Tool names (`read`, `write`, `bash`, `mcp`, `skill`, `external_directory`, `path`, etc.)\n\nA **string** value is shorthand for `{ "*": action }` (surface-level catch-all).\nAn **object** value maps wildcard patterns to actions — last matching pattern wins.\n\nFor built-in file tools (`read`, `write`, `edit`, `find`, `grep`, `ls`), patterns are matched against the file path from `input.path`. For example, `"read": { "*": "allow", "*.env": "deny" }` allows reads but denies `.env` files.\n\nWhen Pi\'s current working directory is known, relative path inputs also match their cwd-normalized absolute form, so `src/App.jsx` can match both `src/*` and `/workspace/project/*`. Bash path tokens use the effective directory after literal `cd` commands for this matching; non-literal `cd "$DIR"` style commands remain conservative.\n\nThe `path` surface is a cross-cutting gate that applies to **all** file access: Pi tools, bash commands, MCP calls (via `input.arguments.path`), and extension tools (via `input.path` or a registered access extractor). A `path` deny cannot be overridden by a per-tool allow. Use it to protect sensitive files (`.env`, `~/.ssh/*`) from all path-aware tools at once.\n\nThe `external_directory` surface gates access **outside** the working directory. Give it a pattern map to allow specific outside-CWD directories without opening all external access — e.g. `"external_directory": { "*": "ask", "~/.cargo/registry/*": "allow" }` to silence repeated prompts on a local cache. The trailing `*` is greedy and crosses subdirectory boundaries; a bare `~/.cargo/registry` matches only the directory entry itself. Because layers compose with most-restrictive-wins, a `path` allow cannot loosen an `external_directory: ask` boundary — allow outside-CWD directories here, not on `path`.\n\n**Merge order (lowest → highest precedence):** global → project → per-agent frontmatter.',
88
+ examples: [
89
+ {
90
+ "*": "ask",
91
+ path: {
92
+ "*": "allow",
93
+ "*.env": "deny",
94
+ "*.env.*": "deny",
95
+ "*.env.example": "allow",
96
+ },
97
+ read: "allow",
98
+ write: "deny",
99
+ edit: "deny",
100
+ bash: {
101
+ "*": "ask",
102
+ "git *": "ask",
103
+ "git status": "allow",
104
+ "git diff": "allow",
105
+ },
106
+ mcp: { "*": "ask", mcp_status: "allow", "exa:*": "allow" },
107
+ skill: { "*": "ask", librarian: "allow" },
108
+ external_directory: { "*": "ask", "~/.cargo/registry/*": "allow" },
109
+ },
110
+ ],
111
+ });
112
+
113
+ /**
114
+ * The on-disk config file shape.
115
+ *
116
+ * Every field is optional so partial global/project configs merge before the
117
+ * runtime defaults are applied downstream (`normalizePermissionSystemConfig`).
118
+ * No `.default()` lives here — injecting defaults at parse time would break the
119
+ * global-vs-project override semantics. `strictObject` makes unknown top-level
120
+ * keys an error, so editors flag typos and the runtime loader rejects them.
121
+ */
122
+ export const unifiedConfigSchema = z
123
+ .strictObject({
124
+ $schema: z.string().optional().meta({
125
+ description: "JSON Schema URI for editor autocomplete and validation.",
126
+ }),
127
+ debugLog: z.boolean().optional().meta({
128
+ description:
129
+ "Write verbose permission-system diagnostics to the extension logs directory.",
130
+ markdownDescription:
131
+ "Write verbose permission-system diagnostics to `logs/pi-permission-system-debug.jsonl` under the extension config directory.",
132
+ default: false,
133
+ }),
134
+ permissionReviewLog: z.boolean().optional().meta({
135
+ description:
136
+ "Write permission request and decision audit events to the extension logs directory.",
137
+ markdownDescription:
138
+ "Write permission request and decision audit events to `logs/pi-permission-system-permission-review.jsonl` under the extension config directory.",
139
+ default: true,
140
+ }),
141
+ yoloMode: z.boolean().optional().meta({
142
+ description:
143
+ "Auto-approve ask-state permission checks, including subagent approval forwarding.",
144
+ markdownDescription:
145
+ "Auto-approve `ask`-state permission checks, including subagent approval forwarding.\n\n⚠️ **Use with caution** — this disables all interactive confirmation prompts.",
146
+ default: false,
147
+ }),
148
+ toolInputPreviewMaxLength: z.number().int().min(1).optional().meta({
149
+ description:
150
+ "Maximum character length of the inline-JSON tool-input preview shown in permission prompts. Omit to use the default (200). Set to a large value to disable truncation.",
151
+ markdownDescription:
152
+ "Maximum character length of the inline-JSON tool-input preview shown in permission prompts.\n\nOmit to use the default (200). Set to a large value (e.g. `10000`) to effectively disable truncation and see the full input.",
153
+ }),
154
+ toolTextSummaryMaxLength: z.number().int().min(1).optional().meta({
155
+ description:
156
+ "Maximum character length of inline pattern/path summaries (e.g. grep patterns, find globs, ls paths) in permission prompts. Omit to use the default (80).",
157
+ markdownDescription:
158
+ "Maximum character length of inline pattern/path summaries (e.g. grep patterns, find globs, ls paths) shown in permission prompts.\n\nOmit to use the default (80). Increase this when working with long regexes or deep paths that are being cut off.",
159
+ }),
160
+ piInfrastructureReadPaths: z.array(z.string().min(1)).optional().meta({
161
+ description:
162
+ "Additional directories to auto-allow for reads as Pi infrastructure, bypassing the external_directory gate. Supports ~ expansion and wildcard patterns (* and ?).",
163
+ markdownDescription:
164
+ "Additional directories to auto-allow for reads as Pi infrastructure, bypassing the `external_directory` gate.\n\nThe extension auto-discovers the global node_modules root (walks up from the extension's install path; falls back to `npm root -g` from a dev checkout), Pi's own install directory (via the coding-agent `getPackageDir()` API), `agentDir`, `agentDir/git`, and project-local `.pi/npm/` and `.pi/git/`. Add entries here for edge cases where auto-discovery is insufficient (e.g. custom `npmCommand` pointing to pnpm).\n\nSupports `~`/`$HOME` expansion. Entries may be plain directory prefixes or wildcard patterns using `*` (matches any characters, including `/`) and `?` (matches exactly one character). `**` and `*` are equivalent — both cross directory boundaries.\n\nOn Windows, matching is case-insensitive and tolerant of either path separator.",
165
+ default: [],
166
+ }),
167
+ permission: permissionSchema.optional(),
168
+ })
169
+ .meta({
170
+ title: "PI Permission System Configuration",
171
+ description:
172
+ "Unified config file combining runtime knobs and flat permission policy for pi-permission-system.",
173
+ markdownDescription:
174
+ "Unified config file combining runtime knobs and flat permission policy for [pi-permission-system](https://github.com/gotgenes/pi-packages/tree/main/packages/pi-permission-system).\n\nPlace at `~/.pi/agent/extensions/pi-permission-system/config.json` (global) or `<project>/.pi/extensions/pi-permission-system/config.json` (project).",
175
+ });
176
+
177
+ /** A permission decision. */
178
+ export type PermissionState = z.infer<typeof permissionStateSchema>;
179
+
180
+ /** A deny action with an optional custom reason. */
181
+ export type DenyWithReason = z.infer<typeof denyWithReasonSchema>;
182
+
183
+ /** A pattern value: a PermissionState string OR a DenyWithReason object. */
184
+ export type PatternValue = z.infer<typeof patternValueSchema>;
185
+
186
+ /** The on-disk permission shape inside the `"permission"` key. */
187
+ export type FlatPermissionConfig = z.infer<typeof permissionSchema>;
188
+
189
+ /** The raw config file shape after validation (all fields optional). */
190
+ export type UnifiedPermissionConfig = z.infer<typeof unifiedConfigSchema>;
191
+
192
+ /**
193
+ * Derive the published JSON Schema (Draft 2020-12) from the zod source.
194
+ *
195
+ * The three id-tagged sub-schemas (`permissionState`, `permissionMap`,
196
+ * `denyWithReason`) become `$defs` referenced by `$ref`; everything else
197
+ * inlines. The root `$id` is set to the canonical monorepo URL.
198
+ */
199
+ export function buildPermissionsJsonSchema(): Record<string, unknown> {
200
+ const { $schema, ...rest } = z.toJSONSchema(unifiedConfigSchema, {
201
+ target: "draft-2020-12",
202
+ });
203
+ return { $schema, $id: PERMISSIONS_SCHEMA_URL, ...rest };
204
+ }
@@ -1,9 +1,7 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
-
3
- import type { InboxProcessor } from "./forwarded-permissions/permission-forwarder";
2
+ import type { InboxProcessor } from "./authority/forwarded-request-server";
3
+ import type { SubagentDetector } from "./authority/subagent-detection";
4
4
  import { PERMISSION_FORWARDING_POLL_INTERVAL_MS } from "./permission-forwarding";
5
- import { isSubagentExecutionContext } from "./subagent-context";
6
- import type { SubagentSessionRegistry } from "./subagent-registry";
7
5
 
8
6
  /**
9
7
  * Narrow interface for the forwarding lifecycle used by `PermissionSession`.
@@ -28,10 +26,8 @@ export class ForwardingManager {
28
26
  private processing = false;
29
27
 
30
28
  constructor(
31
- private readonly subagentSessionsDir: string,
29
+ private readonly detection: SubagentDetector,
32
30
  private readonly forwarder: InboxProcessor,
33
- private readonly platform: NodeJS.Platform,
34
- private readonly registry?: SubagentSessionRegistry,
35
31
  ) {}
36
32
 
37
33
  /**
@@ -41,15 +37,7 @@ export class ForwardingManager {
41
37
  * Stops any existing poll when the context does not qualify for forwarding.
42
38
  */
43
39
  start(ctx: ExtensionContext): void {
44
- if (
45
- !ctx.hasUI ||
46
- isSubagentExecutionContext(
47
- ctx,
48
- this.subagentSessionsDir,
49
- this.platform,
50
- this.registry,
51
- )
52
- ) {
40
+ if (!ctx.hasUI || this.detection.isSubagent(ctx)) {
53
41
  this.stop();
54
42
  return;
55
43
  }
package/src/index.ts CHANGED
@@ -1,5 +1,14 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { getAgentDir, getPackageDir } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ ApprovalEscalator,
5
+ type ApprovalEscalatorDeps,
6
+ } from "./authority/approval-escalator";
7
+ import {
8
+ ForwardedRequestServer,
9
+ type ForwardedRequestServerDeps,
10
+ } from "./authority/forwarded-request-server";
11
+ import { SubagentDetection } from "./authority/subagent-detection";
3
12
  import { registerBuiltinToolInputFormatters } from "./builtin-tool-input-formatters";
4
13
  import { registerPermissionSystemCommand } from "./config-modal";
5
14
  import { getGlobalConfigPath } from "./config-paths";
@@ -8,10 +17,6 @@ import { DecisionAudit } from "./decision-audit";
8
17
  import { GateDecisionReporter } from "./decision-reporter";
9
18
  import { isYoloModeEnabled } from "./extension-config";
10
19
  import { computeExtensionPaths } from "./extension-paths";
11
- import {
12
- PermissionForwarder,
13
- type PermissionForwarderDeps,
14
- } from "./forwarded-permissions/permission-forwarder";
15
20
  import { ForwardingManager } from "./forwarding-manager";
16
21
  import {
17
22
  AgentPrepHandler,
@@ -49,6 +54,13 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
49
54
  const hostPlatform = process.platform;
50
55
  const sessionRules = new SessionRules();
51
56
  const subagentRegistry = getSubagentSessionRegistry();
57
+ // Single owner of subagent detection, shared across every consumer instead of
58
+ // threading the (subagentSessionsDir, platform, registry) triple into each.
59
+ const subagentDetection = new SubagentDetection({
60
+ subagentSessionsDir: paths.subagentSessionsDir,
61
+ platform: hostPlatform,
62
+ registry: subagentRegistry,
63
+ });
52
64
  const formatterRegistry = new ToolInputFormatterRegistry();
53
65
  registerBuiltinToolInputFormatters(formatterRegistry);
54
66
  const accessExtractorRegistry = new ToolAccessExtractorRegistry();
@@ -83,39 +95,38 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
83
95
  logger,
84
96
  });
85
97
 
86
- const forwardingDeps: PermissionForwarderDeps = {
98
+ const escalatorDeps: ApprovalEscalatorDeps = {
87
99
  forwardingDir: paths.forwardingDir,
88
- subagentSessionsDir: paths.subagentSessionsDir,
89
- platform: hostPlatform,
100
+ detection: subagentDetection,
90
101
  registry: subagentRegistry,
91
- events: pi.events,
92
102
  logger,
93
103
  requestPermissionDecisionFromUi,
104
+ };
105
+ const escalator = new ApprovalEscalator(escalatorDeps);
106
+
107
+ const requestServerDeps: ForwardedRequestServerDeps = {
108
+ forwardingDir: paths.forwardingDir,
109
+ logger,
110
+ events: pi.events,
111
+ requestPermissionDecisionFromUi,
94
112
  config: configStore,
95
113
  };
96
- const forwarder = new PermissionForwarder(forwardingDeps);
114
+ const requestServer = new ForwardedRequestServer(requestServerDeps);
97
115
 
98
116
  const prompter = new PermissionPrompter({
99
117
  logger,
100
118
  events: pi.events,
101
- forwarder,
119
+ forwarder: escalator,
102
120
  });
103
121
 
104
122
  const gateway = new PromptingGateway({
105
- subagentSessionsDir: paths.subagentSessionsDir,
106
- platform: hostPlatform,
107
- registry: subagentRegistry,
123
+ detection: subagentDetection,
108
124
  prompter,
109
125
  });
110
126
 
111
127
  session = new PermissionSession(
112
128
  paths,
113
- new ForwardingManager(
114
- paths.subagentSessionsDir,
115
- forwarder,
116
- hostPlatform,
117
- subagentRegistry,
118
- ),
129
+ new ForwardingManager(subagentDetection, requestServer),
119
130
  permissionManager,
120
131
  sessionRules,
121
132
  configStore,
@@ -171,7 +182,7 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
171
182
  // requires the session id from ctx, unavailable at factory-init time.
172
183
  const serviceLifecycle = new PermissionServiceLifecycle(
173
184
  permissionsService,
174
- subagentRegistry,
185
+ subagentDetection,
175
186
  pi.events,
176
187
  [rpcHandles.unsubCheck, rpcHandles.unsubPrompt, unsubSubagentLifecycle],
177
188
  );
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { ApprovalRequester } from "./forwarded-permissions/permission-forwarder";
2
+ import type { ApprovalRequester } from "./authority/approval-escalator";
3
3
  import type { PermissionPromptDecision } from "./permission-dialog";
4
4
  import {
5
5
  emitUiPromptEvent,
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
4
  import {
5
5
  loadUnifiedConfig,
6
- normalizeUnifiedConfig,
6
+ normalizeFlatPermissionValue,
7
7
  stripJsonComments,
8
8
  } from "./config-loader";
9
9
  import { getGlobalConfigPath } from "./config-paths";
@@ -263,10 +263,14 @@ export class FilePolicyLoader implements PolicyLoader {
263
263
  if (!frontmatter) {
264
264
  value = {};
265
265
  } else {
266
+ // Agent frontmatter carries non-config keys (name, description, model,
267
+ // …) alongside `permission`, so it is not validated by the strict
268
+ // config-file schema; only the `permission` block is extracted, and its
269
+ // malformed entries are dropped tolerantly as before.
266
270
  const parsed = parseSimpleYamlMap(frontmatter);
267
- const { config, issues } = normalizeUnifiedConfig(parsed);
268
- this.accumulateConfigIssues(issues);
269
- value = { permission: config.permission };
271
+ value = {
272
+ permission: normalizeFlatPermissionValue(parsed.permission),
273
+ };
270
274
  }
271
275
  } catch {
272
276
  value = {};
@@ -1,28 +1,22 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
-
2
+ import type { SubagentDetector } from "./authority/subagent-detection";
3
3
  import type { GatePrompter } from "./gate-prompter";
4
4
  import type { PermissionPromptDecision } from "./permission-dialog";
5
5
  import type {
6
6
  PermissionPrompterApi,
7
7
  PromptPermissionDetails,
8
8
  } from "./permission-prompter";
9
- import { isSubagentExecutionContext } from "./subagent-context";
10
- import type { SubagentSessionRegistry } from "./subagent-registry";
11
9
 
12
10
  /**
13
11
  * Dependencies required by PromptingGateway.
14
12
  *
15
13
  * All fields are actively consumed:
16
- * - `subagentSessionsDir` + `registry` drive `canConfirm()`.
14
+ * - `detection` drives `canConfirm()`.
17
15
  * - `prompter` is called by `prompt()`.
18
16
  */
19
17
  export interface PromptingGatewayDeps {
20
- /** Static path used to detect a forwarding subagent context. */
21
- subagentSessionsDir: string;
22
- /** Host platform, injected from the composition root, for subagent-context path detection. */
23
- platform: NodeJS.Platform;
24
- /** Process-global registry used to detect a registered child session. */
25
- registry?: SubagentSessionRegistry;
18
+ /** Single owner of subagent detection; drives `canConfirm()`. */
19
+ detection: SubagentDetector;
26
20
  /** Resolves the permission decision: direct UI dialog or forwarded to parent. */
27
21
  prompter: PermissionPrompterApi;
28
22
  }
@@ -75,15 +69,7 @@ export class PromptingGateway
75
69
  */
76
70
  canConfirm(): boolean {
77
71
  if (this.context === null) return false;
78
- return (
79
- this.context.hasUI ||
80
- isSubagentExecutionContext(
81
- this.context,
82
- this.deps.subagentSessionsDir,
83
- this.deps.platform,
84
- this.deps.registry,
85
- )
86
- );
72
+ return this.context.hasUI || this.deps.detection.isSubagent(this.context);
87
73
  }
88
74
 
89
75
  /**
@@ -1,13 +1,11 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
-
2
+ import type { RegisteredChildDetector } from "./authority/subagent-detection";
3
3
  import { emitReadyEvent, type PermissionEventBus } from "./permission-events";
4
4
  import {
5
5
  type PermissionsService,
6
6
  publishPermissionsService,
7
7
  unpublishPermissionsService,
8
8
  } from "./service";
9
- import { isRegisteredSubagentChild } from "./subagent-context";
10
- import type { SubagentSessionRegistry } from "./subagent-registry";
11
9
 
12
10
  /** The session-scoped service lifecycle that the lifecycle handler drives. */
13
11
  export interface ServiceLifecycle {
@@ -28,13 +26,13 @@ export interface ServiceLifecycle {
28
26
  export class PermissionServiceLifecycle implements ServiceLifecycle {
29
27
  constructor(
30
28
  private readonly service: PermissionsService,
31
- private readonly registry: SubagentSessionRegistry,
29
+ private readonly detection: RegisteredChildDetector,
32
30
  private readonly events: PermissionEventBus,
33
31
  private readonly subscriptions: readonly (() => void)[],
34
32
  ) {}
35
33
 
36
34
  activate(ctx: ExtensionContext): void {
37
- if (!isRegisteredSubagentChild(ctx, this.registry)) {
35
+ if (!this.detection.isRegisteredChild(ctx)) {
38
36
  publishPermissionsService(this.service);
39
37
  }
40
38
  emitReadyEvent(this.events);
@@ -19,7 +19,7 @@ export interface ReviewLogger {
19
19
 
20
20
  /**
21
21
  * Logging seam for consumers that write both debug and review entries.
22
- * Injected into `ConfigStore` and `PermissionForwarder`.
22
+ * Injected into `ConfigStore`, `ApprovalEscalator`, and `ForwardedRequestServer`.
23
23
  */
24
24
  export interface DebugReviewLogger extends ReviewLogger {
25
25
  debug(event: string, details?: Record<string, unknown>): void;
package/src/types.ts CHANGED
@@ -1,20 +1,21 @@
1
- export type PermissionState = "allow" | "deny" | "ask";
2
-
1
+ import type {
2
+ DenyWithReason,
3
+ FlatPermissionConfig,
4
+ PatternValue,
5
+ PermissionState,
6
+ } from "./config-schema";
3
7
  import type { RuleOrigin } from "./rule";
4
8
 
5
- export type { RuleOrigin };
6
-
7
- /**
8
- * A deny action with an optional reason annotation, used when a pattern maps
9
- * to an object instead of a plain PermissionState string.
10
- */
11
- export interface DenyWithReason {
12
- action: "deny";
13
- reason?: string;
14
- }
15
-
16
- /** A pattern value: a PermissionState string OR a DenyWithReason object. */
17
- export type PatternValue = PermissionState | DenyWithReason;
9
+ // The config-file shape types are derived from the zod schema
10
+ // (config-schema.ts) — the single source of truth — and re-exported here so
11
+ // existing importers keep their import path.
12
+ export type {
13
+ DenyWithReason,
14
+ FlatPermissionConfig,
15
+ PatternValue,
16
+ PermissionState,
17
+ RuleOrigin,
18
+ };
18
19
 
19
20
  /**
20
21
  * Predicate deciding whether a bare bash token should be promoted into the
@@ -27,17 +28,6 @@ export type PatternValue = PermissionState | DenyWithReason;
27
28
  */
28
29
  export type PathRuleTokenMatcher = (token: string) => boolean;
29
30
 
30
- /**
31
- * The on-disk permission shape inside the `"permission"` key.
32
- * A surface value is a PermissionState string (shorthand for `{ "*": action }`)
33
- * or a pattern→value map. Pattern values may be a PermissionState string or a
34
- * DenyWithReason object. A top-level value is never a bare DenyWithReason.
35
- */
36
- export type FlatPermissionConfig = Record<
37
- string,
38
- PermissionState | Record<string, PatternValue>
39
- >;
40
-
41
31
  /**
42
32
  * Per-scope permission config shape after loading and validation.
43
33
  * Holds only the flat permission map — all policy is expressed there.
@@ -17,23 +17,6 @@ export function getNonEmptyString(value: unknown): string | null {
17
17
  return trimmed.length > 0 ? trimmed : null;
18
18
  }
19
19
 
20
- /** Returns `raw` if it is an array of strings; otherwise `undefined`. */
21
- export function normalizeOptionalStringArray(
22
- raw: unknown,
23
- ): string[] | undefined {
24
- return Array.isArray(raw) &&
25
- raw.every((p): p is string => typeof p === "string")
26
- ? raw
27
- : undefined;
28
- }
29
-
30
- /** Returns `raw` if it is a positive integer; otherwise `undefined`. */
31
- export function normalizeOptionalPositiveInt(raw: unknown): number | undefined {
32
- return typeof raw === "number" && Number.isInteger(raw) && raw > 0
33
- ? raw
34
- : undefined;
35
- }
36
-
37
20
  export function isPermissionState(value: unknown): value is PermissionState {
38
21
  return value === "allow" || value === "deny" || value === "ask";
39
22
  }