@holmes-lab/holmes-kit 0.30.0 → 0.31.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 (139) hide show
  1. package/CHANGELOG.md +505 -0
  2. package/README.md +10 -1
  3. package/bin/holmes-hook-antigravity.js +4 -0
  4. package/bin/holmes-kit.js +4 -0
  5. package/bin/holmes-pre-push.js +3 -0
  6. package/bin/holmes-stop-antigravity.js +4 -0
  7. package/dist/.build-id +1 -1
  8. package/dist/holmes/cli/agents.d.ts +41 -0
  9. package/dist/holmes/cli/agents.js +382 -2
  10. package/dist/holmes/cli/attest.d.ts +2 -0
  11. package/dist/holmes/cli/attest.js +66 -15
  12. package/dist/holmes/cli/ci-gate.js +16 -1
  13. package/dist/holmes/cli/claude-switches.d.ts +95 -0
  14. package/dist/holmes/cli/claude-switches.js +967 -0
  15. package/dist/holmes/cli/codex-hooks.d.ts +77 -0
  16. package/dist/holmes/cli/codex-hooks.js +802 -0
  17. package/dist/holmes/cli/codex-oracle.d.ts +194 -0
  18. package/dist/holmes/cli/codex-oracle.js +1245 -0
  19. package/dist/holmes/cli/codex-toml.d.ts +35 -0
  20. package/dist/holmes/cli/codex-toml.js +321 -52
  21. package/dist/holmes/cli/doctor.d.ts +98 -8
  22. package/dist/holmes/cli/doctor.js +1328 -94
  23. package/dist/holmes/cli/index.js +26 -11
  24. package/dist/holmes/cli/init.d.ts +11 -0
  25. package/dist/holmes/cli/init.js +736 -44
  26. package/dist/holmes/cli/mcp-launcher.d.ts +64 -6
  27. package/dist/holmes/cli/mcp-launcher.js +189 -6
  28. package/dist/holmes/cli/mcp-version.js +13 -2
  29. package/dist/holmes/cli/settings-merge.js +8 -2
  30. package/dist/holmes/cli/upgrade.d.ts +18 -0
  31. package/dist/holmes/cli/upgrade.js +129 -24
  32. package/dist/holmes/cli/workspace-scope.d.ts +22 -0
  33. package/dist/holmes/cli/workspace-scope.js +375 -0
  34. package/dist/holmes/cpg/cpg-scanner.d.ts +29 -0
  35. package/dist/holmes/cpg/cpg-scanner.js +403 -3
  36. package/dist/holmes/cpg/cycle-detect.js +2 -1
  37. package/dist/holmes/cpg/forbidden-edges.js +9 -2
  38. package/dist/holmes/cpg/required-calls.js +8 -1
  39. package/dist/holmes/governance/constitution-debt.js +3 -2
  40. package/dist/holmes/governance/constitution.js +15 -3
  41. package/dist/holmes/governance/provenance-chain.js +3 -2
  42. package/dist/holmes/governance/push-gate-runner.js +4 -3
  43. package/dist/holmes/guardrail/dependency-delta.js +4 -3
  44. package/dist/holmes/guardrail/linear-match.d.ts +57 -0
  45. package/dist/holmes/guardrail/linear-match.js +256 -0
  46. package/dist/holmes/guardrail/risk-classifier.d.ts +6 -7
  47. package/dist/holmes/guardrail/risk-classifier.js +931 -44
  48. package/dist/holmes/guardrail/risk-types.d.ts +6 -0
  49. package/dist/holmes/guardrail/scope-judgment.d.ts +4 -24
  50. package/dist/holmes/guardrail/scope-judgment.js +100 -23
  51. package/dist/holmes/guardrail/shell-words.d.ts +42 -0
  52. package/dist/holmes/guardrail/shell-words.js +1720 -0
  53. package/dist/holmes/guardrail/write-target.d.ts +168 -3
  54. package/dist/holmes/guardrail/write-target.js +2379 -87
  55. package/dist/holmes/hooks/adapters/antigravity.d.ts +3 -1
  56. package/dist/holmes/hooks/adapters/antigravity.js +115 -11
  57. package/dist/holmes/hooks/pre-tool-use.d.ts +32 -6
  58. package/dist/holmes/hooks/pre-tool-use.js +923 -87
  59. package/dist/holmes/hooks/rtm-refresh-child.js +3 -1
  60. package/dist/holmes/hooks/rtm-refresh.js +8 -4
  61. package/dist/holmes/hooks/session-start.d.ts +10 -0
  62. package/dist/holmes/hooks/session-start.js +31 -7
  63. package/dist/holmes/hooks/stop.d.ts +2 -1
  64. package/dist/holmes/hooks/stop.js +197 -91
  65. package/dist/holmes/mcp/approval-commit.d.ts +5 -6
  66. package/dist/holmes/mcp/approval-commit.js +18 -2
  67. package/dist/holmes/mcp/elicit-approval.js +4 -2
  68. package/dist/holmes/mcp/handlers/graph-operations.js +3 -2
  69. package/dist/holmes/mcp/handlers/maintenance-analysis.js +11 -5
  70. package/dist/holmes/mcp/handlers/maintenance-evidence.js +3 -2
  71. package/dist/holmes/mcp/handlers/phase-queries.d.ts +22 -7
  72. package/dist/holmes/mcp/handlers/phase-queries.js +81 -2
  73. package/dist/holmes/mcp/handlers/requirement-triage.js +5 -3
  74. package/dist/holmes/mcp/handlers/review-evidence.js +8 -2
  75. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +11 -0
  76. package/dist/holmes/mcp/handlers/slice-orchestration.js +115 -16
  77. package/dist/holmes/mcp/handlers/spec-approval.d.ts +9 -0
  78. package/dist/holmes/mcp/handlers/spec-approval.js +110 -17
  79. package/dist/holmes/mcp/handlers/spec-authoring.js +17 -2
  80. package/dist/holmes/mcp/handlers/spec-queries.d.ts +39 -3
  81. package/dist/holmes/mcp/handlers/spec-queries.js +114 -7
  82. package/dist/holmes/mcp/handlers/test-execution.js +9 -3
  83. package/dist/holmes/mcp/handlers.d.ts +81 -9
  84. package/dist/holmes/mcp/handlers.js +70 -23
  85. package/dist/holmes/mcp/harness-attestation.d.ts +20 -0
  86. package/dist/holmes/mcp/harness-attestation.js +179 -0
  87. package/dist/holmes/mcp/requirement-triage-evidence.d.ts +36 -0
  88. package/dist/holmes/mcp/requirement-triage-evidence.js +160 -4
  89. package/dist/holmes/mcp/server.js +20 -1
  90. package/dist/holmes/mcp/tool-schemas.js +26 -9
  91. package/dist/holmes/mcp/validate-args.js +12 -0
  92. package/dist/holmes/project/bounded-io.d.ts +102 -0
  93. package/dist/holmes/project/bounded-io.js +212 -0
  94. package/dist/holmes/project/change-source.js +3 -1
  95. package/dist/holmes/project/ci-runs.js +3 -2
  96. package/dist/holmes/project/ignore.d.ts +31 -2
  97. package/dist/holmes/project/ignore.js +409 -50
  98. package/dist/holmes/project/regular-file-guard.d.ts +13 -0
  99. package/dist/holmes/project/regular-file-guard.js +149 -0
  100. package/dist/holmes/project/root.js +12 -3
  101. package/dist/holmes/reverse/anchor.js +4 -3
  102. package/dist/holmes/reverse/scan.js +6 -2
  103. package/dist/holmes/review/commit-text.js +3 -2
  104. package/dist/holmes/review/condition-hunk-replay.js +3 -2
  105. package/dist/holmes/review/failed-test-names.js +13 -10
  106. package/dist/holmes/review/findings.js +3 -1
  107. package/dist/holmes/review/kills-check.js +6 -1
  108. package/dist/holmes/review/point-in-time-replay.js +5 -4
  109. package/dist/holmes/review/replay-corpus.js +5 -4
  110. package/dist/holmes/review/run-replay.js +3 -2
  111. package/dist/holmes/review/temporal-prior.js +3 -2
  112. package/dist/holmes/review/test-evidence.js +3 -2
  113. package/dist/holmes/review/test-outcomes.js +3 -2
  114. package/dist/holmes/review/test-runner.d.ts +6 -0
  115. package/dist/holmes/review/test-runner.js +36 -15
  116. package/dist/holmes/rtm/advisory-outcomes.js +3 -2
  117. package/dist/holmes/rtm/anchor-ids.js +42 -2
  118. package/dist/holmes/rtm/file-anchors.js +4 -1
  119. package/dist/holmes/rtm/ftt-fulfilment.js +8 -3
  120. package/dist/holmes/rtm/git-changes.js +3 -1
  121. package/dist/holmes/rtm/graph-store.js +3 -2
  122. package/dist/holmes/rtm/test-scope.js +9 -4
  123. package/dist/holmes/spec/compat-impact.d.ts +25 -4
  124. package/dist/holmes/spec/compat-impact.js +682 -11
  125. package/dist/holmes/spec/entity-git-snapshot.js +3 -2
  126. package/dist/holmes/spec/entity-integration.js +3 -2
  127. package/dist/holmes/spec/entity-renumber-transaction.d.ts +19 -0
  128. package/dist/holmes/spec/entity-renumber-transaction.js +79 -6
  129. package/dist/holmes/spec/remote-spec-refs.js +3 -2
  130. package/dist/holmes/spec/renumber.js +25 -10
  131. package/dist/holmes/spec/spec-parser.js +9 -3
  132. package/dist/holmes/spec/yaml-scalar.js +2 -2
  133. package/dist/holmes/update/refresh.d.ts +5 -0
  134. package/dist/holmes/update/refresh.js +26 -1
  135. package/dist/holmes/update/update-notice.d.ts +6 -0
  136. package/dist/holmes/update/update-notice.js +18 -1
  137. package/dist/holmes/update/upgrade-plan.d.ts +28 -0
  138. package/dist/holmes/update/upgrade-plan.js +31 -2
  139. package/package.json +11 -4
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.PATH_FIELDS = exports.READ_ONLY_TOOLS = void 0;
36
+ exports.AX_CLIMB_BASES_MAX = exports.WIRING_FILE_NAMES = exports.WIRING_DIR_NAMES = exports.GOVERNANCE_STORE_LABEL = exports.AX_PROTECTED_CHILDREN = exports.PATH_FIELDS = exports.READ_ONLY_TOOLS = void 0;
37
37
  exports.absoluteKindOf = absoluteKindOf;
38
38
  exports.foldsCaseBySyntax = foldsCaseBySyntax;
39
39
  exports.writesFiles = writesFiles;
@@ -42,13 +42,29 @@ exports.resolveTarget = resolveTarget;
42
42
  exports.isProtectedTarget = isProtectedTarget;
43
43
  exports.specTargetOf = specTargetOf;
44
44
  exports.protectedFileKindOf = protectedFileKindOf;
45
+ exports.expandHomeSpelling = expandHomeSpelling;
46
+ exports.withIdentCache = withIdentCache;
47
+ exports.userHarnessConfigKindOf = userHarnessConfigKindOf;
48
+ exports.globPatternRe = globPatternRe;
49
+ exports.wiringDeletionKindOf = wiringDeletionKindOf;
50
+ exports.axCandidateKeys = axCandidateKeys;
51
+ exports.axClimbBases = axClimbBases;
52
+ exports.wiringWriteKindOf = wiringWriteKindOf;
45
53
  exports.protectedKindOf = protectedKindOf;
54
+ exports.reduceCdWord = reduceCdWord;
55
+ exports.shellBaseFor = shellBaseFor;
56
+ exports.envSplitWords = envSplitWords;
57
+ exports.wrapperChdir = wrapperChdir;
58
+ exports.mentionsAxSpelling = mentionsAxSpelling;
59
+ exports.joinShellText = joinShellText;
60
+ exports.commandBases = commandBases;
46
61
  exports.shellSegments = shellSegments;
47
62
  exports.resolvesInside = resolvesInside;
48
- // @implements A-SPEC-163, A-SPEC-627
63
+ // @implements A-SPEC-728, A-SPEC-733, A-SPEC-163, A-SPEC-627
49
64
  const fs = __importStar(require("node:fs"));
50
65
  const path = __importStar(require("node:path"));
51
66
  const os = __importStar(require("node:os"));
67
+ const linear_match_1 = require("./linear-match");
52
68
  /**
53
69
  * Tools known to only READ. Everything else that carries a path is treated as a write.
54
70
  *
@@ -162,28 +178,58 @@ function resolveTarget(root, raw, depth = 0, opts = {}) {
162
178
  // link is followed explicitly. Without this, `ln -s .ax/ledger/not-yet-there innocent` then
163
179
  // writing `innocent` creates a file inside the protected directory while the gate sees a name
164
180
  // outside it. The depth cap stops a symlink cycle from spinning.
181
+ let absent = false;
165
182
  if (depth < 8) {
166
183
  try {
167
- if (fsi.lstatSync(abs).isSymbolicLink()) {
184
+ // Rule 46: a missing entry is answered, not thrown (each throw captured a stack: 51,000 missing members — measured),
185
+ // and an entry known to be missing is not looked up again below.
186
+ const st = fsi.lstatSync(abs, { throwIfNoEntry: false });
187
+ if (st === undefined)
188
+ absent = true;
189
+ else if (st.isSymbolicLink())
168
190
  return resolveTarget(pp.dirname(abs), fsi.readlinkSync(abs), depth + 1, opts);
169
- }
170
191
  }
171
192
  catch { /* not a symlink, or unreadable — fall through to ancestor resolution */ }
172
193
  }
173
- const parts = [];
174
- let cur = abs;
175
- for (;;) {
176
- try {
177
- return pp.join(fsi.realpathSync(cur), ...parts.reverse());
178
- }
179
- catch {
180
- const parent = pp.dirname(cur);
181
- if (parent === cur)
182
- return abs; // reached the filesystem root without an existing ancestor
183
- parts.push(pp.basename(cur));
184
- cur = parent;
194
+ // The nearest ancestor that resolves, found by halving (rule 37): whether an ancestor resolves is monotone along a
195
+ // lexical chain (a path resolves only through a parent that does), and climbing one component at a time cost a
196
+ // throwing look-up per missing component — 48 missing 4 KB paths took 4 s (measured).
197
+ const chain = [abs];
198
+ for (let cur = abs, parent = pp.dirname(cur); parent !== cur; cur = parent, parent = pp.dirname(cur))
199
+ chain.push(parent);
200
+ // @implements A-SPEC-728 (rule 46) — within one judgement an ancestor is looked up once, whichever target asks: 51,000
201
+ // members under one missing directory each looked that directory up again (2.7 s before this rule, 4.1 s with its readings).
202
+ const shared = opts.fs === undefined ? realCache : null;
203
+ const found = new Map();
204
+ if (absent)
205
+ found.set(0, null);
206
+ const resolved = (k) => {
207
+ if (!found.has(k)) {
208
+ let r = shared?.get(chain[k]);
209
+ if (r === undefined) {
210
+ r = null;
211
+ try {
212
+ r = fsi.realpathSync(chain[k]);
213
+ }
214
+ catch { /* not there */ }
215
+ shared?.set(chain[k], r);
216
+ }
217
+ found.set(k, r);
185
218
  }
219
+ return found.get(k) ?? null;
220
+ };
221
+ let lo = 0, hi = chain.length - 1;
222
+ while (lo < hi) {
223
+ const mid = (lo + hi) >> 1;
224
+ if (resolved(mid) !== null)
225
+ hi = mid;
226
+ else
227
+ lo = mid + 1;
186
228
  }
229
+ const real = resolved(hi);
230
+ if (real === null)
231
+ return abs; // no ancestor exists, not even the filesystem root
232
+ return pp.join(real, ...chain.slice(0, hi).reverse().map((c) => pp.basename(c)));
187
233
  }
188
234
  /** Governance directories, relative to the project root. */
189
235
  const PROTECTED_DIRS = [
@@ -288,6 +334,691 @@ function protectedFileKindOf(root, raw) {
288
334
  return '.env';
289
335
  return null;
290
336
  }
337
+ /**
338
+ * @implements A-SPEC-728
339
+ * `~`, `$HOME`/`${HOME}` and `$CODEX_HOME`/`${CODEX_HOME}` in a path argument, replaced by the values
340
+ * this process sees — or `null` when another variable is left, because its value is unknowable here.
341
+ */
342
+ function expandHomeSpelling(raw, env = process.env, home = os.homedir()) {
343
+ let s = raw;
344
+ if (s === '~')
345
+ s = home;
346
+ else if (s.startsWith('~/'))
347
+ s = home + s.slice(1);
348
+ // `${HOME}`, `${HOME:-x}`, `${HOME:?…}`, `${HOME=…}` all yield HOME's value while HOME is set.
349
+ s = s.replace(/\$\{HOME(?::?[-=?][^}]*)?\}|\$HOME\b/g, () => home);
350
+ if (env.CODEX_HOME)
351
+ s = s.replace(/\$\{CODEX_HOME(?::?[-=?][^}]*)?\}|\$CODEX_HOME\b/g, () => env.CODEX_HOME);
352
+ return s.includes('$') ? null : s;
353
+ }
354
+ /** The Codex homes whose config.toml/hooks.json Codex may load: `$CODEX_HOME` and the default `~/.codex`. */
355
+ function codexHomes(env, home) {
356
+ const out = [path.join(home, '.codex')];
357
+ if (env.CODEX_HOME && path.isAbsolute(env.CODEX_HOME))
358
+ out.unshift(env.CODEX_HOME);
359
+ return out;
360
+ }
361
+ const SETTINGS_NAME = /^settings[\w.-]*\.json$/i;
362
+ /** The `.ax` children that hold governance state — the same set the text rules name (A-SPEC-196 family). */
363
+ exports.AX_PROTECTED_CHILDREN = ['specs', 'decisions', 'ledger', 'cpg_cache', 'state', 'roles', 'approvals', 'entities'];
364
+ /**
365
+ * @implements A-SPEC-728 (round 4) — a path this long is judged by its last name only: resolving a
366
+ * 58 000-component path took 37 s, past the hook timeout, and no filesystem accepts it anyway.
367
+ */
368
+ const MAX_PATH_CHARS = 4096;
369
+ const lastName = (s) => (0, linear_match_1.trimTrailing)(s, '/\\').split(/[/\\]/).pop()?.toLowerCase() ?? '';
370
+ /** How a refusal names the `.ax` directory — the spec store and ledger, not session wiring. */
371
+ exports.GOVERNANCE_STORE_LABEL = '.ax (the spec store and ledger)';
372
+ /** Every directory name that is judged as a whole: the session wiring directories and `.ax`. */
373
+ exports.WIRING_DIR_NAMES = ['.claude', '.agents', '.codex', '.ax'];
374
+ /** Every file name a wiring target can carry — `xargs`/`find` judge by name when paths are unknowable. */
375
+ exports.WIRING_FILE_NAMES = ['settings.json', 'settings.local.json', '.mcp.json', 'hooks.json', 'mcp_config.json', 'config.toml'];
376
+ /** Every directory holding a harness file that loads or configures this session's gate. */
377
+ function wiringDirs(root, env, home) {
378
+ const out = [
379
+ { dir: path.join(home, '.claude'), name: SETTINGS_NAME, known: ['settings.json', 'settings.local.json'], label: (n) => `~/.claude/${n}`, dirIsWiring: true },
380
+ ...codexHomes(env, home).map((dir) => ({ dir, name: /^(?:config\.toml|hooks\.json)$/i, known: ['config.toml', 'hooks.json'], label: (n) => `Codex user ${n}`, dirIsWiring: true })),
381
+ ];
382
+ if (root !== null) {
383
+ out.push({ dir: path.join(root, '.claude'), name: SETTINGS_NAME, known: ['settings.json', 'settings.local.json'], label: (n) => `.claude/${n}`, dirIsWiring: true }, { dir: root, name: /^\.mcp\.json$/i, known: ['.mcp.json'], label: () => '.mcp.json', dirIsWiring: false }, { dir: path.join(root, '.agents'), name: /^(?:hooks|mcp_config)\.json$/i, known: ['hooks.json', 'mcp_config.json'], label: (n) => `.agents/${n}`, dirIsWiring: true }, { dir: path.join(root, '.codex'), name: /^(?:config\.toml|mcp_config\.json)$/i, known: ['config.toml', 'mcp_config.json'], label: (n) => `.codex/${n}`, dirIsWiring: true },
384
+ // @implements A-SPEC-728 (round 9) — `.ax` ITSELF: moving it away turned No-Spec-No-Code off in one
385
+ // call (measured: the next code Write was allowed), and a bulk copy into it replaces the specs and
386
+ // ledger. Files inside keep their own rules; only the directory as a whole is judged here.
387
+ // Round 12 — and the files INSIDE its protected children, by identity: the text rules' flattening
388
+ // skipped a quoted or escaped directory component (`cd .ax && rm "ledger/provenance.jsonl"` deleted
389
+ // the ledger — measured), and their removal channel was case-sensitive (`rm .AX/ledger/…`).
390
+ { dir: path.join(root, '.ax'), name: /(?!)/, known: [], label: (n) => (n ? `.ax/${n}` : exports.GOVERNANCE_STORE_LABEL), dirIsWiring: true, subtree: exports.AX_PROTECTED_CHILDREN });
391
+ }
392
+ return out;
393
+ }
394
+ /**
395
+ * @implements A-SPEC-728 (round 3) — identity lookups are memoised for the span of one judgement: a
396
+ * command with 20 000 arguments re-resolved the same parent directory 20 000 times (3.2 s measured).
397
+ * The cache lives only inside `withIdentCache`, so a long-running process never judges from a stale one.
398
+ */
399
+ let identCache = null;
400
+ /** Real paths (or null: not there) looked up during the judgement in hand — `resolveTarget`'s ancestors. */
401
+ let realCache = null;
402
+ function withIdentCache(fn) {
403
+ if (identCache !== null)
404
+ return fn();
405
+ identCache = new Map();
406
+ realCache = new Map();
407
+ try {
408
+ return fn();
409
+ }
410
+ finally {
411
+ identCache = null;
412
+ realCache = null;
413
+ }
414
+ }
415
+ const ident = (base, p) => {
416
+ const key = `${base}\0${p}`;
417
+ const hit = identCache?.get(key);
418
+ if (hit !== undefined)
419
+ return hit;
420
+ const v = (0, linear_match_1.trimTrailing)(foldSep(resolveTarget(base, p)).toLowerCase(), '/');
421
+ identCache?.set(key, v);
422
+ return v;
423
+ };
424
+ /** Identity of the directory entry itself: the parent resolved, the last component NOT followed (rm removes a link, not its target). */
425
+ const identEntry = (base, p) => {
426
+ const trimmed = (0, linear_match_1.trimTrailing)(p, '/\\');
427
+ const name = path.basename(trimmed);
428
+ if (name === '' || name === '.' || name === '..')
429
+ return ident(base, p);
430
+ return `${ident(base, path.dirname(trimmed) || '.')}/${name.toLowerCase()}`;
431
+ };
432
+ /**
433
+ * @implements A-SPEC-728
434
+ * The user-level harness config a path lands on — `~/.claude/settings*.json`, or `config.toml` /
435
+ * `hooks.json` directly in a Codex home — or `null`. Judged by identity like the in-project check;
436
+ * `base` resolves a relative spelling.
437
+ */
438
+ function userHarnessConfigKindOf(raw, base, env = process.env, home = os.homedir()) {
439
+ const s = expandHomeSpelling(raw, env, home);
440
+ if (s === null)
441
+ return null;
442
+ if (s.length > MAX_PATH_CHARS) {
443
+ const n = lastName(s);
444
+ return SETTINGS_NAME.test(n) || /^(?:config\.toml|hooks\.json)$/i.test(n) ? `${n} (a path too long to resolve)` : null;
445
+ }
446
+ const target = ident(base, s);
447
+ for (const w of wiringDirs(null, env, home)) {
448
+ const d = ident(home, w.dir);
449
+ if (!target.startsWith(d + '/'))
450
+ continue;
451
+ const rest = target.slice(d.length + 1);
452
+ if (!rest.includes('/') && w.name.test(rest))
453
+ return w.label(rest);
454
+ }
455
+ return null;
456
+ }
457
+ const POSIX_CLASS = {
458
+ alpha: 'a-zA-Z', digit: '0-9', alnum: 'a-zA-Z0-9', lower: 'a-z', upper: 'A-Z', space: '\\s',
459
+ xdigit: '0-9a-fA-F', punct: '!-\\/:-@\\[-`{-~', word: '\\w', blank: ' \\t', cntrl: '\\x00-\\x1f', print: ' -~', graph: '!-~',
460
+ };
461
+ // The ignoreCase comparison of a non-unicode RegExp (ECMA-262 Canonicalize), so a literal matches as `/x/i` did.
462
+ const canonical = (ch) => {
463
+ const code = ch.charCodeAt(0);
464
+ if (code < 128)
465
+ return code >= 97 && code <= 122 ? String.fromCharCode(code - 32) : ch;
466
+ const u = ch.toUpperCase();
467
+ return u.length !== 1 || u.charCodeAt(0) < 128 ? ch : u;
468
+ };
469
+ // Compiled matchers by pattern: a command repeats its globs, and wiring checks ask about each one many times.
470
+ const GLOB_CACHE = new Map();
471
+ /** `p` starts with `head`, compared as a case-insensitive regex literal compares. */
472
+ const foldedStartsWith = (p, head) => {
473
+ if (p.length < head.length)
474
+ return false;
475
+ for (let i = 0; i < head.length; i++)
476
+ if (p[i] !== head[i] && canonical(p[i]) !== canonical(head[i]))
477
+ return false;
478
+ return true;
479
+ };
480
+ const LINE_END = /[\n\r\u2028\u2029]/;
481
+ /**
482
+ * @implements A-SPEC-728 (round 2) — ONE glob translator for every rule: `*`, `?`, `[…]` with `!`/`^`
483
+ * negation and `[[:class:]]`, zsh `(a|b)` groups, and `**` spanning zero or more directories. With
484
+ * `dotfiles: false` (the shell), a leading `*`/`?`/`[` of a component does not match a dotfile; `find
485
+ * -name` passes `true`. Case-insensitive: identity is folded the same way.
486
+ * @implements A-SPEC-728 (rule 37) — matched by simulating the pattern's automaton, never by regex
487
+ * backtracking: 22 `**` + `/` groups in a 77-character deletion glob took the 20 s deadline (measured),
488
+ * and interleaved `*` components grow the same way. The language is the regex this translator wrote
489
+ * (`^…$`, case-insensitive, its top-level `|` included); the regex is still built to decide a spelling it
490
+ * cannot read, which is matched as literal text.
491
+ */
492
+ function globPatternRe(glob, dotfiles = false) {
493
+ const key = `${dotfiles ? 1 : 0}${glob}`;
494
+ const cached = GLOB_CACHE.get(key);
495
+ if (cached !== undefined)
496
+ return cached;
497
+ // Rule 43: 65,536 — at 1,024 a command of 40,000 distinct globs recompiled every one on each whole-command question.
498
+ if (GLOB_CACHE.size >= 65_536)
499
+ GLOB_CACHE.clear();
500
+ const made = compileGlob(glob, dotfiles);
501
+ GLOB_CACHE.set(key, made);
502
+ return made;
503
+ }
504
+ function compileGlob(glob, dotfiles) {
505
+ // A hook must never throw on a spelling: unbalanced groups are literal characters.
506
+ let depth = 0, balanced = true;
507
+ for (const ch of glob) {
508
+ if (ch === '(')
509
+ depth++;
510
+ else if (ch === ')' && --depth < 0)
511
+ balanced = false;
512
+ }
513
+ const groups = balanced && depth === 0;
514
+ let re = '';
515
+ let atStart = true;
516
+ const top = [[]];
517
+ const stack = [top];
518
+ const push = (...items) => { const alts = stack[stack.length - 1]; alts[alts.length - 1].push(...items); };
519
+ const noDot = () => (atStart && !dotfiles ? '(?!\\.)' : '');
520
+ const noDotItem = () => (atStart && !dotfiles ? [{ k: 'nodot' }] : []);
521
+ for (let i = 0; i < glob.length; i++) {
522
+ const c = glob[i];
523
+ if (c === '*' && glob[i + 1] === '*') {
524
+ i++;
525
+ if (glob[i + 1] === '/') {
526
+ i++;
527
+ re += '(?:[^/]*/)*';
528
+ push({ k: 'globstar' });
529
+ atStart = true;
530
+ continue;
531
+ }
532
+ re += '.*';
533
+ push({ k: 'any' });
534
+ atStart = false;
535
+ continue;
536
+ }
537
+ if (c === '*') {
538
+ re += noDot() + '[^/]*';
539
+ push(...noDotItem(), { k: 'star' });
540
+ atStart = false;
541
+ continue;
542
+ }
543
+ if (c === '?') {
544
+ re += noDot() + '[^/]';
545
+ push(...noDotItem(), { k: 'one' });
546
+ atStart = false;
547
+ continue;
548
+ }
549
+ if (c === '[') {
550
+ let j = i + 1;
551
+ let body = '';
552
+ if (glob[j] === '!' || glob[j] === '^') {
553
+ body += '^';
554
+ j++;
555
+ }
556
+ if (glob[j] === ']') {
557
+ body += '\\]';
558
+ j++;
559
+ }
560
+ let closed = false;
561
+ for (; j < glob.length; j++) {
562
+ if (glob[j] === ']') {
563
+ closed = true;
564
+ break;
565
+ }
566
+ const cls = /^\[:([a-z]+):\]/.exec(glob.slice(j));
567
+ if (cls) {
568
+ body += POSIX_CLASS[cls[1]] ?? '';
569
+ j += cls[0].length - 1;
570
+ continue;
571
+ }
572
+ body += /[\\\]^]/.test(glob[j]) ? `\\${glob[j]}` : glob[j];
573
+ }
574
+ if (!closed) {
575
+ re += '\\[';
576
+ push({ k: 'lit', c: '[' });
577
+ atStart = false;
578
+ continue;
579
+ }
580
+ let cls;
581
+ try {
582
+ cls = new RegExp(`^[${body}]$`, 'i');
583
+ }
584
+ catch {
585
+ cls = /$^/;
586
+ }
587
+ re += noDot() + `[${body}]`;
588
+ push(...noDotItem(), { k: 'cls', re: cls });
589
+ i = j;
590
+ atStart = false;
591
+ continue;
592
+ }
593
+ if (groups && c === '(') {
594
+ re += '(?:';
595
+ const g = { k: 'group', alts: [[]] };
596
+ push(g);
597
+ stack.push(g.alts);
598
+ continue;
599
+ }
600
+ // Rule 39: a `(` inside a `[…]` class is counted as balanced but read as the class's, so a `)` can have no group to
601
+ // close (`[(])` threw — measured); the regex this builds is then invalid and the glob is matched as literal text.
602
+ if (groups && c === ')') {
603
+ re += ')';
604
+ if (stack.length > 1)
605
+ stack.pop();
606
+ atStart = false;
607
+ continue;
608
+ }
609
+ if (groups && c === '|') {
610
+ re += '|';
611
+ stack[stack.length - 1].push([]);
612
+ continue;
613
+ }
614
+ if (c === '/') {
615
+ re += '/';
616
+ push({ k: 'lit', c: '/' });
617
+ atStart = true;
618
+ continue;
619
+ }
620
+ re += c.replace(/[.+^${}()|\\]/g, '\\$&');
621
+ push({ k: 'lit', c });
622
+ atStart = false;
623
+ }
624
+ try {
625
+ new RegExp(`^${re}$`, 'i');
626
+ }
627
+ catch {
628
+ return {
629
+ source: glob.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
630
+ test: (t) => {
631
+ if (t.length !== glob.length)
632
+ return false;
633
+ for (let k = 0; k < t.length; k++)
634
+ if (canonical(t[k]) !== canonical(glob[k]))
635
+ return false;
636
+ return true;
637
+ },
638
+ };
639
+ }
640
+ // A top-level `|` in `^A|B|C$` anchors only its outer ends: A at the start, C at the end, B anywhere.
641
+ const alts = top.length === 1 ? top : top.map((a, k) => [
642
+ ...(k > 0 ? [{ k: 'anyall' }] : []), ...a, ...(k < top.length - 1 ? [{ k: 'anyall' }] : [])
643
+ ]);
644
+ const states = [];
645
+ const add = (st) => { states.push(st); return states.length - 1; };
646
+ const loop = (k, next) => {
647
+ const s = add({ t: 'split', a: -1, b: next });
648
+ states[s].a = add({ t: 'char', k, out: s });
649
+ return s;
650
+ };
651
+ const item = (it, next) => {
652
+ switch (it.k) {
653
+ case 'lit': return add({ t: 'char', k: 0, c: canonical(it.c), out: next });
654
+ case 'one': return add({ t: 'char', k: 1, out: next });
655
+ case 'cls': return add({ t: 'char', k: 4, re: it.re, out: next });
656
+ case 'nodot': return add({ t: 'nodot', out: next });
657
+ case 'star': return loop(1, next);
658
+ case 'any': return loop(2, next);
659
+ case 'anyall': return loop(3, next);
660
+ case 'globstar': {
661
+ const s = add({ t: 'split', a: -1, b: next });
662
+ const inner = add({ t: 'split', a: -1, b: -1 });
663
+ states[inner].a = add({ t: 'char', k: 1, out: inner });
664
+ states[inner].b = add({ t: 'char', k: 5, out: s });
665
+ states[s].a = inner;
666
+ return s;
667
+ }
668
+ case 'group': return choice(it.alts, next);
669
+ }
670
+ };
671
+ const sequence = (items, next) => {
672
+ for (let k = items.length - 1; k >= 0; k--)
673
+ next = item(items[k], next);
674
+ return next;
675
+ };
676
+ const choice = (options, next) => {
677
+ const starts = options.map((o) => sequence(o, next));
678
+ let s = starts[starts.length - 1];
679
+ for (let k = starts.length - 2; k >= 0; k--)
680
+ s = add({ t: 'split', a: starts[k], b: s });
681
+ return s;
682
+ };
683
+ const accept = add({ t: 'match' });
684
+ const start = choice(alts, accept);
685
+ const mark = new Int32Array(states.length).fill(-1);
686
+ return {
687
+ source: re,
688
+ test(t) {
689
+ let gen = 0;
690
+ mark.fill(-1);
691
+ const closure = (list, from, at) => {
692
+ const todo = [from];
693
+ while (todo.length > 0) {
694
+ const k = todo.pop();
695
+ if (mark[k] === gen)
696
+ continue;
697
+ mark[k] = gen;
698
+ const st = states[k];
699
+ if (st.t === 'split') {
700
+ todo.push(st.b, st.a);
701
+ continue;
702
+ }
703
+ if (st.t === 'nodot') {
704
+ if (at >= t.length || t[at] !== '.')
705
+ todo.push(st.out);
706
+ continue;
707
+ }
708
+ list.push(k);
709
+ }
710
+ };
711
+ let cur = [];
712
+ closure(cur, start, 0);
713
+ for (let at = 0; at < t.length && cur.length > 0; at++) {
714
+ gen++;
715
+ const next = [];
716
+ const ch = t[at];
717
+ let folded = null;
718
+ for (const k of cur) {
719
+ const st = states[k];
720
+ if (st.t !== 'char')
721
+ continue;
722
+ const hit = st.k === 0 ? (folded ??= canonical(ch)) === st.c
723
+ : st.k === 1 ? ch !== '/'
724
+ : st.k === 2 ? !LINE_END.test(ch)
725
+ : st.k === 3 ? true
726
+ : st.k === 4 ? st.re.test(ch)
727
+ : ch === '/';
728
+ if (hit)
729
+ closure(next, st.out, at + 1);
730
+ }
731
+ cur = next;
732
+ }
733
+ return cur.some((k) => states[k].t === 'match');
734
+ },
735
+ };
736
+ }
737
+ /**
738
+ * @implements A-SPEC-728
739
+ * Which governance wiring target a deletion argument takes away, or `null`. Deleting a wiring file
740
+ * disarms the gate exactly as rewriting it does. A hit is the entry itself (a link is judged as the
741
+ * link — `rm` removes it, not its target), a directory holding one when the deletion is recursive,
742
+ * or a glob that can expand to one. `base` is the segment's working directory; `null` (unknowable)
743
+ * judges only absolute and home-relative arguments.
744
+ */
745
+ function wiringDeletionKindOf(root, base, arg, env = process.env, home = os.homedir(), recursive = true) {
746
+ const s = expandHomeSpelling(arg, env, home);
747
+ if (s === null || s === '')
748
+ return null;
749
+ if (s.length > MAX_PATH_CHARS) {
750
+ const n = lastName(s);
751
+ return exports.WIRING_FILE_NAMES.includes(n) || (recursive && exports.WIRING_DIR_NAMES.includes(n)) ? `${n} (a path too long to resolve)` : null;
752
+ }
753
+ if (base === null && absoluteKindOf(s) === null)
754
+ return null;
755
+ const from = base ?? root;
756
+ const firstGlob = s.search(/[*?[(]/);
757
+ const dirs = wiringDirs(root, env, home).map((w) => ({ ...w, id: ident(home, w.dir) }));
758
+ if (firstGlob < 0) {
759
+ const entry = identEntry(from, s);
760
+ // rm/mv act on the entry, not on what a link points to — except a trailing slash, which follows it.
761
+ const followed = /[/\\]$/.test(s) ? ident(from, s) : entry;
762
+ for (const w of dirs) {
763
+ if (recursive && (w.id === followed || w.id.startsWith(followed + '/')))
764
+ return w.label(w.known[0]); // a directory holding one
765
+ if (entry.startsWith(w.id + '/')) {
766
+ const rest = entry.slice(w.id.length + 1);
767
+ if (!rest.includes('/') && w.name.test(rest))
768
+ return w.label(rest);
769
+ if (w.subtree !== undefined && w.subtree.includes(rest.split('/')[0]))
770
+ return w.label(rest);
771
+ }
772
+ }
773
+ return null;
774
+ }
775
+ // A glob too long to translate safely is judged by its last component's name only.
776
+ if (s.length > 1024) {
777
+ const last = (0, linear_match_1.trimTrailing)(s, '/\\').split(/[/\\]/).pop() ?? '';
778
+ if (last.length > 256)
779
+ return 'a glob too long to judge';
780
+ const re = globPatternRe(last, false);
781
+ const hit = dirs.flatMap((w) => w.known.filter((n) => re.test(n)).map((n) => w.label(n)))[0];
782
+ return hit ?? (recursive && exports.WIRING_DIR_NAMES.some((d) => re.test(d)) ? `${last} (a wiring directory)` : null);
783
+ }
784
+ // Glob: the fixed directory before the first glob component resolved by identity, then the rest of
785
+ // the pattern matched against every wiring file and wiring directory path under it.
786
+ const cut = s.search(/[*?[(]/);
787
+ const slash = Math.max(s.lastIndexOf('/', cut), s.lastIndexOf('\\', cut));
788
+ const fixed = ident(from, slash < 0 ? '.' : s.slice(0, slash + 1) || '/');
789
+ const restGlob = s.slice(slash + 1).replace(/\\/g, '/').toLowerCase();
790
+ // Rule 37: a fixed directory without a glob character is compared as text and only the rest is compiled — compiling
791
+ // it into every argument's pattern cost a third of a 256 KB command of distinct globs (measured). The same language:
792
+ // a literal prefix fixes where the rest starts; a top-level `|` (which would free the prefix) takes the whole pattern.
793
+ const head = `${fixed}/`;
794
+ const plainHead = !/[*?[()|\\]/.test(fixed) && !restGlob.includes('|');
795
+ const restRe = plainHead ? globPatternRe(restGlob) : null;
796
+ const re = restRe !== null
797
+ ? { test: (p) => foldedStartsWith(p, head) && restRe.test(p.slice(head.length)) }
798
+ : globPatternRe(`${fixed}/${restGlob}`.replace(/^\//, '/'));
799
+ for (const w of dirs) {
800
+ for (const n of w.known)
801
+ if (re.test(`${w.id}/${n}`))
802
+ return w.label(n);
803
+ if (!recursive)
804
+ continue;
805
+ // A recursive deletion of a directory that holds a wiring target: any ancestor path of it.
806
+ const parts = w.id.split('/');
807
+ for (let k = parts.length; k > 1; k--) {
808
+ const anc = parts.slice(0, k).join('/');
809
+ if (anc.length <= fixed.length)
810
+ break;
811
+ if (re.test(anc))
812
+ return w.label(w.known[0]);
813
+ }
814
+ }
815
+ // Round 12 — a glob over a protected subtree: its fixed directory lies inside a protected child, or its
816
+ // components can match the way from the fixed directory to `.ax/<child>` (`.a*/ledger/x`, `ledge*/…`).
817
+ const comps = s.slice(slash + 1).replace(/\\/g, '/').toLowerCase().split('/').filter((c) => c !== '');
818
+ for (const w of dirs) {
819
+ if (w.subtree === undefined)
820
+ continue;
821
+ const inside = path.posix.relative(w.id, fixed);
822
+ if (inside !== '' && !inside.startsWith('..') && !path.posix.isAbsolute(inside)) {
823
+ if (w.subtree.includes(inside.split('/')[0]))
824
+ return w.label(`${inside}/${comps.join('/')} (a glob)`);
825
+ continue;
826
+ }
827
+ const down = path.posix.relative(fixed, w.id);
828
+ if (down.startsWith('..') || path.posix.isAbsolute(down))
829
+ continue;
830
+ const toAx = down === '' ? [] : down.split('/');
831
+ for (const child of w.subtree)
832
+ if (globCoversPrefix(comps, [...toAx, child]))
833
+ return w.label(`${child}/… (a glob ${s.slice(slash + 1)})`);
834
+ }
835
+ return null;
836
+ }
837
+ /**
838
+ * @implements A-SPEC-728 (rule 44) — `placed` remembers each candidate's placement across calls of one judgement: every stdin
839
+ * program's children carry their own list, and 300 `cd a` lines then 300 `bash -s` heredocs placed all 300 candidates again
840
+ * for each heredoc (2.9 s — measured).
841
+ */
842
+ function axCandidateKeys(root, candidates, maxDepth = Infinity, placed) {
843
+ // The real path of `p`, or of its nearest existing ancestor joined with the rest (a target that does
844
+ // not exist yet under an aliased or linked directory). Memoized: candidates share their parents.
845
+ const memo = new Map();
846
+ const looked = new Map();
847
+ // `existsSync` first: a thrown ENOENT costs ~20 µs and most candidates of a long command do not exist
848
+ // (10,000 `cd a<i>` targets: 225 ms → 104 ms, measured; the whole hook at 280 KB: 744 ms).
849
+ const realOf = (p) => {
850
+ let r = looked.get(p);
851
+ if (r === undefined) {
852
+ r = null;
853
+ if (fs.existsSync(p)) {
854
+ try {
855
+ r = fs.realpathSync.native(p);
856
+ }
857
+ catch {
858
+ r = null;
859
+ }
860
+ }
861
+ looked.set(p, r);
862
+ }
863
+ return r;
864
+ };
865
+ // @implements A-SPEC-728 (rule 38) — the nearest existing ancestor is found by halving, as `resolveTarget` finds it, and the
866
+ // rest joined once: one recursion and one memoised joined string per missing component was quadratic in time and memory
867
+ // (16,000 missing components exhausted the worker's heap — measured).
868
+ const realDeep = (p) => {
869
+ const hit = memo.get(p);
870
+ if (hit !== undefined)
871
+ return hit;
872
+ const chain = [p];
873
+ for (let cur = p, parent = path.dirname(cur); parent !== cur; cur = parent, parent = path.dirname(cur))
874
+ chain.push(parent);
875
+ let lo = 0, hi = chain.length - 1;
876
+ while (lo < hi) {
877
+ const mid = (lo + hi) >> 1;
878
+ if (realOf(chain[mid]) !== null)
879
+ hi = mid;
880
+ else
881
+ lo = mid + 1;
882
+ }
883
+ const real = realOf(chain[hi]);
884
+ const out = real === null ? p : hi === 0 ? real : path.join(real, ...chain.slice(0, hi).reverse().map((c) => path.basename(c)));
885
+ memo.set(p, out);
886
+ return out;
887
+ };
888
+ const axRoot = path.join(root, '.ax');
889
+ let realAx;
890
+ const fold = (p) => p.normalize('NFC').toUpperCase();
891
+ const compsUnder = (p, base) => {
892
+ const r = path.relative(base, p);
893
+ if (r === '')
894
+ return [];
895
+ return r.startsWith('..') || path.isAbsolute(r) ? null : r.split(path.sep);
896
+ };
897
+ const placeOf = (m) => {
898
+ // @implements A-SPEC-728 (round 17) — placed by IDENTITY first, then by spelling (case-folded): a link
899
+ // `axlink → .ax` already on disk was dropped for not being spelled `.ax` before its real path was
900
+ // read, and `npm test; cd axlink; rm ledger/provenance.jsonl` deleted the ledger (measured).
901
+ if (realAx === undefined)
902
+ realAx = realDeep(axRoot);
903
+ const rm = realDeep(m);
904
+ const comps = compsUnder(rm, realAx) ?? compsUnder(fold(m), fold(axRoot)) ?? compsUnder(fold(rm), fold(realAx));
905
+ if (comps === null)
906
+ return null;
907
+ if (comps.length === 0)
908
+ return { at: 'root' };
909
+ const child = comps[0].normalize('NFC').toLowerCase();
910
+ return exports.AX_PROTECTED_CHILDREN.includes(child) ? { at: 'child', child, depth: comps.length } : { at: 'climb', depth: comps.length };
911
+ };
912
+ let atRoot = false;
913
+ const deepest = new Map();
914
+ const climbDepths = new Set();
915
+ for (const m of candidates) {
916
+ let p = placed?.get(m);
917
+ if (p === undefined) {
918
+ p = placeOf(m);
919
+ placed?.set(m, p);
920
+ }
921
+ if (p === null)
922
+ continue;
923
+ if (p.at === 'root') {
924
+ atRoot = true;
925
+ continue;
926
+ }
927
+ // Round 15 (measured): keyed by every distinct child, 500 `cd .ax/d<i>` targets took 2.9 s and 2,000
928
+ // exhausted the worker's heap — the keys are now the store's layout, not the command's.
929
+ if (p.at === 'child')
930
+ deepest.set(p.child, Math.max(deepest.get(p.child) ?? 0, p.depth));
931
+ else
932
+ climbDepths.add(p.depth);
933
+ }
934
+ const bases = [];
935
+ if (atRoot)
936
+ bases.push(axRoot);
937
+ // Rule 39: no deeper than `maxDepth` (the caller's longest `../` climb and one) — a deeper key only lengthened every word.
938
+ for (const [child, depth] of deepest)
939
+ bases.push(path.join(axRoot, child, ...new Array(Math.min(depth, maxDepth) - 1).fill('~')));
940
+ return { bases, climbDepths };
941
+ }
942
+ /**
943
+ * @implements A-SPEC-728 (rule 44) — the climb bases one segment is judged at: past 8 the command is refused as too large to
944
+ * judge (60 climbs of distinct depths after cds through a link `axl -> .ax`, at 256 KB, took 5.2 s — measured).
945
+ */
946
+ exports.AX_CLIMB_BASES_MAX = 8;
947
+ /** The placeholder bases a segment's own `..` climbs make relevant (one per climb count it uses that a candidate stood at). */
948
+ function axClimbBases(root, keys, text) {
949
+ if (keys.climbDepths.size === 0)
950
+ return [];
951
+ const counts = new Set();
952
+ for (const m of text.matchAll(/(?:^|[\s'"=(])((?:\.\.[\\/])+)/g))
953
+ counts.add(m[1].length / 3);
954
+ const out = [];
955
+ for (const c of counts)
956
+ if (keys.climbDepths.has(c))
957
+ out.push(path.join(root, '.ax', ...new Array(c).fill('~')));
958
+ return out;
959
+ }
960
+ /** Whether glob components `P` can match a path that starts with the components `T` (`**` spans any number). */
961
+ function globCoversPrefix(P, T) {
962
+ const memo = new Map();
963
+ const go = (i, j) => {
964
+ if (j === T.length)
965
+ return true;
966
+ if (i === P.length)
967
+ return false;
968
+ const key = `${i},${j}`;
969
+ const hit = memo.get(key);
970
+ if (hit !== undefined)
971
+ return hit;
972
+ const v = P[i] === '**' ? (go(i + 1, j) || go(i, j + 1)) : (globPatternRe(P[i], true).test(T[j]) && go(i + 1, j + 1));
973
+ memo.set(key, v);
974
+ return v;
975
+ };
976
+ return go(0, 0);
977
+ }
978
+ /**
979
+ * @implements A-SPEC-728
980
+ * Which governance wiring target a WRITE lands on, or `null`: the wiring file itself (followed
981
+ * through links — a write through a link writes its target), or a wiring directory itself (an
982
+ * archive or copy extracted into `~/.codex` can replace its hooks). The project root and the home
983
+ * directory are not wiring directories.
984
+ */
985
+ function wiringWriteKindOf(root, base, arg, env = process.env, home = os.homedir()) {
986
+ const s = expandHomeSpelling(arg, env, home);
987
+ if (s === null || s === '' || /[*?[]/.test(s))
988
+ return null;
989
+ if (s.length > MAX_PATH_CHARS) {
990
+ const n = lastName(s);
991
+ return exports.WIRING_FILE_NAMES.includes(n) ? `${n} (a path too long to resolve)` : null;
992
+ }
993
+ // A write through a link writes its target; otherwise the entry is the file (cheap: no realpath).
994
+ // The link test is memoised with the identities (45 000 redirects to one name: 0.5 s of lstat, round 4).
995
+ const linkKey = `\u0001${base}\0${s}`;
996
+ let link = identCache?.get(linkKey);
997
+ if (link === undefined) {
998
+ link = '0';
999
+ // Rule 46: asked without an exception for a missing file — 51,000 missing tar members threw 51,000 ENOENT (2.0 s — measured).
1000
+ try {
1001
+ if (fs.lstatSync(pathFlavorFor(base, s).resolve(base, s), { throwIfNoEntry: false })?.isSymbolicLink() === true)
1002
+ link = '1';
1003
+ }
1004
+ catch { /* unreadable: the entry */ }
1005
+ identCache?.set(linkKey, link);
1006
+ }
1007
+ const target = link === '1' ? ident(base, s) : identEntry(base, s);
1008
+ for (const w of wiringDirs(root, env, home)) {
1009
+ const id = ident(home, w.dir);
1010
+ if (w.dirIsWiring && target === id)
1011
+ return w.known.length === 0 ? w.label('') : `${w.label('').replace(/\/$/, '').replace(/ $/, '')} directory`;
1012
+ if (target.startsWith(id + '/')) {
1013
+ const rest = target.slice(id.length + 1);
1014
+ if (!rest.includes('/') && w.name.test(rest))
1015
+ return w.label(rest);
1016
+ if (w.subtree !== undefined && w.subtree.includes(rest.split('/')[0]))
1017
+ return w.label(rest); // round 12
1018
+ }
1019
+ }
1020
+ return null;
1021
+ }
291
1022
  function protectedKindOf(root, raw) {
292
1023
  // @implements A-SPEC-220.2
293
1024
  const pp = pathFlavorFor(root, raw);
@@ -302,14 +1033,1327 @@ function protectedKindOf(root, raw) {
302
1033
  }
303
1034
  return null;
304
1035
  }
305
- const HEREDOC_RE = /<<-?\s*(['"]?)([A-Za-z_]\w*)\1/;
1036
+ // @implements A-SPEC-728 (round 4) — sticky: matched AT each `<<` (a `.slice(k)` per `<<` was
1037
+ // quadratic: 10 s on 50 000 of them). The delimiter is any shell word — `\EOF`, `1`, `EOF-X` —
1038
+ // or a quoted one; the body ends at a line equal to it.
1039
+ const HEREDOC_RE = /<<-?[ \t]*(?:(['"])([^'"\n]+)\1|\\?([^\s;&|<>()'"`$\\]+))/y;
1040
+ const heredocDelimiter = (m) => m[2] ?? m[3];
306
1041
  const SHELL_STDIN_RE = /(?:^|[\s;|&(])(?:sh|bash|zsh|dash|ksh)\b[^<\n]*<</;
307
- const PROG_STRING_RE = /\b(?:(?:sh|bash|zsh|dash|ksh)\b[^\n;|&]*?-c|eval)\s+(?:'([^']*)'|"([^"]*)")/g;
308
- function shellSegments(command, startBase, depth = 0) {
1042
+ // @implements A-SPEC-728 (round 3) — a heredoc whose body an INTERPRETER reads is a program, not data.
1043
+ const INTERP_STDIN_RE = /(?:^|[\s;|&(])(?:node|nodejs|python[0-9.]*|ruby|perl|php|deno|bun)\b[^<\n]*<</;
1044
+ /**
1045
+ * @implements A-SPEC-728 (round 3) — the `<<` of a line that is OUTSIDE quotes and comments, given the
1046
+ * quote state carried in from earlier lines. A `<<` inside `echo "<<EOF"` or `# <<X` is not a heredoc,
1047
+ * and treating it as one hid every following line from the gate.
1048
+ */
1049
+ function unquotedHeredoc(line, st) {
1050
+ let found = null;
1051
+ for (let k = 0; k < line.length; k++) {
1052
+ const ch = line[k];
1053
+ if (st.q !== null) {
1054
+ if (ch === '\\' && st.q === '"') {
1055
+ k++;
1056
+ continue;
1057
+ }
1058
+ if (ch === st.q)
1059
+ st.q = null;
1060
+ continue;
1061
+ }
1062
+ if (ch === '\\') {
1063
+ k++;
1064
+ continue;
1065
+ }
1066
+ if (ch === "'" || ch === '"') {
1067
+ st.q = ch;
1068
+ continue;
1069
+ }
1070
+ if (ch === '#' && (k === 0 || /\s/.test(line[k - 1])))
1071
+ break;
1072
+ // `$((a << b))` is arithmetic, not a heredoc (round 4).
1073
+ if (ch === '$' && line[k + 1] === '(' && line[k + 2] === '(') {
1074
+ const end = line.indexOf('))', k + 3);
1075
+ k = end < 0 ? line.length : end + 1;
1076
+ continue;
1077
+ }
1078
+ if (ch === '<' && line[k + 1] === '<' && line[k + 2] === '<') {
1079
+ k += 2;
1080
+ continue;
1081
+ } // `<<<` here-string
1082
+ if (ch === '<' && line[k + 1] === '<' && found === null) {
1083
+ HEREDOC_RE.lastIndex = k;
1084
+ const m = HEREDOC_RE.exec(line);
1085
+ if (m) {
1086
+ found = m;
1087
+ k += m[0].length - 1;
1088
+ }
1089
+ }
1090
+ }
1091
+ return found;
1092
+ }
1093
+ // @implements A-SPEC-728 (round 3) — `eval` only as the COMMAND word: `deno eval "…"` is deno's argument.
1094
+ // Round 4: the gap between a shell word and its `-c` may not cross another shell word — 38 000 `bash`
1095
+ // words made every one rescan the rest (4 s); the nearest shell word before `-c` is the same program.
1096
+ // @implements A-SPEC-728 (rule 34) — and wherever the shell runs one: a cluster holding `c` (`bash -lc`, `sh -xc`), a `--` before
1097
+ // the program, and `su -c` (`bash -lc 'rm ledger/…'` stayed one segment and passed — measured). The cluster is matched with a
1098
+ // lookahead so a long run of letters is scanned once.
1099
+ const PROG_STRING_RE = /(?:\b(?:sh|bash|zsh|dash|ksh|su)\b(?:(?!\b(?:sh|bash|zsh|dash|ksh|su)\b)[^\n;|&])*?(?<=\s)-(?=[A-Za-z]*c)[A-Za-z]+(?:\s+--)?|^\s*(?:(?:builtin|command)\s+)?eval)\s+(?:'([^']*)'|"((?:[^"\\]|\\.)*)")/g;
1100
+ /**
1101
+ * @implements A-SPEC-728 (round 9) — a cd moves the base only when it is certain. Round 8 read only the
1102
+ * separator AFTER a cd and followed cds the shell skipped (`false && cd /tmp ;`), failed (`cd /nope &&
1103
+ * true;`), ran in a subshell (`(cd /tmp && :);`) or ran elsewhere (`cd ~-`, `pushd +1`, `CDPATH=`,
1104
+ * a link made earlier in the same command) — each rewrote the project file in bash and zsh.
1105
+ */
1106
+ const isSearchableDir = (p) => {
1107
+ try {
1108
+ return fs.statSync(p).isDirectory() && (fs.accessSync(p, fs.constants.X_OK), true);
1109
+ }
1110
+ catch {
1111
+ return false;
1112
+ }
1113
+ };
1114
+ /** A cd-like word in a command position the leading-cd reader does not parse (`then cd`, `a) cd`, `f() { cd`). */
1115
+ const CD_WORD_RE = /(?:^|[;&|(){}!]|\b(?:then|do|else|elif|if|while|until|time|exec|nohup|command|builtin|noglob|nocorrect)\s)\s*(?:cd|chdir|pushd|popd|source|eval|\.)(?=\s|$)/;
1116
+ // @implements A-SPEC-733 (round 9) — one pass: the regex form restarted at every `"` of an unterminated
1117
+ // string (80 KB of `\"`: 4.6 s per hook call — measured). An unterminated quote blanks the rest: the
1118
+ // shell would not run such a command at all.
1119
+ const blankQuotes = (t) => {
1120
+ const parts = [];
1121
+ let last = 0;
1122
+ for (let i = 0; i < t.length; i++) {
1123
+ const ch = t[i];
1124
+ if (ch !== "'" && ch !== '"')
1125
+ continue;
1126
+ let j = i + 1;
1127
+ if (ch === "'")
1128
+ j = t.indexOf("'", j);
1129
+ else {
1130
+ while (j < t.length && t[j] !== '"')
1131
+ j += t[j] === '\\' ? 2 : 1;
1132
+ if (j >= t.length)
1133
+ j = -1;
1134
+ }
1135
+ parts.push(t.slice(last, i), '""');
1136
+ if (j < 0)
1137
+ return parts.join('');
1138
+ i = j;
1139
+ last = j + 1;
1140
+ }
1141
+ parts.push(t.slice(last));
1142
+ return parts.join('');
1143
+ };
1144
+ /**
1145
+ * Commands that cannot create or replace the directory a later cd names: the read verbs, the file
1146
+ * writers that make regular files only, and the shell's own builtins. Round 11 (measured): `git log`,
1147
+ * `find`, `awk`, `jq`, `sed -n` outside this list made the next cd uncertain, and a null base skipped
1148
+ * the .ax flattening — one call deleted the ledger.
1149
+ */
1150
+ const CD_SAFE_WORDS = new Set(['', 'cd', 'chdir', 'pushd', 'popd', 'pwd', 'ls', 'echo', 'printf', 'true', 'false', ':', 'test', '[', '[[',
1151
+ 'mkdir', 'cat', 'head', 'tail', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'wc', 'which', 'type', 'dirname', 'basename', 'realpath',
1152
+ 'readlink', 'stat', 'file', 'diff', 'cmp', 'date', 'sleep', 'exit', 'return', 'set', 'export', 'local', 'unset',
1153
+ 'less', 'more', 'bat', 'md5', 'md5sum', 'shasum', 'sha1sum', 'sha256sum', 'sha512sum', 'cksum', 'od', 'hexdump', 'xxd', 'strings',
1154
+ 'sed', 'awk', 'gawk', 'jq', 'yq', 'sort', 'uniq', 'cut', 'tr', 'column', 'nl', 'fold', 'fmt', 'touch', 'tee', 'declare', 'typeset',
1155
+ 'readonly', 'shift', 'read', 'wait', 'break', 'continue', 'find', 'du', 'df', 'env', 'id', 'whoami', 'hostname', 'uname']);
1156
+ /** `git` subcommands that touch no working-tree directory or link. */
1157
+ const GIT_READ_SUBCOMMANDS = new Set(['status', 'log', 'diff', 'show', 'rev-parse', 'branch', 'ls-files', 'blame', 'grep', 'describe',
1158
+ 'remote', 'config', 'tag', 'cat-file', 'rev-list', 'shortlog', 'ls-tree', 'diff-tree', 'fetch', 'add', 'commit']);
1159
+ /** Whether the part's command can create or replace a directory or link (so a later cd is uncertain). */
1160
+ const cdSafe = (part) => {
1161
+ const word = commandWordOf(part);
1162
+ if (word === 'find')
1163
+ return !/\s-(?:exec|execdir|ok|okdir|delete|fprint\w*)\b/.test(part);
1164
+ if (word === 'env')
1165
+ return !/^(?:[\s({!]|(?:then|do|else)\s)*env(?:\s+(?:-\S+|[A-Za-z_]\w*=\S*))*\s*$/.test(part); // `env` alone lists; `env x cmd` runs cmd
1166
+ if (word !== 'git')
1167
+ return CD_SAFE_WORDS.has(word);
1168
+ const rest = part.slice(part.indexOf('git') + 3).trim().split(/\s+/);
1169
+ for (let i = 0; i < rest.length; i++) {
1170
+ const t = rest[i];
1171
+ if (t === '-C' || t === '-c') {
1172
+ i++;
1173
+ continue;
1174
+ }
1175
+ if (t.startsWith('-'))
1176
+ continue;
1177
+ return GIT_READ_SUBCOMMANDS.has(t);
1178
+ }
1179
+ return true;
1180
+ };
1181
+ /** A `cd`/`pushd`/`chdir` word in a command position the leading-cd reader does not parse, with its argument. */
1182
+ const CD_ARG_RE = /(?:^|[;&|(){}!\s])(?:cd|chdir|pushd)\s+(?:-[A-Za-z@]+\s+|--\s+)*([^\s;&|<>()'"`$]+)/g;
1183
+ const commandWordOf = (t) => {
1184
+ const s = t.replace(/^[\s({!]+/, '').replace(/^(?:(?:then|do|else|elif|if|while|until|fi|done|esac|\})(?:\s+|$))+/, '')
1185
+ .replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*(?:\s+|$))+/, '').replace(/^(?:(?:builtin|command|noglob|nocorrect|-)\s+)+/, '');
1186
+ return /^[^\s;&|<>()]*/.exec(s)?.[0] ?? '';
1187
+ };
1188
+ /**
1189
+ * @implements A-SPEC-728 (round 13) — `s` without its redirects (`\s*\d*[<>]{1,2}&?\s*\S+`), in one pass:
1190
+ * the regex restarted at every digit of a run (`cd 111…1`: 80 K digits 2.9 s — measured).
1191
+ */
1192
+ function stripRedirects(s) {
1193
+ const parts = [];
1194
+ let last = 0;
1195
+ for (let i = 0; i < s.length; i++) {
1196
+ if (s[i] !== '<' && s[i] !== '>')
1197
+ continue;
1198
+ let start = i;
1199
+ while (start > last && s[start - 1] >= '0' && s[start - 1] <= '9')
1200
+ start--;
1201
+ while (start > last && /\s/.test(s[start - 1]))
1202
+ start--;
1203
+ let j = i + 1;
1204
+ if (s[j] === '<' || s[j] === '>')
1205
+ j++;
1206
+ if (s[j] === '&')
1207
+ j++;
1208
+ while (j < s.length && /\s/.test(s[j]))
1209
+ j++;
1210
+ const wordStart = j;
1211
+ while (j < s.length && !/\s/.test(s[j]))
1212
+ j++;
1213
+ if (j === wordStart) {
1214
+ i = wordStart - 1;
1215
+ continue;
1216
+ } // no target word: not a redirect
1217
+ parts.push(s.slice(last, start));
1218
+ last = j;
1219
+ i = j - 1;
1220
+ }
1221
+ parts.push(s.slice(last));
1222
+ return parts.join('');
1223
+ }
1224
+ /** Subshell groups a part opens at its start and closes (unmatched `)`), outside quotes. */
1225
+ function groupParens(t) {
1226
+ let k = 0;
1227
+ let opens = 0;
1228
+ while (k < t.length && (t[k] === '(' || t[k] === '{' || /\s/.test(t[k]))) {
1229
+ if (t[k] === '(')
1230
+ opens++;
1231
+ k++;
1232
+ }
1233
+ let local = 0;
1234
+ let closes = 0;
1235
+ let q = null;
1236
+ for (; k < t.length; k++) {
1237
+ const ch = t[k];
1238
+ if (q !== null) {
1239
+ if (ch === '\\' && q === '"') {
1240
+ k++;
1241
+ continue;
1242
+ }
1243
+ if (ch === q)
1244
+ q = null;
1245
+ continue;
1246
+ }
1247
+ if (ch === '\\') {
1248
+ k++;
1249
+ continue;
1250
+ }
1251
+ if (ch === "'" || ch === '"') {
1252
+ q = ch;
1253
+ continue;
1254
+ }
1255
+ if (ch === '(')
1256
+ local++;
1257
+ else if (ch === ')') {
1258
+ if (local > 0)
1259
+ local--;
1260
+ else
1261
+ closes++;
1262
+ }
1263
+ }
1264
+ return { opens, closes };
1265
+ }
1266
+ const freshList = (b) => ({ start: b, cur: b, pipeBase: b, allAnd: true, cdPrefix: true, sawCd: false, certain: true });
1267
+ /**
1268
+ * @implements A-SPEC-728 (round 17)
1269
+ * One shell word of a `cd`, reduced: adjacent quoted pieces join, a backslash escape drops. `null`
1270
+ * when the shell would expand it (an unquoted `*`, `?`, `[`, `(`, `{`) or a quote is unterminated —
1271
+ * the target is then unknowable, and a command that mentions `.ax` is judged in `.ax`.
1272
+ */
1273
+ function reduceCdWord(word) {
1274
+ let out = '';
1275
+ for (let i = 0; i < word.length; i++) {
1276
+ const c = word[i];
1277
+ if (c === "'") {
1278
+ const j = word.indexOf("'", i + 1);
1279
+ if (j < 0)
1280
+ return null;
1281
+ out += word.slice(i + 1, j);
1282
+ i = j;
1283
+ continue;
1284
+ }
1285
+ if (c === '"') {
1286
+ const j = word.indexOf('"', i + 1);
1287
+ if (j < 0)
1288
+ return null;
1289
+ out += word.slice(i + 1, j).replace(/\\(["\\$`])/g, '$1');
1290
+ i = j;
1291
+ continue;
1292
+ }
1293
+ if (c === '\\') {
1294
+ if (i + 1 < word.length) {
1295
+ out += word[i + 1];
1296
+ i++;
1297
+ }
1298
+ continue;
1299
+ }
1300
+ if (c === '*' || c === '?' || c === '[' || c === '(' || c === '{')
1301
+ return null;
1302
+ out += c;
1303
+ }
1304
+ return out;
1305
+ }
1306
+ /**
1307
+ * @implements A-SPEC-728 (round 17)
1308
+ * The directory a shell command is judged FROM: a Codex `workdir` (a relative one anchored at the payload
1309
+ * `cwd` — round 18: rule 22's first draft computed that anchor and discarded it, so `cwd: sub` with
1310
+ * `workdir: ../.ax/ledger` was judged in `sub` — measured), then the payload `cwd`; the first that is an
1311
+ * existing directory inside the project root by identity, spelled under the root; otherwise the root.
1312
+ * Measured before round 17: a session opened in `sub/` had `rm ../.mcp.json` judged at the root, where
1313
+ * `..` leaves the project.
1314
+ */
1315
+ function shellBaseFor(root, workdir, cwd) {
1316
+ const real = (p) => { try {
1317
+ return fs.realpathSync.native(p);
1318
+ }
1319
+ catch {
1320
+ return null;
1321
+ } };
1322
+ const realRoot = real(root) ?? root;
1323
+ const given = (c) => c !== undefined && c !== '';
1324
+ // @implements A-SPEC-728 (round 27) — resolved as the kernel's chdir resolves it, through links before `..`: a harness
1325
+ // working directory `<ws>/tmp/l/..` with `l -> ../src/lib` is `src` (lexically `tmp`; `rm -r lib` there was allowed —
1326
+ // measured). The text-folded spelling is the fallback for a path that does not resolve as written.
1327
+ const raw = (base, p) => (path.isAbsolute(p) ? p : `${base}${path.sep}${p}`);
1328
+ const anchor = given(cwd) ? (real(raw(root, cwd)) ?? path.resolve(root, cwd)) : root;
1329
+ const candidates = [given(workdir) ? raw(anchor, workdir) : undefined, given(cwd) ? raw(root, cwd) : undefined];
1330
+ for (const abs of candidates) {
1331
+ if (abs === undefined)
1332
+ continue;
1333
+ const r = real(abs) ?? real(path.resolve(abs));
1334
+ if (r === null)
1335
+ continue;
1336
+ try {
1337
+ if (!fs.statSync(r).isDirectory())
1338
+ continue;
1339
+ }
1340
+ catch {
1341
+ continue;
1342
+ }
1343
+ const rel = path.relative(realRoot, r);
1344
+ if (rel === '')
1345
+ return root;
1346
+ if (rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel))
1347
+ continue;
1348
+ return path.join(root, rel);
1349
+ }
1350
+ return root;
1351
+ }
1352
+ /**
1353
+ * @implements A-SPEC-728 (round 18)
1354
+ * The target of a directory word as a `cd` would read it: quotes and escapes reduced, `~` and the home
1355
+ * spellings expanded, an expanded or unknowable word (`$X`, a glob) null, a relative word resolved
1356
+ * against `from` (null when `from` is unknown).
1357
+ */
1358
+ function cdTargetOf(rawArg, from) {
1359
+ const arg0 = rawArg.trim();
1360
+ if (arg0 === '')
1361
+ return null;
1362
+ let arg;
1363
+ if (/[$`]/.test(arg0)) {
1364
+ const one = /'|`|\$\(/.test(arg0) || /\s/.test(arg0.replace(/"[^"]*"/g, 'x')) ? null : arg0.replace(/"/g, '');
1365
+ const expanded = one === null ? null : expandHomeSpelling(one);
1366
+ if (expanded === null || /[*?[({]/.test(expanded))
1367
+ return null;
1368
+ arg = expanded;
1369
+ }
1370
+ else {
1371
+ const reduced = reduceCdWord(arg0);
1372
+ if (reduced === null || reduced === '' || reduced === '-')
1373
+ return null;
1374
+ if (reduced === '~')
1375
+ return os.homedir();
1376
+ if (reduced.startsWith('~/'))
1377
+ return path.join(os.homedir(), reduced.slice(2));
1378
+ if (reduced.startsWith('~'))
1379
+ return null;
1380
+ arg = reduced;
1381
+ }
1382
+ if (absoluteKindOf(arg) !== null)
1383
+ return pathFlavorFor(arg, arg).resolve(arg);
1384
+ if (from === null)
1385
+ return null;
1386
+ const to = pathFlavorFor(from, arg).resolve(from, arg);
1387
+ return to.length > 4096 ? null : to;
1388
+ }
1389
+ const WRAP_PLAIN = new Set(['nohup', 'exec', 'time', 'command', 'builtin', 'busybox']);
1390
+ const WRAPPERS = {
1391
+ env: { shortValue: 'uCSPLUa', shortFlag: 'i0v', longValue: ['unset', 'chdir', 'split-string', 'argv0'],
1392
+ longFlag: ['ignore-environment', 'null', 'debug', 'help', 'version', 'block-signal', 'default-signal', 'ignore-signal', 'list-signal-handling'], chdir: 'C', split: 'S' },
1393
+ sudo: { shortValue: 'ughprtUCTDR', shortFlag: 'AbBEeHiKklnNPSsVv', longValue: ['user', 'group', 'prompt', 'host', 'role', 'type', 'other-user', 'close-from', 'command-timeout', 'chdir', 'chroot'],
1394
+ longFlag: ['askpass', 'background', 'bell', 'preserve-env', 'edit', 'help', 'set-home', 'login', 'remove-timestamp', 'reset-timestamp', 'list', 'non-interactive', 'preserve-groups', 'stdin', 'shell', 'version', 'validate'], chdir: 'D' },
1395
+ timeout: { shortValue: 'sk', shortFlag: 'v', longValue: ['signal', 'kill-after'], longFlag: ['foreground', 'preserve-status', 'verbose', 'help', 'version'], duration: true },
1396
+ nice: { shortValue: 'n', shortFlag: '', longValue: ['adjustment'], longFlag: ['help', 'version'], numericFlag: true },
1397
+ stdbuf: { shortValue: 'ioe', shortFlag: '', longValue: ['input', 'output', 'error'], longFlag: ['help', 'version'] },
1398
+ doas: { shortValue: 'uC', shortFlag: 'nsL', longValue: [], longFlag: [] },
1399
+ };
1400
+ /**
1401
+ * @implements A-SPEC-728 (round 18)
1402
+ * A wrapper that CHANGES DIRECTORY for the command it runs — `env -C DIR`/`-CDIR`/`--chdir=DIR`/`--chdir
1403
+ * DIR`, `sudo -D DIR`/`--chdir=DIR` — behind any other wrapper, option or assignment. Measured: the
1404
+ * option was stripped as a wrapper argument and `env -C .ax rm ledger/provenance.jsonl`, judged at the
1405
+ * root, deleted the ledger (macOS and GNU `env` both chdir; `--chdir` is GNU-only). Returns the
1406
+ * directory words and the command that follows, or null.
1407
+ */
1408
+ /** Round 21: a shell word with its escapes, `\"` inside double quotes, and quoted spans (an unclosed quote ends it). */
1409
+ const WRAP_WORD_RE = /(?:\\[\s\S]|[^\s'"\\]|'[^']*'|"(?:[^"\\]|\\[\s\S])*")+/g;
1410
+ /** The safety limit on the reader's steps; reaching it fails CLOSED (an ambiguous, unknown base), never open. */
1411
+ const WRAP_STEPS_MAX = 1_000_000;
1412
+ /** A shell word as the program receives it; `dynamic` when an expansion (`$`, a backtick) outside single quotes shapes it. */
1413
+ function staticWord(raw) {
1414
+ let text = '';
1415
+ let dynamic = false;
1416
+ for (let i = 0; i < raw.length; i++) {
1417
+ const c = raw[i];
1418
+ if (c === '\\') {
1419
+ i++;
1420
+ if (i < raw.length && raw[i] !== '\n')
1421
+ text += raw[i];
1422
+ continue;
1423
+ }
1424
+ if (c === "'") {
1425
+ const e = raw.indexOf("'", i + 1);
1426
+ const stop = e < 0 ? raw.length : e;
1427
+ text += raw.slice(i + 1, stop);
1428
+ i = stop;
1429
+ continue;
1430
+ }
1431
+ if (c === '"') {
1432
+ let j = i + 1;
1433
+ for (; j < raw.length && raw[j] !== '"'; j++) {
1434
+ if (raw[j] === '\\' && j + 1 < raw.length && '"\\$`\n'.includes(raw[j + 1])) {
1435
+ j++;
1436
+ if (raw[j] !== '\n')
1437
+ text += raw[j];
1438
+ continue;
1439
+ }
1440
+ if (raw[j] === '$' || raw[j] === '`')
1441
+ dynamic = true;
1442
+ text += raw[j];
1443
+ }
1444
+ i = j;
1445
+ continue;
1446
+ }
1447
+ if (c === '$' || c === '`')
1448
+ dynamic = true;
1449
+ text += c;
1450
+ }
1451
+ return { text, dynamic };
1452
+ }
1453
+ /** A literal word as a shell word for the judged text: bare when it needs no quoting. */
1454
+ const quoteLiteral = (w) => (w !== '' && /^[A-Za-z0-9_./@%+=:,-]+$/.test(w) ? w : `'${w.replace(/'/g, `'\\''`)}'`);
1455
+ /** A directory word that can never be resolved (an expansion shaped it): the base becomes unknown. */
1456
+ const UNKNOWN_DIR = '"$__holmes_unknown_dir"';
1457
+ /**
1458
+ * @implements A-SPEC-728 (round 21) — `env -S STRING` split as env splits it (GNU and BSD): single quotes are
1459
+ * literal (`\\`, `\'` aside), double quotes and bare text take `\"`, `\\`, `\$`, `\#`, `\n`, `\t`, `\f`, `\v`,
1460
+ * `\r`, `\_` (a separator outside quotes, a space inside); a `#` that begins a word is a comment to the end,
1461
+ * `\c` stops; any `$` env would expand (`${VAR}`) makes the words unknowable (`dynamic`).
1462
+ */
1463
+ function envSplitWords(s) {
1464
+ const ESC = { n: '\n', t: '\t', f: '\f', v: '\v', r: '\r' };
1465
+ const words = [];
1466
+ let cur = '';
1467
+ let inWord = false;
1468
+ let dynamic = false;
1469
+ const end = () => { if (inWord) {
1470
+ words.push(cur);
1471
+ cur = '';
1472
+ inWord = false;
1473
+ } };
1474
+ let i = 0;
1475
+ scan: while (i < s.length) {
1476
+ const c = s[i];
1477
+ if (c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f' || c === '\v') {
1478
+ end();
1479
+ i++;
1480
+ continue;
1481
+ }
1482
+ if (c === '#' && !inWord)
1483
+ break;
1484
+ if (c === "'") {
1485
+ inWord = true;
1486
+ for (i++; i < s.length && s[i] !== "'"; i++) {
1487
+ if (s[i] === '\\' && (s[i + 1] === '\\' || s[i + 1] === "'"))
1488
+ i++;
1489
+ cur += s[i] ?? '';
1490
+ }
1491
+ i++;
1492
+ continue;
1493
+ }
1494
+ if (c === '"') {
1495
+ inWord = true;
1496
+ for (i++; i < s.length && s[i] !== '"'; i++) {
1497
+ if (s[i] === '\\') {
1498
+ const n = s[i + 1];
1499
+ if (n === 'c')
1500
+ break scan;
1501
+ i++;
1502
+ cur += n === '_' ? ' ' : ESC[n ?? ''] ?? n ?? '';
1503
+ continue;
1504
+ }
1505
+ if (s[i] === '$')
1506
+ dynamic = true;
1507
+ cur += s[i];
1508
+ }
1509
+ i++;
1510
+ continue;
1511
+ }
1512
+ if (c === '\\') {
1513
+ const n = s[i + 1];
1514
+ if (n === 'c')
1515
+ break;
1516
+ if (n === '_') {
1517
+ end();
1518
+ i += 2;
1519
+ continue;
1520
+ }
1521
+ inWord = true;
1522
+ cur += ESC[n ?? ''] ?? n ?? '';
1523
+ i += 2;
1524
+ continue;
1525
+ }
1526
+ if (c === '$')
1527
+ dynamic = true;
1528
+ inWord = true;
1529
+ cur += c;
1530
+ i++;
1531
+ }
1532
+ end();
1533
+ return { words, dynamic };
1534
+ }
1535
+ /**
1536
+ * @implements A-SPEC-728 (round 19/20) — `env -S STRING` is split into words as env does and read IN
1537
+ * PLACE (a `-C` inside it was skipped as an option value — measured, the ledger deleted). Round 20: env
1538
+ * follows a `-S` inside a `-S` to any depth (measured to depth 5), so the split words go through an
1539
+ * iterator STACK, linear in the text — round 19's four-expansion cap answered "no wrapper" on the fifth
1540
+ * and failed open. The step limit, if ever reached, fails CLOSED (an ambiguous, unknown base).
1541
+ * @implements A-SPEC-728 (round 21) — options are read getopt-style from each wrapper's table (bundled short
1542
+ * letters, values glued or in the next word, unique GNU long prefixes, `--`); an option a table does not know,
1543
+ * or an option word an expansion shapes, makes the base AMBIGUOUS, never "no wrapper". Split words are
1544
+ * literal (a frame flag), so they are re-quoted for the judged text and never re-read as shell syntax.
1545
+ */
1546
+ function wrapperChdir(part) {
1547
+ const top = [...part.matchAll(WRAP_WORD_RE)];
1548
+ const frames = [{ words: top.map((m) => m[0]), i: 0, literal: false }];
1549
+ let expanded = false;
1550
+ let steps = 0;
1551
+ const current = () => frames[frames.length - 1];
1552
+ const peek = () => {
1553
+ for (;;) {
1554
+ const f = current();
1555
+ if (f.i < f.words.length)
1556
+ return f.words[f.i];
1557
+ if (frames.length === 1)
1558
+ return undefined;
1559
+ frames.pop();
1560
+ }
1561
+ };
1562
+ const take = () => { const w = peek(); if (w !== undefined)
1563
+ current().i++; return w; };
1564
+ /** The next word as the program receives it (peek first: the frame is the word's own). */
1565
+ const wordOf = (w, literal) => (literal ? { text: w, dynamic: false } : staticWord(w));
1566
+ let ambiguous = false;
1567
+ const pushSplit = (value, literal) => {
1568
+ expanded = true;
1569
+ const v = wordOf(value, literal);
1570
+ const split = envSplitWords(v.text);
1571
+ if (v.dynamic || split.dynamic)
1572
+ ambiguous = true;
1573
+ if (split.words.length > 0)
1574
+ frames.push({ words: split.words, i: 0, literal: true });
1575
+ };
1576
+ const restText = () => {
1577
+ peek();
1578
+ if (!expanded) {
1579
+ const f = frames[0];
1580
+ return f.i < top.length ? part.slice(top[f.i].index ?? 0) : '';
1581
+ }
1582
+ const out = [];
1583
+ for (let k = frames.length - 1; k >= 0; k--)
1584
+ for (let j = frames[k].i; j < frames[k].words.length; j++)
1585
+ out.push(frames[k].literal ? quoteLiteral(frames[k].words[j]) : frames[k].words[j]);
1586
+ return out.join(' ');
1587
+ };
1588
+ const dirs = [];
1589
+ for (;;) {
1590
+ if (++steps > WRAP_STEPS_MAX)
1591
+ return { dirs, ambiguous: true, rest: restText() };
1592
+ const t = peek();
1593
+ if (t === undefined)
1594
+ return null;
1595
+ if (/^[({!]+$/.test(t) || /^(?:then|do|else|elif|if|while|until)$/.test(t) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || WRAP_PLAIN.has(t)) {
1596
+ take();
1597
+ continue;
1598
+ }
1599
+ const name = wordOf(t, current().literal).text;
1600
+ const table = Object.prototype.hasOwnProperty.call(WRAPPERS, name) ? WRAPPERS[name] : undefined;
1601
+ if (table === undefined)
1602
+ break;
1603
+ take();
1604
+ // Round 19: the layers COMPOSE (each process inherits the previous chdir), so every layer's word is
1605
+ // kept in order; several in ONE layer differ by implementation and are ambiguous.
1606
+ const layer = [];
1607
+ const valueWord = (glued, literal) => {
1608
+ if (glued !== '')
1609
+ return { raw: glued, literal: true };
1610
+ const lit = current().literal;
1611
+ const v = take();
1612
+ return v === undefined ? undefined : { raw: v, literal: lit || literal };
1613
+ };
1614
+ const apply = (letterOrName, v) => {
1615
+ if (v === undefined)
1616
+ return;
1617
+ if (letterOrName === table.split || letterOrName === 'split-string') {
1618
+ pushSplit(v.raw, v.literal);
1619
+ return;
1620
+ }
1621
+ if (letterOrName === table.chdir || (letterOrName === 'chdir' && table.chdir !== undefined)) {
1622
+ layer.push(v.literal ? (staticWord(v.raw).dynamic ? UNKNOWN_DIR : v.raw === '' ? v.raw : quoteLiteral(v.raw)) : v.raw);
1623
+ }
1624
+ };
1625
+ for (;;) {
1626
+ if (++steps > WRAP_STEPS_MAX)
1627
+ return { dirs: [...dirs, ...layer], ambiguous: true, rest: restText() };
1628
+ const o = peek();
1629
+ if (o === undefined)
1630
+ break;
1631
+ const literal = current().literal;
1632
+ if (name === 'env' && !literal && /^[A-Za-z_][A-Za-z0-9_]*=/.test(o)) {
1633
+ take();
1634
+ continue;
1635
+ }
1636
+ if (name === 'env' && literal && /^[A-Za-z_][A-Za-z0-9_]*=/.test(o)) {
1637
+ take();
1638
+ continue;
1639
+ }
1640
+ const w = wordOf(o, literal);
1641
+ if (w.dynamic && !w.text.startsWith('-')) {
1642
+ ambiguous = true;
1643
+ break;
1644
+ }
1645
+ if (!w.text.startsWith('-') || (w.text === '-' && name !== 'env'))
1646
+ break;
1647
+ take();
1648
+ if (w.dynamic)
1649
+ ambiguous = true;
1650
+ if (w.text === '--')
1651
+ break;
1652
+ if (w.text === '-')
1653
+ continue;
1654
+ if (w.text.startsWith('--')) {
1655
+ const m = /^--([^=]*)(?:=([\s\S]*))?$/.exec(w.text);
1656
+ const all = [...table.longValue, ...table.longFlag];
1657
+ const hit = all.includes(m[1]) ? [m[1]] : all.filter((n) => n.startsWith(m[1]));
1658
+ if (m[1] === '' || hit.length !== 1) {
1659
+ ambiguous = true;
1660
+ continue;
1661
+ }
1662
+ if (table.longValue.includes(hit[0]))
1663
+ apply(hit[0], m[2] !== undefined ? { raw: m[2], literal: true } : valueWord('', false));
1664
+ continue;
1665
+ }
1666
+ if (table.numericFlag && /^-\d+$/.test(w.text))
1667
+ continue;
1668
+ for (let k = 1; k < w.text.length; k++) {
1669
+ const c = w.text[k];
1670
+ if (table.shortValue.includes(c)) {
1671
+ apply(c, valueWord(w.text.slice(k + 1), false));
1672
+ break;
1673
+ }
1674
+ if (!table.shortFlag.includes(c))
1675
+ ambiguous = true;
1676
+ }
1677
+ }
1678
+ if (table.duration) {
1679
+ if (take() === undefined)
1680
+ return null;
1681
+ }
1682
+ if (layer.length > 1)
1683
+ ambiguous = true;
1684
+ dirs.push(...layer);
1685
+ }
1686
+ if (dirs.length === 0 && !ambiguous)
1687
+ return null;
1688
+ const rest = restText();
1689
+ return rest === '' ? null : { dirs, ambiguous, rest };
1690
+ }
1691
+ /**
1692
+ * @implements A-SPEC-728 (round 20) — a command's redirect targets, split from its words: the shell opens
1693
+ * `>`/`>>`/`>|`/`&>` targets in ITS directory before `env -C`/`sudo -D` change it (measured in bash and
1694
+ * zsh: `env -C /tmp echo x > .mcp.json` overwrote the project's `.mcp.json`), so a wrapper-chdir'd
1695
+ * command's redirects are judged at the base BEFORE the chdir.
1696
+ */
1697
+ function splitRedirects(s) {
1698
+ const command = [];
1699
+ const redirects = [];
1700
+ let last = 0;
1701
+ for (let i = 0; i < s.length; i++) {
1702
+ // A `>` inside quotes belongs to the word (a `sh -c '… > f'` program runs at the moved base).
1703
+ if (s[i] === '\\') {
1704
+ i++;
1705
+ continue;
1706
+ }
1707
+ if (s[i] === "'") {
1708
+ const e = s.indexOf("'", i + 1);
1709
+ if (e < 0)
1710
+ break;
1711
+ i = e;
1712
+ continue;
1713
+ }
1714
+ if (s[i] === '"') {
1715
+ let e = i + 1;
1716
+ while (e < s.length && s[e] !== '"')
1717
+ e += s[e] === '\\' ? 2 : 1;
1718
+ if (e >= s.length)
1719
+ break;
1720
+ i = e;
1721
+ continue;
1722
+ }
1723
+ if (s[i] !== '<' && s[i] !== '>')
1724
+ continue;
1725
+ let start = i;
1726
+ while (start > last && s[start - 1] >= '0' && s[start - 1] <= '9')
1727
+ start--;
1728
+ if (start > last && s[start - 1] === '&')
1729
+ start--;
1730
+ let j = i + 1;
1731
+ if (s[j] === '<' || s[j] === '>' || s[j] === '|' || s[j] === '!')
1732
+ j++;
1733
+ if (s[j] === '&')
1734
+ j++;
1735
+ while (j < s.length && /\s/.test(s[j]))
1736
+ j++;
1737
+ const wordStart = j;
1738
+ while (j < s.length && !/\s/.test(s[j]))
1739
+ j++;
1740
+ if (j === wordStart) {
1741
+ i = wordStart - 1;
1742
+ continue;
1743
+ }
1744
+ command.push(s.slice(last, start));
1745
+ redirects.push(`: ${s.slice(start, j).trim()}`);
1746
+ last = j;
1747
+ i = j - 1;
1748
+ }
1749
+ command.push(s.slice(last));
1750
+ return { command: command.join(''), redirects: redirects.join('; ') };
1751
+ }
1752
+ const AX_WORD_RE = /(?:^|[^\w.-])\.ax(?![\w-])/i;
1753
+ const GLOB_CHAR_RE = /[*?[]/;
1754
+ /** A brace body is read as alternatives; a `..` range or more than this many alternatives counts as a mention. */
1755
+ const BRACE_ALTERNATIVES_MAX = 64;
1756
+ const GLOB_COMPONENT_MAX = 256;
1757
+ const GLOB_COMPONENTS_MAX = 2000;
1758
+ /**
1759
+ * @implements A-SPEC-728 (round 16)
1760
+ * Whether the command's text MENTIONS `.ax` — as a spelling, not a literal word. Round 15 read the literal
1761
+ * word and `ln -s .a? l && cd l && rm ledger/…` deleted the ledger (measured in bash and zsh: `.a?`,
1762
+ * `.[a]x`, `$'\056ax'`, `"."ax`, `.\ax` and `{.ax,}` all reach `.ax`; `[.]ax`, `?ax` and `*` do not — a
1763
+ * leading dot is matched only literally). The text is decoded (ANSI-C octal/hex/unicode escapes,
1764
+ * backslash escapes, quotes) and read as tokens: a literal `.ax` word; a glob token with a component
1765
+ * that can match `.ax` under the shell's dotfile rule; a brace token whose alternatives spell one.
1766
+ * A brace sequence `{a..z}` is the class `[a-z]`; a numeric one spells only digits (an honest
1767
+ * `for i in {1..3}` loop is no mention — measured false refusal of the `npm test` after its uncertain cd).
1768
+ * Bounded toward "mention" (more candidate bases, never fewer): a brace body with over 64
1769
+ * alternatives or nested past 8 levels, a glob component over 256 characters, or more than 2,000
1770
+ * glob components.
1771
+ */
1772
+ // Rule 37: asked three or four times per hook call about the same command (the segment reader, the base reader and the
1773
+ // classifier) — answered once.
1774
+ let axSpellingMemo = null;
1775
+ function mentionsAxSpelling(command) {
1776
+ if (axSpellingMemo !== null && axSpellingMemo.command === command)
1777
+ return axSpellingMemo.answer;
1778
+ const answer = mentionsAxSpellingUncached(command);
1779
+ axSpellingMemo = { command, answer };
1780
+ return answer;
1781
+ }
1782
+ function mentionsAxSpellingUncached(command) {
1783
+ const decoded = command
1784
+ .replace(/\\\n/g, '')
1785
+ .replace(/\\(?:x([0-9A-Fa-f]{1,2})|u([0-9A-Fa-f]{1,4})|U([0-9A-Fa-f]{1,8})|([0-7]{1,3}))/g, (_w, x, u, U, o) => {
1786
+ const cp = x !== undefined ? parseInt(x, 16) : u !== undefined ? parseInt(u, 16) : U !== undefined ? parseInt(U, 16) : parseInt(o ?? '0', 8);
1787
+ return cp <= 0x10ffff ? String.fromCodePoint(cp) : '';
1788
+ })
1789
+ .replace(/\\([\s\S])/g, '$1')
1790
+ .replace(/\$?["']/g, '');
1791
+ if (AX_WORD_RE.test(decoded))
1792
+ return true;
1793
+ let components = 0;
1794
+ const globMatches = (token) => {
1795
+ if (!GLOB_CHAR_RE.test(token))
1796
+ return false;
1797
+ for (const c of token.split('/')) {
1798
+ if (!GLOB_CHAR_RE.test(c))
1799
+ continue;
1800
+ if (c.length > GLOB_COMPONENT_MAX || ++components > GLOB_COMPONENTS_MAX)
1801
+ return true;
1802
+ if (globPatternRe(c, false).test('.ax'))
1803
+ return true;
1804
+ }
1805
+ return false;
1806
+ };
1807
+ // Single-level brace alternatives, innermost first; a body without a comma is literal (`{ax}` stays `{ax}`).
1808
+ const expansions = (token) => {
1809
+ let words = [token];
1810
+ for (let guard = 0; guard < 8; guard++) {
1811
+ const next = [];
1812
+ let grew = false;
1813
+ for (const w of words) {
1814
+ const m = /\{([^{}]*)\}/.exec(w);
1815
+ if (!m) {
1816
+ next.push(w);
1817
+ continue;
1818
+ }
1819
+ const body = m[1];
1820
+ // A sequence `{a..z}` is read as the class `[a-z]` the glob rule understands (`.{a..z}x` reaches
1821
+ // `.ax`); a multi-character endpoint is numeric (`{1..100}`) and spells only digits.
1822
+ // Rule 37: a body holding a comma is never a sequence — skipped before the regex, which is cubic on one
1823
+ // (`{` + 3,000 dots + `,}` took 12 s — measured).
1824
+ const range = body.includes(',') ? null : /^([^,]+?)\.\.([^,]+?)(?:\.\.[^,]*)?$/.exec(body);
1825
+ if (range) {
1826
+ const [a, b] = [range[1], range[2]].sort();
1827
+ next.push(w.slice(0, m.index) + (a.length === 1 && b.length === 1 ? `[${a}-${b}]` : '0') + w.slice(m.index + m[0].length));
1828
+ grew = true;
1829
+ continue;
1830
+ }
1831
+ const alts = body.split(',');
1832
+ if (alts.length === 1) {
1833
+ next.push(w.slice(0, m.index) + '\u0001' + body + '\u0002' + w.slice(m.index + m[0].length));
1834
+ grew = true;
1835
+ continue;
1836
+ }
1837
+ if (alts.length > BRACE_ALTERNATIVES_MAX || next.length + alts.length > BRACE_ALTERNATIVES_MAX)
1838
+ return 'mention';
1839
+ for (const a of alts)
1840
+ next.push(w.slice(0, m.index) + a + w.slice(m.index + m[0].length));
1841
+ grew = true;
1842
+ }
1843
+ words = next;
1844
+ if (!grew)
1845
+ break;
1846
+ }
1847
+ if (words.some((w) => /\{[^{}]*,[^{}]*\}/.test(w)))
1848
+ return 'mention';
1849
+ return words.map((w) => w.replace(/\u0001/g, '{').replace(/\u0002/g, '}'));
1850
+ };
1851
+ for (const token of decoded.split(/[\s;&|<>()=]+/)) {
1852
+ if (token === '' || !(GLOB_CHAR_RE.test(token) || token.includes('{')))
1853
+ continue;
1854
+ const words = token.includes('{') && token.includes('}') ? expansions(token) : [token];
1855
+ if (words === 'mention')
1856
+ return true;
1857
+ for (const w of words)
1858
+ if (AX_WORD_RE.test(w) || globMatches(w))
1859
+ return true;
1860
+ }
1861
+ return false;
1862
+ }
1863
+ /**
1864
+ * @implements A-SPEC-728 (round 22) — the words the cd model reads by name. A word that reaches one of them only after
1865
+ * the shell's quote removal (`\cd`, `"cd"`, `c''d`, `$'\x63d'`) is the same builtin: both shells moved into `.ax`
1866
+ * while the gate judged at the root, and the spec store was deleted unasked (measured).
1867
+ */
1868
+ const CD_MODEL_WORDS = new Set(['cd', 'chdir', 'pushd', 'popd', 'source', 'eval', '.', 'builtin', 'command', 'env', 'sudo', 'timeout', 'nohup', 'exec']);
1869
+ /** One `$'…'` body decoded as bash decodes it (the escapes that can spell a word). */
1870
+ function ansiC(body) {
1871
+ let out = '';
1872
+ for (let i = 0; i < body.length; i++) {
1873
+ const c = body[i];
1874
+ if (c !== '\\' || i + 1 >= body.length) {
1875
+ out += c;
1876
+ continue;
1877
+ }
1878
+ const n = body[++i];
1879
+ if (n === 'x') {
1880
+ const m = /^[0-9A-Fa-f]{1,2}/.exec(body.slice(i + 1));
1881
+ if (m) {
1882
+ out += String.fromCharCode(parseInt(m[0], 16));
1883
+ i += m[0].length;
1884
+ }
1885
+ else
1886
+ out += '\\x';
1887
+ continue;
1888
+ }
1889
+ if (n === 'u' || n === 'U') {
1890
+ const m = new RegExp(`^[0-9A-Fa-f]{1,${n === 'u' ? 4 : 8}}`).exec(body.slice(i + 1));
1891
+ if (m) {
1892
+ out += String.fromCodePoint(parseInt(m[0], 16));
1893
+ i += m[0].length;
1894
+ }
1895
+ else
1896
+ out += '\\' + n;
1897
+ continue;
1898
+ }
1899
+ if (n >= '0' && n <= '7') {
1900
+ const m = /^[0-7]{1,3}/.exec(body.slice(i));
1901
+ out += String.fromCharCode(parseInt(m[0], 8) & 0xff);
1902
+ i += m[0].length - 1;
1903
+ continue;
1904
+ }
1905
+ const simple = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' };
1906
+ out += simple[n] ?? '\\' + n;
1907
+ }
1908
+ return out;
1909
+ }
1910
+ /** A shell word after quote removal; null when the shell would expand part of it (`$X`, `${…}`, `$(…)`, a backtick). */
1911
+ function quoteRemoved(word) {
1912
+ let out = '';
1913
+ for (let i = 0; i < word.length; i++) {
1914
+ const c = word[i];
1915
+ if (c === '\\') {
1916
+ if (i + 1 < word.length)
1917
+ out += word[++i];
1918
+ continue;
1919
+ }
1920
+ if (c === "'") {
1921
+ const j = word.indexOf("'", i + 1);
1922
+ if (j < 0)
1923
+ return null;
1924
+ out += word.slice(i + 1, j);
1925
+ i = j;
1926
+ continue;
1927
+ }
1928
+ if (c === '$' && word[i + 1] === "'") {
1929
+ let j = i + 2;
1930
+ while (j < word.length && word[j] !== "'")
1931
+ j += word[j] === '\\' ? 2 : 1;
1932
+ if (j >= word.length)
1933
+ return null;
1934
+ out += ansiC(word.slice(i + 2, j));
1935
+ i = j;
1936
+ continue;
1937
+ }
1938
+ if (c === '"') {
1939
+ let j = i + 1;
1940
+ while (j < word.length && word[j] !== '"')
1941
+ j += word[j] === '\\' ? 2 : 1;
1942
+ if (j >= word.length)
1943
+ return null;
1944
+ const inner = word.slice(i + 1, j);
1945
+ if (/[$`]/.test(inner.replace(/\\[$`]/g, '')))
1946
+ return null;
1947
+ out += inner.replace(/\\(["\\$`])/g, '$1');
1948
+ i = j;
1949
+ continue;
1950
+ }
1951
+ if (c === '$' || c === '`')
1952
+ return null;
1953
+ out += c;
1954
+ }
1955
+ return out;
1956
+ }
1957
+ /**
1958
+ * @implements A-SPEC-728 (round 22) — every word whose quote removal is a cd-model word is written plainly, so the
1959
+ * readers below see `cd`, `pushd`, `env`, `eval`… however it was spelled. Only such words change (a word that holds a
1960
+ * blank or anything else stays as written); linear in the command.
1961
+ */
1962
+ /** The end of the shell word starting at `i` (quotes and backslash escapes kept inside the word). */
1963
+ function wordEnd(command, i) {
1964
+ while (i < command.length && !/[\s;&|()<>`]/.test(command[i])) {
1965
+ const c = command[i];
1966
+ if (c === '\\') {
1967
+ i += 2;
1968
+ continue;
1969
+ }
1970
+ if (c === "'" || c === '"') {
1971
+ const q = c;
1972
+ let j = i + 1;
1973
+ while (j < command.length && command[j] !== q)
1974
+ j += q === '"' && command[j] === '\\' ? 2 : 1;
1975
+ i = j + 1;
1976
+ continue;
1977
+ }
1978
+ i++;
1979
+ }
1980
+ return Math.min(i, command.length);
1981
+ }
1982
+ /** A word the shell reads as itself once quotes are removed: letters, digits and `_./@%+=:,~-` only. */
1983
+ const PLAIN_WORD = /^[A-Za-z0-9_./@%+=:,~-]+$/;
1984
+ function unmaskModelWords(command) {
1985
+ if (!/[\\'"{]/.test(command))
1986
+ return command;
1987
+ const parts = [];
1988
+ let last = 0;
1989
+ let i = 0;
1990
+ // Round 24: linear — `[^{}\s]*,` backtracked over a run of commas (80,000 took 20 s — measured).
1991
+ const BRACE = /\{([^{}\s,]*),([^{}\s]*)\}/y;
1992
+ while (i < command.length) {
1993
+ const ch = command[i];
1994
+ // @implements A-SPEC-728 (round 23) — a brace list whose first element is a cd-model word is that command
1995
+ // (`{cd,.ax} && rm -r specs` ran `cd .ax` in bash — measured).
1996
+ if (ch === '{' && (i === 0 || /[\s;&|(!]/.test(command[i - 1]))) {
1997
+ BRACE.lastIndex = i;
1998
+ const m = BRACE.exec(command);
1999
+ if (m !== null) {
2000
+ const elems = [m[1], ...m[2].split(',')];
2001
+ const head = quoteRemoved(elems[0]);
2002
+ if (head !== null && CD_MODEL_WORDS.has(head)) {
2003
+ parts.push(command.slice(last, i), [head, ...elems.slice(1)].join(' '));
2004
+ last = i + m[0].length;
2005
+ i = last;
2006
+ continue;
2007
+ }
2008
+ }
2009
+ }
2010
+ if (/[\s;&|()<>{}!`]/.test(ch)) {
2011
+ i++;
2012
+ continue;
2013
+ }
2014
+ const start = i;
2015
+ let quoted = false;
2016
+ while (i < command.length && !/[\s;&|()<>`]/.test(command[i])) {
2017
+ const c = command[i];
2018
+ if (c === '\\') {
2019
+ quoted = true;
2020
+ i += 2;
2021
+ continue;
2022
+ }
2023
+ if (c === "'" || c === '"') {
2024
+ quoted = true;
2025
+ const q = c;
2026
+ let j = i + 1;
2027
+ while (j < command.length && command[j] !== q)
2028
+ j += q === '"' && command[j] === '\\' ? 2 : 1;
2029
+ i = j + 1;
2030
+ continue;
2031
+ }
2032
+ i++;
2033
+ }
2034
+ if (!quoted)
2035
+ continue;
2036
+ const word = command.slice(start, Math.min(i, command.length));
2037
+ const plain = quoteRemoved(word);
2038
+ // @implements A-SPEC-728 (round 24) — every word whose quote removal is plain, not only the cd-model words:
2039
+ // `r''m -rf /usr/local`, `r\m -rf .git` and `g''it reset --hard` were allowed while their plain forms were denied.
2040
+ if (plain !== null && (CD_MODEL_WORDS.has(plain) || PLAIN_WORD.test(plain))) {
2041
+ parts.push(command.slice(last, start), plain);
2042
+ last = Math.min(i, command.length);
2043
+ }
2044
+ }
2045
+ if (last === 0)
2046
+ return command;
2047
+ parts.push(command.slice(last));
2048
+ return parts.join('');
2049
+ }
2050
+ /**
2051
+ * @implements A-SPEC-728 (round 23) — the text as the shell joins it before reading words: a backslash-newline is removed
2052
+ * (`c\⏎d .ax` is `cd .ax` in both shells — measured), then the cd-model words are unmasked.
2053
+ */
2054
+ let JOIN_MEMO = null;
2055
+ function joinShellText(command) {
2056
+ if (JOIN_MEMO !== null && JOIN_MEMO.from === command)
2057
+ return JOIN_MEMO.to;
2058
+ const to = joinProgramWords(unmaskModelWords(command.includes('\\\n') ? command.replace(/\\\n/g, '') : command));
2059
+ JOIN_MEMO = { from: command, to };
2060
+ return to;
2061
+ }
2062
+ /**
2063
+ * @implements A-SPEC-728 (round 24) — the argument words of `eval`, and the one word after a shell's `-c`, read after quote
2064
+ * removal and re-quoted as the one program word they are, when that program holds no shell metacharacter (`eval rm\ -rf\
2065
+ * src`, `eval 'rm -r' src`, `sh -c rm\ -rf\ src` removed tracked source — measured). A program with separators is left
2066
+ * as written for the quoted-program reader.
2067
+ */
2068
+ function joinProgramWords(command) {
2069
+ if (!/(?:eval|-[A-Za-z]*c)/.test(command))
2070
+ return command;
2071
+ const parts = [];
2072
+ let last = 0;
2073
+ const HEAD = /(?:^|[\s;&|(){}!])(?:eval[ \t]+|(?:sh|bash|zsh|dash|ksh)[ \t]+(?:-[A-Za-z]+[ \t]+)*-[A-Za-z]*c[A-Za-z]*[ \t]+)/g;
2074
+ // Each word run is read once: a later `eval` inside a run already read is skipped (120 KB of `eval eval …` read the rest
2075
+ // of the text from every one of them — quadratic).
2076
+ let scanned = 0;
2077
+ for (const m of command.matchAll(HEAD)) {
2078
+ const at = (m.index ?? 0) + m[0].length;
2079
+ if (at < last || at < scanned)
2080
+ continue;
2081
+ const isEval = /eval[ \t]+$/.test(m[0]);
2082
+ const words = [];
2083
+ let i = at;
2084
+ let end = at;
2085
+ for (;;) {
2086
+ const e = wordEnd(command, i);
2087
+ if (e === i)
2088
+ break;
2089
+ words.push(command.slice(i, e));
2090
+ end = e;
2091
+ if (!isEval)
2092
+ break;
2093
+ let k = e;
2094
+ while (k < command.length && (command[k] === ' ' || command[k] === '\t'))
2095
+ k++;
2096
+ if (k >= command.length || /[;&|\n()<>`]/.test(command[k]))
2097
+ break;
2098
+ i = k;
2099
+ }
2100
+ scanned = end;
2101
+ if (words.length === 0 || !words.some((w) => /['"\\]/.test(w)))
2102
+ continue;
2103
+ const plain = words.map(quoteRemoved);
2104
+ if (plain.some((w) => w === null))
2105
+ continue;
2106
+ const program = plain.join(' ');
2107
+ if (/[;&|<>()$`\n']/.test(program))
2108
+ continue;
2109
+ // Re-quoted as ONE word, as the shell passes it: unquoted, `bash -c 'rm .mcp.json'` would read as `rm` with `$0` set
2110
+ // (its program is one word), and the quoted-program reader judges a single-quoted program as a child program.
2111
+ const quoted = `'${program}'`;
2112
+ if (quoted === words.join(' '))
2113
+ continue;
2114
+ parts.push(command.slice(last, at), quoted);
2115
+ last = end;
2116
+ }
2117
+ if (last === 0)
2118
+ return command;
2119
+ parts.push(command.slice(last));
2120
+ return parts.join('');
2121
+ }
2122
+ const CD_ANYWHERE_RE = /(?:^|[\s;&|(){}!`'"=])(?:cd|chdir|pushd)((?:[ \t]+(?:-[A-Za-z@]+|--))*)(?:[ \t]+((?:[^\s;&|<>()'"`]|'[^']*'|"[^"]*")+))?(?:[ \t]+((?:[^\s;&|<>()'"`]|'[^']*'|"[^"]*")+))?(?=[\s;&|<>()'"`]|$)/g;
2123
+ const BASES_MAX = 64;
2124
+ const CDS_MAX = 64;
2125
+ /**
2126
+ * @implements A-SPEC-728 (round 23) — flow-INSENSITIVE: the start, every segment base and candidate, and every literal
2127
+ * `cd`/`chdir`/`pushd` argument written anywhere (inside quotes, loop and function bodies, trap strings) applied to every
2128
+ * base so far. The segment model reads the text top to bottom, and text that runs later or again — `for …; do rm
2129
+ * ledger/provenance.jsonl; cd .ax; done`, `f() { rm -r specs; }; cd .ax && f`, `trap 'rm -r specs' EXIT; cd .ax` —
2130
+ * deleted the store (measured). Unknown when a cd cannot be placed: a non-literal argument, `-`, `~user`, `+N`, a relative
2131
+ * one beside a `CDPATH`/`cdpath`, two words (zsh substitution), an aliased cd, a computed `eval`/`trap`/`sh -c` program,
2132
+ * an expanded command word with a non-literal argument, `find -execdir/-okdir`, or more than 64 directories.
2133
+ */
2134
+ // A-SPEC-728 (round 25): the last answer, reused within a second (the rm gate and the `.ax` rules ask for the same one).
2135
+ let BASES_MEMO = null;
2136
+ function commandBases(command, start, given) {
2137
+ const now = Date.now();
2138
+ if (BASES_MEMO !== null && BASES_MEMO.command === command && BASES_MEMO.start === start && now - BASES_MEMO.at < 1000)
2139
+ return BASES_MEMO.value;
2140
+ const value = commandBasesUncached(command, start, given);
2141
+ BASES_MEMO = { command, start, at: now, value };
2142
+ return value;
2143
+ }
2144
+ function commandBasesUncached(command, start, given) {
2145
+ const text = joinShellText(command);
2146
+ const set = new Set([start]);
2147
+ let unknown = null;
2148
+ let expanded = false;
2149
+ const segments = given ?? shellSegments(command, start);
2150
+ // The `maybe` array is shared by the null-base segments of one shell: each distinct array is walked once (25,000
2151
+ // `cd a &&` segments walked it each time — quadratic, measured), and the set stops at its bound.
2152
+ const walked = new Set();
2153
+ for (const seg of segments) {
2154
+ if (set.size <= BASES_MAX) {
2155
+ if (seg.base !== null)
2156
+ set.add(seg.base);
2157
+ if (seg.maybe && !walked.has(seg.maybe)) {
2158
+ walked.add(seg.maybe);
2159
+ for (const m of seg.maybe) {
2160
+ set.add(m);
2161
+ if (set.size > BASES_MAX)
2162
+ break;
2163
+ }
2164
+ }
2165
+ }
2166
+ if (seg.data)
2167
+ continue;
2168
+ const word = commandWordOf(seg.text);
2169
+ if (word !== '' && /[$`]/.test(word)) {
2170
+ expanded = true;
2171
+ const after = seg.text.slice(seg.text.indexOf(word) + word.length).trim();
2172
+ const first = /^[^\s;&|<>()]+/.exec(after)?.[0];
2173
+ if (first !== undefined && (/[$`]/.test(first) || reduceCdWord(first) === null))
2174
+ unknown ??= 'a command word the shell expands, given an argument that is not a plain word';
2175
+ // Round 24: an expansion inside a cd word (`cd${IFS}src`) is a cd the reader cannot place (measured in bash).
2176
+ if (/cd|chdir|pushd|popd/i.test(word))
2177
+ unknown ??= 'a cd spelled inside an expansion';
2178
+ }
2179
+ }
2180
+ // Judged per clause (between `;`, `&`, `|` and newlines), each test linear in its clause: a pattern that scanned to the
2181
+ // next separator from every `eval` of a 120 KB `eval eval …` was quadratic (measured past the 2 s bound).
2182
+ const dollar = /[$`]/;
2183
+ for (const clause of text.split(/[;&|\n]/)) {
2184
+ if (unknown !== null)
2185
+ break;
2186
+ if (/(?:^|[\s(){}!])(?:eval|trap)[ \t]/.test(clause) && dollar.test(clause))
2187
+ unknown = 'an eval or trap that runs a computed program';
2188
+ else if (/\b(?:sh|bash|zsh|dash|ksh)[ \t]+-[A-Za-z]*c/.test(clause) && dollar.test(clause))
2189
+ unknown = 'a shell -c that runs a computed program';
2190
+ else if (/\balias[ \t]/.test(clause) && /=[ \t]*['"]?(?:cd|chdir|pushd|popd)\b/.test(clause))
2191
+ unknown = 'an alias of cd';
2192
+ }
2193
+ if (/\s-(?:execdir|okdir)\b/.test(text))
2194
+ unknown ??= 'find -execdir or -okdir';
2195
+ if (set.size > BASES_MAX)
2196
+ unknown ??= `more than ${BASES_MAX} directories`;
2197
+ const cdpath = /\bcdpath\b/i.test(text);
2198
+ // Round 24: a loop, a function or a trap can run a cd again — its literal cds are applied to a fixed point (a `cd ..`
2199
+ // repeated in `until`/`for`/a function climbed past a single pass — measured); not settling within the bound is unknown.
2200
+ // Round 25: any function definition (a braceless body — `f() if …`, zsh `chpwd() rm …` — too) and zsh `repeat`/`foreach`
2201
+ // (`repeat 2 cd ..; rm -r .ax` from a subdirectory was allowed — measured).
2202
+ // Round 26: read with quoted text blanked (`git commit -am "call build()"` and `"fix for build"` read as repeated text —
2203
+ // measured).
2204
+ const repeats = /(?:^|[\s;&|(){}!])(?:for|while|until|select|foreach)[ \t]|(?:^|[\s;&|(){}!])repeat[ \t]+\S|[\w.:-][ \t]*\([ \t]*\)|(?:^|[\s;&|])function[ \t]+\w|(?:^|[\s;&|])trap[ \t]/.test(blankQuotes(text));
2205
+ // Round 25: identical cds are applied once per pass (300 `cd .` in a loop over a 62-deep chain hit the 20 s deadline —
2206
+ // measured); a backtick in or next to a cd argument stopped the reader, which then read a bare cd (home).
2207
+ // Round 27: a physical directory change goes through links as the kernel does (`cd -P tmp/l/..` with `l -> ../src/lib`
2208
+ // is `src`; `set -P`, `set -o physical` and zsh `chase_links`/`chase_dots` make every cd physical — measured in bash and
2209
+ // zsh). Both readings are candidates, and a command that switches the mode is not ordered.
2210
+ const physicalMode = /(?:^|[\s;&|(){}!])set[ \t]+(?:-[A-Za-z]*P\b|-o[ \t]+physical\b)|\bchase_?(?:links|dots)\b/i.test(blankQuotes(text));
2211
+ const cds = [...new Map([...text.matchAll(CD_ANYWHERE_RE)].map((m) => {
2212
+ const end = (m.index ?? 0) + m[0].length;
2213
+ // Round 26: keyed on the normalised argument (`cd ./`, `cd .//` are one cd — measured, 90 ms each); a `..` is kept
2214
+ // as written, where a physical reading can differ.
2215
+ const arg = m[2] === undefined ? '' : /(?:^|\/)\.\.(?:\/|$)/.test(m[2]) ? m[2] : ((0, linear_match_1.trimTrailing)(path.posix.normalize(m[2]), '/') || '/');
2216
+ return [`${m[1] ?? ''}\0${arg}\0${m[3] ?? ''}\0${text[end] === '`' ? '`' : ''}\0${/^[ \t]*[<>]/.test(text.slice(end, end + 8)) ? '>' : ''}`, m];
2217
+ })).values()];
2218
+ for (const m of cds) {
2219
+ const end = (m.index ?? 0) + m[0].length;
2220
+ if (text[end] === '`' || (m[2] === undefined && /^[ \t]*`/.test(text.slice(end, end + 64)))) {
2221
+ unknown ??= 'a cd whose target is a command substitution';
2222
+ break;
2223
+ }
2224
+ }
2225
+ // Rule 37: past 64 distinct cds the bases are unknown, as past 64 directories (1,000 `cd /nx0/aK/..` beside a loop took
2226
+ // 3.3 s, 91 KB 14 s — measured); within it each look-up is made once per call.
2227
+ if (cds.length > CDS_MAX)
2228
+ unknown ??= `more than ${CDS_MAX} directory changes`;
2229
+ // Rule 39: the literal cd arguments, read once (the pass loop below may not reach them).
2230
+ const literal = [];
2231
+ for (const m of cds) {
2232
+ const raw = m[2];
2233
+ if (raw === undefined)
2234
+ continue;
2235
+ for (const one of new Set([raw, /^[^'"]+/.exec(raw)?.[0] ?? raw])) {
2236
+ const r = /[$`]/.test(one) ? null : reduceCdWord(one);
2237
+ if (r === null || r === '' || r === '-' || /^[+-]\d+$/.test(r) || (r.startsWith('~') && r !== '~' && !r.startsWith('~/')))
2238
+ continue;
2239
+ literal.push(r === '~' ? os.homedir() : r.startsWith('~/') ? path.join(os.homedir(), r.slice(2)) : r);
2240
+ }
2241
+ }
2242
+ const looked = new Map();
2243
+ const realOnce = (p) => {
2244
+ let r = looked.get(p);
2245
+ if (r === undefined) {
2246
+ try {
2247
+ r = fs.realpathSync.native(p);
2248
+ }
2249
+ catch {
2250
+ r = null;
2251
+ }
2252
+ looked.set(p, r);
2253
+ }
2254
+ return r;
2255
+ };
2256
+ const searchable = new Map();
2257
+ const searchableOnce = (p) => {
2258
+ let r = searchable.get(p);
2259
+ if (r === undefined) {
2260
+ r = isSearchableDir(p);
2261
+ searchable.set(p, r);
2262
+ }
2263
+ return r;
2264
+ };
2265
+ let before = -1;
2266
+ for (let pass = 0; unknown === null && set.size !== before && (pass === 0 || repeats); pass++) {
2267
+ before = set.size;
2268
+ for (const m of cds) {
2269
+ if (unknown !== null)
2270
+ break;
2271
+ const raw = m[2];
2272
+ const second = m[3];
2273
+ if (second !== undefined && !/^[<>]/.test(text.slice((m.index ?? 0) + m[0].length).trimStart()) && !/^\d+$/.test(second)) {
2274
+ unknown = 'a cd given two words';
2275
+ break;
2276
+ }
2277
+ // A cd written inside a quoted string (`trap 'cd .ax' DEBUG`) ends at the string's closing quote, which the word
2278
+ // reading cannot tell from a quoted piece of the argument: both readings are candidates.
2279
+ const readings = raw === undefined ? [undefined] : [...new Set([raw, /^[^'"]+/.exec(raw)?.[0] ?? raw])];
2280
+ const args = [];
2281
+ for (const one of readings) {
2282
+ if (one === undefined) {
2283
+ args.push(os.homedir());
2284
+ continue;
2285
+ }
2286
+ const r = /[$`]/.test(one) ? null : reduceCdWord(one);
2287
+ if (r === null || r === '' || r === '-' || /^[+-]\d+$/.test(r) || (r.startsWith('~') && r !== '~' && !r.startsWith('~/'))) {
2288
+ unknown = 'a cd whose target is not a plain word';
2289
+ break;
2290
+ }
2291
+ if (cdpath && !absoluteKindOf(r) && !/^(?:\.\.?(?:[/\\]|$)|~)/.test(r)) {
2292
+ unknown = 'a relative cd beside a CDPATH';
2293
+ break;
2294
+ }
2295
+ args.push(r === '~' ? os.homedir() : r.startsWith('~/') ? path.join(os.homedir(), r.slice(2)) : r);
2296
+ }
2297
+ if (unknown !== null)
2298
+ break;
2299
+ const physical = physicalMode || /(?:^|\s)-[A-Za-z@]*P/.test(m[1] ?? '');
2300
+ for (const arg of args) {
2301
+ for (const b of [...set]) {
2302
+ const to = absoluteKindOf(arg) !== null ? pathFlavorFor(arg, arg).resolve(arg) : pathFlavorFor(b, arg).resolve(b, arg);
2303
+ // A repeated pass follows only a directory that exists: the shell's cd into a missing one fails, and what a
2304
+ // removal can hit (tracked files, the store) is already on disk — a lexical `cd .ax` in a loop never settled.
2305
+ if (pass > 0 && !searchableOnce(to))
2306
+ continue;
2307
+ set.add(to);
2308
+ const real = realOnce(to);
2309
+ if (real !== null)
2310
+ set.add(real);
2311
+ if (physical) {
2312
+ const through = realOnce(absoluteKindOf(arg) !== null ? arg : `${b}${path.sep}${arg}`);
2313
+ if (through !== null)
2314
+ set.add(through);
2315
+ }
2316
+ if (set.size > BASES_MAX)
2317
+ break;
2318
+ }
2319
+ }
2320
+ if (set.size > BASES_MAX) {
2321
+ unknown = `more than ${BASES_MAX} directories`;
2322
+ break;
2323
+ }
2324
+ }
2325
+ }
2326
+ const ordered = !repeats && !expanded && !physicalMode && !/(?:^|[\s;&|(){}!])(?:eval|source|\.)[ \t]/.test(text)
2327
+ && !/\b(?:sh|bash|zsh|dash|ksh)[ \t]+(?:-[A-Za-z]+[ \t]+)*-[A-Za-z]*c/.test(text);
2328
+ return { bases: [...set], unknown, ordered, literal: [...new Set(literal)] };
2329
+ }
2330
+ /**
2331
+ * @implements A-SPEC-728 (rule 43) — the possible bases of one program invocation's children, as ONE array per distinct child
2332
+ * list: every memo keyed by the array (the wiring rule's `.ax` candidates) then hits once per invocation, not once per child.
2333
+ */
2334
+ function sharedMaybe(seen) {
2335
+ const base = [...seen];
2336
+ const merged = new Map();
2337
+ return (own) => {
2338
+ if (own === undefined || own.length === 0)
2339
+ return base;
2340
+ let m = merged.get(own);
2341
+ if (m === undefined) {
2342
+ m = [...own, ...base];
2343
+ merged.set(own, m);
2344
+ }
2345
+ return m;
2346
+ };
2347
+ }
2348
+ function shellSegments(command, startBase, depth = 0, opts = {}) {
309
2349
  if (depth > 3)
310
2350
  return [{ text: command, base: null }];
2351
+ command = joinShellText(command);
2352
+ // @implements A-SPEC-728 (round 3) — `programs: false` leaves `sh -c '…'`/`eval '…'` text in place for
2353
+ // a caller that parses shell words itself: the regex extraction below cannot read `'\''` joins
2354
+ // and handed such a caller a garbled parent.
2355
+ const programs = opts.programs !== false;
311
2356
  const out = [];
312
- let base = startBase;
313
2357
  const pieces = [];
314
2358
  {
315
2359
  const lines = command.split('\n');
@@ -318,9 +2362,10 @@ function shellSegments(command, startBase, depth = 0) {
318
2362
  pieces.push({ text: cur.join('\n'), kind: 'cmd' });
319
2363
  cur = [];
320
2364
  } };
2365
+ const qs = { q: null };
321
2366
  for (let i = 0; i < lines.length; i++) {
322
2367
  const line = lines[i];
323
- const hd = HEREDOC_RE.exec(line);
2368
+ const hd = unquotedHeredoc(line, qs);
324
2369
  if (!hd) {
325
2370
  cur.push(line);
326
2371
  continue;
@@ -328,118 +2373,362 @@ function shellSegments(command, startBase, depth = 0) {
328
2373
  cur.push(line);
329
2374
  flush();
330
2375
  const body = [];
331
- for (i++; i < lines.length && lines[i].replace(/^\t+/, '') !== hd[2]; i++)
2376
+ const delim = heredocDelimiter(hd);
2377
+ for (i++; i < lines.length && lines[i].replace(/^\t+/, '') !== delim; i++)
332
2378
  body.push(lines[i]);
333
- pieces.push({ text: body.join('\n'), kind: SHELL_STDIN_RE.test(line) ? 'prog' : 'data' });
2379
+ pieces.push({ text: body.join('\n'), kind: SHELL_STDIN_RE.test(line) ? 'prog' : INTERP_STDIN_RE.test(line) ? 'interp' : 'data' });
334
2380
  }
335
2381
  flush();
336
2382
  }
337
2383
  // Quote-aware split at ; & | and newlines — separators inside quotes are data.
2384
+ // @implements A-SPEC-728 (round 8) — each part carries the separator after it: a `cd` moves the base
2385
+ // only as the shell would (`&&` yes, a subshell `|`/`&` no, `;`/newline/`||` only into a directory
2386
+ // that exists — measured: `cd /nonexistent ; echo x > .mcp.json` wrote in the current directory).
338
2387
  const splitTop = (text) => {
339
2388
  const parts = [];
340
2389
  let acc = '';
2390
+ // Round 5: the accumulator's last character is TRACKED, never read back — indexing or
2391
+ // `endsWith` on a string built by `+=` flattens it each time (quadratic: 3 s on 200 KB).
2392
+ let lastCh = '';
2393
+ const add = (t) => { acc += t; lastCh = t[t.length - 1]; };
341
2394
  let quote = null;
2395
+ let wordParen = 0;
2396
+ // @implements A-SPEC-728 (round 13) — a `#` at a word start outside quotes opens a comment to the end
2397
+ // of the line: an apostrophe inside `# don't` opened a quote that swallowed the newline and every
2398
+ // separator after it, and the next line's cd into ~/.codex was never read (measured allow).
2399
+ let comment = false;
342
2400
  for (let k = 0; k < text.length; k++) {
343
2401
  const ch = text[k];
344
- if (quote !== null) {
345
- acc += ch;
2402
+ if (comment) {
2403
+ if (ch !== '\n') {
2404
+ add(ch);
2405
+ continue;
2406
+ }
2407
+ comment = false;
2408
+ }
2409
+ else if (quote !== null) {
2410
+ add(ch);
346
2411
  if (ch === quote)
347
2412
  quote = null;
348
2413
  continue;
349
2414
  }
2415
+ if (ch === '#' && (k === 0 || /[\s;&|(]/.test(text[k - 1]))) {
2416
+ comment = true;
2417
+ add(ch);
2418
+ continue;
2419
+ }
350
2420
  if (ch === "'" || ch === '"') {
351
2421
  quote = ch;
352
- acc += ch;
2422
+ add(ch);
353
2423
  continue;
354
2424
  }
355
2425
  if (ch === '\\' && k + 1 < text.length) {
356
- acc += ch + text[++k];
2426
+ add(ch + text[++k]);
2427
+ continue;
2428
+ }
2429
+ // @implements A-SPEC-728 — `>|` is the noclobber-override redirect, not a pipe: splitting it
2430
+ // left `>` with no target and the written file in a segment of its own.
2431
+ if (ch === '|' && lastCh === '>') {
2432
+ add(ch);
2433
+ continue;
2434
+ }
2435
+ // `>&WORD`, `&>WORD`, `2>&1`: the `&` belongs to the redirect, not a background separator.
2436
+ if (ch === '&' && (lastCh === '>' || text[k + 1] === '>')) {
2437
+ add(ch);
2438
+ continue;
2439
+ }
2440
+ // A `(` glued to a word opens a zsh glob group (`.(mcp|x).json`): its `|` is not a pipe.
2441
+ if (ch === '(' && lastCh !== '' && !/\s/.test(lastCh) && !';&|('.includes(lastCh)) {
2442
+ wordParen++;
2443
+ add(ch);
2444
+ continue;
2445
+ }
2446
+ if (ch === ')' && wordParen > 0) {
2447
+ wordParen--;
2448
+ add(ch);
2449
+ continue;
2450
+ }
2451
+ if (ch === '|' && wordParen > 0) {
2452
+ add(ch);
357
2453
  continue;
358
2454
  }
359
2455
  if (ch === ';' || ch === '&' || ch === '|' || ch === '\n') {
360
2456
  if (acc.trim() !== '')
361
- parts.push(acc);
2457
+ parts.push({ text: acc, sep: ch });
2458
+ else if (parts.length > 0 && parts[parts.length - 1].sep.length < 2)
2459
+ parts[parts.length - 1].sep += ch;
362
2460
  acc = '';
2461
+ lastCh = '';
363
2462
  continue;
364
2463
  }
365
- acc += ch;
2464
+ add(ch);
366
2465
  }
367
2466
  if (acc.trim() !== '')
368
- parts.push(acc);
2467
+ parts.push({ text: acc, sep: '' });
369
2468
  return parts;
370
2469
  };
371
- const applyCd = (part) => {
372
- // `(`/`{` open groups whose leading cd still runs (a brace group shares the CURRENT shell; a
373
- // subshell's cd is over-approximated by design — REQ-528 Out). `builtin cd` and `command cd`
374
- // ARE the real cd — round-1 adversarial harvest: the unprefixed matcher left the base behind
375
- // while the shell moved.
376
- const lead = part.replace(/^[\s({]+/, '').replace(/^(?:builtin|command(?:\s+-p)?)\s+/, '');
377
- if (/^popd\b/.test(lead)) {
378
- base = null;
379
- return;
380
- }
381
- const m = /^(?:cd|chdir|pushd)(?:\s+([\s\S]*))?$/.exec(lead);
2470
+ // Round 10: looked up once per command — per cd part it rescanned the whole command (1 MB of
2471
+ // `cd a && `: 14 s, measured).
2472
+ const mentionsCdpath = /\bCDPATH\b/.test(command);
2473
+ // @implements A-SPEC-728 (round 9) — the directory a LEADING cd names, read without moving anything:
2474
+ // `undefined` = the part is not a leading cd, `null` = unknowable.
2475
+ const readCd = (part, from) => {
2476
+ // `(`/`{` open groups whose leading cd still runs. `builtin cd` and `command cd` ARE the real cd —
2477
+ // round-1 adversarial harvest: the unprefixed matcher left the base behind while the shell moved.
2478
+ // @implements A-SPEC-728 (round 2) — `CDPATH=~ cd x` and `cd -P|-L|-e|-- x` are the same cd.
2479
+ const lead = part.replace(/^[\s({]+/, '').replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/, '')
2480
+ // A-SPEC-728 (round 23): and zsh's precommand modifiers (`noglob cd .ax` moved the shell — measured).
2481
+ .replace(/^(?:(?:builtin|command(?:\s+-p)?|noglob|nocorrect|-)\s+)+/, '');
2482
+ // @implements A-SPEC-728 (round 27) — a physical cd (`-P`) goes through links before `..`; this reader resolves
2483
+ // lexically, so it is a cd it cannot place (the command's directory set holds both readings).
2484
+ if (/^(?:cd|chdir|pushd)(?:\s+-[A-Za-z@]+)*\s+-[A-Za-z@]*P/.test(lead))
2485
+ return null;
2486
+ const leadNoOpts = lead.replace(/^(cd|chdir|pushd)((?:\s+-[PLe@]+)+|\s+--)+(?=\s)/, '$1');
2487
+ if (/^popd\b/.test(lead))
2488
+ return null;
2489
+ // @implements A-SPEC-728 (round 25) — zsh `repeat <n> cd …` runs the cd n times: where it ends is not the lexical
2490
+ // target (`repeat 2 cd ..; rm -r .ax` from a subdirectory was allowed — measured).
2491
+ if (/^repeat\s+\S+\s+(?:cd|chdir|pushd|popd)(?:\s|$)/.test(lead))
2492
+ return null;
2493
+ const m = /^(cd|chdir|pushd)(?:\s+([\s\S]*))?$/.exec(leadNoOpts);
382
2494
  if (!m)
383
- return;
384
- const rawArg = (m[1] ?? '').trim();
385
- if (rawArg === '') {
386
- base = os.homedir();
387
- return;
388
- }
2495
+ return undefined;
2496
+ // A redirect on the cd itself (`cd x >/dev/null`, `2>/dev/null`) is not part of its argument.
2497
+ const rawArg = stripRedirects(m[2] ?? '').trim();
2498
+ if (rawArg === '')
2499
+ return m[1] === 'pushd' ? null : os.homedir(); // a bare pushd swaps the stack
2500
+ if (rawArg === '~+' || rawArg.startsWith('~+/'))
2501
+ return from === null ? null : path.join(from, rawArg.slice(2));
2502
+ let arg;
2503
+ // @implements A-SPEC-728 — `cd $CODEX_HOME` / `cd "$HOME/.codex"` are knowable: expand the home
2504
+ // spellings before the unknowable-variable bail-out, or the next relative write escapes judgment.
389
2505
  if (/[$`]/.test(rawArg)) {
390
- base = null;
391
- return;
392
- }
393
- const words = rawArg.match(/(?:[^\s'"]+|'[^']*'|"[^"]*")+/g) ?? [];
394
- if (words.length !== 1) {
395
- base = null;
396
- return;
397
- }
398
- const arg = words[0].replace(/^"([^"]*)"$/, '$1').replace(/^'([^']*)'$/, '$1');
399
- if (arg === '' || arg === '-') {
400
- base = null;
401
- return;
402
- }
403
- if (arg === '~') {
404
- base = os.homedir();
405
- return;
2506
+ // One word only: double quotes may wrap any piece (`"$HOME"/.codex`); single quotes keep `$` literal.
2507
+ const one = /'|`|\$\(/.test(rawArg) || /\s/.test(rawArg.replace(/"[^"]*"/g, 'x')) ? null : rawArg.replace(/"/g, '');
2508
+ const expanded = one === null ? null : expandHomeSpelling(one);
2509
+ // Round 17: `cd "$HOME"/.a?` is expanded by the shell too.
2510
+ if (expanded === null || /[*?[({]/.test(expanded))
2511
+ return null;
2512
+ arg = expanded;
406
2513
  }
407
- if (arg.startsWith('~/')) {
408
- base = path.join(os.homedir(), arg.slice(2));
409
- return;
2514
+ else {
2515
+ const words = rawArg.match(/(?:[^\s'"]+|'[^']*'|"[^"]*")+/g) ?? [];
2516
+ if (words.length !== 1)
2517
+ return null;
2518
+ // @implements A-SPEC-728 (round 17) — the word is reduced as the shell reduces it (`'.'ax`, `"."ax`,
2519
+ // `.\ax` are `.ax`), and a word the shell would EXPAND (an unquoted `*`, `?`, `[`, `(`, `{`) has an
2520
+ // unknowable target: `cd .a? && rm ledger/provenance.jsonl` resolved to a literal `<root>/.a?` that
2521
+ // exists nowhere, so the candidates never engaged and the ledger was deleted (measured, both shells).
2522
+ const reduced = reduceCdWord(words[0]);
2523
+ if (reduced === null)
2524
+ return null;
2525
+ arg = reduced;
2526
+ if (arg === '' || arg === '-')
2527
+ return null;
2528
+ if (arg === '~')
2529
+ return os.homedir();
2530
+ if (arg.startsWith('~/'))
2531
+ return path.join(os.homedir(), arg.slice(2));
2532
+ // Round 9: `~-` (OLDPWD), `~+N`/`~-N`, `~user` and `+N`/`-N` (stack rotation) name directories
2533
+ // the gate cannot see.
2534
+ if (arg.startsWith('~') || /^[+-]\d+$/.test(arg))
2535
+ return null;
410
2536
  }
411
- if (base === null) {
412
- const kind = absoluteKindOf(arg);
413
- base = kind === null ? null : pathFlavorFor(arg, arg).resolve(arg);
414
- return;
415
- }
416
- base = pathFlavorFor(base, arg).resolve(base, arg);
2537
+ const absolute = absoluteKindOf(arg) !== null;
2538
+ // A relative name not starting with `.`/`..` is searched through CDPATH, which the command may set.
2539
+ if (!absolute && !/^\.\.?(?:[/\\]|$)/.test(arg) && mentionsCdpath)
2540
+ return null;
2541
+ if (absolute)
2542
+ return pathFlavorFor(arg, arg).resolve(arg);
2543
+ if (from === null)
2544
+ return null;
2545
+ const to = pathFlavorFor(from, arg).resolve(from, arg);
2546
+ // @implements A-SPEC-728 (round 7) — `cd a` repeated grew the base without bound, O(n) per resolve
2547
+ // (200 KB: 15 s — measured). Past PATH_MAX the real `cd` fails, so the base is unknown.
2548
+ return to.length > 4096 ? null : to;
2549
+ };
2550
+ let st = freshList(startBase);
2551
+ const frames = [];
2552
+ // @implements A-SPEC-728 (round 11) — the bases a null-base segment MAY run in (shared, push-only: a
2553
+ // consumer sees every candidate the command produced, a superset).
2554
+ const seen = [];
2555
+ const seenSet = new Set();
2556
+ const note = (b) => { if (typeof b === 'string' && !seenSet.has(b)) {
2557
+ seenSet.add(b);
2558
+ seen.push(b);
2559
+ } };
2560
+ const lexical = (arg, from) => {
2561
+ if (arg === '' || arg === '-' || arg.startsWith('~') || /^[+-]\d+$/.test(arg))
2562
+ return arg === '~' || arg.startsWith('~/') ? path.join(os.homedir(), arg.slice(2)) : null;
2563
+ if (absoluteKindOf(arg) !== null)
2564
+ return pathFlavorFor(arg, arg).resolve(arg);
2565
+ return from === null ? null : pathFlavorFor(from, arg).resolve(from, arg);
417
2566
  };
2567
+ const withMaybe = (s) => (s.base === null ? { ...s, maybe: seen } : s);
2568
+ // @implements A-SPEC-728 (round 15) — a cd whose target cannot be resolved, in a command that NAMES `.ax`,
2569
+ // may land in `.ax` or any protected child: `ln -s .ax l && cd l && rm ledger/…` (the link did not exist
2570
+ // when the hook judged) and `X=.ax; cd "$X"; …` deleted the ledger in both shells (measured).
2571
+ // Round 16: a SPELLING (`.a?`, `$'\056ax'`, `"."ax`, `{.ax,}`), read once at the top and inherited by
2572
+ // child programs (re-reading each nested program would be quadratic in nesting — round 7).
2573
+ const mentionsAx = depth === 0 ? mentionsAxSpelling(command) : opts.ax === true;
2574
+ const noteAx = () => { if (!mentionsAx)
2575
+ return; note(path.join(startBase, '.ax')); for (const c of exports.AX_PROTECTED_CHILDREN)
2576
+ note(path.join(startBase, '.ax', c)); };
2577
+ // The lexical chain continues through uncertain cds (`npm test; cd sub; cd ../.ax`: `.ax` is a candidate).
2578
+ let lexBase = startBase;
2579
+ let mutated = opts.mutated === true;
2580
+ // The shell word that opens a stdin program (`bash <<EOF`) is not itself an earlier command of it.
2581
+ let mutatedBeforePart = mutated;
418
2582
  for (const piece of pieces) {
419
2583
  if (piece.kind === 'data') {
420
- out.push({ text: piece.text, base });
2584
+ out.push(withMaybe({ text: piece.text, base: st.cur, data: true }));
2585
+ continue;
2586
+ }
2587
+ if (piece.kind === 'interp') {
2588
+ out.push(withMaybe({ text: piece.text, base: st.cur, data: true, interp: true }));
2589
+ mutated = true;
421
2590
  continue;
422
2591
  }
423
2592
  if (piece.kind === 'prog') {
424
2593
  // A shell reading its program from stdin is a CHILD — its cds do not move the parent base.
425
- out.push(...shellSegments(piece.text, base ?? startBase, depth + 1)
426
- .map((s) => (base === null ? { ...s, base: null } : s)));
2594
+ const at = st.cur;
2595
+ // Rule 43: one list of possible bases per invocation, shared by its children — a fresh copy per child defeated every memo
2596
+ // keyed by the list (300 cds and a 300-line `bash -s` script took 7.4 s — measured).
2597
+ const shared = sharedMaybe(seen);
2598
+ out.push(...shellSegments(piece.text, at ?? startBase, depth + 1, { ...opts, mutated: mutatedBeforePart, ax: mentionsAx })
2599
+ .map((s) => (at === null ? { ...s, base: null, maybe: shared(s.maybe) } : s)));
2600
+ mutated = true;
427
2601
  continue;
428
2602
  }
429
- for (const part of splitTop(piece.text)) {
430
- let rem = part;
431
- for (const m of part.matchAll(PROG_STRING_RE)) {
432
- const prog = m[1] ?? m[2];
2603
+ let prevSep = '';
2604
+ for (const { text: part, sep } of splitTop(piece.text)) {
2605
+ const inPipe = prevSep === '|' || prevSep === '|&';
2606
+ prevSep = sep;
2607
+ const runBase = inPipe ? st.pipeBase : st.cur;
2608
+ if (!inPipe)
2609
+ st.pipeBase = runBase;
2610
+ // @implements A-SPEC-728 (round 18) — a directory-changing wrapper (`env -C DIR`, `sudo -D DIR`) moves
2611
+ // THIS command's base as a cd would: a knowable target from a known base with no earlier mutation;
2612
+ // otherwise unknown, with the lexical target (and `.ax` on a mention) as candidates. Not persisted.
2613
+ // Round 21: the redirects are split from the WHOLE command first — one glued to a wrapper word
2614
+ // (`env -C/tmp>out.txt true`) became part of the directory word and was never judged.
2615
+ const pre = part.includes('>') || part.includes('<') ? splitRedirects(part) : null;
2616
+ const wrap = wrapperChdir(pre !== null ? pre.command : part);
2617
+ let partText = part;
2618
+ let partBase = runBase;
2619
+ if (wrap !== null) {
2620
+ // Round 20: the redirects belong to the shell's own directory, before the wrapper's chdir.
2621
+ partText = wrap.rest;
2622
+ if (pre !== null && pre.redirects !== '')
2623
+ out.push(withMaybe({ text: pre.redirects, base: runBase }));
2624
+ // Round 19: the layers compose like sequential cds; several `-C` in one layer are ambiguous, so
2625
+ // both readings (composed, last-only) become candidates and the base is unknown.
2626
+ let t = runBase ?? lexBase;
2627
+ for (const d of wrap.dirs) {
2628
+ t = t === null ? null : cdTargetOf(d, t);
2629
+ if (t === null)
2630
+ break;
2631
+ }
2632
+ note(t);
2633
+ if (wrap.ambiguous) {
2634
+ if (wrap.dirs.length > 0)
2635
+ note(cdTargetOf(wrap.dirs[wrap.dirs.length - 1], runBase ?? lexBase));
2636
+ partBase = null;
2637
+ }
2638
+ else
2639
+ partBase = t !== null && runBase !== null && !mutated ? t : null;
2640
+ if (partBase === null)
2641
+ noteAx();
2642
+ }
2643
+ // @implements A-SPEC-728 (round 7) — one pass: re-copying the part once per quoted program was
2644
+ // quadratic (`'sh -c ` × n, 200 KB: 6.7 s — measured). Each program is blanked where it matched.
2645
+ const rem = !programs ? partText : partText.replace(PROG_STRING_RE, (whole, single, double) => {
2646
+ // A double-quoted program is read the way the shell reads it: `\"`, `\\`, `\$`, `\``
2647
+ // lose their backslash (round 3: nested `bash -c "bash -c \"…\""` was cut at the first `\"`).
2648
+ const prog = single ?? double?.replace(/\\(["\\$`])/g, '$1');
433
2649
  if (prog === undefined || prog === '')
434
- continue;
2650
+ return whole;
435
2651
  // Same child-shell rule as stdin programs; blank the program out of the parent text so its
436
- // candidates are judged once, at the child's own bases.
437
- out.push(...shellSegments(prog, base ?? startBase, depth + 1)
438
- .map((s) => (base === null ? { ...s, base: null } : s)));
439
- rem = rem.replace(`'${prog}'`, "''").replace(`"${prog}"`, '""');
2652
+ // candidates are judged once, at the child's own bases. (An `eval` runs in THIS shell: the
2653
+ // command-position check below makes the base unknown after it.)
2654
+ const shared = sharedMaybe(seen);
2655
+ out.push(...shellSegments(prog, partBase ?? startBase, depth + 1, { mutated, ax: mentionsAx })
2656
+ .map((s) => ({ ...(partBase === null ? { ...s, base: null, maybe: shared(s.maybe) } : s), nested: true })));
2657
+ return single !== undefined ? whole.replace(`'${single}'`, "''") : whole.replace(`"${double}"`, '""');
2658
+ });
2659
+ const { opens, closes } = groupParens(rem);
2660
+ for (let i = 0; i < opens; i++) {
2661
+ frames.push(st);
2662
+ st = freshList(runBase);
2663
+ }
2664
+ note(runBase);
2665
+ if (runBase !== null)
2666
+ lexBase = runBase;
2667
+ out.push(withMaybe({ text: rem, base: partBase, ...(sep !== undefined && sep !== '' ? { sep } : {}) }));
2668
+ const target = readCd(rem, runBase ?? lexBase);
2669
+ if (target !== undefined) {
2670
+ note(target);
2671
+ lexBase = target;
2672
+ }
2673
+ const blanked = blankQuotes(rem);
2674
+ // @implements A-SPEC-728 (round 22) — a command word the shell expands (`$C`, `${C}`, `"$C"`, `$(…)`) can be `cd`:
2675
+ // the base after it is unknown, its first argument's lexical target a candidate (`C=cd; $C .ax && rm -r specs`
2676
+ // deleted the spec store — measured).
2677
+ const word = target === undefined ? commandWordOf(rem) : '';
2678
+ const expandedWord = word !== '' && /[$`]/.test(word);
2679
+ if (expandedWord) {
2680
+ const after = rem.slice(rem.indexOf(word) + word.length).trim();
2681
+ const first = /^[^\s;&|<>()]+/.exec(after)?.[0];
2682
+ const reduced = first === undefined ? null : reduceCdWord(first);
2683
+ if (reduced !== null)
2684
+ note(lexical(reduced, runBase ?? lexBase));
2685
+ }
2686
+ const cdLike = target === undefined && (expandedWord || CD_WORD_RE.test(blanked));
2687
+ // Round 11: a cd the reader does not parse (`then cd .ax`, `a) cd x`) still names its target.
2688
+ if (cdLike)
2689
+ for (const m of blanked.matchAll(CD_ARG_RE))
2690
+ note(lexical(m[1], runBase ?? lexBase));
2691
+ const lastStage = !(sep === '|' || sep === '|&');
2692
+ if (target !== undefined || cdLike) {
2693
+ if (lastStage) {
2694
+ // @implements A-SPEC-728 (rule 33) — a relative cd from an unknown base lands somewhere unknown: `cd nope; cd src &&
2695
+ // rm -r lib` made `nope/src` a certain base and skipped the reach that holds `src` (measured; bash and zsh delete it).
2696
+ const t = target === undefined || mutated ? null : runBase === null ? readCd(rem, null) ?? null : target;
2697
+ if (t === null)
2698
+ noteAx();
2699
+ st.sawCd = true;
2700
+ if (inPipe) {
2701
+ st.certain = false;
2702
+ st.cur = null;
2703
+ } // zsh runs the last stage here
2704
+ else {
2705
+ if (!(t !== null && st.allAnd && st.cdPrefix && isSearchableDir(t)) && t !== runBase)
2706
+ st.certain = false;
2707
+ st.cur = st.allAnd || t === runBase ? t : null;
2708
+ }
2709
+ }
2710
+ else
2711
+ st.cdPrefix = false; // a cd FOLLOWED by `|`: a subshell
2712
+ }
2713
+ else
2714
+ st.cdPrefix = false;
2715
+ mutatedBeforePart = mutated;
2716
+ if (/\$\(|`|[<>]\(/.test(rem) || !cdSafe(rem))
2717
+ mutated = true;
2718
+ for (let i = 0; i < closes && frames.length > 0; i++) {
2719
+ st = frames.pop();
2720
+ st.cdPrefix = false;
2721
+ }
2722
+ if (sep === '&&' || sep === '|' || sep === '|&')
2723
+ continue;
2724
+ if (sep === '||') {
2725
+ st.allAnd = false;
2726
+ if (st.sawCd && !st.certain)
2727
+ st.cur = null;
2728
+ continue;
440
2729
  }
441
- applyCd(rem);
442
- out.push({ text: rem, base });
2730
+ // The list ends: the next one runs whether or not its cds ran (`&`: it ran in the background).
2731
+ st = freshList(sep.startsWith('&') ? st.start : !st.sawCd ? st.start : st.certain ? st.cur : null);
443
2732
  }
444
2733
  }
445
2734
  return out;
@@ -447,7 +2736,10 @@ function shellSegments(command, startBase, depth = 0) {
447
2736
  function resolvesInside(raw, roots, impl = path) {
448
2737
  if (typeof raw !== 'string' || raw.length === 0 || roots.length === 0)
449
2738
  return false;
450
- const expanded = raw === '~' || raw.startsWith('~/') ? impl.resolve(os.homedir(), raw.slice(1) || '.') : raw;
2739
+ // @implements A-SPEC-728 — `~/x` is `<home>/x`. `raw.slice(1)` handed resolve the ABSOLUTE `/x`,
2740
+ // which discarded the home directory: `echo x > ~/.claude/settings.json` walked through while the
2741
+ // same file spelled absolutely was denied.
2742
+ const expanded = raw === '~' ? os.homedir() : raw.startsWith('~/') ? impl.resolve(os.homedir(), raw.slice(2)) : raw;
451
2743
  for (const root of roots) {
452
2744
  const base = impl.resolve(root);
453
2745
  const abs = impl.resolve(base, expanded);