@agent-corpus/policy-manager 0.6.0 → 0.7.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
@@ -91,8 +91,9 @@ Under a `permissive` profile, a person is asked only for what code says must sta
91
91
  How a hook call flows (Claude Code, Codex and Copilot `PreToolUse`):
92
92
 
93
93
  1. **First call.** The command is _not run_ and the person is not asked. The hook blocks it with a reason that tells the model to ask the session's policy-manager agent whether the exact command is recoverable and non-sensitive, to record the answer with `policy-manager classify`, and to retry the same command. The reason starts with `Needs classification (not an error)` and states the rule the classifier applies (`HUMAN_REVIEW_PRINCIPLE`). A person is needed only for unrecoverable loss, credential or secret retrieval, protected configuration or paths, and `humanPatterns`. A recoverable outward-facing write such as an issue comment is approvable, and so is a destructive-but-safe deletion inside a feature worktree. The request hash covers only effect-relevant input, so a retry with a different Bash `description` reuses the classification.
94
- 2. **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.
94
+ 2. **Recorded.** The session approves the record command in that reason deterministically, in every profile: exactly `node "<this package's dist/cli.js>" classify <harness> <session-id> <<< '<json>'` for the current harness and session, with one single-quoted JSON object and nothing else in the command. Any other direct invocation of a classification record goes to a person: `node … cli.js classify` or `policy-manager classify`, at the start of a command or after an operator, including behind assignments, wrappers such as `env`, `exec` or `xargs`, or keywords such as `then`. That covers another session, harness or CLI path, and anything added before or after. A command that only mentions one, such as a `grep` pattern, gets the normal decision, and so does a record nested in a quoted script (`sh -c '…'`).
95
+ 3. **Classified.** `classify` takes `{requestHash, category, confidence, recoverable, rationale}`. The request is approved only when `recoverable` is `true`, `confidence` is at least 0.95, and the category is not `sensitive` or `unknown`. A `destructive` label approves only a deletion the engine itself identified inside a linked feature worktree, on the same terms. Any other request the AI labels `destructive` (an unparsable `rm -rf ~/{a,b}`, for example), and any such deletion not judged recoverable, goes to a **person** (under Codex, a deny), since it may lose data for good. No other deterministic `destructive` escalation is classified. Anything else is a **deny with a reason** the model sees and works around. The outcome is remembered for five minutes for that exact request, and a verdict is final in that time: a deny cannot be reclassified into an approve.
96
+ 4. **Fallback.** If the classifier is unavailable or its answer is invalid, the retry reaches a person through the normal prompt (under Codex, which cannot ask, it is a deny that 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
 
97
98
  **What always stays with a person, in code, and is never AI-relaxable** (these are the owner's calls; they list exactly what this experiment does not change):
98
99
 
@@ -155,7 +156,11 @@ Deleting disposable files is approved too (`Delete within a scratch directory`):
155
156
 
156
157
  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
 
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.
159
+ Every other argument is a possible file operand and is checked for credentials: by name (`id_rsa`, `credentials`, `secrets.json`, `.env`, `*.pem`, `*.key`, also bare, as in `cat id_rsa` from `~/.ssh`), and, when it exists, by its path resolved against the tracked working directory, so a symlink to a key or any file in a `.ssh` directory counts. A glob (`cat *`, `cat id_*`, `cat .*/*`) is expanded one component at a time against the directories it names; more than 5000 entries in total, an entry that cannot be read or resolved, or a zsh recursive `**`/`***` component counts as sensitive. `*` is assumed not to match dot files, so a shell with zsh `GLOB_DOTS` or bash `dotglob` set can reach dot files a plain `*` check misses. File-name pattern values (`grep --include`, `rg -g`, `find -name`/`-path`) are matched below the searched paths, so they are judged by name only. Credential-path checks skip words that are text, not paths: a `sed` script (but not the files its `r`, `w` or `e` commands name, nor `-f`), a `grep` or `rg` pattern, `gh` `--body`, `--title`, `--jq`, `--template` and `--notes` values, and `echo`/`printf` arguments, which are judged by name only when they look like a path. Other programs keep the conservative check.
160
+
161
+ `cp` and `ln` sources are reads, so copying or linking out of a main checkout into the temp directory is a temp write; only the destination (the last operand, `-t` or `--target-directory`, or the base name of a lone `ln` operand in the working directory) is checked as a write. With a backup suffix (`-b`, `-S`, `--backup`, `--suffix`) or a hard link (`ln` without `-s`, `cp -l`/`--link`) every operand is checked as a write, since a later write through a hard link changes its source; a hard-linked file is never a scratch or temp write. `chmod`'s mode and `chown`'s owner are not paths, except that BSD `chmod -N`/`-E`/`-C`/`-i`/`-I` take no mode, so every operand is a file.
162
+
163
+ `grep --include=*.md`, `--exclude`, `--exclude-dir` and `rg -g`/`--glob`/`--iglob` with an unquoted glob value are approved: the option name is literal, so expansion only yields more of the same option. A glob in any other option or in the command name still needs a human.
159
164
 
160
165
  #### Shell syntax in permissive mode
161
166
 
@@ -171,6 +176,7 @@ Every command that could run is judged, not only the first. Understood: `;`, new
171
176
  - **`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
177
  - **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
178
  - **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.
179
+ - **Variables after an assignment chain.** `S=/abs && H=x; use $S $H` treats `H` as assigned: a bare assignment with no command substitution and no redirection cannot fail, so the `&&` chain always reaches `H=x`. This holds only for uppercase names the shell does not reserve. zsh's lowercase specials, read-only or numeric specials (`UID`, `SECONDS`, `BASH*`, `ZSH*`, ...), a value with `$(...)`, `export NAME=value` and a prefix assignment (`X=1 cmd`) can fail or do not persist, so the chain may stop there and a later name is still an environment variable. A value used as the program (`P=rm; $P -rf x`) is resolved and judged as that program. The remaining window is a `readonly` or `typeset -i` that the user's shell startup files set on a name outside that list (such as `HISTFILE`): bash 5 in default mode may then return 1 without exiting, so the chain could stop there. That is outside what the script controls and is accepted.
174
180
  - **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
181
 
176
182
  #### MCP read-only tools
@@ -189,7 +195,9 @@ A listed tool is approved. Any other MCP tool gets no decision from the policy m
189
195
 
190
196
  Measure a profile against real usage with `policy-manager replay ~/.claude/projects --profile policy.json`: it replays the Bash commands recorded in Claude Code transcripts through the evaluator (nothing is executed) and prints the approval rate with and without the profile, plus the most common reasons that still need a human. Reports include short command excerpts, so keep them local.
191
197
 
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.
198
+ 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.
199
+
200
+ `git worktree remove --force <path>` is approved when `<path>` is a linked worktree of the repository (listed by `git worktree list`, never the main worktree), resolves strictly inside a `scratchRoots` entry or the system temp directory, lies outside the main checkout, and holds no other worktree; exactly one `-f`/`--force` may be given (a second one also removes a locked worktree), and not after a command that can create symlinks. A worktree under the main checkout (`.worktrees/x`) still needs a human. `git worktree prune` with only `-n`/`-v` is approved: it drops records of worktrees whose directories are already gone.
193
201
 
194
202
  #### Recoverable deletions and resets
195
203
 
@@ -10,6 +10,14 @@ export interface HookContext {
10
10
  * round trip could never finish. A test evaluates this exact string and requires `approve`.
11
11
  */
12
12
  export declare function classifyCommand(harness: Request["harness"], context?: HookContext, json?: string): string;
13
+ /**
14
+ * Whether `command` is exactly this session's record command from `classifyCommand`, answer
15
+ * included: one single-quoted literal JSON object, nothing before or after it. Inside single
16
+ * quotes the shell expands nothing, so the answer cannot run anything.
17
+ */
18
+ export declare function isClassifyRecord(command: string, harness: Request["harness"], context: HookContext): boolean;
19
+ /** A command that runs a policy-manager classification record, for any session or CLI. */
20
+ export declare function looksLikeClassifyRecord(command: string): boolean;
13
21
  export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): Record<string, unknown>;
14
22
  /** The exact stdout of a PreToolUse or PermissionRequest hook. Codex gets no output for no decision. */
15
23
  export declare function hookOutput(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): string;
package/dist/adapters.js CHANGED
@@ -37,6 +37,48 @@ export function classifyCommand(harness, context, json = "<json>") {
37
37
  ? `node "${cliPath}" classify ${harness} ${context.sessionId} <<< '${json}'`
38
38
  : `policy-manager classify ${harness} <session-id> <<< '${json}'`;
39
39
  }
40
+ /**
41
+ * Whether `command` is exactly this session's record command from `classifyCommand`, answer
42
+ * included: one single-quoted literal JSON object, nothing before or after it. Inside single
43
+ * quotes the shell expands nothing, so the answer cannot run anything.
44
+ */
45
+ export function isClassifyRecord(command, harness, context) {
46
+ const template = classifyCommand(harness, context, "");
47
+ if (!template.startsWith('node "'))
48
+ return false;
49
+ const head = template.slice(0, -1);
50
+ if (command.length > head.length + 4096 || !command.startsWith(head) || !command.endsWith("'"))
51
+ return false;
52
+ const json = command.slice(head.length, -1);
53
+ if (/['\0\r\n]/.test(json))
54
+ return false;
55
+ try {
56
+ const value = JSON.parse(json);
57
+ return !!value && typeof value === "object" && !Array.isArray(value);
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ }
63
+ const WORD = String.raw `(?:"[^"]*"|'[^']*'|[^\s;&|]+)`;
64
+ const CLI = String.raw `(?:"[^"]*cli\.js"|'[^']*cli\.js'|[^\s"';&|]*cli\.js)`;
65
+ const NODE = String.raw `(?:"(?:[^"]*[/\\])?node(?:\.exe)?"|'(?:[^']*[/\\])?node(?:\.exe)?'|(?:[^\s"';&|]*[/\\])?node(?:\.exe)?)`;
66
+ /** Assignments, wrappers and keywords that can stand before the command in a segment. */
67
+ const LEAD = String.raw `(?:[A-Za-z_]\w*=${WORD}?\s+|(?:then|do|else|elif|if|while|until|!)\s+|(?:env|command|builtin|exec|time|timeout|nohup|nice|ionice|xargs|stdbuf|sudo|doas)(?:\s+${WORD}){0,6}?\s+)*`;
68
+ /**
69
+ * A command segment that runs a policy-manager CLI's `classify`, for any session or CLI: `node`
70
+ * with a `cli.js`, or `policy-manager` (also through `npx`), at the start of the script or after
71
+ * an operator, behind any assignments, wrappers (`env`, `exec`, `xargs`...) or keywords. Text
72
+ * that only mentions such a command (a `grep` pattern, a commit message) does not match, and
73
+ * neither does a script nested in quotes (`sh -c '...'`), which gets the normal decision.
74
+ */
75
+ const CLASSIFY_INVOCATION = new RegExp(String.raw `(?:^|[;&|({` +
76
+ "`" +
77
+ String.raw `\n]|\$\()\s*${LEAD}(?:${NODE}\s+(?:-${WORD}\s+)*${CLI}|(?:npx\s+(?:-\S+\s+)*)?(?:@agent-corpus\/)?policy-manager(?:@\S+)?)\s+["']?classify\b`);
78
+ /** A command that runs a policy-manager classification record, for any session or CLI. */
79
+ export function looksLikeClassifyRecord(command) {
80
+ return CLASSIFY_INVOCATION.test(command);
81
+ }
40
82
  /** What a blocked ambiguous request tells the model to do. Never ask for human approval here. */
41
83
  function classifyInstruction(harness, decision, context) {
42
84
  const command = classifyCommand(harness, context);
package/dist/cli.js CHANGED
@@ -115,7 +115,7 @@ try {
115
115
  console.log(values.json ? JSON.stringify(review, null, 2) : formatReview(review));
116
116
  }
117
117
  else if (action === "serve")
118
- await serve(harness, phase ?? "");
118
+ await serve(harness, phase ?? "", cliPath);
119
119
  else if (action === "stop")
120
120
  console.log(JSON.stringify(await send(harness, phase ?? "", { action: "stop" })));
121
121
  else if (action === "review" || action === "classify" || action === "record") {
package/dist/evidence.js CHANGED
@@ -92,7 +92,7 @@ export function sensitive(path) {
92
92
  return (CREDENTIAL_CONFIG_DIRS.test(path) ||
93
93
  path
94
94
  .split(/[\\/]/)
95
- .some((part) => /^(?:\.git|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.gcloud|\.docker|\.gnupg|\.password-store|\.git-credentials|\.vault-token|\.pgpass|\.my\.cnf|\.pypirc|\.npmrc|\.netrc|\.kube|credentials?|secrets?|id_rsa|id_ed25519|id_ecdsa|kubeconfig|terraform\.tfstate(?:\..*)?|.*\.(?:pem|key|pfx|p12))$/i.test(part)));
95
+ .some((part) => /^(?:\.git|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.gcloud|\.docker|\.gnupg|\.password-store|\.git-credentials|\.vault-token|\.pgpass|\.my\.cnf|\.pypirc|\.npmrc|\.netrc|\.kube|(?:credentials?|secrets?)(?:\.(?:json|ya?ml|toml|ini|env|txt|xml|conf|cfg|properties))?|id_rsa|id_ed25519|id_ecdsa|kubeconfig|terraform\.tfstate(?:\..*)?|.*\.(?:pem|key|pfx|p12))$/i.test(part)));
96
96
  }
97
97
  export function protectedPath(path) {
98
98
  return path
package/dist/flow.js CHANGED
@@ -461,6 +461,23 @@ function splitAssignment(word) {
461
461
  value: { ...word, parts: [first.slice(eq + 1), ...word.parts.slice(1)], subs: [] },
462
462
  };
463
463
  }
464
+ /** grep and rg options whose value is a file-name glob. */
465
+ const GLOB_VALUE_OPTIONS = {
466
+ grep: ["--include", "--exclude", "--exclude-dir"],
467
+ egrep: ["--include", "--exclude", "--exclude-dir"],
468
+ fgrep: ["--include", "--exclude", "--exclude-dir"],
469
+ rg: ["--glob", "--iglob", "-g"],
470
+ };
471
+ /**
472
+ * `--include=*.md` or rg's `-g*.ts`: the option name is literal, so expansion can only yield more
473
+ * words of the same option, never another option or program.
474
+ */
475
+ function globValuedOption(program, text) {
476
+ const options = program === undefined ? undefined : GLOB_VALUE_OPTIONS[basename(program)];
477
+ if (!options || text === undefined)
478
+ return false;
479
+ return options.some((option) => option.startsWith("--") ? text.startsWith(`${option}=`) : text.startsWith(option));
480
+ }
464
481
  function runSimple(ctx, node, state, stage, piped) {
465
482
  const { request, profile } = ctx;
466
483
  const refusal = runSubs(ctx, [
@@ -473,8 +490,10 @@ function runSimple(ctx, node, state, stage, piped) {
473
490
  // A glob in the command name or in a flag-like word expands to whatever file names exist, so
474
491
  // `r[m] -rf x` runs `rm` once a file called `rm` is there, and `--forc[e]` can become `--force`.
475
492
  const hasGlob = (word) => word.glob === true && plainText(word) !== "[" && plainText(word) !== "[[";
493
+ const program0 = plainText(node.argv[0]);
476
494
  const globbed = node.argv.find((word, index) => hasGlob(word) &&
477
- (index === 0 || word.parts.some((p) => typeof p === "string" && p.startsWith("-"))));
495
+ (index === 0 || word.parts.some((p) => typeof p === "string" && p.startsWith("-"))) &&
496
+ !(index > 0 && globValuedOption(program0, plainText(word))));
478
497
  if (globbed)
479
498
  return human(request, "unknown", "A pattern in a command name or option requires human review");
480
499
  const values = node.assigns.map((a) => a.value);
@@ -1339,14 +1358,29 @@ function runCase(ctx, node, state) {
1339
1358
  return runRedirects(ctx, node.redirects, state);
1340
1359
  }
1341
1360
  // --- lists, pipelines and the entry point -----------------------------------------------------
1361
+ const ASSIGNABLE = /^[A-Z][A-Z0-9_]*$/;
1362
+ /** bash and zsh variables whose assignment can fail: read-only, numeric, or tied to the process. */
1363
+ const SHELL_SPECIAL = /^(?:BASH\w*|ZSH\w*|SHELLOPTS|EUID|UID|EGID|GID|GROUPS|PPID|USERNAME|ARGC|HISTCMD|LINENO|SECONDS|EPOCH\w*|S?RANDOM|ERRNO|OPTIND|OPTARG|TTYIDLE|SHLVL|COLUMNS|LINES|HISTSIZE|HISTFILESIZE|SAVEHIST|DIRSTACKSIZE|KEYTIMEOUT|LISTMAX|LOGCHECK|MAILCHECK|PERIOD|TMOUT|TRY_BLOCK_\w+|FUNCNAME|FUNCNEST|COMP_\w+|READLINE_\w+)$/;
1342
1364
  /**
1343
- * True when the pipeline always succeeds: `true`, `:`, or `cd` to an absolute directory that exists
1365
+ * True when the pipeline always succeeds: a literal assignment, `true`, `:`,
1366
+ * or `cd` to an absolute directory that exists
1344
1367
  * and can be entered now. Only used to know that an `&&` chain goes on past it; the directory it
1345
1368
  * started from is still kept as possible.
1346
1369
  */
1347
1370
  function cannotFail(ctx, node, state) {
1348
1371
  const stage = node.stages.length === 1 && !node.negated ? node.stages[0] : undefined;
1349
- if (stage?.kind !== "simple" || stage.assigns.length || stage.redirects.length)
1372
+ if (stage?.kind !== "simple" || stage.redirects.length)
1373
+ return false;
1374
+ // `S=/x && H=y; use $H`: a bare assignment with no substitution succeeds. Only uppercase names
1375
+ // that the shell does not reserve; zsh's lowercase specials and the read-only or numeric
1376
+ // specials of bash and zsh can refuse a value.
1377
+ if (!stage.argv.length)
1378
+ return (stage.assigns.length > 0 &&
1379
+ stage.assigns.every((a) => ASSIGNABLE.test(a.name) &&
1380
+ !SHELL_SPECIAL.test(a.name) &&
1381
+ !BANNED_ENV.test(a.name) &&
1382
+ !a.value.subs.length));
1383
+ if (stage.assigns.length)
1350
1384
  return false;
1351
1385
  const argv = stage.argv.map(plainText);
1352
1386
  const [program, target] = argv;
@@ -1,4 +1,4 @@
1
- import { statSync } from "node:fs";
1
+ import { lstatSync, readdirSync, statSync } from "node:fs";
2
2
  import { basename, delimiter, dirname, join, resolve } from "node:path";
3
3
  import { branchEvidence, canonical, disposable, git, inside, isProtectedPath, OUTSIDE_REPOSITORY, pathEvidence, policyState, protectedPath, resolveWord, sensitive, tempRoots, tempWrite, } from "./evidence.js";
4
4
  import { commandDecision } from "./flow.js";
@@ -294,6 +294,8 @@ function sedScriptPaths(script) {
294
294
  function textOperands(program, args) {
295
295
  const text = new Set();
296
296
  const files = [];
297
+ // Values of file-name pattern options (`--include`, rg `-g`), found by this same parse.
298
+ const patterns = new Set();
297
299
  if (program === "gh") {
298
300
  for (const [index, word] of args.entries()) {
299
301
  if (GH_TEXT.has(word))
@@ -301,16 +303,19 @@ function textOperands(program, args) {
301
303
  else if (/^--(?:body|title|jq|template|notes)=/.test(word))
302
304
  text.add(index);
303
305
  }
304
- return { text, paths: [], files };
306
+ return { text, paths: [], files, patterns };
305
307
  }
308
+ if (program === "find")
309
+ return { text, paths: [], files, patterns: findPatterns(args) };
306
310
  const values = SHORT_VALUES[program];
307
311
  if (values === undefined)
308
- return { text, paths: [], files };
312
+ return { text, paths: [], files, patterns };
309
313
  // Fallback when an option cannot be understood: every operand is checked.
310
314
  const everyWord = {
311
315
  text: new Set(),
312
316
  paths: [],
313
317
  files: args.filter((arg) => arg !== "" && !arg.startsWith("-")),
318
+ patterns: new Set(),
314
319
  };
315
320
  // grep, rg and GNU sed accept options after operands, so collect everything before deciding
316
321
  // which operand, if any, is the pattern or script.
@@ -344,9 +349,15 @@ function textOperands(program, args) {
344
349
  // A pattern or script file means there is no pattern operand: every operand is a file.
345
350
  if (name === "--file")
346
351
  explicit = true;
352
+ const pattern = NAME_PATTERN_OPTIONS[program]?.includes(name);
353
+ if (pattern && eq >= 0)
354
+ patterns.add(index);
347
355
  // A value-taking long option consumes the next word, which stays a checked operand.
348
- if (eq < 0 && LONG_VALUES[program]?.has(name))
356
+ if (eq < 0 && LONG_VALUES[program]?.has(name)) {
349
357
  index++;
358
+ if (pattern)
359
+ patterns.add(index);
360
+ }
350
361
  }
351
362
  continue;
352
363
  }
@@ -372,6 +383,8 @@ function textOperands(program, args) {
372
383
  explicit = true;
373
384
  if (at + 1 === word.length)
374
385
  index++;
386
+ if (program === "rg" && flag === "g")
387
+ patterns.add(index);
375
388
  break;
376
389
  }
377
390
  }
@@ -392,7 +405,7 @@ function textOperands(program, args) {
392
405
  text.add(index);
393
406
  files.push(...operands.map((index) => args[index] ?? ""));
394
407
  const paths = program === "sed" ? scripts.flatMap(([, script]) => sedScriptPaths(script)) : [];
395
- return { text, paths, files };
408
+ return { text, paths, files, patterns };
396
409
  }
397
410
  /** Pattern and script options per program, besides the value lists. */
398
411
  const PATTERN_OPTIONS = {
@@ -598,6 +611,16 @@ export function permissiveWrite(cwd, input, profile, fill) {
598
611
  fill.script.approved = true;
599
612
  return check;
600
613
  }
614
+ /** A file with another hard link may alias a file outside the scratch root; unknown counts as yes. */
615
+ function hardLinked(path) {
616
+ try {
617
+ const stat = lstatSync(path);
618
+ return !stat.isDirectory() && stat.nlink > 1;
619
+ }
620
+ catch (error) {
621
+ return error.code !== "ENOENT";
622
+ }
623
+ }
601
624
  function writeEvidence(cwd, input, profile) {
602
625
  let lexical;
603
626
  let path;
@@ -614,6 +637,7 @@ function writeEvidence(cwd, input, profile) {
614
637
  const target = path;
615
638
  if (!policyState(target) &&
616
639
  !policyState(lexical) &&
640
+ !hardLinked(target) &&
617
641
  profile.scratchRoots.some((root) => inside(root, target)))
618
642
  return {
619
643
  allowed: true,
@@ -715,7 +739,53 @@ function restorePaths(rest) {
715
739
  fromHead: staged,
716
740
  };
717
741
  }
718
- function gitDecision(request, argv, cwdForGit, sole) {
742
+ /**
743
+ * `git worktree remove --force <path>` where `path` is a linked worktree of this repository (never
744
+ * the main one) strictly inside a temp or scratch root and outside the main checkout.
745
+ */
746
+ function disposableWorktree(cwd, args, roots, fill) {
747
+ if (fill?.script.tainted)
748
+ return false;
749
+ const paths = [];
750
+ let ended = false;
751
+ let forces = 0;
752
+ for (const arg of args) {
753
+ if (!ended && arg === "--")
754
+ ended = true;
755
+ else if (!ended && arg.startsWith("-")) {
756
+ if (arg !== "-f" && !abbreviates(arg, "--force"))
757
+ return false;
758
+ forces++;
759
+ }
760
+ else
761
+ paths.push(arg);
762
+ }
763
+ // A second force also removes a locked worktree, and a lock is an explicit keep marker.
764
+ if (paths.length !== 1 || forces !== 1)
765
+ return false;
766
+ try {
767
+ const target = canonical(resolveWord(cwd, paths[0]));
768
+ if (policyState(target) || !roots.some((root) => root !== target && inside(root, target)))
769
+ return false;
770
+ const listed = git(cwd, ["worktree", "list", "--porcelain"])
771
+ .split("\n")
772
+ .filter((line) => line.startsWith("worktree "))
773
+ .map((line) => canonical(line.slice("worktree ".length)));
774
+ const [main, ...linked] = listed;
775
+ if (main === undefined || inside(main, target) || !linked.includes(target))
776
+ return false;
777
+ // Removal deletes the whole directory, so no other checkout may live inside it.
778
+ if (listed.some((path) => path !== target && inside(target, path)))
779
+ return false;
780
+ if (fill?.reorder)
781
+ fill.script.approved = true;
782
+ return true;
783
+ }
784
+ catch {
785
+ return false;
786
+ }
787
+ }
788
+ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
719
789
  const args = argv.slice(1);
720
790
  let index = 0;
721
791
  let cwd = cwdForGit;
@@ -793,8 +863,13 @@ function gitDecision(request, argv, cwdForGit, sole) {
793
863
  return worktreeAdd(request, cwd, rest.slice(rest.indexOf("add") + 1)) ?? ok();
794
864
  if (sub === "worktree" &&
795
865
  ["remove", "prune"].includes(positional[0] ?? "") &&
796
- (has("-f", "--force") || positional[0] === "prune"))
797
- return human(request, "destructive", "Forced worktree removal requires human approval");
866
+ (has("-f", "--force") || cluster("f") || positional[0] === "prune"))
867
+ return positional[0] === "remove" && disposableWorktree(cwd, rest.slice(1), roots, fill)
868
+ ? ok("Removes a linked worktree inside a temp or scratch directory")
869
+ : positional[0] === "prune" &&
870
+ rest.slice(1).every((arg) => ["-n", "-v", "--dry-run", "--verbose"].includes(arg))
871
+ ? ok("Prunes only records of worktrees whose directories are gone")
872
+ : human(request, "destructive", "Forced worktree removal requires human approval");
798
873
  if (sub === "config" &&
799
874
  !has("--get", "--get-all", "--get-regexp", "--list", "-l", "--show-origin") &&
800
875
  !safeConfigWrite(rest))
@@ -941,6 +1016,8 @@ const AWS_METADATA_GETTERS = new Set([
941
1016
  "get-metric-statistics",
942
1017
  "get-log-events",
943
1018
  ]);
1019
+ /** az operations that only read but whose verb is not list or show. */
1020
+ const AZ_READ_OPERATIONS = new Set(["boards query"]);
944
1021
  function readVerb(argv) {
945
1022
  const [tool] = argv;
946
1023
  const firstOption = argv.findIndex((arg) => arg.startsWith("-"));
@@ -955,7 +1032,8 @@ function readVerb(argv) {
955
1032
  if (/token|secret|password|credential|key/i.test(verb))
956
1033
  return false;
957
1034
  if (tool === "az")
958
- return /^(?:list|show|exists|list-[a-z-]+|show-[a-z-]+)$/.test(verb);
1035
+ return (/^(?:list|show|exists|list-[a-z-]+|show-[a-z-]+)$/.test(verb) ||
1036
+ AZ_READ_OPERATIONS.has(operation.join(" ")));
959
1037
  if (tool === "aws") {
960
1038
  // `get-*` is not safe as a family: it includes secret, password, token and access-detail
961
1039
  // retrieval. Only `describe-`/`list-` and an explicit set of metadata getters are automatic.
@@ -1085,6 +1163,305 @@ function autoCd(cwd, word) {
1085
1163
  }
1086
1164
  });
1087
1165
  }
1166
+ const PRINTERS = new Set(["echo", "printf"]);
1167
+ const GLOB = /[*?[]/;
1168
+ /** At most this many directory entries are matched against a glob operand. */
1169
+ const GLOB_ENTRIES = 5000;
1170
+ /**
1171
+ * Whether a word that may be a file operand names a credential: by name, as resolved against the
1172
+ * working directory (a symlink to a key, or a cwd inside `~/.ssh`), or, for a glob in its last
1173
+ * component, by any entry it would match.
1174
+ */
1175
+ function sensitiveOperand(cwd, word) {
1176
+ if (word === "")
1177
+ return false;
1178
+ if (sensitive(word))
1179
+ return true;
1180
+ if (GLOB.test(word))
1181
+ return sensitiveGlob(cwd, word);
1182
+ try {
1183
+ const lexical = resolveWord(cwd, word);
1184
+ if (!lstatExists(lexical))
1185
+ return false;
1186
+ return sensitive(lexical) || sensitive(canonical(lexical));
1187
+ }
1188
+ catch {
1189
+ return false;
1190
+ }
1191
+ }
1192
+ /**
1193
+ * Expands a glob one component at a time, as the shell would, and reports whether any directory
1194
+ * it passes or entry it matches is a credential path. Fails closed: an unreadable directory, an
1195
+ * unresolvable entry or more than GLOB_ENTRIES entries in total count as sensitive.
1196
+ */
1197
+ function sensitiveGlob(cwd, word) {
1198
+ try {
1199
+ const parts = word.split(/[\\/]/);
1200
+ // zsh `**/` matches any depth (and `***/` follows symlinks): too wide to expand here.
1201
+ if (parts.some((part) => part.includes("**")))
1202
+ return true;
1203
+ const first = parts.findIndex((part) => GLOB.test(part));
1204
+ const prefix = parts.slice(0, first).join("/");
1205
+ const start = resolveWord(cwd, first === 0 ? "." : prefix || "/");
1206
+ if (sensitive(start) || sensitive(canonical(start)))
1207
+ return true;
1208
+ let current = [start];
1209
+ let budget = GLOB_ENTRIES;
1210
+ for (const part of parts.slice(first)) {
1211
+ if (part === "" || part === ".")
1212
+ continue;
1213
+ const next = [];
1214
+ for (const dir of current) {
1215
+ if (!GLOB.test(part)) {
1216
+ const path = join(dir, part);
1217
+ if (sensitive(path) || (lstatExists(path) && sensitive(canonical(path))))
1218
+ return true;
1219
+ next.push(path);
1220
+ continue;
1221
+ }
1222
+ let entries;
1223
+ try {
1224
+ if (!statSync(dir).isDirectory())
1225
+ continue;
1226
+ entries = readdirSync(dir);
1227
+ }
1228
+ catch (error) {
1229
+ if (error.code === "ENOENT")
1230
+ continue;
1231
+ return true;
1232
+ }
1233
+ budget -= entries.length;
1234
+ if (budget < 0)
1235
+ return true;
1236
+ const pattern = globPattern(part);
1237
+ // `*` skips dot files unless the pattern itself starts with a dot.
1238
+ for (const name of entries) {
1239
+ if ((name.startsWith(".") && !part.startsWith(".")) || !pattern.test(name))
1240
+ continue;
1241
+ const path = join(dir, name);
1242
+ if (sensitive(name) || sensitive(canonical(path)))
1243
+ return true;
1244
+ next.push(path);
1245
+ }
1246
+ }
1247
+ current = next;
1248
+ }
1249
+ return false;
1250
+ }
1251
+ catch {
1252
+ return true;
1253
+ }
1254
+ }
1255
+ function lstatExists(path) {
1256
+ try {
1257
+ lstatSync(path);
1258
+ return true;
1259
+ }
1260
+ catch {
1261
+ return false;
1262
+ }
1263
+ }
1264
+ /** A shell glob for one path component: `*`, `?` and bracket classes. */
1265
+ function globPattern(glob) {
1266
+ let source = "";
1267
+ for (let index = 0; index < glob.length; index++) {
1268
+ const char = glob[index];
1269
+ if (char === "*")
1270
+ source += ".*";
1271
+ else if (char === "?")
1272
+ source += ".";
1273
+ else if (char === "[") {
1274
+ const close = glob.indexOf("]", index + 2);
1275
+ if (close < 0)
1276
+ source += "\\[";
1277
+ else {
1278
+ const body = glob
1279
+ .slice(index + 1, close)
1280
+ .replace(/^[!^]/, "^")
1281
+ .replace(/\\/g, "\\\\");
1282
+ source += `[${body}]`;
1283
+ index = close;
1284
+ }
1285
+ }
1286
+ else
1287
+ source += char.replace(/[.+^${}()|[\]\\/-]/g, "\\$&");
1288
+ }
1289
+ try {
1290
+ return new RegExp(`^${source}$`, "s");
1291
+ }
1292
+ catch {
1293
+ return /^/; // an unparsable class matches everything, which only sends more to a person
1294
+ }
1295
+ }
1296
+ const NAME_PATTERN_OPTIONS = {
1297
+ grep: ["--include", "--exclude", "--exclude-dir"],
1298
+ egrep: ["--include", "--exclude", "--exclude-dir"],
1299
+ fgrep: ["--include", "--exclude", "--exclude-dir"],
1300
+ rg: ["--glob", "--iglob", "-g"],
1301
+ find: ["-name", "-iname", "-path", "-ipath", "-wholename", "-iwholename"],
1302
+ };
1303
+ /**
1304
+ * Indices of find's `-name`/`-path` values. Every value-taking primary consumes its value; an
1305
+ * unknown primary (`-printf`, `-newerXY`) makes the parse uncertain, so nothing is a pattern.
1306
+ */
1307
+ function findPatterns(args) {
1308
+ const found = new Set();
1309
+ const names = NAME_PATTERN_OPTIONS.find ?? [];
1310
+ for (let index = 0; index < args.length; index++) {
1311
+ const word = args[index] ?? "";
1312
+ if (FIND_VALUE_PRIMARIES.has(word)) {
1313
+ if (names.includes(word))
1314
+ found.add(index + 1);
1315
+ index++;
1316
+ }
1317
+ else if (/^[-(!)]/.test(word) && !FIND_FLAG_PRIMARIES.has(word))
1318
+ return new Set();
1319
+ }
1320
+ return found;
1321
+ }
1322
+ /** Index of chmod's mode or chown's owner (`+x`, `u+w`, `user:group`), which names no file. */
1323
+ function modeIndex(program, args) {
1324
+ if (!["chmod", "chown"].includes(program) || args.some((arg) => arg.startsWith("--reference")))
1325
+ return undefined;
1326
+ // BSD chmod's ACL options (-N, -E, -C, -i, -I) take no mode: every operand is a file.
1327
+ if (program === "chmod" && args.some((arg) => /^-[A-Za-z]*[NECiI]/.test(arg)))
1328
+ return undefined;
1329
+ for (let index = 0; index < args.length; index++) {
1330
+ const arg = args[index] ?? "";
1331
+ if (arg === "--")
1332
+ return index + 1 < args.length ? index + 1 : undefined;
1333
+ // `chmod -w file`: a mode may start with `-`.
1334
+ if (arg.startsWith("-") && !(program === "chmod" && /^-[rwxXst]+$/.test(arg)))
1335
+ continue;
1336
+ return index;
1337
+ }
1338
+ return undefined;
1339
+ }
1340
+ /**
1341
+ * GNU long options of cp and ln. Of those that take a separate value, only --target-directory
1342
+ * matters: a consumed `--sparse`/`--no-preserve` value only adds a read-checked source.
1343
+ */
1344
+ const COPY_LONG = {
1345
+ cp: [
1346
+ "--archive",
1347
+ "--attributes-only",
1348
+ "--backup",
1349
+ "--copy-contents",
1350
+ "--debug",
1351
+ "--dereference",
1352
+ "--force",
1353
+ "--interactive",
1354
+ "--keep-directory-symlink",
1355
+ "--link",
1356
+ "--no-clobber",
1357
+ "--no-dereference",
1358
+ "--no-preserve",
1359
+ "--no-target-directory",
1360
+ "--one-file-system",
1361
+ "--parents",
1362
+ "--preserve",
1363
+ "--recursive",
1364
+ "--reflink",
1365
+ "--remove-destination",
1366
+ "--sparse",
1367
+ "--strip-trailing-slashes",
1368
+ "--suffix",
1369
+ "--symbolic-link",
1370
+ "--target-directory",
1371
+ "--update",
1372
+ "--verbose",
1373
+ ],
1374
+ ln: [
1375
+ "--backup",
1376
+ "--directory",
1377
+ "--force",
1378
+ "--interactive",
1379
+ "--logical",
1380
+ "--no-dereference",
1381
+ "--no-target-directory",
1382
+ "--physical",
1383
+ "--relative",
1384
+ "--suffix",
1385
+ "--symbolic",
1386
+ "--target-directory",
1387
+ "--verbose",
1388
+ ],
1389
+ };
1390
+ /**
1391
+ * Sources and written targets of `cp` and `ln`: sources are only read (a symlink's target is not
1392
+ * touched), so they take the read check. Undefined when the split is uncertain (backup suffixes,
1393
+ * hard links, unknown options), and every operand is then checked as a write.
1394
+ */
1395
+ function copySources(program, args, cwd) {
1396
+ if (program !== "cp" && program !== "ln")
1397
+ return undefined;
1398
+ const operands = [];
1399
+ let target;
1400
+ let ended = false;
1401
+ let symbolic = false;
1402
+ for (let index = 0; index < args.length; index++) {
1403
+ const arg = args[index] ?? "";
1404
+ if (ended || !arg.startsWith("-") || arg === "-") {
1405
+ operands.push(arg);
1406
+ continue;
1407
+ }
1408
+ if (arg === "--") {
1409
+ ended = true;
1410
+ continue;
1411
+ }
1412
+ if (arg.startsWith("--")) {
1413
+ // Resolved as GNU getopt does (exact or unique prefix); unknown or ambiguous fails closed.
1414
+ const given = arg.split("=")[0] ?? "";
1415
+ const known = COPY_LONG[program] ?? [];
1416
+ const matches = known.includes(given) ? [given] : known.filter((o) => o.startsWith(given));
1417
+ const name = matches.length === 1 ? matches[0] : undefined;
1418
+ if (name === undefined || ["--backup", "--suffix", "--link"].includes(name))
1419
+ return undefined;
1420
+ if (name === "--symbolic")
1421
+ symbolic = true;
1422
+ if (name === "--target-directory") {
1423
+ if (target !== undefined)
1424
+ return undefined;
1425
+ target = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : args[++index];
1426
+ if (target === undefined)
1427
+ return undefined;
1428
+ }
1429
+ continue;
1430
+ }
1431
+ const letters = arg.slice(1);
1432
+ const at = letters.indexOf("t");
1433
+ const flags = at < 0 ? letters : letters.slice(0, at);
1434
+ if (/[bS]/.test(flags))
1435
+ return undefined;
1436
+ if (program === "cp" && flags.includes("l"))
1437
+ return undefined;
1438
+ if (program === "ln" && flags.includes("s"))
1439
+ symbolic = true;
1440
+ if (at >= 0) {
1441
+ if (target !== undefined)
1442
+ return undefined;
1443
+ target = at + 1 < letters.length ? letters.slice(at + 1) : args[++index];
1444
+ if (target === undefined)
1445
+ return undefined;
1446
+ }
1447
+ }
1448
+ // A hard link shares its source's inode, so a later write through it changes the source.
1449
+ if (program === "ln" && !symbolic)
1450
+ return undefined;
1451
+ if (target !== undefined)
1452
+ return { sources: operands, targets: [target] };
1453
+ if (operands.length >= 2)
1454
+ return { sources: operands.slice(0, -1), targets: operands.slice(-1) };
1455
+ // `ln -s path` links `basename(path)` in the working directory.
1456
+ if (program === "ln" && operands.length === 1) {
1457
+ const only = operands[0] ?? "";
1458
+ const name = basename(only.replace(/[\\/]+$/, ""));
1459
+ if (!name || name === "." || name === "..")
1460
+ return undefined;
1461
+ return { sources: operands, targets: [resolve(cwd, name)] };
1462
+ }
1463
+ return undefined;
1464
+ }
1088
1465
  export function simpleDecision(request, command, profile, depth, stageIndex, cwd, fill) {
1089
1466
  for (const [name] of command.env)
1090
1467
  if (BANNED_ENV.test(name))
@@ -1152,14 +1529,20 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
1152
1529
  // known text positions (sed scripts, grep patterns, gh message text) are not paths, but the
1153
1530
  // files a sed script reads or writes are.
1154
1531
  const operands = textOperands(program, args);
1532
+ const namePatterns = operands.patterns;
1155
1533
  for (const [index, word] of args.entries()) {
1156
1534
  if (operands.text.has(index))
1157
1535
  continue;
1158
1536
  const candidate = word.includes("=") ? word.slice(word.indexOf("=") + 1) : word;
1159
- if (candidate.includes("/") || candidate.startsWith(".")) {
1160
- if (sensitive(candidate))
1161
- return human(request, "sensitive", "Protected path requires human approval");
1162
- }
1537
+ // echo and printf read no file, so only a path-like word is judged, by name.
1538
+ const pathLike = candidate.includes("/") || candidate.startsWith(".");
1539
+ // A file-name pattern (`--include=*.md`, `find -name '*.ts'`) is matched below the searched
1540
+ // paths, not against the working directory, so it is judged by name only.
1541
+ const namePattern = namePatterns.has(index);
1542
+ if (PRINTERS.has(program) || namePattern
1543
+ ? (pathLike || namePattern) && sensitive(candidate)
1544
+ : sensitiveOperand(cwd, candidate) || (candidate !== word && sensitiveOperand(cwd, word)))
1545
+ return human(request, "sensitive", "Protected path requires human approval");
1163
1546
  }
1164
1547
  if (operands.paths.some((path) => sensitive(path)))
1165
1548
  return human(request, "sensitive", "Protected path requires human approval");
@@ -1251,10 +1634,15 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
1251
1634
  : undefined);
1252
1635
  return value === undefined ? [] : [value];
1253
1636
  });
1254
- for (const file of [
1255
- ...args.filter((arg) => !arg.startsWith("-") && !/^[0-9]+$/.test(arg)),
1256
- ...optionValues,
1257
- ]) {
1637
+ const split = copySources(program, args, cwd);
1638
+ const mode = modeIndex(program, args);
1639
+ const operands = args.filter((arg, index) => index !== mode && !arg.startsWith("-") && !/^[0-9]+$/.test(arg));
1640
+ for (const file of split?.sources ?? []) {
1641
+ const check = permissiveRead(cwd, file);
1642
+ if (!check.allowed)
1643
+ return human(request, check.category, check.reason);
1644
+ }
1645
+ for (const file of [...(split?.targets ?? operands), ...optionValues]) {
1258
1646
  const check = permissiveWrite(cwd, file, profile, fill);
1259
1647
  if (!check.allowed)
1260
1648
  return human(request, check.category, check.reason);
@@ -1281,7 +1669,7 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
1281
1669
  /(?:-X|--request)[=\s]?(?:DELETE|PUT)\b/i.test(joined))
1282
1670
  return human(request, "destructive", "Destructive HTTP verbs require human approval");
1283
1671
  if (program === "git")
1284
- return gitDecision(request, argv, cwd, () => argv[0] === "git" && command.argv[0] === "git" && depth === 0 && soleEffect(request));
1672
+ return gitDecision(request, argv, cwd, () => argv[0] === "git" && command.argv[0] === "git" && depth === 0 && soleEffect(request), [...profile.scratchRoots, ...tempRoots()], fill);
1285
1673
  if (program === "gh") {
1286
1674
  const gh = ghDecision(request, argv);
1287
1675
  if (gh)
package/dist/policy.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { type Profile } from "./profile.js";
2
2
  import { type Category, type Classification, type Decision, type Request } from "./types.js";
3
3
  export declare function hash(value: unknown): string;
4
+ /** Shell tools whose `description` only labels the command. Elsewhere it can be content. */
5
+ export declare const SHELL_TOOLS: Set<string>;
4
6
  /** The correlation hash of a request, over its effect-relevant input only. */
5
7
  export declare function requestHash(request: Request): string;
6
8
  export declare function words(command: string): string[] | undefined;
package/dist/policy.js CHANGED
@@ -10,7 +10,7 @@ export function hash(value) {
10
10
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
11
11
  }
12
12
  /** Shell tools whose `description` only labels the command. Elsewhere it can be content. */
13
- const SHELL_TOOLS = new Set(["Bash", "bash", "exec_command", "shell"]);
13
+ export const SHELL_TOOLS = new Set(["Bash", "bash", "exec_command", "shell"]);
14
14
  /** The correlation hash of a request, over its effect-relevant input only. */
15
15
  export function requestHash(request) {
16
16
  if (!SHELL_TOOLS.has(request.tool))
package/dist/service.d.ts CHANGED
@@ -7,7 +7,7 @@ interface Message {
7
7
  report?: OutcomeReport;
8
8
  phase?: string;
9
9
  }
10
- export declare function serve(harness: string, sessionId: string): Promise<void>;
10
+ export declare function serve(harness: string, sessionId: string, cliPath?: string): Promise<void>;
11
11
  export declare function send(harness: string, sessionId: string, message: Omit<Message, "token">): Promise<unknown>;
12
12
  /**
13
13
  * Stops a session's service. A session with no service (it never started, already ended, or the
package/dist/service.js CHANGED
@@ -11,7 +11,7 @@ function endpoint(directory) {
11
11
  ? `\\\\.\\pipe\\acp-${hash(directory).slice(0, 32)}`
12
12
  : join(directory, "service.sock");
13
13
  }
14
- export async function serve(harness, sessionId) {
14
+ export async function serve(harness, sessionId, cliPath) {
15
15
  const directory = sessionDirectory(harness, sessionId), token = sessionToken(directory);
16
16
  let profile = strictProfile;
17
17
  let profileFailure = false;
@@ -21,7 +21,7 @@ export async function serve(harness, sessionId) {
21
21
  catch {
22
22
  profileFailure = true; // an unreadable or untrusted profile must never loosen policy
23
23
  }
24
- const session = new PolicySession(directory, harness, sessionId, profile);
24
+ const session = new PolicySession(directory, harness, sessionId, profile, cliPath);
25
25
  const server = createServer((socket) => {
26
26
  socket.setTimeout(3000, () => socket.destroy());
27
27
  let data = "";
package/dist/session.d.ts CHANGED
@@ -7,6 +7,8 @@ export declare class PolicySession {
7
7
  readonly harness: string;
8
8
  readonly sessionId: string;
9
9
  readonly profile: Profile;
10
+ /** This package's `cli.js`: the path in the record command the hook gives the model. */
11
+ readonly cliPath?: string | undefined;
10
12
  private cache;
11
13
  private pending;
12
14
  private states;
@@ -15,7 +17,16 @@ export declare class PolicySession {
15
17
  /** Files this session created, and the paths each approved request may create. */
16
18
  private created;
17
19
  private creating;
18
- constructor(directory: string, harness: string, sessionId: string, profile?: Profile);
20
+ constructor(directory: string, harness: string, sessionId: string, profile?: Profile,
21
+ /** This package's `cli.js`: the path in the record command the hook gives the model. */
22
+ cliPath?: string | undefined);
23
+ /**
24
+ * The record command the hook gives this session is approved before the policy runs: the
25
+ * engine cannot always verify an installed CLI outside the repository or a here-string (strict
26
+ * mode never can), so the round trip could not finish. Any other classification record, for
27
+ * another session or CLI or with anything added, goes to a person.
28
+ */
29
+ private classifyRecord;
19
30
  private state;
20
31
  private remember;
21
32
  /**
package/dist/session.js CHANGED
@@ -1,6 +1,7 @@
1
+ import { isClassifyRecord, looksLikeClassifyRecord } from "./adapters.js";
1
2
  import { audit, requestSummary } from "./audit.js";
2
3
  import { creationTargets, pathKey, settle, withCreated, } from "./created.js";
3
- import { evaluate, hash, requestHash as requestHashOf } from "./policy.js";
4
+ import { evaluate, hash, requestHash as requestHashOf, result, SHELL_TOOLS } from "./policy.js";
4
5
  import { strictProfile } from "./profile.js";
5
6
  import { redactText } from "./redact.js";
6
7
  import { CATEGORIES, } from "./types.js";
@@ -15,6 +16,7 @@ export class PolicySession {
15
16
  harness;
16
17
  sessionId;
17
18
  profile;
19
+ cliPath;
18
20
  cache = new Map();
19
21
  pending = new Map();
20
22
  states = new Map();
@@ -23,11 +25,40 @@ export class PolicySession {
23
25
  /** Files this session created, and the paths each approved request may create. */
24
26
  created = new Map();
25
27
  creating = new Map();
26
- constructor(directory, harness, sessionId, profile = strictProfile) {
28
+ constructor(directory, harness, sessionId, profile = strictProfile,
29
+ /** This package's `cli.js`: the path in the record command the hook gives the model. */
30
+ cliPath) {
27
31
  this.directory = directory;
28
32
  this.harness = harness;
29
33
  this.sessionId = sessionId;
30
34
  this.profile = profile;
35
+ this.cliPath = cliPath;
36
+ }
37
+ /**
38
+ * The record command the hook gives this session is approved before the policy runs: the
39
+ * engine cannot always verify an installed CLI outside the repository or a here-string (strict
40
+ * mode never can), so the round trip could not finish. Any other classification record, for
41
+ * another session or CLI or with anything added, goes to a person.
42
+ */
43
+ classifyRecord(request) {
44
+ const input = request.input;
45
+ const command = input.command ?? input.cmd;
46
+ if (!SHELL_TOOLS.has(request.tool) ||
47
+ typeof command !== "string" ||
48
+ !looksLikeClassifyRecord(command))
49
+ return undefined;
50
+ const cwd = input.workdir ?? input.cwd ?? request.cwd;
51
+ if (this.cliPath &&
52
+ cwd === request.cwd &&
53
+ input.env === undefined &&
54
+ input.shell === undefined &&
55
+ input.stdin === undefined &&
56
+ isClassifyRecord(command, request.harness, {
57
+ cliPath: this.cliPath,
58
+ sessionId: this.sessionId,
59
+ }))
60
+ return result(request, "temp-write", "Records a classification for this session", true);
61
+ return result(request, "unknown", "A classification record for another session or CLI, or with anything added, requires human review");
31
62
  }
32
63
  state(requestHash) {
33
64
  const state = this.states.get(requestHash);
@@ -93,7 +124,8 @@ export class PolicySession {
93
124
  ...(ai.recoverable === undefined ? {} : { recoverable: ai.recoverable }),
94
125
  ...(ai.rationale ? { rationale: redactText(ai.rationale, 200) } : {}),
95
126
  });
96
- let decision = withCreated(this.created, () => evaluate(request, ai ?? cachedAi ?? known?.ai, this.profile));
127
+ let decision = this.classifyRecord(request) ??
128
+ withCreated(this.created, () => evaluate(request, ai ?? cachedAi ?? known?.ai, this.profile));
97
129
  if (decision.tier === "ambiguous") {
98
130
  if (ai && !decision.classification)
99
131
  this.remember(requestHash, { invalid: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-corpus/policy-manager",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Deterministic, session-scoped permission decisions with audit logs and bounded AI classification.",
5
5
  "keywords": [
6
6
  "coding-agent",