mirror of
https://bitbucket.org/siakitem/my-pi.git
synced 2026-10-26 10:45:22 +00:00
feat: 组合包配置以包内 config/ 为唯一来源,并新增受保护写入人工审批
配置统一:权限策略、硬防御、Tool Search、提示词封面以及新迁入的 RTK、pi-compaction、pi-worktree、pi-hermes-memory 配置全部由扩展 直接读取已安装组合包内的 config/,pi install / pi update 即完成部署; 删除 rebuild-bundle-config.mjs 与 bundle-manifest.json,my-pi/ 只保留 日志与缓存。update.sh 成功升级后将默认 git 来源的已安装副本 reset 回发布版本。AGENTS.md 新增「组合包配置原则」。 脚本整合:search_config.sh / ssh_config.sh 合并为 configure.sh search|ssh;install.sh / update.sh 共享函数抽到 scripts/lib.sh,远程 安装器改为先下载到临时文件再执行,下载失败可被检测。 权限:hard-guards 新增 protectedWrites,写入 Pi 凭据/设置、已安装 组合包与扩展目录、pi-ssh 凭据库时一律人工确认(跳过 AutoReview、 yolo 与 Session grant,无 UI 时拒绝);放行 ls、LSP 查询、ctx 只读、 web_search、Chrome 只读与 git 只读命令,skill_manage 改为 ask。 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent
a0ee9389c7
commit
2aa1be0b54
@@ -19,6 +19,7 @@ Permission enforcement extension for the [Pi](https://pi.mariozechner.at/) codin
|
||||
- **Uses one global ordinary policy file**; project `policy.jsonc` files are not loaded
|
||||
- **Chooses the most specific matching pattern**, so a specific deny wins over a broad `"*": "allow"` regardless of declaration order
|
||||
- **Applies a separate hard-guard policy first** so session grants, per-agent rules, and model review cannot override high-risk denies
|
||||
- **Keeps protected writes human-only**: files listed in `protectedWrites` (Pi credentials, settings, the installed bundle itself, …) always reach the local human prompt — never AutoReview, never yolo, never a session grant — and are denied when no confirmation UI exists. Reads are unaffected.
|
||||
- **Controls Bash, paths, MCP, skills, and tool surfaces** while leaving active-tool ownership entirely to Tool Search
|
||||
- **Reviews ordinary `ask` requests automatically** with integrated AutoReview; its `allow` verdict is final for ordinary tools and `path`, while `defer` reaches the next authorizer or human terminal
|
||||
- **Follows the session's current model**: AutoReview asks the model you are already chatting with to judge each ask, so the review always reflects the model the operator actually selected; set `autoReview.provider` and `autoReview.model` together to pin a different reviewer
|
||||
@@ -34,7 +35,7 @@ pi install npm:@gotgenes/pi-permission-system
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Create ordinary policy at `~/.pi/agent/my-pi/permission-system/policy.jsonc`:
|
||||
1. Ordinary policy lives in the installed bundle at `config/pi-permission-policy.jsonc` (the bundle repository's `config/` directory — edit it there for durable changes):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
@@ -51,7 +52,7 @@ pi install npm:@gotgenes/pi-permission-system
|
||||
}
|
||||
```
|
||||
|
||||
2. Create independent hard guards at `~/.pi/agent/my-pi/permission-system/hard-guards.jsonc`:
|
||||
2. Independent hard guards live beside it at `config/pi-permission-hard-guards.jsonc`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
@@ -62,7 +63,10 @@ pi install npm:@gotgenes/pi-permission-system
|
||||
"*.env.*": "deny",
|
||||
"*.env.example": "allow",
|
||||
"~/.ssh/**": "deny"
|
||||
}
|
||||
},
|
||||
"protectedWrites": [
|
||||
{ "pattern": "{agentDir}/auth.json", "label": "Pi credentials" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -86,12 +90,12 @@ The integrated extension uses two independent global JSONC files:
|
||||
|
||||
| Purpose | Scope | Path |
|
||||
| ------- | ----- | ---- |
|
||||
| Ordinary policy, runtime knobs, AutoReview | Global only | `~/.pi/agent/my-pi/permission-system/policy.jsonc` |
|
||||
| Non-overridable hard guards | Global only | `~/.pi/agent/my-pi/permission-system/hard-guards.jsonc` |
|
||||
| Ordinary policy, runtime knobs, AutoReview | Global only | `config/pi-permission-policy.jsonc` inside the installed bundle |
|
||||
| Non-overridable hard guards | Global only | `config/pi-permission-hard-guards.jsonc` inside the installed bundle |
|
||||
|
||||
Project-level `policy.jsonc` files are ignored. Project agent Markdown remains a separate per-agent restriction mechanism.
|
||||
|
||||
The bundle deploys both files with mode `0600` via `scripts/rebuild-bundle-config.mjs`: every `install.sh` / `update.sh` run rebuilds the whole `<agentDir>/my-pi/` tree, overwriting local edits without a backup — keep durable changes in the repository's `config/` sources. Files left at the former `extensions/pi-permission-system/` location are ignored.
|
||||
Both files are read directly from the bundle's `config/` directory — the single source of truth. Nothing is deployed to, seeded into, or migrated from the agent directory; `pi update` refreshes them with the bundle. Files left at the former `~/.pi/agent/my-pi/permission-system/` location are ignored.
|
||||
|
||||
Within a pattern map, the most specific match wins: exact patterns, then more literal characters, fewer wildcards, and longer patterns. Declaration order is only a tie-breaker.
|
||||
|
||||
@@ -99,7 +103,7 @@ There is no `external_directory` gate. Outside-CWD paths use the same configured
|
||||
|
||||
Tool Search alone owns Pi's active tool list. Permission System only decides whether an invoked tool call is allowed, denied, or requires confirmation.
|
||||
|
||||
See [docs/configuration.md](docs/configuration.md) for the complete reference and [docs/hard-guards.md](docs/hard-guards.md) for the independent hard-guard format.
|
||||
See [docs/configuration.md](docs/configuration.md) for the complete reference, including the [protected writes](docs/configuration.md#protected-writes) format in the hard-guard file.
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
// User-configurable, global-only hard boundary. Project policy, session
|
||||
// grants and AutoReview cannot override a matching deny.
|
||||
"version": 1,
|
||||
"permission": {
|
||||
"bash": {
|
||||
"rm -rf /": "deny",
|
||||
"rm -rf /*": "deny",
|
||||
"rm -rf ~": "deny",
|
||||
"rm -rf ~/*": "deny",
|
||||
"sudo rm -rf /": "deny",
|
||||
"sudo rm -rf /*": "deny",
|
||||
"mkfs*": "deny",
|
||||
"dd * of=/dev/*": "deny"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -517,6 +517,8 @@ The public authorizer registry remains available for other named authorities. Co
|
||||
|
||||
Authorizers are named capabilities registered on `permissions:ready`; the integrated `auto-review` authorizer uses the same chain contract as third-party links. Once configured, a link's `allow` or `deny` is final for any ordinary-policy `ask`, including `path`; `defer` advances to the next link or terminal.
|
||||
|
||||
One configured path bypasses the chain entirely: `protectedWrites` in the hard-guard file marks write targets as human-only. The protected-write gate produces its `ask` last in the tool-call pipeline (a hard deny still blocks first); the descriptor's `humanOnly` marker skips the runner's session-approval and yolo fast paths, and `AuthorizerSelection` composes it with zero links so no link — including `auto-review` — is consulted. A `LocalUserAuthorizer` terminal prompts without a "for this session" option; any other terminal (`DenyingAuthorizer`, a `ParentAuthorizer` relay) denies without prompting. Reads never reach the gate.
|
||||
|
||||
This is the principled successor to the per-command argument-position work deferred from [#509].
|
||||
The bash path projection surfaces a bare token that names a real file ([#645]) and deliberately accepts a fail-safe false positive (`grep id_rsa secrets.txt` prompts when an `id_rsa` file happens to exist); that false positive lives on the *ask-producing* side of `evaluate()`, and the model link dismisses it on the *ask-consuming* side without hard-coding per-command file-argument tables.
|
||||
This split is the layering principle of [ADR 0009](../decisions/0009-bash-path-projection-completeness-contract.md): the deterministic layer biases toward surfacing because over-suppression is unrecoverable, and the judge absorbs the surplus.
|
||||
@@ -578,7 +580,7 @@ src/
|
||||
├── index.ts Composition root and Pi event registration
|
||||
├── config-loader.ts Global ordinary policy loading
|
||||
├── policy-loader.ts Global policy + active-agent frontmatter gateway
|
||||
├── hard-guard-policy-loader.ts Independent global-only hard-guard loading
|
||||
├── hard-guard-loader.ts Independent global-only hard-guard + protectedWrites loading
|
||||
├── rule.ts Pattern matching and specificity ranking
|
||||
├── permission-manager.ts Unified intent evaluation
|
||||
├── access-intent/ Resolved intent types and resolver
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
|
||||
## Config File Locations
|
||||
|
||||
Pi Permission System reads two user-level JSONC files:
|
||||
Pi Permission System reads two JSONC files from the installed bundle's `config/` directory (the single source of truth; `pi update` refreshes them with the bundle):
|
||||
|
||||
| Purpose | Scope | Path |
|
||||
| ------- | ----- | ---- |
|
||||
| Ordinary policy + runtime | Global only | `~/.pi/agent/my-pi/permission-system/policy.jsonc` |
|
||||
| Hard guards | Global only | `~/.pi/agent/my-pi/permission-system/hard-guards.jsonc` |
|
||||
| Ordinary policy + runtime | Global only | `config/pi-permission-policy.jsonc` |
|
||||
| Hard guards | Global only | `config/pi-permission-hard-guards.jsonc` |
|
||||
|
||||
`PI_CODING_AGENT_DIR` replaces `~/.pi/agent` when set. Project-level `policy.jsonc` files are not loaded. Project agent Markdown may still provide per-agent restrictions; it is not a second ordinary policy file.
|
||||
Project-level `policy.jsonc` files are not loaded. Project agent Markdown may still provide per-agent restrictions; it is not a second ordinary policy file.
|
||||
|
||||
Hard guards are evaluated first. Their matching `deny` decisions cannot be overridden by ordinary policy, session approvals, per-agent rules, or AutoReview.
|
||||
Hard guards are evaluated first. Their matching `deny` decisions cannot be overridden by ordinary policy, session approvals, per-agent rules, or AutoReview. The same file's `protectedWrites` list marks files whose *writes* always reach a human prompt — see [Protected writes](#protected-writes).
|
||||
|
||||
Tool Search is the only extension that controls Pi's active tool list. Permission System never hides, activates, or replaces tools; it only evaluates a tool when Pi calls it.
|
||||
|
||||
@@ -37,6 +37,27 @@ This makes a broad `"*": "allow"` a fallback rather than an ordering trick. For
|
||||
|
||||
There is no separate `external_directory` decision. A path outside the current working directory is evaluated by the same configured tool, `path`, and Bash rules as any other path.
|
||||
|
||||
## Protected writes
|
||||
|
||||
`protectedWrites` in the hard-guard file lists files and subtrees whose **writes** must always be confirmed by a human:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"version": 1,
|
||||
"permission": { "bash": { "rm -rf /": "deny" } },
|
||||
"protectedWrites": [
|
||||
{ "pattern": "{agentDir}/auth.json", "label": "Pi credentials" },
|
||||
{ "pattern": "{configHome}/my-pi/**", "label": "pi-ssh credential store" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Each entry is `{ "pattern": string, "label": string }`. `pattern` uses the same wildcard syntax as the `path` surface (`*` crosses `/`, so a trailing `/**` covers the whole subtree) and is matched against both the lexical and canonical (symlink-resolved) forms of a write target. `{agentDir}` expands to the Pi agent directory (`PI_CODING_AGENT_DIR`), `{configHome}` to `$XDG_CONFIG_HOME` or `~/.config`, and a leading `~/` to the home directory. `label` is the name shown in the prompt and review log.
|
||||
|
||||
Counts as a write: a `write`/`edit` tool call's `input.path`, and a local `bash` command's redirect-out destinations and non-read-only program arguments — including a `bash -c`/`eval`-style opaque payload that textually contains a protected path, an unparseable command, and a relative write after `cd` into a protected directory. Reads of protected paths are unaffected: `cat` and friends are not writes, and neither is a redirect-in (`<`). Aliased shell tools (`shellTools`, e.g. `ssh_bash`) address remote filesystems and are never matched.
|
||||
|
||||
A protected write produces a human-only `ask`: it skips the session-approval and yolo fast paths, composes with zero `authorizerChain` links (AutoReview is never consulted), and the dialog offers no "for this session" option. With no local confirmation UI — a headless session or a subagent relay terminal — the write is denied without prompting. A malformed `protectedWrites` entry makes the whole hard-guard file invalid and follows its fail-closed semantics.
|
||||
|
||||
## Full Example
|
||||
|
||||
```jsonc
|
||||
@@ -244,6 +265,8 @@ Three invariants govern the chain:
|
||||
|
||||
A named authorizer may return a final `allow` or `deny` for any request that ordinary policy resolved to `ask`, including `path`. There is no additional surface-based delegation cap. `defer` advances to the next configured authorizer and ultimately the human terminal.
|
||||
|
||||
The one exception is a [protected write](#protected-writes): its `ask` is human-only and never reaches the chain — `authorizerChain` links are not consulted, and a terminal that is not the local user prompt denies without prompting.
|
||||
|
||||
Extension authors register a link from `permissions:ready` via `getPermissionsService().registerAuthorizer(name, authorize)`. For integration details, see [Cross-Extension API](cross-extension-api.md).
|
||||
|
||||
---
|
||||
|
||||
@@ -49,7 +49,7 @@ If your OpenCode config uses these features, the equivalent works in this extens
|
||||
| `mcp` surface | Not a documented permission surface | First-class with server/tool-level granularity |
|
||||
| Top-level string shorthand | `"permission": "allow"` sets all surfaces | Not supported; must use an object |
|
||||
| Per-agent config location | `agent` key in config JSON or YAML frontmatter | YAML frontmatter in agent `.md` files only |
|
||||
| Config file paths | `~/.config/opencode/opencode.json` | `~/.pi/agent/my-pi/permission-system/policy.jsonc` plus global `hard-guards.jsonc` |
|
||||
| Config file paths | `~/.config/opencode/opencode.json` | `config/pi-permission-policy.jsonc` plus `config/pi-permission-hard-guards.jsonc` inside the installed bundle |
|
||||
| Subagent prompt forwarding | Not documented | `ask` policies work in non-UI subagent contexts |
|
||||
| Infrastructure auto-allow | N/A | Read-only tools to Pi infra dirs bypass the gate |
|
||||
| Permission review log | No equivalent documented | Writes decisions to a JSONL audit log |
|
||||
|
||||
@@ -4,13 +4,15 @@
|
||||
|
||||
| Problem | Cause | Solution |
|
||||
| ----------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Config not applied (everything asks) | File not found or parse error | Verify the global policy at `~/.pi/agent/my-pi/permission-system/policy.jsonc` (respects `PI_CODING_AGENT_DIR`); check JSONC syntax |
|
||||
| Config not applied (everything asks) | File not found or parse error | Verify the global policy at `config/pi-permission-policy.jsonc` inside the installed bundle; check JSONC syntax |
|
||||
| Per-agent override not applied | Frontmatter parsing issue | Ensure `---` delimiters at file top; keep YAML simple; restart session |
|
||||
| Tool blocked as unregistered | Unknown tool name | Server tools arrive as `mcp__<server>__<tool>` under Pi's built-in MCP (check `/mcp`); a unified `mcp` proxy tool uses `{ "tool": "server:tool" }` |
|
||||
| `/skill:<name>` blocked | Deny policy or confirmation unavailable | Check merged `skill` policy (global/project/agent layers). `ask` still requires UI or forwarded confirmation. |
|
||||
| External file path blocked | `external_directory` is `ask` without UI or `deny` | Allow/ask the permission or keep file tools inside the active working directory. |
|
||||
| Spurious external-path prompt for `cd <subdir> && grep … ../path` | Relative path was resolved against cwd instead of the `cd` target | Fixed in current version — paths after a leading `cd <subdir> &&` are resolved against the cd target, matching actual shell behavior. |
|
||||
| Permission prompt is too verbose | Generic extension tool input is large | Built-in file tools are summarized automatically; third-party tools are capped to a bounded one-line JSON preview. |
|
||||
| A file write keeps prompting despite a session grant or yolo | The target is in `protectedWrites` | Working as designed — protected writes are human-only and never take a session grant. Remove the entry from `protectedWrites` in `config/pi-permission-hard-guards.jsonc` to lift it. |
|
||||
| A file write is denied without any prompt | `protectedWrites` target, no confirmation UI (headless or subagent relay) | Working as designed — a human-only ask cannot be answered without a local UI. Run the write from an interactive session instead. |
|
||||
|
||||
## Diagnostic Logging
|
||||
|
||||
@@ -22,17 +24,12 @@ This makes it easy to verify which files the extension actually loaded:
|
||||
```jsonc
|
||||
{
|
||||
"event": "config.resolved",
|
||||
"globalConfigPath": "/…/.pi/agent/my-pi/permission-system/policy.jsonc",
|
||||
"globalConfigPath": "/…/bundle/config/pi-permission-policy.jsonc",
|
||||
"globalConfigExists": true,
|
||||
"projectConfigPath": "/…/my-project/.pi/extensions/pi-permission-system/policy.jsonc",
|
||||
"projectConfigExists": false,
|
||||
"agentsDir": "/…/.pi/agent/agents",
|
||||
"agentsDirExists": true,
|
||||
"projectAgentsDir": "/…/my-project/.pi/agents",
|
||||
"projectAgentsDirExists": false,
|
||||
"legacyGlobalPolicyDetected": false,
|
||||
"legacyProjectPolicyDetected": false,
|
||||
"legacyExtensionConfigDetected": false
|
||||
"projectAgentsDirExists": false
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
"src",
|
||||
"dist",
|
||||
"config/config.example.json",
|
||||
"config/hard-guards.default.jsonc",
|
||||
"schemas/permissions.schema.json",
|
||||
"schemas/hard-guards.schema.json",
|
||||
"docs/*.md",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/siakitem/my-pi/main/pi-permission-system/schemas/hard-guards.schema.json",
|
||||
"title": "Pi Permission System Hard Guards",
|
||||
"description": "Global-only allow exceptions and non-overridable deny rules evaluated before ordinary policy, session grants, and AutoReview.",
|
||||
"description": "Global-only allow exceptions and non-overridable deny rules evaluated before ordinary policy, session grants, and AutoReview, plus protectedWrites whose writes always escalate to a human prompt.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"$schema": { "type": "string" },
|
||||
@@ -18,6 +18,19 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"protectedWrites": {
|
||||
"type": "array",
|
||||
"description": "Files and subtrees whose writes are human-only: every write goes to a local human prompt, skipping AutoReview, yolo, and session grants, and is denied when no UI is available. Patterns use the path surface wildcard syntax; {agentDir}, {configHome} and a leading ~/ are expanded at load.",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pattern": { "type": "string", "minLength": 1 },
|
||||
"label": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"required": ["pattern", "label"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["version", "permission"],
|
||||
|
||||
@@ -266,7 +266,7 @@
|
||||
"additionalProperties": false,
|
||||
"title": "PI Permission System Configuration",
|
||||
"description": "Ordinary JSONC policy combining runtime knobs, AutoReview settings, and flat permission rules for pi-permission-system.",
|
||||
"markdownDescription": "Global ordinary JSONC policy for [pi-permission-system](https://github.com/gotgenes/pi-packages/tree/main/packages/pi-permission-system).\n\nPlace at `~/.pi/agent/my-pi/permission-system/policy.jsonc`. Project-level policy files are not loaded. Global-only hard guards use the separate `hard-guards.jsonc` schema.",
|
||||
"markdownDescription": "Global ordinary JSONC policy for [pi-permission-system](https://github.com/gotgenes/pi-packages/tree/main/packages/pi-permission-system).\n\nRead directly from the installed bundle's `config/pi-permission-policy.jsonc`. Project-level policy files are not loaded. Global-only hard guards use the separate `config/pi-permission-hard-guards.jsonc` schema.",
|
||||
"$defs": {
|
||||
"permissionState": {
|
||||
"anyOf": [
|
||||
|
||||
@@ -9,9 +9,11 @@ import {
|
||||
classifyTokenAsRuleCandidate,
|
||||
} from "#src/access-intent/bash/token-classification";
|
||||
import {
|
||||
collectCommandTokens,
|
||||
collectPathCandidateTokens,
|
||||
collectRedirectTokens,
|
||||
type BashPathTokenRole,
|
||||
type CollectedPathToken,
|
||||
collectCommandTokensDetailed,
|
||||
collectPathCandidateTokensDetailed,
|
||||
collectRedirectTokensDetailed,
|
||||
extractCommandName,
|
||||
} from "#src/access-intent/bash/token-collection";
|
||||
import { normalizePathPolicyLiteral } from "#src/access-intent/path-normalization";
|
||||
@@ -40,6 +42,9 @@ type EffectiveBase =
|
||||
interface PathCandidate {
|
||||
readonly token: string;
|
||||
readonly base: EffectiveBase;
|
||||
readonly role: BashPathTokenRole;
|
||||
readonly program: string | null;
|
||||
readonly wrapped: boolean;
|
||||
}
|
||||
|
||||
// ── Public output types ──────────────────────────────────────────────────────
|
||||
@@ -49,13 +54,41 @@ export interface BashPathRuleCandidate {
|
||||
readonly token: string;
|
||||
/** The path's lexical and canonical forms for permission policy matching. */
|
||||
readonly path: AccessPath;
|
||||
/**
|
||||
* How the command uses the token — `redirect-out`/`redirect-in` for
|
||||
* redirect destinations, `argument` otherwise. Only the protected-write
|
||||
* gate reads this; the ordinary path gate is role-agnostic.
|
||||
*/
|
||||
readonly role: BashPathTokenRole;
|
||||
/** The enclosing command's program name, or `null` outside a command. */
|
||||
readonly program: string | null;
|
||||
/**
|
||||
* True inside a wrapper payload (`bash -c`, `eval`, `sudo`, `xargs`, …) or a
|
||||
* command/process substitution — the enclosing program cannot vouch for the
|
||||
* token's use.
|
||||
*/
|
||||
readonly wrapped: boolean;
|
||||
}
|
||||
|
||||
/** Cd-aware path-rule candidates extracted from a bash program. */
|
||||
export interface ResolvedBashPaths {
|
||||
readonly ruleCandidates: readonly BashPathRuleCandidate[];
|
||||
/**
|
||||
* The protected-write slice: every `ruleCandidates` entry plus every
|
||||
* `redirect-out` destination, which is admitted unconditionally — a redirect
|
||||
* target need not exist nor look like a path to still be written (`cd dir
|
||||
* && echo 1 > new.json`). Role metadata is what the gate classifies on.
|
||||
*/
|
||||
readonly writeCandidates: readonly BashPathRuleCandidate[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect targets that are really file-descriptor plumbing, not files:
|
||||
* `>&1`, `2>&-` and friends write to a descriptor, so they never enter the
|
||||
* write slice.
|
||||
*/
|
||||
const FD_DUPLICATE_TARGET = /^&?[\d-]+$/;
|
||||
|
||||
// ── Walk-time constants ──────────────────────────────────────────────────────
|
||||
|
||||
/** The working directory in force at the start of a program (`cwd`). */
|
||||
@@ -101,9 +134,7 @@ export class BashPathResolver {
|
||||
? CWD_BASE
|
||||
: this.deriveBaseFromCdTarget(CWD_BASE, this.workdir);
|
||||
const candidates = this.collectPathCandidates(rootNode, initialBase);
|
||||
return {
|
||||
ruleCandidates: this.projectRuleCandidates(candidates),
|
||||
};
|
||||
return this.projectCandidates(candidates);
|
||||
}
|
||||
|
||||
// ── AST walk — collect PathCandidates ──────────────────────────────────
|
||||
@@ -145,7 +176,7 @@ export class BashPathResolver {
|
||||
case "redirected_statement":
|
||||
return this.walkCurrentShellSequence(node, base, out);
|
||||
case "command":
|
||||
tagTokens(collectCommandTokens(node), base, out);
|
||||
tagTokens(collectCommandTokensDetailed(node), base, out);
|
||||
return this.foldCd(node, base);
|
||||
case "pipeline":
|
||||
// tree-sitter-bash mis-groups a redirect-bearing `&&`/`;` list as the
|
||||
@@ -170,7 +201,7 @@ export class BashPathResolver {
|
||||
// substitution interiors: collect every candidate in the subtree tagged
|
||||
// with the enclosing base and do not fold their internal `cd`s. (Folding
|
||||
// inside substitutions is deferred — conservative, never under-flags.)
|
||||
tagTokens(collectPathCandidateTokens(node), base, out);
|
||||
tagTokens(collectPathCandidateTokensDetailed(node), base, out);
|
||||
return base;
|
||||
}
|
||||
}
|
||||
@@ -230,7 +261,7 @@ export class BashPathResolver {
|
||||
}
|
||||
// Downstream stage (after a `|`): subshell — collect against the folded
|
||||
// base, do not fold.
|
||||
tagTokens(collectPathCandidateTokens(child), current, out);
|
||||
tagTokens(collectPathCandidateTokensDetailed(child), current, out);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
@@ -260,7 +291,7 @@ export class BashPathResolver {
|
||||
if (child.type === "file_redirect") {
|
||||
// Redirect destinations are part of the piped stage; collect them
|
||||
// against the folded base without folding.
|
||||
tagTokens(collectRedirectTokens(child), current, out);
|
||||
tagTokens(collectRedirectTokensDetailed(child), current, out);
|
||||
continue;
|
||||
}
|
||||
// The inner statement is the `list`/`command` being redirected; fold its
|
||||
@@ -270,7 +301,7 @@ export class BashPathResolver {
|
||||
return current;
|
||||
}
|
||||
// Bare `command` or any other shape: a true subshell first stage.
|
||||
tagTokens(collectPathCandidateTokens(node), base, out);
|
||||
tagTokens(collectPathCandidateTokensDetailed(node), base, out);
|
||||
return base;
|
||||
}
|
||||
|
||||
@@ -298,7 +329,7 @@ export class BashPathResolver {
|
||||
current = this.walkForCandidates(child, current, out);
|
||||
} else {
|
||||
// Terminal child = the real pipe stage; collect without folding.
|
||||
tagTokens(collectPathCandidateTokens(child), current, out);
|
||||
tagTokens(collectPathCandidateTokensDetailed(child), current, out);
|
||||
}
|
||||
}
|
||||
return current;
|
||||
@@ -363,34 +394,67 @@ export class BashPathResolver {
|
||||
/**
|
||||
* Project candidates into policy lookup values while preserving literal
|
||||
* values after a non-literal `cd`, where no reliable absolute base exists.
|
||||
*
|
||||
* `ruleCandidates` keeps the long-standing admission rule — path-shaped
|
||||
* tokens plus bare tokens an existence probe confirms. `writeCandidates`
|
||||
* additionally admits every `redirect-out` destination: a redirect writes
|
||||
* its target whether or not the file exists yet, so existence and shape
|
||||
* cannot gate it. The write slice is deduplicated per role so the same
|
||||
* path appearing as both a read argument and a write destination keeps
|
||||
* both classifications.
|
||||
*/
|
||||
private projectRuleCandidates(
|
||||
private projectCandidates(
|
||||
candidates: readonly PathCandidate[],
|
||||
): BashPathRuleCandidate[] {
|
||||
const seen = new Set<string>();
|
||||
const result: BashPathRuleCandidate[] = [];
|
||||
): ResolvedBashPaths {
|
||||
const seenRules = new Set<string>();
|
||||
const seenWrites = new Set<string>();
|
||||
const ruleCandidates: BashPathRuleCandidate[] = [];
|
||||
const writeCandidates: BashPathRuleCandidate[] = [];
|
||||
|
||||
for (const { token, base } of candidates) {
|
||||
const pushWrite = (
|
||||
candidate: BashPathRuleCandidate,
|
||||
matchValues: readonly string[],
|
||||
): void => {
|
||||
const key = `${candidate.role} | ||||