@agent-corpus/policy-manager 0.6.0 → 0.8.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/README.md +28 -5
- package/dist/adapters.d.ts +11 -0
- package/dist/adapters.js +77 -6
- package/dist/cli.js +58 -3
- package/dist/evidence.js +1 -1
- package/dist/flow.js +37 -3
- package/dist/grants.d.ts +18 -0
- package/dist/grants.js +131 -0
- package/dist/permissive.js +406 -18
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +1 -1
- package/dist/service.d.ts +7 -2
- package/dist/service.js +17 -5
- package/dist/session.d.ts +56 -1
- package/dist/session.js +189 -4
- package/dist/types.d.ts +4 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -91,8 +91,9 @@ Under a `permissive` profile, a person is asked only for what code says must sta
|
|
|
91
91
|
How a hook call flows (Claude Code, Codex and Copilot `PreToolUse`):
|
|
92
92
|
|
|
93
93
|
1. **First call.** The command is _not run_ and the person is not asked. The hook blocks it with a reason that tells the model to ask the session's policy-manager agent whether the exact command is recoverable and non-sensitive, to record the answer with `policy-manager classify`, and to retry the same command. The reason starts with `Needs classification (not an error)` and states the rule the classifier applies (`HUMAN_REVIEW_PRINCIPLE`). A person is needed only for unrecoverable loss, credential or secret retrieval, protected configuration or paths, and `humanPatterns`. A recoverable outward-facing write such as an issue comment is approvable, and so is a destructive-but-safe deletion inside a feature worktree. The request hash covers only effect-relevant input, so a retry with a different Bash `description` reuses the classification.
|
|
94
|
-
2. **
|
|
95
|
-
3. **
|
|
94
|
+
2. **Recorded.** The session approves the record command in that reason deterministically, in every profile: exactly `node "<this package's dist/cli.js>" classify <harness> <session-id> <<< '<json>'` for the current harness and session, with one single-quoted JSON object and nothing else in the command. Any other direct invocation of a classification record goes to a person: `node … cli.js classify` or `policy-manager classify`, at the start of a command or after an operator, including behind assignments, wrappers such as `env`, `exec` or `xargs`, or keywords such as `then`. That covers another session, harness or CLI path, and anything added before or after. A command that only mentions one, such as a `grep` pattern, gets the normal decision, and so does a record nested in a quoted script (`sh -c '…'`).
|
|
95
|
+
3. **Classified.** `classify` takes `{requestHash, category, confidence, recoverable, rationale}`. The request is approved only when `recoverable` is `true`, `confidence` is at least 0.95, and the category is not `sensitive` or `unknown`. A `destructive` label approves only a deletion the engine itself identified inside a linked feature worktree, on the same terms. Any other request the AI labels `destructive` (an unparsable `rm -rf ~/{a,b}`, for example), and any such deletion not judged recoverable, goes to a **person** (under Codex, a deny), since it may lose data for good. No other deterministic `destructive` escalation is classified. Anything else is a **deny with a reason** the model sees and works around. The outcome is remembered for five minutes for that exact request, and a verdict is final in that time: a deny cannot be reclassified into an approve.
|
|
96
|
+
4. **Fallback.** If the classifier is unavailable or its answer is invalid, the retry reaches a person through the normal prompt (under Codex, which cannot ask, it is a deny that gives the `approve` command the user runs; see **Approving from the terminal**). This happens at most once per request, so there is never a loop and never a lost prompt. After 50 AI approvals in a session, further ambiguous requests go to a person.
|
|
96
97
|
|
|
97
98
|
**What always stays with a person, in code, and is never AI-relaxable** (these are the owner's calls; they list exactly what this experiment does not change):
|
|
98
99
|
|
|
@@ -113,6 +114,21 @@ policy-manager review-classifications [--since 2026-11-12T00:00:00Z] [--json]
|
|
|
113
114
|
|
|
114
115
|
The report shows how many ambiguous requests were approved, denied, fell back to a person (and why), and never resolved; a confidence histogram; every AI-approved command with its outcome; approved commands that then failed; and commands a person later denied. It reads the session logs under the temporary directory, which the operating system clears after a few days, so run it within two days of starting. `replay` prints how many escalations in recorded transcripts would go to the classifier instead of a person.
|
|
115
116
|
|
|
117
|
+
## Approving from the terminal
|
|
118
|
+
|
|
119
|
+
Codex cannot ask in `PreToolUse`, so a request that needs a person is denied, and approving it in chat does not change the decision. The deny reason gives the command the user runs in their own terminal:
|
|
120
|
+
|
|
121
|
+
```sh
|
|
122
|
+
policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session]
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
It shows the tool, the redacted request and the rule, and asks for confirmation; it refuses to run without an interactive terminal. The request must be one this session sent to a person in the last 15 minutes. Then the agent retries the same request unchanged.
|
|
126
|
+
|
|
127
|
+
- **Once (default).** The next review of that exact request is approved, once per hook phase (`PreToolUse`, then `PermissionRequest`), and the grant is spent.
|
|
128
|
+
- **`--session`.** Also approves later requests in this session that hit the same rule for the same scope: a protected-path write under the same protected root of the same checkout (`<worktree>/.agent-config`, not `.claude` or another worktree), the same `humanPatterns` entries in the same checkout, or, for other rules, the exact same command in the same checkout. `approve --session` prints the scope before asking. Shell commands are covered only when they are a single simple command, so nothing else in a script hides behind the rule. Credential and secret reads, possible unrecoverable loss (force pushes, deleting unmerged work) and requests whose effect the engine could not determine (category `unknown`, such as an interpreter script) are approved once only, even with `--session`; the deny reason offers `--session` only when it applies.
|
|
129
|
+
|
|
130
|
+
Each grant is audited as `human-grant` (and `human-response` `approved`), and each use as `human-grant-use` with its scope. A shell command that runs or names a policy-manager `approve`, at any nesting (`sh -c`, `npx`, wrappers), always goes to a person, so an agent that follows the deny reason cannot approve its own request. The guard is lexical and the service trusts any holder of the session token, so it is not a boundary against an agent that deliberately works around it. Grants live in the session's policy service; if it restarts (it exits after 30 idle minutes), retry the request and approve the new hash. Claude Code and Copilot ask natively and do not need this, though it works for them too.
|
|
131
|
+
|
|
116
132
|
## Policy
|
|
117
133
|
|
|
118
134
|
- Ordinary file reads must resolve inside a Git repository.
|
|
@@ -155,7 +171,11 @@ Deleting disposable files is approved too (`Delete within a scratch directory`):
|
|
|
155
171
|
|
|
156
172
|
A path is resolved when the hook runs, before the script does, so a symlink that an earlier command in the same script creates is invisible to it. Temp writes and scratch deletions are therefore approved only until the script runs a command that is not known to create no symlink. The known commands print, read, or write regular files: `echo`, `cat`, `sort`, `grep`, `sed`, `tee`, `touch`, `mkdir`, `rm`, `cp` without options that copy links, read-only `git` subcommands and `git init`, and a few others. A shell's `-c` script is judged with the same state. After anything else (`cp -R`, `mv`, `ln`, `tar`, `xargs`, an interpreter, an unknown program) a later temp write or scratch deletion goes to a person. In a loop, a pipeline or a background job a later command can run first, so such a command there after an approved temp path also goes to a person. Writes inside linked feature worktrees are not affected.
|
|
157
173
|
|
|
158
|
-
Credential-path checks skip words that are text, not paths: a `sed` script (but not the files its `r`, `w` or `e` commands name, nor `-f`), a `grep` or `rg` pattern,
|
|
174
|
+
Every other argument is a possible file operand and is checked for credentials: by name (`id_rsa`, `credentials`, `secrets.json`, `.env`, `*.pem`, `*.key`, also bare, as in `cat id_rsa` from `~/.ssh`), and, when it exists, by its path resolved against the tracked working directory, so a symlink to a key or any file in a `.ssh` directory counts. A glob (`cat *`, `cat id_*`, `cat .*/*`) is expanded one component at a time against the directories it names; more than 5000 entries in total, an entry that cannot be read or resolved, or a zsh recursive `**`/`***` component counts as sensitive. `*` is assumed not to match dot files, so a shell with zsh `GLOB_DOTS` or bash `dotglob` set can reach dot files a plain `*` check misses. File-name pattern values (`grep --include`, `rg -g`, `find -name`/`-path`) are matched below the searched paths, so they are judged by name only. Credential-path checks skip words that are text, not paths: a `sed` script (but not the files its `r`, `w` or `e` commands name, nor `-f`), a `grep` or `rg` pattern, `gh` `--body`, `--title`, `--jq`, `--template` and `--notes` values, and `echo`/`printf` arguments, which are judged by name only when they look like a path. Other programs keep the conservative check.
|
|
175
|
+
|
|
176
|
+
`cp` and `ln` sources are reads, so copying or linking out of a main checkout into the temp directory is a temp write; only the destination (the last operand, `-t` or `--target-directory`, or the base name of a lone `ln` operand in the working directory) is checked as a write. With a backup suffix (`-b`, `-S`, `--backup`, `--suffix`) or a hard link (`ln` without `-s`, `cp -l`/`--link`) every operand is checked as a write, since a later write through a hard link changes its source; a hard-linked file is never a scratch or temp write. `chmod`'s mode and `chown`'s owner are not paths, except that BSD `chmod -N`/`-E`/`-C`/`-i`/`-I` take no mode, so every operand is a file.
|
|
177
|
+
|
|
178
|
+
`grep --include=*.md`, `--exclude`, `--exclude-dir` and `rg -g`/`--glob`/`--iglob` with an unquoted glob value are approved: the option name is literal, so expansion only yields more of the same option. A glob in any other option or in the command name still needs a human.
|
|
159
179
|
|
|
160
180
|
#### Shell syntax in permissive mode
|
|
161
181
|
|
|
@@ -171,6 +191,7 @@ Every command that could run is judged, not only the first. Understood: `;`, new
|
|
|
171
191
|
- **`while read`.** When the loop reads a literal here-string or quoted heredoc, the body is judged once per line with the fields `read` assigns. This applies only when nothing in the body can read the loop's standard input (only `echo`, `printf`, `test`, `ls`, read-only `gh pr`/`issue`/`run` views and similar, or commands with their own input), since a body that consumes part of a line changes what the next `read` sees.
|
|
172
192
|
- **Computed substitutions.** `$(dirname x)`, `$(basename x [suffix])` and `$(pwd)` with known arguments (and a single possible directory for `pwd`) are replaced by their output. Any other substitution output stays unknown: no read-only command is safe for an arbitrary argument here, since `ls`, `cat` and `find` reveal credential files, and options such as `wc --files0-from`, `gh --jq '$ENV...'` and `git log --output` read files or the environment or write files.
|
|
173
193
|
- **Variables after a `cd` chain.** `cd /abs/dir && X=1; use $X` treats `X` as assigned when the `cd` is the script's first command and the directory exists and can be entered at evaluation time. An earlier command could remove it, so a later `cd` is still assumed able to fail. Another process changing the directory before the script runs is the remaining window. This affects variables only: `use` is still judged in the starting directory too.
|
|
194
|
+
- **Variables after an assignment chain.** `S=/abs && H=x; use $S $H` treats `H` as assigned: a bare assignment with no command substitution and no redirection cannot fail, so the `&&` chain always reaches `H=x`. This holds only for uppercase names the shell does not reserve. zsh's lowercase specials, read-only or numeric specials (`UID`, `SECONDS`, `BASH*`, `ZSH*`, ...), a value with `$(...)`, `export NAME=value` and a prefix assignment (`X=1 cmd`) can fail or do not persist, so the chain may stop there and a later name is still an environment variable. A value used as the program (`P=rm; $P -rf x`) is resolved and judged as that program. The remaining window is a `readonly` or `typeset -i` that the user's shell startup files set on a name outside that list (such as `HISTFILE`): bash 5 in default mode may then return 1 without exiting, so the chain could stop there. That is outside what the script controls and is accepted.
|
|
174
195
|
- **Still sent to a human:** brace expansion (`{a,b}`, `{1..3}`; `{}` and `@{u}` are literal), arithmetic (`$((`, `$[`, `(( ))`), arrays, other parameter forms (`${X:=y}`, `${!X}`, `${X/a/b}`), `function name` definitions, unquoted heredocs whose body expands, and scripts that expand to more than a few hundred commands. `cloudWrites: "allow"` also approves non-destructive cloud changes.
|
|
175
196
|
|
|
176
197
|
#### MCP read-only tools
|
|
@@ -189,7 +210,9 @@ A listed tool is approved. Any other MCP tool gets no decision from the policy m
|
|
|
189
210
|
|
|
190
211
|
Measure a profile against real usage with `policy-manager replay ~/.claude/projects --profile policy.json`: it replays the Bash commands recorded in Claude Code transcripts through the evaluator (nothing is executed) and prints the approval rate with and without the profile, plus the most common reasons that still need a human. Reports include short command excerpts, so keep them local.
|
|
191
212
|
|
|
192
|
-
Protected names (`.claude`, `.agent-config`, `AGENTS.md`, ...) are judged relative to the repository root, so a linked worktree under `<repo>/.claude/worktrees/<name>` is ordinary code while `<worktree>/.claude/settings.json` stays protected. `git config` is limited to a short allowlist of local, non-executable keys; hooks, aliases, credential helpers, URLs and `--global` always need a human. Read-only cloud verbs (`list`, `show`, `describe`, `get-*`) are approved beyond the exact catalog unless the arguments name credentials or override the endpoint.
|
|
213
|
+
Protected names (`.claude`, `.agent-config`, `AGENTS.md`, ...) are judged relative to the repository root, so a linked worktree under `<repo>/.claude/worktrees/<name>` is ordinary code while `<worktree>/.claude/settings.json` stays protected. `git config` is limited to a short allowlist of local, non-executable keys; hooks, aliases, credential helpers, URLs and `--global` always need a human. Read-only cloud verbs (`list`, `show`, `describe`, `get-*`) and `az boards query` (a WIQL read) are approved beyond the exact catalog unless the arguments name credentials or override the endpoint.
|
|
214
|
+
|
|
215
|
+
`git worktree remove --force <path>` is approved when `<path>` is a linked worktree of the repository (listed by `git worktree list`, never the main worktree), resolves strictly inside a `scratchRoots` entry or the system temp directory, lies outside the main checkout, and holds no other worktree; exactly one `-f`/`--force` may be given (a second one also removes a locked worktree), and not after a command that can create symlinks. A worktree under the main checkout (`.worktrees/x`) still needs a human. `git worktree prune` with only `-n`/`-v` is approved: it drops records of worktrees whose directories are already gone.
|
|
193
216
|
|
|
194
217
|
#### Recoverable deletions and resets
|
|
195
218
|
|
|
@@ -214,7 +237,7 @@ The cache belongs to the service process and is scoped to harness plus session I
|
|
|
214
237
|
|
|
215
238
|
`SessionStart` reports the private temporary directory containing `audit.jsonl`. Each request and decision is recorded before an approval is returned. The log stores versioned event envelopes, readable action summaries, opaque session identifiers, request hashes, and hashed targets. It excludes paths, argument values, source text, credentials, and model explanations. Compare request hashes against the original request in the harness transcript during an investigation. Logs rotate at 10 MiB per segment and stop accepting writes at 100 MiB total. Earlier segments remain available through `audit-log query` and `audit-log export`; no records are automatically deleted. Logs remain after normal shutdown and can disappear during operating-system cleanup. Copy them before cleanup when needed.
|
|
216
239
|
|
|
217
|
-
Logging failure, malformed requests, service failure, and unknown semantics never produce an automatic approval. Permission hooks fall through to native human handling. Pre-tool failures exit 2. Host timeout behavior differs: Copilot command-hook timeouts fall through to its normal permission flow. Codex does not support `ask` in `PreToolUse`: it parses the value, marks the hook failed and runs the tool anyway. A decision that needs a human is therefore returned to Codex as a `deny` whose reason says the command was not run and that approving it in chat does not unblock it (the decision is deterministic, so a retry is denied again); there is no in-Codex button to approve it. The
|
|
240
|
+
Logging failure, malformed requests, service failure, and unknown semantics never produce an automatic approval. Permission hooks fall through to native human handling. Pre-tool failures exit 2. Host timeout behavior differs: Copilot command-hook timeouts fall through to its normal permission flow. Codex does not support `ask` in `PreToolUse`: it parses the value, marks the hook failed and runs the tool anyway. A decision that needs a human is therefore returned to Codex as a `deny` whose reason says the command was not run and that approving it in chat does not unblock it (the decision is deterministic, so a retry is denied again); there is no in-Codex button to approve it. The reason gives the `approve` command the user runs in their own terminal (see **Approving from the terminal**). An ambiguous request is the other way through: its reason points to the session policy-manager agent, and a classification of approved is accepted for the session, so a retry passes. Codex also rejects `PreToolUse` `permissionDecision: "allow"` without `updatedInput` ("PreToolUse hook returned unsupported permissionDecision:allow", checked against Codex CLI 0.167.2), so an approval there is no decision: empty output and exit 0. If Codex would still prompt, its `PermissionRequest` hook returns `{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}`, which suppresses the prompt; a request that needs a human gets no output there and Codex's own prompt.
|
|
218
241
|
|
|
219
242
|
## Audit API and reported outcomes
|
|
220
243
|
|
package/dist/adapters.d.ts
CHANGED
|
@@ -10,6 +10,17 @@ export interface HookContext {
|
|
|
10
10
|
* round trip could never finish. A test evaluates this exact string and requires `approve`.
|
|
11
11
|
*/
|
|
12
12
|
export declare function classifyCommand(harness: Request["harness"], context?: HookContext, json?: string): string;
|
|
13
|
+
/**
|
|
14
|
+
* Whether `command` is exactly this session's record command from `classifyCommand`, answer
|
|
15
|
+
* included: one single-quoted literal JSON object, nothing before or after it. Inside single
|
|
16
|
+
* quotes the shell expands nothing, so the answer cannot run anything.
|
|
17
|
+
*/
|
|
18
|
+
export declare function isClassifyRecord(command: string, harness: Request["harness"], context: HookContext): boolean;
|
|
19
|
+
/** A command that runs a policy-manager classification record, for any session or CLI. */
|
|
20
|
+
export declare function looksLikeClassifyRecord(command: string): boolean;
|
|
21
|
+
export declare function looksLikeApproveGrant(command: string): boolean;
|
|
22
|
+
/** The command the user runs in their own terminal to approve a human decision. */
|
|
23
|
+
export declare function approveCommand(harness: Request["harness"], requestHash: string, context?: HookContext): string;
|
|
13
24
|
export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): Record<string, unknown>;
|
|
14
25
|
/** The exact stdout of a PreToolUse or PermissionRequest hook. Codex gets no output for no decision. */
|
|
15
26
|
export declare function hookOutput(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): string;
|
package/dist/adapters.js
CHANGED
|
@@ -37,6 +37,75 @@ export function classifyCommand(harness, context, json = "<json>") {
|
|
|
37
37
|
? `node "${cliPath}" classify ${harness} ${context.sessionId} <<< '${json}'`
|
|
38
38
|
: `policy-manager classify ${harness} <session-id> <<< '${json}'`;
|
|
39
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Whether `command` is exactly this session's record command from `classifyCommand`, answer
|
|
42
|
+
* included: one single-quoted literal JSON object, nothing before or after it. Inside single
|
|
43
|
+
* quotes the shell expands nothing, so the answer cannot run anything.
|
|
44
|
+
*/
|
|
45
|
+
export function isClassifyRecord(command, harness, context) {
|
|
46
|
+
const template = classifyCommand(harness, context, "");
|
|
47
|
+
if (!template.startsWith('node "'))
|
|
48
|
+
return false;
|
|
49
|
+
const head = template.slice(0, -1);
|
|
50
|
+
if (command.length > head.length + 4096 || !command.startsWith(head) || !command.endsWith("'"))
|
|
51
|
+
return false;
|
|
52
|
+
const json = command.slice(head.length, -1);
|
|
53
|
+
if (/['\0\r\n]/.test(json))
|
|
54
|
+
return false;
|
|
55
|
+
try {
|
|
56
|
+
const value = JSON.parse(json);
|
|
57
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const WORD = String.raw `(?:"[^"]*"|'[^']*'|[^\s;&|]+)`;
|
|
64
|
+
const CLI = String.raw `(?:"[^"]*cli\.js"|'[^']*cli\.js'|[^\s"';&|]*cli\.js)`;
|
|
65
|
+
const NODE = String.raw `(?:"(?:[^"]*[/\\])?node(?:\.exe)?"|'(?:[^']*[/\\])?node(?:\.exe)?'|(?:[^\s"';&|]*[/\\])?node(?:\.exe)?)`;
|
|
66
|
+
/** Assignments, wrappers and keywords that can stand before the command in a segment. */
|
|
67
|
+
const LEAD = String.raw `(?:[A-Za-z_]\w*=${WORD}?\s+|(?:then|do|else|elif|if|while|until|!)\s+|(?:env|command|builtin|exec|time|timeout|nohup|nice|ionice|xargs|stdbuf|sudo|doas)(?:\s+${WORD}){0,6}?\s+)*`;
|
|
68
|
+
/**
|
|
69
|
+
* A command segment that runs a policy-manager CLI's `classify`, for any session or CLI: `node`
|
|
70
|
+
* with a `cli.js`, or `policy-manager` (also through `npx`), at the start of the script or after
|
|
71
|
+
* an operator, behind any assignments, wrappers (`env`, `exec`, `xargs`...) or keywords. Text
|
|
72
|
+
* that only mentions such a command (a `grep` pattern, a commit message) does not match, and
|
|
73
|
+
* neither does a script nested in quotes (`sh -c '...'`), which gets the normal decision.
|
|
74
|
+
*/
|
|
75
|
+
const CLASSIFY_INVOCATION = new RegExp(String.raw `(?:^|[;&|({` +
|
|
76
|
+
"`" +
|
|
77
|
+
String.raw `\n]|\$\()\s*${LEAD}(?:${NODE}\s+(?:-${WORD}\s+)*${CLI}|(?:npx\s+(?:-\S+\s+)*)?(?:@agent-corpus\/)?policy-manager(?:@\S+)?)\s+["']?classify\b`);
|
|
78
|
+
/** A command that runs a policy-manager classification record, for any session or CLI. */
|
|
79
|
+
export function looksLikeClassifyRecord(command) {
|
|
80
|
+
return CLASSIFY_INVOCATION.test(command);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* A command that runs, or names, a policy-manager `approve`, anywhere in the script and at any
|
|
84
|
+
* nesting (`sh -c '...'`, a here-document). Unlike a classification record, the agent never runs
|
|
85
|
+
* this: only the user approves, from their own terminal.
|
|
86
|
+
*/
|
|
87
|
+
const APPROVE_PROGRAM = /^(?:.*cli\.js|(?:@agent-corpus\/)?policy-manager(?:@.*)?)$/;
|
|
88
|
+
// A token scan rather than one regular expression over the command, so its cost stays linear.
|
|
89
|
+
export function looksLikeApproveGrant(command) {
|
|
90
|
+
const tokens = command.split(/[\s"'`;&|()]+/);
|
|
91
|
+
return tokens.some((token, i) => tokens[i + 1] === "approve" && APPROVE_PROGRAM.test(token));
|
|
92
|
+
}
|
|
93
|
+
/** The command the user runs in their own terminal to approve a human decision. */
|
|
94
|
+
export function approveCommand(harness, requestHash, context) {
|
|
95
|
+
const cliPath = context && /^[A-Za-z]:\\/.test(context.cliPath)
|
|
96
|
+
? context.cliPath.replace(/\\/g, "/")
|
|
97
|
+
: context?.cliPath;
|
|
98
|
+
return cliPath && context
|
|
99
|
+
? `node "${cliPath}" approve ${harness} ${context.sessionId} ${requestHash}`
|
|
100
|
+
: `policy-manager approve ${harness} <session-id> ${requestHash}`;
|
|
101
|
+
}
|
|
102
|
+
function approveInstruction(harness, decision, context) {
|
|
103
|
+
const command = approveCommand(harness, decision.requestHash, context);
|
|
104
|
+
const session = decision.sessionGrantable
|
|
105
|
+
? " Adding --session also allows later requests in this session that hit the same rule for the same scope."
|
|
106
|
+
: "";
|
|
107
|
+
return `Approving it in chat does not unblock it. To allow it once, the user runs in their own terminal: ${command} — then retry the same request unchanged.${session} Do not run that command yourself.`;
|
|
108
|
+
}
|
|
40
109
|
/** What a blocked ambiguous request tells the model to do. Never ask for human approval here. */
|
|
41
110
|
function classifyInstruction(harness, decision, context) {
|
|
42
111
|
const command = classifyCommand(harness, context);
|
|
@@ -88,14 +157,16 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
88
157
|
: { hookSpecificOutput: { hookEventName: phase, permissionDecision: "allow" } };
|
|
89
158
|
// Codex parses permissionDecision "ask" but does not support it: it marks the hook failed and
|
|
90
159
|
// runs the tool anyway (https://developers.openai.com/codex/hooks). Only "deny" stops a command,
|
|
91
|
-
// so a decision that needs a human is a deny. Approving it in chat does not change the decision
|
|
92
|
-
//
|
|
93
|
-
// request (needsClassification),
|
|
94
|
-
// (PermissionRequest, above) still handles the requests it
|
|
160
|
+
// so a decision that needs a human is a deny. Approving it in chat does not change the decision;
|
|
161
|
+
// the user approves it from their own terminal (`approve`, once or for the session), or an
|
|
162
|
+
// ambiguous request (needsClassification) is classified, and a retry then sees the approval.
|
|
163
|
+
// Codex's own approval prompt (PermissionRequest, above) still handles the requests it asks about.
|
|
95
164
|
if (harness === "codex") {
|
|
96
165
|
const next = decision.needsClassification === true && decision.classification !== "fallback"
|
|
97
|
-
? "Classify it with the session policy-manager agent and retry. If it is not classified as approved,
|
|
98
|
-
:
|
|
166
|
+
? "Classify it with the session policy-manager agent and retry. If it is not classified as approved, the retry is blocked with the command the user runs to approve it."
|
|
167
|
+
: decision.userOnly
|
|
168
|
+
? "Do not run approve yourself: ask the user to approve the original request from their own terminal."
|
|
169
|
+
: approveInstruction(harness, decision, context);
|
|
99
170
|
return {
|
|
100
171
|
hookSpecificOutput: {
|
|
101
172
|
hookEventName: phase,
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
4
5
|
import { fileURLToPath } from "node:url";
|
|
5
6
|
import { parseArgs } from "node:util";
|
|
6
7
|
import { executionReport, hookOutput, normalize } from "./adapters.js";
|
|
8
|
+
import { sessionDirectoryPath } from "./audit.js";
|
|
7
9
|
import { hookConfig } from "./config.js";
|
|
8
10
|
import { HUMAN_REVIEW_PRINCIPLE } from "./principle.js";
|
|
9
11
|
import { defaultProfilePath, loadProfile, parseProfile } from "./profile.js";
|
|
@@ -16,6 +18,7 @@ policy-manager hook <claude|codex|copilot> <SessionStart|PreToolUse|PermissionRe
|
|
|
16
18
|
policy-manager review <claude|codex|copilot> <session-id> # normalized request JSON on stdin
|
|
17
19
|
policy-manager classify <claude|codex|copilot> <session-id> # {requestHash,category,confidence} on stdin
|
|
18
20
|
policy-manager record <claude|codex|copilot> <session-id> # host-reported human response or execution result JSON
|
|
21
|
+
policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session] # the user, in their own terminal: allow a blocked request once, or its rule and scope for the session
|
|
19
22
|
policy-manager setup-hook <claude|codex|copilot> [--dry-run] [--config-dir <harness-config-directory>]
|
|
20
23
|
policy-manager setup-hook-claude|setup-hook-codex|setup-hook-copilot [--dry-run] [--config-dir <directory>]
|
|
21
24
|
policy-manager config <claude|codex|copilot> <absolute-installed-cli-path>
|
|
@@ -28,6 +31,9 @@ A per-session background service checks policy and writes private temporary audi
|
|
|
28
31
|
AI classification comes from the session's policy-manager agent, never an external API.
|
|
29
32
|
Unknown effects require human approval. Exit 0: protocol response; exit 1: malformed input or service failure.
|
|
30
33
|
`;
|
|
34
|
+
/** An `approve` failure whose message is meant for the user. */
|
|
35
|
+
class ApproveError extends Error {
|
|
36
|
+
}
|
|
31
37
|
async function stdin() {
|
|
32
38
|
let text = "";
|
|
33
39
|
for await (const chunk of process.stdin) {
|
|
@@ -114,8 +120,49 @@ try {
|
|
|
114
120
|
const review = await reviewClassifications(sessionDirectories(values.dir ?? []), values.since);
|
|
115
121
|
console.log(values.json ? JSON.stringify(review, null, 2) : formatReview(review));
|
|
116
122
|
}
|
|
123
|
+
else if (action === "approve") {
|
|
124
|
+
const { values, positionals } = parseArgs({
|
|
125
|
+
args: args.slice(1),
|
|
126
|
+
options: { session: { type: "boolean" } },
|
|
127
|
+
allowPositionals: true,
|
|
128
|
+
});
|
|
129
|
+
const [target, sessionId, requestHash] = positionals;
|
|
130
|
+
if (!["claude", "codex", "copilot"].includes(target) ||
|
|
131
|
+
!/^[A-Za-z0-9_.-]+$/.test(sessionId ?? "") ||
|
|
132
|
+
!/^[a-f0-9]{64}$/.test(requestHash ?? ""))
|
|
133
|
+
throw new ApproveError("Usage: policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session]");
|
|
134
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
135
|
+
throw new ApproveError("Run approve yourself in an interactive terminal; it asks you to confirm the request.");
|
|
136
|
+
if (!existsSync(sessionDirectoryPath(target, sessionId)))
|
|
137
|
+
throw new ApproveError("No policy service is running for that session.");
|
|
138
|
+
const ask = (confirm) => send(target, sessionId, {
|
|
139
|
+
action: "grant",
|
|
140
|
+
grant: { requestHash, confirm, session: values.session === true },
|
|
141
|
+
});
|
|
142
|
+
const preview = await ask(false);
|
|
143
|
+
if (preview.refused)
|
|
144
|
+
throw new ApproveError(preview.refused);
|
|
145
|
+
console.log(`Tool: ${preview.tool}\nRequest: ${preview.detail}\nRule: ${preview.reason}`);
|
|
146
|
+
if (values.session && preview.scope !== "session")
|
|
147
|
+
console.log("This request can only be approved once: credential reads, possible unrecoverable loss and requests whose effect could not be determined are never approved for a session.");
|
|
148
|
+
if (preview.scope === "session" && preview.sessionScope)
|
|
149
|
+
console.log(`Scope: ${preview.sessionScope}`);
|
|
150
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
151
|
+
const answer = await prompt.question(preview.scope === "session"
|
|
152
|
+
? "Allow this and later requests in this session that hit the same rule for the same scope? [y/N] "
|
|
153
|
+
: "Allow this request once? [y/N] ");
|
|
154
|
+
prompt.close();
|
|
155
|
+
if (!/^y(?:es)?$/i.test(answer.trim()))
|
|
156
|
+
throw new ApproveError("Not approved.");
|
|
157
|
+
const granted = await ask(true);
|
|
158
|
+
if (!granted.granted)
|
|
159
|
+
throw new ApproveError(granted.refused ?? "Not approved.");
|
|
160
|
+
console.log(granted.scope === "session"
|
|
161
|
+
? "Approved for this session. Tell the agent to retry the request unchanged."
|
|
162
|
+
: "Approved once. Tell the agent to retry the request unchanged.");
|
|
163
|
+
}
|
|
117
164
|
else if (action === "serve")
|
|
118
|
-
await serve(harness, phase ?? "");
|
|
165
|
+
await serve(harness, phase ?? "", cliPath);
|
|
119
166
|
else if (action === "stop")
|
|
120
167
|
console.log(JSON.stringify(await send(harness, phase ?? "", { action: "stop" })));
|
|
121
168
|
else if (action === "review" || action === "classify" || action === "record") {
|
|
@@ -171,7 +218,15 @@ try {
|
|
|
171
218
|
throw new Error(usage);
|
|
172
219
|
}
|
|
173
220
|
catch (error) {
|
|
174
|
-
if (
|
|
221
|
+
if (error instanceof ApproveError) {
|
|
222
|
+
console.error(error.message);
|
|
223
|
+
process.exitCode = 1;
|
|
224
|
+
}
|
|
225
|
+
else if (action === "approve") {
|
|
226
|
+
console.error("The approval could not be recorded. Nothing was approved.");
|
|
227
|
+
process.exitCode = 1;
|
|
228
|
+
}
|
|
229
|
+
else if (action?.startsWith("setup-hook")) {
|
|
175
230
|
console.error(error instanceof SetupError
|
|
176
231
|
? error.message
|
|
177
232
|
: "Hook setup failed. No automatic approval was granted.");
|
package/dist/evidence.js
CHANGED
|
@@ -92,7 +92,7 @@ export function sensitive(path) {
|
|
|
92
92
|
return (CREDENTIAL_CONFIG_DIRS.test(path) ||
|
|
93
93
|
path
|
|
94
94
|
.split(/[\\/]/)
|
|
95
|
-
.some((part) => /^(?:\.git|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.gcloud|\.docker|\.gnupg|\.password-store|\.git-credentials|\.vault-token|\.pgpass|\.my\.cnf|\.pypirc|\.npmrc|\.netrc|\.kube|credentials?|secrets?|id_rsa|id_ed25519|id_ecdsa|kubeconfig|terraform\.tfstate(?:\..*)?|.*\.(?:pem|key|pfx|p12))$/i.test(part)));
|
|
95
|
+
.some((part) => /^(?:\.git|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.gcloud|\.docker|\.gnupg|\.password-store|\.git-credentials|\.vault-token|\.pgpass|\.my\.cnf|\.pypirc|\.npmrc|\.netrc|\.kube|(?:credentials?|secrets?)(?:\.(?:json|ya?ml|toml|ini|env|txt|xml|conf|cfg|properties))?|id_rsa|id_ed25519|id_ecdsa|kubeconfig|terraform\.tfstate(?:\..*)?|.*\.(?:pem|key|pfx|p12))$/i.test(part)));
|
|
96
96
|
}
|
|
97
97
|
export function protectedPath(path) {
|
|
98
98
|
return path
|
package/dist/flow.js
CHANGED
|
@@ -461,6 +461,23 @@ function splitAssignment(word) {
|
|
|
461
461
|
value: { ...word, parts: [first.slice(eq + 1), ...word.parts.slice(1)], subs: [] },
|
|
462
462
|
};
|
|
463
463
|
}
|
|
464
|
+
/** grep and rg options whose value is a file-name glob. */
|
|
465
|
+
const GLOB_VALUE_OPTIONS = {
|
|
466
|
+
grep: ["--include", "--exclude", "--exclude-dir"],
|
|
467
|
+
egrep: ["--include", "--exclude", "--exclude-dir"],
|
|
468
|
+
fgrep: ["--include", "--exclude", "--exclude-dir"],
|
|
469
|
+
rg: ["--glob", "--iglob", "-g"],
|
|
470
|
+
};
|
|
471
|
+
/**
|
|
472
|
+
* `--include=*.md` or rg's `-g*.ts`: the option name is literal, so expansion can only yield more
|
|
473
|
+
* words of the same option, never another option or program.
|
|
474
|
+
*/
|
|
475
|
+
function globValuedOption(program, text) {
|
|
476
|
+
const options = program === undefined ? undefined : GLOB_VALUE_OPTIONS[basename(program)];
|
|
477
|
+
if (!options || text === undefined)
|
|
478
|
+
return false;
|
|
479
|
+
return options.some((option) => option.startsWith("--") ? text.startsWith(`${option}=`) : text.startsWith(option));
|
|
480
|
+
}
|
|
464
481
|
function runSimple(ctx, node, state, stage, piped) {
|
|
465
482
|
const { request, profile } = ctx;
|
|
466
483
|
const refusal = runSubs(ctx, [
|
|
@@ -473,8 +490,10 @@ function runSimple(ctx, node, state, stage, piped) {
|
|
|
473
490
|
// A glob in the command name or in a flag-like word expands to whatever file names exist, so
|
|
474
491
|
// `r[m] -rf x` runs `rm` once a file called `rm` is there, and `--forc[e]` can become `--force`.
|
|
475
492
|
const hasGlob = (word) => word.glob === true && plainText(word) !== "[" && plainText(word) !== "[[";
|
|
493
|
+
const program0 = plainText(node.argv[0]);
|
|
476
494
|
const globbed = node.argv.find((word, index) => hasGlob(word) &&
|
|
477
|
-
(index === 0 || word.parts.some((p) => typeof p === "string" && p.startsWith("-")))
|
|
495
|
+
(index === 0 || word.parts.some((p) => typeof p === "string" && p.startsWith("-"))) &&
|
|
496
|
+
!(index > 0 && globValuedOption(program0, plainText(word))));
|
|
478
497
|
if (globbed)
|
|
479
498
|
return human(request, "unknown", "A pattern in a command name or option requires human review");
|
|
480
499
|
const values = node.assigns.map((a) => a.value);
|
|
@@ -1339,14 +1358,29 @@ function runCase(ctx, node, state) {
|
|
|
1339
1358
|
return runRedirects(ctx, node.redirects, state);
|
|
1340
1359
|
}
|
|
1341
1360
|
// --- lists, pipelines and the entry point -----------------------------------------------------
|
|
1361
|
+
const ASSIGNABLE = /^[A-Z][A-Z0-9_]*$/;
|
|
1362
|
+
/** bash and zsh variables whose assignment can fail: read-only, numeric, or tied to the process. */
|
|
1363
|
+
const SHELL_SPECIAL = /^(?:BASH\w*|ZSH\w*|SHELLOPTS|EUID|UID|EGID|GID|GROUPS|PPID|USERNAME|ARGC|HISTCMD|LINENO|SECONDS|EPOCH\w*|S?RANDOM|ERRNO|OPTIND|OPTARG|TTYIDLE|SHLVL|COLUMNS|LINES|HISTSIZE|HISTFILESIZE|SAVEHIST|DIRSTACKSIZE|KEYTIMEOUT|LISTMAX|LOGCHECK|MAILCHECK|PERIOD|TMOUT|TRY_BLOCK_\w+|FUNCNAME|FUNCNEST|COMP_\w+|READLINE_\w+)$/;
|
|
1342
1364
|
/**
|
|
1343
|
-
* True when the pipeline always succeeds: `true`, `:`,
|
|
1365
|
+
* True when the pipeline always succeeds: a literal assignment, `true`, `:`,
|
|
1366
|
+
* or `cd` to an absolute directory that exists
|
|
1344
1367
|
* and can be entered now. Only used to know that an `&&` chain goes on past it; the directory it
|
|
1345
1368
|
* started from is still kept as possible.
|
|
1346
1369
|
*/
|
|
1347
1370
|
function cannotFail(ctx, node, state) {
|
|
1348
1371
|
const stage = node.stages.length === 1 && !node.negated ? node.stages[0] : undefined;
|
|
1349
|
-
if (stage?.kind !== "simple" || stage.
|
|
1372
|
+
if (stage?.kind !== "simple" || stage.redirects.length)
|
|
1373
|
+
return false;
|
|
1374
|
+
// `S=/x && H=y; use $H`: a bare assignment with no substitution succeeds. Only uppercase names
|
|
1375
|
+
// that the shell does not reserve; zsh's lowercase specials and the read-only or numeric
|
|
1376
|
+
// specials of bash and zsh can refuse a value.
|
|
1377
|
+
if (!stage.argv.length)
|
|
1378
|
+
return (stage.assigns.length > 0 &&
|
|
1379
|
+
stage.assigns.every((a) => ASSIGNABLE.test(a.name) &&
|
|
1380
|
+
!SHELL_SPECIAL.test(a.name) &&
|
|
1381
|
+
!BANNED_ENV.test(a.name) &&
|
|
1382
|
+
!a.value.subs.length));
|
|
1383
|
+
if (stage.assigns.length)
|
|
1350
1384
|
return false;
|
|
1351
1385
|
const argv = stage.argv.map(plainText);
|
|
1352
1386
|
const [program, target] = argv;
|
package/dist/grants.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Profile } from "./profile.js";
|
|
2
|
+
import type { Decision, Request } from "./types.js";
|
|
3
|
+
export declare const PROTECTED_PATH = "Protected path requires human approval";
|
|
4
|
+
export declare const HUMAN_PATTERN = "Matches an organization human-approval pattern";
|
|
5
|
+
/**
|
|
6
|
+
* The scope a `--session` approval of this human decision covers, or undefined when it can only
|
|
7
|
+
* be approved once. Credential and secret reads, possible unrecoverable loss and anything whose
|
|
8
|
+
* targets cannot be read from the request stay one-time. Scopes:
|
|
9
|
+
* - a protected-path write: the protected roots it touches (`<worktree>/.agent-config`);
|
|
10
|
+
* - a humanPatterns match: the matching patterns, in the same checkout;
|
|
11
|
+
* - any other human rule for a simple command: that exact command, same checkout.
|
|
12
|
+
* Category unknown (the engine could not rule out loss) is approved once only.
|
|
13
|
+
* Shell scopes need a simple command, so nothing else in the script hides behind the rule.
|
|
14
|
+
*/
|
|
15
|
+
export declare function grantScope(request: Request, decision: Decision, profile: Profile): string | undefined;
|
|
16
|
+
/** What a session scope covers, in words the user can check before approving it. */
|
|
17
|
+
export declare function scopeLabel(scope: string, profile: Profile): string;
|
|
18
|
+
//# sourceMappingURL=grants.d.ts.map
|
package/dist/grants.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { existsSync, statSync } from "node:fs";
|
|
2
|
+
import { dirname, join, relative } from "node:path";
|
|
3
|
+
import { canonical, git, inside, policyState, protectedPath, resolveWord, sensitive, } from "./evidence.js";
|
|
4
|
+
import { SHELL_TOOLS, words } from "./policy.js";
|
|
5
|
+
export const PROTECTED_PATH = "Protected path requires human approval";
|
|
6
|
+
export const HUMAN_PATTERN = "Matches an organization human-approval pattern";
|
|
7
|
+
const FILE_TOOLS = new Set(["Write", "create", "write_file", "Edit", "edit", "MultiEdit"]);
|
|
8
|
+
function topLevel(path) {
|
|
9
|
+
let parent = existsSync(path) && statSync(path).isDirectory() ? path : dirname(path);
|
|
10
|
+
while (!existsSync(parent))
|
|
11
|
+
parent = dirname(parent);
|
|
12
|
+
return canonical(git(parent, ["rev-parse", "--show-toplevel"]));
|
|
13
|
+
}
|
|
14
|
+
/** `<checkout>/<first protected name>` for a path inside a protected directory of a checkout. */
|
|
15
|
+
function protectedRoot(path) {
|
|
16
|
+
const top = topLevel(path);
|
|
17
|
+
const target = canonical(path);
|
|
18
|
+
if (!inside(top, target))
|
|
19
|
+
return undefined;
|
|
20
|
+
const parts = relative(top, target).split(/[\\/]/);
|
|
21
|
+
const index = parts.findIndex((part) => protectedPath(part));
|
|
22
|
+
return index < 0 ? undefined : join(top, ...parts.slice(0, index + 1));
|
|
23
|
+
}
|
|
24
|
+
/** The paths a request names: file tool targets, patch headers, or a simple command's path words. */
|
|
25
|
+
function targets(request) {
|
|
26
|
+
const input = request.input;
|
|
27
|
+
if (FILE_TOOLS.has(request.tool)) {
|
|
28
|
+
const file = input.file_path ?? input.path;
|
|
29
|
+
return typeof file === "string" ? [file] : undefined;
|
|
30
|
+
}
|
|
31
|
+
if (request.tool === "apply_patch") {
|
|
32
|
+
const patch = input.command ?? input.patch ?? input.input;
|
|
33
|
+
if (typeof patch !== "string")
|
|
34
|
+
return undefined;
|
|
35
|
+
const found = patch
|
|
36
|
+
.split("\n")
|
|
37
|
+
.flatMap((line) => /^\*\*\* (?:Add File|Update File|Delete File|Move to): /.test(line)
|
|
38
|
+
? [line.slice(line.indexOf(": ") + 2).trim()]
|
|
39
|
+
: []);
|
|
40
|
+
return found.length ? found : undefined;
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
/** A simple command (one program, no operators, expansions or redirects) as words. */
|
|
45
|
+
function simple(request) {
|
|
46
|
+
const command = request.input.command ?? request.input.cmd;
|
|
47
|
+
if (!SHELL_TOOLS.has(request.tool) || typeof command !== "string")
|
|
48
|
+
return undefined;
|
|
49
|
+
const argv = words(command);
|
|
50
|
+
return argv?.length ? argv : undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The scope a `--session` approval of this human decision covers, or undefined when it can only
|
|
54
|
+
* be approved once. Credential and secret reads, possible unrecoverable loss and anything whose
|
|
55
|
+
* targets cannot be read from the request stay one-time. Scopes:
|
|
56
|
+
* - a protected-path write: the protected roots it touches (`<worktree>/.agent-config`);
|
|
57
|
+
* - a humanPatterns match: the matching patterns, in the same checkout;
|
|
58
|
+
* - any other human rule for a simple command: that exact command, same checkout.
|
|
59
|
+
* Category unknown (the engine could not rule out loss) is approved once only.
|
|
60
|
+
* Shell scopes need a simple command, so nothing else in the script hides behind the rule.
|
|
61
|
+
*/
|
|
62
|
+
export function grantScope(request, decision, profile) {
|
|
63
|
+
try {
|
|
64
|
+
if (decision.reason === PROTECTED_PATH) {
|
|
65
|
+
let paths = targets(request);
|
|
66
|
+
if (!paths) {
|
|
67
|
+
const argv = simple(request);
|
|
68
|
+
paths = argv
|
|
69
|
+
?.slice(1)
|
|
70
|
+
.filter((word) => !word.startsWith("-") && (word.includes("/") || word.startsWith(".")));
|
|
71
|
+
}
|
|
72
|
+
if (!paths?.length)
|
|
73
|
+
return undefined;
|
|
74
|
+
const roots = new Set();
|
|
75
|
+
let top;
|
|
76
|
+
for (const path of paths) {
|
|
77
|
+
const lexical = resolveWord(request.cwd, path);
|
|
78
|
+
if (sensitive(lexical) || policyState(lexical))
|
|
79
|
+
return undefined;
|
|
80
|
+
const resolved = canonical(lexical);
|
|
81
|
+
if (sensitive(resolved) || policyState(resolved))
|
|
82
|
+
return undefined;
|
|
83
|
+
const root = protectedRoot(resolved);
|
|
84
|
+
const checkout = topLevel(resolved);
|
|
85
|
+
if (top !== undefined && checkout !== top)
|
|
86
|
+
return undefined;
|
|
87
|
+
top = checkout;
|
|
88
|
+
if (root)
|
|
89
|
+
roots.add(root);
|
|
90
|
+
}
|
|
91
|
+
return roots.size ? `protected:${[...roots].sort().join("\u0000")}` : undefined;
|
|
92
|
+
}
|
|
93
|
+
const argv = simple(request);
|
|
94
|
+
if (!argv)
|
|
95
|
+
return undefined;
|
|
96
|
+
const checkout = topLevel(request.cwd);
|
|
97
|
+
if (decision.reason === HUMAN_PATTERN) {
|
|
98
|
+
const joined = argv.join(" ");
|
|
99
|
+
const matched = profile.humanPatterns.flatMap((pattern, index) => pattern.test(joined) ? [index] : []);
|
|
100
|
+
return matched.length ? `pattern:${matched.join(",")}:${checkout}` : undefined;
|
|
101
|
+
}
|
|
102
|
+
if (decision.category === "sensitive" ||
|
|
103
|
+
decision.category === "destructive" ||
|
|
104
|
+
decision.category === "unknown")
|
|
105
|
+
return undefined;
|
|
106
|
+
if (argv.slice(1).some((word) => sensitive(word)))
|
|
107
|
+
return undefined;
|
|
108
|
+
return `command:${decision.reason}:${JSON.stringify(argv)}:${checkout}`;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** What a session scope covers, in words the user can check before approving it. */
|
|
115
|
+
export function scopeLabel(scope, profile) {
|
|
116
|
+
if (scope.startsWith("protected:"))
|
|
117
|
+
return `writes under ${scope.slice("protected:".length).split("\u0000").join(", ")}`;
|
|
118
|
+
if (scope.startsWith("pattern:")) {
|
|
119
|
+
const [, indexes = "", ...checkout] = scope.split(":");
|
|
120
|
+
const patterns = indexes
|
|
121
|
+
.split(",")
|
|
122
|
+
.map((index) => profile.humanPatterns[Number(index)]?.source ?? index)
|
|
123
|
+
.join(", ");
|
|
124
|
+
return `commands matching ${patterns} in ${checkout.join(":")}`;
|
|
125
|
+
}
|
|
126
|
+
const rest = scope.slice(scope.indexOf(":[") + 1);
|
|
127
|
+
const end = rest.lastIndexOf("]:");
|
|
128
|
+
const argv = JSON.parse(rest.slice(0, end + 1));
|
|
129
|
+
return `the exact command \`${argv.join(" ")}\` in ${rest.slice(end + 2)}`;
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=grants.js.map
|