@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
@@ -37,10 +37,11 @@ exports.isLowRiskTarget = isLowRiskTarget;
37
37
  exports.evaluateEditEvidence = evaluateEditEvidence;
38
38
  exports.preEditEvidenceDecision = preEditEvidenceDecision;
39
39
  exports.loadEditEvidence = loadEditEvidence;
40
- // @implements A-SPEC-279, A-SPEC-278.1
40
+ // @implements A-SPEC-279, A-SPEC-278.1, A-SPEC-278.2, A-SPEC-278.3
41
41
  // @implements A-SPEC-278
42
42
  // @implements A-SPEC-277
43
43
  // @implements A-SPEC-276
44
+ const node_child_process_1 = require("node:child_process");
44
45
  const fs = __importStar(require("node:fs"));
45
46
  const crypto = __importStar(require("node:crypto"));
46
47
  const path = __importStar(require("node:path"));
@@ -272,7 +273,11 @@ function newestPersistedAnalysis(projectRoot, target, currentHead) {
272
273
  catch {
273
274
  return null;
274
275
  }
276
+ const newer = (a, b) => b === null || String(a.recordedAt ?? '') > String(b.recordedAt ?? '');
275
277
  let best = null;
278
+ const older = [];
279
+ let targetIsNew;
280
+ const isNew = () => (targetIsNew ??= !gitOk(projectRoot, ['cat-file', '-e', `${currentHead}:${target}`]));
276
281
  for (const { file } of entries.sort((a, b) => b.mtime - a.mtime).slice(0, PERSISTED_SCAN_LIMIT)) {
277
282
  let candidate;
278
283
  try {
@@ -281,14 +286,94 @@ function newestPersistedAnalysis(projectRoot, target, currentHead) {
281
286
  catch {
282
287
  continue;
283
288
  }
284
- if (candidate?.graphBasis?.head !== currentHead)
289
+ if (!Array.isArray(candidate?.predicted?.files) || typeof candidate?.graphBasis?.head !== 'string')
285
290
  continue;
286
- if (!Array.isArray(candidate?.predicted?.files) || !candidate.predicted.files.includes(target))
291
+ if (candidate.graphBasis.head !== currentHead) {
292
+ older.push(candidate);
287
293
  continue;
288
- if (best === null || String(candidate.recordedAt ?? '') > String(best.recordedAt ?? ''))
294
+ }
295
+ if (!coversTarget(candidate, target, isNew))
296
+ continue;
297
+ if (newer(candidate, best))
289
298
  best = candidate;
290
299
  }
291
- return best;
300
+ if (best)
301
+ return best;
302
+ // @implements A-SPEC-278.2 (rule 2) — an analysis at an ancestor ≤ 20 commits back still describes this tree when every
303
+ // file changed since it was predicted or named by its request (the RED commit adds only the request-named test). The
304
+ // copy carries the current head so the basis is not reported as drifted; the target's own digest still is.
305
+ const lineage = new Map();
306
+ for (const candidate of older.sort((a, b) => String(b.recordedAt ?? '').localeCompare(String(a.recordedAt ?? '')))) {
307
+ const a = candidate.graphBasis.head;
308
+ if (!coversTarget(candidate, target, isNew))
309
+ continue;
310
+ if (!lineage.has(a)) {
311
+ if (lineage.size >= LINEAGE_HEADS_MAX)
312
+ break;
313
+ lineage.set(a, unchangedOutside(projectRoot, a, currentHead, candidate));
314
+ }
315
+ if (lineage.get(a))
316
+ return { ...candidate, graphBasis: { ...candidate.graphBasis, head: currentHead } };
317
+ }
318
+ return null;
319
+ }
320
+ /** @implements A-SPEC-278.2 — distinct ancestor heads examined per judgement (each costs three bounded git calls). */
321
+ const LINEAGE_HEADS_MAX = 8;
322
+ const LINEAGE_DEPTH_MAX = 20;
323
+ /** The analysis request names `rel` as a whole path (not as part of a longer one). */
324
+ function requestNames(candidate, rel) {
325
+ // @implements A-SPEC-278.3 — a file the caller listed in changedFiles is named exactly, whatever the request text says.
326
+ const listed = candidate.changedFiles;
327
+ if (rel !== '' && Array.isArray(listed) && listed.includes(rel))
328
+ return true;
329
+ const request = candidate.request;
330
+ if (typeof request !== 'string' || rel === '')
331
+ return false;
332
+ let at = request.indexOf(rel);
333
+ while (at >= 0) {
334
+ const before = at === 0 ? '' : request[at - 1];
335
+ const after = request[at + rel.length] ?? '';
336
+ if (!/[\w./-]/.test(before) && !/[\w/-]/.test(after) && !(after === '.' && /[\w]/.test(request[at + rel.length + 1] ?? '')))
337
+ return true;
338
+ at = request.indexOf(rel, at + 1);
339
+ }
340
+ return false;
341
+ }
342
+ /** @implements A-SPEC-278.2 (rule 1) — predicted, or a file new at HEAD that the request names. */
343
+ function coversTarget(candidate, target, isNew) {
344
+ if (candidate.predicted.files.includes(target))
345
+ return true;
346
+ return requestNames(candidate, target) && isNew();
347
+ }
348
+ function unchangedOutside(projectRoot, ancestor, head, candidate) {
349
+ if (!/^[0-9a-f]{7,64}$/i.test(ancestor) || !gitOk(projectRoot, ['merge-base', '--is-ancestor', ancestor, head]))
350
+ return false;
351
+ const count = Number(gitText(projectRoot, ['rev-list', '--count', `${ancestor}..${head}`]));
352
+ if (!Number.isInteger(count) || count < 1 || count > LINEAGE_DEPTH_MAX)
353
+ return false;
354
+ const changed = gitText(projectRoot, ['diff', '--name-only', '--no-renames', ancestor, head]);
355
+ if (changed === null)
356
+ return false;
357
+ return changed.split('\n').filter(Boolean).every((f) => candidate.predicted.files.includes(f) || requestNames(candidate, f));
358
+ }
359
+ const GIT_TIMEOUT_MS = 5000;
360
+ const GIT_MAX_BUFFER = 1024 * 1024;
361
+ function gitOk(cwd, args) {
362
+ try {
363
+ (0, node_child_process_1.execFileSync)('git', ['-C', cwd, ...args], { timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER, stdio: ['ignore', 'pipe', 'ignore'] });
364
+ return true;
365
+ }
366
+ catch {
367
+ return false;
368
+ }
369
+ }
370
+ function gitText(cwd, args) {
371
+ try {
372
+ return (0, node_child_process_1.execFileSync)('git', ['-C', cwd, ...args], { timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER, stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' }).trim();
373
+ }
374
+ catch {
375
+ return null;
376
+ }
292
377
  }
293
378
  /**
294
379
  * @implements A-SPEC-278
@@ -154,6 +154,11 @@ function redirectTokenTester(tail) {
154
154
  let i = text.indexOf('>');
155
155
  while (i >= 0) {
156
156
  let j = i + 1;
157
+ // @implements A-SPEC-728.1 — one `&` or `|` right after `>` belongs to the operator (`>&`, `>|`): it ended the
158
+ // target token at once, so `echo x >& .ax/ledger/…` was `confirm` here (measured on 0.33.0 and 0.34.0).
159
+ const dup = text[j] === '&';
160
+ if (dup || text[j] === '|')
161
+ j++;
157
162
  while (j < text.length && /\s/.test(text[j]))
158
163
  j++;
159
164
  if (text[j] === '"' || text[j] === "'")
@@ -161,7 +166,9 @@ function redirectTokenTester(tail) {
161
166
  let k = j;
162
167
  while (k < text.length && !/[\s;&|]/.test(text[k]))
163
168
  k++;
164
- if (t.test(text.slice(j, k)))
169
+ const token = text.slice(j, k);
170
+ // `>&2`, `>& 2`, `>&-` duplicate or close a descriptor; they name no file.
171
+ if (!(dup && /^(?:\d+|-)$/.test(token)) && t.test(token))
165
172
  return true;
166
173
  // A `>` ending the token targets the NEXT token (after blanks); one inside it sees a suffix.
167
174
  i = text.indexOf('>', k > i + 1 && text[k - 1] === '>' ? k - 1 : Math.max(k, i + 1));
@@ -16,6 +16,12 @@ export declare function rmCommandTargets(cmd: string): string[];
16
16
  export declare function normalizeWindowsPathSpellings(cmd: string): string;
17
17
  export declare function scopeAxToProject(cmd: string, projectRoot?: string): string;
18
18
  export declare function normalizeCommandPaths(cmd: string, followCd?: boolean): string;
19
+ /**
20
+ * @implements A-SPEC-728.2 — the classifier's own read judgement of a whole shell text, loops included, for the identity
21
+ * layer: a `for` loop whose body only reads its variable's files names no mutation target with its word list.
22
+ */
23
+ export declare function shellTextOnlyReads(text: string): boolean;
24
+ export declare function stripCommitMessages(cmd: string): string;
19
25
  /**
20
26
  * @implements A-SPEC-125.1
21
27
  * Reversibility axis: can the action's effect be undone? Conservative default —
@@ -37,17 +37,21 @@ exports.rmCommandTargets = rmCommandTargets;
37
37
  exports.normalizeWindowsPathSpellings = normalizeWindowsPathSpellings;
38
38
  exports.scopeAxToProject = scopeAxToProject;
39
39
  exports.normalizeCommandPaths = normalizeCommandPaths;
40
+ exports.shellTextOnlyReads = shellTextOnlyReads;
41
+ exports.stripCommitMessages = stripCommitMessages;
40
42
  exports.classifyReversibility = classifyReversibility;
41
43
  exports.classifyArchitectureReversal = classifyArchitectureReversal;
42
44
  exports.classifySecret = classifySecret;
43
45
  exports.classifyBlastRadius = classifyBlastRadius;
44
46
  exports.assessRisk = assessRisk;
45
- // @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
46
48
  const fs = __importStar(require("node:fs"));
47
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");
48
52
  const risk_types_1 = require("./risk-types");
49
53
  const linear_match_1 = require("./linear-match");
50
- const write_target_1 = require("./write-target");
54
+ const write_target_2 = require("./write-target");
51
55
  const AWS_KEY_RE = /AKIA[0-9A-Z]{16}/;
52
56
  const PEM_KEY_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
53
57
  const SECRET_KV_RE = /(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S{6,}/i;
@@ -311,6 +315,12 @@ function normalizeWindowsPathSpellings(cmd) {
311
315
  .replace(/(^|[\s'"=(])\/([A-Za-z])\/(?=[^\s'"()/])/g, (_m, pre, d) => `${pre}${d.toLowerCase()}:/`);
312
316
  }
313
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>';
314
324
  const spelled = normalizeWindowsPathSpellings(cmd);
315
325
  if (!projectRoot)
316
326
  return spelled;
@@ -327,7 +337,10 @@ function scopeAxToProject(cmd, projectRoot) {
327
337
  // time: the regex rescanned each run of path characters from every `=` (256 KB of `=/` met the hook's 20 s wall —
328
338
  // measured). A match lies inside one maximal run of `[^\s'"()]` and extends to its end, so each run needs only its last
329
339
  // `/.ax/` and its leftmost start: the run's first character after a boundary other than `)`, or one after an `=` inside it.
330
- 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;
331
344
  let out = '';
332
345
  let last = 0;
333
346
  for (let m = RUN.exec(spelled); m !== null; m = RUN.exec(spelled)) {
@@ -351,7 +364,7 @@ function scopeAxToProject(cmd, projectRoot) {
351
364
  continue;
352
365
  const pre = start === 0 ? '' : spelled[start - 1];
353
366
  const abs = spelled.slice(start, b);
354
- 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);
355
368
  last = b;
356
369
  }
357
370
  return out + spelled.slice(last);
@@ -401,7 +414,7 @@ function redirectTargetsUnder(text, ax) {
401
414
  return text;
402
415
  // Rule 36: the digits have their own lookbehind; the operator only must not follow `<`/`>` (`2>&1>ledger/x` matched no
403
416
  // start and passed — measured).
404
- 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');
405
418
  return text.replace(re, (whole, op, q, p, at) => (masked[at + op.indexOf('>')] === '>' ? `${op}${q}${ax}/${p}` : whole));
406
419
  }
407
420
  /**
@@ -424,8 +437,8 @@ function cdReachesStore(cb, start, rootAx) {
424
437
  const realAx = real(rootAx);
425
438
  const seen = new Set();
426
439
  for (const arg of cb.literal) {
427
- for (const b of (0, write_target_1.absoluteKindOf)(arg) !== null ? [arg] : bases) {
428
- 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);
429
442
  if (seen.has(to))
430
443
  continue;
431
444
  seen.add(to);
@@ -489,7 +502,7 @@ function segmentFlattened(cmd, root, start = root) {
489
502
  });
490
503
  };
491
504
  // Round 17: from the directory the harness runs the shell in (`start`), not always the root.
492
- const segments = (0, write_target_1.shellSegments)(cmd, start);
505
+ const segments = (0, write_target_2.shellSegments)(cmd, start);
493
506
  // @implements A-SPEC-728 (round 11) — a null-base segment MAY run in any base the command produced
494
507
  // (`maybe`); the ones under `.ax` matter, keyed by the top-level `.ax` child so the rewrite count is
495
508
  // bounded by the store's layout, not the command's length (measured: `git log; cd sub; cd ../.ax;
@@ -507,12 +520,12 @@ function segmentFlattened(cmd, root, start = root) {
507
520
  // @implements A-SPEC-728 (round 23) — every segment is also judged from every directory under `.ax` the command may
508
521
  // run ANY part in (flow-insensitive): a loop, a function or a trap runs text after a later `cd .ax` (measured: `for …;
509
522
  // do rm ledger/provenance.jsonl; cd .ax; done` deleted the ledger). An unknown set on a `.ax` mention adds `.ax`.
510
- const cb = (0, write_target_1.commandBases)(cmd, start, segments);
523
+ const cb = (0, write_target_2.commandBases)(cmd, start, segments);
511
524
  for (const b of cb.bases)
512
525
  candidates.add(b);
513
- if (cb.unknown !== null && (0, write_target_1.mentionsAxSpelling)(cmd)) {
526
+ if (cb.unknown !== null && (0, write_target_2.mentionsAxSpelling)(cmd)) {
514
527
  candidates.add(path.join(start, '.ax'));
515
- for (const c of write_target_1.AX_PROTECTED_CHILDREN)
528
+ for (const c of write_target_2.AX_PROTECTED_CHILDREN)
516
529
  candidates.add(path.join(start, '.ax', c));
517
530
  }
518
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
@@ -520,7 +533,7 @@ function segmentFlattened(cmd, root, start = root) {
520
533
  let climb = 0;
521
534
  for (const m of cmd.matchAll(/(?:\.\.[\\/])+/g))
522
535
  climb = Math.max(climb, m[0].length / 3);
523
- const keys = (0, write_target_1.axCandidateKeys)(root, candidates, climb + 1);
536
+ const keys = (0, write_target_2.axCandidateKeys)(root, candidates, climb + 1);
524
537
  const forms = [];
525
538
  // @implements A-SPEC-728 (rule 44) — every form is kept within one budget: past FORMS_MAX characters the command is too large
526
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
@@ -535,10 +548,10 @@ function segmentFlattened(cmd, root, start = root) {
535
548
  // @implements A-SPEC-728 (round 24) — an unknown set on a command that never spells `.ax`: a path whose first component is a
536
549
  // protected `.ax` child is judged under the store too (`cd "$(printf '.%s' ax)" && echo x > ledger/provenance.jsonl` was
537
550
  // allowed — measured). Only those paths, so an ordinary relative write is not read as a store write.
538
- 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;
539
552
  // Round 25: `./ledger/…` too. Round 28: after `=` and `(`, before `)`/`>`/`;`/`&`/`|`, with glob and brace characters
540
553
  // (`cp a --target-directory=ledger`, `rm ledger/*` — measured).
541
- 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');
542
555
  // Round 26: only a segment that writes or removes (reads of an ordinary top-level `specs/` after a computed cd were
543
556
  // denied — measured).
544
557
  // Round 27: inverted — a segment skips this reading only when it is recognisably read-only and redirects nothing into a
@@ -561,7 +574,7 @@ function segmentFlattened(cmd, root, start = root) {
561
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
562
575
  // store. Past 16,384 argument-base pairs the store is read without looking.
563
576
  const rootAx = path.join(root, '.ax');
564
- 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))] : [];
565
578
  const fed = axChildren === null && storeBases.length === 0 ? new Set() : feedsAShell(segments);
566
579
  for (const [i, s] of segments.entries()) {
567
580
  if ((axChildren !== null || storeBases.length > 0) && !s.data) {
@@ -582,9 +595,9 @@ function segmentFlattened(cmd, root, start = root) {
582
595
  add(s.text);
583
596
  if (s.maybe || keys.bases.length > 0) {
584
597
  // @implements A-SPEC-728 (rule 44) — past 8 climb bases the command is too large to judge (60 rewrites of 256 KB — measured).
585
- const climbs = (0, write_target_1.axClimbBases)(root, keys, s.text);
586
- if (climbs.length > write_target_1.AX_CLIMB_BASES_MAX)
587
- 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)`);
588
601
  for (const k of keys.bases)
589
602
  add(rewrite(s.text, k));
590
603
  for (const k of climbs)
@@ -1476,6 +1489,26 @@ function isIndexRestoreClause(clause) {
1476
1489
  }
1477
1490
  return false;
1478
1491
  }
1492
+ /**
1493
+ * @implements A-SPEC-728.2 — the classifier's own read judgement of a whole shell text, loops included, for the identity
1494
+ * layer: a `for` loop whose body only reads its variable's files names no mutation target with its word list.
1495
+ */
1496
+ function shellTextOnlyReads(text) {
1497
+ return clausesAreReads(splitShellClauses(text), (c) => clauseIsRead(c, isReadOnlyShellClause));
1498
+ }
1499
+ /**
1500
+ * @implements A-SPEC-728.2 — a `git commit` message is text, not a path: `git commit -m "… .ax/specs …"` was refused as "not
1501
+ * recognisably read-only" (measured 2026-10-01). The values of `-m`/`--message`/`--message=`/`-F`/`--file` in a `git …
1502
+ * commit` segment are blanked before the `.ax` rules read the command. A double-quoted value holding `$` or a backtick (a
1503
+ * substitution runs), an unquoted value's redirect (`-m x>FILE`), and a pathspec stay as written.
1504
+ */
1505
+ const COMMIT_SEGMENT_RE = /(\bgit\b(?:\s+(?:-C|-c)\s+\S+|\s+--no-pager)*\s+commit\b)([^;&|\n]*)/g;
1506
+ const COMMIT_MESSAGE_RE = /(\s(?:-[a-zA-Z]*[mF]|--message|--file))(=|\s+)("(?:[^"\\$`]|\\[^$`])*"|'[^']*'|[^\s;&|<>()$`"']+)/g;
1507
+ function stripCommitMessages(cmd) {
1508
+ if (!/\bcommit\b/.test(cmd))
1509
+ return cmd;
1510
+ return cmd.replace(COMMIT_SEGMENT_RE, (_, head, rest) => head + rest.replace(COMMIT_MESSAGE_RE, '$1$2""'));
1511
+ }
1479
1512
  /**
1480
1513
  * A shell command that touches a protected governance path and is not recognisably read-only.
1481
1514
  *
@@ -1514,7 +1547,7 @@ function shellWritesProtectedAx(ncmd) {
1514
1547
  */
1515
1548
  function classifyReversibility(action) {
1516
1549
  const raw = action.command ?? '';
1517
- const joined = raw === '' ? raw : (0, write_target_1.joinShellText)(raw);
1550
+ const joined = raw === '' ? raw : (0, write_target_2.joinShellText)(raw);
1518
1551
  if (joined === raw)
1519
1552
  return classifyReversibilityAsWritten(action);
1520
1553
  const a = classifyReversibilityAsWritten(action);
@@ -1542,11 +1575,23 @@ function classifyReversibilityAsWritten(action) {
1542
1575
  // @implements A-SPEC-728 (round 9) — the cd-flattened text AND the text as written: flattening
1543
1576
  // followed a cd the shell never ran (`cd /nonexistent && true; echo x > .ax/ledger/p.jsonl` became an
1544
1577
  // other-project path and was allowed — measured). Judging both only ever adds refusals.
1545
- const flat = scopeAxToProject(normalizeCommandPaths(cmd), action.projectRoot);
1546
- const asWritten = scopeAxToProject(normalizeCommandPaths(cmd, false), action.projectRoot);
1578
+ // A-SPEC-728.2 — a commit message is text the `.ax` rules do not read.
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));
1547
1591
  // Round 10: and with every segment at the base the certain-cd model gives it (a second cd into .ax).
1548
- const bySegment = action.projectRoot ? scopeAxToProject(normalizeCommandPaths(segmentFlattened(cmd, action.projectRoot, action.cwd ?? action.projectRoot), false), action.projectRoot) : asWritten;
1549
- 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');
1550
1595
  // @implements A-SPEC-737 — one reason served all four channels, so an interpreter READ was refused as
1551
1596
  // a "removal command" and the author could not tell what to change. Each channel names itself.
1552
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[];