@agent-corpus/policy-manager 0.8.0 → 0.9.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,14 @@ 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
+
197
218
  #### MCP read-only tools
198
219
 
199
220
  `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 +231,7 @@ A listed tool is approved. Any other MCP tool gets no decision from the policy m
210
231
 
211
232
  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
233
 
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.
234
+ 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
235
 
215
236
  `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
237
 
@@ -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
@@ -68,6 +68,16 @@ function replace(target, source) {
68
68
  }
69
69
  // --- words ------------------------------------------------------------------------------------
70
70
  const isKnown = (values) => !!values?.length && values.every((v) => SIMPLE_VALUE.test(v));
71
+ /** The one literal value of a variable, usable only inside double quotes. */
72
+ function literalValue(values) {
73
+ const value = values?.length === 1 ? values[0] : undefined;
74
+ return value !== undefined &&
75
+ value.length <= 4096 &&
76
+ !value.includes("\0") &&
77
+ !value.includes(SUBSTITUTION)
78
+ ? value
79
+ : undefined;
80
+ }
71
81
  /**
72
82
  * Environment variables whose value is harmless to print or pass on. Any other variable the script
73
83
  * did not assign could hold a credential (`$GITHUB_TOKEN`, `$AWS_SECRET_ACCESS_KEY`), so using it
@@ -202,6 +212,9 @@ function instantiate(word, known, env, state) {
202
212
  }
203
213
  else if (known.has(part.name))
204
214
  text += applyParamOp(env[part.name] ?? "", part.op);
215
+ else if (part.quoted && !part.op && literalValue(state?.vars.get(part.name)) !== undefined)
216
+ // Inside double quotes a literal value is one word with no further expansion.
217
+ text += literalValue(state?.vars.get(part.name));
205
218
  else {
206
219
  text += SUBSTITUTION;
207
220
  // "$@" is one word per parameter even when quoted.
@@ -458,7 +471,11 @@ function splitAssignment(word) {
458
471
  return undefined;
459
472
  return {
460
473
  name,
461
- value: { ...word, parts: [first.slice(eq + 1), ...word.parts.slice(1)], subs: [] },
474
+ value: {
475
+ ...word,
476
+ parts: [first.slice(eq + 1), ...word.parts.slice(1)],
477
+ subs: [],
478
+ },
462
479
  };
463
480
  }
464
481
  /** grep and rg options whose value is a file-name glob. */
@@ -607,6 +624,13 @@ function runSimple(ctx, node, state, stage, piped) {
607
624
  continue;
608
625
  }
609
626
  }
627
+ // A single literal value that is not one plain word (`Q='query($t: ID!)'`) is kept for
628
+ // double-quoted use only: isKnown rejects it, so an unquoted `$Q` stays unknown.
629
+ const set = [...new Set(texts)];
630
+ if (set.length === 1 && literalValue(set) !== undefined) {
631
+ state.vars.set(a.name, set);
632
+ continue;
633
+ }
610
634
  state.vars.set(a.name, null);
611
635
  }
612
636
  ctx.box.last = result(request, "code-read", "Variable assignment", true);
@@ -672,7 +696,10 @@ function runSimple(ctx, node, state, stage, piped) {
672
696
  }
673
697
  /** In a loop, a pipeline or a background job, a later command can run first. */
674
698
  function fillFor(ctx, piped) {
675
- return { script: ctx.box.script, reorder: ctx.loop > 0 || piped || !!ctx.reorder };
699
+ return {
700
+ script: ctx.box.script,
701
+ reorder: ctx.loop > 0 || piped || !!ctx.reorder,
702
+ };
676
703
  }
677
704
  /**
678
705
  * Programs that create no symlink: they read, print, or write regular files only. Shells are here
@@ -1500,13 +1527,20 @@ export function commandDecision(request, command, profile, depth = 0, start = [r
1500
1527
  loop: 0,
1501
1528
  calls: 0,
1502
1529
  positional: !/argv/.test(command),
1503
- box: { calls: 0, script: fill?.script ?? { tainted: false, approved: false, jobs: 0 } },
1530
+ box: {
1531
+ calls: 0,
1532
+ script: fill?.script ?? { tainted: false, approved: false, jobs: 0 },
1533
+ },
1504
1534
  ...(fill?.reorder ? { reorder: true } : {}),
1505
1535
  };
1506
1536
  const opening = script.items[0];
1507
1537
  if (depth === 0 && opening && !opening.background)
1508
1538
  ctx.box.first = opening.node.first;
1509
- const refusal = runList(ctx, script, { cwds: [...start], vars: new Map(), funcs: new Map() });
1539
+ const refusal = runList(ctx, script, {
1540
+ cwds: [...start],
1541
+ vars: new Map(),
1542
+ funcs: new Map(),
1543
+ });
1510
1544
  return refusal ?? ctx.box.last ?? human(request, "unknown", "Empty command");
1511
1545
  }
1512
1546
  //# 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();
@@ -3,6 +3,12 @@ import { commandDecision } from "./flow.js";
3
3
  import type { Profile } from "./profile.js";
4
4
  import { type Redirect, type SimpleCommand } from "./shell.js";
5
5
  import type { Decision, Request } from "./types.js";
6
+ /**
7
+ * The files `sort` writes: its `-o`/`--output` file and its `-T`/`--temporary-directory`. Options
8
+ * are parsed as GNU getopt does (clustered short options, exact or unique long prefixes).
9
+ * Undefined when it may run another program (`--compress-program`) or an option is unknown.
10
+ */
11
+ export declare function sortWrites(args: string[]): string[] | undefined;
6
12
  export declare const BANNED_ENV: RegExp;
7
13
  export declare function human(request: Request, category: Decision["category"], reason: string): Decision;
8
14
  export declare function permissiveRead(cwd: string, input: string): {
@@ -51,6 +51,65 @@ const WRITERS = new Set([
51
51
  "chown",
52
52
  ]);
53
53
  const WRAPPERS = new Set(["env", "nohup", "time", "command", "nice", "timeout", "xargs"]);
54
+ const SORT_LONG = [
55
+ ...["ignore-leading-blanks", "dictionary-order", "ignore-case", "general-numeric-sort"],
56
+ ...["ignore-nonprinting", "month-sort", "human-numeric-sort", "numeric-sort", "random-sort"],
57
+ ...["random-source", "reverse", "sort", "version-sort", "batch-size", "check", "debug"],
58
+ ...["compress-program", "files0-from", "key", "merge", "output", "stable", "buffer-size"],
59
+ ...["field-separator", "temporary-directory", "parallel", "unique", "zero-terminated"],
60
+ ...["help", "version"],
61
+ ];
62
+ const SORT_LONG_VALUE = new Set([
63
+ ...["random-source", "sort", "batch-size", "compress-program", "files0-from", "key"],
64
+ ...["output", "buffer-size", "field-separator", "temporary-directory", "parallel"],
65
+ ]);
66
+ /**
67
+ * The files `sort` writes: its `-o`/`--output` file and its `-T`/`--temporary-directory`. Options
68
+ * are parsed as GNU getopt does (clustered short options, exact or unique long prefixes).
69
+ * Undefined when it may run another program (`--compress-program`) or an option is unknown.
70
+ */
71
+ export function sortWrites(args) {
72
+ const writes = [];
73
+ for (let i = 0; i < args.length; i++) {
74
+ const arg = args[i] ?? "";
75
+ if (arg === "--")
76
+ break;
77
+ if (arg.startsWith("--")) {
78
+ const [given = "", inline] = arg.slice(2).split(/=(.*)/s, 2);
79
+ const exact = SORT_LONG.includes(given)
80
+ ? [given]
81
+ : SORT_LONG.filter((n) => n.startsWith(given));
82
+ if (exact.length !== 1)
83
+ return undefined;
84
+ const name = exact[0] ?? "";
85
+ if (!SORT_LONG_VALUE.has(name))
86
+ continue;
87
+ const value = inline ?? args[++i];
88
+ if (value === undefined)
89
+ return undefined;
90
+ if (name === "compress-program")
91
+ return undefined;
92
+ if (name === "output" || name === "temporary-directory")
93
+ writes.push(value);
94
+ }
95
+ else if (arg.startsWith("-") && arg.length > 1) {
96
+ for (let j = 1; j < arg.length; j++) {
97
+ const flag = arg[j] ?? "";
98
+ if ("ktSTo".includes(flag)) {
99
+ const value = arg.slice(j + 1) || args[++i];
100
+ if (value === undefined)
101
+ return undefined;
102
+ if (flag === "o" || flag === "T")
103
+ writes.push(value);
104
+ break;
105
+ }
106
+ if (!"bdfgiMhnRrVcCmsuz".includes(flag))
107
+ return undefined;
108
+ }
109
+ }
110
+ }
111
+ return writes;
112
+ }
54
113
  /**
55
114
  * Programs whose behaviour cannot be changed by an unknown argument: they only print or compare
56
115
  * strings. The output of a command substitution may be an argument of these and of nothing else,
@@ -1611,6 +1670,16 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
1611
1670
  if (program === "find" &&
1612
1671
  args.some((arg) => ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprintf", "-fls"].includes(arg)))
1613
1672
  return human(request, "destructive", "find with actions requires human review");
1673
+ if (program === "sort") {
1674
+ const outputs = sortWrites(args);
1675
+ if (outputs === undefined)
1676
+ return human(request, "unknown", "sort with an option that runs a program requires review");
1677
+ for (const file of outputs) {
1678
+ const check = permissiveWrite(cwd, file, profile, fill);
1679
+ if (!check.allowed)
1680
+ return human(request, check.category, check.reason);
1681
+ }
1682
+ }
1614
1683
  if (["chmod", "chown"].includes(program) && args.some((arg) => /^-[a-zA-Z]*R/.test(arg)))
1615
1684
  return human(request, "destructive", "Recursive permission changes require human approval");
1616
1685
  if ((program === "sed" &&
package/dist/policy.js CHANGED
@@ -5,6 +5,7 @@ import { branchEvidence, canonical, git, inside, pathEvidence } from "./evidence
5
5
  import { commandDecision, permissiveRead, permissiveWrite, WORKTREE_DELETION, } from "./permissive.js";
6
6
  import { mcpReadOnly, strictProfile } from "./profile.js";
7
7
  import { redactText } from "./redact.js";
8
+ import { defaultAllowed } from "./tools.js";
8
9
  import { CATEGORIES, } from "./types.js";
9
10
  export function hash(value) {
10
11
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
@@ -315,6 +316,15 @@ function evaluateCore(request, profile) {
315
316
  ...result(request, "unknown", "MCP tool not listed as read-only; left to the harness"),
316
317
  decision: "native",
317
318
  };
319
+ // Harness tools that are not shell, file, patch or MCP tools (task control, plan mode, asking
320
+ // the user, loading tool schemas) are approved by default under the permissive profile; the
321
+ // profile's toolsDeny keeps chosen ones on the classification path. Each approval names the tool.
322
+ if (profile.mode === "permissive" &&
323
+ defaultAllowed(request.harness, request.tool, profile.toolsDeny[request.harness] ?? []))
324
+ return {
325
+ ...result(request, "code-read", "Harness tool approved by default", true),
326
+ defaultTool: request.tool,
327
+ };
318
328
  const cwd = input.workdir ?? input.cwd ?? request.cwd;
319
329
  if (typeof cwd !== "string" || cwd !== request.cwd)
320
330
  return result(request, "unknown", "Execution directory differs from the reviewed directory");