@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
@@ -44,12 +44,14 @@ exports.classifyArchitectureReversal = classifyArchitectureReversal;
44
44
  exports.classifySecret = classifySecret;
45
45
  exports.classifyBlastRadius = classifyBlastRadius;
46
46
  exports.assessRisk = assessRisk;
47
- // @implements A-SPEC-125.1, A-SPEC-627, A-SPEC-728, A-SPEC-737, A-SPEC-747
47
+ // @implements A-SPEC-125.1, A-SPEC-627, A-SPEC-728, A-SPEC-737, A-SPEC-747, A-SPEC-753
48
48
  const fs = __importStar(require("node:fs"));
49
49
  const path = __importStar(require("node:path"));
50
+ const shell_argument_roles_1 = require("./shell-argument-roles");
51
+ const write_target_1 = require("./write-target");
50
52
  const risk_types_1 = require("./risk-types");
51
53
  const linear_match_1 = require("./linear-match");
52
- const write_target_1 = require("./write-target");
54
+ const write_target_2 = require("./write-target");
53
55
  const AWS_KEY_RE = /AKIA[0-9A-Z]{16}/;
54
56
  const PEM_KEY_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
55
57
  const SECRET_KV_RE = /(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S{6,}/i;
@@ -313,6 +315,12 @@ function normalizeWindowsPathSpellings(cmd) {
313
315
  .replace(/(^|[\s'"=(])\/([A-Za-z])\/(?=[^\s'"()/])/g, (_m, pre, d) => `${pre}${d.toLowerCase()}:/`);
314
316
  }
315
317
  function scopeAxToProject(cmd, projectRoot) {
318
+ return scopeAxWithPlaceholder(cmd, projectRoot, false);
319
+ }
320
+ // Keep the diagnostic representation stable, but never introduce shell operators into text
321
+ // that will be classified again: a synthetic `>` can target the next real governance path.
322
+ function scopeAxWithPlaceholder(cmd, projectRoot, forClassification) {
323
+ const placeholder = forClassification ? '__other_project_path__' : '<other-project-path>';
316
324
  const spelled = normalizeWindowsPathSpellings(cmd);
317
325
  if (!projectRoot)
318
326
  return spelled;
@@ -329,7 +337,10 @@ function scopeAxToProject(cmd, projectRoot) {
329
337
  // time: the regex rescanned each run of path characters from every `=` (256 KB of `=/` met the hook's 20 s wall —
330
338
  // measured). A match lies inside one maximal run of `[^\s'"()]` and extends to its end, so each run needs only its last
331
339
  // `/.ax/` and its leftmost start: the run's first character after a boundary other than `)`, or one after an `=` inside it.
332
- const RUN = /[^\s'"()]+/g;
340
+ // Preserve shell syntax attached to a masked path: redirects, control operators,
341
+ // substitution delimiters and escapes must reach the downstream shell checks intact.
342
+ // The public diagnostic rendering retains its historical contract.
343
+ const RUN = forClassification ? /[^\s'"();&|<>`$\\]+/g : /[^\s'"()]+/g;
333
344
  let out = '';
334
345
  let last = 0;
335
346
  for (let m = RUN.exec(spelled); m !== null; m = RUN.exec(spelled)) {
@@ -353,7 +364,7 @@ function scopeAxToProject(cmd, projectRoot) {
353
364
  continue;
354
365
  const pre = start === 0 ? '' : spelled[start - 1];
355
366
  const abs = spelled.slice(start, b);
356
- out += spelled.slice(last, start === 0 ? 0 : start - 1) + (inside(abs) ? pre + abs : `${pre}<other-project-path>`);
367
+ out += spelled.slice(last, start === 0 ? 0 : start - 1) + (inside(abs) ? pre + abs : pre + placeholder);
357
368
  last = b;
358
369
  }
359
370
  return out + spelled.slice(last);
@@ -403,7 +414,7 @@ function redirectTargetsUnder(text, ax) {
403
414
  return text;
404
415
  // Rule 36: the digits have their own lookbehind; the operator only must not follow `<`/`>` (`2>&1>ledger/x` matched no
405
416
  // start and passed — measured).
406
- const re = new RegExp(`((?:(?<![0-9&<>])(?:[0-9]+|&))?(?<![<>])(?:>{1,2}[|!&]?|<>)[ \\t]*)(['"]?)(?:\\./)*((?:${write_target_1.AX_PROTECTED_CHILDREN.join('|')})(?:/[^\\s'"<>|;&()]*)?)(?=[\\s'"<>|;&()]|$)`, 'g');
417
+ const re = new RegExp(`((?:(?<![0-9&<>])(?:[0-9]+|&))?(?<![<>])(?:>{1,2}[|!&]?|<>)[ \\t]*)(['"]?)(?:\\./)*((?:${write_target_2.AX_PROTECTED_CHILDREN.join('|')})(?:/[^\\s'"<>|;&()]*)?)(?=[\\s'"<>|;&()]|$)`, 'g');
407
418
  return text.replace(re, (whole, op, q, p, at) => (masked[at + op.indexOf('>')] === '>' ? `${op}${q}${ax}/${p}` : whole));
408
419
  }
409
420
  /**
@@ -426,8 +437,8 @@ function cdReachesStore(cb, start, rootAx) {
426
437
  const realAx = real(rootAx);
427
438
  const seen = new Set();
428
439
  for (const arg of cb.literal) {
429
- for (const b of (0, write_target_1.absoluteKindOf)(arg) !== null ? [arg] : bases) {
430
- const to = (0, write_target_1.absoluteKindOf)(arg) !== null ? (0, write_target_1.pathFlavorFor)(arg, arg).resolve(arg) : (0, write_target_1.pathFlavorFor)(b, arg).resolve(b, arg);
440
+ for (const b of (0, write_target_2.absoluteKindOf)(arg) !== null ? [arg] : bases) {
441
+ const to = (0, write_target_2.absoluteKindOf)(arg) !== null ? (0, write_target_2.pathFlavorFor)(arg, arg).resolve(arg) : (0, write_target_2.pathFlavorFor)(b, arg).resolve(b, arg);
431
442
  if (seen.has(to))
432
443
  continue;
433
444
  seen.add(to);
@@ -491,7 +502,7 @@ function segmentFlattened(cmd, root, start = root) {
491
502
  });
492
503
  };
493
504
  // Round 17: from the directory the harness runs the shell in (`start`), not always the root.
494
- const segments = (0, write_target_1.shellSegments)(cmd, start);
505
+ const segments = (0, write_target_2.shellSegments)(cmd, start);
495
506
  // @implements A-SPEC-728 (round 11) — a null-base segment MAY run in any base the command produced
496
507
  // (`maybe`); the ones under `.ax` matter, keyed by the top-level `.ax` child so the rewrite count is
497
508
  // bounded by the store's layout, not the command's length (measured: `git log; cd sub; cd ../.ax;
@@ -509,12 +520,12 @@ function segmentFlattened(cmd, root, start = root) {
509
520
  // @implements A-SPEC-728 (round 23) — every segment is also judged from every directory under `.ax` the command may
510
521
  // run ANY part in (flow-insensitive): a loop, a function or a trap runs text after a later `cd .ax` (measured: `for …;
511
522
  // do rm ledger/provenance.jsonl; cd .ax; done` deleted the ledger). An unknown set on a `.ax` mention adds `.ax`.
512
- const cb = (0, write_target_1.commandBases)(cmd, start, segments);
523
+ const cb = (0, write_target_2.commandBases)(cmd, start, segments);
513
524
  for (const b of cb.bases)
514
525
  candidates.add(b);
515
- if (cb.unknown !== null && (0, write_target_1.mentionsAxSpelling)(cmd)) {
526
+ if (cb.unknown !== null && (0, write_target_2.mentionsAxSpelling)(cmd)) {
516
527
  candidates.add(path.join(start, '.ax'));
517
- for (const c of write_target_1.AX_PROTECTED_CHILDREN)
528
+ for (const c of write_target_2.AX_PROTECTED_CHILDREN)
518
529
  candidates.add(path.join(start, '.ax', c));
519
530
  }
520
531
  // @implements A-SPEC-728 (rule 39) — a store key is only as deep as the command's longest `../` climb needs (a `cd` 1,000
@@ -522,7 +533,7 @@ function segmentFlattened(cmd, root, start = root) {
522
533
  let climb = 0;
523
534
  for (const m of cmd.matchAll(/(?:\.\.[\\/])+/g))
524
535
  climb = Math.max(climb, m[0].length / 3);
525
- const keys = (0, write_target_1.axCandidateKeys)(root, candidates, climb + 1);
536
+ const keys = (0, write_target_2.axCandidateKeys)(root, candidates, climb + 1);
526
537
  const forms = [];
527
538
  // @implements A-SPEC-728 (rule 44) — every form is kept within one budget: past FORMS_MAX characters the command is too large
528
539
  // to judge (after `cd .ax; cd "$X"`, `sed -i` over 131,000 words was rewritten at the store and each protected child, ~150 MB
@@ -537,10 +548,10 @@ function segmentFlattened(cmd, root, start = root) {
537
548
  // @implements A-SPEC-728 (round 24) — an unknown set on a command that never spells `.ax`: a path whose first component is a
538
549
  // protected `.ax` child is judged under the store too (`cd "$(printf '.%s' ax)" && echo x > ledger/provenance.jsonl` was
539
550
  // allowed — measured). Only those paths, so an ordinary relative write is not read as a store write.
540
- const axChildren = cb.unknown !== null && !(0, write_target_1.mentionsAxSpelling)(cmd) ? path.join(root, '.ax') : null;
551
+ const axChildren = cb.unknown !== null && !(0, write_target_2.mentionsAxSpelling)(cmd) ? path.join(root, '.ax') : null;
541
552
  // Round 25: `./ledger/…` too. Round 28: after `=` and `(`, before `)`/`>`/`;`/`&`/`|`, with glob and brace characters
542
553
  // (`cp a --target-directory=ledger`, `rm ledger/*` — measured).
543
- const childRe = new RegExp(`(^|[\\s>|=(])(['"]?)(?:\\./)*((?:${write_target_1.AX_PROTECTED_CHILDREN.join('|')})(?:/[^\\s'"<>|;&()]*)?)(?=[\\s'"<>|;&()]|$)`, 'g');
554
+ const childRe = new RegExp(`(^|[\\s>|=(])(['"]?)(?:\\./)*((?:${write_target_2.AX_PROTECTED_CHILDREN.join('|')})(?:/[^\\s'"<>|;&()]*)?)(?=[\\s'"<>|;&()]|$)`, 'g');
544
555
  // Round 26: only a segment that writes or removes (reads of an ordinary top-level `specs/` after a computed cd were
545
556
  // denied — measured).
546
557
  // Round 27: inverted — a segment skips this reading only when it is recognisably read-only and redirects nothing into a
@@ -563,7 +574,7 @@ function segmentFlattened(cmd, root, start = root) {
563
574
  // regression); rule 37 read it never, which let 64 no-op cds before `eval 'cd axl/specs/01_req'` carry `sed -i` into the
564
575
  // store. Past 16,384 argument-base pairs the store is read without looking.
565
576
  const rootAx = path.join(root, '.ax');
566
- const storeBases = cb.unknown !== null && cdReachesStore(cb, start, rootAx) ? [rootAx, ...write_target_1.AX_PROTECTED_CHILDREN.map((c) => path.join(rootAx, c))] : [];
577
+ const storeBases = cb.unknown !== null && cdReachesStore(cb, start, rootAx) ? [rootAx, ...write_target_2.AX_PROTECTED_CHILDREN.map((c) => path.join(rootAx, c))] : [];
567
578
  const fed = axChildren === null && storeBases.length === 0 ? new Set() : feedsAShell(segments);
568
579
  for (const [i, s] of segments.entries()) {
569
580
  if ((axChildren !== null || storeBases.length > 0) && !s.data) {
@@ -584,9 +595,9 @@ function segmentFlattened(cmd, root, start = root) {
584
595
  add(s.text);
585
596
  if (s.maybe || keys.bases.length > 0) {
586
597
  // @implements A-SPEC-728 (rule 44) — past 8 climb bases the command is too large to judge (60 rewrites of 256 KB — measured).
587
- const climbs = (0, write_target_1.axClimbBases)(root, keys, s.text);
588
- if (climbs.length > write_target_1.AX_CLIMB_BASES_MAX)
589
- throw new RangeError(`a command too large to judge at every directory it may run in under .ax (more than ${write_target_1.AX_CLIMB_BASES_MAX} climbs)`);
598
+ const climbs = (0, write_target_2.axClimbBases)(root, keys, s.text);
599
+ if (climbs.length > write_target_2.AX_CLIMB_BASES_MAX)
600
+ throw new RangeError(`a command too large to judge at every directory it may run in under .ax (more than ${write_target_2.AX_CLIMB_BASES_MAX} climbs)`);
590
601
  for (const k of keys.bases)
591
602
  add(rewrite(s.text, k));
592
603
  for (const k of climbs)
@@ -1536,7 +1547,7 @@ function shellWritesProtectedAx(ncmd) {
1536
1547
  */
1537
1548
  function classifyReversibility(action) {
1538
1549
  const raw = action.command ?? '';
1539
- const joined = raw === '' ? raw : (0, write_target_1.joinShellText)(raw);
1550
+ const joined = raw === '' ? raw : (0, write_target_2.joinShellText)(raw);
1540
1551
  if (joined === raw)
1541
1552
  return classifyReversibilityAsWritten(action);
1542
1553
  const a = classifyReversibilityAsWritten(action);
@@ -1565,12 +1576,22 @@ function classifyReversibilityAsWritten(action) {
1565
1576
  // followed a cd the shell never ran (`cd /nonexistent && true; echo x > .ax/ledger/p.jsonl` became an
1566
1577
  // other-project path and was allowed — measured). Judging both only ever adds refusals.
1567
1578
  // A-SPEC-728.2 — a commit message is text the `.ax` rules do not read.
1568
- const axCmd = stripCommitMessages(cmd);
1569
- const flat = scopeAxToProject(normalizeCommandPaths(axCmd), action.projectRoot);
1570
- const asWritten = scopeAxToProject(normalizeCommandPaths(axCmd, false), action.projectRoot);
1579
+ const roles = (0, shell_argument_roles_1.shellArgumentRoles)(cmd, action.cwd ?? action.projectRoot ?? null);
1580
+ if (action.projectRoot) {
1581
+ for (const output of roles.outputPaths) {
1582
+ const kind = (0, write_target_1.wiringWriteKindOf)(action.projectRoot, action.cwd ?? action.projectRoot, output);
1583
+ if (kind)
1584
+ return { axis, level: 'hard-hitl', reasons: [`CLI output option writes protected ${kind}`] };
1585
+ }
1586
+ }
1587
+ const axCmd = stripCommitMessages(roles.governanceText);
1588
+ const scopeForClassification = (text) => scopeAxWithPlaceholder(text, action.projectRoot, true);
1589
+ const flat = scopeForClassification(normalizeCommandPaths(axCmd));
1590
+ const asWritten = scopeForClassification(normalizeCommandPaths(axCmd, false));
1571
1591
  // Round 10: and with every segment at the base the certain-cd model gives it (a second cd into .ax).
1572
- const bySegment = action.projectRoot ? scopeAxToProject(normalizeCommandPaths(segmentFlattened(axCmd, action.projectRoot, action.cwd ?? action.projectRoot), false), action.projectRoot) : asWritten;
1573
- const ncmd = [...new Set([flat, asWritten, bySegment])].join('\n');
1592
+ const bySegment = action.projectRoot ? scopeForClassification(normalizeCommandPaths(segmentFlattened(axCmd, action.projectRoot, action.cwd ?? action.projectRoot), false)) : asWritten;
1593
+ const outputTargets = roles.outputPaths.map(p => scopeForClassification(normalizeCommandPaths(p, false)));
1594
+ const ncmd = [...new Set([flat, asWritten, bySegment, ...outputTargets])].join('\n');
1574
1595
  // @implements A-SPEC-737 — one reason served all four channels, so an interpreter READ was refused as
1575
1596
  // a "removal command" and the author could not tell what to change. Each channel names itself.
1576
1597
  const axChannel = REMOVAL_VERB_RE.test(ncmd) && CMD_PROTECTED_AX_RE.test(ncmd)
@@ -0,0 +1,15 @@
1
+ export interface ArgumentRoles {
2
+ /** Original syntax, except proven literal prompt operands; never a permission decision. */
3
+ governanceText: string;
4
+ /** Original executable syntax, with proven script/search data operands neutralized. */
5
+ serverText: string;
6
+ /** Potential output identities at each plausible CLI base; shell redirects remain in source. */
7
+ outputPaths: string[];
8
+ }
9
+ /**
10
+ * @implements A-SPEC-753.1 — whether a command is the documented installer, and whether it applies or only previews.
11
+ * Measured 2026-10-04: the apply form was refused as a server start (A-SPEC-732), which it is not; the caller needs to
12
+ * know the act to name it. One command, every word certain, no substitution and no redirect — anything else is null.
13
+ */
14
+ export declare function installerInvocationOf(command: string, cwd?: string | null): 'preview' | 'apply' | null;
15
+ export declare function shellArgumentRoles(command: string, cwd?: string | null): ArgumentRoles;
@@ -0,0 +1,209 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.installerInvocationOf = installerInvocationOf;
37
+ exports.shellArgumentRoles = shellArgumentRoles;
38
+ // @implements A-SPEC-753
39
+ const path = __importStar(require("node:path"));
40
+ const shell_syntax_1 = require("./shell-syntax");
41
+ const LIMIT = 256 * 1024;
42
+ const nameOf = (text) => path.posix.basename(text.replace(/\\/g, '/')).replace(/\.exe$/i, '').toLowerCase();
43
+ const certain = (word) => word.known && !word.glob && word.sourceStart !== undefined && word.sourceEnd !== undefined;
44
+ const noValue = new Set(['--json', '--ephemeral', '--skip-git-repo-check', '--strict-config', '--worktree', '--oss']);
45
+ const withValue = new Set(['-m', '--model', '--local-provider', '--color', '--thread-source', '-C', '--cd', '--add-dir', '--output-schema', '-o', '--output-last-message']);
46
+ function mask(source, words) {
47
+ const sorted = words.filter(certain).sort((a, b) => a.sourceStart - b.sourceStart);
48
+ let out = '', at = 0;
49
+ for (const word of sorted) {
50
+ if (word.sourceStart < at)
51
+ continue;
52
+ out += source.slice(at, word.sourceStart) + '__holmes_literal_argument__';
53
+ at = word.sourceEnd;
54
+ }
55
+ return out + source.slice(at);
56
+ }
57
+ function optionValue(words, i) {
58
+ const text = words[i].text;
59
+ const equals = text.indexOf('=');
60
+ if (equals > 0 && withValue.has(text.slice(0, equals)))
61
+ return { option: text.slice(0, equals), value: text.slice(equals + 1), last: i };
62
+ if (/^-[mCo].+/.test(text))
63
+ return { option: text.slice(0, 2), value: text.slice(2), last: i };
64
+ if (!withValue.has(text) || !words[i + 1] || words[i + 1].text.startsWith('-'))
65
+ return null;
66
+ return { option: text, value: words[i + 1].text, last: i + 1 };
67
+ }
68
+ /** Narrow grammar, not a CLI allowlist. Unknown roles retain the untouched command. */
69
+ function codexPrompt(words, base) {
70
+ if (nameOf(words[0]?.text ?? '') !== 'codex' || words[1]?.text !== 'exec' || !words.every(certain))
71
+ return null;
72
+ let prompt, endOptions = false;
73
+ const directories = [], outputs = [];
74
+ for (let i = 2; i < words.length; i++) {
75
+ const word = words[i], text = word.text;
76
+ if (!endOptions && text === '--') {
77
+ endOptions = true;
78
+ continue;
79
+ }
80
+ if (!endOptions && noValue.has(text))
81
+ continue;
82
+ if (!endOptions && text.startsWith('-')) {
83
+ const value = optionValue(words, i);
84
+ if (!value || value.value.length === 0)
85
+ return null;
86
+ if (value.option === '-C' || value.option === '--cd')
87
+ directories.push(value.value);
88
+ if (value.option === '-o' || value.option === '--output-last-message')
89
+ outputs.push(value.value);
90
+ i = value.last;
91
+ continue;
92
+ }
93
+ if (prompt || text === '-' || (!endOptions && ['resume', 'fork', 'review', 'help'].includes(text)))
94
+ return null;
95
+ prompt = word;
96
+ }
97
+ // Multiple --cd semantics are not established; no exemption for ambiguous bases.
98
+ if (directories.length > 1 || (!base && outputs.some(p => !path.isAbsolute(p))))
99
+ return null;
100
+ const bases = base ? [base, ...directories.map(p => path.resolve(base, p))] : [];
101
+ return { prompt, outputs: outputs.flatMap(p => path.isAbsolute(p) ? [p] : bases.map(b => path.resolve(b, p))) };
102
+ }
103
+ function searchData(words) {
104
+ if (!['rg', 'grep', 'egrep', 'fgrep'].includes(nameOf(words[0]?.text ?? '')) || !words.every(certain))
105
+ return [];
106
+ const flags = /^(?:-[nrilHEFsvwox]+|--hidden|--line-number|--files-with-matches|--ignore-case|--fixed-strings)$/;
107
+ for (let i = 1; i < words.length; i++) {
108
+ const text = words[i].text;
109
+ if (flags.test(text))
110
+ continue;
111
+ if (text.startsWith('-'))
112
+ return [];
113
+ // Unknown options anywhere may introduce executable behavior, e.g. rg --pre.
114
+ if (words.slice(i + 1).some(w => w.text.startsWith('-')))
115
+ return [];
116
+ return [words[i]];
117
+ }
118
+ return [];
119
+ }
120
+ const INSTALLER_VALUED = new Set(['--workspace', '--package', '--release-package', '--registry', '--activate-hooks']);
121
+ /** The documented installer grammar over one command's words: its package operands and whether it only previews. */
122
+ function installerWords(words, operations, everySpelling = false) {
123
+ if (!words.every(certain))
124
+ return null;
125
+ // Node argv may itself be a runner's program. Only the documented Holmes setup grammar
126
+ // establishes data roles here; arbitrary scripts, startup options and runner CLIs retain text.
127
+ let at;
128
+ if (['node', 'nodejs'].includes(nameOf(words[0]?.text ?? ''))) {
129
+ if (!/(?:^|\/)bin\/holmes-kit\.js$/.test((words[1]?.text ?? '').replace(/\\/g, '/')))
130
+ return null;
131
+ at = 2;
132
+ }
133
+ else if (everySpelling && installerBinName(words[0]?.text ?? '') === 'holmes-kit') {
134
+ // @implements A-SPEC-753.2 — the installed bin is the same program under another spelling.
135
+ at = 1;
136
+ }
137
+ else
138
+ return null;
139
+ if (words[at]?.text !== 'runtime-binding' || !operations.includes(words[at + 1]?.text ?? ''))
140
+ return null;
141
+ const data = [];
142
+ let preview = false;
143
+ for (let i = at + 2; i < words.length; i++) {
144
+ const flag = words[i].text;
145
+ if (flag === '--dry-run') {
146
+ preview = true;
147
+ continue;
148
+ }
149
+ // @implements A-SPEC-753.2 — `--name=value` is the spelling the CLI also accepts; an empty value is not the grammar.
150
+ const eq = everySpelling ? flag.indexOf('=') : -1;
151
+ if (eq !== -1) {
152
+ if (!INSTALLER_VALUED.has(flag.slice(0, eq)) || eq === flag.length - 1)
153
+ return null;
154
+ continue;
155
+ }
156
+ if (!INSTALLER_VALUED.has(flag) || !words[i + 1] || words[i + 1].text.startsWith('-'))
157
+ return null;
158
+ const value = words[++i];
159
+ if (flag === '--package' || flag === '--release-package')
160
+ data.push(value);
161
+ }
162
+ return { data, preview };
163
+ }
164
+ /** The last path segment of a command word without a Windows launcher suffix. */
165
+ function installerBinName(text) {
166
+ const base = text.replace(/\\/g, '/').split('/').pop() ?? '';
167
+ const lower = base.toLowerCase();
168
+ return lower.endsWith('.cmd') || lower.endsWith('.exe') ? base.slice(0, -4) : base;
169
+ }
170
+ /** A-SPEC-753.2 rule 4: the data-role masking stays with the measured `node …` preview spelling. */
171
+ function nodeData(words) {
172
+ const installer = installerWords(words, ['setup']);
173
+ return installer?.preview ? installer.data : [];
174
+ }
175
+ /** @implements A-SPEC-753.2 — a longer command, or one with a line break, is not the installer grammar. */
176
+ const INSTALLER_COMMAND_MAX = 4096;
177
+ /**
178
+ * @implements A-SPEC-753.1 — whether a command is the documented installer, and whether it applies or only previews.
179
+ * Measured 2026-10-04: the apply form was refused as a server start (A-SPEC-732), which it is not; the caller needs to
180
+ * know the act to name it. One command, every word certain, no substitution and no redirect — anything else is null.
181
+ */
182
+ function installerInvocationOf(command, cwd = null) {
183
+ if (command.length > LIMIT || command.length > INSTALLER_COMMAND_MAX || command.includes('\n') || command.includes('\r'))
184
+ return null;
185
+ const parsed = (0, shell_syntax_1.shellWords)(command, process.env, undefined, cwd, true);
186
+ if (parsed.overflow || parsed.subs.length || parsed.commands.length !== 1 || parsed.commands[0].redirects.length > 0)
187
+ return null;
188
+ const installer = installerWords(parsed.commands[0].words, ['setup', 'remove'], true);
189
+ return installer === null ? null : installer.preview ? 'preview' : 'apply';
190
+ }
191
+ function shellArgumentRoles(command, cwd = null) {
192
+ const original = { governanceText: command, serverText: command, outputPaths: [] };
193
+ if (command.length > LIMIT)
194
+ return original;
195
+ const parsed = (0, shell_syntax_1.shellWords)(command, process.env, undefined, cwd, true);
196
+ // A nested shell or substitution retains its complete original text. No flattened reparse can
197
+ // turn its executable payload into an inert argument. Unknown syntax likewise receives no mask.
198
+ if (parsed.overflow || parsed.subs.length || parsed.commands.some(c => !c.words.every(certain) || c.redirects.some(w => !certain(w))))
199
+ return original;
200
+ const serverData = parsed.commands.flatMap(c => [...searchData(c.words), ...nodeData(c.words)]);
201
+ // CLI path bases are currently certain only for a direct single invocation. Shell cd/wrappers
202
+ // keep existing conservative policy until their bases are explicitly modeled.
203
+ const codex = parsed.commands.length === 1 ? codexPrompt(parsed.commands[0].words, cwd) : null;
204
+ return {
205
+ governanceText: codex?.prompt ? mask(command, [codex.prompt]) : command,
206
+ serverText: mask(command, serverData),
207
+ outputPaths: codex?.outputs ?? [],
208
+ };
209
+ }
@@ -0,0 +1,20 @@
1
+ export interface Word {
2
+ text: string;
3
+ known: boolean;
4
+ glob: boolean;
5
+ sourceStart?: number;
6
+ sourceEnd?: number;
7
+ }
8
+ export interface SimpleCommand {
9
+ words: Word[];
10
+ redirects: Word[];
11
+ }
12
+ /** Bodies of `$(…)`, backticks and `<(…)`/`>(…)`: they RUN, so they are judged as commands too. */
13
+ export interface ParsedSegment {
14
+ commands: SimpleCommand[];
15
+ subs: string[];
16
+ overflow: boolean;
17
+ }
18
+ export declare function shellWords(src: string, env?: NodeJS.ProcessEnv, home?: string, pwd?: string | null, sourceRanges?: boolean): SimpleCommand & ParsedSegment;
19
+ /** The words from the real command word on, behind wrappers, assignments and grouping keywords. */
20
+ export declare function commandOf(input: Word[]): Word[];