@agent-corpus/policy-manager 0.4.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 CHANGED
@@ -46,6 +46,18 @@ Setup merges only the managed hook definitions. Existing custom hooks, permissio
46
46
 
47
47
  Start a new session after setup. Codex still requires explicit review and trust through `/hooks`; setup does not grant that trust. Existing sandbox controls and host permission rules continue to apply. Ambiguous requests retain the documented classification or human fallback; setup does not enable automatic AI fallback across unsupported native interfaces.
48
48
 
49
+ ### Codex hook trust
50
+
51
+ Codex runs a non-managed hook only after you review and trust its exact definition, and setup never grants that trust. After `setup-hook-codex`, start Codex and open `/hooks`, review the five policy-manager hooks, and trust them. Until then Codex skips them and prints a warning at startup, so no policy decision is made.
52
+
53
+ Trust is recorded per hook in `config.toml` under `[hooks.state."<hooks.json path>:<event>:0:0"]` as `trusted_hash = "sha256:<hex>"`. The hash covers the event, the matcher, and the hook's command and timeout, so:
54
+
55
+ - Trust is tied to the command text only: Codex hashes the command line, not the script behind it. An upgrade that keeps the same CLI path (for example an in-place `npm install -g` upgrade) keeps trust while the code behind the hooks changes, so review a new version before upgrading in place. An upgrade that changes the command, such as installing into a per-version directory or a Node upgrade that changes `process.execPath` (it is part of the command), makes Codex mark all five hooks as changed and skip them until you trust them again. Re-running `setup-hook-codex` for the same installed version changes nothing and keeps trust.
56
+ - Codex hashes the effective timeout, which it limits to 1 to 3 seconds for `SessionEnd`. The generated `SessionEnd` timeout is 3 seconds, the same effective value as the earlier 8, so changing it did not by itself invalidate trust.
57
+ - `--dangerously-bypass-hook-trust` runs enabled hooks without persisted trust for one invocation. Use it only for automation that already vets the hook source.
58
+
59
+ Codex hook trust was checked against Codex CLI 0.167.1; see the [Codex hooks reference](https://developers.openai.com/codex/hooks) for the release behavior.
60
+
49
61
  ## Request protocol
50
62
 
51
63
  Pass one JSON object on standard input:
@@ -60,7 +72,7 @@ Pass one JSON object on standard input:
60
72
  }
61
73
  ```
62
74
 
63
- Run `policy-manager review codex session-example`. The response includes `decision` (`approve` or `human`), `category`, `reason`, `requestHash`, `cache`, and `cached`. The library exports the same evaluator.
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.
64
76
 
65
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`:
66
78
 
@@ -68,7 +80,38 @@ The session's policy-manager agent returns the following object for an ambiguous
68
80
  { "requestHash": "<exact hash from review>", "category": "unknown", "confidence": 0.4 }
69
81
  ```
70
82
 
71
- 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
+
85
+ ## AI classification of ambiguous requests (experiment)
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
+
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.
90
+
91
+ How a hook call flows (Claude Code, Codex and Copilot `PreToolUse`):
92
+
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.
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.
96
+
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):
98
+
99
+ - Credential and secret retrieval, protected paths and configuration such as the policy profile and hook settings (category `sensitive`).
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.
101
+ - Commands matching the profile's `humanPatterns`.
102
+ - Writes outside a linked feature worktree (main clones and protected branches).
103
+ - Cloud operations outside the read catalog. The profile's `cloudWrites: "allow"` is the way to automate these.
104
+ - Requests the engine cannot trust: incomplete or invalid requests, a different execution directory, unrecognized patches, and environment or loader overrides such as `LD_PRELOAD`.
105
+
106
+ **Known weakness.** The classifier is the working model's own policy-manager agent, and the working model records its answer, so a model that wanted to approve itself could. Confidence is self-reported. This is why the experiment records everything and is reviewed after two days of use rather than trusted.
107
+
108
+ **Recording.** The audit log gets `classification-requested` (with the command, redacted: secret-looking values, URL credentials and long tokens are replaced and the text is capped), `classification` (category, confidence, recoverable, redacted rationale), `decision` (with the stage `requested`, `approved`, `denied` or `fallback`), and `classification-fallback` (with the reason `unavailable`, `invalid-result` or `limit`). Review them across sessions:
109
+
110
+ ```sh
111
+ policy-manager review-classifications [--since 2026-11-12T00:00:00Z] [--json]
112
+ ```
113
+
114
+ 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.
72
115
 
73
116
  ## Policy
74
117
 
@@ -92,7 +135,8 @@ Without a profile the engine is strict (everything above). An organization can i
92
135
  "mode": "permissive",
93
136
  "cloudWrites": "human",
94
137
  "humanPatterns": ["^npm install"],
95
- "scratchRoots": ["/tmp"]
138
+ "scratchRoots": ["/srv/scratch"],
139
+ "mcpReadOnly": ["mcp__github__get_issue", "mcp__github__list_pull_requests"]
96
140
  }
97
141
  ```
98
142
 
@@ -103,7 +147,15 @@ policy-manager profile install policy.json # writes ~/.config/agent-corpus/pol
103
147
 
104
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`.
105
149
 
106
- `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 still sends these to a human: deletion (`rm`, `find -delete`, `xargs rm`), `sudo`, `git reset --hard`, `git clean`, forced or mirror pushes, discarding checkouts and restores, 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 and `scratchRoots`, and protected or credential paths. `humanPatterns` adds organization-specific expressions.
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.
107
159
 
108
160
  #### Shell syntax in permissive mode
109
161
 
@@ -112,13 +164,46 @@ Every command that could run is judged, not only the first. Understood: `;`, new
112
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.
113
165
  - **Command substitution** and process substitution run first: the inner command is judged with the same rules.
114
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.
115
- - **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.
116
- - **Still sent to a human:** brace expansion, arithmetic (`$((`, `$[`, `(( ))`), `${X:-y}` and other parameter forms, `$'...'`, function 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.
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. |
117
189
 
118
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.
119
191
 
120
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.
121
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
+
122
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.
123
208
 
124
209
  ## Service, cache, and logs
@@ -129,7 +214,7 @@ The cache belongs to the service process and is scoped to harness plus session I
129
214
 
130
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.
131
216
 
132
- 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`, so human recommendations add context and leave native permission handling unchanged.
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.
133
218
 
134
219
  ## Audit API and reported outcomes
135
220
 
@@ -159,9 +244,9 @@ Or an execution report:
159
244
  }
160
245
  ```
161
246
 
162
- Human responses are `approved` or `denied`. Execution statuses are `completed`, `succeeded`, `failed`, or `cancelled`. Reports use the source `policy-manager.adapter-report`. They are observations declared by the caller and never modify permission decisions or caches. The API does not authenticate a human identity. A denial policy remains a human decision even after an approval report is recorded.
247
+ Human responses are `approved` or `denied`. Execution statuses are `completed`, `succeeded`, `failed`, `cancelled`, or `unknown`. `unknown` is recorded for Codex when the hook payload exposes no exit status, which is the usual case for a Bash result. Reports use the source `policy-manager.adapter-report`. They are observations declared by the caller and never modify permission decisions or caches. The API does not authenticate a human identity. A denial policy remains a human decision even after an approval report is recorded.
163
248
 
164
- Generated post-tool hooks record execution reports for the supported tool matcher. Claude and Copilot also get failure hooks. Codex uses `PostToolUse`, which can carry nonzero exit codes. When an exit code is absent, the adapter records `completed` rather than inventing success. Output text and error bodies are discarded. Human responses require an explicit report from the host; the native hooks do not provide a universal human-response signal.
249
+ Generated post-tool hooks record execution reports for the supported tool matcher. Claude and Copilot also get failure hooks. Codex uses `PostToolUse`, which also runs after commands that exit non-zero. Codex sends a Bash result as the command's output text only, with no exit code and no duration, so the adapter records `unknown` for Codex rather than `completed` or `succeeded`; a structured `exit_code` is used when one is present. Claude and Copilot record `completed` when an exit code is absent. Output text and error bodies are discarded. Human responses require an explicit report from the host; the native hooks do not provide a universal human-response signal.
165
250
 
166
251
  The shared logger redacts structured sensitive fields, validates events, locks concurrent access, and flushes each append. Queries cover active and rotated segments. Busy storage, a stale lock, incomplete records, capacity limits, or write failures prevent automatic approval. The initial API is a library plus CLI; an additional resident logging server is deferred until another consumer needs one.
167
252
 
@@ -172,7 +257,7 @@ Tests exercise real service processes and native-shaped hook payloads for all th
172
257
  Verified documentation, November 5, 2026:
173
258
 
174
259
  - [Claude Code hooks](https://code.claude.com/docs/en/hooks)
175
- - [Codex hooks](https://learn.chatgpt.com/docs/hooks)
260
+ - [Codex hooks](https://developers.openai.com/codex/hooks)
176
261
  - [Copilot hooks](https://docs.github.com/en/copilot/reference/hooks-reference)
177
262
 
178
263
  Exit codes: 0 means a protocol response was returned; inspect `decision` before acting. 1 means invalid input or service failure. Pre-tool hook failures use 2. Diagnostics use stderr and contain no raw request data.
@@ -1,5 +1,17 @@
1
- import type { Decision, OutcomeReport, Request } from "./types.js";
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
- export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision): Record<string, unknown>;
3
+ export interface HookContext {
4
+ cliPath: string;
5
+ sessionId: string;
6
+ }
7
+ /**
8
+ * The exact command the model is told to run to record a classification. A here-string, not a
9
+ * pipe: `printf ... | node ...` is "piping into an interpreter" and is itself escalated, so the
10
+ * round trip could never finish. A test evaluates this exact string and requires `approve`.
11
+ */
12
+ export declare function classifyCommand(harness: Request["harness"], context?: HookContext, json?: string): string;
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;
4
16
  export declare function executionReport(request: Request, phase: string, payload: Record<string, unknown>): OutcomeReport;
5
17
  //# sourceMappingURL=adapters.d.ts.map
package/dist/adapters.js CHANGED
@@ -1,4 +1,6 @@
1
- import { hash } from "./policy.js";
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")
@@ -15,7 +17,57 @@ export function normalize(harness, payload) {
15
17
  input: args,
16
18
  };
17
19
  }
18
- export function hookResponse(harness, phase, decision) {
20
+ /**
21
+ * The exact command the model is told to run to record a classification. A here-string, not a
22
+ * pipe: `printf ... | node ...` is "piping into an interpreter" and is itself escalated, so the
23
+ * round trip could never finish. A test evaluates this exact string and requires `approve`.
24
+ */
25
+ export function classifyCommand(harness, context, json = "<json>") {
26
+ // A Windows path (`D:\\a\\cli.js`) is written with forward slashes: Node accepts them, and a
27
+ // backslash inside double quotes is a shell escape the policy cannot judge, which would
28
+ // escalate the command that finishes the round trip.
29
+ const cliPath = context && /^[A-Za-z]:\\/.test(context.cliPath)
30
+ ? context.cliPath.replace(/\\/g, "/")
31
+ : context?.cliPath;
32
+ const safe = context &&
33
+ cliPath &&
34
+ /^[^"$`\\\n']+$/.test(cliPath) &&
35
+ /^[A-Za-z0-9_.-]+$/.test(context.sessionId);
36
+ return safe
37
+ ? `node "${cliPath}" classify ${harness} ${context.sessionId} <<< '${json}'`
38
+ : `policy-manager classify ${harness} <session-id> <<< '${json}'`;
39
+ }
40
+ /** What a blocked ambiguous request tells the model to do. Never ask for human approval here. */
41
+ function classifyInstruction(harness, decision, context) {
42
+ const command = classifyCommand(harness, context);
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.`;
44
+ }
45
+ export function hookResponse(harness, phase, decision, context) {
46
+ if (decision.decision === "native")
47
+ return {};
48
+ if (decision.decision === "deny") {
49
+ const reason = decision.classification === "requested"
50
+ ? classifyInstruction(harness, decision, context)
51
+ : decision.reason;
52
+ if (phase === "PermissionRequest")
53
+ return harness === "copilot"
54
+ ? {}
55
+ : {
56
+ hookSpecificOutput: {
57
+ hookEventName: phase,
58
+ decision: { behavior: "deny", message: reason },
59
+ },
60
+ };
61
+ return harness === "copilot"
62
+ ? { permissionDecision: "deny", permissionDecisionReason: reason }
63
+ : {
64
+ hookSpecificOutput: {
65
+ hookEventName: phase,
66
+ permissionDecision: "deny",
67
+ permissionDecisionReason: reason,
68
+ },
69
+ };
70
+ }
19
71
  if (harness === "copilot") {
20
72
  if (phase === "PermissionRequest")
21
73
  return decision.decision === "approve" ? { behavior: "allow" } : {};
@@ -27,15 +79,31 @@ export function hookResponse(harness, phase, decision) {
27
79
  return decision.decision === "approve"
28
80
  ? { hookSpecificOutput: { hookEventName: phase, decision: { behavior: "allow" } } }
29
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.
30
85
  if (decision.decision === "approve")
31
- return { hookSpecificOutput: { hookEventName: phase, permissionDecision: "allow" } };
32
- if (harness === "codex")
86
+ return harness === "codex"
87
+ ? {}
88
+ : { hookSpecificOutput: { hookEventName: phase, permissionDecision: "allow" } };
89
+ // Codex parses permissionDecision "ask" but does not support it: it marks the hook failed and
90
+ // 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
+ // so the reason says so; the one in-session way through is classifying an ambiguous cloud
93
+ // request (needsClassification), which a retry then sees as approved. Codex's own approval prompt
94
+ // (PermissionRequest, above) still handles the requests it would ask about.
95
+ if (harness === "codex") {
96
+ 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, ask the user to run it themselves or to change the policy profile."
98
+ : "Approving it in this session does not unblock it: ask the user to run it themselves or to change the policy profile.";
33
99
  return {
34
100
  hookSpecificOutput: {
35
101
  hookEventName: phase,
36
- additionalContext: `${decision.reason}. Request ${decision.requestHash}. The policy manager grants no approval. Classify ambiguous requests with the session policy-manager agent. Preserve the native human approval flow.`,
102
+ permissionDecision: "deny",
103
+ permissionDecisionReason: `Policy manager: ${decision.reason}. This needs a human decision and was not run. ${next} Request ${decision.requestHash}.`,
37
104
  },
38
105
  };
106
+ }
39
107
  return {
40
108
  hookSpecificOutput: {
41
109
  hookEventName: phase,
@@ -44,6 +112,11 @@ export function hookResponse(harness, phase, decision) {
44
112
  },
45
113
  };
46
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
+ }
47
120
  export function executionReport(request, phase, payload) {
48
121
  const response = payload.tool_response ?? payload.toolResponse ?? payload.tool_result ?? payload.toolResult;
49
122
  const result = response && typeof response === "object" ? response : {};
@@ -51,16 +124,22 @@ export function executionReport(request, phase, payload) {
51
124
  const exitCode = typeof code === "number" && Number.isSafeInteger(code) && Math.abs(code) <= 2147483647
52
125
  ? code
53
126
  : undefined;
127
+ // Codex sends a Bash result as the output text alone: no exit code and no duration, even for a
128
+ // command that exited non-zero. That is not "completed"; the outcome is unknown. Claude and
129
+ // Copilot keep their existing behaviour.
130
+ const unknown = exitCode === undefined && request.harness === "codex";
54
131
  const duration = payload.duration_ms ?? payload.durationMs;
55
132
  return {
56
- requestHash: hash(request),
133
+ requestHash: requestHash(request),
57
134
  event: "execution-result",
58
135
  status: phase === "PostToolUseFailure"
59
136
  ? payload.is_interrupt === true
60
137
  ? "cancelled"
61
138
  : "failed"
62
139
  : exitCode === undefined
63
- ? "completed"
140
+ ? unknown
141
+ ? "unknown"
142
+ : "completed"
64
143
  : exitCode === 0
65
144
  ? "succeeded"
66
145
  : "failed",
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: hash(request),
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,10 +3,12 @@ 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, hookResponse, normalize } from "./adapters.js";
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";
11
+ import { formatReview, reviewClassifications, sessionDirectories } from "./review.js";
10
12
  import { send, serve, start, stop } from "./service.js";
11
13
  import { SetupError, setupHook } from "./setup.js";
12
14
  const usage = `policy-manager usage [--json]
@@ -20,6 +22,7 @@ policy-manager config <claude|codex|copilot> <absolute-installed-cli-path>
20
22
  policy-manager profile validate <file> # check a policy profile without installing it
21
23
  policy-manager profile install <file> # install it to the user config directory outside Git
22
24
  policy-manager replay <transcript-dir-or-file...> [--profile <file>] [--files <n>] # approval rate over recorded Bash commands; nothing is executed
25
+ policy-manager review-classifications [--since <iso-time>] [--dir <session-dir>...] [--json] # risk review of AI-classified ambiguous requests
23
26
  policy-manager stop <claude|codex|copilot> <session-id>
24
27
  A per-session background service checks policy and writes private temporary audit.jsonl logs.
25
28
  AI classification comes from the session's policy-manager agent, never an external API.
@@ -65,6 +68,7 @@ try {
65
68
  const summary = {
66
69
  mode: profile.mode,
67
70
  cloudWrites: profile.cloudWrites,
71
+ mcpReadOnly: profile.mcpReadOnly.length,
68
72
  digest: profile.digest,
69
73
  };
70
74
  if (harnessArg === "install") {
@@ -90,12 +94,26 @@ try {
90
94
  const report = replayTranscripts(positionals, profile, Number(values.files ?? 50));
91
95
  const pct = (n) => `${((100 * n) / Math.max(report.commands, 1)).toFixed(1)}%`;
92
96
  console.log(`${report.commands} unique commands; approved ${pct(report.approved)} (strict ${pct(report.strictApproved)})`);
97
+ const humans = report.commands - report.approved;
98
+ console.log(`${report.classified} of ${humans} escalations go to AI classification instead of a person; ${humans - report.classified} stay with a human by rule`);
93
99
  for (const row of report.reasons.slice(0, 15)) {
94
100
  console.log(`${row.count}\t${row.reason}`);
95
101
  for (const example of row.examples)
96
102
  console.log(`\t ${example}`);
97
103
  }
98
104
  }
105
+ else if (action === "review-classifications") {
106
+ const { values } = parseArgs({
107
+ args: args.slice(1),
108
+ options: {
109
+ since: { type: "string" },
110
+ dir: { type: "string", multiple: true },
111
+ json: { type: "boolean" },
112
+ },
113
+ });
114
+ const review = await reviewClassifications(sessionDirectories(values.dir ?? []), values.since);
115
+ console.log(values.json ? JSON.stringify(review, null, 2) : formatReview(review));
116
+ }
99
117
  else if (action === "serve")
100
118
  await serve(harness, phase ?? "");
101
119
  else if (action === "stop")
@@ -120,7 +138,7 @@ try {
120
138
  else {
121
139
  const directory = await start(harness, request.sessionId, cliPath);
122
140
  if (phase === "SessionStart") {
123
- const context = `Policy service started. Audit log: ${join(directory, "audit.jsonl")}. Native hooks route tool and permission requests directly to the deterministic service. For ambiguous requests, use a configured policy-manager agent or retain native human approval. 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.`;
124
142
  console.log(JSON.stringify(harness === "copilot"
125
143
  ? { additionalContext: context }
126
144
  : { hookSpecificOutput: { hookEventName: phase, additionalContext: context } }));
@@ -136,8 +154,14 @@ try {
136
154
  const decision = (await send(harness, request.sessionId, {
137
155
  action: "review",
138
156
  request,
157
+ phase,
139
158
  }));
140
- console.log(JSON.stringify(hookResponse(harness, phase, decision)));
159
+ const output = hookOutput(harness, phase, decision, {
160
+ cliPath,
161
+ sessionId: request.sessionId,
162
+ });
163
+ if (output)
164
+ console.log(output);
141
165
  }
142
166
  else
143
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",
@@ -16,6 +18,8 @@ export function hookConfig(harness, cliPath) {
16
18
  "SessionEnd",
17
19
  ];
18
20
  for (const phase of phases) {
21
+ // Codex limits SessionEnd to 1 to 3 seconds and warns about anything longer.
22
+ const timeout = harness === "codex" && phase === "SessionEnd" ? 3 : 8;
19
23
  if (harness === "copilot") {
20
24
  const event = phase[0]?.toLowerCase() + phase.slice(1);
21
25
  hooks[event] = [
@@ -24,19 +28,23 @@ export function hookConfig(harness, cliPath) {
24
28
  ...(phase === "PreToolUse" || phase.startsWith("PostToolUse") ? { matcher } : {}),
25
29
  exec: process.execPath,
26
30
  args: [cliPath, "hook", harness, phase, managedHookFlag],
27
- timeoutSec: 8,
31
+ timeoutSec: timeout,
28
32
  },
29
33
  ];
30
34
  }
31
35
  else
32
36
  hooks[phase] = [
33
37
  {
34
- ...(phase === "PreToolUse" || phase.startsWith("PostToolUse") ? { matcher } : {}),
38
+ ...(phase === "PreToolUse"
39
+ ? { matcher: preMatcher }
40
+ : phase.startsWith("PostToolUse")
41
+ ? { matcher }
42
+ : {}),
35
43
  hooks: [
36
44
  {
37
45
  type: "command",
38
46
  command: `"${process.execPath}" "${cliPath}" hook ${harness} ${phase} ${managedHookFlag}`,
39
- timeout: 8,
47
+ timeout,
40
48
  },
41
49
  ],
42
50
  },
@@ -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