@agent-corpus/policy-manager 0.5.0 → 0.6.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/policy.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { type Profile } from "./profile.js";
2
- import type { Category, Classification, Decision, Request } from "./types.js";
2
+ import { type Category, type Classification, type Decision, type Request } from "./types.js";
3
3
  export declare function hash(value: unknown): string;
4
+ /** The correlation hash of a request, over its effect-relevant input only. */
5
+ export declare function requestHash(request: Request): string;
4
6
  export declare function words(command: string): string[] | undefined;
5
7
  export declare function result(request: Request, category: Category, reason: string, approve?: boolean): Decision;
6
8
  /** Self-reported confidence needed for the AI to approve an ambiguous request. */
package/dist/policy.js CHANGED
@@ -1,13 +1,23 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync } from "node:fs";
3
- import { resolve } from "node:path";
3
+ import { basename, dirname, resolve } from "node:path";
4
4
  import { branchEvidence, canonical, git, inside, pathEvidence } from "./evidence.js";
5
- import { commandDecision, permissiveRead, permissiveWrite } from "./permissive.js";
6
- import { strictProfile } from "./profile.js";
5
+ import { commandDecision, permissiveRead, permissiveWrite, WORKTREE_DELETION, } from "./permissive.js";
6
+ import { mcpReadOnly, strictProfile } from "./profile.js";
7
7
  import { redactText } from "./redact.js";
8
+ import { CATEGORIES, } from "./types.js";
8
9
  export function hash(value) {
9
10
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
10
11
  }
12
+ /** Shell tools whose `description` only labels the command. Elsewhere it can be content. */
13
+ const SHELL_TOOLS = new Set(["Bash", "bash", "exec_command", "shell"]);
14
+ /** The correlation hash of a request, over its effect-relevant input only. */
15
+ export function requestHash(request) {
16
+ if (!SHELL_TOOLS.has(request.tool))
17
+ return hash(request);
18
+ const input = Object.fromEntries(Object.entries(request.input ?? {}).filter(([key]) => key !== "description"));
19
+ return hash({ ...request, input });
20
+ }
11
21
  // Deliberately accepts one simple command. Shell syntax and expansions need human review.
12
22
  export function words(command) {
13
23
  if (!command || /[\r\n\0]/.test(command))
@@ -168,7 +178,7 @@ export function result(request, category, reason, approve = false) {
168
178
  decision: approve ? "approve" : "human",
169
179
  category,
170
180
  reason,
171
- requestHash: hash(request),
181
+ requestHash: requestHash(request),
172
182
  cache: approve && category === "cloud-read" ? "session" : "none",
173
183
  cached: false,
174
184
  };
@@ -176,10 +186,11 @@ export function result(request, category, reason, approve = false) {
176
186
  /** Self-reported confidence needed for the AI to approve an ambiguous request. */
177
187
  export const AMBIGUOUS_CONFIDENCE = 0.95;
178
188
  /**
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.
189
+ * Escalations that stay with a human in every profile. Category `sensitive` (credentials,
190
+ * secrets, protected paths and configuration) is excluded by category; these are the remaining
191
+ * boundaries: the request itself cannot be trusted, an organization or the profile asked for a
192
+ * human, or a repository rule forbids the write. Of `destructive`, only deletion inside a linked
193
+ * feature worktree is classified: recoverable is approved, anything else goes to a person.
183
194
  */
184
195
  const HUMAN_BOUNDARIES = [
185
196
  /^Incomplete request/,
@@ -203,15 +214,21 @@ function markAmbiguous(decision, profile) {
203
214
  decision.decision !== "human" ||
204
215
  decision.needsClassification ||
205
216
  decision.category === "sensitive" ||
206
- decision.category === "destructive" ||
217
+ // Git history, remote, cloud, publish and HTTP deletions are not provably recoverable, and the
218
+ // classifier is not independent; only local deletion inside a feature worktree is classified.
219
+ (decision.category === "destructive" && decision.reason !== WORKTREE_DELETION) ||
207
220
  HUMAN_BOUNDARIES.some((pattern) => pattern.test(decision.reason)))
208
221
  return decision;
209
222
  return { ...decision, needsClassification: true, tier: "ambiguous" };
210
223
  }
211
224
  function resolveAmbiguous(decision, ai) {
225
+ // A `destructive` verdict approves only what the engine proved is a deletion inside a feature
226
+ // worktree; on anything else (an unparsable `rm -rf ~/{a,b}`) the label alone means a person.
227
+ const destructiveOk = ai.category !== "destructive" || decision.reason === WORKTREE_DELETION;
212
228
  const safe = ai.recoverable === true &&
213
229
  ai.confidence >= AMBIGUOUS_CONFIDENCE &&
214
- !["sensitive", "destructive", "unknown"].includes(ai.category);
230
+ destructiveOk &&
231
+ !["sensitive", "unknown"].includes(ai.category);
215
232
  const base = { ...decision, needsClassification: false, cache: "session", ai };
216
233
  if (safe)
217
234
  return {
@@ -222,6 +239,15 @@ function resolveAmbiguous(decision, ai) {
222
239
  reason: "Ambiguous request judged recoverable and non-sensitive by the same-session AI",
223
240
  };
224
241
  const why = ai.rationale ? ` Rationale: ${redactText(ai.rationale, 200)}` : "";
242
+ // Possible unrecoverable loss is a person's decision, not a deny the model works around.
243
+ if (decision.category === "destructive" || ai.category === "destructive")
244
+ return {
245
+ ...base,
246
+ decision: "human",
247
+ cache: "none",
248
+ classification: "denied",
249
+ reason: `Destructive request not judged recoverable by the classifier (confidence ${ai.confidence}, recoverable ${ai.recoverable ?? "not stated"}); a person decides.${why}`,
250
+ };
225
251
  return {
226
252
  ...base,
227
253
  decision: "deny",
@@ -233,16 +259,7 @@ export function evaluate(request, ai, profile = strictProfile) {
233
259
  const decision = markAmbiguous(evaluateCore(request, profile), profile);
234
260
  if (ai) {
235
261
  // Self-reported confidence is not a probability or a substitute for verified effects.
236
- if (![
237
- "code-read",
238
- "worktree-write",
239
- "cloud-read",
240
- "git-read",
241
- "impactful-write",
242
- "destructive",
243
- "sensitive",
244
- "unknown",
245
- ].includes(ai.category) ||
262
+ if (!CATEGORIES.includes(ai.category) ||
246
263
  ai.requestHash !== decision.requestHash ||
247
264
  !Number.isFinite(ai.confidence) ||
248
265
  ai.confidence < 0 ||
@@ -290,6 +307,14 @@ function evaluateCore(request, profile) {
290
307
  const input = request.input;
291
308
  if (!input || typeof input !== "object" || Array.isArray(input))
292
309
  return result(request, "unknown", "Invalid tool input");
310
+ // MCP arguments are tool-specific, so their `cwd` or `path` mean nothing here.
311
+ if (request.tool.startsWith("mcp__"))
312
+ return mcpReadOnly(profile, request.tool)
313
+ ? result(request, "cloud-read", "MCP tool listed as read-only in the profile", true)
314
+ : {
315
+ ...result(request, "unknown", "MCP tool not listed as read-only; left to the harness"),
316
+ decision: "native",
317
+ };
293
318
  const cwd = input.workdir ?? input.cwd ?? request.cwd;
294
319
  if (typeof cwd !== "string" || cwd !== request.cwd)
295
320
  return result(request, "unknown", "Execution directory differs from the reviewed directory");
@@ -338,6 +363,25 @@ function evaluateCore(request, profile) {
338
363
  return result(request, "unknown", "Unsupported shell syntax; no AI classification was performed for this request, so a human decision is required");
339
364
  return evaluateArgv(request, argv);
340
365
  }
366
+ /**
367
+ * `worktree add [--no-track] <path> -b <branch> <base>` (or `-b <branch>` before the path), with
368
+ * `origin/main` or `origin/master` as the base. Anything else is not recognised.
369
+ */
370
+ function worktreeAddForm(args) {
371
+ if (args[0] !== "worktree" || args[1] !== "add")
372
+ return undefined;
373
+ const rest = args.slice(2);
374
+ if (rest[0] === "--no-track")
375
+ rest.shift();
376
+ if (rest.length !== 4 || !/^origin\/(?:main|master)$/.test(rest[3] ?? ""))
377
+ return undefined;
378
+ const [a = "", b = "", c = "", base = ""] = rest;
379
+ if (a === "-b" && !b.startsWith("-") && !c.startsWith("-"))
380
+ return { path: c, branch: b, base };
381
+ if (b === "-b" && !a.startsWith("-") && !c.startsWith("-"))
382
+ return { path: a, branch: c, base };
383
+ return undefined;
384
+ }
341
385
  export function evaluateArgv(request, argv) {
342
386
  const [program, ...args] = argv;
343
387
  let gitCwd = request.cwd;
@@ -375,23 +419,22 @@ export function evaluateArgv(request, argv) {
375
419
  return result(request, "unknown", "Cannot verify Git fetch target");
376
420
  }
377
421
  }
378
- if (args.length === 7 &&
379
- args[0] === "worktree" &&
380
- args[1] === "add" &&
381
- args[2] === "--no-track" &&
382
- args[4] === "-b" &&
383
- args[6] === "origin/main") {
422
+ const add = worktreeAddForm(args);
423
+ if (add) {
384
424
  try {
385
- const root = canonical(git(gitCwd, ["rev-parse", "--show-toplevel"]));
386
- const target = canonical(resolve(gitCwd, args[3] ?? ""));
387
- const branch = args[5] ?? "";
388
- git(gitCwd, ["check-ref-format", "--branch", branch]);
389
- git(gitCwd, ["rev-parse", "--verify", "origin/main^{commit}"]);
390
- if (!/^(?:main|master)$/.test(branch) &&
425
+ // The main checkout's root, also when the command runs in a linked worktree.
426
+ const common = canonical(resolve(gitCwd, git(gitCwd, ["rev-parse", "--git-common-dir"])));
427
+ const root = basename(common) === ".git"
428
+ ? dirname(common)
429
+ : canonical(git(gitCwd, ["rev-parse", "--show-toplevel"]));
430
+ const target = canonical(resolve(gitCwd, add.path));
431
+ git(gitCwd, ["check-ref-format", "--branch", add.branch]);
432
+ git(gitCwd, ["rev-parse", "--verify", `${add.base}^{commit}`]);
433
+ const parents = [resolve(root, ".worktrees"), resolve(root, ".claude", "worktrees")];
434
+ if (!/^(?:main|master)$/.test(add.branch) &&
391
435
  !existsSync(target) &&
392
- inside(resolve(root, ".worktrees"), target) &&
393
- target !== resolve(root, ".worktrees"))
394
- return result(request, "worktree-write", "Create a new linked feature worktree under the repository's .worktrees directory", true);
436
+ parents.some((parent) => inside(parent, target) && target !== parent))
437
+ return result(request, "worktree-write", "Create a new linked feature worktree under the repository's .worktrees or .claude/worktrees directory", true);
395
438
  }
396
439
  catch {
397
440
  /* Unverified worktree creation requires a human. */
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The owner's rule for what needs a person. The engine enforces the deterministic part; the
3
+ * classifier is told this text so its answers agree with the engine.
4
+ */
5
+ export declare const HUMAN_ONLY_FOR = "unrecoverable loss (deleting unmerged work, data with no backup), credential or secret retrieval, protected configuration or paths, and the profile's humanPatterns";
6
+ /** The one rule every harness's classifier is given, and the one the engine enforces. */
7
+ export declare const HUMAN_REVIEW_PRINCIPLE = "A person is needed only for unrecoverable loss (deleting unmerged work, data with no backup), credential or secret retrieval, protected configuration or paths, and the profile's humanPatterns. Everything recoverable is approvable by AI, including outward-facing writes such as a GitHub issue or PR comment: answer recoverable true with its category, not unknown. Recoverable or disposable effects are automatic, including destructive-but-safe ones such as deleting, inside a feature worktree, tracked content Git can restore or a file this session itself created.";
8
+ //# sourceMappingURL=principle.d.ts.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The owner's rule for what needs a person. The engine enforces the deterministic part; the
3
+ * classifier is told this text so its answers agree with the engine.
4
+ */
5
+ export const HUMAN_ONLY_FOR = "unrecoverable loss (deleting unmerged work, data with no backup), credential or secret retrieval, protected configuration or paths, and the profile's humanPatterns";
6
+ /** The one rule every harness's classifier is given, and the one the engine enforces. */
7
+ export const HUMAN_REVIEW_PRINCIPLE = `A person is needed only for ${HUMAN_ONLY_FOR}. Everything recoverable is approvable by AI, including outward-facing writes such as a GitHub issue or PR comment: answer recoverable true with its category, not unknown. Recoverable or disposable effects are automatic, including destructive-but-safe ones such as deleting, inside a feature worktree, tracked content Git can restore or a file this session itself created.`;
8
+ //# sourceMappingURL=principle.js.map
package/dist/profile.d.ts CHANGED
@@ -11,10 +11,18 @@ export interface Profile {
11
11
  humanPatterns: RegExp[];
12
12
  /** Absolute directories where permissive mode may write besides linked feature worktrees. */
13
13
  scratchRoots: string[];
14
+ /**
15
+ * MCP tools that approve without a prompt: exact `mcp__<server>__<tool>` names, or a name whose
16
+ * last segment ends in `*` (`mcp__github__get_*`). Unlisted MCP tools are left to the harness.
17
+ */
18
+ mcpReadOnly: string[];
14
19
  /** SHA-256 of the file the profile came from, for the audit log. */
15
20
  digest?: string;
16
21
  }
17
22
  export declare const strictProfile: Profile;
23
+ export declare const MAX_MCP_READ_ONLY = 200;
24
+ /** Whether `tool` is listed in the profile's `mcpReadOnly`. */
25
+ export declare function mcpReadOnly(profile: Profile, tool: string): boolean;
18
26
  export declare function defaultProfilePath(): string;
19
27
  export declare class ProfileError extends Error {
20
28
  }
package/dist/profile.js CHANGED
@@ -8,7 +8,26 @@ export const strictProfile = {
8
8
  cloudWrites: "human",
9
9
  humanPatterns: [],
10
10
  scratchRoots: [],
11
+ mcpReadOnly: [],
11
12
  };
13
+ export const MAX_MCP_READ_ONLY = 200;
14
+ /**
15
+ * `mcp__<server>__<tool>` where neither segment contains `__` (so the split is unambiguous); `*`
16
+ * only as the suffix of a non-empty tool segment.
17
+ */
18
+ const MCP_ENTRY = /^mcp__[A-Za-z0-9.-]+(?:_[A-Za-z0-9.-]+)*__[A-Za-z0-9.-]+(?:_[A-Za-z0-9.-]+)*(?:_?\*)?$/;
19
+ /** Whether `tool` is listed in the profile's `mcpReadOnly`. */
20
+ export function mcpReadOnly(profile, tool) {
21
+ if (!tool.startsWith("mcp__"))
22
+ return false;
23
+ return profile.mcpReadOnly.some((entry) => {
24
+ if (!entry.endsWith("*"))
25
+ return tool === entry;
26
+ // The whole tool segment, not just the wildcard's part, must be free of `__`.
27
+ const server = entry.slice(0, entry.lastIndexOf("__") + 2);
28
+ return tool.startsWith(entry.slice(0, -1)) && !tool.slice(server.length).includes("__");
29
+ });
30
+ }
12
31
  export function defaultProfilePath() {
13
32
  const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
14
33
  return join(base, "agent-corpus", "policy-manager", "policy.json");
@@ -55,6 +74,7 @@ export function parseProfile(text) {
55
74
  "cloudWrites",
56
75
  "humanPatterns",
57
76
  "scratchRoots",
77
+ "mcpReadOnly",
58
78
  "description",
59
79
  ]);
60
80
  for (const key of Object.keys(value))
@@ -73,6 +93,11 @@ export function parseProfile(text) {
73
93
  throw new ProfileError("humanPatterns must be short strings");
74
94
  if (!Array.isArray(roots) || roots.some((r) => typeof r !== "string" || !isAbsolute(r)))
75
95
  throw new ProfileError("scratchRoots must be absolute paths");
96
+ const mcp = value.mcpReadOnly ?? [];
97
+ if (!Array.isArray(mcp) ||
98
+ mcp.length > MAX_MCP_READ_ONLY ||
99
+ mcp.some((entry) => typeof entry !== "string" || entry.length > 128 || !MCP_ENTRY.test(entry)))
100
+ throw new ProfileError(`mcpReadOnly must list at most ${MAX_MCP_READ_ONLY} names like mcp__server__tool, optionally ending in *`);
76
101
  let humanPatterns;
77
102
  try {
78
103
  humanPatterns = patterns.map((p) => new RegExp(p));
@@ -94,6 +119,7 @@ export function parseProfile(text) {
94
119
  cloudWrites,
95
120
  humanPatterns,
96
121
  scratchRoots: value.mode === "permissive" ? [...scratchRoots] : [],
122
+ mcpReadOnly: [...new Set(mcp)],
97
123
  digest: createHash("sha256").update(text).digest("hex"),
98
124
  };
99
125
  }
@@ -0,0 +1,41 @@
1
+ import type { Request } from "./types.js";
2
+ /**
3
+ * The one directory a script deletes in when its whole effect is `rm` inside linked feature
4
+ * worktrees, or undefined. The script may hold only `rm` and inert commands, with no redirection,
5
+ * assignment, variable or substitution, and at most a leading `cd <dir>` whose list is joined by
6
+ * `&&` alone: if the cd fails nothing else runs. Every `rm` must be a worktree deletion, so one
7
+ * classifier verdict on the first cannot carry an unjudged later command.
8
+ */
9
+ export declare function deletionScriptCwd(request: Request): string | undefined;
10
+ export declare function soleEffect(request: Request): boolean;
11
+ /** A deletion operand that names a credential or protected path, as written or resolved. */
12
+ export declare function deletesProtected(cwd: string, args: string[]): boolean;
13
+ /**
14
+ * `rm` that removes only tracked content identical to HEAD (no untracked, ignored, modified or
15
+ * staged path under any operand, no submodule): "tracked". Or, without -r, also untracked files
16
+ * this session created and nothing has changed since: "session". Otherwise undefined.
17
+ */
18
+ export declare function rmRecoverable(cwd: string, args: string[]): "tracked" | "session" | undefined;
19
+ /**
20
+ * An `rm` whose every operand is a plain path inside a linked feature worktree (not the worktree
21
+ * itself, nothing protected): local file deletion the classifier may judge. Anything else that is
22
+ * destructive stays a person's decision.
23
+ */
24
+ export declare function worktreeDeletion(cwd: string, args: string[]): boolean;
25
+ /**
26
+ * `git rm -f`: the same evidence as rm, but a path already deleted from the working tree is fine,
27
+ * since only the index changes.
28
+ */
29
+ export declare function gitRmRecoverable(cwd: string, rest: string[]): boolean;
30
+ /**
31
+ * `git checkout [--] <paths>` and `git restore [-W|-SW] <paths>`: the working tree loses nothing
32
+ * when it already matches the source (index, or HEAD for --staged --worktree), or the file is only
33
+ * missing from it.
34
+ */
35
+ export declare function restoreRecoverable(cwd: string, paths: string[], fromHead: boolean): boolean;
36
+ /**
37
+ * `git reset --hard [<commit>]` with no uncommitted tracked change, every commit it drops from the
38
+ * branch still on a remote-tracking ref, and no untracked or ignored file where the target writes.
39
+ */
40
+ export declare function resetRecoverable(cwd: string, target?: string): boolean;
41
+ //# sourceMappingURL=recoverable.d.ts.map