@odingard/guardian-hook 0.3.0 → 0.4.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/index.js CHANGED
@@ -2,6 +2,461 @@
2
2
 
3
3
  // src/classify.ts
4
4
  import { createHash } from "node:crypto";
5
+ import {
6
+ CONTENT_PIN_INVALID_ARGUMENT,
7
+ CONTENT_PIN_KEY,
8
+ pinFile
9
+ } from "@odingard/guardian-sdk";
10
+
11
+ // src/shell.ts
12
+ var MAX_NESTING = 16;
13
+ var isBlank = (c) => c === " " || c === " ";
14
+ var OPERATOR_START = /* @__PURE__ */ new Set([";", "&", "|", "\n", "(", ")", "<", ">"]);
15
+ function parseShell(src) {
16
+ const st = {
17
+ src,
18
+ pos: 0,
19
+ ambiguous: false,
20
+ nesting: 0,
21
+ heredocs: [],
22
+ bodySubs: []
23
+ };
24
+ const parsed = parseList(st, false);
25
+ if (st.pos < src.length) st.ambiguous = true;
26
+ if (st.bodySubs.length > 0) {
27
+ parsed.commands.push(bodyCommand(st.bodySubs));
28
+ }
29
+ return {
30
+ commands: parsed.commands,
31
+ ambiguous: st.ambiguous || parsed.ambiguous
32
+ };
33
+ }
34
+ function bodyCommand(subs) {
35
+ return { words: [], writes: [], pipeline: -1, stage: 0, subs };
36
+ }
37
+ function parseList(st, inSub) {
38
+ const commands = [];
39
+ let pipeline = 0;
40
+ let stage = 0;
41
+ let words = [];
42
+ let writes = [];
43
+ let depth = 0;
44
+ let pendingWrite = false;
45
+ let pendingHeredoc = null;
46
+ let pendingHereString = false;
47
+ const endCommand = (nextIsPipe) => {
48
+ if (words.length > 0 || writes.length > 0) {
49
+ commands.push({ words, writes, pipeline, stage, subs: [] });
50
+ }
51
+ words = [];
52
+ writes = [];
53
+ if (nextIsPipe) stage++;
54
+ else {
55
+ pipeline++;
56
+ stage = 0;
57
+ }
58
+ };
59
+ const { src } = st;
60
+ while (st.pos < src.length) {
61
+ const c = src[st.pos];
62
+ if (isBlank(c)) {
63
+ st.pos++;
64
+ continue;
65
+ }
66
+ if (c === "\\" && src[st.pos + 1] === "\n") {
67
+ st.pos += 2;
68
+ continue;
69
+ }
70
+ if (c === "#") {
71
+ while (st.pos < src.length && src[st.pos] !== "\n") st.pos++;
72
+ continue;
73
+ }
74
+ if (c === "\n") {
75
+ st.pos++;
76
+ endCommand(false);
77
+ readHeredocBodies(st);
78
+ continue;
79
+ }
80
+ if (c === ";" || c === "&" || c === "|") {
81
+ const two = src.slice(st.pos, st.pos + 2);
82
+ if (c === "&" && src[st.pos + 1] === ">") {
83
+ st.pos += src[st.pos + 2] === ">" ? 3 : 2;
84
+ pendingWrite = true;
85
+ continue;
86
+ }
87
+ if (two === "&&" || two === "||" || two === ";;" || two === "|&") {
88
+ st.pos += 2;
89
+ endCommand(two === "|&");
90
+ continue;
91
+ }
92
+ st.pos++;
93
+ endCommand(c === "|");
94
+ continue;
95
+ }
96
+ if (c === "(") {
97
+ st.pos++;
98
+ depth++;
99
+ endCommand(false);
100
+ continue;
101
+ }
102
+ if (c === ")") {
103
+ if (depth > 0) {
104
+ st.pos++;
105
+ depth--;
106
+ endCommand(false);
107
+ continue;
108
+ }
109
+ if (inSub) {
110
+ endCommand(false);
111
+ return { commands, ambiguous: false };
112
+ }
113
+ st.pos++;
114
+ st.ambiguous = true;
115
+ endCommand(false);
116
+ continue;
117
+ }
118
+ if (c === "<" || c === ">") {
119
+ if (src[st.pos + 1] === "(") {
120
+ const w2 = readWord(st);
121
+ if (w2) addWord(w2);
122
+ continue;
123
+ }
124
+ const op = /^(<<<|<<-|<<|<>|<&|>>|>&|>\||<|>)/.exec(src.slice(st.pos))[0];
125
+ st.pos += op.length;
126
+ if (op === "<<" || op === "<<-") pendingHeredoc = { stripTabs: op === "<<-" };
127
+ else if (op === "<<<") pendingHereString = true;
128
+ else if (op === ">&" || op === "<&") {
129
+ const m = /^[ \t]*([0-9]+|-)(?=[\s;&|)<>]|$)/.exec(src.slice(st.pos));
130
+ if (m) st.pos += m[0].length;
131
+ else if (op === ">&") pendingWrite = true;
132
+ } else if (op !== "<") pendingWrite = true;
133
+ continue;
134
+ }
135
+ const w = readWord(st);
136
+ if (!w) continue;
137
+ addWord(w);
138
+ }
139
+ if (inSub) st.ambiguous = true;
140
+ if (depth > 0) st.ambiguous = true;
141
+ endCommand(false);
142
+ return { commands, ambiguous: false };
143
+ function addWord(w) {
144
+ if (pendingHeredoc) {
145
+ st.heredocs.push({
146
+ delimiter: w.value,
147
+ stripTabs: pendingHeredoc.stripTabs,
148
+ quoted: w.quoted
149
+ });
150
+ pendingHeredoc = null;
151
+ return;
152
+ }
153
+ if (pendingHereString) {
154
+ pendingHereString = false;
155
+ collectSubs(w);
156
+ return;
157
+ }
158
+ if (pendingWrite) {
159
+ pendingWrite = false;
160
+ writes.push(w);
161
+ return;
162
+ }
163
+ const next = src[st.pos];
164
+ if (/^[0-9]+$/.test(w.value) && !w.quoted && (next === ">" || next === "<")) {
165
+ return;
166
+ }
167
+ words.push(w);
168
+ }
169
+ function collectSubs(w) {
170
+ if (w.subs.length > 0) {
171
+ commands.push({ words: [], writes: [], pipeline: -1, stage: 0, subs: w.subs });
172
+ }
173
+ }
174
+ }
175
+ function readHeredocBodies(st) {
176
+ while (st.heredocs.length > 0) {
177
+ const doc = st.heredocs.shift();
178
+ const lines = [];
179
+ let found = false;
180
+ while (st.pos < st.src.length) {
181
+ let end = st.src.indexOf("\n", st.pos);
182
+ if (end < 0) end = st.src.length;
183
+ const raw = st.src.slice(st.pos, end);
184
+ st.pos = Math.min(end + 1, st.src.length);
185
+ const line = doc.stripTabs ? raw.replace(/^\t+/, "") : raw;
186
+ if (line === doc.delimiter) {
187
+ found = true;
188
+ break;
189
+ }
190
+ lines.push(raw);
191
+ }
192
+ void found;
193
+ if (!doc.quoted) {
194
+ const body = lines.join("\n");
195
+ if (/\$\(|`/.test(body)) {
196
+ const inner = { ...st, src: body, pos: 0, heredocs: [], bodySubs: [] };
197
+ const w = readDoubleQuotedBody(inner);
198
+ st.ambiguous ||= inner.ambiguous;
199
+ if (w.subs.length > 0) st.bodySubs.push(...w.subs);
200
+ }
201
+ }
202
+ }
203
+ }
204
+ function readDoubleQuotedBody(st) {
205
+ const word = { value: "", dynamic: false, subs: [] };
206
+ while (st.pos < st.src.length) {
207
+ const c = st.src[st.pos];
208
+ if (c === "\\") {
209
+ st.pos += 2;
210
+ continue;
211
+ }
212
+ if (c === "$" || c === "`") {
213
+ readExpansion(st, word);
214
+ continue;
215
+ }
216
+ st.pos++;
217
+ }
218
+ return word;
219
+ }
220
+ function readWord(st) {
221
+ const { src } = st;
222
+ const word = {
223
+ value: "",
224
+ dynamic: false,
225
+ subs: [],
226
+ quoted: false
227
+ };
228
+ const start = st.pos;
229
+ while (st.pos < src.length) {
230
+ const c = src[st.pos];
231
+ if (isBlank(c) || c === "\n") break;
232
+ if ((c === "<" || c === ">") && src[st.pos + 1] === "(") {
233
+ st.pos += 2;
234
+ word.dynamic = true;
235
+ word.subs.push(parseNested(st));
236
+ continue;
237
+ }
238
+ if (OPERATOR_START.has(c)) break;
239
+ if (c === "\\") {
240
+ if (st.pos + 1 < src.length) {
241
+ if (src[st.pos + 1] !== "\n") word.value += src[st.pos + 1];
242
+ st.pos += 2;
243
+ } else {
244
+ st.pos++;
245
+ }
246
+ word.quoted = true;
247
+ continue;
248
+ }
249
+ if (c === "'") {
250
+ const end = src.indexOf("'", st.pos + 1);
251
+ if (end < 0) {
252
+ st.ambiguous = true;
253
+ word.value += src.slice(st.pos + 1);
254
+ st.pos = src.length;
255
+ break;
256
+ }
257
+ word.value += src.slice(st.pos + 1, end);
258
+ st.pos = end + 1;
259
+ word.quoted = true;
260
+ continue;
261
+ }
262
+ if (c === '"') {
263
+ st.pos++;
264
+ word.quoted = true;
265
+ let closed = false;
266
+ while (st.pos < src.length) {
267
+ const d = src[st.pos];
268
+ if (d === '"') {
269
+ st.pos++;
270
+ closed = true;
271
+ break;
272
+ }
273
+ if (d === "\\") {
274
+ const n = src[st.pos + 1];
275
+ if (n === void 0) {
276
+ st.pos++;
277
+ continue;
278
+ }
279
+ if ('$`"\\\n'.includes(n)) {
280
+ if (n !== "\n") word.value += n;
281
+ } else {
282
+ word.value += d + n;
283
+ }
284
+ st.pos += 2;
285
+ continue;
286
+ }
287
+ if (d === "$" || d === "`") {
288
+ readExpansion(st, word);
289
+ continue;
290
+ }
291
+ word.value += d;
292
+ st.pos++;
293
+ }
294
+ if (!closed) st.ambiguous = true;
295
+ continue;
296
+ }
297
+ if (c === "$" && src[st.pos + 1] === "'") {
298
+ let i = st.pos + 2;
299
+ let out = "";
300
+ let closed = false;
301
+ while (i < src.length) {
302
+ const d = src[i];
303
+ if (d === "'") {
304
+ closed = true;
305
+ i++;
306
+ break;
307
+ }
308
+ if (d === "\\" && i + 1 < src.length) {
309
+ const n = src[i + 1];
310
+ const simple = { n: "\n", t: " ", "\\": "\\", "'": "'", '"': '"' };
311
+ if (simple[n] !== void 0) {
312
+ out += simple[n];
313
+ i += 2;
314
+ continue;
315
+ }
316
+ const hex = /^x([0-9a-fA-F]{1,2})/.exec(src.slice(i + 1));
317
+ if (hex) {
318
+ out += String.fromCharCode(parseInt(hex[1], 16));
319
+ i += 1 + hex[0].length;
320
+ continue;
321
+ }
322
+ const oct = /^([0-7]{1,3})/.exec(src.slice(i + 1));
323
+ if (oct) {
324
+ out += String.fromCharCode(parseInt(oct[1], 8));
325
+ i += 1 + oct[0].length;
326
+ continue;
327
+ }
328
+ st.ambiguous = true;
329
+ out += n;
330
+ i += 2;
331
+ continue;
332
+ }
333
+ out += d;
334
+ i++;
335
+ }
336
+ if (!closed) st.ambiguous = true;
337
+ word.value += out;
338
+ word.quoted = true;
339
+ st.pos = i;
340
+ continue;
341
+ }
342
+ if (c === "$" || c === "`") {
343
+ readExpansion(st, word);
344
+ continue;
345
+ }
346
+ word.value += c;
347
+ st.pos++;
348
+ }
349
+ return st.pos > start ? word : null;
350
+ }
351
+ function readExpansion(st, word) {
352
+ const { src } = st;
353
+ const c = src[st.pos];
354
+ if (c === "`") {
355
+ let i = st.pos + 1;
356
+ let inner = "";
357
+ while (i < src.length && src[i] !== "`") {
358
+ if (src[i] === "\\" && i + 1 < src.length) {
359
+ inner += src[i + 1];
360
+ i += 2;
361
+ continue;
362
+ }
363
+ inner += src[i];
364
+ i++;
365
+ }
366
+ if (i >= src.length) st.ambiguous = true;
367
+ word.value += "`" + inner + "`";
368
+ word.dynamic = true;
369
+ word.subs.push(parseString(st, inner));
370
+ st.pos = Math.min(i + 1, src.length);
371
+ return;
372
+ }
373
+ const n = src[st.pos + 1];
374
+ if (n === "(" && src[st.pos + 2] === "(") {
375
+ let i = st.pos + 3;
376
+ let level = 2;
377
+ while (i < src.length && level > 0) {
378
+ if (src[i] === "(") level++;
379
+ else if (src[i] === ")") level--;
380
+ i++;
381
+ }
382
+ if (level > 0) st.ambiguous = true;
383
+ word.value += src.slice(st.pos, i);
384
+ word.dynamic = true;
385
+ st.pos = i;
386
+ return;
387
+ }
388
+ if (n === "(") {
389
+ const start = st.pos;
390
+ st.pos += 2;
391
+ word.subs.push(parseNested(st));
392
+ word.value += src.slice(start, st.pos);
393
+ word.dynamic = true;
394
+ return;
395
+ }
396
+ if (n === "{") {
397
+ let i = st.pos + 2;
398
+ let level = 1;
399
+ while (i < src.length && level > 0) {
400
+ if (src[i] === "{") level++;
401
+ else if (src[i] === "}") level--;
402
+ i++;
403
+ }
404
+ if (level > 0) st.ambiguous = true;
405
+ const text = src.slice(st.pos, i);
406
+ word.value += text;
407
+ word.dynamic = true;
408
+ if (/\$\(|`/.test(text)) {
409
+ word.subs.push(parseString(st, text.slice(2, -1)));
410
+ }
411
+ st.pos = i;
412
+ return;
413
+ }
414
+ const name = /^\$([A-Za-z_][A-Za-z0-9_]*|[0-9@*#?$!-])/.exec(src.slice(st.pos));
415
+ if (name) {
416
+ word.value += name[0];
417
+ word.dynamic = true;
418
+ st.pos += name[0].length;
419
+ return;
420
+ }
421
+ word.value += "$";
422
+ st.pos++;
423
+ }
424
+ function parseNested(st) {
425
+ if (st.nesting >= MAX_NESTING) {
426
+ st.ambiguous = true;
427
+ st.pos = st.src.length;
428
+ return { commands: [], ambiguous: true };
429
+ }
430
+ st.nesting++;
431
+ const savedHeredocs = st.heredocs;
432
+ st.heredocs = [];
433
+ const inner = parseList(st, true);
434
+ st.heredocs = savedHeredocs;
435
+ st.nesting--;
436
+ if (st.src[st.pos] === ")") st.pos++;
437
+ else st.ambiguous = true;
438
+ return inner;
439
+ }
440
+ function parseString(st, text) {
441
+ if (st.nesting >= MAX_NESTING) {
442
+ st.ambiguous = true;
443
+ return { commands: [], ambiguous: true };
444
+ }
445
+ const inner = {
446
+ src: text,
447
+ pos: 0,
448
+ ambiguous: false,
449
+ nesting: st.nesting + 1,
450
+ heredocs: [],
451
+ bodySubs: []
452
+ };
453
+ const parsed = parseList(inner, false);
454
+ if (inner.bodySubs.length) parsed.commands.push(bodyCommand(inner.bodySubs));
455
+ st.ambiguous ||= inner.ambiguous;
456
+ return { commands: parsed.commands, ambiguous: inner.ambiguous };
457
+ }
458
+
459
+ // src/classify.ts
5
460
  var HOOK_TOOLS = [
6
461
  {
7
462
  name: "shell",
@@ -16,7 +471,7 @@ var HOOK_TOOLS = [
16
471
  {
17
472
  name: "shell_destructive",
18
473
  suggestedMode: "ask",
19
- description: "Destructive commands: rm -rf, git reset --hard, git clean, force pushes, dropping databases, disk formatting."
474
+ description: "Destructive commands: rm -rf (also through xargs or find -exec), git reset --hard, git clean, force pushes and remote branch deletes, dropping databases, disk formatting, piping a download into a shell. Also changes to the agent's own MCP servers, hooks or permissions (claude mcp add, writes to .mcp.json or .claude/settings.json), and commands the hook cannot parse."
20
475
  },
21
476
  {
22
477
  name: "git_push",
@@ -67,6 +522,9 @@ var DESTRUCTIVE = [
67
522
  /\b(drop|truncate)\s+(table|database|schema)\b/i,
68
523
  /\bdelete\s+from\s+\w+\s*(;|$)/i,
69
524
  /\b(mkfs|dd\s+if=|shred|wipefs)\b/,
525
+ /\bdd\b.*\bof=/,
526
+ /\brsync\b.*\s--(delete\S*|remove-source-files)\b/,
527
+ /\btruncate\b.*(\s-s\s*0\b|\s--size[= ]0\b)/,
70
528
  /\bchmod\s+-R\s+777\b/,
71
529
  /\bfind\b.*\s-delete\b/
72
530
  ];
@@ -162,12 +620,599 @@ function startsInteractiveSession(command) {
162
620
  if (/\bwhile\s+(?:IFS=\S*\s+)?read\b/.test(command)) return true;
163
621
  return command.split(/&&|\|\||[;&|\n()]|\$\(|`/).some((segment) => startsSession(segment));
164
622
  }
623
+ var RANK = {
624
+ shell: 0,
625
+ shell_session: 1,
626
+ git_push: 2,
627
+ shell_deploy: 3,
628
+ shell_destructive: 4
629
+ };
630
+ var BY_RANK = [
631
+ "shell",
632
+ "shell_session",
633
+ "git_push",
634
+ "shell_deploy",
635
+ "shell_destructive"
636
+ ];
637
+ var ASK = RANK.shell_destructive;
638
+ var MAX_DEPTH = 12;
639
+ var EDGE = String.raw`(?:^|[\s/\\'"=:,(~])`;
640
+ var AGENT_CONFIG_PATH = new RegExp(
641
+ [
642
+ EDGE + String.raw`(?:\.?mcp\.json|\.claude\.json|settings\.local\.json|managed-settings\.json|managed-mcp\.json|claude_desktop_config\.json|guardian-hooks\.json|cordis\.patch\.ya?ml)(?![\w-])`,
643
+ EDGE + String.raw`\.claude(?:[/\\](?:settings[^/\\\s'"]*\.json|hooks|agents|commands|skills|plugins|output-styles)(?![\w-])|[/\\]?(?=$|[\s'"]))`,
644
+ EDGE + String.raw`\.(?:codex|cursor|gemini|dsh)(?=$|[/\\\s'"])`
645
+ ].join("|"),
646
+ "i"
647
+ );
648
+ var READERS = new Set(
649
+ "cat tac less more head tail grep egrep fgrep zgrep rg ag ack ls dir stat file wc diff cmp comm jq bat batcat md5sum sha1sum sha256sum sha512sum shasum b2sum cksum echo printf test [ [[ find fd realpath readlink dirname basename du tree type which".split(" ")
650
+ );
651
+ var GIT_READS = new Set(
652
+ "status log show diff blame ls-files grep add commit check-ignore cat-file rev-parse ls-tree shortlog describe".split(" ")
653
+ );
654
+ var RESERVED = new Set(
655
+ "if then else elif fi do done while until for in case esac ! { } select function".split(
656
+ " "
657
+ )
658
+ );
659
+ var ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])?\+?=/;
660
+ var SHELLS = new Set(
661
+ "sh bash zsh dash ksh mksh ash yash posh fish busybox".split(" ")
662
+ );
663
+ var FETCHERS = new Set(
664
+ "curl wget fetch http https xh aria2c iwr irm invoke-webrequest invoke-restmethod".split(
665
+ " "
666
+ )
667
+ );
668
+ var BULK_DELETE = /* @__PURE__ */ new Set(["rm", "unlink", "shred"]);
669
+ var EVALUATORS = /* @__PURE__ */ new Set(["eval", "source", ".", "iex", "invoke-expression"]);
670
+ var WRAPPER_SPECS = {
671
+ nohup: {},
672
+ command: {},
673
+ builtin: {},
674
+ chronic: {},
675
+ unbuffer: {},
676
+ busybox: {},
677
+ time: { value: ["-f", "-o", "--format", "--output"] },
678
+ nice: { value: ["-n", "--adjustment"] },
679
+ ionice: { value: ["-c", "-n", "-p", "-P", "-u", "--class", "--classdata"] },
680
+ stdbuf: { value: ["-i", "-o", "-e", "--input", "--output", "--error"] },
681
+ timeout: { value: ["-s", "-k", "--signal", "--kill-after"], positional: 1 },
682
+ exec: { value: ["-a"] },
683
+ sudo: {
684
+ value: [
685
+ ...SUDO_VALUE_OPTS,
686
+ "--user",
687
+ "--group",
688
+ "--host",
689
+ "--prompt",
690
+ "--chdir",
691
+ "--role",
692
+ "--type",
693
+ "--close-from",
694
+ "--other-user",
695
+ "--command-timeout"
696
+ ]
697
+ },
698
+ doas: { value: ["-u", "-C"] },
699
+ xargs: {
700
+ value: [
701
+ "-a",
702
+ "--arg-file",
703
+ "-d",
704
+ "--delimiter",
705
+ "-E",
706
+ "-I",
707
+ "-L",
708
+ "-n",
709
+ "--max-args",
710
+ "-P",
711
+ "--max-procs",
712
+ "-s",
713
+ "--max-chars",
714
+ "--process-slot-var",
715
+ "--max-lines"
716
+ ]
717
+ },
718
+ chroot: { value: ["--userspec", "--groups"], positional: 1 },
719
+ taskset: { positional: 1 },
720
+ flock: {
721
+ value: ["-w", "-E", "--timeout", "--conflict-exit-code"],
722
+ positional: 1
723
+ },
724
+ setsid: {},
725
+ caffeinate: { value: ["-t", "-w"] }
726
+ };
727
+ var leaf = (rank, base = "", args = []) => ({
728
+ rank,
729
+ base,
730
+ args
731
+ });
732
+ function baseName(value) {
733
+ return (value.split(/[\\/]/).pop() ?? "").toLowerCase().replace(/\.exe$/, "");
734
+ }
735
+ var literal = (value) => ({ value, dynamic: false, subs: [] });
736
+ function skipOptions(args, spec) {
737
+ const value = new Set(spec.value ?? []);
738
+ let i = 0;
739
+ let unknown = false;
740
+ while (i < args.length) {
741
+ const a = args[i].value;
742
+ if (a === "--") {
743
+ i++;
744
+ break;
745
+ }
746
+ if (a.startsWith("--")) {
747
+ if (a.includes("=")) i++;
748
+ else if (value.has(a)) i += 2;
749
+ else {
750
+ unknown = true;
751
+ i++;
752
+ }
753
+ continue;
754
+ }
755
+ if (a.startsWith("-") && a.length > 1) {
756
+ let takes = false;
757
+ for (let k = 1; k < a.length; k++) {
758
+ if (value.has(`-${a[k]}`)) {
759
+ takes = k === a.length - 1;
760
+ break;
761
+ }
762
+ }
763
+ i += takes ? 2 : 1;
764
+ continue;
765
+ }
766
+ break;
767
+ }
768
+ let positional = spec.positional ?? 0;
769
+ while (positional-- > 0 && i < args.length) i++;
770
+ return { start: i, unknown };
771
+ }
772
+ function rankText(text, depth) {
773
+ if (depth > MAX_DEPTH) return ASK;
774
+ return rankParsed(parseShell(text), depth + 1);
775
+ }
776
+ function rankParsed(parsed, depth) {
777
+ if (depth > MAX_DEPTH) return ASK;
778
+ let rank = parsed.ambiguous ? ASK : 0;
779
+ const stages = /* @__PURE__ */ new Map();
780
+ for (const cmd of parsed.commands) {
781
+ const l = rankArgv(cmd.words, depth);
782
+ rank = Math.max(rank, l.rank);
783
+ if (cmd.writes.some((w) => AGENT_CONFIG_PATH.test(w.value))) rank = ASK;
784
+ const subs = [
785
+ ...cmd.subs,
786
+ ...cmd.words.flatMap((w) => w.subs),
787
+ ...cmd.writes.flatMap((w) => w.subs)
788
+ ];
789
+ for (const sub of subs) rank = Math.max(rank, rankParsed(sub, depth + 1));
790
+ if (runsCode(l) && cmd.words.some((w) => w.subs.some((s) => fetches(s, depth + 1)))) {
791
+ rank = ASK;
792
+ }
793
+ if (cmd.pipeline >= 0) {
794
+ const list = stages.get(cmd.pipeline) ?? [];
795
+ list.push(l);
796
+ stages.set(cmd.pipeline, list);
797
+ }
798
+ }
799
+ for (const list of stages.values()) {
800
+ const first = list.findIndex((l) => FETCHERS.has(l.base));
801
+ if (first >= 0 && list.slice(first + 1).some((l) => readsCodeFromStdin(l))) {
802
+ rank = ASK;
803
+ }
804
+ }
805
+ return rank;
806
+ }
807
+ function fetches(parsed, depth) {
808
+ return parsed.commands.some(
809
+ (c) => FETCHERS.has(rankArgv(c.words, depth).base) || [...c.subs, ...c.words.flatMap((w) => w.subs)].some(
810
+ (s) => fetches(s, depth + 1)
811
+ )
812
+ );
813
+ }
814
+ var isInterpreter = (base) => INTERPRETERS.has(base) || /^python[0-9.]*$/.test(base);
815
+ function runsCode(l) {
816
+ return EVALUATORS.has(l.base) || isInterpreter(l.base);
817
+ }
818
+ function readsCodeFromStdin(l) {
819
+ if (EVALUATORS.has(l.base)) return true;
820
+ if (!isInterpreter(l.base)) return false;
821
+ const options = [];
822
+ let script = false;
823
+ for (const a of l.args) {
824
+ if (a === "--") break;
825
+ if (a === "-") return true;
826
+ if (a.startsWith("-") || a.startsWith("+")) options.push(a);
827
+ else {
828
+ script = true;
829
+ break;
830
+ }
831
+ }
832
+ if (options.some((a) => /^-[a-zA-Z]*s[a-zA-Z]*$/.test(a))) return true;
833
+ if (options.some((a) => /^-[a-zA-Z]*[cem][a-zA-Z]*$/.test(a))) return false;
834
+ return !script;
835
+ }
836
+ function rankArgv(words, depth) {
837
+ if (depth > MAX_DEPTH) return leaf(ASK);
838
+ let i = 0;
839
+ while (i < words.length && (ASSIGNMENT.test(words[i].value) || RESERVED.has(words[i].value))) {
840
+ i++;
841
+ }
842
+ if (i >= words.length) return leaf(0);
843
+ const head = words[i];
844
+ const argWords = words.slice(i + 1);
845
+ if (head.dynamic) return leaf(ASK);
846
+ const base = baseName(head.value);
847
+ const args = argWords.map((w) => w.value);
848
+ const joined = [base, ...args].join(" ");
849
+ let rank = 0;
850
+ if (DESTRUCTIVE.some((re) => re.test(joined))) rank = ASK;
851
+ else if (DEPLOY.some((re) => re.test(joined))) rank = RANK.shell_deploy;
852
+ const done = (r, b = base, a = args) => leaf(Math.max(rank, r), b, a);
853
+ const inner = (from) => rankArgv(from, depth + 1);
854
+ const pathCheck = (values) => values.some((v) => AGENT_CONFIG_PATH.test(v)) ? ASK : 0;
855
+ if (base === "env") return done(rankEnv(argWords, depth));
856
+ if (base === "sudoedit") return done(pathCheck(args));
857
+ if (Object.hasOwn(WRAPPER_SPECS, base)) {
858
+ if (base === "sudo" && args.some((a) => /^-[a-zA-Z]*e[a-zA-Z]*$/.test(a))) {
859
+ return done(pathCheck(args));
860
+ }
861
+ if (base === "command" && args.some((a) => /^-[a-zA-Z]*[vV]/.test(a))) {
862
+ return done(0);
863
+ }
864
+ if (base === "flock") {
865
+ const c = args.findIndex((a) => a === "-c" || a === "--command");
866
+ if (c >= 0) return done(rankText(args[c + 1] ?? "", depth));
867
+ }
868
+ const { start, unknown } = skipOptions(argWords, WRAPPER_SPECS[base]);
869
+ let rest = argWords.slice(start);
870
+ if (base === "xargs" && rest.length === 0) rest = [literal("echo")];
871
+ const l = inner(rest);
872
+ if (base === "xargs" && BULK_DELETE.has(l.base)) l.rank = ASK;
873
+ const alt = unknown ? inner(argWords.slice(start + 1)).rank : 0;
874
+ return leaf(Math.max(rank, l.rank, alt), l.base, l.args);
875
+ }
876
+ if (base === "watch") {
877
+ const { start } = skipOptions(argWords, {
878
+ value: ["-n", "--interval", "-d", "-q", "--equexit"]
879
+ });
880
+ return done(rankText(args.slice(start).join(" "), depth));
881
+ }
882
+ if (SHELLS.has(base)) {
883
+ return done(rankShell(base, argWords, depth));
884
+ }
885
+ if (base === "su") {
886
+ const c = args.findIndex((a) => /^(-c|--command)$/.test(a));
887
+ const eq = args.find((a) => a.startsWith("--command="));
888
+ if (c >= 0) return done(rankText(args[c + 1] ?? "", depth));
889
+ if (eq) return done(rankText(eq.slice("--command=".length), depth));
890
+ return done(0);
891
+ }
892
+ if (base === "eval" || base === "iex" || base === "invoke-expression") {
893
+ return done(rankText(args.join(" "), depth));
894
+ }
895
+ if (base === "find") return done(rankFind(argWords, depth));
896
+ if (["npx", "bunx", "pnpx", "npm", "pnpm", "yarn"].includes(base)) {
897
+ const l = rankRunner(base, argWords, depth);
898
+ if (l) return leaf(Math.max(rank, l.rank), l.base, l.args);
899
+ return done(0);
900
+ }
901
+ if (base === "rm") {
902
+ const recursive = argsBeforeDashDash(args).some(
903
+ (a) => a === "--recursive" || /^-[a-zA-Z]*[rR]/.test(a)
904
+ );
905
+ return done(Math.max(recursive ? ASK : 0, pathCheck(args)));
906
+ }
907
+ if (base === "chmod") return done(Math.max(rankChmod(args), pathCheck(args)));
908
+ if (base === "git") return done(rankGit(argWords, depth));
909
+ if (base === "claude" || base === "codex" || base === "gemini") {
910
+ return done(rankAgentCli(base, args));
911
+ }
912
+ if (READERS.has(base)) return done(0);
913
+ return done(pathCheck(args));
914
+ }
915
+ function argsBeforeDashDash(args) {
916
+ const end = args.indexOf("--");
917
+ return end < 0 ? args : args.slice(0, end);
918
+ }
919
+ function rankEnv(argWords, depth) {
920
+ let i = 0;
921
+ while (i < argWords.length) {
922
+ const a = argWords[i].value;
923
+ if (a === "--") {
924
+ i++;
925
+ break;
926
+ }
927
+ if (a === "-S" || a === "--split-string") {
928
+ const text = [a, ...argWords.slice(i + 1).map((w) => w.value)].slice(1).join(" ");
929
+ return rankText(text, depth);
930
+ }
931
+ if (a.startsWith("--split-string=") || /^-S./.test(a)) {
932
+ const first = a.startsWith("--") ? a.slice(15) : a.slice(2);
933
+ return rankText(
934
+ [first, ...argWords.slice(i + 1).map((w) => w.value)].join(" "),
935
+ depth
936
+ );
937
+ }
938
+ if (/^(-u|-C|-P|--unset|--chdir)$/.test(a)) {
939
+ i += 2;
940
+ continue;
941
+ }
942
+ if (a.startsWith("-") && a.length > 1) {
943
+ i++;
944
+ continue;
945
+ }
946
+ break;
947
+ }
948
+ return rankArgv(argWords.slice(i), depth + 1).rank;
949
+ }
950
+ function rankShell(base, argWords, depth) {
951
+ let code = false;
952
+ for (let i = 0; i < argWords.length; i++) {
953
+ const a = argWords[i].value;
954
+ if (a === "--") break;
955
+ if (/^(--rcfile|--init-file|-o|\+o|-O|\+O)$/.test(a)) {
956
+ i++;
957
+ continue;
958
+ }
959
+ if (a === "--command" || base === "fish" && a === "-c") {
960
+ return rankText(argWords[i + 1]?.value ?? "", depth);
961
+ }
962
+ if (/^[-+][a-zA-Z]+$/.test(a)) {
963
+ if (/^-[a-zA-Z]*c/.test(a)) code = true;
964
+ continue;
965
+ }
966
+ if (a.startsWith("-")) continue;
967
+ if (code) {
968
+ if (base === "busybox")
969
+ return rankArgv(argWords.slice(i), depth + 1).rank;
970
+ return rankText(a, depth);
971
+ }
972
+ if (base === "busybox") return rankArgv(argWords.slice(i), depth + 1).rank;
973
+ return 0;
974
+ }
975
+ return 0;
976
+ }
977
+ function rankFind(argWords, depth) {
978
+ let rank = 0;
979
+ for (let i = 0; i < argWords.length; i++) {
980
+ const a = argWords[i].value;
981
+ if (a === "-delete") rank = ASK;
982
+ if (/^-(exec|execdir|ok|okdir)$/.test(a)) {
983
+ let end = i + 1;
984
+ while (end < argWords.length && argWords[end].value !== ";" && argWords[end].value !== "+") {
985
+ end++;
986
+ }
987
+ const l = rankArgv(argWords.slice(i + 1, end), depth + 1);
988
+ rank = Math.max(rank, BULK_DELETE.has(l.base) ? ASK : l.rank);
989
+ i = end;
990
+ }
991
+ if (/^-f(print|print0|printf|ls)$/.test(a)) {
992
+ if (AGENT_CONFIG_PATH.test(argWords[i + 1]?.value ?? "")) rank = ASK;
993
+ }
994
+ }
995
+ return rank;
996
+ }
997
+ function rankRunner(base, argWords, depth) {
998
+ let rest = argWords;
999
+ if (base === "npm" || base === "pnpm" || base === "yarn") {
1000
+ const sub = rest[0]?.value;
1001
+ if (!["exec", "x", "dlx"].includes(sub ?? "")) return null;
1002
+ rest = rest.slice(1);
1003
+ }
1004
+ let i = 0;
1005
+ while (i < rest.length) {
1006
+ const a = rest[i].value;
1007
+ if (a === "--") {
1008
+ i++;
1009
+ break;
1010
+ }
1011
+ if (a === "-c" || a === "--call")
1012
+ return leaf(rankText(rest[i + 1]?.value ?? "", depth));
1013
+ if (a.startsWith("--call=")) return leaf(rankText(a.slice(7), depth));
1014
+ if (a === "-p" || a === "--package") {
1015
+ i += 2;
1016
+ continue;
1017
+ }
1018
+ if (a.startsWith("-")) {
1019
+ i++;
1020
+ continue;
1021
+ }
1022
+ break;
1023
+ }
1024
+ const pkg = rest[i];
1025
+ if (!pkg) return null;
1026
+ if (pkg.dynamic) return leaf(ASK);
1027
+ const name = /^(?:@[^/]+\/)?([^@]+)(?:@.*)?$/.exec(pkg.value)?.[1] ?? pkg.value;
1028
+ const bin = name === "claude-code" ? "claude" : name;
1029
+ return rankArgv([literal(bin), ...rest.slice(i + 1)], depth + 1);
1030
+ }
1031
+ function rankChmod(args) {
1032
+ const opts = argsBeforeDashDash(args);
1033
+ const recursive = opts.some(
1034
+ (a) => a === "--recursive" || /^-[a-zA-Z]*R/.test(a)
1035
+ );
1036
+ if (!recursive) return 0;
1037
+ const modes = args.filter(
1038
+ (a) => !a.startsWith("-") || /^-[rwxXst]+$/.test(a)
1039
+ );
1040
+ const worldWritable = modes.some(
1041
+ (m) => /^0*[0-7]?[0-7]?[0-7]?[2367]$/.test(m) && m.length >= 3 || /(^|,)[ugo]*[ao][ugo]*[+=][rwxXst]*w/.test(m)
1042
+ );
1043
+ return worldWritable ? ASK : 0;
1044
+ }
1045
+ var GIT_VALUE_OPTS = /* @__PURE__ */ new Set([
1046
+ "-C",
1047
+ "-c",
1048
+ "--git-dir",
1049
+ "--work-tree",
1050
+ "--namespace",
1051
+ "--super-prefix",
1052
+ "--config-env",
1053
+ "--exec-path",
1054
+ "--list-cmds",
1055
+ "--attr-source"
1056
+ ]);
1057
+ var GIT_EXEC_KEY = /^(core\.(pager|editor|sshcommand|askpass|gitproxy)|pager\..+|sequence\.editor|.+\.(textconv|command|cmd|helper|program|clean|smudge|process|driver|tool)|credential\..*|uploadpack\.packobjectshook|gpg\..*program|.*\.(receivepack|uploadpack))$/i;
1058
+ function rankGit(argWords, depth) {
1059
+ const args = argWords.map((w) => w.value);
1060
+ let rank = 0;
1061
+ const aliases = /* @__PURE__ */ new Map();
1062
+ let i = 0;
1063
+ while (i < args.length) {
1064
+ const a = args[i];
1065
+ if (!a.startsWith("-")) break;
1066
+ let opt = a;
1067
+ let val;
1068
+ if (a.startsWith("--") && a.includes("=")) {
1069
+ opt = a.slice(0, a.indexOf("="));
1070
+ val = a.slice(a.indexOf("=") + 1);
1071
+ i++;
1072
+ } else if (GIT_VALUE_OPTS.has(a)) {
1073
+ val = args[i + 1] ?? "";
1074
+ if (argWords[i + 1]?.dynamic && (a === "-c" || a === "--config-env")) {
1075
+ rank = ASK;
1076
+ }
1077
+ i += 2;
1078
+ } else {
1079
+ i++;
1080
+ }
1081
+ if (opt === "-c" && val !== void 0) {
1082
+ const eq = val.indexOf("=");
1083
+ const key = (eq < 0 ? val : val.slice(0, eq)).toLowerCase();
1084
+ const value = eq < 0 ? "" : val.slice(eq + 1);
1085
+ if (key.startsWith("alias.")) aliases.set(key.slice(6), value);
1086
+ else if (key === "core.hookspath" || key === "core.fsmonitor") {
1087
+ if (!/^(false|0|no|off|)$/i.test(value)) rank = ASK;
1088
+ } else if (GIT_EXEC_KEY.test(key)) {
1089
+ rank = Math.max(rank, rankText(value, depth));
1090
+ }
1091
+ }
1092
+ if (opt === "--config-env" && val !== void 0) {
1093
+ const key = val.split("=")[0].toLowerCase();
1094
+ if (key.startsWith("alias.") || GIT_EXEC_KEY.test(key) || /hookspath|fsmonitor/.test(key)) {
1095
+ rank = ASK;
1096
+ }
1097
+ }
1098
+ }
1099
+ if (i >= args.length) return rank;
1100
+ if (argWords[i].dynamic) return ASK;
1101
+ const sub = args[i];
1102
+ const rest = args.slice(i + 1);
1103
+ const alias = aliases.get(sub.toLowerCase());
1104
+ if (alias !== void 0) {
1105
+ if (alias.startsWith("!")) {
1106
+ return Math.max(
1107
+ rank,
1108
+ rankText(`${alias.slice(1)} ${rest.join(" ")}`, depth)
1109
+ );
1110
+ }
1111
+ const expanded = parseShell(alias);
1112
+ const aliasWords = expanded.commands[0]?.words ?? [];
1113
+ return Math.max(
1114
+ rank,
1115
+ expanded.ambiguous ? ASK : 0,
1116
+ rankGit([...aliasWords, ...argWords.slice(i + 1)], depth + 1)
1117
+ );
1118
+ }
1119
+ const opts = argsBeforeDashDash(rest);
1120
+ const has = (...names) => opts.some((a) => names.includes(a.split("=")[0]));
1121
+ const short = (letter) => opts.some((a) => new RegExp(`^-[a-zA-Z]*${letter}`).test(a));
1122
+ let sr = 0;
1123
+ switch (sub) {
1124
+ case "push": {
1125
+ const forced = has(
1126
+ "--force",
1127
+ "--force-with-lease",
1128
+ "--force-if-includes",
1129
+ "--mirror",
1130
+ "--delete",
1131
+ "--prune"
1132
+ ) || opts.some(
1133
+ (a) => /^-[a-zA-Z]+$/.test(a) && /[fd]/.test(a.replace(/o.*$/, ""))
1134
+ ) || rest.some((a) => /^[+:]/.test(a));
1135
+ sr = forced ? ASK : RANK.git_push;
1136
+ break;
1137
+ }
1138
+ case "reset":
1139
+ sr = has("--hard", "--merge") ? ASK : 0;
1140
+ break;
1141
+ case "clean":
1142
+ sr = has("--force") || short("f") ? ASK : 0;
1143
+ break;
1144
+ case "branch":
1145
+ sr = short("D") || (has("--delete") || short("d")) && (has("--force") || short("f")) ? ASK : 0;
1146
+ break;
1147
+ case "checkout":
1148
+ sr = rest.includes("--") || has("--force") || short("f") ? ASK : 0;
1149
+ break;
1150
+ case "switch":
1151
+ sr = has("--discard-changes", "--force") || short("f") ? ASK : 0;
1152
+ break;
1153
+ case "restore":
1154
+ sr = has("--source") || short("s") ? ASK : 0;
1155
+ break;
1156
+ case "stash":
1157
+ sr = ["drop", "clear"].includes(rest[0] ?? "") ? ASK : 0;
1158
+ break;
1159
+ case "update-ref":
1160
+ sr = short("d") ? ASK : 0;
1161
+ break;
1162
+ case "reflog":
1163
+ sr = ["expire", "delete"].includes(rest[0] ?? "") ? ASK : 0;
1164
+ break;
1165
+ case "filter-branch":
1166
+ case "filter-repo":
1167
+ sr = ASK;
1168
+ break;
1169
+ }
1170
+ if (!GIT_READS.has(sub) && rest.some((a) => AGENT_CONFIG_PATH.test(a)))
1171
+ sr = ASK;
1172
+ return Math.max(rank, sr);
1173
+ }
1174
+ var AGENT_CONFIG_SUBCOMMANDS = /* @__PURE__ */ new Set([
1175
+ "mcp",
1176
+ "plugin",
1177
+ "plugins",
1178
+ "config"
1179
+ ]);
1180
+ var AGENT_READ_ACTIONS = /* @__PURE__ */ new Set([
1181
+ "list",
1182
+ "ls",
1183
+ "get",
1184
+ "show",
1185
+ "serve",
1186
+ "help",
1187
+ "--help",
1188
+ "-h"
1189
+ ]);
1190
+ var AGENT_WIDENING_OPTS = /^(--mcp-config|--settings|--dangerously-skip-permissions|--allow-dangerously-skip-permissions|--allowed-tools|--allowedtools|--add-dir|--plugin-dir|--dangerously-bypass-approvals-and-sandbox|--yolo|--config)(=|$)/i;
1191
+ function rankAgentCli(base, args) {
1192
+ if (args.some((a) => AGENT_WIDENING_OPTS.test(a))) return ASK;
1193
+ if (base === "codex" && args.includes("-c")) return ASK;
1194
+ const mode = args.findIndex((a) => a === "--permission-mode");
1195
+ const modeValue = mode >= 0 ? args[mode + 1] : args.find((a) => a.startsWith("--permission-mode="))?.slice(18);
1196
+ if (modeValue !== void 0 && !/^(default|plan)$/i.test(modeValue))
1197
+ return ASK;
1198
+ const positionals2 = args.filter((a) => !a.startsWith("-"));
1199
+ const sub = positionals2.findIndex((p) => AGENT_CONFIG_SUBCOMMANDS.has(p));
1200
+ if (sub < 0) return 0;
1201
+ const action = positionals2[sub + 1];
1202
+ if (action === void 0 || AGENT_READ_ACTIONS.has(action)) return 0;
1203
+ return ASK;
1204
+ }
165
1205
  function classifyCommand(command) {
166
- if (DESTRUCTIVE.some((re) => re.test(command))) return "shell_destructive";
167
- if (DEPLOY.some((re) => re.test(command))) return "shell_deploy";
168
- if (GIT_PUSH.test(command)) return "git_push";
169
- if (startsInteractiveSession(command)) return "shell_session";
170
- return "shell";
1206
+ let rank = 0;
1207
+ if (DESTRUCTIVE.some((re) => re.test(command))) rank = ASK;
1208
+ else if (DEPLOY.some((re) => re.test(command))) rank = RANK.shell_deploy;
1209
+ else if (GIT_PUSH.test(command)) rank = RANK.git_push;
1210
+ else if (startsInteractiveSession(command)) rank = RANK.shell_session;
1211
+ if (rank < ASK) rank = Math.max(rank, rankText(command, 0));
1212
+ return BY_RANK[rank];
1213
+ }
1214
+ function isAgentConfigPath(path) {
1215
+ return AGENT_CONFIG_PATH.test(path);
171
1216
  }
172
1217
  function mcpToolName(server, tool) {
173
1218
  const part = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").replace(/^(\d)/, "x$1") || "x";
@@ -203,6 +1248,54 @@ var FILE_TOOLS = /* @__PURE__ */ new Set([
203
1248
  "edit"
204
1249
  // DeepSeek Harness
205
1250
  ]);
1251
+ var CONTENT_PIN_TOOLS = /* @__PURE__ */ new Set([
1252
+ "Edit",
1253
+ "MultiEdit",
1254
+ "NotebookEdit",
1255
+ "edit"
1256
+ // DeepSeek Harness
1257
+ ]);
1258
+ var EditPinRefused = class extends Error {
1259
+ constructor(reasonCode, message) {
1260
+ super(message);
1261
+ this.reasonCode = reasonCode;
1262
+ this.name = "EditPinRefused";
1263
+ }
1264
+ reasonCode;
1265
+ };
1266
+ async function pinEditTarget(call, governed) {
1267
+ if (!CONTENT_PIN_TOOLS.has(call.tool)) return governed;
1268
+ const path = governed.arguments.path;
1269
+ if (typeof path !== "string" || !path.startsWith("/")) {
1270
+ throw new EditPinRefused(
1271
+ CONTENT_PIN_INVALID_ARGUMENT,
1272
+ `${call.tool} needs an absolute file path; the hook does not resolve relative paths`
1273
+ );
1274
+ }
1275
+ let pin;
1276
+ try {
1277
+ pin = await pinFile(path, { allowAbsent: true });
1278
+ } catch (err) {
1279
+ const code = typeof err?.reasonCode === "string" ? err.reasonCode : "CONTENT_PIN_UNREADABLE";
1280
+ throw new EditPinRefused(
1281
+ code,
1282
+ `the current contents of ${path} could not be pinned`
1283
+ );
1284
+ }
1285
+ const record = "absent" in pin ? { arg: "path", index: 0, mode: "recheck", absent: true } : {
1286
+ arg: "path",
1287
+ index: 0,
1288
+ mode: "recheck",
1289
+ name: pin.name,
1290
+ size: pin.size,
1291
+ sha256: pin.sha256
1292
+ };
1293
+ return {
1294
+ ...governed,
1295
+ arguments: { ...governed.arguments, [CONTENT_PIN_KEY]: [record] },
1296
+ contentPin: { path, pin }
1297
+ };
1298
+ }
206
1299
  function commandText(value) {
207
1300
  if (typeof value === "string") return value;
208
1301
  if (Array.isArray(value) && value.every((v) => typeof v === "string")) {
@@ -221,17 +1314,20 @@ function patchTargets(patch) {
221
1314
  }
222
1315
  return targets;
223
1316
  }
1317
+ var AGENT_CONFIG_NOTE = "(agent MCP, hook, permission or plugin config)";
224
1318
  function fileWrite(operation, path, content, cwd, summaryVerb) {
1319
+ const config = isAgentConfigPath(path);
225
1320
  return {
226
- toolName: "file_write",
1321
+ toolName: config ? "shell_destructive" : "file_write",
227
1322
  arguments: {
228
1323
  operation,
229
1324
  path,
230
1325
  contentBytes: Buffer.byteLength(content),
231
1326
  contentDigest: digest(content),
1327
+ ...config ? { touches: "agent-config" } : {},
232
1328
  ...cwd
233
1329
  },
234
- summary: `${summaryVerb} ${path}`
1330
+ summary: `${summaryVerb} ${path}${config ? ` ${AGENT_CONFIG_NOTE}` : ""}`
235
1331
  };
236
1332
  }
237
1333
  function governedCall(call) {
@@ -279,10 +1375,12 @@ function governedCall(call) {
279
1375
  const targets = patchTargets(patch);
280
1376
  const paths = [...new Set(targets.map((t) => t.path))];
281
1377
  const shown = paths.slice(0, MAX_PATHS).map((p) => bounded(p, 500));
1378
+ const config = paths.some((p) => isAgentConfigPath(p));
282
1379
  return {
283
- toolName: "file_write",
1380
+ toolName: config ? "shell_destructive" : "file_write",
284
1381
  arguments: {
285
1382
  operation: "apply_patch",
1383
+ ...config ? { touches: "agent-config" } : {},
286
1384
  path: shown[0] ?? "",
287
1385
  paths: shown,
288
1386
  ...paths.length > MAX_PATHS ? { morePaths: paths.length - MAX_PATHS } : {},
@@ -291,7 +1389,7 @@ function governedCall(call) {
291
1389
  contentDigest: digest(patch),
292
1390
  ...cwd
293
1391
  },
294
- summary: paths.length === 0 ? "Apply a patch (no file headers found)" : paths.length === 1 ? `Patch ${bounded(paths[0], 160)}` : `Patch ${paths.length} files: ${bounded(paths.join(", "), 160)}`
1392
+ summary: (paths.length === 0 ? "Apply a patch (no file headers found)" : paths.length === 1 ? `Patch ${bounded(paths[0], 160)}` : `Patch ${paths.length} files: ${bounded(paths.join(", "), 160)}`) + (config ? ` ${AGENT_CONFIG_NOTE}` : "")
295
1393
  };
296
1394
  }
297
1395
  if (tool === "WebFetch" || tool === "web_fetch") {
@@ -328,6 +1426,7 @@ function tierOf(toolName) {
328
1426
  import { createGuardianClient } from "@odingard/guardian-sdk";
329
1427
 
330
1428
  // src/decide.ts
1429
+ import { verifyPin } from "@odingard/guardian-sdk";
331
1430
  var PLAIN = {
332
1431
  NOT_AUTHORIZED: "this agent is not authorized for it",
333
1432
  APPROVAL_DENIED: "the approver declined it",
@@ -338,6 +1437,16 @@ var PLAIN = {
338
1437
  SERVICE_UNAVAILABLE: "Guardian could not be reached",
339
1438
  REQUEST_CONFLICT: "Guardian saw a conflicting request"
340
1439
  };
1440
+ async function contentPinRefusal(call) {
1441
+ if (!call.contentPin) return void 0;
1442
+ try {
1443
+ await verifyPin(call.contentPin.path, call.contentPin.pin);
1444
+ return void 0;
1445
+ } catch (err) {
1446
+ const code = err?.reasonCode;
1447
+ return typeof code === "string" ? code : "CONTENT_PIN_UNREADABLE";
1448
+ }
1449
+ }
341
1450
  function plain(code) {
342
1451
  return PLAIN[code] ?? code;
343
1452
  }
@@ -418,6 +1527,17 @@ async function decide(call, options) {
418
1527
  guardianDecision: "DENY"
419
1528
  });
420
1529
  }
1530
+ const pinRefusal = await contentPinRefusal(call);
1531
+ if (pinRefusal !== void 0) {
1532
+ const path = call.contentPin.path;
1533
+ return {
1534
+ decision: "deny",
1535
+ reason: pinRefusal === "CONTENT_CHANGED_SINCE_APPROVAL" ? `Guardian hook: ${path} changed since this edit was proposed (CONTENT_CHANGED_SINCE_APPROVAL). Nothing ran. Read the file again and propose the edit again; it needs a new approval.` : `Guardian hook: ${path} could not be checked against its approval (${pinRefusal}). Nothing ran.`,
1536
+ requestId: result.requestId,
1537
+ guardianDecision: approvedByHuman ? "ASK" : "ALLOW",
1538
+ approvedByHuman
1539
+ };
1540
+ }
421
1541
  let executed;
422
1542
  try {
423
1543
  executed = await options.client.execute({
@@ -669,12 +1789,21 @@ async function evaluate(dialect2, stdinText, env, deps, deadlineMs) {
669
1789
  if (!input || typeof input.tool_name !== "string") {
670
1790
  return failClosed("the tool call had no tool name. Nothing ran.");
671
1791
  }
672
- const call = governedCall({
1792
+ const toolCall = {
673
1793
  tool: input.tool_name,
674
1794
  input: input.tool_input && typeof input.tool_input === "object" ? input.tool_input : {},
675
1795
  ...typeof input.cwd === "string" ? { cwd: input.cwd } : {}
676
- });
677
- if (call === null) return null;
1796
+ };
1797
+ const classified = governedCall(toolCall);
1798
+ if (classified === null) return null;
1799
+ let call;
1800
+ try {
1801
+ call = await pinEditTarget(toolCall, classified);
1802
+ } catch (err) {
1803
+ const code = err instanceof EditPinRefused ? err.reasonCode : "CONTENT_PIN_UNREADABLE";
1804
+ const detail = err instanceof EditPinRefused ? err.message : "the target file could not be pinned";
1805
+ return failClosed(`${detail} (${code}). Nothing ran.`);
1806
+ }
678
1807
  const connectionId = connectionFor(call.toolName, env);
679
1808
  const credential = env.GUARDIAN_AGENT_CREDENTIAL?.trim();
680
1809
  const baseUrl = (env.GUARDIAN_BASE_URL?.trim() || DEFAULT_BASE_URL).replace(