{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://raw.githubusercontent.com/gotgenes/pi-packages/main/packages/pi-permission-system/schemas/permissions.schema.json",
  "type": "object",
  "properties": {
    "$schema": {
      "description": "JSON Schema URI for editor autocomplete and validation.",
      "type": "string"
    },
    "debugLog": {
      "description": "Write verbose permission-system diagnostics to the extension logs directory.",
      "markdownDescription": "Write verbose permission-system diagnostics to `logs/pi-permission-system-debug.jsonl` under the extension config directory.",
      "default": false,
      "type": "boolean"
    },
    "permissionReviewLog": {
      "description": "Write permission request and decision audit events to the extension logs directory.",
      "markdownDescription": "Write permission request and decision audit events to `logs/pi-permission-system-permission-review.jsonl` under the extension config directory.",
      "default": true,
      "type": "boolean"
    },
    "yoloMode": {
      "description": "Auto-approve ask-state permission checks, including subagent approval forwarding.",
      "markdownDescription": "Auto-approve `ask`-state permission checks, including subagent approval forwarding.\n\n⚠️ **Use with caution** — this disables all interactive confirmation prompts.",
      "default": false,
      "type": "boolean"
    },
    "doublePressToConfirm": {
      "description": "Require a confirming second press of a decision hotkey in the inline permission dialog. Applies to TUI sessions only.",
      "markdownDescription": "Require a confirming second press of a decision hotkey (`y`/`s`/`n`/`r`) in the inline permission dialog before it commits — the first press arms the action and shows a `Press y again to approve.` hint.\n\nApplies to interactive **TUI** sessions only; the non-TUI (RPC/frontend) prompt keeps its single-select flow. Set to `false` to commit decisions on the first hotkey press.",
      "default": true,
      "type": "boolean"
    },
    "forwardingTimeoutMs": {
      "description": "How long a subagent waits for the parent session to answer a forwarded permission request, in milliseconds. Omit to use the default (600000, ten minutes).",
      "markdownDescription": "How long a subagent waits for the parent session to answer a forwarded permission request, in milliseconds.\n\nOmit to use the default (`600000`, ten minutes). A child whose in-process parent is not draining its inbox at all gives up in a couple of seconds regardless of this value, so lower it only to bound how long you are willing to leave an *unanswered* prompt pending.",
      "default": 600000,
      "type": "integer",
      "minimum": 1,
      "maximum": 9007199254740991
    },
    "promptMaxRows": {
      "description": "Maximum rows a permission prompt renders before eliding its evidence. Omit to use the default (24).",
      "markdownDescription": "Maximum rows a permission prompt renders before eliding its evidence.\n\nOmit to use the default (24). The request's own facts — the requesting agent, the tool, the matched rule, the decision-relevant value — are never elided by this budget; what gives way is the supporting evidence, and `Ctrl+O` expands the prompt to the complete request.",
      "default": 24,
      "type": "integer",
      "minimum": 1,
      "maximum": 9007199254740991
    },
    "promptFieldMaxWidth": {
      "description": "Maximum characters of any one field shown in a permission prompt. Omit to use the default (400).",
      "markdownDescription": "Maximum characters of any one field shown in a permission prompt.\n\nOmit to use the default (400). This is what bounds a single pathological field — a long here-string command, say — that would otherwise fill the prompt through wrapping. A shortened field is marked with an ellipsis, and `Ctrl+O` shows it in full.",
      "default": 400,
      "type": "integer",
      "minimum": 1,
      "maximum": 9007199254740991
    },
    "reviewLogFieldMaxWidth": {
      "description": "Maximum characters of any one value written to the permission review log. Omit to use the default (1000).",
      "markdownDescription": "Maximum characters of any one value written to the permission review log.\n\nOmit to use the default (1000). Every string the review log writes is narrowed to this width and marked with an ellipsis, so the log's growth is a decision you make rather than a side effect of how long a command happened to be. Raise it to keep longer values — a bash command exceeding the width is stored shortened.\n\nThis is a length bound, not redaction: it never inspects a value to decide what to hide. Key-name masking is unchanged and applies independently.",
      "default": 1000,
      "type": "integer",
      "minimum": 1,
      "maximum": 9007199254740991
    },
    "toolInputPreviewMaxLength": {
      "deprecated": true,
      "description": "Deprecated and ignored. Superseded by promptMaxRows and promptFieldMaxWidth, which bound the whole prompt rather than one preview. Still accepted so an existing config is not rejected; remove it.",
      "markdownDescription": "**Deprecated and ignored.** Superseded by `promptMaxRows` and `promptFieldMaxWidth`, which bound the whole permission prompt rather than one preview inside it.\n\nStill accepted so an existing config is not rejected fail-closed, but the value no longer takes effect. Remove it.",
      "type": "integer",
      "minimum": 1,
      "maximum": 9007199254740991
    },
    "toolTextSummaryMaxLength": {
      "deprecated": true,
      "description": "Deprecated and ignored. Superseded by promptMaxRows and promptFieldMaxWidth, which bound the whole prompt rather than one summary. Still accepted so an existing config is not rejected; remove it.",
      "markdownDescription": "**Deprecated and ignored.** Superseded by `promptMaxRows` and `promptFieldMaxWidth`, which bound the whole permission prompt rather than one summary inside it.\n\nStill accepted so an existing config is not rejected fail-closed, but the value no longer takes effect. Remove it.",
      "type": "integer",
      "minimum": 1,
      "maximum": 9007199254740991
    },
    "piInfrastructureReadPaths": {
      "description": "Additional directories to auto-allow for reads as Pi infrastructure, bypassing the external_directory gate. Supports ~ expansion and wildcard patterns (* and ?).",
      "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.",
      "default": [],
      "type": "array",
      "items": {
        "type": "string",
        "minLength": 1
      }
    },
    "authorizerChain": {
      "description": "Ordered names of registered live-authority chain links to consult before the terminal authorizer. Config order (not registration order) fixes the chain order; an unregistered name is skipped fail-safe (more prompting, never less); a link decides nothing until it is named here.",
      "markdownDescription": "Ordered names of registered **live-authority chain links** (e.g. a model judge) to consult before the terminal authorizer (the human, or the subagent-forwarding / headless-deny fallback).\n\nA link reviews an `ask` and returns `allow` / `deny` (with an optional teaching reason) / `defer` to the next link. Three invariants govern the chain:\n\n- **Config order wins.** The order here — not the order extensions register in — fixes the security-relevant chain order.\n- **Fail-safe skip.** A name with no registered link is skipped with a warning; the `ask` still reaches the terminal (more prompting, never less).\n- **Opt-in activation.** Installing a judge extension grants it no authority; a link decides nothing until you name it here.\n\nThe chain owner caps every verdict with a bounded-delegation checkpoint: a link's `allow` on an excluded surface (`external_directory` or `path`) is downgraded to `defer`, so a link cannot exceed your policy.\n\nDefaults to an empty list (no links).",
      "default": [],
      "type": "array",
      "items": {
        "type": "string",
        "minLength": 1
      }
    },
    "permission": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "minLength": 1,
        "description": "A surface name or the universal fallback key '*'."
      },
      "additionalProperties": {
        "anyOf": [
          {
            "$ref": "#/$defs/permissionState"
          },
          {
            "$ref": "#/$defs/permissionMap"
          }
        ]
      },
      "description": "Flat permission policy. Each key is a surface name; values are a PermissionState string (catch-all) or a pattern→action map.",
      "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.",
      "examples": [
        {
          "*": "ask",
          "path": {
            "*": "allow",
            "*.env": "deny",
            "*.env.*": "deny",
            "*.env.example": "allow"
          },
          "read": "allow",
          "write": "deny",
          "edit": "deny",
          "bash": {
            "*": "ask",
            "git *": "ask",
            "git status": "allow",
            "git diff": "allow"
          },
          "mcp": {
            "*": "ask",
            "mcp_status": "allow",
            "exa:*": "allow"
          },
          "skill": {
            "*": "ask",
            "librarian": "allow"
          },
          "external_directory": {
            "*": "ask",
            "~/.cargo/registry/*": "allow"
          }
        }
      ]
    },
    "shellTools": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "minLength": 1,
        "description": "A non-bash tool name that carries shell semantics."
      },
      "additionalProperties": {
        "type": "object",
        "properties": {
          "commandArgument": {
            "type": "string",
            "minLength": 1,
            "description": "The name of the tool's input argument holding the shell command string (e.g. 'cmd')."
          },
          "workdirArgument": {
            "description": "Optional name of the tool's input argument holding the working directory (e.g. 'workdir').",
            "type": "string",
            "minLength": 1
          },
          "decisionFloor": {
            "description": "Require every invocation of this shell alias to be reviewed at least as an ask; deny remains deny.",
            "markdownDescription": "Sets the minimum review decision for this alias. `allow` results from Bash policy are raised to `ask`, while existing `ask` and `deny` results are preserved. Only `\"ask\"` is accepted so a project override cannot weaken a global floor.",
            "type": "string",
            "const": "ask"
          }
        },
        "required": [
          "commandArgument"
        ],
        "additionalProperties": false,
        "description": "Maps one shell-aliased tool to the input arguments holding its command and optional working directory, plus an optional ask decision floor."
      },
      "description": "Maps non-bash tool names that carry shell semantics to the input arguments holding their command and working directory.",
      "markdownDescription": "Records which non-`bash` tools carry shell semantics, mapping each tool name to the input argument holding its command (and optionally its working directory).\n\nUse this when an extension replaces the native `bash` tool under a different name — e.g. `@howaboua/pi-codex-conversion` registers `exec_command` with a `cmd` argument and an optional `workdir`. Recording the alias lets the permission system gate that tool through the same bash enforcement stack as native `bash` (command decomposition, wrapper flooring, path/external-directory token gates, and `bash:` rules).\n\nSet `decisionFloor` to `\"ask\"` when the wrapper crosses an additional trust boundary, such as SSH or container execution. Bash `allow` results are raised to `ask`; existing `ask` and `deny` results remain unchanged.\n\nExample:\n\n```json\n\"shellTools\": {\n  \"exec_command\": { \"commandArgument\": \"cmd\", \"workdirArgument\": \"workdir\" },\n  \"ssh_bash\": { \"commandArgument\": \"command\", \"decisionFloor\": \"ask\" }\n}\n```\n\n**Merge order:** merge each tool mapping by field across global → project. Project values can replace argument names, while a global `decisionFloor: \"ask\"` survives when the project entry omits it.",
      "examples": [
        {
          "exec_command": {
            "commandArgument": "cmd",
            "workdirArgument": "workdir"
          },
          "ssh_bash": {
            "commandArgument": "command",
            "decisionFloor": "ask"
          }
        }
      ]
    }
  },
  "additionalProperties": false,
  "title": "PI Permission System Configuration",
  "description": "Unified config file combining runtime knobs and flat permission policy for pi-permission-system.",
  "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).",
  "$defs": {
    "permissionState": {
      "anyOf": [
        {
          "type": "string",
          "const": "allow",
          "description": "Permit the action silently with no user interaction."
        },
        {
          "type": "string",
          "const": "deny",
          "description": "Block the action with an error message. The agent is told not to retry."
        },
        {
          "type": "string",
          "const": "ask",
          "description": "Prompt the user for confirmation via the interactive UI before proceeding."
        }
      ],
      "description": "A permission decision: allow (permit silently), deny (block with error), or ask (prompt the user for confirmation)."
    },
    "permissionMap": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "minLength": 1,
        "description": "A non-empty pattern string. Use * for wildcard matching. Prefix with ~/ or $HOME/ for home-relative paths."
      },
      "additionalProperties": {
        "anyOf": [
          {
            "$ref": "#/$defs/permissionState"
          },
          {
            "$ref": "#/$defs/denyWithReason"
          }
        ]
      },
      "description": "A map of wildcard patterns to permission states. Last matching pattern wins.",
      "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/*`)."
    },
    "denyWithReason": {
      "type": "object",
      "properties": {
        "action": {
          "type": "string",
          "const": "deny",
          "description": "The permission decision — must be \"deny\"."
        },
        "reason": {
          "description": "Optional reason shown to the agent when this action is denied.",
          "type": "string",
          "maxLength": 500
        }
      },
      "required": [
        "action"
      ],
      "additionalProperties": false,
      "description": "Deny with an optional custom reason shown to the agent when the action is blocked."
    }
  }
}
