@holmes-lab/holmes-kit 0.34.0 → 0.35.1

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +6 -0
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/codex-oracle.js +36 -2
  5. package/dist/holmes/cli/doctor.d.ts +14 -1
  6. package/dist/holmes/cli/doctor.js +335 -71
  7. package/dist/holmes/cli/index.d.ts +1 -1
  8. package/dist/holmes/cli/index.js +38 -5
  9. package/dist/holmes/cli/runtime-binding-approval.d.ts +7 -0
  10. package/dist/holmes/cli/runtime-binding-approval.js +102 -0
  11. package/dist/holmes/cli/runtime-binding.d.ts +29 -0
  12. package/dist/holmes/cli/runtime-binding.js +570 -0
  13. package/dist/holmes/governance/approval-queue.d.ts +2 -0
  14. package/dist/holmes/governance/approval-queue.js +11 -4
  15. package/dist/holmes/guardrail/impact-gate.js +90 -5
  16. package/dist/holmes/guardrail/linear-match.js +8 -1
  17. package/dist/holmes/guardrail/risk-classifier.d.ts +6 -0
  18. package/dist/holmes/guardrail/risk-classifier.js +68 -23
  19. package/dist/holmes/guardrail/shell-argument-roles.d.ts +15 -0
  20. package/dist/holmes/guardrail/shell-argument-roles.js +209 -0
  21. package/dist/holmes/guardrail/shell-syntax.d.ts +20 -0
  22. package/dist/holmes/guardrail/shell-syntax.js +489 -0
  23. package/dist/holmes/guardrail/shell-words.d.ts +2 -18
  24. package/dist/holmes/guardrail/shell-words.js +67 -442
  25. package/dist/holmes/guardrail/write-target.d.ts +54 -0
  26. package/dist/holmes/guardrail/write-target.js +327 -1
  27. package/dist/holmes/hooks/pre-tool-use.d.ts +12 -0
  28. package/dist/holmes/hooks/pre-tool-use.js +377 -66
  29. package/dist/holmes/mcp/handlers/maintenance-analysis.js +4 -2
  30. package/dist/holmes/mcp/handlers/test-execution.js +6 -2
  31. package/dist/holmes/mcp/handlers.d.ts +9 -1
  32. package/dist/holmes/mcp/handlers.js +6 -4
  33. package/dist/holmes/mcp/maintenance-evidence.d.ts +16 -1
  34. package/dist/holmes/mcp/maintenance-evidence.js +29 -3
  35. package/dist/holmes/mcp/operator-recovery.d.ts +9 -0
  36. package/dist/holmes/mcp/operator-recovery.js +63 -0
  37. package/dist/holmes/rtm/test-scope.d.ts +9 -0
  38. package/dist/holmes/rtm/test-scope.js +284 -14
  39. package/dist/holmes/runtime/binding.d.ts +30 -0
  40. package/dist/holmes/runtime/binding.js +164 -0
  41. package/dist/holmes/runtime/dispatch.d.ts +9 -0
  42. package/dist/holmes/runtime/dispatch.js +169 -0
  43. package/dist/holmes/runtime/hook-process.d.ts +11 -0
  44. package/dist/holmes/runtime/hook-process.js +130 -0
  45. package/docs/install-guide.md +65 -0
  46. package/package.json +1 -1
@@ -33,14 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.MAX_COMMAND = void 0;
37
- exports.shellWords = shellWords;
38
- exports.commandOf = commandOf;
36
+ exports.MAX_COMMAND = exports.commandOf = exports.shellWords = void 0;
39
37
  exports.findRunsUnfiltered = findRunsUnfiltered;
40
38
  exports.harnessWiringActOf = harnessWiringActOf;
41
39
  exports.harnessWiringActOfCommand = harnessWiringActOfCommand;
42
40
  exports.globToRe = globToRe;
43
- // @implements A-SPEC-728, A-SPEC-733
41
+ // @implements A-SPEC-728, A-SPEC-733, A-SPEC-753
44
42
  // Shell WORDS, not spellings. The wiring-protection rule was first written as regexes over verb
45
43
  // spellings and the adversarial round walked through it twenty ways (`\rm`, `env rm`, `rm .mcp"".json`,
46
44
  // `rm .claude/settings.{json,local.json}`, `mv`, `git rm`, `find -delete`, …): a gate over a spelling
@@ -54,435 +52,12 @@ const fs = __importStar(require("node:fs"));
54
52
  const os = __importStar(require("node:os"));
55
53
  const path = __importStar(require("node:path"));
56
54
  const linear_match_1 = require("./linear-match");
55
+ const risk_classifier_1 = require("./risk-classifier");
57
56
  const write_target_1 = require("./write-target");
58
- const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*/;
59
- /**
60
- * `$NAME` / `${NAME[:-…]}` at `src[i]` → [value | null(unknown), length consumed, what an unknown
61
- * variable's default spells]. `${X:-word}` with X unknowable may expand to `word` (round 4).
62
- */
63
- function readVar(src, i, env, home, pwd) {
64
- const known = (name) => name === 'HOME' ? home : name === 'CODEX_HOME' && env.CODEX_HOME ? env.CODEX_HOME : name === 'PWD' ? pwd : null;
65
- if (src[i + 1] === '{') {
66
- const close = src.indexOf('}', i + 2);
67
- if (close < 0)
68
- return [null, src.length - i];
69
- const inner = src.slice(i + 2, close);
70
- const name = NAME_RE.exec(inner)?.[0] ?? '';
71
- const rest = inner.slice(name.length);
72
- // `${HOME}`, `${HOME:-x}`, `${HOME:?}`, `${HOME=…}`: the value is HOME's whenever HOME is set.
73
- const v = /^(?::?[-=?].*)?$/s.test(rest) ? known(name) : null;
74
- const dflt = /^:?[-=](.*)$/s.exec(rest)?.[1];
75
- return [v, close + 1 - i, v === null && dflt ? dflt.replace(/^(['"])(.*)\1$/s, '$2') : undefined];
76
- }
77
- // Linear: the name is read in place, never from a copy of the rest of the text (round 4).
78
- NAME_Y.lastIndex = i + 1;
79
- const name = NAME_Y.exec(src)?.[0];
80
- if (!name)
81
- return [null, 2];
82
- return [known(name), 1 + name.length];
83
- }
84
- const NAME_Y = /[A-Za-z_][A-Za-z0-9_]*/y;
85
- /** `$'…'` (ANSI-C quoting) starting at `src[i]` (the `$`) → [decoded text, index of the closing quote]. */
86
- function readAnsiC(src, i) {
87
- let out = '';
88
- let j = i + 2;
89
- const simple = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' };
90
- for (; j < src.length && src[j] !== "'"; j++) {
91
- if (src[j] !== '\\') {
92
- out += src[j];
93
- continue;
94
- }
95
- const n = src[j + 1] ?? '';
96
- // Sticky reads in place: a `.slice` per escape was quadratic on a long `$'…'` (round 4).
97
- const at = (re) => { re.lastIndex = j + 1; return re.exec(src); };
98
- const hex = at(HEX_Y);
99
- const oct = at(OCT_Y);
100
- const uni = at(UNI_Y);
101
- if (hex) {
102
- out += String.fromCharCode(parseInt(hex[1], 16));
103
- j += hex[0].length;
104
- continue;
105
- }
106
- if (uni) {
107
- const cp = parseInt(uni[1], 16);
108
- out += cp <= 0x10ffff ? String.fromCodePoint(cp) : '\ufffd';
109
- j += uni[0].length;
110
- continue;
111
- }
112
- if (oct) {
113
- out += String.fromCharCode(parseInt(oct[1], 8));
114
- j += oct[0].length;
115
- continue;
116
- }
117
- if (n in simple) {
118
- out += simple[n];
119
- j++;
120
- continue;
121
- }
122
- out += n;
123
- j++;
124
- }
125
- return [out, j];
126
- }
127
- const HEX_Y = /x([0-9a-fA-F]{1,2})/y;
128
- const OCT_Y = /([0-7]{1,3})/y;
129
- const UNI_Y = /[uU]([0-9a-fA-F]{1,8})/y;
130
- /** Index of the paren balancing the `(` at `src[i]`, or the end. */
131
- function balance(src, i) {
132
- let d = 0;
133
- for (let j = i; j < src.length; j++) {
134
- if (src[j] === '(')
135
- d++;
136
- else if (src[j] === ')' && --d === 0)
137
- return j;
138
- }
139
- return src.length - 1;
140
- }
141
- /**
142
- * Expand unquoted `{a,b}` lists (bounded), keeping quoted braces literal.
143
- * @implements A-SPEC-728 (round 8) — the total characters produced are bounded too (1 MB per segment):
144
- * counting alternatives alone let `{a,b}` × n copy the whole word at every level until a 4 GB heap
145
- * aborted the hook with no verdict (measured). Past the bound the word stays literal and is marked
146
- * unknowable (`overflow`), the conservative reading.
147
- */
148
- const BRACE_CHAR_BUDGET = 1024 * 1024;
149
- function expandBraces(chars, budget = { n: 64 }) {
150
- if (budget.chars === undefined)
151
- budget.chars = BRACE_CHAR_BUDGET;
152
- let depth = 0, open = -1;
153
- for (let i = 0; i < chars.length; i++) {
154
- const { c, q } = chars[i];
155
- if (q)
156
- continue;
157
- if (c === '{') {
158
- if (depth === 0)
159
- open = i;
160
- depth++;
161
- }
162
- else if (c === '}' && depth > 0) {
163
- depth--;
164
- if (depth === 0 && open >= 0) {
165
- const inner = chars.slice(open + 1, i);
166
- const alts = [];
167
- let d = 0, start = 0;
168
- for (let j = 0; j < inner.length; j++) {
169
- if (inner[j].q)
170
- continue;
171
- if (inner[j].c === '{')
172
- d++;
173
- else if (inner[j].c === '}')
174
- d--;
175
- else if (inner[j].c === ',' && d === 0) {
176
- alts.push(inner.slice(start, j));
177
- start = j + 1;
178
- }
179
- }
180
- if (alts.length === 0) {
181
- open = -1;
182
- continue;
183
- } // `{x}` is literal
184
- alts.push(inner.slice(start));
185
- const out = [];
186
- for (const a of alts) {
187
- if (budget.n-- <= 0)
188
- break;
189
- const size = open + a.length + (chars.length - i - 1);
190
- if ((budget.chars -= size) < 0) {
191
- budget.overflow = true;
192
- return [chars];
193
- }
194
- out.push(...expandBraces([...chars.slice(0, open), ...a, ...chars.slice(i + 1)], budget));
195
- }
196
- return out;
197
- }
198
- }
199
- }
200
- return [chars];
201
- }
202
- /**
203
- * The simple commands of one segment, as the shell would split and expand them. Operators split
204
- * commands (`;`, `&`, `|`, newline, `(`, `)` at a word start); redirect targets are collected per
205
- * command. `pwd` is the segment's working directory (for `~+` and `$PWD`), null when unknowable.
206
- */
207
- let USERNAME;
208
- function shellWords(src, env = process.env, home = os.homedir(), pwd = null) {
209
- // @implements A-SPEC-728 (rule 42) — read once per process: it ran for every segment (13% of a 256 KB command — measured).
210
- const me = USERNAME ?? (USERNAME = (() => { try {
211
- return os.userInfo().username;
212
- }
213
- catch {
214
- return '';
215
- } })());
216
- const commands = [];
217
- let cur = { words: [], redirects: [] };
218
- let chars = [];
219
- let inWord = false, known = true;
220
- let pending = null;
221
- const subs = [];
222
- const budget = { n: 4096 }; // brace expansions per segment; beyond it the segment is too large to judge
223
- const finishWord = () => {
224
- if (!inWord)
225
- return;
226
- let raw = chars;
227
- // Tilde at the start of an unquoted word: `~`, `~/…`, `~<me>`, `~+` (the working directory).
228
- if (raw.length > 0 && raw[0].c === '~' && !raw[0].q) {
229
- const slash = raw.findIndex((x) => x.c === '/');
230
- const user = raw.slice(1, slash < 0 ? raw.length : slash).map((x) => x.c).join('');
231
- const to = user === '' || user === me ? home : user === '+' ? pwd : null;
232
- if (to !== null)
233
- raw = [...[...to].map((c) => ({ c, q: true })), ...(slash < 0 ? [] : raw.slice(slash))];
234
- else
235
- known = false;
236
- }
237
- const expanded = expandBraces(raw, budget);
238
- if (budget.overflow)
239
- known = false;
240
- for (const w of expanded) {
241
- const full = w.map((x) => x.c).join('');
242
- const nul = full.indexOf('\0'); // an argument ends at NUL: `.mcp.json\0x` is `.mcp.json`
243
- const word = { text: nul >= 0 ? full.slice(0, nul) : full, known, glob: w.some((x) => !x.q && /[*?[(]/.test(x.c)) };
244
- if (pending === 'write')
245
- cur.redirects.push(word);
246
- else if (pending === null)
247
- cur.words.push(word);
248
- }
249
- pending = null;
250
- chars = [];
251
- inWord = false;
252
- known = true;
253
- };
254
- const endCommand = () => {
255
- finishWord();
256
- if (cur.words.length > 0 || cur.redirects.length > 0)
257
- commands.push(cur);
258
- cur = { words: [], redirects: [] };
259
- };
260
- const push = (c, q) => { chars.push({ c, q }); inWord = true; };
261
- const pushText = (t) => { for (const c of t)
262
- push(c, true); };
263
- for (let i = 0; i < src.length; i++) {
264
- const c = src[i];
265
- if (c === '\\') {
266
- const n = src[i + 1];
267
- if (n === '\n') {
268
- i++;
269
- continue;
270
- }
271
- if (n !== undefined) {
272
- push(n, true);
273
- i++;
274
- }
275
- continue;
276
- }
277
- if (c === '$' && src[i + 1] === "'") {
278
- const [t, end] = readAnsiC(src, i);
279
- inWord = true;
280
- pushText(t);
281
- i = end;
282
- continue;
283
- }
284
- if (c === "'") {
285
- const close = src.indexOf("'", i + 1);
286
- const end = close < 0 ? src.length : close;
287
- inWord = true;
288
- pushText(src.slice(i + 1, end));
289
- i = end;
290
- continue;
291
- }
292
- if (c === '"') {
293
- inWord = true;
294
- let j = i + 1;
295
- for (; j < src.length && src[j] !== '"'; j++) {
296
- if (src[j] === '\\' && /["\\$`\n]/.test(src[j + 1] ?? '')) {
297
- if (src[j + 1] !== '\n')
298
- push(src[j + 1], true);
299
- j++;
300
- continue;
301
- }
302
- if (src[j] === '$' && /[{A-Za-z_]/.test(src[j + 1] ?? '')) {
303
- const [v, len, dflt] = readVar(src, j, env, home, pwd);
304
- if (v === null) {
305
- known = false;
306
- if (dflt)
307
- pushText(dflt);
308
- }
309
- else
310
- pushText(v);
311
- j += len - 1;
312
- continue;
313
- }
314
- if (src[j] === '$' && src[j + 1] === '(') {
315
- const end = balance(src, j + 1);
316
- subs.push(src.slice(j + 2, end));
317
- known = false;
318
- j = end;
319
- continue;
320
- }
321
- if (src[j] === '`') {
322
- const close = src.indexOf('`', j + 1);
323
- const end = close < 0 ? src.length : close;
324
- subs.push(src.slice(j + 1, end));
325
- known = false;
326
- j = end;
327
- continue;
328
- }
329
- push(src[j], true);
330
- }
331
- i = j;
332
- continue;
333
- }
334
- if (c === '$' && src[i + 1] === '(') {
335
- const end = balance(src, i + 1);
336
- subs.push(src.slice(i + 2, end));
337
- known = false;
338
- inWord = true;
339
- i = end;
340
- continue;
341
- }
342
- if (c === '`') {
343
- const close = src.indexOf('`', i + 1);
344
- const end = close < 0 ? src.length : close;
345
- subs.push(src.slice(i + 1, end));
346
- known = false;
347
- inWord = true;
348
- i = end;
349
- continue;
350
- }
351
- if (c === '$' && /[{A-Za-z_]/.test(src[i + 1] ?? '')) {
352
- const [v, len, dflt] = readVar(src, i, env, home, pwd);
353
- if (v === null) {
354
- known = false;
355
- inWord = true;
356
- if (dflt)
357
- pushText(dflt);
358
- }
359
- else
360
- pushText(v);
361
- i += len - 1;
362
- continue;
363
- }
364
- if (/\s/.test(c)) {
365
- if (c === '\n')
366
- endCommand();
367
- else
368
- finishWord();
369
- continue;
370
- }
371
- // A `#` that starts a word starts a comment: the rest of the line is not run (round 4).
372
- if (c === '#' && !inWord) {
373
- const nl = src.indexOf('\n', i);
374
- i = (nl < 0 ? src.length : nl) - 1;
375
- continue;
376
- }
377
- // Process substitution `<(…)`/`>(…)`: one unknowable word; it does not end the command.
378
- if ((c === '<' || c === '>') && src[i + 1] === '(' && !inWord) {
379
- finishWord();
380
- const end = balance(src, i + 1);
381
- subs.push(src.slice(i + 2, end));
382
- cur.words.push({ text: src.slice(i, end + 1), known: false, glob: false });
383
- i = end;
384
- continue;
385
- }
386
- // Redirect operators: `N>`, `>`, `>>`, `>|`, `&>`, `&>>`, `<>`; `<`, `<<`, `<<<`, `>&N` read or dup.
387
- if (c === '>' || (c === '&' && src[i + 1] === '>') || (c === '<')) {
388
- const fdWord = inWord && chars.every((x) => /[0-9]/.test(x.c) && !x.q);
389
- if (fdWord) {
390
- chars = [];
391
- inWord = false;
392
- }
393
- else
394
- finishWord();
395
- let op = c;
396
- let j = i + 1;
397
- while (j < src.length && /[<>&|!]/.test(src[j]) && op.length < 3) {
398
- op += src[j];
399
- j++;
400
- }
401
- i = j - 1;
402
- if (/^&?>>?[|!]?$|^<>$/.test(op))
403
- pending = 'write';
404
- else if (/^>>?&$/.test(op)) {
405
- // `>&N`/`>&-` duplicates a descriptor; `>&WORD` (bash) writes stdout+stderr to WORD.
406
- let k = j;
407
- while (k < src.length && /[ \t]/.test(src[k]))
408
- k++;
409
- pending = /[0-9-]/.test(src[k] ?? '') && !/[^\s;&|]/.test(src[k + 1] ?? ' ') ? 'skip' : 'write';
410
- }
411
- else
412
- pending = 'skip'; // `<`, `<<`, `<<<`: input, delimiter or data
413
- continue;
414
- }
415
- // An unquoted `(…)` INSIDE a word is a zsh glob group (`.(mcp|x).json`, `@(…)`), part of the word.
416
- if (c === '(' && inWord) {
417
- const end = balance(src, i);
418
- for (const ch of src.slice(i, end + 1))
419
- push(ch, false);
420
- i = end;
421
- continue;
422
- }
423
- if (c === ';' || c === '|' || c === '&' || c === '(' || c === ')') {
424
- endCommand();
425
- continue;
426
- }
427
- push(c, false);
428
- }
429
- endCommand();
430
- return { commands, subs, overflow: budget.n <= 0, words: commands[0]?.words ?? [], redirects: commands[0]?.redirects ?? [] };
431
- }
432
- const WRAPPERS_WITH_ARG = {
433
- sudo: /^-[ugpChrtUD]$|^--(?:user|group|prompt|chdir|host|role|type|other-user)$/,
434
- doas: /^-[uC]$/,
435
- env: /^-u$|^--unset$|^-C$|^--chdir$/,
436
- nice: /^-n$|^--adjustment$/,
437
- stdbuf: /^-[ioe]$/,
438
- timeout: /^-[sk]$|^--(?:signal|kill-after)$/,
439
- };
440
- const PLAIN_WRAPPERS = new Set(['(', '{', '!', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', 'time', 'exec', 'nohup', 'command', 'builtin', 'busybox', 'sudo', 'env', 'nice', 'stdbuf', 'timeout', 'doas', 'coproc']);
441
- /** The words from the real command word on, behind wrappers, assignments and grouping keywords. */
442
- function commandOf(input) {
443
- let words = input;
444
- let i = 0;
445
- let unwraps = 0;
446
- while (i < words.length) {
447
- if (unwraps > 64)
448
- throw new Error('wrapper nesting too deep to judge');
449
- const t = words[i].text;
450
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)) {
451
- i++;
452
- continue;
453
- }
454
- if (!PLAIN_WRAPPERS.has(t))
455
- break;
456
- i++;
457
- const withArg = WRAPPERS_WITH_ARG[t];
458
- while (i < words.length && words[i].text.startsWith('-') && words[i].text !== '-') {
459
- const o = words[i].text;
460
- i++;
461
- if (o === '--')
462
- break;
463
- // `env -S 'prog args'` / `--split-string=…`: the value IS the command line.
464
- if (t === 'env' && (o === '-S' || o === '--split-string' || o.startsWith('--split-string=') || /^-S./.test(o))) {
465
- const prog = o.startsWith('--split-string=') ? o.slice('--split-string='.length) : /^-S./.test(o) ? o.slice(2) : words[i]?.text ?? '';
466
- if (!(o.startsWith('--split-string=') || /^-S./.test(o)))
467
- i++;
468
- words = [...shellWords(prog).words, ...words.slice(i)];
469
- i = 0;
470
- unwraps++;
471
- break;
472
- }
473
- if (withArg?.test(o) && i < words.length)
474
- i++;
475
- }
476
- if (t === 'env')
477
- while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i].text))
478
- i++;
479
- if (t === 'timeout' && i < words.length && /^[0-9.]+[smhd]?$/.test(words[i].text))
480
- i++;
481
- if (t === 'nice' && i < words.length && /^-?[0-9]+$/.test(words[i].text))
482
- i++;
483
- }
484
- return words.slice(i);
485
- }
57
+ const shell_syntax_1 = require("./shell-syntax");
58
+ var shell_syntax_2 = require("./shell-syntax");
59
+ Object.defineProperty(exports, "shellWords", { enumerable: true, get: function () { return shell_syntax_2.shellWords; } });
60
+ Object.defineProperty(exports, "commandOf", { enumerable: true, get: function () { return shell_syntax_2.commandOf; } });
486
61
  const READ_VERBS = new Set(['cat', 'less', 'more', 'head', 'tail', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'diff',
487
62
  'cmp', 'wc', 'stat', 'ls', 'file', 'bat', 'md5', 'md5sum', 'shasum', 'sha1sum', 'sha224sum', 'sha256sum', 'sha384sum',
488
63
  'sha512sum', 'b2sum', 'cksum', 'od', 'hexdump', 'xxd', 'strings', 'test', '[', 'realpath', 'readlink', 'basename',
@@ -653,6 +228,17 @@ const mentionsWiring = (text) => {
653
228
  // Rule 46: one memo — the single-slot one beside it made each defence untestable alone.
654
229
  return remembered(wiringAnswers, text, mentionsWiringUncached);
655
230
  };
231
+ /**
232
+ * @implements A-SPEC-728.2 — a quoted literal can be a computed target only when it is path-shaped: no whitespace after
233
+ * trimming, or a whole quoted path (rooted, relative-dotted, a drive letter, or a wiring file name first). A Markdown
234
+ * table row or a sentence that mentions `.ax` is prose (measured 2026-10-01: a docs rewrite was refused for one).
235
+ */
236
+ const pathShapedLiteral = (literal) => {
237
+ const t = literal.trim();
238
+ if (t === '')
239
+ return false;
240
+ return !/\s/.test(t) || /^(?:[/~]|\.{1,2}[/\\]|[A-Za-z]:[\\/])/.test(t) || write_target_1.WIRING_FILE_NAMES.some((n) => t.toLowerCase().startsWith(n));
241
+ };
656
242
  const mentionsWiringUncached = (text) => {
657
243
  const t = text.toLowerCase();
658
244
  if (write_target_1.WIRING_FILE_NAMES.some((n) => t.includes(n)) || /(^|[^\w.-])\.(?:claude|agents|codex|ax)(?![\w-])/.test(t))
@@ -780,7 +366,7 @@ const SHELLY = /\b(?:rm|unlink|mv|cp|tee|shred|truncate|dd|git|find|xargs|sh|bas
780
366
  function harnessWiringActOf(root, base, segmentText, fullText, env = process.env, home = os.homedir(), depth = 0) {
781
367
  if (depth > 8)
782
368
  return mentionsWiring(segmentText) ? 'a wiring file named in a command nested too deep to judge' : null;
783
- const { commands, subs, overflow } = shellWords(segmentText, env, home, base);
369
+ const { commands, subs, overflow } = (0, shell_syntax_1.shellWords)(segmentText, env, home, base);
784
370
  if (overflow)
785
371
  return 'a command too large to judge (brace expansion)';
786
372
  const absolute = (t) => path.isAbsolute(t) || /^[A-Za-z]:[\\/]/.test(t);
@@ -943,7 +529,7 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
943
529
  // A computed target in a program that quotes a wiring path (`p=".mcp.json"; os.remove(p)`).
944
530
  if (computed) {
945
531
  for (const m of program.matchAll(QUOTED_LITERAL))
946
- if (mentionsWiring(m[2]))
532
+ if (pathShapedLiteral(m[2]) && mentionsWiring(m[2]))
947
533
  return `${m[2]} (the target of a mutating call is computed from it)`;
948
534
  }
949
535
  return null;
@@ -993,13 +579,13 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
993
579
  k++;
994
580
  k++;
995
581
  }
996
- return judge(commandOf(rest.slice(k)), nest + 1);
582
+ return judge((0, shell_syntax_1.commandOf)(rest.slice(k)), nest + 1);
997
583
  }
998
584
  if (verb === 'npx' || verb === 'bunx' || verb === 'pnpx') {
999
585
  const call = callProgram(args);
1000
586
  if (call)
1001
587
  return call.known ? recurse(call.text, base) : (mentionsWiring(fullText) ? 'a wiring file named in a runner program that cannot be read' : null);
1002
- return judge(commandOf(afterFlags(args)), nest + 1);
588
+ return judge((0, shell_syntax_1.commandOf)(afterFlags(args)), nest + 1);
1003
589
  }
1004
590
  if ((verb === 'npm' || verb === 'pnpm' || verb === 'yarn') && pos.length > 0) {
1005
591
  // Global options may sit before the sub-command (`npm --prefix . exec`, `pnpm -C . exec`).
@@ -1010,11 +596,11 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1010
596
  const call = callProgram(rest);
1011
597
  if (call)
1012
598
  return call.known ? recurse(call.text, base) : (mentionsWiring(fullText) ? 'a wiring file named in a runner program that cannot be read' : null);
1013
- return judge(commandOf(afterFlags(rest)), nest + 1);
599
+ return judge((0, shell_syntax_1.commandOf)(afterFlags(rest)), nest + 1);
1014
600
  }
1015
601
  if (verb === 'yarn' && !['add', 'remove', 'install', 'upgrade', 'init', 'run', 'why', 'info', 'config', 'cache', 'global',
1016
602
  'workspace', 'workspaces', 'set', 'plugin', 'npm', 'pack', 'publish', 'list', 'outdated', 'link', 'unlink', 'test', 'build'].includes(sub)) {
1017
- return judge(commandOf(args.slice(args.indexOf(pos[0]))), nest + 1);
603
+ return judge((0, shell_syntax_1.commandOf)(args.slice(args.indexOf(pos[0]))), nest + 1);
1018
604
  }
1019
605
  return null; // their own sub-commands (`npm rm left-pad`, `npm run build`)
1020
606
  }
@@ -1535,7 +1121,7 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1535
1121
  let mutates = texts.includes('-delete');
1536
1122
  if (execAt >= 0) {
1537
1123
  const end = texts.findIndex((t, i) => i > execAt && (t === ';' || t === '+' || t === '\\;'));
1538
- const inner = commandOf(args.slice(execAt + 1, end < 0 ? undefined : end));
1124
+ const inner = (0, shell_syntax_1.commandOf)(args.slice(execAt + 1, end < 0 ? undefined : end));
1539
1125
  const iv = inner[0] ? verbName(inner[0].text) : '';
1540
1126
  mutates = mutates || (iv !== '' && !READ_VERBS.has(iv));
1541
1127
  // The exec'd command is a command: its own fixed arguments are judged (`-exec rm .mcp.json \;`).
@@ -1558,7 +1144,7 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1558
1144
  return first((starts.length > 0 ? starts : [{ text: '.', known: true, glob: false }]).map((w) => del(w, true)));
1559
1145
  }
1560
1146
  if (verb === 'xargs' || verb === 'parallel') {
1561
- const inner = commandOf(positionalsOf(args.filter((a, i) => !(i > 0 && /^-[IiLlnPdEsaj]$/.test(args[i - 1].text)))));
1147
+ const inner = (0, shell_syntax_1.commandOf)(positionalsOf(args.filter((a, i) => !(i > 0 && /^-[IiLlnPdEsaj]$/.test(args[i - 1].text)))));
1562
1148
  const iv = inner[0] ? verbName(inner[0].text) : '';
1563
1149
  if (iv === '' || READ_VERBS.has(iv))
1564
1150
  return null;
@@ -1584,7 +1170,7 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1584
1170
  return h;
1585
1171
  }
1586
1172
  for (const cmd of commands) {
1587
- const hit = first(cmd.redirects.map(wr)) ?? judge(commandOf(cmd.words));
1173
+ const hit = first(cmd.redirects.map(wr)) ?? judge((0, shell_syntax_1.commandOf)(cmd.words));
1588
1174
  if (hit)
1589
1175
  return hit;
1590
1176
  }
@@ -1604,6 +1190,7 @@ function harnessWiringActOfCommand(root, command, env = process.env, home = os.h
1604
1190
  if (command.length > exports.MAX_COMMAND) {
1605
1191
  return mentionsWiring(command) || /[$\\`'"{*?[]/.test(command) ? 'a command too large to judge that could name a wiring file' : null;
1606
1192
  }
1193
+ command = readLoopWordsNeutral(command);
1607
1194
  const run = () => {
1608
1195
  const loop = forLoopAct(root, command, env, home, startBase, depth, baseUnknown);
1609
1196
  if (loop)
@@ -1691,6 +1278,44 @@ const PATHS_JUDGED_MAX = 65_536;
1691
1278
  const PATHS_CHARS_MAX = 16 * 1024 * 1024;
1692
1279
  let pathsJudged = null;
1693
1280
  const FOR_RE = /(?:^|[\s;&|(])for[ \t]+([A-Za-z_]\w{0,63})[ \t]+in[ \t]+([^;\n]{0,1024})[;\n]\s*do\b/g;
1281
+ /**
1282
+ * @implements A-SPEC-728.2 — a `for` loop whose whole text the classifier judges a read (every body command a read form,
1283
+ * the variable only an argument — `"$f"` as a command is not a read) names no mutation target with its word list:
1284
+ * `for f in .ax/specs/…; do echo "---- $f"; cat "$f"; done` was refused as moving or deleting governance state (measured
1285
+ * 2026-10-01). The words are replaced before the identity rule reads the command; a word list holding a substitution, a
1286
+ * redirect or a pipe is left as written, and so is a loop the classifier does not call a read.
1287
+ */
1288
+ const READ_LOOP_WORDS = '__read_loop_words__';
1289
+ function readLoopWordsNeutral(command) {
1290
+ if (!/\bfor\b/.test(command) || !/\bdone\b/.test(command))
1291
+ return command;
1292
+ let out = command;
1293
+ let loops = 0;
1294
+ for (const m of command.matchAll(FOR_RE)) {
1295
+ if (++loops > 16)
1296
+ break;
1297
+ const words = m[2];
1298
+ if (/[$`<>()|&]/.test(words) || words.trim() === '')
1299
+ continue;
1300
+ const head = m[0].search(/for[ \t]/);
1301
+ const start = (m.index ?? 0) + head;
1302
+ const bodyStart = (m.index ?? 0) + m[0].length;
1303
+ const end = command.indexOf('done', bodyStart);
1304
+ if (end < 0)
1305
+ continue;
1306
+ const loop = command.slice(start, end + 4);
1307
+ // Only the loop's own variable, whole: a body that also reads another variable (`echo $a $b $c` inside three loops)
1308
+ // can assemble a word only substitution shows, and keeps the A-SPEC-728 rule 37 judgement.
1309
+ const own = new RegExp(String.raw `\$(?:\{${m[1]}\}|${m[1]}(?!\w))`, 'g');
1310
+ if (/[$`]/.test(command.slice(bodyStart, end).replace(own, '')))
1311
+ continue;
1312
+ if (!(0, risk_classifier_1.shellTextOnlyReads)(loop))
1313
+ continue;
1314
+ const at = loop.indexOf(words);
1315
+ out = out.replace(loop, `${loop.slice(0, at)}${READ_LOOP_WORDS}${loop.slice(at + words.length)}`);
1316
+ }
1317
+ return out;
1318
+ }
1694
1319
  function forLoopAct(root, command, env, home, startBase, depth, baseUnknown) {
1695
1320
  if (depth > 4)
1696
1321
  return null;
@@ -1704,7 +1329,7 @@ function forLoopAct(root, command, env, home, startBase, depth, baseUnknown) {
1704
1329
  const v = new RegExp(`"?\\$(?:\\{${m[1]}\\}|${m[1]}(?!\\w))"?`, 'g');
1705
1330
  if (!v.test(body))
1706
1331
  continue;
1707
- const words = shellWords(m[2], env, home, null).words.slice(0, 64);
1332
+ const words = (0, shell_syntax_1.shellWords)(m[2], env, home, null).words.slice(0, 64);
1708
1333
  for (const w of words) {
1709
1334
  const text = w.known ? w.text : '"$__unknown__"';
1710
1335
  if (++loopBudget.judged > LOOP_JUDGED_MAX || (loopBudget.bytes += body.length) > LOOP_BYTES_MAX)
@@ -51,6 +51,60 @@ export declare const PATH_FIELDS: readonly ["file_path", "notebook_path"];
51
51
  * the path field while leaving the name field open.
52
52
  */
53
53
  export declare function writesFiles(toolName: string | undefined, input: unknown): boolean;
54
+ /**
55
+ * The files a patch names, read from its text.
56
+ *
57
+ * @implements A-SPEC-163.1
58
+ * A patch tool carries no path field: its targets are the header lines of the patch. Measured 2026-10-04 on
59
+ * codex-cli 0.160.0 — `apply_patch` wrote an unanchored code file in a governed worktree and the gate, which asked
60
+ * `writesFiles` for a path FIELD, saw nothing to judge. Lines are matched by prefix (no pattern to back-track on),
61
+ * and a header with an empty path is returned as `path: ''` so the caller can refuse it rather than skip it.
62
+ */
63
+ /**
64
+ * @implements A-SPEC-163.2 — `hunk` is the text an update (or the move that follows it) applies; `from` is the file a
65
+ * move reads; `movedTo` marks an update whose result is written elsewhere, so the source is judged as a delete.
66
+ */
67
+ export interface PatchTarget {
68
+ path: string;
69
+ kind: 'add' | 'update' | 'delete' | 'move';
70
+ content?: string;
71
+ hunk?: string;
72
+ from?: string;
73
+ movedTo?: string;
74
+ }
75
+ /** More targets than this is not judged target by target; the caller refuses the patch (A-SPEC-163.2). */
76
+ export declare const PATCH_TARGETS_MAX = 64;
77
+ /** Whether a string carries a patch envelope: a begin line or any file header, at any indentation. */
78
+ export declare function hasPatchEnvelope(text: string): boolean;
79
+ /** A whole patch: the first non-blank line, trimmed, is the begin line (A-SPEC-163.2 rule 1). */
80
+ export declare function isWholePatch(text: string): boolean;
81
+ /**
82
+ * An indented line that would be a header after trimming: harnesses differ on whether it is a header or a context
83
+ * line, so the patch cannot be read one way (A-SPEC-163.2 rule 2).
84
+ */
85
+ export declare function patchAmbiguous(text: string): boolean;
86
+ /**
87
+ * Whether a text is the one patch form the gate judges.
88
+ *
89
+ * @implements A-SPEC-163.4 (rule 1)
90
+ * Four review rounds each found a shape the previous list of refused shapes did not name. This states what IS read:
91
+ * begin and end lines, the three file headers, a move directly after an update header, `+` lines in an add, and
92
+ * `@@` / ` ` / `+` / `-` / end-of-file lines in an update. Any other line — an empty one, an unknown `*** ` line, a
93
+ * header behind anything — makes the text not canonical, and the caller refuses it. A line-by-line prefix walk: no
94
+ * pattern over the whole text, nothing to back-track on.
95
+ */
96
+ export declare function canonicalPatch(text: string): boolean;
97
+ /** Every header is a target, in order; nothing is merged or dropped by path (A-SPEC-163.2 rule 2). */
98
+ export declare function patchTargetsOf(text: string): PatchTarget[];
99
+ /**
100
+ * The file an update hunk produces, or null when it does not apply.
101
+ *
102
+ * @implements A-SPEC-163.2 (rule 3)
103
+ * Chunks are separated by lines starting with `@@`; a chunk's old text is its ` ` and `-` lines. A kept line stays
104
+ * as the file has it. Plain line comparison: no pattern, nothing to back-track on. Where a chunk goes is A-SPEC-163.3's
105
+ * rule (below): its one place in the file, or no result.
106
+ */
107
+ export declare function applyPatchUpdate(original: string, hunk: string): string | null;
54
108
  /**
55
109
  * The file a raw path actually names.
56
110
  *