@agent-corpus/policy-manager 0.9.0 → 0.11.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.
Files changed (47) hide show
  1. package/README.md +126 -29
  2. package/dist/adapters.d.ts +3 -1
  3. package/dist/adapters.js +37 -18
  4. package/dist/classifier.d.ts +98 -0
  5. package/dist/classifier.js +343 -0
  6. package/dist/cli.js +66 -7
  7. package/dist/config.d.ts +2 -0
  8. package/dist/config.js +6 -2
  9. package/dist/evidence.d.ts +1 -0
  10. package/dist/evidence.js +60 -0
  11. package/dist/flow.d.ts +4 -0
  12. package/dist/flow.js +91 -18
  13. package/dist/gitalias.d.ts +13 -0
  14. package/dist/gitalias.js +33 -0
  15. package/dist/grants.d.ts +9 -9
  16. package/dist/grants.js +46 -30
  17. package/dist/hard.d.ts +63 -0
  18. package/dist/hard.js +1637 -0
  19. package/dist/helpers.d.ts +59 -0
  20. package/dist/helpers.js +304 -0
  21. package/dist/merged.d.ts +6 -0
  22. package/dist/merged.js +23 -0
  23. package/dist/nativerules.d.ts +44 -0
  24. package/dist/nativerules.js +653 -0
  25. package/dist/permissive.js +179 -7
  26. package/dist/policy.d.ts +12 -0
  27. package/dist/policy.js +228 -45
  28. package/dist/profile.d.ts +7 -0
  29. package/dist/profile.js +32 -1
  30. package/dist/prompt.d.ts +32 -0
  31. package/dist/prompt.js +334 -0
  32. package/dist/reads.d.ts +46 -0
  33. package/dist/reads.js +812 -0
  34. package/dist/replay.d.ts +42 -0
  35. package/dist/replay.js +174 -1
  36. package/dist/service.d.ts +12 -1
  37. package/dist/service.js +23 -6
  38. package/dist/session.d.ts +76 -13
  39. package/dist/session.js +373 -116
  40. package/dist/shell.d.ts +2 -0
  41. package/dist/shell.js +1 -1
  42. package/dist/shellscan.d.ts +58 -0
  43. package/dist/shellscan.js +395 -0
  44. package/dist/statepaths.d.ts +41 -0
  45. package/dist/statepaths.js +706 -0
  46. package/dist/types.d.ts +11 -1
  47. package/package.json +1 -1
@@ -2,8 +2,11 @@ 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";
5
- import { mergedEvidence, remoteTipMatches } from "./merged.js";
6
- import { evaluateArgv, result } from "./policy.js";
5
+ import { aliasDirectory, gitAlias, KNOWN_GIT, shellArgs } from "./gitalias.js";
6
+ import { helperMatch } from "./helpers.js";
7
+ import { mergedEvidence, onRemote, remoteTipMatches } from "./merged.js";
8
+ import { evaluateArgv, result, words as shellWords } from "./policy.js";
9
+ import { sedScript } from "./reads.js";
7
10
  import { deletesProtected, deletionScriptCwd, gitRmRecoverable, resetRecoverable, restoreRecoverable, rmRecoverable, soleEffect, worktreeDeletion, } from "./recoverable.js";
8
11
  import { SUBSTITUTION } from "./shell.js";
9
12
  /**
@@ -341,6 +344,11 @@ const LONG_FLAGS = {
341
344
  * Over-matching only sends more to a human.
342
345
  */
343
346
  function sedScriptPaths(script) {
347
+ // Parsed the way sed reads it, a replacement's text (`s/x/see .claude/`) is data, not a path;
348
+ // only an `r`, `w` or `e` command or flag names one. Unreadable scripts keep the wide reading.
349
+ const scanned = sedScript(script);
350
+ if (scanned && !scanned.runs)
351
+ return scanned.files;
344
352
  const paths = [];
345
353
  for (const match of script.matchAll(/(?:^|[^A-Za-z\\])[eErRwW]\s*([^\n]*)/g))
346
354
  paths.push(...(match[1] ?? "").split(/[\s;]+/).filter(Boolean));
@@ -844,7 +852,9 @@ function disposableWorktree(cwd, args, roots, fill) {
844
852
  return false;
845
853
  }
846
854
  }
847
- function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
855
+ function gitDecision(request, argv, cwdForGit, sole, roots, fill,
856
+ /** Judges a `!` alias's shell command in the directory Git runs it in. */
857
+ shell, aliasDepth = 0) {
848
858
  const args = argv.slice(1);
849
859
  let index = 0;
850
860
  let cwd = cwdForGit;
@@ -860,6 +870,21 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
860
870
  }
861
871
  const sub = args[index];
862
872
  const rest = args.slice(index + 1);
873
+ // A word Git does not know is an alias (repository, global or system configuration) or an
874
+ // external command: judge what the alias expands to, and approve nothing else.
875
+ if (sub !== undefined && !KNOWN_GIT.has(sub)) {
876
+ const alias = aliasDepth < 4 ? gitAlias(cwd, sub) : undefined;
877
+ if (alias === undefined)
878
+ return human(request, "unknown", "Git subcommand is neither built in nor an alias");
879
+ if (alias.startsWith("!"))
880
+ return shell
881
+ ? shell(`${alias.slice(1)} ${shellArgs(rest)}`.trim(), aliasDirectory(cwd))
882
+ : human(request, "unknown", "Git shell alias requires human review");
883
+ const expanded = shellWords(alias);
884
+ if (!expanded)
885
+ return human(request, "unknown", "Git alias with shell syntax requires human review");
886
+ return gitDecision(request, ["git", ...expanded, ...rest], cwd, sole, roots, fill, shell, aliasDepth + 1);
887
+ }
863
888
  const flags = rest.filter((word) => word.startsWith("-"));
864
889
  const positional = rest.filter((word) => !word.startsWith("-"));
865
890
  const has = (...names) => flags.some((flag) => names.some((name) => abbreviates(flag, name)));
@@ -867,15 +892,23 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
867
892
  const ok = (reason = "Permissive profile: Git operation has no destructive effect") => result(request, "impactful-write", reason, true);
868
893
  if (!sub)
869
894
  return ok();
895
+ const refWrite = remoteRefWrite(cwd, sub, rest);
896
+ if (refWrite)
897
+ return human(request, "sensitive", refWrite);
898
+ if ((sub === "clone" || sub === "init") &&
899
+ rest.some((word) => CLONE_CONFIG.some((option) => word === option || abbreviates(word, option)) ||
900
+ /^-c./.test(word) ||
901
+ (sub === "clone" && /^-[A-Za-z]*[cou]/.test(word) && !word.startsWith("--"))))
902
+ return human(request, "sensitive", `git ${sub} with a configuration, origin, template or separate git directory requires human approval`);
870
903
  if (sub === "push")
871
904
  return gitPush(request, cwd, rest);
872
905
  if (sub === "branch" && (has("-d", "-D", "--delete") || cluster("d") || cluster("D"))) {
873
906
  if (has("-r", "--remotes"))
874
907
  return ok();
875
- const unmerged = positional.filter((name) => !mergedEvidence(cwd, `refs/heads/${name}`).merged);
908
+ const unmerged = positional.filter((name) => !mergedEvidence(cwd, `refs/heads/${name}`).merged && !onRemote(cwd, name));
876
909
  return unmerged.length
877
910
  ? human(request, "destructive", branchEvidence(cwd, unmerged[0] ?? ""))
878
- : ok("Branch is already merged into origin's default branch");
911
+ : ok("Every deleted branch is merged into origin's default branch or its tip is on a remote ref");
879
912
  }
880
913
  if (sub === "branch" && (has("-f", "--force") || cluster("f") || has("-M")))
881
914
  return human(request, "destructive", "Forced branch move requires human approval");
@@ -934,10 +967,119 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
934
967
  !safeConfigWrite(rest))
935
968
  return human(request, "sensitive", "Git configuration can install hooks or credential helpers");
936
969
  if (sub === "remote" &&
937
- ["set-url", "remove", "rm", "rename", "set-head"].includes(positional[0] ?? ""))
970
+ ["add", "set-url", "remove", "rm", "rename", "set-head", "set-branches"].includes(positional[0] ?? ""))
938
971
  return human(request, "impactful-write", "Changing remotes requires human approval");
939
972
  return ok();
940
973
  }
974
+ /**
975
+ * `git clone`/`init` options that set the new repository's configuration or origin, or run a
976
+ * program: a credential helper trusts a checkout by its configured origin.
977
+ */
978
+ const CLONE_CONFIG = ["--config", "--origin", "--template", "--separate-git-dir", "--upload-pack"];
979
+ /** Whether a credential helper's file argument lies in the working checkout or a temp/scratch root. */
980
+ function helperFileAllowed(cwd, file, profile) {
981
+ let path;
982
+ try {
983
+ path = canonical(resolveWord(cwd, file));
984
+ }
985
+ catch {
986
+ return false;
987
+ }
988
+ const roots = [...profile.scratchRoots, ...tempRoots()];
989
+ try {
990
+ roots.push(canonical(git(cwd, ["rev-parse", "--show-toplevel"])));
991
+ }
992
+ catch {
993
+ /* not in a checkout: temp and scratch roots only */
994
+ }
995
+ return roots.some((root) => inside(canonical(root), path));
996
+ }
997
+ /** A fetch or push target that is this machine, not a remote: `.`, a path, or a `file:` URL. */
998
+ function localRepository(word) {
999
+ return (word === "." ||
1000
+ word === ".." ||
1001
+ word.startsWith("/") ||
1002
+ word.startsWith("./") ||
1003
+ word.startsWith("../") ||
1004
+ word.startsWith("~") ||
1005
+ word.startsWith("\\") ||
1006
+ /^[A-Za-z]:/.test(word) ||
1007
+ /^file:/i.test(word) ||
1008
+ (!word.includes(":") && word.includes("/")));
1009
+ }
1010
+ /** Remote names configured in the repository, read locally. */
1011
+ function configuredRemotes(cwd) {
1012
+ try {
1013
+ return new Set(git(cwd, ["remote"]).split("\n").filter(Boolean));
1014
+ }
1015
+ catch {
1016
+ return undefined;
1017
+ }
1018
+ }
1019
+ /**
1020
+ * A local write that moves a remote-tracking ref. Remote-tracking refs are this policy's evidence
1021
+ * of what a remote holds (merged branches, unchanged credential helpers), so only fetching the
1022
+ * same branch from its own configured remote may move them.
1023
+ */
1024
+ function remoteRefWrite(cwd, sub, rest) {
1025
+ const positional = rest.filter((word) => !word.startsWith("-"));
1026
+ const remoteRef = (word) => /^(?:\+)?refs\/remotes\//.test(word);
1027
+ const why = "Moving a remote-tracking ref locally requires human approval";
1028
+ if (sub === "update-ref") {
1029
+ // Only a plain branch or tag, named in full, that is not a symbolic ref: anything else could
1030
+ // move a remote-tracking ref, a replace ref, or whatever HEAD points to.
1031
+ const name = positional[0] ?? "";
1032
+ if (rest.some((w) => w === "--stdin" || w.startsWith("--no-deref")) ||
1033
+ positional.some(remoteRef) ||
1034
+ !/^refs\/(?:heads|tags)\/[^\s]+$/.test(name))
1035
+ return "Updating a ref other than a plain branch or tag requires human approval";
1036
+ try {
1037
+ git(cwd, ["symbolic-ref", "--quiet", name]);
1038
+ return "Updating a ref through a symbolic ref requires human approval";
1039
+ }
1040
+ catch {
1041
+ return undefined;
1042
+ }
1043
+ }
1044
+ if (sub === "symbolic-ref") {
1045
+ const writes = positional.length > 1 || rest.some((w) => w === "-d" || w === "--delete");
1046
+ return writes && positional.some((w) => /^(?:refs\/)?remotes\//.test(w)) ? why : undefined;
1047
+ }
1048
+ if (sub === "push") {
1049
+ const remote = positional[0];
1050
+ return remote !== undefined && localRepository(remote)
1051
+ ? "Pushing to a local repository requires human approval"
1052
+ : undefined;
1053
+ }
1054
+ if (sub !== "fetch" && sub !== "pull")
1055
+ return undefined;
1056
+ if (rest.some((w) => w.startsWith("--refmap") || w === "--stdin"))
1057
+ return "A fetch with a custom ref map requires human approval";
1058
+ const remote = positional[0];
1059
+ if (remote === undefined)
1060
+ return undefined;
1061
+ if (localRepository(remote))
1062
+ return `A ${sub} from a local repository requires human approval`;
1063
+ const remotes = configuredRemotes(cwd);
1064
+ for (const spec of positional.slice(1)) {
1065
+ const colon = spec.indexOf(":");
1066
+ if (colon < 0)
1067
+ continue;
1068
+ const source = spec.slice(spec.startsWith("+") ? 1 : 0, colon);
1069
+ // Git also takes `remotes/<r>/<b>` as a short name for `refs/remotes/<r>/<b>`.
1070
+ const raw = spec.slice(colon + 1);
1071
+ const destination = raw.startsWith("remotes/") ? `refs/${raw}` : raw;
1072
+ if (!destination.startsWith("refs/remotes/"))
1073
+ continue;
1074
+ const [owner = "", ...branch] = destination.slice("refs/remotes/".length).split("/");
1075
+ const name = branch.join("/");
1076
+ if (owner !== remote ||
1077
+ !remotes?.has(remote) ||
1078
+ (source !== name && source !== `refs/heads/${name}`))
1079
+ return why;
1080
+ }
1081
+ return undefined;
1082
+ }
941
1083
  /**
942
1084
  * `git worktree add` from any clone is approved, except that the main checkout's working tree
943
1085
  * stays protected: a new worktree inside it must go under `.worktrees/` or `.claude/worktrees/`.
@@ -1633,6 +1775,34 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
1633
1775
  return human(request, "unknown", "wait with options requires human review");
1634
1776
  if (program === "set" && !args.every((word) => /^[-+][B-Za-z]+$|^pipefail$/.test(word)))
1635
1777
  return human(request, "unknown", "Changing shell settings requires human review");
1778
+ // A listed credential helper reads a secret for one narrow job. It runs only as committed on the
1779
+ // default branch, with an accepted argument shape, and with nothing changing its environment.
1780
+ const helper = helperMatch(profile.credentialHelpers, cwd, argv);
1781
+ if (helper.kind === "refused")
1782
+ return human(request, "sensitive", helper.reason);
1783
+ if (helper.kind === "match") {
1784
+ if (stageIndex > 0 ||
1785
+ command.stdin !== undefined ||
1786
+ command.redirects.some((r) => r.op === "<" || r.fd === "0") ||
1787
+ command.env.length > 0 ||
1788
+ unwrapped.env.length > 0 ||
1789
+ argv.length !== command.argv.length)
1790
+ return human(request, "sensitive", "A credential helper with a changed environment or input requires a person");
1791
+ // A pattern or `~` would let the shell turn one checked word into other words or files.
1792
+ if (argv.some((word, index) => index > 0 && (command.glob?.[index] === true || word.startsWith("~"))))
1793
+ return human(request, "sensitive", "A credential helper argument the shell would expand requires a person");
1794
+ for (const file of helper.files) {
1795
+ const check = permissiveRead(cwd, file);
1796
+ if (!check.allowed)
1797
+ return human(request, check.category, check.reason);
1798
+ if (!helperFileAllowed(cwd, file, profile))
1799
+ return human(request, "sensitive", "A credential helper may only send a file from this checkout or a temp directory");
1800
+ }
1801
+ return {
1802
+ ...result(request, "impactful-write", "Listed credential helper", true),
1803
+ credentialHelpers: [`${helper.helper.path}#${helper.shape}`],
1804
+ };
1805
+ }
1636
1806
  if (SHELLS.has(program) || INTERPRETERS.has(program)) {
1637
1807
  if (stageIndex > 0)
1638
1808
  return human(request, "unknown", "Piping into a shell or interpreter requires human review");
@@ -1738,7 +1908,9 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
1738
1908
  /(?:-X|--request)[=\s]?(?:DELETE|PUT)\b/i.test(joined))
1739
1909
  return human(request, "destructive", "Destructive HTTP verbs require human approval");
1740
1910
  if (program === "git")
1741
- return gitDecision(request, argv, cwd, () => argv[0] === "git" && command.argv[0] === "git" && depth === 0 && soleEffect(request), [...profile.scratchRoots, ...tempRoots()], fill);
1911
+ return gitDecision(request, argv, cwd, () => argv[0] === "git" && command.argv[0] === "git" && depth === 0 && soleEffect(request), [...profile.scratchRoots, ...tempRoots()], fill, (script, dir) => depth >= 2
1912
+ ? human(request, "unknown", "Git shell alias requires human review")
1913
+ : commandDecision(request, script, profile, depth + 1, [dir], fill));
1742
1914
  if (program === "gh") {
1743
1915
  const gh = ghDecision(request, argv);
1744
1916
  if (gh)
package/dist/policy.d.ts CHANGED
@@ -9,6 +9,18 @@ export declare function words(command: string): string[] | undefined;
9
9
  export declare function result(request: Request, category: Category, reason: string, approve?: boolean): Decision;
10
10
  /** Self-reported confidence needed for the AI to approve an ambiguous request. */
11
11
  export declare const AMBIGUOUS_CONFIDENCE = 0.95;
12
+ /** The reason a plain read of non-secret files is approved, protected configuration included. */
13
+ export declare const PLAIN_READ = "Plain read of non-secret files";
14
+ export declare const CHAIN_APPROVED = "A read-only prefix followed by a command approved on its own";
15
+ /** Most words of a shell command the engine judges; here-document bodies do not count. */
16
+ export declare const MAX_WORDS = 1000;
17
+ export declare const TOO_MANY_WORDS = "Command has too many words to check";
18
+ export declare const FLOOR_REASON = "A cloud, repository, publishing or deletion command outside disposable roots needs a person";
19
+ /**
20
+ * The decision for a request. The floor runs after the engine: a cloud or infrastructure write, a
21
+ * repository deletion, a publish or a recursive delete outside disposable roots is never approved,
22
+ * whatever rule approved it, and asks instead.
23
+ */
12
24
  export declare function evaluate(request: Request, ai?: Classification, profile?: Profile): Decision;
13
25
  export declare function evaluateArgv(request: Request, argv: string[]): Decision;
14
26
  //# sourceMappingURL=policy.d.ts.map
package/dist/policy.js CHANGED
@@ -1,10 +1,26 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync } from "node:fs";
3
3
  import { basename, dirname, resolve } from "node:path";
4
- import { branchEvidence, canonical, git, inside, pathEvidence } from "./evidence.js";
5
- import { commandDecision, permissiveRead, permissiveWrite, WORKTREE_DELETION, } from "./permissive.js";
4
+ import { branchEvidence, canonical, git, inside, pathEvidence, resolveWord, withEvidence, } from "./evidence.js";
5
+ import { hardRule, hardRules } from "./hard.js";
6
+ /** Tools that write a file (a shell command is judged by the engine itself). */
7
+ const WRITE_TOOLS = new Set([
8
+ "Write",
9
+ "Edit",
10
+ "MultiEdit",
11
+ "NotebookEdit",
12
+ "create",
13
+ "edit",
14
+ "write_file",
15
+ "apply_patch",
16
+ ]);
17
+ import { onRemote } from "./merged.js";
18
+ import { commandDecision, permissiveRead, permissiveWrite } from "./permissive.js";
6
19
  import { mcpReadOnly, strictProfile } from "./profile.js";
20
+ import { enterable, plainRead, readOnly, unsafeGlob } from "./reads.js";
7
21
  import { redactText } from "./redact.js";
22
+ import { parseShell } from "./shell.js";
23
+ import { scan } from "./shellscan.js";
8
24
  import { defaultAllowed } from "./tools.js";
9
25
  import { CATEGORIES, } from "./types.js";
10
26
  export function hash(value) {
@@ -186,14 +202,14 @@ export function result(request, category, reason, approve = false) {
186
202
  }
187
203
  /** Self-reported confidence needed for the AI to approve an ambiguous request. */
188
204
  export const AMBIGUOUS_CONFIDENCE = 0.95;
205
+ /** The reason a plain read of non-secret files is approved, protected configuration included. */
206
+ export const PLAIN_READ = "Plain read of non-secret files";
189
207
  /**
190
- * Escalations that stay with a human in every profile. Category `sensitive` (credentials,
191
- * secrets, protected paths and configuration) is excluded by category; these are the remaining
192
- * boundaries: the request itself cannot be trusted, an organization or the profile asked for a
193
- * human, or a repository rule forbids the write. Of `destructive`, only deletion inside a linked
194
- * feature worktree is classified: recoverable is approved, anything else goes to a person.
208
+ * Escalations the classifier is never asked about because the request itself cannot be judged
209
+ * from what it is shown: an incomplete or malformed request, a working directory other than the
210
+ * reviewed one, an unreadable patch, or a custom environment the classifier does not see.
195
211
  */
196
- const HUMAN_BOUNDARIES = [
212
+ const NOT_CLASSIFIABLE = [
197
213
  /^Incomplete request/,
198
214
  /^Invalid tool input/,
199
215
  /^Execution directory differs/,
@@ -201,63 +217,218 @@ const HUMAN_BOUNDARIES = [
201
217
  /^Patch has no verified target paths/,
202
218
  /^Environment override requires human review/,
203
219
  /^Custom execution environment requires human review/,
204
- /^Matches an organization human-approval pattern/,
205
- /^Write requires a linked worktree on a feature branch/,
206
- /^Cloud operation is outside the verified inspection catalog/,
207
220
  ];
208
221
  /**
209
- * Under the permissive profile, every escalation that is not a boundary is ambiguous: the
210
- * deterministic engine cannot decide it, so the session's AI classifier does. Strict mode is
211
- * unchanged.
222
+ * Every escalation the engine cannot decide goes to the AI classifier, in every profile, unless it
223
+ * is a hard human item (credentials, protected configuration, unrecoverable loss, humanPatterns),
224
+ * which goes straight to a person, or cannot be judged from what the classifier is shown.
212
225
  */
213
- function markAmbiguous(decision, profile) {
214
- if (profile.mode !== "permissive" ||
215
- decision.decision !== "human" ||
216
- decision.needsClassification ||
217
- decision.category === "sensitive" ||
218
- // Git history, remote, cloud, publish and HTTP deletions are not provably recoverable, and the
219
- // classifier is not independent; only local deletion inside a feature worktree is classified.
220
- (decision.category === "destructive" && decision.reason !== WORKTREE_DELETION) ||
221
- HUMAN_BOUNDARIES.some((pattern) => pattern.test(decision.reason)))
226
+ function markAmbiguous(request, decision, profile) {
227
+ if (decision.decision !== "human")
228
+ return decision;
229
+ const hard = hardRule(request, decision, profile.scratchRoots);
230
+ if (hard)
231
+ return { ...decision, needsClassification: false, tier: undefined, hard };
232
+ if (NOT_CLASSIFIABLE.some((pattern) => pattern.test(decision.reason)))
222
233
  return decision;
223
234
  return { ...decision, needsClassification: true, tier: "ambiguous" };
224
235
  }
236
+ /**
237
+ * Approves iff `recoverable && confidence >= 0.95 && category not in {sensitive, unknown}`.
238
+ * Anything else is a person's decision; the engine's reason is kept (session grants key on it)
239
+ * and the classifier's answer is shown beside it.
240
+ */
225
241
  function resolveAmbiguous(decision, ai) {
226
- // A `destructive` verdict approves only what the engine proved is a deletion inside a feature
227
- // worktree; on anything else (an unparsable `rm -rf ~/{a,b}`) the label alone means a person.
228
- const destructiveOk = ai.category !== "destructive" || decision.reason === WORKTREE_DELETION;
229
242
  const safe = ai.recoverable === true &&
230
243
  ai.confidence >= AMBIGUOUS_CONFIDENCE &&
231
- destructiveOk &&
232
244
  !["sensitive", "unknown"].includes(ai.category);
233
- const base = { ...decision, needsClassification: false, cache: "session", ai };
245
+ const base = { ...decision, needsClassification: false, ai };
234
246
  if (safe)
235
247
  return {
236
248
  ...base,
237
249
  decision: "approve",
250
+ cache: "session",
238
251
  category: ai.category,
239
252
  classification: "approved",
240
- reason: "Ambiguous request judged recoverable and non-sensitive by the same-session AI",
241
- };
242
- const why = ai.rationale ? ` Rationale: ${redactText(ai.rationale, 200)}` : "";
243
- // Possible unrecoverable loss is a person's decision, not a deny the model works around.
244
- if (decision.category === "destructive" || ai.category === "destructive")
245
- return {
246
- ...base,
247
- decision: "human",
248
- cache: "none",
249
- classification: "denied",
250
- reason: `Destructive request not judged recoverable by the classifier (confidence ${ai.confidence}, recoverable ${ai.recoverable ?? "not stated"}); a person decides.${why}`,
253
+ reason: "Judged recoverable and non-sensitive by the AI classifier",
251
254
  };
255
+ const why = ai.rationale ? `: ${redactText(ai.rationale, 200)}` : "";
252
256
  return {
253
257
  ...base,
254
- decision: "deny",
258
+ decision: "human",
259
+ cache: "none",
255
260
  classification: "denied",
256
- 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.`,
261
+ classifierNote: `The AI classifier did not approve it (category ${ai.category}, confidence ${ai.confidence}, recoverable ${ai.recoverable ?? "not stated"})${why}`,
257
262
  };
258
263
  }
264
+ export const CHAIN_APPROVED = "A read-only prefix followed by a command approved on its own";
265
+ /** A word as a single-quoted shell word. */
266
+ const quote = (word) => /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
267
+ /**
268
+ * A chain (`a && b; c`) whose commands before the last only read (or `cd` into an existing
269
+ * directory), and whose last command the engine approves on its own in every directory the `cd`s
270
+ * could leave it in. Earlier commands change nothing the last one could see, so judging it alone
271
+ * is judging it in place. Rejected outright: substitutions, variables, assignments, globs,
272
+ * here-documents, background jobs, `CDPATH`, and pipes (unless every stage only reads). The last
273
+ * command still gets every check, hard human items included.
274
+ */
275
+ function chainApproved(request, profile) {
276
+ const command = request.input.command ?? request.input.cmd;
277
+ if (!SHELL_TOOLS.has(request.tool) || typeof command !== "string" || command.length > 20_000)
278
+ return false;
279
+ const pipelines = parseShell(command);
280
+ if (!pipelines || pipelines.length < 2 || pipelines.length > 24)
281
+ return false;
282
+ const cwds = new Set([request.cwd]);
283
+ for (const [index, pipeline] of pipelines.entries()) {
284
+ const last = index === pipelines.length - 1;
285
+ for (const cmd of pipeline) {
286
+ if (cmd.env.length || cmd.subs.length || cmd.stdin !== undefined)
287
+ return false;
288
+ if (cmd.loose?.some(Boolean) || unsafeGlob(cmd.argv, cmd.glob))
289
+ return false;
290
+ }
291
+ if (pipeline.length > 1 && !pipeline.every((cmd) => readOnly(cmd.argv)))
292
+ return false;
293
+ const [cmd] = pipeline;
294
+ if (!cmd)
295
+ return false;
296
+ if (cmd.argv[0] === "cd") {
297
+ const target = cmd.argv[1];
298
+ if (last ||
299
+ pipeline.length > 1 ||
300
+ cmd.argv.length !== 2 ||
301
+ !target ||
302
+ target.startsWith("-") ||
303
+ cmd.redirects.length ||
304
+ (process.env.CDPATH && !/^[/~.]/.test(target)))
305
+ return false;
306
+ // As the script's first command, a `cd` that cannot fail leaves only its target.
307
+ // After `||` the next command runs exactly when it fails, so `||` anywhere keeps the old one.
308
+ const sure = index === 0 && !command.includes("||") ? enterable(target) : undefined;
309
+ if (sure) {
310
+ cwds.clear();
311
+ cwds.add(sure);
312
+ continue;
313
+ }
314
+ const next = new Set();
315
+ for (const dir of cwds) {
316
+ try {
317
+ const to = resolveWord(dir, target);
318
+ if (!existsSync(to))
319
+ return false;
320
+ next.add(to);
321
+ }
322
+ catch {
323
+ return false;
324
+ }
325
+ }
326
+ // `cd x || y` may leave the old directory; keep every place the next command could run.
327
+ for (const dir of next)
328
+ cwds.add(dir);
329
+ if (cwds.size > 4)
330
+ return false;
331
+ continue;
332
+ }
333
+ if (!last) {
334
+ // Output may only go nowhere: a read-only command that writes a file is not read-only.
335
+ const quiet = cmd.redirects.every((r) => (r.op === ">&" && r.target === "1") || (r.op === ">" && r.target === "/dev/null"));
336
+ if (!quiet)
337
+ return false;
338
+ // Only reads, and only of what a plain read may name (`readable`): the prefix's output
339
+ // reaches the agent too. Every stage gets the full plain-read check, file readers and
340
+ // filters (`jq`, `cut`, `wc`, `diff`, `sort`) alike.
341
+ for (const stage of pipeline) {
342
+ if (!readOnly(stage.argv))
343
+ return false;
344
+ const text = stage.argv.map(quote).join(" ");
345
+ for (const cwd of cwds)
346
+ if (!plainRead({ ...request, cwd, input: { command: text } }, profile.scratchRoots))
347
+ return false;
348
+ }
349
+ continue;
350
+ }
351
+ const text = pipeline
352
+ .map((stage) => [
353
+ ...stage.argv.map(quote),
354
+ ...stage.redirects.map((r) => `${r.fd}${r.op}${r.op === ">&" ? r.target : quote(r.target)}`),
355
+ ].join(" "))
356
+ .join(" | ");
357
+ for (const cwd of cwds) {
358
+ const input = { ...request.input, command: text };
359
+ if ("workdir" in input)
360
+ input.workdir = cwd;
361
+ if ("cwd" in input)
362
+ input.cwd = cwd;
363
+ if (evaluate({ ...request, cwd, input }, undefined, profile).decision !== "approve")
364
+ return false;
365
+ }
366
+ }
367
+ return true;
368
+ }
369
+ /** Most words of a shell command the engine judges; here-document bodies do not count. */
370
+ export const MAX_WORDS = 1_000;
371
+ export const TOO_MANY_WORDS = "Command has too many words to check";
372
+ /** Whether a script has more than MAX_WORDS words outside here-documents (one linear scan). */
373
+ function tooManyWords(command) {
374
+ let count = 0;
375
+ for (const segment of scan(command).segments)
376
+ for (const word of segment)
377
+ if (!word.heredoc && ++count > MAX_WORDS)
378
+ return true;
379
+ return false;
380
+ }
381
+ /** Hard items no step approves, the engine's included: the deterministic floor. */
382
+ const FLOOR = new Set(["cloud-write", "repo-delete", "publish", "rm-outside", "policy-state"]);
383
+ export const FLOOR_REASON = "A cloud, repository, publishing or deletion command outside disposable roots needs a person";
384
+ /**
385
+ * The decision for a request. The floor runs after the engine: a cloud or infrastructure write, a
386
+ * repository deletion, a publish or a recursive delete outside disposable roots is never approved,
387
+ * whatever rule approved it, and asks instead.
388
+ */
259
389
  export function evaluate(request, ai, profile = strictProfile) {
260
- const decision = markAmbiguous(evaluateCore(request, profile), profile);
390
+ return withEvidence(() => evaluateOnce(request, ai, profile));
391
+ }
392
+ function evaluateOnce(request, ai, profile) {
393
+ // A shell command with more words than the engine judges in time asks, before any judging.
394
+ const command = request.input?.command ?? request.input?.cmd;
395
+ if (SHELL_TOOLS.has(request.tool) && typeof command === "string" && tooManyWords(command))
396
+ return result(request, "unknown", TOO_MANY_WORDS);
397
+ const decision = evaluateSteps(request, ai, profile);
398
+ if (decision.decision !== "approve" || !SHELL_TOOLS.has(request.tool))
399
+ return decision;
400
+ const floor = hardRules(request, { ...decision, decision: "human" }, profile.scratchRoots).find(
401
+ // A profile with `cloudWrites: "allow"` chose to automate non-destructive cloud writes; the
402
+ // engine still asks for cloud deletion there.
403
+ (rule) => FLOOR.has(rule) && !(rule === "cloud-write" && profile.cloudWrites === "allow"));
404
+ return floor ? { ...result(request, "destructive", FLOOR_REASON), hard: floor } : decision;
405
+ }
406
+ function evaluateSteps(request, ai, profile = strictProfile) {
407
+ const core = evaluateCore(request, profile);
408
+ // A plain read of non-secret files, protected configuration included, changes nothing.
409
+ if (core.decision === "human" &&
410
+ !NOT_CLASSIFIABLE.some((pattern) => pattern.test(core.reason)) &&
411
+ plainRead(request, profile.scratchRoots))
412
+ return result(request, "code-read", PLAIN_READ, true);
413
+ if (core.decision === "human" &&
414
+ !NOT_CLASSIFIABLE.some((pattern) => pattern.test(core.reason)) &&
415
+ chainApproved(request, profile))
416
+ return result(request, "worktree-write", CHAIN_APPROVED, true);
417
+ // What the harness lets run (its settings, hooks, permission rules) and the policy profile are
418
+ // never approved by any step, the engine's included: wherever they live (`CLAUDE_CONFIG_DIR` in
419
+ // a temp directory, say), a write to them asks.
420
+ if (core.decision === "approve" && WRITE_TOOLS.has(request.tool)) {
421
+ const tamper = hardRules(request, { ...core, decision: "human" }, profile.scratchRoots).find((rule) => rule === "harness-settings" || rule === "policy-profile" || rule === "policy-state");
422
+ if (tamper)
423
+ return {
424
+ ...result(request, "sensitive", "Harness settings and the policy profile require a person"),
425
+ hard: tamper,
426
+ };
427
+ }
428
+ const decision = markAmbiguous(request, core, profile);
429
+ // A hard human item is a person's: no classification, however confident, approves it.
430
+ if (decision.hard)
431
+ return decision;
261
432
  if (ai) {
262
433
  // Self-reported confidence is not a probability or a substitute for verified effects.
263
434
  if (!CATEGORIES.includes(ai.category) ||
@@ -328,7 +499,8 @@ function evaluateCore(request, profile) {
328
499
  const cwd = input.workdir ?? input.cwd ?? request.cwd;
329
500
  if (typeof cwd !== "string" || cwd !== request.cwd)
330
501
  return result(request, "unknown", "Execution directory differs from the reviewed directory");
331
- const file = input.file_path ?? input.path;
502
+ // Only the target decides a file tool: `content`, `old_string` and `new_string` are data.
503
+ const file = input.file_path ?? input.notebook_path ?? input.path;
332
504
  if (request.tool === "apply_patch" && typeof input.command === "string") {
333
505
  const lines = input.command.split("\n");
334
506
  if (lines[0] !== "*** Begin Patch" || lines.at(-1)?.trim() !== "*** End Patch")
@@ -349,7 +521,10 @@ function evaluateCore(request, profile) {
349
521
  const denied = checks.find((check) => !check.allowed);
350
522
  return result(request, denied?.category ?? "worktree-write", denied?.reason ?? "Verified patch targets within feature worktrees", !denied);
351
523
  }
352
- if (["Read", "view", "read_file", "Edit", "Write", "edit", "create", "write_file"].includes(request.tool) &&
524
+ if ([
525
+ ...["Read", "view", "read_file", "Edit", "Write", "edit", "create", "write_file"],
526
+ ...["MultiEdit", "NotebookEdit"],
527
+ ].includes(request.tool) &&
353
528
  typeof file === "string") {
354
529
  const write = !["Read", "view", "read_file"].includes(request.tool);
355
530
  const evidence = profile.mode === "permissive"
@@ -451,8 +626,16 @@ export function evaluateArgv(request, argv) {
451
626
  }
452
627
  return result(request, "worktree-write", "Cannot verify worktree creation targets");
453
628
  }
454
- if (args[0] === "branch" && args.some((a) => a === "-d" || a === "-D" || a === "--delete"))
629
+ if (args[0] === "branch" && args.some((a) => a === "-d" || a === "-D" || a === "--delete")) {
630
+ const names = args.slice(1).filter((a) => !a.startsWith("-"));
631
+ const flags = args.slice(1).filter((a) => a.startsWith("-"));
632
+ // A branch whose tip is on a remote-tracking ref loses nothing when deleted.
633
+ if (names.length &&
634
+ flags.every((f) => ["-d", "-D", "--delete", "-q", "--quiet"].includes(f)) &&
635
+ names.every((name) => onRemote(gitCwd, name)))
636
+ return result(request, "git-read", "Deleted branches' tips are on a remote ref", true);
455
637
  return result(request, "destructive", branchEvidence(gitCwd, args.at(-1) ?? ""));
638
+ }
456
639
  if (args.length === 1 && ["status", "diff", "log"].includes(args[0] ?? ""))
457
640
  return result(request, "git-read", "Verified Git inspection command", true);
458
641
  if (args.join(" ") === "branch --show-current" || args.join(" ") === "rev-parse HEAD")
package/dist/profile.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { type ClassifierConfig } from "./classifier.js";
2
+ import { type CredentialHelper } from "./helpers.js";
1
3
  /**
2
4
  * A profile is policy *data*. The engine's checks (protected paths, secret retrieval, verified
3
5
  * effects) are code and cannot be relaxed by a profile; a profile only chooses how much of the
@@ -25,6 +27,10 @@ export interface Profile {
25
27
  codex: string[];
26
28
  copilot: string[];
27
29
  };
30
+ /** Scripts that may read a credential for one narrow job, as committed on the default branch. */
31
+ credentialHelpers: CredentialHelper[];
32
+ /** The AI classifier each harness runs for what the engine escalates: CLI models and a kill switch. */
33
+ classifier: ClassifierConfig;
28
34
  /** SHA-256 of the file the profile came from, for the audit log. */
29
35
  digest?: string;
30
36
  }
@@ -33,6 +39,7 @@ export declare const MAX_MCP_READ_ONLY = 200;
33
39
  /** Whether `tool` is listed in the profile's `mcpReadOnly`. */
34
40
  export declare function mcpReadOnly(profile: Profile, tool: string): boolean;
35
41
  export declare const MAX_TOOLS_DENY = 100;
42
+ /** The default profile path (memoized on the variables it depends on: it is asked per word). */
36
43
  export declare function defaultProfilePath(): string;
37
44
  export declare class ProfileError extends Error {
38
45
  }