@agent-corpus/policy-manager 0.10.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.
package/dist/flow.js CHANGED
@@ -34,18 +34,26 @@ const FUNCTION_MARK = "()";
34
34
  const copy = (state) => ({
35
35
  cwds: [...state.cwds],
36
36
  ...(state.failed ? { failed: [...state.failed] } : {}),
37
+ ...(state.sure ? { sure: true } : {}),
37
38
  vars: new Map(state.vars),
38
39
  funcs: new Map(state.funcs),
39
40
  });
40
41
  /** The last `cd` may have failed: every directory it could have left the shell in is possible. */
41
- function settle(state) {
42
- if (state.failed)
42
+ function settle(state, failure = false) {
43
+ // After `;`, a newline or `&`, a `cd` that cannot fail did not; after `||` or `!` it did.
44
+ if (state.failed && (failure || !state.sure))
43
45
  state.cwds = [...new Set([...state.cwds, ...state.failed])];
44
46
  delete state.failed;
47
+ delete state.sure;
45
48
  }
46
49
  /** Every directory either state could be in; neither input is changed. */
47
50
  function merge(a, b) {
48
- const cwds = [...a.cwds, ...(a.failed ?? []), ...b.cwds, ...(b.failed ?? [])];
51
+ const cwds = [
52
+ ...a.cwds,
53
+ ...(a.sure ? [] : (a.failed ?? [])),
54
+ ...b.cwds,
55
+ ...(b.sure ? [] : (b.failed ?? [])),
56
+ ];
49
57
  const vars = new Map();
50
58
  for (const [name, left] of a.vars) {
51
59
  if (!b.vars.has(name))
@@ -67,6 +75,10 @@ function replace(target, source) {
67
75
  target.failed = source.failed;
68
76
  else
69
77
  delete target.failed;
78
+ if (source.sure)
79
+ target.sure = true;
80
+ else
81
+ delete target.sure;
70
82
  target.vars = source.vars;
71
83
  target.funcs = source.funcs;
72
84
  }
@@ -875,6 +887,7 @@ function changeDirectory(ctx, state, piped, envs, build) {
875
887
  return human(request, "unknown", "Directory change in a loop or pipeline requires human review");
876
888
  settle(state);
877
889
  let cwds = [];
890
+ let absolute = true;
878
891
  for (const env of envs) {
879
892
  const target = build(env)
880
893
  .argv.slice(1)
@@ -882,6 +895,8 @@ function changeDirectory(ctx, state, piped, envs, build) {
882
895
  // A bare `cd` and `~` or `~/x` go to the home directory; `~user` and `-` stay with a human.
883
896
  const raw = target.length === 0 ? "~" : target[0];
884
897
  const word = raw === "~" || raw?.startsWith("~/") ? join(homedir(), raw.slice(1)) : raw;
898
+ if (!word || !isAbsolute(word))
899
+ absolute = false;
885
900
  if (target.length > 1 ||
886
901
  !word ||
887
902
  word.includes(SUBSTITUTION) ||
@@ -921,8 +936,26 @@ function changeDirectory(ctx, state, piped, envs, build) {
921
936
  }
922
937
  if (!cwds.length || cwds.length + state.cwds.length > MAX_DIRECTORIES)
923
938
  return human(request, "unknown", "Too many directory changes to verify");
924
- // `cd` can fail, so the directory it started from stays possible unless `&&` follows.
939
+ // `cd` can fail, so the directory it started from stays possible unless `&&` follows. As the
940
+ // script's first command (nothing earlier could remove it), into an absolute directory that
941
+ // exists and that this user may enter, it does not fail: the next command runs there whatever
942
+ // joins it (`cd /x && a; b`, or a newline after a here-document).
943
+ const certain = ctx.depth === 0 &&
944
+ ctx.box.current === ctx.box.first &&
945
+ absolute &&
946
+ cwds.every((dir) => {
947
+ try {
948
+ return isDirectory(dir) && (accessSync(dir, constants.X_OK), true);
949
+ }
950
+ catch {
951
+ return false;
952
+ }
953
+ });
925
954
  state.failed = state.cwds;
955
+ if (certain)
956
+ state.sure = true;
957
+ else
958
+ delete state.sure;
926
959
  state.cwds = cwds;
927
960
  ctx.box.last = result(request, "code-read", "Directory change", true);
928
961
  return undefined;
@@ -1357,6 +1390,7 @@ function runIf(ctx, node, state) {
1357
1390
  // that ends the condition did change directory. Earlier clauses are already merged in.
1358
1391
  const taken = copy(outcome.success ?? current);
1359
1392
  delete taken.failed;
1393
+ delete taken.sure;
1360
1394
  const body = runList(ctx, clause.body, taken);
1361
1395
  if (body)
1362
1396
  return body;
@@ -1446,8 +1480,15 @@ function cannotFail(ctx, node, state) {
1446
1480
  }
1447
1481
  }
1448
1482
  /** With `outcome`, also reports the state when the list's exit status is success. */
1483
+ /** How long one evaluation may take before it asks instead. */
1484
+ export const TIME_BUDGET_MS = 5_000;
1485
+ export const TIME_BUDGET_REASON = "Command took too long to check";
1486
+ /** When the evaluation in progress must stop, checked between commands. */
1487
+ let deadline = 0;
1449
1488
  function runList(ctx, list, state, outcome) {
1450
1489
  for (const [index, item] of list.items.entries()) {
1490
+ if (deadline && Date.now() > deadline)
1491
+ return human(ctx.request, "unknown", TIME_BUDGET_REASON);
1451
1492
  const last = index === list.items.length - 1;
1452
1493
  // Each item runs whether or not the one before it succeeded.
1453
1494
  settle(state);
@@ -1478,11 +1519,14 @@ function runList(ctx, list, state, outcome) {
1478
1519
  for (const [step, next] of rest.entries()) {
1479
1520
  running = copy(running);
1480
1521
  onlyAnd &&= next.op === "&&";
1481
- if (onlyAnd)
1522
+ if (onlyAnd) {
1482
1523
  delete running.failed;
1524
+ delete running.sure;
1525
+ }
1483
1526
  else {
1484
- settle(running);
1485
- running.cwds = [...new Set([...running.cwds, ...possible.cwds])];
1527
+ settle(running, true);
1528
+ // An `||` runs when something before it failed, a `cd` that cannot otherwise fail included.
1529
+ running.cwds = [...new Set([...running.cwds, ...possible.cwds, ...(target.failed ?? [])])];
1486
1530
  }
1487
1531
  const skipped = runPipeline(ctx, next.node, running);
1488
1532
  if (skipped)
@@ -1505,10 +1549,11 @@ function runList(ctx, list, state, outcome) {
1505
1549
  }
1506
1550
  function runPipeline(ctx, node, state) {
1507
1551
  if (node.stages.length === 1) {
1552
+ ctx.box.current = node;
1508
1553
  const refusal = runCommand(ctx, node.stages[0], state, 0, false);
1509
1554
  // `! cd x` succeeds exactly when the `cd` failed.
1510
1555
  if (node.negated)
1511
- settle(state);
1556
+ settle(state, true);
1512
1557
  return refusal;
1513
1558
  }
1514
1559
  const changed = new Set();
@@ -1549,11 +1594,21 @@ export function commandDecision(request, command, profile, depth = 0, start = [r
1549
1594
  const opening = script.items[0];
1550
1595
  if (depth === 0 && opening && !opening.background)
1551
1596
  ctx.box.first = opening.node.first;
1552
- const refusal = runList(ctx, script, {
1553
- cwds: [...start],
1554
- vars: new Map(),
1555
- funcs: new Map(),
1556
- });
1597
+ const outer = depth === 0 && !deadline;
1598
+ if (outer)
1599
+ deadline = Date.now() + TIME_BUDGET_MS;
1600
+ let refusal;
1601
+ try {
1602
+ refusal = runList(ctx, script, {
1603
+ cwds: [...start],
1604
+ vars: new Map(),
1605
+ funcs: new Map(),
1606
+ });
1607
+ }
1608
+ finally {
1609
+ if (outer)
1610
+ deadline = 0;
1611
+ }
1557
1612
  if (refusal)
1558
1613
  return refusal;
1559
1614
  const last = ctx.box.last ?? human(request, "unknown", "Empty command");
@@ -0,0 +1,13 @@
1
+ /** Git's own subcommands. Any other word after `git` is an alias or an external `git-<name>`. */
2
+ export declare const KNOWN_GIT: Set<string>;
3
+ /**
4
+ * What `git <name>` runs when `name` is an alias, read with `git config --get alias.<name>` in
5
+ * `cwd` (repository, global and system configuration, as Git reads them). Undefined when it is
6
+ * not an alias or cannot be read. A value starting with `!` is a shell command.
7
+ */
8
+ export declare function gitAlias(cwd: string, name: string): string | undefined;
9
+ /** The directory Git runs a `!` alias in: the top level of the work tree, or `cwd` outside one. */
10
+ export declare function aliasDirectory(cwd: string): string;
11
+ /** `args` as shell words, single-quoted, the way Git appends them to a `!` alias. */
12
+ export declare function shellArgs(args: string[]): string;
13
+ //# sourceMappingURL=gitalias.d.ts.map
@@ -0,0 +1,33 @@
1
+ import { git } from "./evidence.js";
2
+ /** Git's own subcommands. Any other word after `git` is an alias or an external `git-<name>`. */
3
+ export const KNOWN_GIT = new Set("add am annotate apply archive bisect blame branch bugreport bundle cat-file check-attr check-ignore check-ref-format checkout cherry cherry-pick clean clone column commit commit-tree config count-objects credential describe diff diff-files diff-index diff-tree difftool fetch filter-branch for-each-ref format-patch fsck gc grep hash-object help init interpret-trailers log ls-files ls-remote ls-tree maintenance merge merge-base merge-file merge-tree mergetool mktag mktree mv name-rev notes prune pull push range-diff read-tree rebase reflog remote repack replace request-pull rerere reset restore rev-list rev-parse revert rm send-email shortlog show show-branch show-ref sparse-checkout stage stash status submodule switch symbolic-ref tag update-index update-ref var verify-commit verify-pack verify-tag version whatchanged worktree write-tree".split(" "));
4
+ /**
5
+ * What `git <name>` runs when `name` is an alias, read with `git config --get alias.<name>` in
6
+ * `cwd` (repository, global and system configuration, as Git reads them). Undefined when it is
7
+ * not an alias or cannot be read. A value starting with `!` is a shell command.
8
+ */
9
+ export function gitAlias(cwd, name) {
10
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name))
11
+ return undefined;
12
+ try {
13
+ const value = git(cwd, ["config", "--get", `alias.${name}`]);
14
+ return value.trim() ? value : undefined;
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ /** The directory Git runs a `!` alias in: the top level of the work tree, or `cwd` outside one. */
21
+ export function aliasDirectory(cwd) {
22
+ try {
23
+ return git(cwd, ["rev-parse", "--show-toplevel"]);
24
+ }
25
+ catch {
26
+ return cwd;
27
+ }
28
+ }
29
+ /** `args` as shell words, single-quoted, the way Git appends them to a `!` alias. */
30
+ export function shellArgs(args) {
31
+ return args.map((arg) => `'${arg.replace(/'/g, `'\\''`)}'`).join(" ");
32
+ }
33
+ //# sourceMappingURL=gitalias.js.map
package/dist/grants.d.ts CHANGED
@@ -3,16 +3,16 @@ import type { Decision, Request } from "./types.js";
3
3
  export declare const PROTECTED_PATH = "Protected path requires human approval";
4
4
  export declare const HUMAN_PATTERN = "Matches an organization human-approval pattern";
5
5
  /**
6
- * The scope a `--session` approval of this human decision covers, or undefined when it can only
7
- * be approved once. Credential and secret reads, possible unrecoverable loss and anything whose
8
- * targets cannot be read from the request stay one-time. Scopes:
9
- * - a protected-path write: the protected roots it touches (`<worktree>/.agent-config`);
10
- * - a humanPatterns match: the matching patterns, in the same checkout;
11
- * - any other human rule for a simple command: that exact command, same checkout.
12
- * Category unknown (the engine could not rule out loss) is approved once only.
13
- * Shell scopes need a simple command, so nothing else in the script hides behind the rule.
6
+ * The scope a session approval of this human decision covers, or undefined when it can only be
7
+ * approved once. A scope is always the same rule and the same exact target:
8
+ * - a protected-path write: the exact files it writes, in the same checkout;
9
+ * - any other rule for a simple command (a humanPatterns match included): that exact command, in
10
+ * the same checkout.
11
+ * Category unknown, sensitive or destructive, the ONCE_ONLY hard items, and anything whose targets
12
+ * cannot be read from the request are approved once only. Shell scopes need a simple command, so
13
+ * nothing else in the script hides behind the rule.
14
14
  */
15
15
  export declare function grantScope(request: Request, decision: Decision, profile: Profile): string | undefined;
16
16
  /** What a session scope covers, in words the user can check before approving it. */
17
- export declare function scopeLabel(scope: string, profile: Profile): string;
17
+ export declare function scopeLabel(scope: string, _profile: Profile): string;
18
18
  //# sourceMappingURL=grants.d.ts.map
package/dist/grants.js CHANGED
@@ -85,22 +85,46 @@ function simple(request) {
85
85
  return argv?.length ? argv : undefined;
86
86
  }
87
87
  /**
88
- * The scope a `--session` approval of this human decision covers, or undefined when it can only
89
- * be approved once. Credential and secret reads, possible unrecoverable loss and anything whose
90
- * targets cannot be read from the request stay one-time. Scopes:
91
- * - a protected-path write: the protected roots it touches (`<worktree>/.agent-config`);
92
- * - a humanPatterns match: the matching patterns, in the same checkout;
93
- * - any other human rule for a simple command: that exact command, same checkout.
94
- * Category unknown (the engine could not rule out loss) is approved once only.
95
- * Shell scopes need a simple command, so nothing else in the script hides behind the rule.
88
+ * Hard items a session grant never covers: possible unrecoverable loss, credentials, the policy
89
+ * manager's own guards, deterministic-floor items, and every file that changes what the harness
90
+ * allows (settings, hooks, permission rules, the policy profile). Each is asked every time.
91
+ */
92
+ const ONCE_ONLY = new Set([
93
+ "force-push",
94
+ "delete-unmerged-branch",
95
+ "remove-worktree-force",
96
+ "git-clean",
97
+ "credential-read",
98
+ "harness-settings",
99
+ "policy-profile",
100
+ "policy-state",
101
+ "opaque-script",
102
+ "self-approve",
103
+ "foreign-classification-record",
104
+ "cloud-write",
105
+ "repo-delete",
106
+ "publish",
107
+ "rm-outside",
108
+ ]);
109
+ /**
110
+ * The scope a session approval of this human decision covers, or undefined when it can only be
111
+ * approved once. A scope is always the same rule and the same exact target:
112
+ * - a protected-path write: the exact files it writes, in the same checkout;
113
+ * - any other rule for a simple command (a humanPatterns match included): that exact command, in
114
+ * the same checkout.
115
+ * Category unknown, sensitive or destructive, the ONCE_ONLY hard items, and anything whose targets
116
+ * cannot be read from the request are approved once only. Shell scopes need a simple command, so
117
+ * nothing else in the script hides behind the rule.
96
118
  */
97
119
  export function grantScope(request, decision, profile) {
98
120
  try {
121
+ if (decision.hard && ONCE_ONLY.has(decision.hard))
122
+ return undefined;
99
123
  if (decision.reason === PROTECTED_PATH) {
100
124
  const paths = targets(request) ?? shellPaths(request);
101
125
  if (!paths?.length)
102
126
  return undefined;
103
- const roots = new Set();
127
+ const files = new Set();
104
128
  let top;
105
129
  for (const path of paths) {
106
130
  const lexical = resolveWord(request.cwd, path);
@@ -109,28 +133,28 @@ export function grantScope(request, decision, profile) {
109
133
  const resolved = canonical(lexical);
110
134
  if (sensitive(resolved) || policyState(resolved))
111
135
  return undefined;
112
- const root = protectedRoot(resolved);
136
+ // A word that is not under a protected root (`printf test >> AGENTS.md`) is not the write.
137
+ if (!protectedRoot(resolved))
138
+ continue;
113
139
  const checkout = topLevel(resolved);
114
140
  if (top !== undefined && checkout !== top)
115
141
  return undefined;
116
142
  top = checkout;
117
- if (root)
118
- roots.add(root);
143
+ files.add(resolved);
119
144
  }
120
- return roots.size ? `protected:${[...roots].sort().join("\u0000")}` : undefined;
145
+ return files.size ? `protected:${[...files].sort().join("\u0000")}` : undefined;
121
146
  }
122
147
  const argv = simple(request);
123
148
  if (!argv)
124
149
  return undefined;
125
150
  const checkout = topLevel(request.cwd);
126
- if (decision.reason === HUMAN_PATTERN) {
127
- const joined = argv.join(" ");
128
- const matched = profile.humanPatterns.flatMap((pattern, index) => pattern.test(joined) ? [index] : []);
129
- return matched.length ? `pattern:${matched.join(",")}:${checkout}` : undefined;
151
+ if (decision.reason !== HUMAN_PATTERN) {
152
+ if (decision.category === "sensitive" ||
153
+ decision.category === "destructive" ||
154
+ decision.category === "unknown")
155
+ return undefined;
130
156
  }
131
- if (decision.category === "sensitive" ||
132
- decision.category === "destructive" ||
133
- decision.category === "unknown")
157
+ else if (!profile.humanPatterns.some((pattern) => pattern.test(argv.join(" "))))
134
158
  return undefined;
135
159
  if (argv.slice(1).some((word) => sensitive(word)))
136
160
  return undefined;
@@ -141,22 +165,9 @@ export function grantScope(request, decision, profile) {
141
165
  }
142
166
  }
143
167
  /** What a session scope covers, in words the user can check before approving it. */
144
- export function scopeLabel(scope, profile) {
168
+ export function scopeLabel(scope, _profile) {
145
169
  if (scope.startsWith("protected:"))
146
- return `writes ${scope
147
- .slice("protected:".length)
148
- .split("\u0000")
149
- // A root that is a file (`AGENTS.md`) is written to; a directory, or one not made yet, under.
150
- .map((root) => (existsSync(root) && !statSync(root).isDirectory() ? "to " : "under ") + root)
151
- .join(", ")}`;
152
- if (scope.startsWith("pattern:")) {
153
- const [, indexes = "", ...checkout] = scope.split(":");
154
- const patterns = indexes
155
- .split(",")
156
- .map((index) => profile.humanPatterns[Number(index)]?.source ?? index)
157
- .join(", ");
158
- return `commands matching ${patterns} in ${checkout.join(":")}`;
159
- }
170
+ return `writes to ${scope.slice("protected:".length).split("\u0000").join(", ")}`;
160
171
  const rest = scope.slice(scope.indexOf(":[") + 1);
161
172
  const end = rest.lastIndexOf("]:");
162
173
  const argv = JSON.parse(rest.slice(0, end + 1));
package/dist/hard.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { type Command } from "./shellscan.js";
2
+ import type { Decision, Request } from "./types.js";
3
+ /**
4
+ * Hard human items: requests that always go to a person, are never sent to the AI classifier, and
5
+ * that no classification can approve. Credentials, protected configuration, unrecoverable loss and
6
+ * the profile's humanPatterns, plus two built-in guards on the policy manager's own approvals.
7
+ */
8
+ export declare const HARD_RULES: readonly [
9
+ /** Credential or secret retrieval, and reads of credential paths. */
10
+ "credential-read",
11
+ /** Writes to harness permission and hook settings. */
12
+ "harness-settings",
13
+ /** Writes to the policy profile itself. */
14
+ "policy-profile",
15
+ /**
16
+ * Writing, moving, deleting or changing the policy service's own state (`acp-<uid>-*` in the
17
+ * temp directory: audit logs, token, socket, grants, cache). Reading the audit logs is allowed.
18
+ */
19
+ "policy-state",
20
+ /**
21
+ * A shell or interpreter that reads its script from standard input, a here-string or a file the
22
+ * policy cannot read (`cat x.sh | sh`, `sh < x.sh`, `. <(curl ...)`, `| pwsh`). A literal
23
+ * `echo`, `printf` or quoted here-document piped in is unwrapped and judged instead.
24
+ */
25
+ "opaque-script",
26
+ /** `git push --force`/`--mirror`, and `+` refspecs: they overwrite remote history. */
27
+ "force-push",
28
+ /** Deleting a local or remote branch whose commits are not verified merged. */
29
+ "delete-unmerged-branch",
30
+ /** `git worktree remove --force`/`prune`: discards a worktree's uncommitted and untracked work. */
31
+ "remove-worktree-force",
32
+ /** `git clean`: deletes untracked files. */
33
+ "git-clean",
34
+ /** A command matching the profile's `humanPatterns`. */
35
+ "human-patterns",
36
+ /**
37
+ * The deterministic floor under the classifier: cloud and infrastructure writes and deletes
38
+ * (az, aws, gcloud, kubectl, helm, terraform, pulumi...), GitHub repository, release and secret
39
+ * deletion, package publishing, and a recursive `rm` outside a linked feature worktree, the
40
+ * temp directory and the profile's scratch roots. None of these is provably recoverable.
41
+ */
42
+ "cloud-write", "repo-delete", "publish", "rm-outside",
43
+ /** Any other decision the engine filed as sensitive: protected paths and configuration. */
44
+ "protected",
45
+ /** An agent running `approve` itself. */
46
+ "self-approve",
47
+ /** A classification record for another session or CLI, or with anything added. */
48
+ "foreign-classification-record"];
49
+ export type HardRule = (typeof HARD_RULES)[number];
50
+ /** The reason of session's approve guard (an agent running `approve`). */
51
+ export declare const APPROVE_GUARD = "Only the user may approve a request, by running approve in their own terminal";
52
+ export declare const policyStatePath: (path: string) => boolean;
53
+ /** Whether a command (after wrappers) can run text as code. Unknown programs count. */
54
+ export declare function runsText(cmd: Command): boolean;
55
+ /** Whether any command of a script can run text as code, or the script could not be read. */
56
+ export declare function scriptRunsText(script: string): boolean;
57
+ /** The hard rules a shell script falls under, judged in its working directory. */
58
+ export declare function scriptRules(script: string, cwd: string, scratchRoots?: string[]): Set<HardRule>;
59
+ /** Every hard rule a decision that needs a person falls under, built-in guards first. */
60
+ export declare function hardRules(request: Request, decision: Decision, scratchRoots?: string[]): HardRule[];
61
+ /** The first hard rule a decision that needs a person falls under, or undefined. */
62
+ export declare function hardRule(request: Request, decision: Decision, scratchRoots?: string[]): HardRule | undefined;
63
+ //# sourceMappingURL=hard.d.ts.map