@holmes-lab/holmes-kit 0.35.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 (37) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +5 -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/risk-classifier.js +45 -24
  16. package/dist/holmes/guardrail/shell-argument-roles.d.ts +15 -0
  17. package/dist/holmes/guardrail/shell-argument-roles.js +209 -0
  18. package/dist/holmes/guardrail/shell-syntax.d.ts +20 -0
  19. package/dist/holmes/guardrail/shell-syntax.js +489 -0
  20. package/dist/holmes/guardrail/shell-words.d.ts +2 -18
  21. package/dist/holmes/guardrail/shell-words.js +15 -441
  22. package/dist/holmes/guardrail/write-target.d.ts +54 -0
  23. package/dist/holmes/guardrail/write-target.js +327 -1
  24. package/dist/holmes/hooks/pre-tool-use.d.ts +12 -0
  25. package/dist/holmes/hooks/pre-tool-use.js +377 -66
  26. package/dist/holmes/mcp/handlers.d.ts +9 -1
  27. package/dist/holmes/mcp/handlers.js +6 -4
  28. package/dist/holmes/mcp/operator-recovery.d.ts +9 -0
  29. package/dist/holmes/mcp/operator-recovery.js +63 -0
  30. package/dist/holmes/runtime/binding.d.ts +30 -0
  31. package/dist/holmes/runtime/binding.js +164 -0
  32. package/dist/holmes/runtime/dispatch.d.ts +9 -0
  33. package/dist/holmes/runtime/dispatch.js +169 -0
  34. package/dist/holmes/runtime/hook-process.d.ts +11 -0
  35. package/dist/holmes/runtime/hook-process.js +130 -0
  36. package/docs/install-guide.md +65 -0
  37. 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
@@ -56,434 +54,10 @@ const path = __importStar(require("node:path"));
56
54
  const linear_match_1 = require("./linear-match");
57
55
  const risk_classifier_1 = require("./risk-classifier");
58
56
  const write_target_1 = require("./write-target");
59
- const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*/;
60
- /**
61
- * `$NAME` / `${NAME[:-…]}` at `src[i]` → [value | null(unknown), length consumed, what an unknown
62
- * variable's default spells]. `${X:-word}` with X unknowable may expand to `word` (round 4).
63
- */
64
- function readVar(src, i, env, home, pwd) {
65
- const known = (name) => name === 'HOME' ? home : name === 'CODEX_HOME' && env.CODEX_HOME ? env.CODEX_HOME : name === 'PWD' ? pwd : null;
66
- if (src[i + 1] === '{') {
67
- const close = src.indexOf('}', i + 2);
68
- if (close < 0)
69
- return [null, src.length - i];
70
- const inner = src.slice(i + 2, close);
71
- const name = NAME_RE.exec(inner)?.[0] ?? '';
72
- const rest = inner.slice(name.length);
73
- // `${HOME}`, `${HOME:-x}`, `${HOME:?}`, `${HOME=…}`: the value is HOME's whenever HOME is set.
74
- const v = /^(?::?[-=?].*)?$/s.test(rest) ? known(name) : null;
75
- const dflt = /^:?[-=](.*)$/s.exec(rest)?.[1];
76
- return [v, close + 1 - i, v === null && dflt ? dflt.replace(/^(['"])(.*)\1$/s, '$2') : undefined];
77
- }
78
- // Linear: the name is read in place, never from a copy of the rest of the text (round 4).
79
- NAME_Y.lastIndex = i + 1;
80
- const name = NAME_Y.exec(src)?.[0];
81
- if (!name)
82
- return [null, 2];
83
- return [known(name), 1 + name.length];
84
- }
85
- const NAME_Y = /[A-Za-z_][A-Za-z0-9_]*/y;
86
- /** `$'…'` (ANSI-C quoting) starting at `src[i]` (the `$`) → [decoded text, index of the closing quote]. */
87
- function readAnsiC(src, i) {
88
- let out = '';
89
- let j = i + 2;
90
- const simple = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' };
91
- for (; j < src.length && src[j] !== "'"; j++) {
92
- if (src[j] !== '\\') {
93
- out += src[j];
94
- continue;
95
- }
96
- const n = src[j + 1] ?? '';
97
- // Sticky reads in place: a `.slice` per escape was quadratic on a long `$'…'` (round 4).
98
- const at = (re) => { re.lastIndex = j + 1; return re.exec(src); };
99
- const hex = at(HEX_Y);
100
- const oct = at(OCT_Y);
101
- const uni = at(UNI_Y);
102
- if (hex) {
103
- out += String.fromCharCode(parseInt(hex[1], 16));
104
- j += hex[0].length;
105
- continue;
106
- }
107
- if (uni) {
108
- const cp = parseInt(uni[1], 16);
109
- out += cp <= 0x10ffff ? String.fromCodePoint(cp) : '\ufffd';
110
- j += uni[0].length;
111
- continue;
112
- }
113
- if (oct) {
114
- out += String.fromCharCode(parseInt(oct[1], 8));
115
- j += oct[0].length;
116
- continue;
117
- }
118
- if (n in simple) {
119
- out += simple[n];
120
- j++;
121
- continue;
122
- }
123
- out += n;
124
- j++;
125
- }
126
- return [out, j];
127
- }
128
- const HEX_Y = /x([0-9a-fA-F]{1,2})/y;
129
- const OCT_Y = /([0-7]{1,3})/y;
130
- const UNI_Y = /[uU]([0-9a-fA-F]{1,8})/y;
131
- /** Index of the paren balancing the `(` at `src[i]`, or the end. */
132
- function balance(src, i) {
133
- let d = 0;
134
- for (let j = i; j < src.length; j++) {
135
- if (src[j] === '(')
136
- d++;
137
- else if (src[j] === ')' && --d === 0)
138
- return j;
139
- }
140
- return src.length - 1;
141
- }
142
- /**
143
- * Expand unquoted `{a,b}` lists (bounded), keeping quoted braces literal.
144
- * @implements A-SPEC-728 (round 8) — the total characters produced are bounded too (1 MB per segment):
145
- * counting alternatives alone let `{a,b}` × n copy the whole word at every level until a 4 GB heap
146
- * aborted the hook with no verdict (measured). Past the bound the word stays literal and is marked
147
- * unknowable (`overflow`), the conservative reading.
148
- */
149
- const BRACE_CHAR_BUDGET = 1024 * 1024;
150
- function expandBraces(chars, budget = { n: 64 }) {
151
- if (budget.chars === undefined)
152
- budget.chars = BRACE_CHAR_BUDGET;
153
- let depth = 0, open = -1;
154
- for (let i = 0; i < chars.length; i++) {
155
- const { c, q } = chars[i];
156
- if (q)
157
- continue;
158
- if (c === '{') {
159
- if (depth === 0)
160
- open = i;
161
- depth++;
162
- }
163
- else if (c === '}' && depth > 0) {
164
- depth--;
165
- if (depth === 0 && open >= 0) {
166
- const inner = chars.slice(open + 1, i);
167
- const alts = [];
168
- let d = 0, start = 0;
169
- for (let j = 0; j < inner.length; j++) {
170
- if (inner[j].q)
171
- continue;
172
- if (inner[j].c === '{')
173
- d++;
174
- else if (inner[j].c === '}')
175
- d--;
176
- else if (inner[j].c === ',' && d === 0) {
177
- alts.push(inner.slice(start, j));
178
- start = j + 1;
179
- }
180
- }
181
- if (alts.length === 0) {
182
- open = -1;
183
- continue;
184
- } // `{x}` is literal
185
- alts.push(inner.slice(start));
186
- const out = [];
187
- for (const a of alts) {
188
- if (budget.n-- <= 0)
189
- break;
190
- const size = open + a.length + (chars.length - i - 1);
191
- if ((budget.chars -= size) < 0) {
192
- budget.overflow = true;
193
- return [chars];
194
- }
195
- out.push(...expandBraces([...chars.slice(0, open), ...a, ...chars.slice(i + 1)], budget));
196
- }
197
- return out;
198
- }
199
- }
200
- }
201
- return [chars];
202
- }
203
- /**
204
- * The simple commands of one segment, as the shell would split and expand them. Operators split
205
- * commands (`;`, `&`, `|`, newline, `(`, `)` at a word start); redirect targets are collected per
206
- * command. `pwd` is the segment's working directory (for `~+` and `$PWD`), null when unknowable.
207
- */
208
- let USERNAME;
209
- function shellWords(src, env = process.env, home = os.homedir(), pwd = null) {
210
- // @implements A-SPEC-728 (rule 42) — read once per process: it ran for every segment (13% of a 256 KB command — measured).
211
- const me = USERNAME ?? (USERNAME = (() => { try {
212
- return os.userInfo().username;
213
- }
214
- catch {
215
- return '';
216
- } })());
217
- const commands = [];
218
- let cur = { words: [], redirects: [] };
219
- let chars = [];
220
- let inWord = false, known = true;
221
- let pending = null;
222
- const subs = [];
223
- const budget = { n: 4096 }; // brace expansions per segment; beyond it the segment is too large to judge
224
- const finishWord = () => {
225
- if (!inWord)
226
- return;
227
- let raw = chars;
228
- // Tilde at the start of an unquoted word: `~`, `~/…`, `~<me>`, `~+` (the working directory).
229
- if (raw.length > 0 && raw[0].c === '~' && !raw[0].q) {
230
- const slash = raw.findIndex((x) => x.c === '/');
231
- const user = raw.slice(1, slash < 0 ? raw.length : slash).map((x) => x.c).join('');
232
- const to = user === '' || user === me ? home : user === '+' ? pwd : null;
233
- if (to !== null)
234
- raw = [...[...to].map((c) => ({ c, q: true })), ...(slash < 0 ? [] : raw.slice(slash))];
235
- else
236
- known = false;
237
- }
238
- const expanded = expandBraces(raw, budget);
239
- if (budget.overflow)
240
- known = false;
241
- for (const w of expanded) {
242
- const full = w.map((x) => x.c).join('');
243
- const nul = full.indexOf('\0'); // an argument ends at NUL: `.mcp.json\0x` is `.mcp.json`
244
- const word = { text: nul >= 0 ? full.slice(0, nul) : full, known, glob: w.some((x) => !x.q && /[*?[(]/.test(x.c)) };
245
- if (pending === 'write')
246
- cur.redirects.push(word);
247
- else if (pending === null)
248
- cur.words.push(word);
249
- }
250
- pending = null;
251
- chars = [];
252
- inWord = false;
253
- known = true;
254
- };
255
- const endCommand = () => {
256
- finishWord();
257
- if (cur.words.length > 0 || cur.redirects.length > 0)
258
- commands.push(cur);
259
- cur = { words: [], redirects: [] };
260
- };
261
- const push = (c, q) => { chars.push({ c, q }); inWord = true; };
262
- const pushText = (t) => { for (const c of t)
263
- push(c, true); };
264
- for (let i = 0; i < src.length; i++) {
265
- const c = src[i];
266
- if (c === '\\') {
267
- const n = src[i + 1];
268
- if (n === '\n') {
269
- i++;
270
- continue;
271
- }
272
- if (n !== undefined) {
273
- push(n, true);
274
- i++;
275
- }
276
- continue;
277
- }
278
- if (c === '$' && src[i + 1] === "'") {
279
- const [t, end] = readAnsiC(src, i);
280
- inWord = true;
281
- pushText(t);
282
- i = end;
283
- continue;
284
- }
285
- if (c === "'") {
286
- const close = src.indexOf("'", i + 1);
287
- const end = close < 0 ? src.length : close;
288
- inWord = true;
289
- pushText(src.slice(i + 1, end));
290
- i = end;
291
- continue;
292
- }
293
- if (c === '"') {
294
- inWord = true;
295
- let j = i + 1;
296
- for (; j < src.length && src[j] !== '"'; j++) {
297
- if (src[j] === '\\' && /["\\$`\n]/.test(src[j + 1] ?? '')) {
298
- if (src[j + 1] !== '\n')
299
- push(src[j + 1], true);
300
- j++;
301
- continue;
302
- }
303
- if (src[j] === '$' && /[{A-Za-z_]/.test(src[j + 1] ?? '')) {
304
- const [v, len, dflt] = readVar(src, j, env, home, pwd);
305
- if (v === null) {
306
- known = false;
307
- if (dflt)
308
- pushText(dflt);
309
- }
310
- else
311
- pushText(v);
312
- j += len - 1;
313
- continue;
314
- }
315
- if (src[j] === '$' && src[j + 1] === '(') {
316
- const end = balance(src, j + 1);
317
- subs.push(src.slice(j + 2, end));
318
- known = false;
319
- j = end;
320
- continue;
321
- }
322
- if (src[j] === '`') {
323
- const close = src.indexOf('`', j + 1);
324
- const end = close < 0 ? src.length : close;
325
- subs.push(src.slice(j + 1, end));
326
- known = false;
327
- j = end;
328
- continue;
329
- }
330
- push(src[j], true);
331
- }
332
- i = j;
333
- continue;
334
- }
335
- if (c === '$' && src[i + 1] === '(') {
336
- const end = balance(src, i + 1);
337
- subs.push(src.slice(i + 2, end));
338
- known = false;
339
- inWord = true;
340
- i = end;
341
- continue;
342
- }
343
- if (c === '`') {
344
- const close = src.indexOf('`', i + 1);
345
- const end = close < 0 ? src.length : close;
346
- subs.push(src.slice(i + 1, end));
347
- known = false;
348
- inWord = true;
349
- i = end;
350
- continue;
351
- }
352
- if (c === '$' && /[{A-Za-z_]/.test(src[i + 1] ?? '')) {
353
- const [v, len, dflt] = readVar(src, i, env, home, pwd);
354
- if (v === null) {
355
- known = false;
356
- inWord = true;
357
- if (dflt)
358
- pushText(dflt);
359
- }
360
- else
361
- pushText(v);
362
- i += len - 1;
363
- continue;
364
- }
365
- if (/\s/.test(c)) {
366
- if (c === '\n')
367
- endCommand();
368
- else
369
- finishWord();
370
- continue;
371
- }
372
- // A `#` that starts a word starts a comment: the rest of the line is not run (round 4).
373
- if (c === '#' && !inWord) {
374
- const nl = src.indexOf('\n', i);
375
- i = (nl < 0 ? src.length : nl) - 1;
376
- continue;
377
- }
378
- // Process substitution `<(…)`/`>(…)`: one unknowable word; it does not end the command.
379
- if ((c === '<' || c === '>') && src[i + 1] === '(' && !inWord) {
380
- finishWord();
381
- const end = balance(src, i + 1);
382
- subs.push(src.slice(i + 2, end));
383
- cur.words.push({ text: src.slice(i, end + 1), known: false, glob: false });
384
- i = end;
385
- continue;
386
- }
387
- // Redirect operators: `N>`, `>`, `>>`, `>|`, `&>`, `&>>`, `<>`; `<`, `<<`, `<<<`, `>&N` read or dup.
388
- if (c === '>' || (c === '&' && src[i + 1] === '>') || (c === '<')) {
389
- const fdWord = inWord && chars.every((x) => /[0-9]/.test(x.c) && !x.q);
390
- if (fdWord) {
391
- chars = [];
392
- inWord = false;
393
- }
394
- else
395
- finishWord();
396
- let op = c;
397
- let j = i + 1;
398
- while (j < src.length && /[<>&|!]/.test(src[j]) && op.length < 3) {
399
- op += src[j];
400
- j++;
401
- }
402
- i = j - 1;
403
- if (/^&?>>?[|!]?$|^<>$/.test(op))
404
- pending = 'write';
405
- else if (/^>>?&$/.test(op)) {
406
- // `>&N`/`>&-` duplicates a descriptor; `>&WORD` (bash) writes stdout+stderr to WORD.
407
- let k = j;
408
- while (k < src.length && /[ \t]/.test(src[k]))
409
- k++;
410
- pending = /[0-9-]/.test(src[k] ?? '') && !/[^\s;&|]/.test(src[k + 1] ?? ' ') ? 'skip' : 'write';
411
- }
412
- else
413
- pending = 'skip'; // `<`, `<<`, `<<<`: input, delimiter or data
414
- continue;
415
- }
416
- // An unquoted `(…)` INSIDE a word is a zsh glob group (`.(mcp|x).json`, `@(…)`), part of the word.
417
- if (c === '(' && inWord) {
418
- const end = balance(src, i);
419
- for (const ch of src.slice(i, end + 1))
420
- push(ch, false);
421
- i = end;
422
- continue;
423
- }
424
- if (c === ';' || c === '|' || c === '&' || c === '(' || c === ')') {
425
- endCommand();
426
- continue;
427
- }
428
- push(c, false);
429
- }
430
- endCommand();
431
- return { commands, subs, overflow: budget.n <= 0, words: commands[0]?.words ?? [], redirects: commands[0]?.redirects ?? [] };
432
- }
433
- const WRAPPERS_WITH_ARG = {
434
- sudo: /^-[ugpChrtUD]$|^--(?:user|group|prompt|chdir|host|role|type|other-user)$/,
435
- doas: /^-[uC]$/,
436
- env: /^-u$|^--unset$|^-C$|^--chdir$/,
437
- nice: /^-n$|^--adjustment$/,
438
- stdbuf: /^-[ioe]$/,
439
- timeout: /^-[sk]$|^--(?:signal|kill-after)$/,
440
- };
441
- 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']);
442
- /** The words from the real command word on, behind wrappers, assignments and grouping keywords. */
443
- function commandOf(input) {
444
- let words = input;
445
- let i = 0;
446
- let unwraps = 0;
447
- while (i < words.length) {
448
- if (unwraps > 64)
449
- throw new Error('wrapper nesting too deep to judge');
450
- const t = words[i].text;
451
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)) {
452
- i++;
453
- continue;
454
- }
455
- if (!PLAIN_WRAPPERS.has(t))
456
- break;
457
- i++;
458
- const withArg = WRAPPERS_WITH_ARG[t];
459
- while (i < words.length && words[i].text.startsWith('-') && words[i].text !== '-') {
460
- const o = words[i].text;
461
- i++;
462
- if (o === '--')
463
- break;
464
- // `env -S 'prog args'` / `--split-string=…`: the value IS the command line.
465
- if (t === 'env' && (o === '-S' || o === '--split-string' || o.startsWith('--split-string=') || /^-S./.test(o))) {
466
- const prog = o.startsWith('--split-string=') ? o.slice('--split-string='.length) : /^-S./.test(o) ? o.slice(2) : words[i]?.text ?? '';
467
- if (!(o.startsWith('--split-string=') || /^-S./.test(o)))
468
- i++;
469
- words = [...shellWords(prog).words, ...words.slice(i)];
470
- i = 0;
471
- unwraps++;
472
- break;
473
- }
474
- if (withArg?.test(o) && i < words.length)
475
- i++;
476
- }
477
- if (t === 'env')
478
- while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i].text))
479
- i++;
480
- if (t === 'timeout' && i < words.length && /^[0-9.]+[smhd]?$/.test(words[i].text))
481
- i++;
482
- if (t === 'nice' && i < words.length && /^-?[0-9]+$/.test(words[i].text))
483
- i++;
484
- }
485
- return words.slice(i);
486
- }
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; } });
487
61
  const READ_VERBS = new Set(['cat', 'less', 'more', 'head', 'tail', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'diff',
488
62
  'cmp', 'wc', 'stat', 'ls', 'file', 'bat', 'md5', 'md5sum', 'shasum', 'sha1sum', 'sha224sum', 'sha256sum', 'sha384sum',
489
63
  'sha512sum', 'b2sum', 'cksum', 'od', 'hexdump', 'xxd', 'strings', 'test', '[', 'realpath', 'readlink', 'basename',
@@ -792,7 +366,7 @@ const SHELLY = /\b(?:rm|unlink|mv|cp|tee|shred|truncate|dd|git|find|xargs|sh|bas
792
366
  function harnessWiringActOf(root, base, segmentText, fullText, env = process.env, home = os.homedir(), depth = 0) {
793
367
  if (depth > 8)
794
368
  return mentionsWiring(segmentText) ? 'a wiring file named in a command nested too deep to judge' : null;
795
- const { commands, subs, overflow } = shellWords(segmentText, env, home, base);
369
+ const { commands, subs, overflow } = (0, shell_syntax_1.shellWords)(segmentText, env, home, base);
796
370
  if (overflow)
797
371
  return 'a command too large to judge (brace expansion)';
798
372
  const absolute = (t) => path.isAbsolute(t) || /^[A-Za-z]:[\\/]/.test(t);
@@ -1005,13 +579,13 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1005
579
  k++;
1006
580
  k++;
1007
581
  }
1008
- return judge(commandOf(rest.slice(k)), nest + 1);
582
+ return judge((0, shell_syntax_1.commandOf)(rest.slice(k)), nest + 1);
1009
583
  }
1010
584
  if (verb === 'npx' || verb === 'bunx' || verb === 'pnpx') {
1011
585
  const call = callProgram(args);
1012
586
  if (call)
1013
587
  return call.known ? recurse(call.text, base) : (mentionsWiring(fullText) ? 'a wiring file named in a runner program that cannot be read' : null);
1014
- return judge(commandOf(afterFlags(args)), nest + 1);
588
+ return judge((0, shell_syntax_1.commandOf)(afterFlags(args)), nest + 1);
1015
589
  }
1016
590
  if ((verb === 'npm' || verb === 'pnpm' || verb === 'yarn') && pos.length > 0) {
1017
591
  // Global options may sit before the sub-command (`npm --prefix . exec`, `pnpm -C . exec`).
@@ -1022,11 +596,11 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1022
596
  const call = callProgram(rest);
1023
597
  if (call)
1024
598
  return call.known ? recurse(call.text, base) : (mentionsWiring(fullText) ? 'a wiring file named in a runner program that cannot be read' : null);
1025
- return judge(commandOf(afterFlags(rest)), nest + 1);
599
+ return judge((0, shell_syntax_1.commandOf)(afterFlags(rest)), nest + 1);
1026
600
  }
1027
601
  if (verb === 'yarn' && !['add', 'remove', 'install', 'upgrade', 'init', 'run', 'why', 'info', 'config', 'cache', 'global',
1028
602
  'workspace', 'workspaces', 'set', 'plugin', 'npm', 'pack', 'publish', 'list', 'outdated', 'link', 'unlink', 'test', 'build'].includes(sub)) {
1029
- 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);
1030
604
  }
1031
605
  return null; // their own sub-commands (`npm rm left-pad`, `npm run build`)
1032
606
  }
@@ -1547,7 +1121,7 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1547
1121
  let mutates = texts.includes('-delete');
1548
1122
  if (execAt >= 0) {
1549
1123
  const end = texts.findIndex((t, i) => i > execAt && (t === ';' || t === '+' || t === '\\;'));
1550
- 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));
1551
1125
  const iv = inner[0] ? verbName(inner[0].text) : '';
1552
1126
  mutates = mutates || (iv !== '' && !READ_VERBS.has(iv));
1553
1127
  // The exec'd command is a command: its own fixed arguments are judged (`-exec rm .mcp.json \;`).
@@ -1570,7 +1144,7 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1570
1144
  return first((starts.length > 0 ? starts : [{ text: '.', known: true, glob: false }]).map((w) => del(w, true)));
1571
1145
  }
1572
1146
  if (verb === 'xargs' || verb === 'parallel') {
1573
- 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)))));
1574
1148
  const iv = inner[0] ? verbName(inner[0].text) : '';
1575
1149
  if (iv === '' || READ_VERBS.has(iv))
1576
1150
  return null;
@@ -1596,7 +1170,7 @@ function harnessWiringActOf(root, base, segmentText, fullText, env = process.env
1596
1170
  return h;
1597
1171
  }
1598
1172
  for (const cmd of commands) {
1599
- 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));
1600
1174
  if (hit)
1601
1175
  return hit;
1602
1176
  }
@@ -1755,7 +1329,7 @@ function forLoopAct(root, command, env, home, startBase, depth, baseUnknown) {
1755
1329
  const v = new RegExp(`"?\\$(?:\\{${m[1]}\\}|${m[1]}(?!\\w))"?`, 'g');
1756
1330
  if (!v.test(body))
1757
1331
  continue;
1758
- 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);
1759
1333
  for (const w of words) {
1760
1334
  const text = w.known ? w.text : '"$__unknown__"';
1761
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
  *