@agent-corpus/policy-manager 0.8.0 → 0.10.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
@@ -42,6 +42,8 @@ The canonical form is `policy-manager setup-hook <claude|codex|copilot>`. Each a
42
42
 
43
43
  Setup merges only the managed hook definitions. Existing custom hooks, permissions, settings, allow rules, and deny rules remain. Repeated setup is idempotent. Package upgrades replace hooks carrying the managed marker; unmarked manual entries remain. Existing settings receive an owner-only backup, and updates use a temporary file with atomic replacement. Invalid JSON, unsupported schemas, symbolic links, concurrent setup, and detected concurrent edits fail without replacing the existing settings.
44
44
 
45
+ Setup also installs a small launcher named `pm` that runs this CLI, so a user can type `pm approve --last`: `~/.local/bin/pm` (a Node script, mode 0755) on macOS and Linux, `%LOCALAPPDATA%\agent-corpus\bin\pm.cmd` on Windows. It carries a marker with the version that wrote it. Setup replaces only a launcher it wrote for the same or an older version; a newer one, or a `pm` it did not write, is left alone and reported. Setup never edits `PATH`: the result's `shim.onPath` says whether the directory is on it, and the next steps say how to add it. `--shim-dir <directory>` puts the launcher elsewhere; with `--config-dir` and no `--shim-dir`, setup leaves the launcher alone.
46
+
45
47
  `--dry-run` prints the target path, proposed managed hooks, and next steps without writing files or printing existing settings. `--config-dir <directory>` selects a harness configuration root for portable profiles or testing. Defaults respect `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, and `COPILOT_HOME`, then use the standard user directories listed above. Setup refuses to activate an entrypoint inside a Git checkout, including an npm link into a checkout. Source builds can preview with `--dry-run`.
46
48
 
47
49
  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.
@@ -116,13 +118,24 @@ The report shows how many ambiguous requests were approved, denied, fell back to
116
118
 
117
119
  ## Approving from the terminal
118
120
 
119
- Codex cannot ask in `PreToolUse`, so a request that needs a person is denied, and approving it in chat does not change the decision. The deny reason gives the command the user runs in their own terminal:
121
+ Codex cannot ask in `PreToolUse`, so a request that needs a person is denied, and approving it in chat does not change the decision. The deny reason leads with what to do:
122
+
123
+ ```text
124
+ ⏸ Waiting for your approval. Not run: Protected path requires human approval.
125
+ Run in your own terminal, then say "retry":
126
+ pm approve --last
127
+ Add --session to also allow writes under /tmp/wt/.agent-config for the rest of this session.
128
+ Agent: stop now and end your turn; approving it in chat does not unblock it. Show the user the command above exactly, in a code block. Never run it yourself.
129
+ Request <64-character request hash>.
130
+ ```
131
+
132
+ `pm approve --last` approves the newest request that any running policy session of this user sent to a person in the last 15 minutes. It shows the harness and session, the tool, the redacted request, the rule, and (with `--session`) the scope, then asks y/N; it refuses to run without an interactive terminal. To approve one exact request instead:
120
133
 
121
134
  ```sh
122
135
  policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session]
123
136
  ```
124
137
 
125
- It shows the tool, the redacted request and the rule, and asks for confirmation; it refuses to run without an interactive terminal. The request must be one this session sent to a person in the last 15 minutes. Then the agent retries the same request unchanged.
138
+ The deny reason uses `pm` when the managed launcher (see **Install native hooks**) for this version is installed and its directory is on `PATH`, and `node "<cli>" approve --last` otherwise. Then the agent retries the same request unchanged.
126
139
 
127
140
  - **Once (default).** The next review of that exact request is approved, once per hook phase (`PreToolUse`, then `PermissionRequest`), and the grant is spent.
128
141
  - **`--session`.** Also approves later requests in this session that hit the same rule for the same scope: a protected-path write under the same protected root of the same checkout (`<worktree>/.agent-config`, not `.claude` or another worktree), the same `humanPatterns` entries in the same checkout, or, for other rules, the exact same command in the same checkout. `approve --session` prints the scope before asking. Shell commands are covered only when they are a single simple command, so nothing else in a script hides behind the rule. Credential and secret reads, possible unrecoverable loss (force pushes, deleting unmerged work) and requests whose effect the engine could not determine (category `unknown`, such as an interpreter script) are approved once only, even with `--session`; the deny reason offers `--session` only when it applies.
@@ -194,6 +207,46 @@ Every command that could run is judged, not only the first. Understood: `;`, new
194
207
  - **Variables after an assignment chain.** `S=/abs && H=x; use $S $H` treats `H` as assigned: a bare assignment with no command substitution and no redirection cannot fail, so the `&&` chain always reaches `H=x`. This holds only for uppercase names the shell does not reserve. zsh's lowercase specials, read-only or numeric specials (`UID`, `SECONDS`, `BASH*`, `ZSH*`, ...), a value with `$(...)`, `export NAME=value` and a prefix assignment (`X=1 cmd`) can fail or do not persist, so the chain may stop there and a later name is still an environment variable. A value used as the program (`P=rm; $P -rf x`) is resolved and judged as that program. The remaining window is a `readonly` or `typeset -i` that the user's shell startup files set on a name outside that list (such as `HISTFILE`): bash 5 in default mode may then return 1 without exiting, so the chain could stop there. That is outside what the script controls and is accepted.
195
208
  - **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.
196
209
 
210
+ #### Harness tools approved by default
211
+
212
+ Under the permissive profile, a harness tool that is not a shell, file, patch or MCP tool is approved without a prompt or classification: task control (`TaskStop`, `TaskOutput`), scheduling the session's own wakeup, listing agents, loading tool schemas, asking the user, plan mode, and tools a harness adds later. Shell, file and patch tools (`Bash`, `exec_command`, `Read`, `Write`, `Edit`, `apply_patch`, `Grep`, `Glob`, `view_image`, and `Monitor`, which runs a command) always get the engine's checks. So does any tool that runs code, writes to a running command, or touches files, whether listed (Codex `shell_command`, `local_shell`, `write_stdin`; Copilot `write_bash`) or only named like one (a name containing `bash`, `shell`, `exec`, `stdin`, `command`, `repl`, `eval`, `python`, `run`, `file`, `delete`, `move`, `edit` and similar), so a new one fails closed. A false positive such as `BashOutput` only costs a classification. MCP tools follow `mcpReadOnly`. The strict profile approves none of them by default.
213
+
214
+ `toolsDeny` keeps chosen tools on today's path, an AI classification for each call: `{ "claude": ["SendMessage", "WebFetch"], "codex": [], "copilot": [] }`, exact names, at most 100 per harness. An unknown harness, a non-list, or a name that is not a tool name makes the profile invalid (strict). The built-in deny list is empty.
215
+
216
+ Each default approval's audit `decision` record carries `defaultTool` with the tool name. `review-classifications` lists these tools newest first by when each was first seen, so a tool a harness newly added is noticed and can be put in `toolsDeny`.
217
+
218
+ #### Credential helpers
219
+
220
+ Reading a credential always goes to a person, except through a script listed in `credentialHelpers` (permissive profile only). A helper reads a secret for one narrow job, such as posting a review as a GitHub App:
221
+
222
+ ```json
223
+ "credentialHelpers": [
224
+ {
225
+ "path": "tools/review-bot.mjs",
226
+ "remotes": ["github.com/example-org/"],
227
+ "args": [
228
+ ["--repo", "<repo>", "check"],
229
+ ["--repo", "<repo>", "gh", "api", "repos/<repo>/pulls/<int>/reviews", "--input", "<file>"],
230
+ ["--repo", "<repo>", "gh", "pr", "review", "<int>", "-R", "<repo>", ["--approve", "--comment"], "--body-file", "<file>"]
231
+ ]
232
+ }
233
+ ]
234
+ ```
235
+
236
+ `node <script> <args>` is approved, and named in the audit `decision` record as `credentialHelpers: ["<path>#<shape index>"]`, only when all of these hold:
237
+
238
+ - The checkout comes from a listed remote. `remotes` (required) lists normalized prefixes such as `github.com/example-org/`: a lowercase host, then at least an owner, where a trailing `/` makes it a prefix. The checkout's `remote.origin.url` (https, ssh or `git@host:` form, normalized to lowercase `host/owner/repo` without `.git`) must match one. It must equal what `git remote get-url origin` resolves, so no `url.*.insteadOf` rewrite applies, and there must be no `remote.origin.pushurl`. A clone of a local or other repository, or a `git init`, has an origin that does not match.
239
+ - The script, however it is named (relative, absolute, from another directory), is the regular file at `<checkout>/<path>` with no symlink on the way, tracked, and identical to the committed file on the default branch of `origin`. The branch is found by full ref name only (`refs/remotes/origin/HEAD` when it points into `refs/remotes/origin/`, else `refs/remotes/origin/main`), so a tag or branch named `origin/HEAD` cannot stand in for it, and every lookup ignores replace refs. The committed blob's bytes are compared in Node with the working file: an exact match, or, when the blob has no CR, a match once the file's CRLF line ends become LF (a `core.autocrlf` checkout). No clean filter or `.gitattributes` setting applies. A local edit makes it a different script.
240
+ - The arguments match one listed shape exactly, word for word. A token is a literal, a list of literal alternatives, or a word with placeholders: `<repo>` (`owner/name`, each part starting with a letter or digit), `<int>`, `<sha>` (7 to 40 hex digits), `<word>` (a letter or digit, then letters, digits, `_.-`), `<url>` (a `https://github.com/` URL), `<file>` (a path with no pattern or `~` characters and not under `/dev/`, inside the working checkout or a temp or scratch root, that passes the usual read check), or `<text>` (any one argument, only as a whole word). Profiles hold no regular expressions.
241
+ - No argument the shell would expand: an unquoted `*`, `?` or `[`, or a leading `~`. Quote a literal pattern (`--reason '*'`).
242
+ - No environment prefix, wrapper (`env`, `command`), input redirect, standard input or pipe into it.
243
+
244
+ The default-branch check trusts the local remote-tracking refs, so the engine refuses local writes that could move them or what they show: `git update-ref` on anything but a plain `refs/heads/*` or `refs/tags/*` name that is not a symbolic ref (so not `refs/remotes/*`, `refs/replace/*` or `HEAD`), `update-ref --stdin` or `--no-deref`, `symbolic-ref` with a name or target under `refs/remotes/`, a fetch from `.`, a path or a `file:` URL, a fetch whose refspec writes `refs/remotes/<remote>/<branch>` from anything but that branch of that configured remote, `--refmap`, and a push to `.` or a local path. (`remotes/<r>/<b>` counts as `refs/remotes/<r>/<b>`.) To keep the origin honest it also refuses `git remote add`, `set-url`, `rename`, `set-branches`, `remove` and `set-head`; `git config` writes outside a short list of safe keys, which covers `remote.*`, `url.*` and `include*`; `git clone` with `-c`/`--config`, `-o`/`--origin`, `--template`, `--separate-git-dir` or `--upload-pack`; and `git init --template` or `--separate-git-dir`. Direct writes into `.git/config`, `.git/worktrees/*/config` and `config.worktree` are refused as protected paths. A normal `git fetch origin [main | +pull/N/head:prN]`, and a plain clone from the listed remote, stay approved.
245
+
246
+ **This is an audit label, not yet a security boundary.** In a worktree the engine approves `node <script>` for a script it does not list without reading it ([#48](https://github.com/agent-corpus/tools/issues/48)), so an agent could run an unlisted script that reads the same secret. Until #48 lands, a helper approval records which listed helper ran; it does not stop an unlisted one.
247
+
248
+ Every other command in the same script is judged as usual. A script with a listed file name that fails any check (changed, untracked, outside a checkout, a symlink, other arguments) goes to a person as a credential read. A listed helper counts as creating no symlink, so a later temp write in the same script stays approvable. An entry's path must be repository-relative with `/` separators and no `.` or `..` segments; the list holds at most 20 helpers of 50 shapes each, and an invalid entry makes the profile invalid (strict).
249
+
197
250
  #### MCP read-only tools
198
251
 
199
252
  `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.
@@ -210,7 +263,7 @@ A listed tool is approved. Any other MCP tool gets no decision from the policy m
210
263
 
211
264
  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.
212
265
 
213
- Protected names (`.claude`, `.agent-config`, `AGENTS.md`, ...) are judged relative to the repository root, so a linked worktree under `<repo>/.claude/worktrees/<name>` is ordinary code while `<worktree>/.claude/settings.json` stays protected. `git config` is limited to a short allowlist of local, non-executable keys; hooks, aliases, credential helpers, URLs and `--global` always need a human. Read-only cloud verbs (`list`, `show`, `describe`, `get-*`) and `az boards query` (a WIQL read) are approved beyond the exact catalog unless the arguments name credentials or override the endpoint.
266
+ 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. For `--session`, a single shell command's scope comes from every word that could name a file it touches: non-option arguments, `--option=value` and `-oVALUE` values, and redirect targets (`>`, `>>`, `<`), so `printf x >> .agent-config/README.md` and `tee -a .agent-config/a` are covered like a patch, while a command that also names `AGENTS.md` or `.claude` is not. A variable assigned a single-quoted literal that is not one plain word (`Q='query($t: ID!)'`) is known only inside double quotes, so `gh api graphql -f query="$Q"` is judged on its value; an unquoted `$Q` stays unknown. Read-only cloud verbs (`list`, `show`, `describe`, `get-*`) and `az boards query` (a WIQL read) are approved beyond the exact catalog unless the arguments name credentials or override the endpoint.
214
267
 
215
268
  `git worktree remove --force <path>` is approved when `<path>` is a linked worktree of the repository (listed by `git worktree list`, never the main worktree), resolves strictly inside a `scratchRoots` entry or the system temp directory, lies outside the main checkout, and holds no other worktree; exactly one `-f`/`--force` may be given (a second one also removes a locked worktree), and not after a command that can create symlinks. A worktree under the main checkout (`.worktrees/x`) still needs a human. `git worktree prune` with only `-n`/`-v` is approved: it drops records of worktrees whose directories are already gone.
216
269
 
@@ -3,6 +3,8 @@ export declare function normalize(harness: Request["harness"], payload: Record<s
3
3
  export interface HookContext {
4
4
  cliPath: string;
5
5
  sessionId: string;
6
+ /** A managed `pm` launcher for this CLI is installed and on PATH. */
7
+ pmOnPath?: boolean;
6
8
  }
7
9
  /**
8
10
  * The exact command the model is told to run to record a classification. A here-string, not a
@@ -21,6 +23,13 @@ export declare function looksLikeClassifyRecord(command: string): boolean;
21
23
  export declare function looksLikeApproveGrant(command: string): boolean;
22
24
  /** The command the user runs in their own terminal to approve a human decision. */
23
25
  export declare function approveCommand(harness: Request["harness"], requestHash: string, context?: HookContext): string;
26
+ /** The short command the user runs to approve the newest blocked request (`approve --last`). */
27
+ export declare function approveLastCommand(context?: HookContext): string;
28
+ /**
29
+ * What Codex shows for a decision that needs a person. Codex cannot ask, so the agent must stop
30
+ * and hand the user one command; the first line says so, and the command stands on its own line.
31
+ */
32
+ export declare function approveInstruction(decision: Decision, context?: HookContext): string;
24
33
  export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): Record<string, unknown>;
25
34
  /** The exact stdout of a PreToolUse or PermissionRequest hook. Codex gets no output for no decision. */
26
35
  export declare function hookOutput(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): string;
package/dist/adapters.js CHANGED
@@ -99,12 +99,32 @@ export function approveCommand(harness, requestHash, context) {
99
99
  ? `node "${cliPath}" approve ${harness} ${context.sessionId} ${requestHash}`
100
100
  : `policy-manager approve ${harness} <session-id> ${requestHash}`;
101
101
  }
102
- function approveInstruction(harness, decision, context) {
103
- const command = approveCommand(harness, decision.requestHash, context);
104
- const session = decision.sessionGrantable
105
- ? " Adding --session also allows later requests in this session that hit the same rule for the same scope."
106
- : "";
107
- return `Approving it in chat does not unblock it. To allow it once, the user runs in their own terminal: ${command} — then retry the same request unchanged.${session} Do not run that command yourself.`;
102
+ /** The short command the user runs to approve the newest blocked request (`approve --last`). */
103
+ export function approveLastCommand(context) {
104
+ if (context?.pmOnPath)
105
+ return "pm approve --last";
106
+ const cliPath = context && /^[A-Za-z]:\\/.test(context.cliPath)
107
+ ? context.cliPath.replace(/\\/g, "/")
108
+ : context?.cliPath;
109
+ return cliPath ? `node "${cliPath}" approve --last` : "policy-manager approve --last";
110
+ }
111
+ /**
112
+ * What Codex shows for a decision that needs a person. Codex cannot ask, so the agent must stop
113
+ * and hand the user one command; the first line says so, and the command stands on its own line.
114
+ */
115
+ export function approveInstruction(decision, context) {
116
+ return [
117
+ `⏸ Waiting for your approval. Not run: ${decision.reason}.`,
118
+ 'Run in your own terminal, then say "retry":',
119
+ ` ${approveLastCommand(context)}`,
120
+ ...(decision.sessionGrantable
121
+ ? [
122
+ `Add --session to also allow ${decision.sessionScopeLabel ?? "the same rule for the same scope"} for the rest of this session.`,
123
+ ]
124
+ : []),
125
+ "Agent: stop now and end your turn; approving it in chat does not unblock it. Show the user the command above exactly, in a code block. Never run it yourself.",
126
+ `Request ${decision.requestHash}.`,
127
+ ].join("\n");
108
128
  }
109
129
  /** What a blocked ambiguous request tells the model to do. Never ask for human approval here. */
110
130
  function classifyInstruction(harness, decision, context) {
@@ -142,11 +162,19 @@ export function hookResponse(harness, phase, decision, context) {
142
162
  return decision.decision === "approve" ? { behavior: "allow" } : {};
143
163
  return decision.decision === "approve"
144
164
  ? { permissionDecision: "allow" }
145
- : { permissionDecision: "ask", permissionDecisionReason: decision.reason };
165
+ : {
166
+ permissionDecision: "ask",
167
+ permissionDecisionReason: decision.reason,
168
+ };
146
169
  }
147
170
  if (phase === "PermissionRequest")
148
171
  return decision.decision === "approve"
149
- ? { hookSpecificOutput: { hookEventName: phase, decision: { behavior: "allow" } } }
172
+ ? {
173
+ hookSpecificOutput: {
174
+ hookEventName: phase,
175
+ decision: { behavior: "allow" },
176
+ },
177
+ }
150
178
  : {};
151
179
  // Codex rejects PreToolUse `permissionDecision: "allow"` without `updatedInput` ("unsupported
152
180
  // permissionDecision:allow") and marks the hook failed. An approval there is no decision at all;
@@ -154,7 +182,12 @@ export function hookResponse(harness, phase, decision, context) {
154
182
  if (decision.decision === "approve")
155
183
  return harness === "codex"
156
184
  ? {}
157
- : { hookSpecificOutput: { hookEventName: phase, permissionDecision: "allow" } };
185
+ : {
186
+ hookSpecificOutput: {
187
+ hookEventName: phase,
188
+ permissionDecision: "allow",
189
+ },
190
+ };
158
191
  // Codex parses permissionDecision "ask" but does not support it: it marks the hook failed and
159
192
  // runs the tool anyway (https://developers.openai.com/codex/hooks). Only "deny" stops a command,
160
193
  // so a decision that needs a human is a deny. Approving it in chat does not change the decision;
@@ -162,16 +195,17 @@ export function hookResponse(harness, phase, decision, context) {
162
195
  // ambiguous request (needsClassification) is classified, and a retry then sees the approval.
163
196
  // Codex's own approval prompt (PermissionRequest, above) still handles the requests it asks about.
164
197
  if (harness === "codex") {
165
- const next = decision.needsClassification === true && decision.classification !== "fallback"
166
- ? "Classify it with the session policy-manager agent and retry. If it is not classified as approved, the retry is blocked with the command the user runs to approve it."
167
- : decision.userOnly
168
- ? "Do not run approve yourself: ask the user to approve the original request from their own terminal."
169
- : approveInstruction(harness, decision, context);
198
+ const classify = decision.needsClassification === true && decision.classification !== "fallback";
199
+ const reason = !classify && !decision.userOnly
200
+ ? approveInstruction(decision, context)
201
+ : `Policy manager: ${decision.reason}. This needs a human decision and was not run. ${classify
202
+ ? "Classify it with the session policy-manager agent and retry. If it is not classified as approved, the retry is blocked with the command the user runs to approve it."
203
+ : "Do not run approve yourself: ask the user to approve the original request from their own terminal."} Request ${decision.requestHash}.`;
170
204
  return {
171
205
  hookSpecificOutput: {
172
206
  hookEventName: phase,
173
207
  permissionDecision: "deny",
174
- permissionDecisionReason: `Policy manager: ${decision.reason}. This needs a human decision and was not run. ${next} Request ${decision.requestHash}.`,
208
+ permissionDecisionReason: reason,
175
209
  },
176
210
  };
177
211
  }
package/dist/cli.js CHANGED
@@ -11,16 +11,18 @@ import { HUMAN_REVIEW_PRINCIPLE } from "./principle.js";
11
11
  import { defaultProfilePath, loadProfile, parseProfile } from "./profile.js";
12
12
  import { replayTranscripts } from "./replay.js";
13
13
  import { formatReview, reviewClassifications, sessionDirectories } from "./review.js";
14
- import { send, serve, start, stop } from "./service.js";
14
+ import { latestHumanDecision, send, sendTo, serve, start, stop } from "./service.js";
15
15
  import { SetupError, setupHook } from "./setup.js";
16
+ import { cliVersion, inspectShim, shimDirectory } from "./shim.js";
16
17
  const usage = `policy-manager usage [--json]
17
18
  policy-manager hook <claude|codex|copilot> <SessionStart|PreToolUse|PermissionRequest|PostToolUse|PostToolUseFailure|SessionEnd>
18
19
  policy-manager review <claude|codex|copilot> <session-id> # normalized request JSON on stdin
19
20
  policy-manager classify <claude|codex|copilot> <session-id> # {requestHash,category,confidence} on stdin
20
21
  policy-manager record <claude|codex|copilot> <session-id> # host-reported human response or execution result JSON
21
- policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session] # the user, in their own terminal: allow a blocked request once, or its rule and scope for the session
22
- policy-manager setup-hook <claude|codex|copilot> [--dry-run] [--config-dir <harness-config-directory>]
23
- policy-manager setup-hook-claude|setup-hook-codex|setup-hook-copilot [--dry-run] [--config-dir <directory>]
22
+ policy-manager approve --last [--session] # the user, in their own terminal: allow the newest blocked request once, or its rule and scope for the session
23
+ policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session] # the same for one exact request
24
+ policy-manager setup-hook <claude|codex|copilot> [--dry-run] [--config-dir <harness-config-directory>] [--shim-dir <directory>]
25
+ policy-manager setup-hook-claude|setup-hook-codex|setup-hook-copilot [--dry-run] [--config-dir <directory>] [--shim-dir <directory>]
24
26
  policy-manager config <claude|codex|copilot> <absolute-installed-cli-path>
25
27
  policy-manager profile validate <file> # check a policy profile without installing it
26
28
  policy-manager profile install <file> # install it to the user config directory outside Git
@@ -50,6 +52,16 @@ const args = process.argv.slice(2);
50
52
  const [action, harnessArg, phase] = args;
51
53
  const harness = harnessArg;
52
54
  const cliPath = fileURLToPath(import.meta.url);
55
+ /** Whether a managed `pm` launcher for this CLI is installed and on PATH. */
56
+ function pmReady() {
57
+ try {
58
+ const status = inspectShim(shimDirectory(), cliPath, cliVersion(cliPath));
59
+ return status.state === "current" && status.onPath;
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
53
65
  try {
54
66
  if (action === "usage" || !action)
55
67
  console.log(args.includes("--json") ? JSON.stringify({ usage }) : usage);
@@ -58,11 +70,16 @@ try {
58
70
  const selected = (alias ?? harnessArg);
59
71
  const { values } = parseArgs({
60
72
  args: args.slice(alias ? 1 : 2),
61
- options: { "dry-run": { type: "boolean" }, "config-dir": { type: "string" } },
73
+ options: {
74
+ "dry-run": { type: "boolean" },
75
+ "config-dir": { type: "string" },
76
+ "shim-dir": { type: "string" },
77
+ },
62
78
  });
63
79
  console.log(JSON.stringify(setupHook(selected, cliPath, {
64
80
  dryRun: values["dry-run"],
65
81
  configDirectory: values["config-dir"],
82
+ shimDirectory: values["shim-dir"],
66
83
  }), null, 2));
67
84
  }
68
85
  else if (action === "config")
@@ -75,6 +92,7 @@ try {
75
92
  mode: profile.mode,
76
93
  cloudWrites: profile.cloudWrites,
77
94
  mcpReadOnly: profile.mcpReadOnly.length,
95
+ toolsDeny: Object.values(profile.toolsDeny).reduce((n, list) => n + list.length, 0),
78
96
  digest: profile.digest,
79
97
  };
80
98
  if (harnessArg === "install") {
@@ -123,19 +141,37 @@ try {
123
141
  else if (action === "approve") {
124
142
  const { values, positionals } = parseArgs({
125
143
  args: args.slice(1),
126
- options: { session: { type: "boolean" } },
144
+ options: { session: { type: "boolean" }, last: { type: "boolean" } },
127
145
  allowPositionals: true,
128
146
  });
129
- const [target, sessionId, requestHash] = positionals;
130
- if (!["claude", "codex", "copilot"].includes(target) ||
131
- !/^[A-Za-z0-9_.-]+$/.test(sessionId ?? "") ||
132
- !/^[a-f0-9]{64}$/.test(requestHash ?? ""))
133
- throw new ApproveError("Usage: policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session]");
134
- if (!process.stdin.isTTY || !process.stdout.isTTY)
135
- throw new ApproveError("Run approve yourself in an interactive terminal; it asks you to confirm the request.");
136
- if (!existsSync(sessionDirectoryPath(target, sessionId)))
137
- throw new ApproveError("No policy service is running for that session.");
138
- const ask = (confirm) => send(target, sessionId, {
147
+ const usageText = "Usage: policy-manager approve --last [--session], or approve <claude|codex|copilot> <session-id> <request-hash> [--session]";
148
+ let directory;
149
+ let requestHash;
150
+ if (values.last) {
151
+ if (positionals.length)
152
+ throw new ApproveError(usageText);
153
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
154
+ throw new ApproveError("Run approve yourself in an interactive terminal; it asks you to confirm the request.");
155
+ const latest = await latestHumanDecision();
156
+ if (!latest)
157
+ throw new ApproveError("No running policy session has a request waiting for approval from the last 15 minutes. Have the agent retry so it is blocked again.");
158
+ ({ directory, requestHash } = latest);
159
+ console.log(`Session: ${latest.harness} ${latest.sessionId}`);
160
+ }
161
+ else {
162
+ const [target, sessionId, hashArg] = positionals;
163
+ if (!["claude", "codex", "copilot"].includes(target) ||
164
+ !/^[A-Za-z0-9_.-]+$/.test(sessionId ?? "") ||
165
+ !/^[a-f0-9]{64}$/.test(hashArg ?? ""))
166
+ throw new ApproveError(usageText);
167
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
168
+ throw new ApproveError("Run approve yourself in an interactive terminal; it asks you to confirm the request.");
169
+ if (!existsSync(sessionDirectoryPath(target, sessionId)))
170
+ throw new ApproveError("No policy service is running for that session.");
171
+ directory = sessionDirectoryPath(target, sessionId);
172
+ requestHash = hashArg;
173
+ }
174
+ const ask = (confirm) => sendTo(directory, {
139
175
  action: "grant",
140
176
  grant: { requestHash, confirm, session: values.session === true },
141
177
  });
@@ -147,7 +183,10 @@ try {
147
183
  console.log("This request can only be approved once: credential reads, possible unrecoverable loss and requests whose effect could not be determined are never approved for a session.");
148
184
  if (preview.scope === "session" && preview.sessionScope)
149
185
  console.log(`Scope: ${preview.sessionScope}`);
150
- const prompt = createInterface({ input: process.stdin, output: process.stdout });
186
+ const prompt = createInterface({
187
+ input: process.stdin,
188
+ output: process.stdout,
189
+ });
151
190
  const answer = await prompt.question(preview.scope === "session"
152
191
  ? "Allow this and later requests in this session that hit the same rule for the same scope? [y/N] "
153
192
  : "Allow this request once? [y/N] ");
@@ -188,7 +227,12 @@ try {
188
227
  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.`;
189
228
  console.log(JSON.stringify(harness === "copilot"
190
229
  ? { additionalContext: context }
191
- : { hookSpecificOutput: { hookEventName: phase, additionalContext: context } }));
230
+ : {
231
+ hookSpecificOutput: {
232
+ hookEventName: phase,
233
+ additionalContext: context,
234
+ },
235
+ }));
192
236
  }
193
237
  else if (phase === "PostToolUse" || phase === "PostToolUseFailure") {
194
238
  await send(harness, request.sessionId, {
@@ -206,6 +250,7 @@ try {
206
250
  const output = hookOutput(harness, phase, decision, {
207
251
  cliPath,
208
252
  sessionId: request.sessionId,
253
+ pmOnPath: decision.decision === "human" && harness === "codex" && pmReady(),
209
254
  });
210
255
  if (output)
211
256
  console.log(output);
package/dist/flow.js CHANGED
@@ -18,8 +18,12 @@ const MAX_VARIANTS = 16;
18
18
  const MAX_SUBSTITUTION_DEPTH = 3;
19
19
  /** Commands one script may be judged as; past this it is too large to verify in time. */
20
20
  const MAX_JUDGEMENTS = 400;
21
- /** No whitespace, glob, quote, expansion or tilde characters: the value is exactly one word. */
22
- const SIMPLE_VALUE = /^[A-Za-z0-9_@%+=:,./-]+$/;
21
+ /**
22
+ * No whitespace, glob, quote or expansion characters: the value is exactly one word. A `~` is
23
+ * allowed only right after a letter or digit, where no shell expands it (a Windows short name
24
+ * such as `RUNNER~1`); at the start or after `=` or `:` it would become a home directory.
25
+ */
26
+ const SIMPLE_VALUE = /^(?:[A-Za-z0-9_@%+=:,./-]|(?<=[A-Za-z0-9])~)+$/;
23
27
  const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
24
28
  const UNSUPPORTED = "Unsupported shell syntax; expansions and subshells need human review";
25
29
  const MAX_CALL_DEPTH = 4;
@@ -68,6 +72,16 @@ function replace(target, source) {
68
72
  }
69
73
  // --- words ------------------------------------------------------------------------------------
70
74
  const isKnown = (values) => !!values?.length && values.every((v) => SIMPLE_VALUE.test(v));
75
+ /** The one literal value of a variable, usable only inside double quotes. */
76
+ function literalValue(values) {
77
+ const value = values?.length === 1 ? values[0] : undefined;
78
+ return value !== undefined &&
79
+ value.length <= 4096 &&
80
+ !value.includes("\0") &&
81
+ !value.includes(SUBSTITUTION)
82
+ ? value
83
+ : undefined;
84
+ }
71
85
  /**
72
86
  * Environment variables whose value is harmless to print or pass on. Any other variable the script
73
87
  * did not assign could hold a credential (`$GITHUB_TOKEN`, `$AWS_SECRET_ACCESS_KEY`), so using it
@@ -202,6 +216,9 @@ function instantiate(word, known, env, state) {
202
216
  }
203
217
  else if (known.has(part.name))
204
218
  text += applyParamOp(env[part.name] ?? "", part.op);
219
+ else if (part.quoted && !part.op && literalValue(state?.vars.get(part.name)) !== undefined)
220
+ // Inside double quotes a literal value is one word with no further expansion.
221
+ text += literalValue(state?.vars.get(part.name));
205
222
  else {
206
223
  text += SUBSTITUTION;
207
224
  // "$@" is one word per parameter even when quoted.
@@ -458,7 +475,11 @@ function splitAssignment(word) {
458
475
  return undefined;
459
476
  return {
460
477
  name,
461
- value: { ...word, parts: [first.slice(eq + 1), ...word.parts.slice(1)], subs: [] },
478
+ value: {
479
+ ...word,
480
+ parts: [first.slice(eq + 1), ...word.parts.slice(1)],
481
+ subs: [],
482
+ },
462
483
  };
463
484
  }
464
485
  /** grep and rg options whose value is a file-name glob. */
@@ -540,6 +561,7 @@ function runSimple(ctx, node, state, stage, piped) {
540
561
  redirects,
541
562
  subs: [],
542
563
  loose,
564
+ glob: node.argv.map((word) => word.glob === true),
543
565
  ...(stdin === undefined ? {} : { stdin }),
544
566
  };
545
567
  };
@@ -607,6 +629,13 @@ function runSimple(ctx, node, state, stage, piped) {
607
629
  continue;
608
630
  }
609
631
  }
632
+ // A single literal value that is not one plain word (`Q='query($t: ID!)'`) is kept for
633
+ // double-quoted use only: isKnown rejects it, so an unquoted `$Q` stays unknown.
634
+ const set = [...new Set(texts)];
635
+ if (set.length === 1 && literalValue(set) !== undefined) {
636
+ state.vars.set(a.name, set);
637
+ continue;
638
+ }
610
639
  state.vars.set(a.name, null);
611
640
  }
612
641
  ctx.box.last = result(request, "code-read", "Variable assignment", true);
@@ -622,7 +651,13 @@ function runSimple(ctx, node, state, stage, piped) {
622
651
  if (decision.decision !== "approve")
623
652
  return decision;
624
653
  ctx.box.last = decision;
625
- if (!symlinkFree(unwrap(command.argv).argv)) {
654
+ if (decision.credentialHelpers?.length) {
655
+ ctx.box.helpers ??= new Set();
656
+ for (const helper of decision.credentialHelpers)
657
+ ctx.box.helpers.add(helper);
658
+ }
659
+ // A listed credential helper only reads a secret and talks to its service.
660
+ if (!decision.credentialHelpers?.length && !symlinkFree(unwrap(command.argv).argv)) {
626
661
  if (ctx.box.script.approved)
627
662
  return human(request, "unknown", "A command that can create symlinks may run before an approved temp path");
628
663
  ctx.box.script.tainted = true;
@@ -672,7 +707,10 @@ function runSimple(ctx, node, state, stage, piped) {
672
707
  }
673
708
  /** In a loop, a pipeline or a background job, a later command can run first. */
674
709
  function fillFor(ctx, piped) {
675
- return { script: ctx.box.script, reorder: ctx.loop > 0 || piped || !!ctx.reorder };
710
+ return {
711
+ script: ctx.box.script,
712
+ reorder: ctx.loop > 0 || piped || !!ctx.reorder,
713
+ };
676
714
  }
677
715
  /**
678
716
  * Programs that create no symlink: they read, print, or write regular files only. Shells are here
@@ -1393,7 +1431,9 @@ function cannotFail(ctx, node, state) {
1393
1431
  if (program !== "cd" || argv.length !== 2 || target === undefined || node !== ctx.box.first)
1394
1432
  return false;
1395
1433
  const path = target === "~" || target.startsWith("~/") ? join(homedir(), target.slice(1)) : target;
1396
- if (!path.startsWith("/") || /[*?[\]]/.test(path))
1434
+ // On Windows an absolute path starts with a drive (`C:/x` or `C:\x`), including the home directory.
1435
+ const absolute = path.startsWith("/") || (process.platform === "win32" && /^[A-Za-z]:[\\/]/.test(path));
1436
+ if (!absolute || /[*?[\]]/.test(path))
1397
1437
  return false;
1398
1438
  try {
1399
1439
  if (!statSync(path).isDirectory())
@@ -1500,13 +1540,25 @@ export function commandDecision(request, command, profile, depth = 0, start = [r
1500
1540
  loop: 0,
1501
1541
  calls: 0,
1502
1542
  positional: !/argv/.test(command),
1503
- box: { calls: 0, script: fill?.script ?? { tainted: false, approved: false, jobs: 0 } },
1543
+ box: {
1544
+ calls: 0,
1545
+ script: fill?.script ?? { tainted: false, approved: false, jobs: 0 },
1546
+ },
1504
1547
  ...(fill?.reorder ? { reorder: true } : {}),
1505
1548
  };
1506
1549
  const opening = script.items[0];
1507
1550
  if (depth === 0 && opening && !opening.background)
1508
1551
  ctx.box.first = opening.node.first;
1509
- const refusal = runList(ctx, script, { cwds: [...start], vars: new Map(), funcs: new Map() });
1510
- return refusal ?? ctx.box.last ?? human(request, "unknown", "Empty command");
1552
+ const refusal = runList(ctx, script, {
1553
+ cwds: [...start],
1554
+ vars: new Map(),
1555
+ funcs: new Map(),
1556
+ });
1557
+ if (refusal)
1558
+ return refusal;
1559
+ const last = ctx.box.last ?? human(request, "unknown", "Empty command");
1560
+ return ctx.box.helpers?.size && last.decision === "approve"
1561
+ ? { ...last, credentialHelpers: [...ctx.box.helpers] }
1562
+ : last;
1511
1563
  }
1512
1564
  //# sourceMappingURL=flow.js.map
package/dist/grants.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync, statSync } from "node:fs";
2
2
  import { dirname, join, relative } from "node:path";
3
3
  import { canonical, git, inside, policyState, protectedPath, resolveWord, sensitive, } from "./evidence.js";
4
4
  import { SHELL_TOOLS, words } from "./policy.js";
5
+ import { parseShell, SUBSTITUTION } from "./shell.js";
5
6
  export const PROTECTED_PATH = "Protected path requires human approval";
6
7
  export const HUMAN_PATTERN = "Matches an organization human-approval pattern";
7
8
  const FILE_TOOLS = new Set(["Write", "create", "write_file", "Edit", "edit", "MultiEdit"]);
@@ -41,6 +42,40 @@ function targets(request) {
41
42
  }
42
43
  return undefined;
43
44
  }
45
+ /**
46
+ * Every word of a single shell command that could name a file it touches: non-option arguments,
47
+ * the value of `--option=value` or `-oVALUE`, and redirect targets (`> f`, `>> f`, `< f`). One program, no
48
+ * operators, pipes, substitutions or variables. A word that is not a path only adds a scope, so
49
+ * treating it as one fails closed.
50
+ */
51
+ function shellPaths(request) {
52
+ const command = request.input.command ?? request.input.cmd;
53
+ if (!SHELL_TOOLS.has(request.tool) || typeof command !== "string")
54
+ return undefined;
55
+ const pipelines = parseShell(command);
56
+ const only = pipelines?.length === 1 && pipelines[0]?.length === 1 ? pipelines[0][0] : undefined;
57
+ if (!only || only.env.length || only.subs.length || only.stdin !== undefined)
58
+ return undefined;
59
+ const texts = [...only.argv, ...only.redirects.map((r) => r.target)];
60
+ if (texts.some((text) => text.includes(SUBSTITUTION)))
61
+ return undefined;
62
+ const paths = [];
63
+ for (const word of only.argv.slice(1)) {
64
+ if (!word.startsWith("-"))
65
+ paths.push(word);
66
+ else if (word.startsWith("--")) {
67
+ if (word.includes("="))
68
+ paths.push(word.slice(word.indexOf("=") + 1));
69
+ }
70
+ // `-oFILE` attaches a value to a short option; flags like `-rf` only add a harmless path.
71
+ else if (word.length > 2)
72
+ paths.push(word.slice(2).replace(/^=/, ""));
73
+ }
74
+ for (const redirect of only.redirects)
75
+ if (redirect.op !== ">&" && redirect.target !== "/dev/null")
76
+ paths.push(redirect.target);
77
+ return paths.filter((path) => path.length > 0);
78
+ }
44
79
  /** A simple command (one program, no operators, expansions or redirects) as words. */
45
80
  function simple(request) {
46
81
  const command = request.input.command ?? request.input.cmd;
@@ -62,13 +97,7 @@ function simple(request) {
62
97
  export function grantScope(request, decision, profile) {
63
98
  try {
64
99
  if (decision.reason === PROTECTED_PATH) {
65
- let paths = targets(request);
66
- if (!paths) {
67
- const argv = simple(request);
68
- paths = argv
69
- ?.slice(1)
70
- .filter((word) => !word.startsWith("-") && (word.includes("/") || word.startsWith(".")));
71
- }
100
+ const paths = targets(request) ?? shellPaths(request);
72
101
  if (!paths?.length)
73
102
  return undefined;
74
103
  const roots = new Set();
@@ -114,7 +143,12 @@ export function grantScope(request, decision, profile) {
114
143
  /** What a session scope covers, in words the user can check before approving it. */
115
144
  export function scopeLabel(scope, profile) {
116
145
  if (scope.startsWith("protected:"))
117
- return `writes under ${scope.slice("protected:".length).split("\u0000").join(", ")}`;
146
+ return `writes ${scope
147
+ .slice("protected:".length)
148
+ .split("\u0000")
149
+ // A root that is a file (`AGENTS.md`) is written to; a directory, or one not made yet, under.
150
+ .map((root) => (existsSync(root) && !statSync(root).isDirectory() ? "to " : "under ") + root)
151
+ .join(", ")}`;
118
152
  if (scope.startsWith("pattern:")) {
119
153
  const [, indexes = "", ...checkout] = scope.split(":");
120
154
  const patterns = indexes