@agent-corpus/policy-manager 0.5.0 → 0.6.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 +54 -10
- package/dist/adapters.d.ts +3 -1
- package/dist/adapters.js +18 -4
- package/dist/audit.js +16 -2
- package/dist/cli.js +10 -3
- package/dist/config.js +7 -1
- package/dist/created.d.ts +44 -0
- package/dist/created.js +236 -0
- package/dist/evidence.d.ts +53 -1
- package/dist/evidence.js +201 -6
- package/dist/flow.d.ts +2 -1
- package/dist/flow.js +856 -76
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/permissive.d.ts +11 -3
- package/dist/permissive.js +648 -28
- package/dist/policy.d.ts +3 -1
- package/dist/policy.js +78 -35
- package/dist/principle.d.ts +8 -0
- package/dist/principle.js +8 -0
- package/dist/profile.d.ts +8 -0
- package/dist/profile.js +26 -0
- package/dist/recoverable.d.ts +41 -0
- package/dist/recoverable.js +391 -0
- package/dist/script.d.ts +35 -1
- package/dist/script.js +215 -17
- package/dist/service.js +2 -2
- package/dist/session.d.ts +4 -1
- package/dist/session.js +44 -15
- package/dist/types.d.ts +9 -3
- package/dist/types.js +12 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -72,7 +72,7 @@ Pass one JSON object on standard input:
|
|
|
72
72
|
}
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
-
Run `policy-manager review codex session-example`. The response includes `decision` (`approve` or `
|
|
75
|
+
Run `policy-manager review codex session-example`. The response includes `decision` (`approve`, `human`, `deny`, or `native` for an unlisted MCP tool left to the harness), `category`, `reason`, `requestHash`, `cache`, and `cached`. The library exports the same evaluator.
|
|
76
76
|
|
|
77
77
|
The session's policy-manager agent returns the following object for an ambiguous request. The working agent submits it through `policy-manager classify codex session-example`:
|
|
78
78
|
|
|
@@ -80,22 +80,24 @@ The session's policy-manager agent returns the following object for an ambiguous
|
|
|
80
80
|
{ "requestHash": "<exact hash from review>", "category": "unknown", "confidence": 0.4 }
|
|
81
81
|
```
|
|
82
82
|
|
|
83
|
-
Categories are `code-read`, `worktree-write`, `cloud-read`, `git-read`, `impactful-write`, `destructive`, `sensitive`, and `unknown`. The threshold is 0.99 plus deterministic verification and category agreement. Explicitly listed metadata operations with permitted selectors can qualify through AI classification. Endpoint overrides and cloud writes cannot qualify. Unknown commands stay human decisions. No classifier starts a second harness or calls an external model API.
|
|
83
|
+
Categories are `code-read`, `worktree-write`, `temp-write` (a recoverable write outside any repository), `cloud-read`, `git-read`, `impactful-write`, `destructive`, `sensitive`, and `unknown`. The threshold is 0.99 plus deterministic verification and category agreement. Explicitly listed metadata operations with permitted selectors can qualify through AI classification. Endpoint overrides and cloud writes cannot qualify. Unknown commands stay human decisions. No classifier starts a second harness or calls an external model API.
|
|
84
84
|
|
|
85
85
|
## AI classification of ambiguous requests (experiment)
|
|
86
86
|
|
|
87
|
+
The rule, exported as `HUMAN_REVIEW_PRINCIPLE` and included in every classification hint: _A human prompt is reserved for high-value, high-impact actions: unrecoverable data loss, credential/secret retrieval, protected config/paths, and profile humanPatterns. Recoverable or disposable effects, including destructive-but-safe ones, are automatic._
|
|
88
|
+
|
|
87
89
|
Under a `permissive` profile, a person is asked only for what code says must stay with a person. Every other escalation is _ambiguous_: the deterministic engine cannot decide it, so the session's AI decides it instead of the person. Strict mode, and calls made outside the hooks (`policy-manager review`), are unchanged.
|
|
88
90
|
|
|
89
91
|
How a hook call flows (Claude Code, Codex and Copilot `PreToolUse`):
|
|
90
92
|
|
|
91
|
-
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.
|
|
92
|
-
2. **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
|
|
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. **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.
|
|
93
95
|
3. **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 tells the model to have the user run the command themselves or change the profile). 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.
|
|
94
96
|
|
|
95
97
|
**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):
|
|
96
98
|
|
|
97
99
|
- Credential and secret retrieval, protected paths and configuration such as the policy profile and hook settings (category `sensitive`).
|
|
98
|
-
- Destructive operations:
|
|
100
|
+
- Destructive operations: unmerged-work loss, history and remote rewrites, cloud deletion, publishing, and deletion outside a linked feature worktree. Recoverable deletion is approved deterministically (see **Recoverable deletions and resets**). The only destructive escalation the classifier decides is an `rm` inside a linked feature worktree that the evidence cannot prove recoverable.
|
|
99
101
|
- Commands matching the profile's `humanPatterns`.
|
|
100
102
|
- Writes outside a linked feature worktree (main clones and protected branches).
|
|
101
103
|
- Cloud operations outside the read catalog. The profile's `cloudWrites: "allow"` is the way to automate these.
|
|
@@ -133,7 +135,8 @@ Without a profile the engine is strict (everything above). An organization can i
|
|
|
133
135
|
"mode": "permissive",
|
|
134
136
|
"cloudWrites": "human",
|
|
135
137
|
"humanPatterns": ["^npm install"],
|
|
136
|
-
"scratchRoots": ["/
|
|
138
|
+
"scratchRoots": ["/srv/scratch"],
|
|
139
|
+
"mcpReadOnly": ["mcp__github__get_issue", "mcp__github__list_pull_requests"]
|
|
137
140
|
}
|
|
138
141
|
```
|
|
139
142
|
|
|
@@ -144,7 +147,15 @@ policy-manager profile install policy.json # writes ~/.config/agent-corpus/pol
|
|
|
144
147
|
|
|
145
148
|
The service reads the profile only from that user directory (`$XDG_CONFIG_HOME` honored). It must be a regular, non-symlink file owned by the user, not group/world writable, and outside every Git checkout, so an agent cannot rewrite its own rules from a worktree. On Windows, POSIX owner and mode bits do not exist, so only the regular-file, non-symlink and outside-Git checks apply and the user-profile ACL is the trust boundary. `cd <literal>` is tracked, and each later command is judged in every directory it could run in. Git long-option abbreviations are treated as the full option. An invalid or untrusted profile logs `profile ... invalid-using-strict` and the session stays strict. Each session records the profile mode and SHA-256 digest in `audit.jsonl`.
|
|
146
149
|
|
|
147
|
-
`permissive` approves compound commands (`;`, `&&`, `||`, `|`, quotes, redirects, `VAR=x` prefixes) when every simple command is acceptable, and approves unknown executables and interpreters with inline code. It
|
|
150
|
+
`permissive` approves compound commands (`;`, `&&`, `||`, `|`, quotes, redirects, `VAR=x` prefixes) when every simple command is acceptable, and approves unknown executables and interpreters with inline code. It sends these to a person, except for the scratch deletions below and an `rm` inside a linked feature worktree, which the classifier may approve as recoverable: deletion (`rm`, `find -delete`, `xargs rm`) and `git reset --hard`, checkouts and restores that discard work (see **Recoverable deletions and resets** for what Git can undo), `sudo`, `git clean`, forced or mirror pushes, stash and reflog destruction, `gh` deletions and security endpoints, cloud deletion and credential retrieval, infrastructure destroy, `npm publish`, destructive HTTP verbs, piping into a shell, ssh and database clients, builtins that run a string later (`eval`, `source`, `trap`, `alias`), printing the environment, writes outside linked feature worktrees, `scratchRoots` and the system temp directory, and protected or credential paths. `humanPatterns` adds organization-specific expressions.
|
|
151
|
+
|
|
152
|
+
Writes outside every repository to the system temp directory (`os.tmpdir()`, plus `/tmp` and `/private/tmp` off Windows) are approved as `temp-write`, after symlinks (dangling ones too) and `..` are resolved. Repository rules still apply to a checkout that lives in the temp directory. The policy service's own `acp-*` session directories, hard-linked files, protected names and credential paths are never temp writes. A temp root that contains the home directory grants nothing.
|
|
153
|
+
|
|
154
|
+
Deleting disposable files is approved too (`Delete within a scratch directory`): `rm`, `rmdir`, `unlink` and `find ... -delete` (without `-exec`, `-L` or `-follow`) when every target resolves strictly inside a `scratchRoots` entry or the system temp directory, never the root itself. A glob may appear only in the last component, and its directory must itself be strictly inside a root, so `rm -rf /tmp/*` still asks. Targets in or holding a Git repository (unpushed work), `acp-*` policy state, and protected or credential names still go to a person.
|
|
155
|
+
|
|
156
|
+
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
|
+
|
|
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, and `gh` `--body`, `--title`, `--jq`, `--template` and `--notes` values. Other programs keep the conservative check.
|
|
148
159
|
|
|
149
160
|
#### Shell syntax in permissive mode
|
|
150
161
|
|
|
@@ -153,13 +164,46 @@ Every command that could run is judged, not only the first. Understood: `;`, new
|
|
|
153
164
|
- **Variables.** `NAME=value`, `export NAME=value` and `for NAME in a b c` give a variable a known value; the command is then judged with the value substituted, in every directory and for every value it could take. A variable assigned in only some branches, in a loop, or from a command, glob or `read` has an unknown value, as does any environment variable the script did not assign. An unknown value is accepted only as an argument to `echo`, `printf` with string conversions, `test`/`[` without numeric tests, `true`, `false`, `basename` and `dirname`, and as the value of a commit or PR message option (`git commit -m "$(...)"`, `gh pr create --body "$(...)"`). It is never a program, option, path, `cd` target or redirection target. Environment variables other than a short list (`PWD`, `USER`, `TMPDIR`, ...) need a human, because they can hold credentials.
|
|
154
165
|
- **Command substitution** and process substitution run first: the inner command is judged with the same rules.
|
|
155
166
|
- **Heredocs.** A quoted delimiter (`<<'EOF'`) is literal text. An unquoted delimiter is accepted only when the body has no `$`, backtick or backslash. A shell fed by a heredoc (`bash <<'EOF'`) has its body judged as a script. An interpreter fed by a heredoc or `-c` is treated like inline code: the code is scanned for file deletion, process creation, string evaluation and protected paths, and anything flagged goes to a human; code piped in from elsewhere always does.
|
|
156
|
-
- **Compound commands.** Branches are judged on copies of the state and merged; a loop's assigned variables are unknown inside it and afterwards, and a `cd` inside a loop or pipeline needs a human.
|
|
157
|
-
- **
|
|
167
|
+
- **Compound commands.** Branches are judged on copies of the state and merged; a loop's assigned variables are unknown inside it and afterwards, and a `cd` inside a loop or pipeline needs a human. A `cd` can fail, so the directory it started from stays possible, except in an unbroken `&&` chain (`cd X && cmd`) or an `if cd X; then` body, which run only after it succeeded. `cd X; cmd`, `cd X || cmd` and `! cd X && cmd` are judged in both directories. A `for` loop over literal items is judged once per item. The body of an `if` sees what its condition assigned when the condition is an `&&` chain.
|
|
168
|
+
- **Other repositories.** A session started in one repository may change any other Git repository when the writes land in a linked feature worktree: `cd <worktree> && <edit>`, and commits, pushes and `gh pr create` from there. From any clone, `git fetch origin` and `git worktree add` are approved; a new worktree inside the main checkout must go under `.worktrees/` or `.claude/worktrees/`, and `-B` needs a human. Writes to a main checkout still need a human. The strict profile approves `git worktree add [--no-track] <path> -b <new branch> origin/main` (either order, `main` or `master`) under those two directories.
|
|
169
|
+
- **Functions.** `name() { ...; }` is recorded, and each call judges the body with the call's arguments as `$1`, `$2`, .... A function defined on only some paths, called through a wrapper or variable (`time f`, `X=f; $X`), named like a special builtin, or nested more than four calls deep needs a human. `set -- words` sets the positional parameters the same way. A value with blanks is not split (zsh does not split an unquoted parameter, bash does), so the positions after it are unknown. `shift` and any other `set` with words make them unknown. Functions zsh or bash runs with no call (`TRAPxxx`, `chpwd`, `precmd`, `preexec`, `periodic`, `zshexit`, `zshaddhistory`, the not-found handlers) need a human. Positional parameters never count as environment variables; outside a call or `set --` they are unknown.
|
|
170
|
+
- **Parameter forms.** `${X:-w}`, `${X:+w}`, `${#X}`, `${X#p}`, `${X##p}`, `${X%p}`, `${X%%p}` and `${X:o:l}` with a literal word or pattern are computed when `X` is known and are unknown otherwise; `X` is still checked as an environment variable. `$'...'` is decoded and judged as a literal. An assignment value starting with `~` or `~/` is the home directory.
|
|
171
|
+
- **`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
|
+
- **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
|
+
- **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.
|
|
174
|
+
- **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
|
+
|
|
176
|
+
#### MCP read-only tools
|
|
177
|
+
|
|
178
|
+
`mcpReadOnly` lists MCP tools that run without a prompt, in any `mode`. Each entry is an exact `mcp__<server>__<tool>` name, or a name whose tool segment ends in `*` (`mcp__docs__search_*`). Neither segment may contain `__`, and a wildcard approves only a tool whose whole tool segment (after `mcp__<server>__`) is free of `__`, so it cannot reach another server such as `github__get`. Whole-server wildcards (`mcp__github__*`), regular expressions and other tool names are rejected, and the list holds at most 200 entries of 128 characters. List only tools that cannot change anything and cannot return credentials: the tool name is all the engine checks, not the arguments. Prefer exact names. A prefix also covers tools that a server adds later, and read-looking prefixes can include secret readers: the GitHub server's `get_*` and `list_*` cover its secret-scanning alert tools, which return the detected secret.
|
|
179
|
+
|
|
180
|
+
The server segment is whatever name the harness configuration gives the server, and the engine cannot tell where it came from. In Claude Code, a project `.mcp.json` server overrides a user server of the same name, so a repository can register its own `github`. Once the user enables it, its listed tools run without a prompt. List only servers defined in managed or user configuration, and pair the list with the harness's MCP server allowlists (Claude Code `enabledMcpjsonServers`, or managed MCP settings).
|
|
181
|
+
|
|
182
|
+
A listed tool is approved. Any other MCP tool gets no decision from the policy manager: the harness's own permission flow (allow rules, prompts) handles it exactly as without the hook, so nothing that worked before needs a classification or a new prompt. The audit log records an MCP request with the tool name and argument keys hashed, never argument values.
|
|
183
|
+
|
|
184
|
+
| Harness | MCP support |
|
|
185
|
+
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
186
|
+
| Claude Code | `PreToolUse` matcher `mcp__.*` (regex on `mcp__<server>__<tool>`); `PermissionRequest` already sees every tool. |
|
|
187
|
+
| Codex | Same matcher; Codex names MCP tools `mcp__<server>__<tool>` in `PreToolUse` and `PermissionRequest`. The new matcher changes the `PreToolUse` hook's trust hash, so trust it again in `/hooks` after `setup-hook-codex`. |
|
|
188
|
+
| Copilot | Not supported. The Copilot hooks reference documents no MCP tool name for hooks, so setup adds no MCP matcher and `mcpReadOnly` never matches a Copilot tool; Copilot's own MCP permissions apply. |
|
|
158
189
|
|
|
159
190
|
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.
|
|
160
191
|
|
|
161
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.
|
|
162
193
|
|
|
194
|
+
#### Recoverable deletions and resets
|
|
195
|
+
|
|
196
|
+
Deletion that Git can undo is approved; anything Git cannot restore still goes to a human. The evidence is read from Git at decision time and never cached. All of these require a linked worktree on a feature branch (not `main`, `master` or `origin/HEAD`'s branch) and a script that contains only these commands plus `cd`, `pwd`, `echo`, `ls` and `true`, with no redirections, assignments, wrappers, variables or substitutions, since an earlier command could change the files first (`mv untracked tracked; rm tracked`).
|
|
197
|
+
|
|
198
|
+
- **`rm`** with only `-f`, `-r`, `-R`, `-d`, `-v` before the operands, when every operand exists, is tracked, and has nothing under it that is untracked, ignored, modified, staged, assume-unchanged, skip-worktree or a submodule. Globs, `~`, `.`/`..` segments, backslashes and a leading `-`, `:` or `=` (zsh expands `=name` to a command's path; `./=name` is fine) stay human. Parent symlinks are resolved; a final symlink is the link itself unless a trailing slash follows it. Protected and credential paths stay human, as category `sensitive`, never classified.
|
|
199
|
+
- **Files this session created.** `rm`/`rm -f` (not `-r`) of an untracked file is approved when this session created that exact path: a Write or patch, a `>`/`>>` redirect, `touch`, `tee` or `cp` to a path that did not exist, or that is still exactly the session's file. `mv` and a patch's `Move to:` keep the source's content, so they count only when the source was the session's. After the tool runs (`PostToolUse`), the file there is recorded only if it is the session's own inode (edited, or moved there by the session) or a new inode whose birth time is no older than the approval. A rename keeps the birth time, so `mv notes.md x && touch x` does not make a user's file the session's. A new inode still says nothing about its content (`gzip notes.md`, `git stash pop`), so a shell script records creations only when every simple command in it is provably on an allowlist. The allowed commands are `touch`, `tee [-a]`, `cp`/`mv` from a file the session owns when the hook runs, and inert commands (`echo`, `printf`, `pwd`, `ls`, `true`), each with any `>`/`>>` redirect. A `cd` (or `pushd`, `popd`, `chdir`) anywhere makes the script record nothing, since a skipped `true || cd sub` cannot be told from the text. A bare name or a system bin path counts; a relative path does not. Ownership never chains through earlier commands in the same script. A command substitution, process substitution, heredoc or here-string, input or descriptor redirect (`<`, `>&`), path word the shell would expand or resolve differently (leading `~` or `=`; a `$`, glob, brace or backslash anywhere; a `.` or `..` segment, which the kernel resolves from a symlink's target), assignment, variable, wrapper (`env`, `xargs`, `time`, `nice`, `command`), nested shell, unknown option, or anything unparsable makes the whole script record nothing. Where the platform reports no birth time, nothing new is recorded. The session stores the file's device, inode, size and mtime under a hash of its path. A later symlink, hard link, edit by anything else, or `git checkout` over it no longer matches. This is held in the session's memory only, never shared or cached across sessions. Any other untracked file or directory goes to the classifier.
|
|
200
|
+
- **`cd <dir> && ...`.** When the rest of an `&&` chain follows a lone `cd`, later commands are judged only in the new directory, since they run only if the `cd` succeeded. With `;` or a later `||`, both directories are judged.
|
|
201
|
+
- **`git rm`** without `--force` is approved as before (Git itself refuses to drop changes). `git rm -f` needs the `rm` evidence, except that a file already deleted from the working tree is fine.
|
|
202
|
+
- **`git reset --hard [<commit>]`** (with at most `-q`) when no tracked change is uncommitted, every commit it drops from the branch is on a remote-tracking ref, no untracked or ignored file sits where the target writes, and the target changes no protected path.
|
|
203
|
+
- **`git checkout -- <paths>`, `git checkout .` and `git restore [-W] <paths>`** when the working tree already matches the index for those paths, or the files are only missing. `git restore -SW` needs the working tree and index to match `HEAD`. A tree-ish, `--source`, `-p` or `-f` stays human.
|
|
204
|
+
|
|
205
|
+
An `rm` whose operands are all plain paths inside a linked feature worktree, but which the evidence above cannot prove recoverable (another untracked file, a directory), goes to the session classifier. This holds only when such deletions are the script's whole effect. The script may also hold `pwd`, `echo`, `ls` and `true`, and at most a leading `cd <dir>` joined by `&&` alone. It may not contain redirections, assignments, variables or substitutions. Otherwise one verdict on the `rm` would carry later commands nobody judged, so the script goes to a person. It is approved on `recoverable: true` at 0.95, and otherwise goes to a person. Every other destructive escalation goes to a person and is never classified: `git clean`, forced pushes and refspecs, unmerged branch deletion, stash and reflog destruction, `find -delete`, `xargs rm`, `unlink`, `sudo`, cloud and infrastructure deletion, publishing, destructive HTTP verbs, and anything in the main checkout or outside a worktree.
|
|
206
|
+
|
|
163
207
|
Deleting a branch is automatic only when it is already merged into `origin/main` (or `master`): reachable from it, or patch-equivalent to a squash or rebase merge. Remote deletion also needs `origin` and a `git ls-remote` tip that matches the fetched tracking ref, so unfetched commits block it. Evidence uses the locally fetched default branch; fetch first for very recent merges.
|
|
164
208
|
|
|
165
209
|
## Service, cache, and logs
|
|
@@ -170,7 +214,7 @@ The cache belongs to the service process and is scoped to harness plus session I
|
|
|
170
214
|
|
|
171
215
|
`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.
|
|
172
216
|
|
|
173
|
-
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 user runs the command themselves or changes the policy profile. An ambiguous cloud request is the one exception: its reason points to the session policy-manager agent, and a classification of approved is accepted for the session, so a retry passes. Codex
|
|
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 user runs the command themselves or changes the policy profile. An ambiguous cloud request is the one exception: 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.
|
|
174
218
|
|
|
175
219
|
## Audit API and reported outcomes
|
|
176
220
|
|
package/dist/adapters.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Decision, type OutcomeReport, type Request } from "./types.js";
|
|
2
2
|
export declare function normalize(harness: Request["harness"], payload: Record<string, unknown>): Request;
|
|
3
3
|
export interface HookContext {
|
|
4
4
|
cliPath: string;
|
|
@@ -11,5 +11,7 @@ export interface HookContext {
|
|
|
11
11
|
*/
|
|
12
12
|
export declare function classifyCommand(harness: Request["harness"], context?: HookContext, json?: string): string;
|
|
13
13
|
export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): Record<string, unknown>;
|
|
14
|
+
/** The exact stdout of a PreToolUse or PermissionRequest hook. Codex gets no output for no decision. */
|
|
15
|
+
export declare function hookOutput(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): string;
|
|
14
16
|
export declare function executionReport(request: Request, phase: string, payload: Record<string, unknown>): OutcomeReport;
|
|
15
17
|
//# sourceMappingURL=adapters.d.ts.map
|
package/dist/adapters.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { requestHash } from "./policy.js";
|
|
2
|
+
import { HUMAN_REVIEW_PRINCIPLE } from "./principle.js";
|
|
3
|
+
import { CATEGORIES } from "./types.js";
|
|
2
4
|
export function normalize(harness, payload) {
|
|
3
5
|
let input = payload.tool_input ?? payload.toolInput ?? payload.toolArgs ?? {};
|
|
4
6
|
if (typeof input === "string")
|
|
@@ -38,9 +40,11 @@ export function classifyCommand(harness, context, json = "<json>") {
|
|
|
38
40
|
/** What a blocked ambiguous request tells the model to do. Never ask for human approval here. */
|
|
39
41
|
function classifyInstruction(harness, decision, context) {
|
|
40
42
|
const command = classifyCommand(harness, context);
|
|
41
|
-
return `
|
|
43
|
+
return `Needs classification (not an error): not run yet. Ask the session's policy-manager agent whether this exact command is recoverable and non-sensitive, record its answer, then retry the same command unchanged. Rule: ${HUMAN_REVIEW_PRINCIPLE} Request ${decision.requestHash}: ${decision.reason}. Answer shape: {"requestHash":"${decision.requestHash}","category":"${CATEGORIES.join("|")}","confidence":0.0-1.0,"recoverable":true|false,"rationale":"one short sentence without quotes"}. Record it by replacing <json> in this command, with no single quotes in the answer: ${command} If no classification is available, retry once and the user will be asked.`;
|
|
42
44
|
}
|
|
43
45
|
export function hookResponse(harness, phase, decision, context) {
|
|
46
|
+
if (decision.decision === "native")
|
|
47
|
+
return {};
|
|
44
48
|
if (decision.decision === "deny") {
|
|
45
49
|
const reason = decision.classification === "requested"
|
|
46
50
|
? classifyInstruction(harness, decision, context)
|
|
@@ -75,8 +79,13 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
75
79
|
return decision.decision === "approve"
|
|
76
80
|
? { hookSpecificOutput: { hookEventName: phase, decision: { behavior: "allow" } } }
|
|
77
81
|
: {};
|
|
82
|
+
// Codex rejects PreToolUse `permissionDecision: "allow"` without `updatedInput` ("unsupported
|
|
83
|
+
// permissionDecision:allow") and marks the hook failed. An approval there is no decision at all;
|
|
84
|
+
// if Codex would then prompt, its PermissionRequest hook (above) returns the allow.
|
|
78
85
|
if (decision.decision === "approve")
|
|
79
|
-
return
|
|
86
|
+
return harness === "codex"
|
|
87
|
+
? {}
|
|
88
|
+
: { hookSpecificOutput: { hookEventName: phase, permissionDecision: "allow" } };
|
|
80
89
|
// Codex parses permissionDecision "ask" but does not support it: it marks the hook failed and
|
|
81
90
|
// runs the tool anyway (https://developers.openai.com/codex/hooks). Only "deny" stops a command,
|
|
82
91
|
// so a decision that needs a human is a deny. Approving it in chat does not change the decision,
|
|
@@ -103,6 +112,11 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
103
112
|
},
|
|
104
113
|
};
|
|
105
114
|
}
|
|
115
|
+
/** The exact stdout of a PreToolUse or PermissionRequest hook. Codex gets no output for no decision. */
|
|
116
|
+
export function hookOutput(harness, phase, decision, context) {
|
|
117
|
+
const response = hookResponse(harness, phase, decision, context);
|
|
118
|
+
return harness === "codex" && Object.keys(response).length === 0 ? "" : JSON.stringify(response);
|
|
119
|
+
}
|
|
106
120
|
export function executionReport(request, phase, payload) {
|
|
107
121
|
const response = payload.tool_response ?? payload.toolResponse ?? payload.tool_result ?? payload.toolResult;
|
|
108
122
|
const result = response && typeof response === "object" ? response : {};
|
|
@@ -116,7 +130,7 @@ export function executionReport(request, phase, payload) {
|
|
|
116
130
|
const unknown = exitCode === undefined && request.harness === "codex";
|
|
117
131
|
const duration = payload.duration_ms ?? payload.durationMs;
|
|
118
132
|
return {
|
|
119
|
-
requestHash:
|
|
133
|
+
requestHash: requestHash(request),
|
|
120
134
|
event: "execution-result",
|
|
121
135
|
status: phase === "PostToolUseFailure"
|
|
122
136
|
? payload.is_interrupt === true
|
package/dist/audit.js
CHANGED
|
@@ -3,7 +3,7 @@ import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { basename, join } from "node:path";
|
|
5
5
|
import { AuditLog } from "@agent-corpus/audit-log";
|
|
6
|
-
import { hash, words } from "./policy.js";
|
|
6
|
+
import { hash, requestHash, words } from "./policy.js";
|
|
7
7
|
const vocabulary = new Set("git az aws gcloud cat rm terraform resource group network monitor servicebus queue topic storage blob webapp appservice containerapp vm disk ec2 rds s3api cloudformation logs cloudwatch sqs sns ecs eks compute instances projects container run sql pubsub logging monitoring log-analytics workspace boards work-item account list show query create update delete destroy purge status diff log fetch origin branch worktree add describe-instances describe-volumes describe-stacks".split(" "));
|
|
8
8
|
const tools = new Set("Read Write Edit view create edit Bash bash powershell exec_command apply_patch shell read_file write_file".split(" "));
|
|
9
9
|
export function sessionDirectoryPath(harness, sessionId) {
|
|
@@ -59,6 +59,20 @@ export function audit(directory, event) {
|
|
|
59
59
|
});
|
|
60
60
|
}
|
|
61
61
|
export function requestSummary(request) {
|
|
62
|
+
// MCP arguments are tool-specific: record only hashes of the tool name and argument keys.
|
|
63
|
+
if (request.tool.startsWith("mcp__"))
|
|
64
|
+
return {
|
|
65
|
+
summary: "MCP tool operation",
|
|
66
|
+
action: "tool operation",
|
|
67
|
+
tool: "mcp",
|
|
68
|
+
requestHash: requestHash(request),
|
|
69
|
+
harness: request.harness,
|
|
70
|
+
sessionHash: hash(request.sessionId),
|
|
71
|
+
cwdHash: hash(request.cwd),
|
|
72
|
+
toolHash: hash(request.tool),
|
|
73
|
+
inputKeys: Object.keys(request.input).map((key) => hash(key)),
|
|
74
|
+
executable: "other",
|
|
75
|
+
};
|
|
62
76
|
const command = request.input.command ?? request.input.cmd;
|
|
63
77
|
const argv = typeof command === "string" ? words(command) : undefined;
|
|
64
78
|
const operation = argv?.slice(0, 4).filter((word, index) => index === 0 || !word.startsWith("-"));
|
|
@@ -85,7 +99,7 @@ export function requestSummary(request) {
|
|
|
85
99
|
tool: tools.has(request.tool) ? request.tool : "other",
|
|
86
100
|
...(typeof file === "string" ? { targetHash: hash([request.cwd, file]) } : {}),
|
|
87
101
|
...(targets.length ? { targets } : {}),
|
|
88
|
-
requestHash:
|
|
102
|
+
requestHash: requestHash(request),
|
|
89
103
|
harness: request.harness,
|
|
90
104
|
sessionHash: hash(request.sessionId),
|
|
91
105
|
cwdHash: hash(request.cwd),
|
package/dist/cli.js
CHANGED
|
@@ -3,8 +3,9 @@ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { parseArgs } from "node:util";
|
|
6
|
-
import { executionReport,
|
|
6
|
+
import { executionReport, hookOutput, normalize } from "./adapters.js";
|
|
7
7
|
import { hookConfig } from "./config.js";
|
|
8
|
+
import { HUMAN_REVIEW_PRINCIPLE } from "./principle.js";
|
|
8
9
|
import { defaultProfilePath, loadProfile, parseProfile } from "./profile.js";
|
|
9
10
|
import { replayTranscripts } from "./replay.js";
|
|
10
11
|
import { formatReview, reviewClassifications, sessionDirectories } from "./review.js";
|
|
@@ -67,6 +68,7 @@ try {
|
|
|
67
68
|
const summary = {
|
|
68
69
|
mode: profile.mode,
|
|
69
70
|
cloudWrites: profile.cloudWrites,
|
|
71
|
+
mcpReadOnly: profile.mcpReadOnly.length,
|
|
70
72
|
digest: profile.digest,
|
|
71
73
|
};
|
|
72
74
|
if (harnessArg === "install") {
|
|
@@ -136,7 +138,7 @@ try {
|
|
|
136
138
|
else {
|
|
137
139
|
const directory = await start(harness, request.sessionId, cliPath);
|
|
138
140
|
if (phase === "SessionStart") {
|
|
139
|
-
const context = `Policy service started. Audit log: ${join(directory, "audit.jsonl")}. Native hooks route tool and permission requests directly to the deterministic service. An ambiguous request is blocked once with instructions to have the policy-manager agent classify it and then retry; the person is asked only if classification fails. If .agent-config/agents/policy-manager.md exists, read it before creating a read-only policy-manager agent. Never ask an agent to approve its own tools.`;
|
|
141
|
+
const context = `Policy service started. Audit log: ${join(directory, "audit.jsonl")}. Native hooks route tool and permission requests directly to the deterministic service. An ambiguous request is blocked once with instructions to have the policy-manager agent classify it and then retry; the person is asked only if classification fails. ${HUMAN_REVIEW_PRINCIPLE} If .agent-config/agents/policy-manager.md exists, read it before creating a read-only policy-manager agent. Never ask an agent to approve its own tools.`;
|
|
140
142
|
console.log(JSON.stringify(harness === "copilot"
|
|
141
143
|
? { additionalContext: context }
|
|
142
144
|
: { hookSpecificOutput: { hookEventName: phase, additionalContext: context } }));
|
|
@@ -154,7 +156,12 @@ try {
|
|
|
154
156
|
request,
|
|
155
157
|
phase,
|
|
156
158
|
}));
|
|
157
|
-
|
|
159
|
+
const output = hookOutput(harness, phase, decision, {
|
|
160
|
+
cliPath,
|
|
161
|
+
sessionId: request.sessionId,
|
|
162
|
+
});
|
|
163
|
+
if (output)
|
|
164
|
+
console.log(output);
|
|
158
165
|
}
|
|
159
166
|
else
|
|
160
167
|
throw new Error("Unsupported hook event");
|
package/dist/config.js
CHANGED
|
@@ -7,6 +7,8 @@ export function hookConfig(harness, cliPath) {
|
|
|
7
7
|
throw new Error("Unknown harness");
|
|
8
8
|
const hooks = {};
|
|
9
9
|
const matcher = "Bash|Read|Edit|Write|apply_patch|bash|powershell|view|read_file|write_file|edit|create|exec_command|shell";
|
|
10
|
+
// Copilot documents no MCP tool name format for hooks, so only Claude and Codex see MCP calls.
|
|
11
|
+
const preMatcher = harness === "copilot" ? matcher : `${matcher}|mcp__.*`;
|
|
10
12
|
const phases = [
|
|
11
13
|
"SessionStart",
|
|
12
14
|
"PreToolUse",
|
|
@@ -33,7 +35,11 @@ export function hookConfig(harness, cliPath) {
|
|
|
33
35
|
else
|
|
34
36
|
hooks[phase] = [
|
|
35
37
|
{
|
|
36
|
-
...(phase === "PreToolUse"
|
|
38
|
+
...(phase === "PreToolUse"
|
|
39
|
+
? { matcher: preMatcher }
|
|
40
|
+
: phase.startsWith("PostToolUse")
|
|
41
|
+
? { matcher }
|
|
42
|
+
: {}),
|
|
37
43
|
hooks: [
|
|
38
44
|
{
|
|
39
45
|
type: "command",
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Request } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Files this session created, keyed by a hash of the path with parent symlinks resolved, with the
|
|
4
|
+
* file's identity after the creating tool ran. Held in the session only, never shared or cached.
|
|
5
|
+
*/
|
|
6
|
+
export interface Stamp {
|
|
7
|
+
dev: number;
|
|
8
|
+
ino: number;
|
|
9
|
+
size: number;
|
|
10
|
+
mtimeMs: number;
|
|
11
|
+
}
|
|
12
|
+
export type CreatedFiles = Map<string, Stamp>;
|
|
13
|
+
/**
|
|
14
|
+
* A path an approved request may create or rewrite. `prior` is the identity that may carry over:
|
|
15
|
+
* the session's own file being edited in place, or its own file being moved there. Any other file
|
|
16
|
+
* found there afterwards must be a new inode.
|
|
17
|
+
*/
|
|
18
|
+
export interface Target {
|
|
19
|
+
path: string;
|
|
20
|
+
prior?: Stamp;
|
|
21
|
+
}
|
|
22
|
+
export declare const pathKey: (path: string) => string;
|
|
23
|
+
/** `path` with its parent symlinks resolved; the last component stays as written. */
|
|
24
|
+
export declare function located(cwd: string, path: string): string | undefined;
|
|
25
|
+
/** Identity of a regular file (not a symlink), or undefined. */
|
|
26
|
+
export declare function stamp(path: string): Stamp | undefined;
|
|
27
|
+
/** Runs `fn` with this session's created files visible to `createdBySession`. */
|
|
28
|
+
export declare function withCreated<T>(created: CreatedFiles | undefined, fn: () => T): T;
|
|
29
|
+
/** True when this session created `path` and nothing has replaced or changed it since. */
|
|
30
|
+
export declare function createdBySession(path: string): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Paths an approved request may create or rewrite: those that do not exist yet, or that are still
|
|
33
|
+
* the session's own file. Best effort; a path it misses only means a later deletion is classified
|
|
34
|
+
* instead of approved.
|
|
35
|
+
*/
|
|
36
|
+
export declare function creationTargets(request: Request, created: CreatedFiles): Target[];
|
|
37
|
+
/**
|
|
38
|
+
* The session's stamp for a target after its tool ran, or undefined. A file is the session's only
|
|
39
|
+
* if it is the prior inode (its own file, edited or moved there) or a new inode born after the
|
|
40
|
+
* approval. A rename keeps the birth time, so `mv notes.md x && touch x` does not qualify. Without
|
|
41
|
+
* a birth time from the platform, nothing new is recorded.
|
|
42
|
+
*/
|
|
43
|
+
export declare function settle(target: Target, approvedAt: number): Stamp | undefined;
|
|
44
|
+
//# sourceMappingURL=created.d.ts.map
|
package/dist/created.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstatSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import { canonical } from "./evidence.js";
|
|
5
|
+
import { parseShell } from "./shell.js";
|
|
6
|
+
export const pathKey = (path) => createHash("sha256").update(path).digest("hex");
|
|
7
|
+
/** Coarse filesystem clocks can stamp a new file slightly before the approval was given. */
|
|
8
|
+
const BIRTH_SLACK_MS = 100;
|
|
9
|
+
/** `path` with its parent symlinks resolved; the last component stays as written. */
|
|
10
|
+
export function located(cwd, path) {
|
|
11
|
+
try {
|
|
12
|
+
const lexical = resolve(cwd, path);
|
|
13
|
+
return join(canonical(dirname(lexical)), basename(lexical));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Identity of a regular file (not a symlink), or undefined. */
|
|
20
|
+
export function stamp(path) {
|
|
21
|
+
try {
|
|
22
|
+
const s = lstatSync(path);
|
|
23
|
+
return s.isFile() ? { dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs } : undefined;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function exists(path) {
|
|
30
|
+
try {
|
|
31
|
+
lstatSync(path);
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
let current;
|
|
39
|
+
/** Runs `fn` with this session's created files visible to `createdBySession`. */
|
|
40
|
+
export function withCreated(created, fn) {
|
|
41
|
+
const previous = current;
|
|
42
|
+
current = created;
|
|
43
|
+
try {
|
|
44
|
+
return fn();
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
current = previous;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** True when this session created `path` and nothing has replaced or changed it since. */
|
|
51
|
+
export function createdBySession(path) {
|
|
52
|
+
return current !== undefined && owns(current, path);
|
|
53
|
+
}
|
|
54
|
+
/** The session's recorded stamp for `path`, if the file there still matches it exactly. */
|
|
55
|
+
function owned(created, path) {
|
|
56
|
+
const recorded = path === undefined ? undefined : created.get(pathKey(path));
|
|
57
|
+
const now = recorded && stamp(path);
|
|
58
|
+
return recorded &&
|
|
59
|
+
now &&
|
|
60
|
+
now.dev === recorded.dev &&
|
|
61
|
+
now.ino === recorded.ino &&
|
|
62
|
+
now.size === recorded.size &&
|
|
63
|
+
now.mtimeMs === recorded.mtimeMs
|
|
64
|
+
? recorded
|
|
65
|
+
: undefined;
|
|
66
|
+
}
|
|
67
|
+
function owns(created, path) {
|
|
68
|
+
return owned(created, path) !== undefined;
|
|
69
|
+
}
|
|
70
|
+
const WRITE_TOOLS = new Set(["Write", "create", "write_file", "Edit", "edit"]);
|
|
71
|
+
/**
|
|
72
|
+
* The allowlist for shell scripts that record creations. A new inode proves nothing about its
|
|
73
|
+
* content (`gzip notes.md && touch notes.md.gz`, `git stash pop && touch x`), so every simple
|
|
74
|
+
* command must be one of these, in the form the checks below accept, or nothing is recorded.
|
|
75
|
+
* No `cd` (nor `pushd`, `popd`, `chdir`): whether a skipped `true || cd sub` runs cannot be told
|
|
76
|
+
* from the text, so a directory change makes the script record nothing.
|
|
77
|
+
*/
|
|
78
|
+
const CREATING = new Set(["touch", "tee", "cp", "mv", "pwd", "echo", "printf", "ls", "true"]);
|
|
79
|
+
/** Absolute directories whose `touch`, `cp`, ... are the system tools, not a lookalike script. */
|
|
80
|
+
const SYSTEM_BIN = /^\/(?:usr\/(?:local\/)?)?bin\/[^/]+$|^\/opt\/homebrew\/bin\/[^/]+$/;
|
|
81
|
+
/**
|
|
82
|
+
* A path word the shell passes through unchanged. A leading `~` or `=` (zsh's command path) and a
|
|
83
|
+
* `$`, glob or brace anywhere could expand to something else, so such a word is unprovable.
|
|
84
|
+
*/
|
|
85
|
+
function literal(word) {
|
|
86
|
+
return (word.length > 0 &&
|
|
87
|
+
!/^[~=]/.test(word) &&
|
|
88
|
+
!/[$*?[\]{}\\]/.test(word) &&
|
|
89
|
+
// `link/../x` is resolved from the link's target by the kernel but as `./x` by `resolve()`.
|
|
90
|
+
!word.split("/").some((part, i) => part === ".." || (part === "." && i > 0)));
|
|
91
|
+
}
|
|
92
|
+
/** The allowlisted program `word` names, or undefined (a relative path may be any script). */
|
|
93
|
+
function program(word) {
|
|
94
|
+
if (!word || (word.includes("/") && !SYSTEM_BIN.test(word)))
|
|
95
|
+
return undefined;
|
|
96
|
+
const name = basename(word);
|
|
97
|
+
return CREATING.has(name) ? name : undefined;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Creation targets of a plain script, or undefined when any command is not provably on the
|
|
101
|
+
* allowlist. A substitution, process substitution, heredoc, input or descriptor redirect,
|
|
102
|
+
* expandable path word, assignment, wrapper (`env`, `xargs`, `time`, `nice`, `command`), nested
|
|
103
|
+
* shell or unknown option makes the whole script record
|
|
104
|
+
* nothing; so does `mv` or `cp` from a file the session does not own when the hook runs (an
|
|
105
|
+
* earlier command in the same script cannot confer ownership).
|
|
106
|
+
*/
|
|
107
|
+
function shellTargets(pipelines, start, created) {
|
|
108
|
+
const found = [];
|
|
109
|
+
const cwd = start;
|
|
110
|
+
const add = (path, prior) => {
|
|
111
|
+
const at = literal(path) ? located(cwd, path) : undefined;
|
|
112
|
+
if (!at)
|
|
113
|
+
return false;
|
|
114
|
+
found.push({ path: at, ...(prior ? { prior } : {}) });
|
|
115
|
+
return true;
|
|
116
|
+
};
|
|
117
|
+
for (const stages of pipelines)
|
|
118
|
+
for (const c of stages) {
|
|
119
|
+
// parseShell already refuses heredocs and here-strings, so `subs` and `env` are what remain.
|
|
120
|
+
if (c.subs.length || c.env.length)
|
|
121
|
+
return undefined;
|
|
122
|
+
const name = program(c.argv[0]);
|
|
123
|
+
if (!name)
|
|
124
|
+
return undefined;
|
|
125
|
+
const args = c.argv.slice(1);
|
|
126
|
+
const flags = args.filter((word) => word.startsWith("-"));
|
|
127
|
+
const words = args.filter((word) => !word.startsWith("-"));
|
|
128
|
+
// Only output redirects to the script's own targets: `tee y < notes.md` reads a user's file,
|
|
129
|
+
// and `<`, `>&` and the like may carry content the session did not write.
|
|
130
|
+
for (const r of c.redirects) {
|
|
131
|
+
if (r.op !== ">" && r.op !== ">>")
|
|
132
|
+
return undefined;
|
|
133
|
+
if (r.target !== "/dev/null" && !add(r.target))
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
if (name === "touch") {
|
|
137
|
+
if (flags.length)
|
|
138
|
+
return undefined;
|
|
139
|
+
for (const word of words)
|
|
140
|
+
if (!add(word))
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
else if (name === "tee") {
|
|
144
|
+
if (flags.some((flag) => flag !== "-a"))
|
|
145
|
+
return undefined;
|
|
146
|
+
for (const word of words)
|
|
147
|
+
if (!add(word))
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
else if (name === "cp" || name === "mv") {
|
|
151
|
+
if (flags.some((flag) => flag !== "-f" && flag !== "-v") || words.length !== 2)
|
|
152
|
+
return undefined;
|
|
153
|
+
// Only from a file the session owns now: `mv` keeps its inode, `cp` copies its content.
|
|
154
|
+
const from = words[0];
|
|
155
|
+
const source = literal(from) ? owned(created, located(cwd, from)) : undefined;
|
|
156
|
+
if (!source || !add(words[1], name === "mv" ? source : undefined))
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return found;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Paths an approved request may create or rewrite: those that do not exist yet, or that are still
|
|
164
|
+
* the session's own file. Best effort; a path it misses only means a later deletion is classified
|
|
165
|
+
* instead of approved.
|
|
166
|
+
*/
|
|
167
|
+
export function creationTargets(request, created) {
|
|
168
|
+
const input = request.input;
|
|
169
|
+
const found = [];
|
|
170
|
+
const add = (cwd, path, prior) => {
|
|
171
|
+
const at = located(cwd, path);
|
|
172
|
+
if (at)
|
|
173
|
+
found.push({ path: at, ...(prior ? { prior } : {}) });
|
|
174
|
+
};
|
|
175
|
+
if (WRITE_TOOLS.has(request.tool)) {
|
|
176
|
+
const file = input.file_path ?? input.path;
|
|
177
|
+
if (typeof file === "string")
|
|
178
|
+
add(request.cwd, file);
|
|
179
|
+
}
|
|
180
|
+
else if (request.tool === "apply_patch" && typeof input.command === "string") {
|
|
181
|
+
let source;
|
|
182
|
+
for (const line of input.command.split("\n")) {
|
|
183
|
+
if (line.startsWith("*** Add File: "))
|
|
184
|
+
add(request.cwd, line.slice(14));
|
|
185
|
+
if (line.startsWith("*** Update File: ")) {
|
|
186
|
+
source = located(request.cwd, line.slice(17));
|
|
187
|
+
if (source)
|
|
188
|
+
found.push({ path: source });
|
|
189
|
+
}
|
|
190
|
+
// A move keeps the source's content, so the target is the session's only if the source was.
|
|
191
|
+
const moved = owned(created, source);
|
|
192
|
+
if (line.startsWith("*** Move to: ") && moved)
|
|
193
|
+
add(request.cwd, line.slice(13), moved);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
else {
|
|
197
|
+
const command = input.command ?? input.cmd;
|
|
198
|
+
const pipelines = typeof command === "string" ? parseShell(command) : undefined;
|
|
199
|
+
const targets = pipelines && shellTargets(pipelines, request.cwd, created);
|
|
200
|
+
if (!targets)
|
|
201
|
+
return [];
|
|
202
|
+
found.push(...targets);
|
|
203
|
+
}
|
|
204
|
+
const unique = new Map();
|
|
205
|
+
for (const target of found) {
|
|
206
|
+
// Only a path that is new, or still exactly the session's file, can become or stay its own.
|
|
207
|
+
const own = owned(created, target.path);
|
|
208
|
+
if (exists(target.path) && !own)
|
|
209
|
+
continue;
|
|
210
|
+
const prior = target.prior ?? own ?? unique.get(target.path)?.prior;
|
|
211
|
+
unique.set(target.path, { path: target.path, ...(prior ? { prior } : {}) });
|
|
212
|
+
}
|
|
213
|
+
return [...unique.values()];
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The session's stamp for a target after its tool ran, or undefined. A file is the session's only
|
|
217
|
+
* if it is the prior inode (its own file, edited or moved there) or a new inode born after the
|
|
218
|
+
* approval. A rename keeps the birth time, so `mv notes.md x && touch x` does not qualify. Without
|
|
219
|
+
* a birth time from the platform, nothing new is recorded.
|
|
220
|
+
*/
|
|
221
|
+
export function settle(target, approvedAt) {
|
|
222
|
+
let s;
|
|
223
|
+
try {
|
|
224
|
+
s = lstatSync(target.path);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
if (!s.isFile())
|
|
230
|
+
return undefined;
|
|
231
|
+
const now = { dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs };
|
|
232
|
+
if (target.prior && now.dev === target.prior.dev && now.ino === target.prior.ino)
|
|
233
|
+
return now;
|
|
234
|
+
return s.birthtimeMs > 0 && s.birthtimeMs >= approvedAt - BIRTH_SLACK_MS ? now : undefined;
|
|
235
|
+
}
|
|
236
|
+
//# sourceMappingURL=created.js.map
|