@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.
@@ -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
+ }
@@ -66,6 +66,13 @@ export function normalizePermissionSystemConfig(
66
66
  return result;
67
67
  }
68
68
 
69
+ export function isYoloModeEnabled(
70
+ config: PermissionSystemExtensionConfig,
71
+ ): boolean {
72
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-conversion -- typed as boolean but may be undefined at runtime (untyped callers); Boolean() guards against that
73
+ return Boolean(config.yoloMode);
74
+ }
75
+
69
76
  export function ensurePermissionSystemLogsDirectory(
70
77
  logsDir: string,
71
78
  ): string | undefined {
@@ -6,6 +6,7 @@ import {
6
6
  type SessionEntryView,
7
7
  } from "#src/active-agent";
8
8
  import type { ConfigReader } from "#src/config-store";
9
+ import { isYoloModeEnabled } from "#src/extension-config";
9
10
  import type {
10
11
  PermissionDecisionUi,
11
12
  PermissionPromptDecision,
@@ -31,7 +32,6 @@ import type { DebugReviewLogger } from "#src/session-logger";
31
32
  import { isSubagentExecutionContext } from "#src/subagent-context";
32
33
  import type { SubagentSessionRegistry } from "#src/subagent-registry";
33
34
  import { toRecord } from "#src/value-guards";
34
- import { shouldAutoApprovePermissionState } from "#src/yolo-mode";
35
35
 
36
36
  import {
37
37
  cleanupPermissionForwardingLocationIfEmpty,
@@ -90,7 +90,7 @@ export interface PermissionForwarderDeps {
90
90
  message: string,
91
91
  options?: RequestPermissionOptions,
92
92
  ) => Promise<PermissionPromptDecision>;
93
- /** Read current config for yolo-mode auto-approve check (called at prompt time). */
93
+ /** Read current config for the retained forwarded-inbox yolo auto-approve check. */
94
94
  config: ConfigReader;
95
95
  }
96
96
 
@@ -506,7 +506,10 @@ export class PermissionForwarder implements ApprovalRequester, InboxProcessor {
506
506
  approved: false,
507
507
  state: "denied",
508
508
  };
509
- if (shouldAutoApprovePermissionState("ask", this.config.current())) {
509
+ // Last yolo check outside the composed ruleset: dissolves when
510
+ // processInbox is refactored onto evaluate() + Authorizer selection in
511
+ // the Phase 9 spine work.
512
+ if (isYoloModeEnabled(this.config.current())) {
510
513
  this.logger.review(
511
514
  "forwarded_permission.auto_approved",
512
515
  forwardedPermissionLogDetails,
@@ -62,7 +62,7 @@ export function deriveResolution(
62
62
  canConfirm: boolean,
63
63
  autoApproved = false,
64
64
  ): PermissionDecisionResolution {
65
- if (state === "allow") return "policy_allow";
65
+ if (state === "allow") return autoApproved ? "auto_approved" : "policy_allow";
66
66
  if (state === "deny") return "policy_deny";
67
67
  // state === "ask"
68
68
  if (action === "allow") {
@@ -105,6 +105,28 @@ export class GateRunner {
105
105
  return { action: "allow" };
106
106
  }
107
107
 
108
+ // 2b. Yolo fast-path — a composition-stage ask→allow rewrite records
109
+ // origin "yolo" on the matched rule. Auto-approve without prompting,
110
+ // preserving today's single auto_approved review entry + decision event
111
+ // so review-log parity holds (#526).
112
+ if (check.state === "allow" && check.origin === "yolo") {
113
+ this.reporter.writeReviewLog("permission_request.auto_approved", {
114
+ ...descriptor.logContext,
115
+ agentName,
116
+ resolution: "auto_approved",
117
+ });
118
+ this.reporter.emitDecision(
119
+ buildDecisionEvent(
120
+ descriptor.decision,
121
+ check,
122
+ agentName,
123
+ "allow",
124
+ deriveResolution(check.state, "allow", false, false, true),
125
+ ),
126
+ );
127
+ return { action: "allow" };
128
+ }
129
+
108
130
  // 3. Apply the deny/ask/allow gate
109
131
  const canConfirm = this.prompter.canConfirm();
110
132
 
package/src/index.ts CHANGED
@@ -6,6 +6,7 @@ import { getGlobalConfigPath } from "./config-paths";
6
6
  import { ConfigStore } from "./config-store";
7
7
  import { DecisionAudit } from "./decision-audit";
8
8
  import { GateDecisionReporter } from "./decision-reporter";
9
+ import { isYoloModeEnabled } from "./extension-config";
9
10
  import { computeExtensionPaths } from "./extension-paths";
10
11
  import {
11
12
  PermissionForwarder,
@@ -46,10 +47,6 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
46
47
  // session (PathNormalizer) and, later, rule evaluation. Interior modules must
47
48
  // not read process.platform (enforced by the eslint guard scoped to src/).
48
49
  const hostPlatform = process.platform;
49
- const permissionManager = new PermissionManager({
50
- agentDir,
51
- platform: hostPlatform,
52
- });
53
50
  const sessionRules = new SessionRules();
54
51
  const subagentRegistry = getSubagentSessionRegistry();
55
52
  const formatterRegistry = new ToolInputFormatterRegistry();
@@ -65,6 +62,15 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
65
62
  // eslint-disable-next-line prefer-const -- forward-declared let; `const` requires an initializer
66
63
  let session: PermissionSession;
67
64
 
65
+ // Constructed after the `configStore` forward declaration so the yolo reader
66
+ // can close over it; the closure runs per check(), after configStore is
67
+ // assigned below. yolo becomes a composition-stage ask→allow rewrite (#526).
68
+ const permissionManager = new PermissionManager({
69
+ agentDir,
70
+ platform: hostPlatform,
71
+ isYoloEnabled: () => isYoloModeEnabled(configStore.current()),
72
+ });
73
+
68
74
  const logger = new PermissionSessionLogger({
69
75
  globalLogsDir: paths.globalLogsDir,
70
76
  getConfig: () => configStore.current(),
@@ -90,14 +96,12 @@ export default function piPermissionSystemExtension(pi: ExtensionAPI): void {
90
96
  const forwarder = new PermissionForwarder(forwardingDeps);
91
97
 
92
98
  const prompter = new PermissionPrompter({
93
- config: configStore,
94
99
  logger,
95
100
  events: pi.events,
96
101
  forwarder,
97
102
  });
98
103
 
99
104
  const gateway = new PromptingGateway({
100
- config: configStore,
101
105
  subagentSessionsDir: paths.subagentSessionsDir,
102
106
  platform: hostPlatform,
103
107
  registry: subagentRegistry,
@@ -20,6 +20,7 @@ import {
20
20
  evaluateAnyValue,
21
21
  evaluateFirst,
22
22
  pathMatchOptions,
23
+ rewriteAsksToYolo,
23
24
  } from "./rule";
24
25
  import { mergeScopesWithOrigins } from "./scope-merge";
25
26
  import {
@@ -53,6 +54,9 @@ const DEFAULT_UNIVERSAL_FALLBACK: PermissionState = "ask";
53
54
  /** Promotion predicate matching no token — the no-`path`-rules default (#509). */
54
55
  const NO_PROMOTION: PathRuleTokenMatcher = () => false;
55
56
 
57
+ /** Default yolo reader — yolo disabled unless the composition root injects one. */
58
+ const YOLO_DISABLED = (): boolean => false;
59
+
56
60
  type FileCacheEntry<TValue> = {
57
61
  stamp: string;
58
62
  value: TValue;
@@ -110,11 +114,20 @@ export interface PermissionManagerOptions extends PolicyLoaderOptions {
110
114
  * Defaults to a POSIX flavor; production always supplies the real platform.
111
115
  */
112
116
  platform?: NodeJS.Platform;
117
+ /**
118
+ * yolo-mode reader, injected from the composition root. When it reports
119
+ * true, {@link PermissionManager.check} rewrites every matched `ask` to a
120
+ * standing `allow` tagged `origin: "yolo"` (recorded authority, #526).
121
+ * Read per check so a mid-session config change takes effect; defaults to
122
+ * yolo disabled.
123
+ */
124
+ isYoloEnabled?: () => boolean;
113
125
  }
114
126
 
115
127
  export class PermissionManager implements ScopedPermissionManager {
116
128
  private readonly agentDir: string | undefined;
117
129
  private readonly platform: NodeJS.Platform;
130
+ private readonly isYoloEnabled: () => boolean;
118
131
  private loader: PolicyLoader;
119
132
  private readonly resolvedPermissionsCache = new Map<
120
133
  string,
@@ -124,6 +137,7 @@ export class PermissionManager implements ScopedPermissionManager {
124
137
  constructor(options: PermissionManagerOptions = {}) {
125
138
  this.agentDir = options.agentDir;
126
139
  this.platform = options.platform ?? "linux";
140
+ this.isYoloEnabled = options.isYoloEnabled ?? YOLO_DISABLED;
127
141
  this.loader =
128
142
  options.policyLoader ??
129
143
  new FilePolicyLoader(
@@ -311,9 +325,15 @@ export class PermissionManager implements ScopedPermissionManager {
311
325
  sessionRules?: Ruleset,
312
326
  ): PermissionCheckResult {
313
327
  const { composedRules } = this.resolvePermissions(intent.agentName);
314
- const fullRules: Ruleset = sessionRules?.length
328
+ const composedWithSession: Ruleset = sessionRules?.length
315
329
  ? [...composedRules, ...sessionRules]
316
330
  : composedRules;
331
+ // Apply the yolo rewrite post-cache so the resolved-permissions cache and
332
+ // the display surfaces (getComposedConfigRules / getToolPermission) stay
333
+ // yolo-free — only the resolution path sees the ask→allow rewrite (#526).
334
+ const fullRules: Ruleset = this.isYoloEnabled()
335
+ ? rewriteAsksToYolo(composedWithSession)
336
+ : composedWithSession;
317
337
 
318
338
  if (intent.kind === "path-values") {
319
339
  const lookupValues =
@@ -1,5 +1,4 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { ConfigReader } from "./config-store";
3
2
  import type { ApprovalRequester } from "./forwarded-permissions/permission-forwarder";
4
3
  import type { PermissionPromptDecision } from "./permission-dialog";
5
4
  import {
@@ -8,7 +7,6 @@ import {
8
7
  } from "./permission-events";
9
8
  import { buildDirectUiPrompt } from "./permission-ui-prompt";
10
9
  import type { ReviewLogger } from "./session-logger";
11
- import { shouldAutoApprovePermissionState } from "./yolo-mode";
12
10
 
13
11
  export type PermissionReviewSource = "tool_call" | "skill_input" | "skill_read";
14
12
 
@@ -40,13 +38,11 @@ export interface PermissionPrompterApi {
40
38
  /**
41
39
  * Dependencies required by PermissionPrompter.
42
40
  *
43
- * Keeps the prompter's external surface narrow: callers provide config
44
- * access, a review logger, the UI-prompt event bus, and the forwarder
45
- * that owns the UI/subagent-forwarding branching logic.
41
+ * Keeps the prompter's external surface narrow: callers provide a review
42
+ * logger, the UI-prompt event bus, and the forwarder that owns the
43
+ * UI/subagent-forwarding branching logic.
46
44
  */
47
45
  export interface PermissionPrompterDeps {
48
- /** Read current config for yolo-mode check (called at prompt time). */
49
- config: ConfigReader;
50
46
  /** Write structured entries to the permission review log. */
51
47
  logger: ReviewLogger;
52
48
  /** Event bus used for UI prompt broadcasts. */
@@ -57,10 +53,13 @@ export interface PermissionPrompterDeps {
57
53
 
58
54
  /**
59
55
  * Encapsulates the full permission-prompt flow:
60
- * 1. Yolo-mode auto-approval check.
61
- * 2. Review-log "waiting" entry.
62
- * 3. UI-present vs. subagent-forwarding branching (via confirmPermission).
63
- * 4. Review-log "approved" / "denied" entry.
56
+ * 1. Review-log "waiting" entry.
57
+ * 2. UI-present vs. subagent-forwarding branching (via confirmPermission).
58
+ * 3. Review-log "approved" / "denied" entry.
59
+ *
60
+ * Yolo-mode auto-approval happens upstream, at the composition stage
61
+ * (`PermissionManager.check`'s `rewriteAsksToYolo`) — an `ask` never reaches
62
+ * this class under yolo, so this class has no yolo-mode knowledge.
64
63
  *
65
64
  * Injecting a single PermissionPrompter instance means adding a new prompt
66
65
  * parameter (e.g. a future sessionLabel variant) only requires changing
@@ -73,11 +72,6 @@ export class PermissionPrompter implements PermissionPrompterApi {
73
72
  ctx: ExtensionContext,
74
73
  details: PromptPermissionDetails,
75
74
  ): Promise<PermissionPromptDecision> {
76
- if (shouldAutoApprovePermissionState("ask", this.deps.config.current())) {
77
- this.writeReviewEntry("permission_request.auto_approved", details);
78
- return { approved: true, state: "approved", autoApproved: true };
79
- }
80
-
81
75
  this.writeReviewEntry("permission_request.waiting", details);
82
76
 
83
77
  // Build the event once. When this session has UI it broadcasts directly;
@@ -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,6 +1,5 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
 
3
- import type { ConfigReader } from "./config-store";
4
3
  import type { GatePrompter } from "./gate-prompter";
5
4
  import type { PermissionPromptDecision } from "./permission-dialog";
6
5
  import type {
@@ -9,18 +8,15 @@ import type {
9
8
  } from "./permission-prompter";
10
9
  import { isSubagentExecutionContext } from "./subagent-context";
11
10
  import type { SubagentSessionRegistry } from "./subagent-registry";
12
- import { canResolveAskPermissionRequest } from "./yolo-mode";
13
11
 
14
12
  /**
15
13
  * Dependencies required by PromptingGateway.
16
14
  *
17
- * All four fields are actively consumed:
18
- * - `config` + `subagentSessionsDir` + `registry` drive `canConfirm()`.
15
+ * All fields are actively consumed:
16
+ * - `subagentSessionsDir` + `registry` drive `canConfirm()`.
19
17
  * - `prompter` is called by `prompt()`.
20
18
  */
21
19
  export interface PromptingGatewayDeps {
22
- /** Read current config for the yolo-mode branch of the can-prompt policy. */
23
- config: ConfigReader;
24
20
  /** Static path used to detect a forwarding subagent context. */
25
21
  subagentSessionsDir: string;
26
22
  /** Host platform, injected from the composition root, for subagent-context path detection. */
@@ -46,8 +42,8 @@ export interface PromptingGatewayLifecycle {
46
42
  * Context-owning implementation of the GatePrompter role.
47
43
  *
48
44
  * Owns the stored ExtensionContext and the "can we prompt?" policy
49
- * (UI / subagent / yolo-mode), replacing the four twin methods
50
- * that previously lived on PermissionSession.
45
+ * (UI / subagent), replacing the four twin methods that previously
46
+ * lived on PermissionSession.
51
47
  *
52
48
  * Lifecycle: PermissionSession drives activate/deactivate so the stored
53
49
  * context mirrors the session context without independent call-site changes.
@@ -72,22 +68,22 @@ export class PromptingGateway
72
68
  /**
73
69
  * Whether an interactive permission prompt can be shown.
74
70
  *
75
- * Returns false when no context is active. Otherwise delegates to
76
- * canResolveAskPermissionRequest, which checks hasUI, subagent status,
77
- * and yolo-mode relocating the policy from the index.ts closure.
71
+ * Returns false when no context is active. Otherwise true when the
72
+ * context has UI or is a forwarding subagent — the two Authorizer-
73
+ * selection predicates the Phase 9 spine will consume. Yolo-mode never
74
+ * reaches this policy: it is resolved upstream at the composition stage.
78
75
  */
79
76
  canConfirm(): boolean {
80
77
  if (this.context === null) return false;
81
- return canResolveAskPermissionRequest({
82
- config: this.deps.config.current(),
83
- hasUI: this.context.hasUI,
84
- isSubagent: isSubagentExecutionContext(
78
+ return (
79
+ this.context.hasUI ||
80
+ isSubagentExecutionContext(
85
81
  this.context,
86
82
  this.deps.subagentSessionsDir,
87
83
  this.deps.platform,
88
84
  this.deps.registry,
89
- ),
90
- });
85
+ )
86
+ );
91
87
  }
92
88
 
93
89
  /**
package/src/rule.ts CHANGED
@@ -9,6 +9,7 @@ import { wildcardMatch } from "./wildcard-matcher";
9
9
  * Synthesized: "builtin" (universal default / evaluate() fallback),
10
10
  * "baseline" (conditional MCP metadata auto-allow).
11
11
  * Runtime: "session" (session approvals).
12
+ * Rewrite: "yolo" (composition-stage ask→allow rewrite under yolo mode).
12
13
  */
13
14
  export type RuleOrigin =
14
15
  | "global"
@@ -17,7 +18,8 @@ export type RuleOrigin =
17
18
  | "project-agent"
18
19
  | "builtin"
19
20
  | "baseline"
20
- | "session";
21
+ | "session"
22
+ | "yolo";
21
23
 
22
24
  /** A single permission rule — the atomic unit of policy. */
23
25
  export interface Rule {
@@ -41,6 +43,24 @@ export interface Rule {
41
43
  /** An ordered list of rules. Later rules take priority (last-match-wins). */
42
44
  export type Ruleset = Rule[];
43
45
 
46
+ /**
47
+ * Rewrite every `ask` rule to `allow`, tagged `origin: "yolo"`.
48
+ *
49
+ * The composition-stage expression of yolo mode as recorded authority: when
50
+ * enabled, an `ask` becomes a standing `allow` grant in the ruleset rather than
51
+ * a live prompt-path concern. `deny` and existing `allow` rules pass through
52
+ * untouched, so yolo suppresses prompts but preserves hard denies.
53
+ *
54
+ * Pure and non-mutating — `surface`, `pattern`, and `layer` are preserved so
55
+ * downstream `matchedPattern` / source derivation is unaffected; only `action`
56
+ * and `origin` change.
57
+ */
58
+ export function rewriteAsksToYolo(rules: Ruleset): Ruleset {
59
+ return rules.map((rule) =>
60
+ rule.action === "ask" ? { ...rule, action: "allow", origin: "yolo" } : rule,
61
+ );
62
+ }
63
+
44
64
  /**
45
65
  * Pure permission evaluation.
46
66
  *
package/src/status.ts CHANGED
@@ -5,9 +5,9 @@ import type {
5
5
 
6
6
  import {
7
7
  EXTENSION_ID,
8
+ isYoloModeEnabled,
8
9
  type PermissionSystemExtensionConfig,
9
10
  } from "./extension-config";
10
- import { isYoloModeEnabled } from "./yolo-mode";
11
11
 
12
12
  export const PERMISSION_SYSTEM_STATUS_KEY = EXTENSION_ID;
13
13
  export const PERMISSION_SYSTEM_YOLO_STATUS_VALUE = "yolo";