@gotgenes/pi-permission-system 18.1.2 → 19.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,33 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [19.0.0](https://github.com/gotgenes/pi-packages/compare/pi-permission-system-v18.2.0...pi-permission-system-v19.0.0) (2026-07-06)
9
+
10
+
11
+ ### ⚠ BREAKING CHANGES
12
+
13
+ * **pi-permission-system:** The permission-system config loader was tolerant — it silently discarded malformed fields (a non-boolean `debugLog`, an invalid permission action, an unknown key) and loaded the rest. It now rejects the entire config file for that scope when any field is invalid, and reports each problem with its JSON path. On upgrade, a config that previously loaded with silently-dropped fields will be rejected until the reported problems are fixed; the affected scope falls back to the safe `ask` default until then. Fix each field named in the emitted issues (visible in the permission review log / debug log).
14
+
15
+ ### Features
16
+
17
+ * **pi-permission-system:** add zod config schema as validation source ([6b71491](https://github.com/gotgenes/pi-packages/commit/6b71491b058d64e328139bd8ccfa104e9bbe2f5a))
18
+ * **pi-permission-system:** generate JSON Schema from zod and fix hosted $id URL ([7b6556d](https://github.com/gotgenes/pi-packages/commit/7b6556d7676b8e6574cd01eeec2032a499b19649))
19
+ * **pi-permission-system:** validate config with zod and reject invalid fields ([7e32cae](https://github.com/gotgenes/pi-packages/commit/7e32caea8f750637069ebaf243bb1db90ae745f7))
20
+
21
+
22
+ ### Documentation
23
+
24
+ * **pi-permission-system:** document zod config schema and strict validation ([c8babf9](https://github.com/gotgenes/pi-packages/commit/c8babf962be56fa48eba22d5a7fe7ca34ccfa1e7))
25
+
26
+ ## [18.2.0](https://github.com/gotgenes/pi-packages/compare/pi-permission-system-v18.1.2...pi-permission-system-v18.2.0) (2026-07-06)
27
+
28
+
29
+ ### Features
30
+
31
+ * **pi-permission-system:** add yolo rule origin and ask→allow rewrite helper ([a4bbcc0](https://github.com/gotgenes/pi-packages/commit/a4bbcc0f25d57e31c7658e48ec5bc4465a4c1908))
32
+ * **pi-permission-system:** auto-approve yolo-origin allow in the gate runner ([caf8419](https://github.com/gotgenes/pi-packages/commit/caf8419f835b37693678fccf77373a828f850386))
33
+ * **pi-permission-system:** rewrite ask rules to yolo-origin allow at check time ([cd4e509](https://github.com/gotgenes/pi-packages/commit/cd4e509290aed701928890a6df585b383abbfc2b))
34
+
8
35
  ## [18.1.2](https://github.com/gotgenes/pi-packages/compare/pi-permission-system-v18.1.1...pi-permission-system-v18.1.2) (2026-07-05)
9
36
 
10
37
 
package/README.md CHANGED
@@ -132,6 +132,7 @@ If you relied on the old permissive behavior for bash, set an explicit permissiv
132
132
  | [docs/opencode-compatibility.md](docs/opencode-compatibility.md) | OpenCode compatibility — shared concepts, divergences, porting guide |
133
133
  | [docs/troubleshooting.md](docs/troubleshooting.md) | Common issues, diagnostic logging, threat model |
134
134
  | [docs/migration/legacy-to-flat.md](docs/migration/legacy-to-flat.md) | Migration from pre-v2 config layout |
135
+ | [docs/migration/strict-config-validation.md](docs/migration/strict-config-validation.md) | Strict config validation (breaking) — reading and fixing rejected configs |
135
136
 
136
137
  ## Development
137
138
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://raw.githubusercontent.com/gotgenes/pi-permission-system/main/schemas/permissions.schema.json",
2
+ "$schema": "https://raw.githubusercontent.com/gotgenes/pi-packages/main/packages/pi-permission-system/schemas/permissions.schema.json",
3
3
 
4
4
  "debugLog": false,
5
5
  "permissionReviewLog": true,
@@ -36,7 +36,7 @@ Scalar fields (`debugLog`, `permissionReviewLog`, `yoloMode`) use simple replace
36
36
 
37
37
  ```jsonc
38
38
  {
39
- "$schema": "https://raw.githubusercontent.com/gotgenes/pi-permission-system/main/schemas/permissions.schema.json",
39
+ "$schema": "https://raw.githubusercontent.com/gotgenes/pi-packages/main/packages/pi-permission-system/schemas/permissions.schema.json",
40
40
 
41
41
  // Runtime knobs
42
42
  "debugLog": false,
@@ -697,4 +697,10 @@ npx --yes ajv-cli@5 validate \
697
697
  -d ./config.json
698
698
  ```
699
699
 
700
- **Editor tip:** Add `"$schema": "./schemas/permissions.schema.json"` to your config for autocomplete support.
700
+ **Editor tip:** Add the hosted schema URL as the `$schema` key in your config for autocomplete and validation support:
701
+
702
+ ```json
703
+ "$schema": "https://raw.githubusercontent.com/gotgenes/pi-packages/main/packages/pi-permission-system/schemas/permissions.schema.json"
704
+ ```
705
+
706
+ The schema is generated from the extension's zod source of truth (`src/config-schema.ts`); regenerate it with `pnpm run gen:schema` after changing the config shape.
@@ -0,0 +1,38 @@
1
+ # Migration guide: strict config validation
2
+
3
+ Starting with the release that closes #547, the permission-system config loader validates each config file against a JSON Schema derived from a zod source of truth.
4
+ This is a **breaking change** in how malformed config is handled.
5
+
6
+ ## What changed
7
+
8
+ The loader used to be **tolerant**: it silently discarded a malformed field and loaded the rest.
9
+ For example, a config with `"debugLog": "yes"` (a string, not a boolean) simply dropped `debugLog` and kept going; an unknown key like `"debugLo": true` was ignored.
10
+
11
+ The loader is now **strict and fail-closed**:
12
+
13
+ - A config file with **any** invalid field is rejected as a whole scope (global or project).
14
+ - The rejected scope contributes **no** permission rules, so its surfaces fall back to the safe universal `ask` default — never `allow`.
15
+ - Each problem is reported as a clear, path-qualified issue in the permission review log (and the debug log when `debugLog` is on).
16
+
17
+ Nothing about the config **format** changed — a config that was already valid keeps working unchanged.
18
+
19
+ ## What you need to do
20
+
21
+ If your config was valid, nothing.
22
+
23
+ If a scope stops taking effect after upgrading (surfaces start prompting with `ask`), open the permission review log and look for `Invalid config value at '<path>': …` or `Unrecognized config key '<key>'.` messages.
24
+ Fix each reported problem, then reload.
25
+
26
+ Common fixes:
27
+
28
+ - **Wrong type** — e.g. `"toolInputPreviewMaxLength": "400"` (string) → `400` (number); `"debugLog": "true"` → `true`.
29
+ - **Unknown key** — a typo (`"debugLo"` → `"debugLog"`) or a legacy top-level policy key (`defaultPolicy`, `tools`, `bash`, …) that belongs under `permission` (see `legacy-to-flat.md`).
30
+ - **Invalid permission action** — an action must be `"allow"`, `"deny"`, or `"ask"` (or a `{ "action": "deny", "reason": "…" }` object).
31
+
32
+ ## Editor support
33
+
34
+ Add the hosted schema to your config for autocomplete and inline validation, so these problems surface as you type:
35
+
36
+ ```json
37
+ "$schema": "https://raw.githubusercontent.com/gotgenes/pi-packages/main/packages/pi-permission-system/schemas/permissions.schema.json"
38
+ ```
@@ -153,7 +153,7 @@ The result is broader coverage (paths detected in any command, not just a curate
153
153
 
154
154
  ```jsonc
155
155
  {
156
- "$schema": "https://raw.githubusercontent.com/gotgenes/pi-permission-system/main/schemas/permissions.schema.json",
156
+ "$schema": "https://raw.githubusercontent.com/gotgenes/pi-packages/main/packages/pi-permission-system/schemas/permissions.schema.json",
157
157
  "permission": {
158
158
  "*": "allow",
159
159
  "bash": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gotgenes/pi-permission-system",
3
- "version": "18.1.2",
3
+ "version": "19.0.0",
4
4
  "description": "Permission enforcement extension for the Pi coding agent.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -73,10 +73,12 @@
73
73
  },
74
74
  "dependencies": {
75
75
  "tree-sitter-bash": "^0.25.1",
76
- "web-tree-sitter": "^0.26.9"
76
+ "web-tree-sitter": "^0.26.9",
77
+ "zod": "^4.4.3"
77
78
  },
78
79
  "scripts": {
79
80
  "check": "tsc --noEmit",
81
+ "gen:schema": "node --experimental-strip-types scripts/generate-permissions-schema.ts && biome format --write schemas/permissions.schema.json",
80
82
  "test": "vitest run",
81
83
  "test:watch": "vitest",
82
84
  "lint:md": "rumdl check *.md docs/**/*.md",
@@ -1,11 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "$id": "https://raw.githubusercontent.com/gotgenes/pi-permission-system/main/schemas/permissions.schema.json",
4
- "title": "PI Permission System Configuration",
5
- "description": "Unified config file combining runtime knobs and flat permission policy for pi-permission-system.",
6
- "markdownDescription": "Unified config file combining runtime knobs and flat permission policy for [pi-permission-system](https://github.com/gotgenes/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).",
3
+ "$id": "https://raw.githubusercontent.com/gotgenes/pi-packages/main/packages/pi-permission-system/schemas/permissions.schema.json",
7
4
  "type": "object",
8
- "additionalProperties": false,
9
5
  "properties": {
10
6
  "$schema": {
11
7
  "description": "JSON Schema URI for editor autocomplete and validation.",
@@ -14,64 +10,64 @@
14
10
  "debugLog": {
15
11
  "description": "Write verbose permission-system diagnostics to the extension logs directory.",
16
12
  "markdownDescription": "Write verbose permission-system diagnostics to `logs/pi-permission-system-debug.jsonl` under the extension config directory.",
17
- "type": "boolean",
18
- "default": false
13
+ "default": false,
14
+ "type": "boolean"
19
15
  },
20
16
  "permissionReviewLog": {
21
17
  "description": "Write permission request and decision audit events to the extension logs directory.",
22
18
  "markdownDescription": "Write permission request and decision audit events to `logs/pi-permission-system-permission-review.jsonl` under the extension config directory.",
23
- "type": "boolean",
24
- "default": true
19
+ "default": true,
20
+ "type": "boolean"
25
21
  },
26
22
  "yoloMode": {
27
23
  "description": "Auto-approve ask-state permission checks, including subagent approval forwarding.",
28
24
  "markdownDescription": "Auto-approve `ask`-state permission checks, including subagent approval forwarding.\n\n⚠️ **Use with caution** — this disables all interactive confirmation prompts.",
29
- "type": "boolean",
30
- "default": false
25
+ "default": false,
26
+ "type": "boolean"
31
27
  },
32
28
  "toolInputPreviewMaxLength": {
33
29
  "description": "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.",
34
30
  "markdownDescription": "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.",
35
31
  "type": "integer",
36
- "minimum": 1
32
+ "minimum": 1,
33
+ "maximum": 9007199254740991
37
34
  },
38
35
  "toolTextSummaryMaxLength": {
39
36
  "description": "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).",
40
37
  "markdownDescription": "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.",
41
38
  "type": "integer",
42
- "minimum": 1
39
+ "minimum": 1,
40
+ "maximum": 9007199254740991
43
41
  },
44
42
  "piInfrastructureReadPaths": {
45
43
  "description": "Additional directories to auto-allow for reads as Pi infrastructure, bypassing the external_directory gate. Supports ~ expansion and wildcard patterns (* and ?).",
46
44
  "markdownDescription": "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.",
45
+ "default": [],
47
46
  "type": "array",
48
47
  "items": {
49
48
  "type": "string",
50
49
  "minLength": 1
51
- },
52
- "default": []
50
+ }
53
51
  },
54
52
  "permission": {
55
- "description": "Flat permission policy. Each key is a surface name; values are a PermissionState string (catch-all) or a pattern→action map.",
56
- "markdownDescription": "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.",
57
53
  "type": "object",
58
54
  "propertyNames": {
59
- "description": "A surface name or the universal fallback key '*'.",
60
55
  "type": "string",
61
- "minLength": 1
56
+ "minLength": 1,
57
+ "description": "A surface name or the universal fallback key '*'."
62
58
  },
63
59
  "additionalProperties": {
64
- "oneOf": [
60
+ "anyOf": [
65
61
  {
66
- "$ref": "#/$defs/permissionState",
67
- "description": "Catch-all shorthand: equivalent to { \"*\": action }."
62
+ "$ref": "#/$defs/permissionState"
68
63
  },
69
64
  {
70
- "$ref": "#/$defs/permissionMap",
71
- "description": "Pattern→action map for this surface."
65
+ "$ref": "#/$defs/permissionMap"
72
66
  }
73
67
  ]
74
68
  },
69
+ "description": "Flat permission policy. Each key is a surface name; values are a PermissionState string (catch-all) or a pattern→action map.",
70
+ "markdownDescription": "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.",
75
71
  "examples": [
76
72
  {
77
73
  "*": "ask",
@@ -90,69 +86,85 @@
90
86
  "git status": "allow",
91
87
  "git diff": "allow"
92
88
  },
93
- "mcp": { "*": "ask", "mcp_status": "allow", "exa:*": "allow" },
94
- "skill": { "*": "ask", "librarian": "allow" },
95
- "external_directory": { "*": "ask", "~/.cargo/registry/*": "allow" }
89
+ "mcp": {
90
+ "*": "ask",
91
+ "mcp_status": "allow",
92
+ "exa:*": "allow"
93
+ },
94
+ "skill": {
95
+ "*": "ask",
96
+ "librarian": "allow"
97
+ },
98
+ "external_directory": {
99
+ "*": "ask",
100
+ "~/.cargo/registry/*": "allow"
101
+ }
96
102
  }
97
103
  ]
98
104
  }
99
105
  },
106
+ "additionalProperties": false,
107
+ "title": "PI Permission System Configuration",
108
+ "description": "Unified config file combining runtime knobs and flat permission policy for pi-permission-system.",
109
+ "markdownDescription": "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).",
100
110
  "$defs": {
101
111
  "permissionState": {
102
- "description": "A permission decision: allow (permit silently), deny (block with error), or ask (prompt the user for confirmation).",
103
- "oneOf": [
112
+ "anyOf": [
104
113
  {
114
+ "type": "string",
105
115
  "const": "allow",
106
116
  "description": "Permit the action silently with no user interaction."
107
117
  },
108
118
  {
119
+ "type": "string",
109
120
  "const": "deny",
110
121
  "description": "Block the action with an error message. The agent is told not to retry."
111
122
  },
112
123
  {
124
+ "type": "string",
113
125
  "const": "ask",
114
126
  "description": "Prompt the user for confirmation via the interactive UI before proceeding."
115
127
  }
116
- ]
128
+ ],
129
+ "description": "A permission decision: allow (permit silently), deny (block with error), or ask (prompt the user for confirmation)."
117
130
  },
118
131
  "permissionMap": {
119
- "description": "A map of wildcard patterns to permission states. Last matching pattern wins.",
120
- "markdownDescription": "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/*`).",
121
132
  "type": "object",
122
133
  "propertyNames": {
123
- "description": "A non-empty pattern string. Use * for wildcard matching. Prefix with ~/ or $HOME/ for home-relative paths.",
124
134
  "type": "string",
125
- "minLength": 1
135
+ "minLength": 1,
136
+ "description": "A non-empty pattern string. Use * for wildcard matching. Prefix with ~/ or $HOME/ for home-relative paths."
126
137
  },
127
138
  "additionalProperties": {
128
- "oneOf": [
139
+ "anyOf": [
129
140
  {
130
- "$ref": "#/$defs/permissionState",
131
- "description": "A permission decision for this pattern."
141
+ "$ref": "#/$defs/permissionState"
132
142
  },
133
143
  {
134
- "$ref": "#/$defs/denyWithReason",
135
- "description": "Deny this pattern with an optional custom reason."
144
+ "$ref": "#/$defs/denyWithReason"
136
145
  }
137
146
  ]
138
- }
147
+ },
148
+ "description": "A map of wildcard patterns to permission states. Last matching pattern wins.",
149
+ "markdownDescription": "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/*`)."
139
150
  },
140
151
  "denyWithReason": {
141
152
  "type": "object",
142
- "description": "Deny with an optional custom reason shown to the agent when the action is blocked.",
143
153
  "properties": {
144
154
  "action": {
155
+ "type": "string",
145
156
  "const": "deny",
146
- "description": "The permission decision \u2014 must be \"deny\"."
157
+ "description": "The permission decision must be \"deny\"."
147
158
  },
148
159
  "reason": {
160
+ "description": "Optional reason shown to the agent when this action is denied.",
149
161
  "type": "string",
150
- "maxLength": 500,
151
- "description": "Optional reason shown to the agent when this action is denied."
162
+ "maxLength": 500
152
163
  }
153
164
  },
154
165
  "required": ["action"],
155
- "additionalProperties": false
166
+ "additionalProperties": false,
167
+ "description": "Deny with an optional custom reason shown to the agent when the action is blocked."
156
168
  }
157
169
  }
158
170
  }
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { normalize } from "node:path";
3
+ import type { ZodError } from "zod";
3
4
  import {
4
5
  getGlobalConfigPath,
5
6
  getLegacyExtensionConfigPath,
@@ -7,32 +8,19 @@ import {
7
8
  getLegacyProjectPolicyPath,
8
9
  getProjectConfigPath,
9
10
  } from "./config-paths";
11
+ import {
12
+ type UnifiedPermissionConfig,
13
+ unifiedConfigSchema,
14
+ } from "./config-schema";
10
15
  import { mergeFlatPermissions } from "./permission-merge";
11
16
  import type { FlatPermissionConfig, PatternValue } from "./types";
12
- import {
13
- isDenyWithReason,
14
- isPermissionState,
15
- normalizeOptionalPositiveInt,
16
- normalizeOptionalStringArray,
17
- toRecord,
18
- } from "./value-guards";
17
+ import { isDenyWithReason, isPermissionState } from "./value-guards";
19
18
 
20
- /**
21
- * Unified config shape combining runtime knobs and flat permission policy.
22
- * All fields are optional so partial configs (project-only, global-only) work.
23
- */
24
- export interface UnifiedPermissionConfig {
25
- // Runtime knobs
26
- debugLog?: boolean;
27
- permissionReviewLog?: boolean;
28
- yoloMode?: boolean;
29
- toolInputPreviewMaxLength?: number;
30
- toolTextSummaryMaxLength?: number;
31
- piInfrastructureReadPaths?: string[];
32
-
33
- // Flat permission policy
34
- permission?: FlatPermissionConfig;
35
- }
19
+ // The unified config shape is derived from the zod schema (config-schema.ts,
20
+ // the single source of truth) and re-exported so existing importers keep their
21
+ // import path. All fields are optional so partial configs merge before
22
+ // defaults are applied downstream.
23
+ export type { UnifiedPermissionConfig };
36
24
 
37
25
  export interface UnifiedConfigLoadResult {
38
26
  config: UnifiedPermissionConfig;
@@ -118,20 +106,13 @@ function consumeString(input: string, start: number): ScanSegment {
118
106
  return { output, nextIndex: i };
119
107
  }
120
108
 
121
- function normalizeOptionalBoolean(value: unknown): boolean | undefined {
122
- if (typeof value === "boolean") {
123
- return value;
124
- }
125
- return undefined;
126
- }
127
-
128
109
  /**
129
110
  * Normalize a raw `permission` value from parsed JSON into a FlatPermissionConfig.
130
111
  * Accepts PermissionState strings and DenyWithReason objects inside pattern
131
112
  * maps. Drops non-object top-level values, invalid PermissionState strings, and
132
113
  * invalid action values inside object maps.
133
114
  */
134
- function normalizeFlatPermissionValue(
115
+ export function normalizeFlatPermissionValue(
135
116
  value: unknown,
136
117
  ): FlatPermissionConfig | undefined {
137
118
  if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -172,52 +153,39 @@ function normalizeFlatPermissionValue(
172
153
  }
173
154
 
174
155
  /**
175
- * Normalize raw parsed JSON into the unified config shape.
156
+ * Validate raw parsed JSON against the config schema (the single source of
157
+ * truth in `config-schema.ts`).
158
+ *
159
+ * On success the typed config is returned. On failure the whole scope config is
160
+ * rejected — fail-closed: an empty config contributes no rules, so missing
161
+ * surfaces fall through to the universal `ask` default rather than `allow` —
162
+ * and every schema violation is reported as a clear, actionable issue.
176
163
  */
177
- export function normalizeUnifiedConfig(raw: unknown): {
178
- config: UnifiedPermissionConfig;
179
- issues: string[];
180
- } {
181
- const record = toRecord(raw);
182
- const issues: string[] = [];
183
- const config: UnifiedPermissionConfig = {};
184
-
185
- // Runtime knobs
186
- const debugLog = normalizeOptionalBoolean(record.debugLog);
187
- if (debugLog !== undefined) config.debugLog = debugLog;
188
-
189
- const permissionReviewLog = normalizeOptionalBoolean(
190
- record.permissionReviewLog,
191
- );
192
- if (permissionReviewLog !== undefined)
193
- config.permissionReviewLog = permissionReviewLog;
194
-
195
- const yoloMode = normalizeOptionalBoolean(record.yoloMode);
196
- if (yoloMode !== undefined) config.yoloMode = yoloMode;
197
-
198
- const toolInputPreviewMaxLength = normalizeOptionalPositiveInt(
199
- record.toolInputPreviewMaxLength,
200
- );
201
- if (toolInputPreviewMaxLength !== undefined)
202
- config.toolInputPreviewMaxLength = toolInputPreviewMaxLength;
203
-
204
- const toolTextSummaryMaxLength = normalizeOptionalPositiveInt(
205
- record.toolTextSummaryMaxLength,
206
- );
207
- if (toolTextSummaryMaxLength !== undefined)
208
- config.toolTextSummaryMaxLength = toolTextSummaryMaxLength;
209
-
210
- const piInfrastructureReadPaths = normalizeOptionalStringArray(
211
- record.piInfrastructureReadPaths,
212
- );
213
- if (piInfrastructureReadPaths !== undefined)
214
- config.piInfrastructureReadPaths = piInfrastructureReadPaths;
215
-
216
- // Flat permission policy
217
- const permission = normalizeFlatPermissionValue(record.permission);
218
- if (permission !== undefined) config.permission = permission;
164
+ export function validateUnifiedConfig(
165
+ parsed: unknown,
166
+ ): UnifiedConfigLoadResult {
167
+ const result = unifiedConfigSchema.safeParse(parsed);
168
+ if (result.success) {
169
+ return { config: result.data, issues: [] };
170
+ }
171
+ return { config: {}, issues: formatConfigIssues(result.error) };
172
+ }
219
173
 
220
- return { config, issues };
174
+ /** Render each schema violation as a clear, path-qualified message. */
175
+ function formatConfigIssues(error: ZodError): string[] {
176
+ const messages: string[] = [];
177
+ for (const issue of error.issues) {
178
+ if (issue.code === "unrecognized_keys") {
179
+ for (const key of issue.keys) {
180
+ messages.push(`Unrecognized config key '${key}'.`);
181
+ }
182
+ continue;
183
+ }
184
+ const location =
185
+ issue.path.length > 0 ? issue.path.map(String).join(".") : "(root)";
186
+ messages.push(`Invalid config value at '${location}': ${issue.message}`);
187
+ }
188
+ return messages;
221
189
  }
222
190
 
223
191
  /**
@@ -320,7 +288,8 @@ export function loadAndMergeConfigs(
320
288
  `Move it to '${newGlobalPath}':\n` +
321
289
  ` mv '${legacyGlobalPolicyPath}' '${newGlobalPath}'`,
322
290
  );
323
- allIssues.push(...legacy.issues);
291
+ // Legacy files are migrated away; the move-it guidance above is the
292
+ // actionable signal, so strict-validation issues for them are suppressed.
324
293
  merged = mergeUnifiedConfigs(merged, legacy.config);
325
294
  }
326
295
 
@@ -337,7 +306,7 @@ export function loadAndMergeConfigs(
337
306
  `Move runtime settings to '${newGlobalPath}':\n` +
338
307
  ` mv '${legacyExtConfigPath}' '${newGlobalPath}'`,
339
308
  );
340
- allIssues.push(...legacy.issues);
309
+ // See above: legacy-file validation issues are suppressed.
341
310
  merged = mergeUnifiedConfigs(merged, legacy.config);
342
311
  }
343
312
 
@@ -355,7 +324,7 @@ export function loadAndMergeConfigs(
355
324
  `Move it to '${newProjectPath}':\n` +
356
325
  ` mv '${legacyProjectPolicyPath}' '${newProjectPath}'`,
357
326
  );
358
- allIssues.push(...legacy.issues);
327
+ // See above: legacy-file validation issues are suppressed.
359
328
  merged = mergeUnifiedConfigs(merged, legacy.config);
360
329
  }
361
330
 
@@ -421,7 +390,7 @@ export function loadUnifiedConfig(path: string): UnifiedConfigLoadResult {
421
390
  try {
422
391
  const raw = readFileSync(path, "utf-8");
423
392
  const parsed = JSON.parse(stripJsonComments(raw)) as unknown;
424
- return normalizeUnifiedConfig(parsed);
393
+ return validateUnifiedConfig(parsed);
425
394
  } catch (error) {
426
395
  const message = error instanceof Error ? error.message : String(error);
427
396
  return {