@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/README.md +94 -29
- package/dist/adapters.d.ts +3 -1
- package/dist/adapters.js +37 -18
- package/dist/classifier.d.ts +98 -0
- package/dist/classifier.js +343 -0
- package/dist/cli.js +66 -7
- package/dist/config.d.ts +2 -0
- package/dist/config.js +6 -2
- package/dist/evidence.d.ts +1 -0
- package/dist/evidence.js +60 -0
- package/dist/flow.d.ts +4 -0
- package/dist/flow.js +68 -13
- package/dist/gitalias.d.ts +13 -0
- package/dist/gitalias.js +33 -0
- package/dist/grants.d.ts +9 -9
- package/dist/grants.js +46 -35
- package/dist/hard.d.ts +63 -0
- package/dist/hard.js +1637 -0
- package/dist/merged.d.ts +6 -0
- package/dist/merged.js +23 -0
- package/dist/nativerules.d.ts +44 -0
- package/dist/nativerules.js +653 -0
- package/dist/permissive.js +32 -6
- package/dist/policy.d.ts +12 -0
- package/dist/policy.js +228 -45
- package/dist/profile.d.ts +4 -0
- package/dist/profile.js +19 -1
- package/dist/prompt.d.ts +32 -0
- package/dist/prompt.js +334 -0
- package/dist/reads.d.ts +46 -0
- package/dist/reads.js +812 -0
- package/dist/replay.d.ts +42 -0
- package/dist/replay.js +174 -1
- package/dist/service.d.ts +12 -1
- package/dist/service.js +23 -6
- package/dist/session.d.ts +76 -13
- package/dist/session.js +373 -116
- package/dist/shellscan.d.ts +58 -0
- package/dist/shellscan.js +395 -0
- package/dist/statepaths.d.ts +41 -0
- package/dist/statepaths.js +706 -0
- package/dist/types.d.ts +9 -1
- package/package.json +1 -1
package/dist/permissive.js
CHANGED
|
@@ -2,9 +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 { aliasDirectory, gitAlias, KNOWN_GIT, shellArgs } from "./gitalias.js";
|
|
5
6
|
import { helperMatch } from "./helpers.js";
|
|
6
|
-
import { mergedEvidence, remoteTipMatches } from "./merged.js";
|
|
7
|
-
import { evaluateArgv, result } from "./policy.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";
|
|
8
10
|
import { deletesProtected, deletionScriptCwd, gitRmRecoverable, resetRecoverable, restoreRecoverable, rmRecoverable, soleEffect, worktreeDeletion, } from "./recoverable.js";
|
|
9
11
|
import { SUBSTITUTION } from "./shell.js";
|
|
10
12
|
/**
|
|
@@ -342,6 +344,11 @@ const LONG_FLAGS = {
|
|
|
342
344
|
* Over-matching only sends more to a human.
|
|
343
345
|
*/
|
|
344
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;
|
|
345
352
|
const paths = [];
|
|
346
353
|
for (const match of script.matchAll(/(?:^|[^A-Za-z\\])[eErRwW]\s*([^\n]*)/g))
|
|
347
354
|
paths.push(...(match[1] ?? "").split(/[\s;]+/).filter(Boolean));
|
|
@@ -845,7 +852,9 @@ function disposableWorktree(cwd, args, roots, fill) {
|
|
|
845
852
|
return false;
|
|
846
853
|
}
|
|
847
854
|
}
|
|
848
|
-
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) {
|
|
849
858
|
const args = argv.slice(1);
|
|
850
859
|
let index = 0;
|
|
851
860
|
let cwd = cwdForGit;
|
|
@@ -861,6 +870,21 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
|
|
|
861
870
|
}
|
|
862
871
|
const sub = args[index];
|
|
863
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
|
+
}
|
|
864
888
|
const flags = rest.filter((word) => word.startsWith("-"));
|
|
865
889
|
const positional = rest.filter((word) => !word.startsWith("-"));
|
|
866
890
|
const has = (...names) => flags.some((flag) => names.some((name) => abbreviates(flag, name)));
|
|
@@ -881,10 +905,10 @@ function gitDecision(request, argv, cwdForGit, sole, roots, fill) {
|
|
|
881
905
|
if (sub === "branch" && (has("-d", "-D", "--delete") || cluster("d") || cluster("D"))) {
|
|
882
906
|
if (has("-r", "--remotes"))
|
|
883
907
|
return ok();
|
|
884
|
-
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));
|
|
885
909
|
return unmerged.length
|
|
886
910
|
? human(request, "destructive", branchEvidence(cwd, unmerged[0] ?? ""))
|
|
887
|
-
: ok("
|
|
911
|
+
: ok("Every deleted branch is merged into origin's default branch or its tip is on a remote ref");
|
|
888
912
|
}
|
|
889
913
|
if (sub === "branch" && (has("-f", "--force") || cluster("f") || has("-M")))
|
|
890
914
|
return human(request, "destructive", "Forced branch move requires human approval");
|
|
@@ -1884,7 +1908,9 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
|
|
|
1884
1908
|
/(?:-X|--request)[=\s]?(?:DELETE|PUT)\b/i.test(joined))
|
|
1885
1909
|
return human(request, "destructive", "Destructive HTTP verbs require human approval");
|
|
1886
1910
|
if (program === "git")
|
|
1887
|
-
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));
|
|
1888
1914
|
if (program === "gh") {
|
|
1889
1915
|
const gh = ghDecision(request, argv);
|
|
1890
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 {
|
|
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
|
|
191
|
-
*
|
|
192
|
-
*
|
|
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
|
|
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
|
-
*
|
|
210
|
-
*
|
|
211
|
-
*
|
|
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 (
|
|
215
|
-
decision
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
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,
|
|
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: "
|
|
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: "
|
|
258
|
+
decision: "human",
|
|
259
|
+
cache: "none",
|
|
255
260
|
classification: "denied",
|
|
256
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 ([
|
|
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,4 @@
|
|
|
1
|
+
import { type ClassifierConfig } from "./classifier.js";
|
|
1
2
|
import { type CredentialHelper } from "./helpers.js";
|
|
2
3
|
/**
|
|
3
4
|
* A profile is policy *data*. The engine's checks (protected paths, secret retrieval, verified
|
|
@@ -28,6 +29,8 @@ export interface Profile {
|
|
|
28
29
|
};
|
|
29
30
|
/** Scripts that may read a credential for one narrow job, as committed on the default branch. */
|
|
30
31
|
credentialHelpers: CredentialHelper[];
|
|
32
|
+
/** The AI classifier each harness runs for what the engine escalates: CLI models and a kill switch. */
|
|
33
|
+
classifier: ClassifierConfig;
|
|
31
34
|
/** SHA-256 of the file the profile came from, for the audit log. */
|
|
32
35
|
digest?: string;
|
|
33
36
|
}
|
|
@@ -36,6 +39,7 @@ export declare const MAX_MCP_READ_ONLY = 200;
|
|
|
36
39
|
/** Whether `tool` is listed in the profile's `mcpReadOnly`. */
|
|
37
40
|
export declare function mcpReadOnly(profile: Profile, tool: string): boolean;
|
|
38
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). */
|
|
39
43
|
export declare function defaultProfilePath(): string;
|
|
40
44
|
export declare class ProfileError extends Error {
|
|
41
45
|
}
|
package/dist/profile.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { lstatSync, readFileSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { dirname, isAbsolute, join } from "node:path";
|
|
5
|
+
import { DEFAULT_CLASSIFIER, parseClassifierConfig } from "./classifier.js";
|
|
5
6
|
import { canonical, git } from "./evidence.js";
|
|
6
7
|
import { HelperError, parseCredentialHelpers } from "./helpers.js";
|
|
7
8
|
import { TOOL_NAME } from "./tools.js";
|
|
@@ -13,6 +14,7 @@ export const strictProfile = {
|
|
|
13
14
|
mcpReadOnly: [],
|
|
14
15
|
toolsDeny: { claude: [], codex: [], copilot: [] },
|
|
15
16
|
credentialHelpers: [],
|
|
17
|
+
classifier: DEFAULT_CLASSIFIER,
|
|
16
18
|
};
|
|
17
19
|
export const MAX_MCP_READ_ONLY = 200;
|
|
18
20
|
/**
|
|
@@ -50,9 +52,16 @@ function parseToolsDeny(raw) {
|
|
|
50
52
|
}
|
|
51
53
|
return result;
|
|
52
54
|
}
|
|
55
|
+
let profilePathMemo;
|
|
56
|
+
/** The default profile path (memoized on the variables it depends on: it is asked per word). */
|
|
53
57
|
export function defaultProfilePath() {
|
|
58
|
+
const key = `${process.env.XDG_CONFIG_HOME}|${process.env.HOME}|${process.env.USERPROFILE}`;
|
|
59
|
+
if (profilePathMemo?.key === key)
|
|
60
|
+
return profilePathMemo.path;
|
|
54
61
|
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
55
|
-
|
|
62
|
+
const path = join(base, "agent-corpus", "policy-manager", "policy.json");
|
|
63
|
+
profilePathMemo = { key, path };
|
|
64
|
+
return path;
|
|
56
65
|
}
|
|
57
66
|
export class ProfileError extends Error {
|
|
58
67
|
}
|
|
@@ -99,6 +108,7 @@ export function parseProfile(text) {
|
|
|
99
108
|
"mcpReadOnly",
|
|
100
109
|
"toolsDeny",
|
|
101
110
|
"credentialHelpers",
|
|
111
|
+
"classifier",
|
|
102
112
|
"description",
|
|
103
113
|
]);
|
|
104
114
|
for (const key of Object.keys(value))
|
|
@@ -123,6 +133,13 @@ export function parseProfile(text) {
|
|
|
123
133
|
mcp.some((entry) => typeof entry !== "string" || entry.length > 128 || !MCP_ENTRY.test(entry)))
|
|
124
134
|
throw new ProfileError(`mcpReadOnly must list at most ${MAX_MCP_READ_ONLY} names like mcp__server__tool, optionally ending in *`);
|
|
125
135
|
const toolsDeny = parseToolsDeny(value.toolsDeny);
|
|
136
|
+
let classifier;
|
|
137
|
+
try {
|
|
138
|
+
classifier = parseClassifierConfig(value.classifier);
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
throw new ProfileError(error.message);
|
|
142
|
+
}
|
|
126
143
|
let credentialHelpers;
|
|
127
144
|
try {
|
|
128
145
|
credentialHelpers = parseCredentialHelpers(value.credentialHelpers);
|
|
@@ -156,6 +173,7 @@ export function parseProfile(text) {
|
|
|
156
173
|
mcpReadOnly: [...new Set(mcp)],
|
|
157
174
|
toolsDeny,
|
|
158
175
|
credentialHelpers: value.mode === "permissive" ? credentialHelpers : [],
|
|
176
|
+
classifier,
|
|
159
177
|
digest: createHash("sha256").update(text).digest("hex"),
|
|
160
178
|
};
|
|
161
179
|
}
|
package/dist/prompt.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Request } from "./types.js";
|
|
2
|
+
/** The longest command text the classifier is shown; a longer one goes to a person. */
|
|
3
|
+
export declare const MAX_COMMAND_CHARS = 20000;
|
|
4
|
+
/** Facts about the repository a directory is in. */
|
|
5
|
+
export interface GitFacts {
|
|
6
|
+
exists: boolean;
|
|
7
|
+
repo: boolean;
|
|
8
|
+
top?: string;
|
|
9
|
+
branch?: string;
|
|
10
|
+
defaultBranch?: string;
|
|
11
|
+
/** A linked worktree, not the main checkout. */
|
|
12
|
+
linked?: boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare function gitFacts(path: string): GitFacts;
|
|
15
|
+
/** The paths a request names, as absolute paths. */
|
|
16
|
+
export declare function requestPaths(request: Request): string[];
|
|
17
|
+
/** What the classifier is shown for a request. */
|
|
18
|
+
export interface PromptInput {
|
|
19
|
+
request: Request;
|
|
20
|
+
/** The engine's reason for escalating. */
|
|
21
|
+
reason: string;
|
|
22
|
+
/** Extra absolute directories treated as session scratch (the profile's scratchRoots). */
|
|
23
|
+
scratchRoots?: string[];
|
|
24
|
+
}
|
|
25
|
+
/** The text the classifier sees as "the command": a shell command, or a tool and its target. */
|
|
26
|
+
export declare function commandText(request: Request): string;
|
|
27
|
+
/**
|
|
28
|
+
* The classification prompt, or undefined when the command is too long to classify (a person
|
|
29
|
+
* decides). Path facts are computed here; call it with the session's created files visible.
|
|
30
|
+
*/
|
|
31
|
+
export declare function buildPrompt(input: PromptInput): string | undefined;
|
|
32
|
+
//# sourceMappingURL=prompt.d.ts.map
|