@agent-corpus/policy-manager 0.3.0 → 0.5.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.
@@ -1,5 +1,9 @@
1
+ import { commandDecision } from "./flow.js";
1
2
  import type { Profile } from "./profile.js";
3
+ import { type Redirect, type SimpleCommand } from "./shell.js";
2
4
  import type { Decision, Request } from "./types.js";
5
+ export declare const BANNED_ENV: RegExp;
6
+ export declare function human(request: Request, category: Decision["category"], reason: string): Decision;
3
7
  export declare function permissiveRead(cwd: string, input: string): {
4
8
  allowed: boolean;
5
9
  category: "sensitive";
@@ -14,10 +18,15 @@ export declare function permissiveWrite(cwd: string, input: string, profile: Pro
14
18
  category: "code-read" | "worktree-write" | "sensitive";
15
19
  reason: string;
16
20
  };
17
- /**
18
- * Evaluates a compound command. `cd <literal>` is tracked: every later command is judged in each
19
- * directory it could run in (before and after the `cd`, since `cd x || ...` may fail), so a command
20
- * that only looks safe relative to the starting directory cannot hide behind a `cd`.
21
- */
22
- export declare function commandDecision(request: Request, command: string, profile: Profile, depth?: number, start?: string[]): Decision;
21
+ interface Unwrapped {
22
+ argv: string[];
23
+ /** Assignments given to `env`, which the parser does not see as shell assignments. */
24
+ env: string[];
25
+ refusal?: string;
26
+ }
27
+ export declare function unwrap(argv: string[]): Unwrapped;
28
+ /** Judges one redirection's target in `cwd`; undefined means it is acceptable. */
29
+ export declare function redirectDecision(request: Request, redirect: Redirect, profile: Profile, cwd: string): Decision | undefined;
30
+ export declare function simpleDecision(request: Request, command: SimpleCommand, profile: Profile, depth: number, stageIndex: number, cwd: string): Decision;
31
+ export { commandDecision };
23
32
  //# sourceMappingURL=permissive.d.ts.map
@@ -1,9 +1,9 @@
1
- import { homedir } from "node:os";
2
- import { basename, join, resolve } from "node:path";
3
- import { branchEvidence, canonical, inside, isProtectedPath, pathEvidence, sensitive, } from "./evidence.js";
1
+ import { basename, resolve } from "node:path";
2
+ import { branchEvidence, canonical, inside, isProtectedPath, pathEvidence, protectedPath, sensitive, } from "./evidence.js";
3
+ import { commandDecision } from "./flow.js";
4
4
  import { mergedEvidence, remoteTipMatches } from "./merged.js";
5
5
  import { evaluateArgv, result } from "./policy.js";
6
- import { parseShell, SUBSTITUTION } from "./shell.js";
6
+ import { SUBSTITUTION } from "./shell.js";
7
7
  /**
8
8
  * Permissive profile: approve everything except effects that are destructive, irreversible,
9
9
  * outward-facing, or touch credentials and protected configuration. The default for anything not
@@ -64,10 +64,95 @@ const SUBSTITUTION_OK = new Set([
64
64
  "basename",
65
65
  "dirname",
66
66
  ]);
67
- const MAX_SUBSTITUTION_DEPTH = 3;
68
- const BANNED_ENV = /^(?:LD_|DYLD_|GIT_|PYTHON|NODE_OPTIONS$|PATH$|HOME$|BASH_ENV$|ENV$|SHELL$|PAGER$|EDITOR$|GH_TOKEN$|GITHUB_TOKEN$)/;
67
+ // Variables that change how later commands are found, split or started. Assigning one, as a prefix
68
+ // or on its own, needs a human.
69
+ export const BANNED_ENV = /^(?:LD_|DYLD_|GIT_|PYTHON|NODE_OPTIONS$|PATH$|HOME$|BASH_ENV$|ENV$|SHELL$|PAGER$|EDITOR$|GH_TOKEN$|GITHUB_TOKEN$|IFS$|PS4$|PROMPT_COMMAND$|CDPATH$|GLOBIGNORE$|BASHOPTS$|SHELLOPTS$|BASH_XTRACEFD$|FPATH$|ZDOTDIR$|BASH_FUNC_|path$|cdpath$|fpath$|manpath$|module_path$)/;
70
+ // zsh ties the lowercase arrays path, cdpath, fpath, manpath and module_path to PATH, CDPATH, FPATH,
71
+ // MANPATH and MODULE_PATH, so those names are covered too (they are matched case-sensitively).
72
+ /** Runs arbitrary statements on another machine or database, so its argument is not judged. */
73
+ const REMOTE_EXECUTORS = new Set([
74
+ "ssh",
75
+ "psql",
76
+ "mysql",
77
+ "mariadb",
78
+ "sqlite3",
79
+ "sqlcmd",
80
+ "mongo",
81
+ "mongosh",
82
+ "redis-cli",
83
+ "cqlsh",
84
+ "sqlplus",
85
+ ]);
86
+ /** Builtins that run a string later or change how later commands behave. */
87
+ const STATE_BUILTINS = new Set([
88
+ "trap",
89
+ "alias",
90
+ "unalias",
91
+ "builtin",
92
+ "enable",
93
+ "declare",
94
+ "typeset",
95
+ "local",
96
+ "readonly",
97
+ "let",
98
+ "mapfile",
99
+ "readarray",
100
+ "getopts",
101
+ "coproc",
102
+ "fc",
103
+ "history",
104
+ "hash",
105
+ // builtins that store into a variable the evaluator tracks, or run a command through a module
106
+ "vared",
107
+ "zparseopts",
108
+ "r",
109
+ "zformat",
110
+ "zstyle",
111
+ "zregexparse",
112
+ "getln",
113
+ "compgen",
114
+ "sysread",
115
+ "zselect",
116
+ "ztcp",
117
+ "zpty",
118
+ "setopt",
119
+ "unsetopt",
120
+ "shopt",
121
+ // zsh precommand modifiers and builtins that run a command or string
122
+ "noglob",
123
+ "nocorrect",
124
+ "repeat",
125
+ "emulate",
126
+ "sched",
127
+ "zmodload",
128
+ "autoload",
129
+ "integer",
130
+ "float",
131
+ "functions",
132
+ "-",
133
+ ]);
134
+ /**
135
+ * Options whose next word is a value, not a flag or path, so an unknown (but single, quoted) word
136
+ * there cannot change what the command does: commit and PR messages built with `$(cat <<EOF ...)`.
137
+ */
138
+ const VALUE_OPTIONS = {
139
+ git: {
140
+ commit: ["-m", "--message"],
141
+ tag: ["-m", "--message"],
142
+ stash: ["-m", "--message"],
143
+ },
144
+ gh: {
145
+ "pr create": ["--title", "-t", "--body", "-b"],
146
+ "pr edit": ["--title", "-t", "--body", "-b"],
147
+ "pr comment": ["--body", "-b"],
148
+ "pr review": ["--body", "-b"],
149
+ "issue create": ["--title", "-t", "--body", "-b"],
150
+ "issue edit": ["--title", "-t", "--body", "-b"],
151
+ "issue comment": ["--body", "-b"],
152
+ },
153
+ };
69
154
  const FORCE_PUSH = ["--force", "--force-with-lease", "--force-if-includes", "--mirror", "--prune"];
70
- function human(request, category, reason) {
155
+ export function human(request, category, reason) {
71
156
  return result(request, category, reason);
72
157
  }
73
158
  export function permissiveRead(cwd, input) {
@@ -118,7 +203,7 @@ export function permissiveWrite(cwd, input, profile) {
118
203
  }
119
204
  return pathEvidence(cwd, input, true);
120
205
  }
121
- function unwrap(argv) {
206
+ export function unwrap(argv) {
122
207
  let current = argv;
123
208
  const env = [];
124
209
  for (let depth = 0; depth < 4; depth++) {
@@ -357,23 +442,79 @@ function cloudDecision(request, argv, profile) {
357
442
  return result(request, "impactful-write", "Permissive profile: non-destructive cloud change", true);
358
443
  return strict;
359
444
  }
360
- function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
445
+ /** Judges one redirection's target in `cwd`; undefined means it is acceptable. */
446
+ export function redirectDecision(request, redirect, profile, cwd) {
447
+ if (redirect.target.includes(SUBSTITUTION))
448
+ return human(request, "unknown", "Command substitution in a redirection requires human review");
449
+ // `>& word` duplicates a descriptor only when word is a number or `-`; otherwise it names a file.
450
+ if (redirect.target === "/dev/null" ||
451
+ (redirect.op === ">&" && /^(?:[0-9]+|-)$/.test(redirect.target)))
452
+ return undefined;
453
+ const check = redirect.op === "<"
454
+ ? permissiveRead(cwd, redirect.target)
455
+ : permissiveWrite(cwd, redirect.target, profile);
456
+ return check.allowed ? undefined : human(request, check.category, check.reason);
457
+ }
458
+ /** printf formats with only %s, %b, %q and %%: no argument is evaluated as arithmetic. */
459
+ function printfOnlyPrintsStrings(args) {
460
+ const rest = args[0] === "-v" ? args.slice(2) : args;
461
+ const format = rest[0] === "--" ? rest[1] : rest[0];
462
+ if (format === undefined)
463
+ return true;
464
+ if (format.includes(SUBSTITUTION) || format.includes("*"))
465
+ return false;
466
+ for (const match of format.matchAll(/%[-+ #0-9.]*([A-Za-z%])/g))
467
+ if (!"sbq%".includes(match[1]))
468
+ return false;
469
+ return true;
470
+ }
471
+ /** The unknown words of `argv` that sit in a value position (see VALUE_OPTIONS), made literal. */
472
+ function withOpaqueValues(argv, loose) {
473
+ const program = basename(argv[0] ?? "");
474
+ const table = VALUE_OPTIONS[program];
475
+ if (!table)
476
+ return argv;
477
+ const first = program === "git" ? argv.findIndex((w, i) => i > 0 && !w.startsWith("-")) : 1;
478
+ const key = program === "git" ? (argv[first] ?? "") : `${argv[1] ?? ""} ${argv[2] ?? ""}`;
479
+ const options = table[key];
480
+ if (!options)
481
+ return argv;
482
+ return argv.map((word, index) => {
483
+ if (index === 0 || !word.includes(SUBSTITUTION) || loose?.[index])
484
+ return word;
485
+ const previous = argv[index - 1] ?? "";
486
+ const valueOfPrevious = !previous.includes(SUBSTITUTION) &&
487
+ (options.includes(previous) ||
488
+ (program === "git" && key === "commit" && /^-[A-Za-z]*m$/.test(previous)));
489
+ const inline = options.some((option) => option.startsWith("--") && word.startsWith(`${option}=`));
490
+ if (!valueOfPrevious && !(inline && !word.split("=")[0]?.includes(SUBSTITUTION)))
491
+ return word;
492
+ return word.split(SUBSTITUTION).join("OPAQUE");
493
+ });
494
+ }
495
+ /**
496
+ * A best-effort scan of code an interpreter is about to run, which this policy cannot otherwise
497
+ * read: deleting files, starting processes, evaluating strings, and touching credential or
498
+ * protected paths. It is a denylist, not a proof, so anything it flags goes to a human.
499
+ */
500
+ const DANGEROUS_CODE = /\b(?:rmtree|removedirs|unlink|unlinkSync|rmdir|rmdirSync|rmSync|os\.remove|os\.removedirs|shutil\.move|child_process|execSync|spawnSync|spawn|subprocess|os\.system|os\.popen|os\.exec[a-z]*|eval|exec|compile|__import__|importlib|ctypes|socket|urlopen|requests\.(?:post|put|delete|patch)|fetch)\b|\bfs\.rm\b|\bPath\([^)]*\)\.(?:unlink|rmdir)|\brm\s+-/;
501
+ function interpreterCodeRefusal(code) {
502
+ if (DANGEROUS_CODE.test(code))
503
+ return "Interpreter code that deletes files, starts processes or evaluates strings requires human review";
504
+ for (const token of code.split(/[\s"'`()[\]{},;=<>|&]+/))
505
+ if ((token.includes("/") || token.startsWith(".")) &&
506
+ (sensitive(token) || protectedPath(token)))
507
+ return "Interpreter code that names a protected or credential path requires human review";
508
+ return undefined;
509
+ }
510
+ export function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
361
511
  for (const [name] of command.env)
362
512
  if (BANNED_ENV.test(name))
363
513
  return human(request, "unknown", "Environment override requires human review");
364
- for (const redirect of command.redirects)
365
- if (redirect.target.includes(SUBSTITUTION))
366
- return human(request, "unknown", "Command substitution in a redirection requires human review");
367
514
  for (const redirect of command.redirects) {
368
- // `>& word` duplicates a descriptor only when word is a number or `-`; otherwise it names a file.
369
- if (redirect.target === "/dev/null" ||
370
- (redirect.op === ">&" && /^(?:[0-9]+|-)$/.test(redirect.target)))
371
- continue;
372
- const check = redirect.op === "<"
373
- ? permissiveRead(cwd, redirect.target)
374
- : permissiveWrite(cwd, redirect.target, profile);
375
- if (!check.allowed)
376
- return human(request, check.category, check.reason);
515
+ const refusal = redirectDecision(request, redirect, profile, cwd);
516
+ if (refusal)
517
+ return refusal;
377
518
  }
378
519
  const unwrapped = unwrap(command.argv);
379
520
  if (unwrapped.refusal)
@@ -381,7 +522,8 @@ function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
381
522
  for (const name of unwrapped.env)
382
523
  if (BANNED_ENV.test(name))
383
524
  return human(request, "unknown", "Environment override requires human review");
384
- const argv = unwrapped.argv;
525
+ const looseAfterWrappers = command.loose?.slice(command.argv.length - unwrapped.argv.length);
526
+ const argv = withOpaqueValues(unwrapped.argv, looseAfterWrappers);
385
527
  const program = basename(argv[0] ?? "");
386
528
  // Words a wrapper consumed (env assignments, options, durations) are gone from `argv`, but an
387
529
  // unquoted substitution in them can still split into extra words and pick a different program.
@@ -391,6 +533,33 @@ function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
391
533
  (argv[0]?.includes(SUBSTITUTION) || !SUBSTITUTION_OK.has(program)))
392
534
  return human(request, "unknown", "Command substitution output is only accepted as an argument to echo, printf and similar");
393
535
  const args = argv.slice(1);
536
+ // zsh expands `=name` to the path of a command, so `command =rm` runs rm.
537
+ if (argv[0]?.startsWith("=") && argv[0].length > 1)
538
+ return human(request, "unknown", "A command named with = requires human review");
539
+ // `[[` evaluates the operands of -eq, -lt and the like as arithmetic, including the value of a
540
+ // bare variable name, and `a[$(cmd)]` runs the command. Only plain integers are safe.
541
+ // `-v` and `-R` take a variable name, and bash evaluates a subscript in it (`a[$(cmd)]`).
542
+ if (program === "[[" || program === "test" || program === "[")
543
+ for (const [index, word] of args.entries())
544
+ if ((word === "-v" || word === "-R") &&
545
+ !/^[A-Za-z_][A-Za-z0-9_]*$/.test(args[index + 1] ?? ""))
546
+ return human(request, "unknown", "A variable test with a subscript or computed name requires human review");
547
+ if (program === "[[")
548
+ for (const [index, word] of args.entries())
549
+ if (/^(?:-eq|-ne|-lt|-le|-gt|-ge)$/.test(word)) {
550
+ const operands = [args[index - 1], args[index + 1]];
551
+ if (operands.some((operand) => operand === undefined || !/^-?[0-9]+$/.test(operand)))
552
+ return human(request, "unknown", "A numeric test with a non-integer operand requires human review");
553
+ }
554
+ // zsh and bash evaluate arithmetic in some builtins' operands, and a name such as `a[$(cmd)]`
555
+ // runs the command. An unknown value is therefore only safe where nothing is evaluated.
556
+ if (argv.some((word) => word.includes(SUBSTITUTION))) {
557
+ if ((program === "test" || program === "[") &&
558
+ args.some((word) => /^(?:-eq|-ne|-lt|-le|-gt|-ge|-v|-R)$/.test(word)))
559
+ return human(request, "unknown", "An unknown value in a numeric or variable test requires human review");
560
+ if (program === "printf" && !printfOnlyPrintsStrings(args))
561
+ return human(request, "unknown", "An unknown value in a printf with numeric conversions requires human review");
562
+ }
394
563
  const joined = argv.join(" ");
395
564
  if (profile.humanPatterns.some((pattern) => pattern.test(joined)))
396
565
  return human(request, "destructive", "Matches an organization human-approval pattern");
@@ -404,21 +573,51 @@ function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
404
573
  }
405
574
  if (DESTRUCTIVE.has(program) || program.startsWith("mkfs"))
406
575
  return human(request, "destructive", "Destructive operation requires human approval");
576
+ if (REMOTE_EXECUTORS.has(program))
577
+ return human(request, "unknown", "Remote or database command execution requires human review");
578
+ if (STATE_BUILTINS.has(program))
579
+ return human(request, "unknown", "A shell builtin that runs a string later or changes later commands requires human review");
580
+ // These print the whole environment, which can hold credentials.
581
+ if (program === "printenv" || program === "env" || (program === "set" && args.length === 0))
582
+ return human(request, "sensitive", "Printing the environment requires human review");
583
+ // `set -A name values` assigns an array, and `wait -p VAR` assigns a variable.
584
+ if (program === "wait" && args.some((word) => word.startsWith("-")))
585
+ return human(request, "unknown", "wait with options requires human review");
586
+ if (program === "set" && !args.every((word) => /^[-+][B-Za-z]+$|^pipefail$/.test(word)))
587
+ return human(request, "unknown", "Changing shell settings requires human review");
407
588
  if (SHELLS.has(program) || INTERPRETERS.has(program)) {
408
589
  if (stageIndex > 0)
409
590
  return human(request, "unknown", "Piping into a shell or interpreter requires human review");
410
591
  if (SHELLS.has(program)) {
411
592
  const inline = args.indexOf("-c");
412
- const script = inline >= 0 ? args[inline + 1] : undefined;
593
+ // A shell fed by a heredoc runs exactly that text, so judge it as a script.
594
+ const script = inline >= 0
595
+ ? args[inline + 1]
596
+ : (args.length === 0 || args.every((arg) => arg === "-" || arg === "-s")) &&
597
+ command.stdin !== undefined
598
+ ? command.stdin
599
+ : undefined;
413
600
  if (script === undefined || depth >= 2)
414
601
  return human(request, "unknown", "Shell invocation requires human review");
415
602
  return commandDecision(request, script, profile, depth + 1, [cwd]);
416
603
  }
417
- if (args.length === 0 || args[0] === "-")
604
+ // Inline code and a heredoc body are both literal text, so both can be read. Code piped in
605
+ // from elsewhere cannot.
606
+ const fromStdin = args.length === 0 || args[0] === "-";
607
+ const inlineAt = args.findIndex((arg) => ["-c", "-e", "-p", "--eval", "--print"].includes(arg));
608
+ const code = fromStdin ? command.stdin : inlineAt >= 0 ? args[inlineAt + 1] : undefined;
609
+ if (fromStdin && code === undefined)
418
610
  return human(request, "unknown", "Interpreter reading code from standard input requires human review");
611
+ const unsafe = code === undefined ? undefined : interpreterCodeRefusal(code);
612
+ if (unsafe)
613
+ return human(request, "unknown", unsafe);
419
614
  }
420
615
  if (program === "xargs" &&
421
- args.some((arg) => DESTRUCTIVE.has(basename(arg)) || SHELLS.has(basename(arg)) || basename(arg) === "git"))
616
+ args.some((arg) =>
617
+ // zsh expands `=rm` to the path of rm.
618
+ DESTRUCTIVE.has(basename(arg.replace(/^=/, ""))) ||
619
+ SHELLS.has(basename(arg.replace(/^=/, ""))) ||
620
+ basename(arg.replace(/^=/, "")) === "git"))
422
621
  return human(request, "destructive", "xargs into a destructive or shell command requires human review");
423
622
  if (program === "find" &&
424
623
  args.some((arg) => ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprintf", "-fls"].includes(arg)))
@@ -472,58 +671,5 @@ function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
472
671
  return cloudDecision(request, argv, profile);
473
672
  return result(request, "impactful-write", "Permissive profile: no destructive effect detected", true);
474
673
  }
475
- const MAX_DIRECTORIES = 8;
476
- /**
477
- * Evaluates a compound command. `cd <literal>` is tracked: every later command is judged in each
478
- * directory it could run in (before and after the `cd`, since `cd x || ...` may fail), so a command
479
- * that only looks safe relative to the starting directory cannot hide behind a `cd`.
480
- */
481
- export function commandDecision(request, command, profile, depth = 0, start = [request.cwd]) {
482
- const pipelines = parseShell(command);
483
- if (!pipelines)
484
- return human(request, "unknown", "Unsupported shell syntax; expansions and subshells need human review");
485
- let cwds = [...start];
486
- let last;
487
- for (const pipeline of pipelines)
488
- for (const [index, simple] of pipeline.entries()) {
489
- // Command substitutions run before the command, in the directories it could start from.
490
- for (const inner of simple.subs) {
491
- if (depth >= MAX_SUBSTITUTION_DEPTH)
492
- return human(request, "unknown", "Command substitutions are nested too deeply");
493
- const own = commandDecision(request, inner, profile, depth + 1, cwds);
494
- if (own.decision !== "approve")
495
- return own;
496
- }
497
- if (basename(simple.argv[0] ?? "") === "cd") {
498
- const target = simple.argv.slice(1).filter((word) => word !== "--");
499
- // A bare `cd` and `~` or `~/x` go to the home directory; `~user` and `-` stay with a human.
500
- const raw = target.length === 0 ? "~" : target[0];
501
- const word = raw === "~" || raw?.startsWith("~/") ? join(homedir(), raw.slice(1)) : raw;
502
- if (target.length > 1 ||
503
- !word ||
504
- word.includes(SUBSTITUTION) ||
505
- /^~|[*?[\]]/.test(word) ||
506
- word.startsWith("-"))
507
- return human(request, "unknown", "Directory change requires human review");
508
- // The cd's own redirections, env assignments and organization patterns run first, in the
509
- // directories it could start from.
510
- for (const cwd of cwds) {
511
- const own = simpleDecision(request, simple, profile, depth, index, cwd);
512
- if (own.decision !== "approve")
513
- return own;
514
- }
515
- cwds = [...new Set([...cwds, ...cwds.map((cwd) => resolve(cwd, word))])];
516
- if (cwds.length > MAX_DIRECTORIES)
517
- return human(request, "unknown", "Too many directory changes to verify");
518
- last = result(request, "code-read", "Directory change", true);
519
- continue;
520
- }
521
- for (const cwd of cwds) {
522
- last = simpleDecision(request, simple, profile, depth, index, cwd);
523
- if (last.decision !== "approve")
524
- return last;
525
- }
526
- }
527
- return last ?? human(request, "unknown", "Empty command");
528
- }
674
+ export { commandDecision };
529
675
  //# sourceMappingURL=permissive.js.map
package/dist/policy.d.ts CHANGED
@@ -3,6 +3,8 @@ import type { Category, Classification, Decision, Request } from "./types.js";
3
3
  export declare function hash(value: unknown): string;
4
4
  export declare function words(command: string): string[] | undefined;
5
5
  export declare function result(request: Request, category: Category, reason: string, approve?: boolean): Decision;
6
+ /** Self-reported confidence needed for the AI to approve an ambiguous request. */
7
+ export declare const AMBIGUOUS_CONFIDENCE = 0.95;
6
8
  export declare function evaluate(request: Request, ai?: Classification, profile?: Profile): Decision;
7
9
  export declare function evaluateArgv(request: Request, argv: string[]): Decision;
8
10
  //# sourceMappingURL=policy.d.ts.map
package/dist/policy.js CHANGED
@@ -4,6 +4,7 @@ import { resolve } from "node:path";
4
4
  import { branchEvidence, canonical, git, inside, pathEvidence } from "./evidence.js";
5
5
  import { commandDecision, permissiveRead, permissiveWrite } from "./permissive.js";
6
6
  import { strictProfile } from "./profile.js";
7
+ import { redactText } from "./redact.js";
7
8
  export function hash(value) {
8
9
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
9
10
  }
@@ -172,8 +173,64 @@ export function result(request, category, reason, approve = false) {
172
173
  cached: false,
173
174
  };
174
175
  }
176
+ /** Self-reported confidence needed for the AI to approve an ambiguous request. */
177
+ export const AMBIGUOUS_CONFIDENCE = 0.95;
178
+ /**
179
+ * Escalations that stay with a human in every profile. Categories `sensitive` (credentials,
180
+ * secrets, protected paths and configuration) and `destructive` (unrecoverable loss) are excluded
181
+ * by category; these are the remaining boundaries: the request itself cannot be trusted, an
182
+ * organization or the profile asked for a human, or a repository rule forbids the write.
183
+ */
184
+ const HUMAN_BOUNDARIES = [
185
+ /^Incomplete request/,
186
+ /^Invalid tool input/,
187
+ /^Execution directory differs/,
188
+ /^Unrecognized patch format/,
189
+ /^Patch has no verified target paths/,
190
+ /^Environment override requires human review/,
191
+ /^Custom execution environment requires human review/,
192
+ /^Matches an organization human-approval pattern/,
193
+ /^Write requires a linked worktree on a feature branch/,
194
+ /^Cloud operation is outside the verified inspection catalog/,
195
+ ];
196
+ /**
197
+ * Under the permissive profile, every escalation that is not a boundary is ambiguous: the
198
+ * deterministic engine cannot decide it, so the session's AI classifier does. Strict mode is
199
+ * unchanged.
200
+ */
201
+ function markAmbiguous(decision, profile) {
202
+ if (profile.mode !== "permissive" ||
203
+ decision.decision !== "human" ||
204
+ decision.needsClassification ||
205
+ decision.category === "sensitive" ||
206
+ decision.category === "destructive" ||
207
+ HUMAN_BOUNDARIES.some((pattern) => pattern.test(decision.reason)))
208
+ return decision;
209
+ return { ...decision, needsClassification: true, tier: "ambiguous" };
210
+ }
211
+ function resolveAmbiguous(decision, ai) {
212
+ const safe = ai.recoverable === true &&
213
+ ai.confidence >= AMBIGUOUS_CONFIDENCE &&
214
+ !["sensitive", "destructive", "unknown"].includes(ai.category);
215
+ const base = { ...decision, needsClassification: false, cache: "session", ai };
216
+ if (safe)
217
+ return {
218
+ ...base,
219
+ decision: "approve",
220
+ category: ai.category,
221
+ classification: "approved",
222
+ reason: "Ambiguous request judged recoverable and non-sensitive by the same-session AI",
223
+ };
224
+ const why = ai.rationale ? ` Rationale: ${redactText(ai.rationale, 200)}` : "";
225
+ return {
226
+ ...base,
227
+ decision: "deny",
228
+ classification: "denied",
229
+ reason: `Not run: the classifier did not approve this request (category ${ai.category}, confidence ${ai.confidence}, recoverable ${ai.recoverable ?? "not stated"}).${why} Use a recoverable, non-sensitive alternative, or explain to the user what is needed.`,
230
+ };
231
+ }
175
232
  export function evaluate(request, ai, profile = strictProfile) {
176
- const decision = evaluateCore(request, profile);
233
+ const decision = markAmbiguous(evaluateCore(request, profile), profile);
177
234
  if (ai) {
178
235
  // Self-reported confidence is not a probability or a substitute for verified effects.
179
236
  if (![
@@ -197,6 +254,8 @@ export function evaluate(request, ai, profile = strictProfile) {
197
254
  reason: "Invalid or mismatched AI classification",
198
255
  };
199
256
  decision.ai = ai;
257
+ if (decision.tier === "ambiguous")
258
+ return resolveAmbiguous(decision, ai);
200
259
  if (decision.category === "cloud-read" &&
201
260
  decision.needsClassification === true &&
202
261
  ai.category === "cloud-read" &&
@@ -0,0 +1,3 @@
1
+ /** Redacts a shell command or other free text, keeping it recognisable and at most `max` long. */
2
+ export declare function redactText(text: string, max?: number): string;
3
+ //# sourceMappingURL=redact.d.ts.map
package/dist/redact.js ADDED
@@ -0,0 +1,140 @@
1
+ // Redaction for text that is written to the audit log: the exact command of an ambiguous request
2
+ // and the classifier's free-text rationale. The audit log is private, but it is also what a human
3
+ // reads in a risk review, so values that look like secrets never reach it.
4
+ //
5
+ // Text is split into words by hand (quotes keep a quoted value together) and every pattern is
6
+ // anchored or linear, so hostile input cannot make the redaction slow.
7
+ /** Names that carry a secret as a substring: `DB_PASSWORD`, `--api-key`, `x-auth-token`. */
8
+ const SECRET_NAME = /(?:token|secret|pass(?:word|wd|phrase)?|pwd|api[-_]?key|apikey|credential|bearer|cookie|private[-_]?key|access[-_]?key|signature)/i;
9
+ /** `auth` only as a whole word, so `--author` is not a secret but `--auth` and `Authorization` are. */
10
+ const AUTH_NAME = /(?:^|[^a-z])auth(?:orization)?(?:[^a-z]|$)/i;
11
+ const TOKEN_PREFIX = /^(?:gh[pousr]_|github_pat_|sk-|xox[baprs]-|AKIA|ASIA|AIza|eyJ|glpat-|npm_|shpat_)/;
12
+ const LONG_OPAQUE = /^[A-Za-z0-9+/=_-]{32,}$/;
13
+ /** Programs whose `-pPASSWORD` attaches the password to the flag. Elsewhere `-p…` is not secret. */
14
+ const ATTACHED_PASSWORD = /^(?:mysql|mysqldump|mysqladmin|mysqlcheck|mariadb|mariadb-dump)$/;
15
+ /** Flags whose next word is a credential, whatever the word looks like. */
16
+ const CREDENTIAL_FLAG = /^(?:-u|-U|--user|--proxy-user|--oauth2-bearer)$/;
17
+ const isSecretName = (name) => SECRET_NAME.test(name) || AUTH_NAME.test(name);
18
+ function words(text) {
19
+ const out = [];
20
+ let current = "";
21
+ let quote = "";
22
+ let inWord = false;
23
+ const flush = () => {
24
+ if (inWord)
25
+ out.push(current);
26
+ current = "";
27
+ inWord = false;
28
+ };
29
+ for (const char of text) {
30
+ if (quote) {
31
+ current += char;
32
+ if (char === quote)
33
+ quote = "";
34
+ }
35
+ else if (char === '"' || char === "'") {
36
+ quote = char;
37
+ current += char;
38
+ inWord = true;
39
+ }
40
+ else if (/\s/.test(char)) {
41
+ flush();
42
+ out.push(char);
43
+ inWord = false;
44
+ }
45
+ else {
46
+ current += char;
47
+ inWord = true;
48
+ }
49
+ }
50
+ flush();
51
+ return out;
52
+ }
53
+ /** `https://user:pass@host/x?token=1` keeps host and path but loses userinfo and query values. */
54
+ function redactUrl(word) {
55
+ const scheme = word.match(/^["']?[a-z][a-z0-9+.-]*:\/\//i)?.[0];
56
+ if (!scheme)
57
+ return word;
58
+ const rest = word.slice(scheme.length);
59
+ const cut = rest.search(/[?#]/);
60
+ const head = cut < 0 ? rest : rest.slice(0, cut);
61
+ const slash = head.indexOf("/");
62
+ const authority = slash < 0 ? head : head.slice(0, slash);
63
+ const path = slash < 0 ? "" : head.slice(slash);
64
+ const at = authority.lastIndexOf("@");
65
+ const host = at < 0 ? authority : `[REDACTED]@${authority.slice(at + 1)}`;
66
+ return `${scheme}${host}${path}${cut >= 0 && rest[cut] === "?" ? "?[REDACTED]" : ""}`;
67
+ }
68
+ /** `-H "X-Api-Key: abc"` and `"Authorization: Bearer abc"`, one quoted word. */
69
+ function redactHeader(word) {
70
+ const colon = word.indexOf(":");
71
+ if (colon <= 0 || word.startsWith("//", colon + 1))
72
+ return undefined;
73
+ const name = word.slice(0, colon).replace(/^["']/, "");
74
+ if (!/^[A-Za-z][\w-]*$/.test(name) || !isSecretName(name))
75
+ return undefined;
76
+ const quote = /["']$/.test(word) ? word.at(-1) : "";
77
+ return `${word.slice(0, colon + 1)} [REDACTED]${quote}`;
78
+ }
79
+ /** Redacts a shell command or other free text, keeping it recognisable and at most `max` long. */
80
+ export function redactText(text, max = 300) {
81
+ let hideNext = false;
82
+ let program = "";
83
+ let atStart = true;
84
+ const out = words(text).map((raw) => {
85
+ if (/^\s$/.test(raw))
86
+ return raw;
87
+ if (/^(?:\||\|\||&&|;|&)$/.test(raw)) {
88
+ atStart = true;
89
+ return raw;
90
+ }
91
+ if (atStart && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(raw)) {
92
+ program =
93
+ raw
94
+ .replace(/^["']|["']$/g, "")
95
+ .split(/[\\/]/)
96
+ .pop() ?? "";
97
+ atStart = false;
98
+ }
99
+ if (hideNext) {
100
+ // `Authorization: Bearer abc` carries the secret in the word after the scheme.
101
+ hideNext = /^["']?(?:bearer|basic|token)["']?$/i.test(raw);
102
+ return hideNext ? raw : "[REDACTED]";
103
+ }
104
+ // URL credentials first: a `?token=` in the query must not hide userinfo before it.
105
+ const piece = redactUrl(raw);
106
+ if (CREDENTIAL_FLAG.test(piece)) {
107
+ hideNext = true;
108
+ return piece;
109
+ }
110
+ // `Authorization:` alone: the value, and a scheme before it, are the words that follow.
111
+ if (/^["']?[A-Za-z][\w-]*:["']?$/.test(piece) && isSecretName(piece.replace(/[:"']/g, ""))) {
112
+ hideNext = true;
113
+ return piece;
114
+ }
115
+ const header = redactHeader(piece);
116
+ if (header)
117
+ return header;
118
+ const eq = piece.indexOf("=");
119
+ const name = eq >= 0 ? piece.slice(0, eq) : piece;
120
+ // `mysql -pSECRET`: a short option with its value attached.
121
+ if (/^-p./.test(piece) && eq < 0 && ATTACHED_PASSWORD.test(program))
122
+ return "-p[REDACTED]";
123
+ if (/^-[A-Za-z]./.test(piece) && eq < 0 && isSecretName(piece))
124
+ return `${piece.slice(0, 2)}[REDACTED]`;
125
+ if (isSecretName(name)) {
126
+ if (eq >= 0)
127
+ return `${name}=[REDACTED]`;
128
+ // A bare flag takes its value from the next word; a header name waits for its value.
129
+ if (/^-{1,2}[A-Za-z]/.test(piece) || /:["']?$/.test(piece))
130
+ hideNext = true;
131
+ return piece;
132
+ }
133
+ // A quoted token is still a token: judge the word without its surrounding quote.
134
+ const bare = piece.replace(/^["']|["']$/g, "");
135
+ return TOKEN_PREFIX.test(bare) || LONG_OPAQUE.test(bare) ? "[REDACTED]" : piece;
136
+ });
137
+ const joined = out.join("");
138
+ return joined.length > max ? `${joined.slice(0, max)}…` : joined;
139
+ }
140
+ //# sourceMappingURL=redact.js.map
package/dist/replay.d.ts CHANGED
@@ -3,6 +3,8 @@ export interface ReplayReport {
3
3
  commands: number;
4
4
  approved: number;
5
5
  strictApproved: number;
6
+ /** Escalations the AI classifier handles instead of a person (permissive profile only). */
7
+ classified: number;
6
8
  reasons: Array<{
7
9
  reason: string;
8
10
  count: number;