@agent-corpus/policy-manager 0.4.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,8 +1,12 @@
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;
8
+ /** Self-reported confidence needed for the AI to approve an ambiguous request. */
9
+ export declare const AMBIGUOUS_CONFIDENCE = 0.95;
6
10
  export declare function evaluate(request: Request, ai?: Classification, profile?: Profile): Decision;
7
11
  export declare function evaluateArgv(request: Request, argv: string[]): Decision;
8
12
  //# sourceMappingURL=policy.d.ts.map
package/dist/policy.js CHANGED
@@ -1,12 +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
+ import { redactText } from "./redact.js";
8
+ import { CATEGORIES, } from "./types.js";
7
9
  export function hash(value) {
8
10
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
9
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
+ }
10
21
  // Deliberately accepts one simple command. Shell syntax and expansions need human review.
11
22
  export function words(command) {
12
23
  if (!command || /[\r\n\0]/.test(command))
@@ -167,25 +178,88 @@ export function result(request, category, reason, approve = false) {
167
178
  decision: approve ? "approve" : "human",
168
179
  category,
169
180
  reason,
170
- requestHash: hash(request),
181
+ requestHash: requestHash(request),
171
182
  cache: approve && category === "cloud-read" ? "session" : "none",
172
183
  cached: false,
173
184
  };
174
185
  }
186
+ /** Self-reported confidence needed for the AI to approve an ambiguous request. */
187
+ export const AMBIGUOUS_CONFIDENCE = 0.95;
188
+ /**
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.
194
+ */
195
+ const HUMAN_BOUNDARIES = [
196
+ /^Incomplete request/,
197
+ /^Invalid tool input/,
198
+ /^Execution directory differs/,
199
+ /^Unrecognized patch format/,
200
+ /^Patch has no verified target paths/,
201
+ /^Environment override requires human review/,
202
+ /^Custom execution environment requires human review/,
203
+ /^Matches an organization human-approval pattern/,
204
+ /^Write requires a linked worktree on a feature branch/,
205
+ /^Cloud operation is outside the verified inspection catalog/,
206
+ ];
207
+ /**
208
+ * Under the permissive profile, every escalation that is not a boundary is ambiguous: the
209
+ * deterministic engine cannot decide it, so the session's AI classifier does. Strict mode is
210
+ * unchanged.
211
+ */
212
+ function markAmbiguous(decision, profile) {
213
+ if (profile.mode !== "permissive" ||
214
+ decision.decision !== "human" ||
215
+ decision.needsClassification ||
216
+ decision.category === "sensitive" ||
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) ||
220
+ HUMAN_BOUNDARIES.some((pattern) => pattern.test(decision.reason)))
221
+ return decision;
222
+ return { ...decision, needsClassification: true, tier: "ambiguous" };
223
+ }
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;
228
+ const safe = ai.recoverable === true &&
229
+ ai.confidence >= AMBIGUOUS_CONFIDENCE &&
230
+ destructiveOk &&
231
+ !["sensitive", "unknown"].includes(ai.category);
232
+ const base = { ...decision, needsClassification: false, cache: "session", ai };
233
+ if (safe)
234
+ return {
235
+ ...base,
236
+ decision: "approve",
237
+ category: ai.category,
238
+ classification: "approved",
239
+ reason: "Ambiguous request judged recoverable and non-sensitive by the same-session AI",
240
+ };
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
+ };
251
+ return {
252
+ ...base,
253
+ decision: "deny",
254
+ classification: "denied",
255
+ 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.`,
256
+ };
257
+ }
175
258
  export function evaluate(request, ai, profile = strictProfile) {
176
- const decision = evaluateCore(request, profile);
259
+ const decision = markAmbiguous(evaluateCore(request, profile), profile);
177
260
  if (ai) {
178
261
  // Self-reported confidence is not a probability or a substitute for verified effects.
179
- if (![
180
- "code-read",
181
- "worktree-write",
182
- "cloud-read",
183
- "git-read",
184
- "impactful-write",
185
- "destructive",
186
- "sensitive",
187
- "unknown",
188
- ].includes(ai.category) ||
262
+ if (!CATEGORIES.includes(ai.category) ||
189
263
  ai.requestHash !== decision.requestHash ||
190
264
  !Number.isFinite(ai.confidence) ||
191
265
  ai.confidence < 0 ||
@@ -197,6 +271,8 @@ export function evaluate(request, ai, profile = strictProfile) {
197
271
  reason: "Invalid or mismatched AI classification",
198
272
  };
199
273
  decision.ai = ai;
274
+ if (decision.tier === "ambiguous")
275
+ return resolveAmbiguous(decision, ai);
200
276
  if (decision.category === "cloud-read" &&
201
277
  decision.needsClassification === true &&
202
278
  ai.category === "cloud-read" &&
@@ -231,6 +307,14 @@ function evaluateCore(request, profile) {
231
307
  const input = request.input;
232
308
  if (!input || typeof input !== "object" || Array.isArray(input))
233
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
+ };
234
318
  const cwd = input.workdir ?? input.cwd ?? request.cwd;
235
319
  if (typeof cwd !== "string" || cwd !== request.cwd)
236
320
  return result(request, "unknown", "Execution directory differs from the reviewed directory");
@@ -279,6 +363,25 @@ function evaluateCore(request, profile) {
279
363
  return result(request, "unknown", "Unsupported shell syntax; no AI classification was performed for this request, so a human decision is required");
280
364
  return evaluateArgv(request, argv);
281
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
+ }
282
385
  export function evaluateArgv(request, argv) {
283
386
  const [program, ...args] = argv;
284
387
  let gitCwd = request.cwd;
@@ -316,23 +419,22 @@ export function evaluateArgv(request, argv) {
316
419
  return result(request, "unknown", "Cannot verify Git fetch target");
317
420
  }
318
421
  }
319
- if (args.length === 7 &&
320
- args[0] === "worktree" &&
321
- args[1] === "add" &&
322
- args[2] === "--no-track" &&
323
- args[4] === "-b" &&
324
- args[6] === "origin/main") {
422
+ const add = worktreeAddForm(args);
423
+ if (add) {
325
424
  try {
326
- const root = canonical(git(gitCwd, ["rev-parse", "--show-toplevel"]));
327
- const target = canonical(resolve(gitCwd, args[3] ?? ""));
328
- const branch = args[5] ?? "";
329
- git(gitCwd, ["check-ref-format", "--branch", branch]);
330
- git(gitCwd, ["rev-parse", "--verify", "origin/main^{commit}"]);
331
- 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) &&
332
435
  !existsSync(target) &&
333
- inside(resolve(root, ".worktrees"), target) &&
334
- target !== resolve(root, ".worktrees"))
335
- 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);
336
438
  }
337
439
  catch {
338
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