@holmes-lab/holmes-kit 0.30.0 → 0.31.0

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 (136) hide show
  1. package/CHANGELOG.md +494 -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 +23 -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 +13 -0
  31. package/dist/holmes/cli/upgrade.js +116 -23
  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.js +3 -1
  134. package/dist/holmes/update/update-notice.d.ts +6 -0
  135. package/dist/holmes/update/update-notice.js +18 -1
  136. package/package.json +11 -4
@@ -1,4 +1,37 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.rmCommandTargets = rmCommandTargets;
4
37
  exports.normalizeWindowsPathSpellings = normalizeWindowsPathSpellings;
@@ -9,8 +42,12 @@ exports.classifyArchitectureReversal = classifyArchitectureReversal;
9
42
  exports.classifySecret = classifySecret;
10
43
  exports.classifyBlastRadius = classifyBlastRadius;
11
44
  exports.assessRisk = assessRisk;
12
- // @implements A-SPEC-125.1, A-SPEC-627
45
+ // @implements A-SPEC-125.1, A-SPEC-627, A-SPEC-728, A-SPEC-737
46
+ const fs = __importStar(require("node:fs"));
47
+ const path = __importStar(require("node:path"));
13
48
  const risk_types_1 = require("./risk-types");
49
+ const linear_match_1 = require("./linear-match");
50
+ const write_target_1 = require("./write-target");
14
51
  const AWS_KEY_RE = /AKIA[0-9A-Z]{16}/;
15
52
  const PEM_KEY_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
16
53
  const SECRET_KV_RE = /(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S{6,}/i;
@@ -32,15 +69,19 @@ const FORCE_RE = /--force(?![-\w])|--force=/i;
32
69
  // unrelated later `-f` (e.g. `git push origin main && rm -f tmp`) as a force push, and the
33
70
  // single-dash start means `--force-with-lease` never matches it. (Corpus finding: `git push -f`
34
71
  // slipped the `--force`-only rule.)
35
- const PUSH_FORCE_SHORT_RE = /\bpush\b[^;&|\n]*\s-[a-z]*f[a-z]*(?:\s|$)/i;
72
+ // @implements A-SPEC-728 (round 5) — linear: the regex form restarted at every `push` (O(n²)).
73
+ const SEG = /[;&|\n]/;
74
+ const PUSH_FORCE_SHORT_RE = (0, linear_match_1.headThenTail)(/\bpush\b/i, SEG, /\s-(?=[a-z]*f)[a-z]+(?:\s|$)/i);
36
75
  // Recursive+force `rm`, scoped to each `rm` invocation up to a shell separator so an
37
76
  // unrelated later subcommand's flag (e.g. `rm x && terraform apply --force`) is not
38
77
  // misattributed, and so an unrelated long option on the rm line (`rm x --format json`)
39
78
  // does not spuriously match. Catches combined clusters (`-rf`, `-fr`, `-rfv`) AND
40
79
  // separated short flags (`-r -f`) AND long options (`--recursive --force`).
41
80
  const RM_SEGMENT_RE = /\brm\b[^;&|\n]*/gi;
42
- const RM_RECURSIVE_RE = /(?:^|\s)-[a-z]*r[a-z]*(?:\s|$)|(?:^|\s)--recursive(?:\s|$)/i;
43
- const RM_FORCE_RE = /(?:^|\s)-[a-z]*f[a-z]*(?:\s|$)|(?:^|\s)--force(?:\s|$)/i;
81
+ // @implements A-SPEC-728 (round 6) — `-[a-z]*r[a-z]*` backtracked quadratically on a run of the letter
82
+ // (`rm -rrr…`: 47 s at 240 KB); a lookahead finds the letter, one `[a-z]+` consumes the cluster.
83
+ const RM_RECURSIVE_RE = /(?:^|\s)-(?=[a-z]*r)[a-z]+(?:\s|$)|(?:^|\s)--recursive(?:\s|$)/i;
84
+ const RM_FORCE_RE = /(?:^|\s)-(?=[a-z]*f)[a-z]+(?:\s|$)|(?:^|\s)--force(?:\s|$)/i;
44
85
  // A recursive-force `rm` is whole-tree destruction ONLY when its target isn't a manifestly-safe,
45
86
  // regenerable build/dependency/cache dir. Cleaning `build/`, `dist/`, `node_modules/`, `target/`,
46
87
  // etc. is a routine non-destructive dev command — blanket-blocking it as hard-hitl broke real
@@ -58,7 +99,7 @@ const SAFE_RM_DIRS = new Set([
58
99
  ]);
59
100
  function isSafeScopedRmTarget(raw) {
60
101
  const unq = raw.replace(/^["']/, '').replace(/["']$/, ''); // strip one surrounding quote pair
61
- const t = unq.replace(/\/+$/, '').replace(/^(?:\.\/)+/, ''); // strip trailing / and leading ./
102
+ const t = (0, linear_match_1.trimTrailing)(unq, '/').replace(/^(?:\.\/)+/, ''); // strip trailing / and leading ./
62
103
  if (!t || t === '.' || t === '..')
63
104
  return false;
64
105
  // Only a CLEAN simple path may be safe. Any shell metacharacter means we cannot statically know
@@ -85,7 +126,12 @@ function isSafeScopedRmTarget(raw) {
85
126
  return SAFE_RM_DIRS.has(segs[0]); // relative: first segment is a known build dir
86
127
  }
87
128
  function rmTargets(segment) {
88
- return segment.replace(/^\s*rm\b/i, '').split(/\s+/).filter((tok) => tok && !tok.startsWith('-'));
129
+ // A-SPEC-728 (round 27): a closing `)` or `}` the shell reads as syntax is not part of the target (`(cd web && rm -rf
130
+ // dist)` was refused as the catastrophic target `dist)` — measured).
131
+ return segment.replace(/^\s*rm\b/i, '').split(/\s+/)
132
+ .map((tok) => { let t = tok; while (/[)}]$/.test(t) && !/[({]/.test(t))
133
+ t = t.slice(0, -1); return t; })
134
+ .filter((tok) => tok && !tok.startsWith('-'));
89
135
  }
90
136
  // The rm target tokens the classifier will look up in `rmTargetSignals`, across every RECURSIVE rm
91
137
  // segment of a command. Exported so the hook resolves git facts for EXACTLY these tokens (the signal
@@ -119,7 +165,7 @@ const EPHEMERAL_ABS_ROOT_RE = /^\/(private\/)?(tmp|var\/tmp|var\/folders)(\/|$)/
119
165
  // can't make `/` or `~/.ssh` safe, so these short-circuit before any signal is consulted.
120
166
  function isCatastrophicRmFloor(raw) {
121
167
  const unquoted = raw.replace(/^["']/, '').replace(/["']$/, '');
122
- const t = unquoted === '/' ? '/' : unquoted.replace(/\/+$/, '');
168
+ const t = unquoted === '/' ? '/' : (0, linear_match_1.trimTrailing)(unquoted, '/');
123
169
  if (!t)
124
170
  return false;
125
171
  if (t === '/')
@@ -154,7 +200,7 @@ function rmTargetSafety(raw, sig) {
154
200
  }
155
201
  if (isSafeScopedRmTarget(raw))
156
202
  return 'safe'; // name allowlist: build/, /path/build, CMake…
157
- const t = raw.replace(/^["']/, '').replace(/["']$/, '').replace(/\/+$/, '');
203
+ const t = (0, linear_match_1.trimTrailing)(raw.replace(/^["']/, '').replace(/["']$/, ''), '/');
158
204
  if (t.startsWith('/') && !EPHEMERAL_ABS_ROOT_RE.test(t))
159
205
  return 'dangerous'; // system-area absolute
160
206
  return 'unknown';
@@ -212,27 +258,29 @@ const DROP_TABLE_OR_DB_RE = /\bDROP\s+(TABLE|DATABASE)\b/i;
212
258
  // coverage is a calibration concern deferred per REQ-125; false-negatives on unlisted
213
259
  // destructive commands are possible and must not be over-trusted (other layers + human
214
260
  // oversight remain). Each is scanned across the whole command string, case-insensitively.
261
+ // @implements A-SPEC-728 (round 5) — the `HEAD[^SEP]*TAIL` checks run as linear testers that decide
262
+ // the same (repeating HEAD 40 000 times made each regex rescan: seconds per verdict).
215
263
  const DESTRUCTIVE_CMD_CHECKS = [
216
- { re: /\bdd\b[^;&|\n]*\bof=\/dev\//i, reason: 'dd writing to a raw device (irreversible disk overwrite)' },
264
+ { re: (0, linear_match_1.headThenTail)(/\bdd\b/i, SEG, /\bof=\/dev\//i), reason: 'dd writing to a raw device (irreversible disk overwrite)' },
217
265
  { re: /\bmkfs(\.\w+)?\b/i, reason: 'mkfs formats a filesystem (irreversible)' },
218
266
  { re: /\bshred\b/i, reason: 'shred irreversibly destroys file contents' },
219
267
  // Raw-device redirect — widened past sd/disk/nvme/hd to rdisk (macOS), device-mapper, loop, md, vd (review F5).
220
268
  { re: />\s*\/dev\/(r?disk|sd|nvme|hd|vd|md|loop|mapper)/i, reason: 'redirect overwrites a raw device' },
221
269
  // Pipe-to-shell RCE — `[^;&\n]*` now CROSSES intermediate `|` stages (curl|tee|sh, curl|grep|sh) and
222
270
  // covers more interpreters (python/perl/ruby/node/php/ksh), which the old single-pipe list missed (F5).
223
- { re: /\b(curl|wget|fetch)\b[^;&\n]*\|[^;&\n]*\b(sudo\s+)?(sh|bash|zsh|dash|ksh|python[0-9.]*|perl|ruby|node|php)\b/i, reason: 'pipe-to-shell executes remote code (RCE)' },
224
- { re: /\bgit\s+clean\b[^;&|\n]*-[a-z]*f/i, reason: 'git clean -f irreversibly removes untracked files' },
225
- { re: /\bfind\b[^;&|\n]*\s-delete\b/i, reason: 'find -delete irreversibly removes matched files' },
271
+ { re: (0, linear_match_1.headMidTail)(/\b(curl|wget|fetch)\b/i, /(?!)/, /\|/, /[;&\n]/, /\b(sudo\s+)?(sh|bash|zsh|dash|ksh|python[0-9.]*|perl|ruby|node|php)\b/i), reason: 'pipe-to-shell executes remote code (RCE)' },
272
+ { re: (0, linear_match_1.headThenTail)(/\bgit\s+clean\b/i, SEG, /-[a-z]*f/i), reason: 'git clean -f irreversibly removes untracked files' },
273
+ { re: (0, linear_match_1.headThenTail)(/\bfind\b/i, SEG, /\s-delete\b/i), reason: 'find -delete irreversibly removes matched files' },
226
274
  // Discard ALL uncommitted work — same harm as `git reset --hard`, previously unchecked (review F3).
227
- { re: /\bgit\s+(restore|checkout)\b[^;&|\n]*(?:\s--)?\s\.(?:\s|$)/i, reason: 'git restore/checkout . discards all uncommitted work irreversibly' },
228
- { re: /\bgit\s+branch\b[^;&|\n]*\s-D\b/i, reason: 'git branch -D force-deletes a branch' },
275
+ { re: (0, linear_match_1.headThenTail)(/\bgit\s+(restore|checkout)\b/i, SEG, /(?:\s--)?\s\.(?:\s|$)/i), reason: 'git restore/checkout . discards all uncommitted work irreversibly' },
276
+ { re: (0, linear_match_1.headThenTail)(/\bgit\s+branch\b/i, SEG, /\s-D\b/i), reason: 'git branch -D force-deletes a branch' },
229
277
  // Recursive chmod on a catastrophic target bricks permissions; truncate -s 0 zeroes a file (F3).
230
- { re: /\bchmod\b\s+-[a-z]*R[a-z]*\b[^;&|\n]*\s(\/|~|\.)(\s|$)/i, reason: 'recursive chmod on root/home/cwd bricks permissions' },
231
- { re: /\btruncate\b[^;&|\n]*-s\s*0\b/i, reason: 'truncate -s 0 irreversibly zeroes a file' },
278
+ { re: (0, linear_match_1.headThenTail)(/\bchmod\b\s+-(?=[a-z]*R)[a-z]+\b/i, SEG, /\s(\/|~|\.)(\s|$)/i), reason: 'recursive chmod on root/home/cwd bricks permissions' },
279
+ { re: (0, linear_match_1.headThenTail)(/\btruncate\b/i, SEG, /-s\s*0\b/i), reason: 'truncate -s 0 irreversibly zeroes a file' },
232
280
  // @implements A-SPEC-196 (Windows Native CMD / PowerShell destructive command classification)
233
- { re: /\b(?:Remove-Item|ri)\b[^;&|\n]*-(?:Recurse|Force|r|f)\b/i, reason: 'PowerShell Remove-Item -Recurse/-Force deletes file trees (irreversible)' },
234
- { re: /\bdel\b[^;&|\n]*\/(s|f|q)\b/i, reason: 'Windows CMD del /s deletes file trees (irreversible)' },
235
- { re: /\b(rmdir|rd)\b[^;&|\n]*\/s\b/i, reason: 'Windows CMD rmdir /s deletes directory trees (irreversible)' },
281
+ { re: (0, linear_match_1.headThenTail)(/\b(?:Remove-Item|ri)\b/i, SEG, /-(?:Recurse|Force|r|f)\b/i), reason: 'PowerShell Remove-Item -Recurse/-Force deletes file trees (irreversible)' },
282
+ { re: (0, linear_match_1.headThenTail)(/\bdel\b/i, SEG, /\/(s|f|q)\b/i), reason: 'Windows CMD del /s deletes file trees (irreversible)' },
283
+ { re: (0, linear_match_1.headThenTail)(/\b(rmdir|rd)\b/i, SEG, /\/s\b/i), reason: 'Windows CMD rmdir /s deletes directory trees (irreversible)' },
236
284
  ];
237
285
  // Protected .ax governance paths, matched as a path SEGMENT so absolute (`/proj/.ax/specs/x`)
238
286
  // and `./`-relative (`./.ax/decisions/x`) forms are caught, not just a literal string prefix.
@@ -266,7 +314,7 @@ function scopeAxToProject(cmd, projectRoot) {
266
314
  const spelled = normalizeWindowsPathSpellings(cmd);
267
315
  if (!projectRoot)
268
316
  return spelled;
269
- const root = normalizeWindowsPathSpellings(projectRoot.replace(/\\/g, '/')).replace(/\/+$/, '');
317
+ const root = (0, linear_match_1.trimTrailing)(normalizeWindowsPathSpellings(projectRoot.replace(/\\/g, '/')), '/');
270
318
  // NTFS folds case (foldsCaseBySyntax says the same of a drive letter); POSIX does not.
271
319
  const drive = /^[a-z]:\//.test(root);
272
320
  const inside = (abs) => {
@@ -275,7 +323,38 @@ function scopeAxToProject(cmd, projectRoot) {
275
323
  return a === r || a.startsWith(`${r}/`);
276
324
  };
277
325
  // The pre-class no longer admits `:` — that is what cut `C:/proj/.ax/x` down to `/proj/.ax/x`.
278
- return spelled.replace(/(^|[\s'"=(])((?:[a-z]:)?\/[^\s'"()]*\/\.ax\/[^\s'"()]*)/g, (m, pre, abs) => (inside(abs) ? m : `${pre}<other-project-path>`));
326
+ // @implements A-SPEC-728 (rule 42) — the same rewrite as `/(^|[\s'"=(])((?:[a-z]:)?\/[^\s'"()]*\/\.ax\/[^\s'"()]*)/g`, in linear
327
+ // time: the regex rescanned each run of path characters from every `=` (256 KB of `=/` met the hook's 20 s wall —
328
+ // measured). A match lies inside one maximal run of `[^\s'"()]` and extends to its end, so each run needs only its last
329
+ // `/.ax/` and its leftmost start: the run's first character after a boundary other than `)`, or one after an `=` inside it.
330
+ const RUN = /[^\s'"()]+/g;
331
+ let out = '';
332
+ let last = 0;
333
+ for (let m = RUN.exec(spelled); m !== null; m = RUN.exec(spelled)) {
334
+ const a = m.index;
335
+ const run = m[0];
336
+ const b = a + run.length;
337
+ // Searched inside the run only — the whole text searched per run was quadratic again (` > hooks.json` repeated).
338
+ const inRun = run.lastIndexOf('/.ax/');
339
+ if (inRun < 0)
340
+ continue;
341
+ const lastAx = a + inRun;
342
+ const firstSlash = (st) => (spelled[st] === '/' ? st
343
+ : st + 2 < b && spelled[st] >= 'a' && spelled[st] <= 'z' && spelled[st + 1] === ':' && spelled[st + 2] === '/' ? st + 2 : -1);
344
+ const valid = (st) => { const f = firstSlash(st); return f >= 0 && lastAx >= f + 1; };
345
+ let start = (a === 0 || spelled[a - 1] !== ')') && valid(a) ? a : -1;
346
+ for (let e = run.indexOf('='); start < 0 && e >= 0 && a + e + 1 <= lastAx; e = run.indexOf('=', e + 1)) {
347
+ if (valid(a + e + 1))
348
+ start = a + e + 1;
349
+ }
350
+ if (start < 0)
351
+ continue;
352
+ const pre = start === 0 ? '' : spelled[start - 1];
353
+ const abs = spelled.slice(start, b);
354
+ out += spelled.slice(last, start === 0 ? 0 : start - 1) + (inside(abs) ? pre + abs : `${pre}<other-project-path>`);
355
+ last = b;
356
+ }
357
+ return out + spelled.slice(last);
279
358
  }
280
359
  // `state` joined the protected set with P3 (REQ-134): it holds the constitution-debt and the
281
360
  // last-green baseline, so a single-file `rm` there would bypass the WRITE_CODE debt gate — measured
@@ -287,39 +366,273 @@ function scopeAxToProject(cmd, projectRoot) {
287
366
  // the exact two-copies drift this repository has paid for with isTestFile and a restated section
288
367
  // splitter. The directories are now written once; each rule keeps its own shape around them.
289
368
  const PROTECTED_AX_ALT = 'specs|decisions|ledger|cpg_cache|state|roles|approvals|entities';
290
- const PROTECTED_AX_PATH_RE = new RegExp(String.raw `(^|/)\.ax/(${PROTECTED_AX_ALT})(/|$)`);
369
+ // @implements A-SPEC-728 (round 12) — case-folded like the redirect and write-verb channels: `rm .AX/ledger/…`
370
+ // deleted the real file on a case-folding disk while `echo x > .AX/ledger/…` was refused (measured).
371
+ const PROTECTED_AX_PATH_RE = new RegExp(String.raw `(^|/)\.ax/(${PROTECTED_AX_ALT})(/|$)`, 'i');
291
372
  // A removal verb + a protected .ax path anywhere in a shell command — the command form of
292
373
  // the governance-path delete, which the structured `kind:'delete'` branch alone would miss.
293
374
  // Not just removal: RELOCATING or CLOBBERING a protected .ax path is equally destructive to it, so
294
375
  // mv/cp/git-mv and a `>` truncation count too (review F4 — `mv .ax/specs /tmp` evaded the rm-only rule).
295
376
  const REMOVAL_VERB_RE = /\b(rm|rmdir|unlink|git\s+rm|git\s+mv|mv|cp)\b/i;
296
- const CLOBBER_AX_RE = new RegExp(String.raw `>\s*['"]?[^\s;&|]*\.ax/(${PROTECTED_AX_ALT})\b`, 'i');
297
- const CMD_PROTECTED_AX_RE = new RegExp(String.raw `(^|[\s'"=(/])\.ax/(${PROTECTED_AX_ALT})(/|\b)`);
377
+ // @implements A-SPEC-728 (round 6) — linear: the regex restarted its token scan at every `>` (51 s on
378
+ // 240 000 of them). A later `>` inside an already-scanned token can only see a suffix of it.
379
+ const CLOBBER_AX_RE = (0, linear_match_1.redirectTokenTester)(new RegExp(String.raw `\.ax/(${PROTECTED_AX_ALT})\b`, 'i'));
380
+ const CMD_PROTECTED_AX_RE = new RegExp(String.raw `(^|[\s'"=(/])\.ax/(${PROTECTED_AX_ALT})(/|\b)`, 'i');
298
381
  /**
299
382
  * Normalize a command string for protected-path matching: collapse `//` runs and `./` segments so
300
383
  * `./.ax//ledger/x` matches the same rules as `.ax/ledger/x` (adversarial probe: those forms slipped
301
384
  * every protected-path regex). Also flattens a leading `cd <dir> &&` so a cd-relative write
302
385
  * (`cd .ax/ledger && cat > provenance.jsonl`) is seen against its real directory.
303
386
  */
304
- function normalizeCommandPaths(cmd) {
387
+ /** Bare relative paths in `text` prefixed with `dir`, so the path rules see where they land. */
388
+ function prefixBareRelative(text, dir) {
389
+ return text.replace(/(^|[\s>|])(?![-/~'"])([\w@.][\w@./-]*)/g, (full, pre, p) => /^[A-Za-z0-9_.@-]+$/.test(p) || p.includes('/') ? `${pre}${dir}/${p}` : full);
390
+ }
391
+ /**
392
+ * The segment with only its redirect targets that name a protected `.ax` child read under the store (`> ledger/x`,
393
+ * `>> "specs/y"`, `>&state/z`); a `>` inside quotes is not a redirect.
394
+ *
395
+ * @implements A-SPEC-728 (rule 34)
396
+ */
397
+ function redirectTargetsUnder(text, ax) {
398
+ const masked = maskQuoted(text);
399
+ // Rule 35: the descriptor digits start at a non-digit (a 100 KB digit run took 5 s — measured), and `<>` is a write.
400
+ if (!text.includes('>'))
401
+ return text;
402
+ // Rule 36: the digits have their own lookbehind; the operator only must not follow `<`/`>` (`2>&1>ledger/x` matched no
403
+ // start and passed — measured).
404
+ const re = new RegExp(`((?:(?<![0-9&<>])(?:[0-9]+|&))?(?<![<>])(?:>{1,2}[|!&]?|<>)[ \\t]*)(['"]?)(?:\\./)*((?:${write_target_1.AX_PROTECTED_CHILDREN.join('|')})(?:/[^\\s'"<>|;&()]*)?)(?=[\\s'"<>|;&()]|$)`, 'g');
405
+ return text.replace(re, (whole, op, q, p, at) => (masked[at + op.indexOf('>')] === '>' ? `${op}${q}${ax}/${p}` : whole));
406
+ }
407
+ /**
408
+ * @implements A-SPEC-728 (rule 39) — whether a literal cd argument of the command lands in the store (`.ax` or below, by
409
+ * identity: a link counts) from the start or from any base the command has. Past 16,384 argument-base pairs it answers yes
410
+ * without looking.
411
+ */
412
+ function cdReachesStore(cb, start, rootAx) {
413
+ const bases = [...new Set([start, ...cb.bases])];
414
+ if (cb.literal.length * bases.length > 16_384)
415
+ return true;
416
+ const real = (p) => { try {
417
+ return fs.realpathSync.native(p);
418
+ }
419
+ catch {
420
+ return null;
421
+ } };
422
+ const fold = (p) => p.normalize('NFC').toUpperCase();
423
+ const within = (p, dir) => p === dir || p.startsWith(dir + path.sep);
424
+ const realAx = real(rootAx);
425
+ const seen = new Set();
426
+ for (const arg of cb.literal) {
427
+ for (const b of (0, write_target_1.absoluteKindOf)(arg) !== null ? [arg] : bases) {
428
+ const to = (0, write_target_1.absoluteKindOf)(arg) !== null ? (0, write_target_1.pathFlavorFor)(arg, arg).resolve(arg) : (0, write_target_1.pathFlavorFor)(b, arg).resolve(b, arg);
429
+ if (seen.has(to))
430
+ continue;
431
+ seen.add(to);
432
+ if (within(fold(to), fold(rootAx)))
433
+ return true;
434
+ const r = realAx === null ? null : real(to);
435
+ if (r !== null && realAx !== null && (within(r, realAx) || within(fold(r), fold(realAx))))
436
+ return true;
437
+ }
438
+ }
439
+ return false;
440
+ }
441
+ /**
442
+ * @implements A-SPEC-728 (round 10) — the command with each segment's bare relative paths prefixed by
443
+ * the base the certain-cd model gives it. `normalizeCommandPaths` follows only the FIRST leading cd:
444
+ * `cd /tmp; cd <proj>/.ax; echo x > ledger/provenance.jsonl` overwrote the ledger in bash and zsh
445
+ * (measured). A base that resolves inside the project is spelled under the project root as given,
446
+ * so `/private/var` aliases and `.AX` spellings fold to the spelling the path rules compare against.
447
+ */
448
+ function segmentFlattened(cmd, root, start = root) {
449
+ const real = (p) => { try {
450
+ return fs.realpathSync.native(p);
451
+ }
452
+ catch {
453
+ return p;
454
+ } };
455
+ const realRoot = real(root);
456
+ // Rule 37: once per base, not once per segment (131,000 segments of `a\n` spent 2.8 s of a 4.8 s verdict in this
457
+ // look-up — measured).
458
+ const placed = new Map();
459
+ const under = (base) => {
460
+ const known = placed.get(base);
461
+ if (known !== undefined)
462
+ return known;
463
+ const rel = path.relative(realRoot, real(base));
464
+ const dir = rel === '' ? root : rel.startsWith('..') || path.isAbsolute(rel) ? base : path.join(root, rel);
465
+ placed.set(base, dir);
466
+ return dir;
467
+ };
468
+ // Only a segment whose base MOVED is rewritten (the as-written form already covers the root), and
469
+ // never its command word or a shell keyword — prefixing `sed`'s `1p` or a loop's `do` turned every
470
+ // read over .ax into "not recognisably read-only" (measured on the A-SPEC-737 read loops).
471
+ const KEYWORD = /^(?:do|done|then|else|elif|fi|in|for|if|while|until|case|esac|select|function)$/;
472
+ // Round 14: a token is prefixed after its opening quote, and a `\x` escape reads as `x` — the text rules
473
+ // could not re-spell `rm "ledger/x"` or `rm r\oles/x` (measured allow after an uncertain cd).
474
+ // Rule 39: `globs` also prefixes a word that starts with a glob character (`*.md`, `?EQ-1.md`, `[R]*`, `{a,b}`), for the
475
+ // store reading — outside it the rm rule sees the store directory itself.
476
+ // @implements A-SPEC-728 (rule 44) — `only` limits the prefix to the words that match it: at a climb base (`.ax/~/…`, a
477
+ // placeholder for an unprotected child) only a word that climbs can leave the placeholder, and prefixing all 131,000 words
478
+ // of a 256 KB segment at each of 8 climb bases built ~60 MB for the path rules (3.7 s — measured).
479
+ const rewrite = (text, dir, globs = false, only) => {
480
+ let first = true;
481
+ const word = globs ? /(^|[\s>|])(['"]?)(?![-/~'"])([\w@.*?[{][\w@./*?[\]{},-]*)/g : /(^|[\s>|])(['"]?)(?![-/~'"])([\w@.][\w@./-]*)/g;
482
+ const plain = globs ? /^[A-Za-z0-9_.@*?[\]{},-]+$/ : /^[A-Za-z0-9_.@-]+$/;
483
+ return text.replace(/\\([\w@./-])/g, '$1').replace(word, (full, pre, q, p) => {
484
+ const skip = first || KEYWORD.test(p);
485
+ first = false;
486
+ if (skip || (only !== undefined && !only.test(p)))
487
+ return full;
488
+ return plain.test(p) || p.includes('/') ? `${pre}${q}${dir}/${p}` : full;
489
+ });
490
+ };
491
+ // Round 17: from the directory the harness runs the shell in (`start`), not always the root.
492
+ const segments = (0, write_target_1.shellSegments)(cmd, start);
493
+ // @implements A-SPEC-728 (round 11) — a null-base segment MAY run in any base the command produced
494
+ // (`maybe`); the ones under `.ax` matter, keyed by the top-level `.ax` child so the rewrite count is
495
+ // bounded by the store's layout, not the command's length (measured: `git log; cd sub; cd ../.ax;
496
+ // rm ledger/provenance.jsonl` deleted the ledger — the uncertain cd left the segment unflattened).
497
+ const candidates = new Set();
498
+ // The `maybe` array is shared by every null-base segment of one shell: walk each distinct array once
499
+ // (65k segments × 2k candidates was 1.4 s — measured).
500
+ const arrays = new Set();
501
+ for (const s of segments)
502
+ if (s.base === null && s.maybe)
503
+ arrays.add(s.maybe);
504
+ for (const a of arrays)
505
+ for (const m of a)
506
+ candidates.add(m);
507
+ // @implements A-SPEC-728 (round 23) — every segment is also judged from every directory under `.ax` the command may
508
+ // run ANY part in (flow-insensitive): a loop, a function or a trap runs text after a later `cd .ax` (measured: `for …;
509
+ // do rm ledger/provenance.jsonl; cd .ax; done` deleted the ledger). An unknown set on a `.ax` mention adds `.ax`.
510
+ const cb = (0, write_target_1.commandBases)(cmd, start, segments);
511
+ for (const b of cb.bases)
512
+ candidates.add(b);
513
+ if (cb.unknown !== null && (0, write_target_1.mentionsAxSpelling)(cmd)) {
514
+ candidates.add(path.join(start, '.ax'));
515
+ for (const c of write_target_1.AX_PROTECTED_CHILDREN)
516
+ candidates.add(path.join(start, '.ax', c));
517
+ }
518
+ // @implements A-SPEC-728 (rule 39) — a store key is only as deep as the command's longest `../` climb needs (a `cd` 1,000
519
+ // levels into `.ax/specs` made every rewritten word 2 KB longer: 3 s at 150 KB — measured).
520
+ let climb = 0;
521
+ for (const m of cmd.matchAll(/(?:\.\.[\\/])+/g))
522
+ climb = Math.max(climb, m[0].length / 3);
523
+ const keys = (0, write_target_1.axCandidateKeys)(root, candidates, climb + 1);
524
+ const forms = [];
525
+ // @implements A-SPEC-728 (rule 44) — every form is kept within one budget: past FORMS_MAX characters the command is too large
526
+ // to judge (after `cd .ax; cd "$X"`, `sed -i` over 131,000 words was rewritten at the store and each protected child, ~150 MB
527
+ // for the path rules: 2.8 s — measured). The hook refuses it as such.
528
+ let formed = 0;
529
+ const add = (form) => {
530
+ formed += form.length + 1;
531
+ if (formed > FORMS_MAX)
532
+ throw new RangeError('a command too large to judge at every directory it may run in');
533
+ forms.push(form);
534
+ };
535
+ // @implements A-SPEC-728 (round 24) — an unknown set on a command that never spells `.ax`: a path whose first component is a
536
+ // protected `.ax` child is judged under the store too (`cd "$(printf '.%s' ax)" && echo x > ledger/provenance.jsonl` was
537
+ // allowed — measured). Only those paths, so an ordinary relative write is not read as a store write.
538
+ const axChildren = cb.unknown !== null && !(0, write_target_1.mentionsAxSpelling)(cmd) ? path.join(root, '.ax') : null;
539
+ // Round 25: `./ledger/…` too. Round 28: after `=` and `(`, before `)`/`>`/`;`/`&`/`|`, with glob and brace characters
540
+ // (`cp a --target-directory=ledger`, `rm ledger/*` — measured).
541
+ const childRe = new RegExp(`(^|[\\s>|=(])(['"]?)(?:\\./)*((?:${write_target_1.AX_PROTECTED_CHILDREN.join('|')})(?:/[^\\s'"<>|;&()]*)?)(?=[\\s'"<>|;&()]|$)`, 'g');
542
+ // Round 26: only a segment that writes or removes (reads of an ordinary top-level `specs/` after a computed cd were
543
+ // denied — measured).
544
+ // Round 27: inverted — a segment skips this reading only when it is recognisably read-only and redirects nothing into a
545
+ // file; the round-26 list of write verbs let 28 of 46 store writes through (`perl -pi`, `sed --in-place`, `/bin/rm`,
546
+ // `git checkout HEAD~1 -- ./specs`, `>&` — measured), the enumeration A-SPEC-226 had rejected.
547
+ // @implements A-SPEC-728 (rule 33) — round 28, owner decision 2026-09-26: since REQ-739 a pass is the harness asking, so the
548
+ // reading applies to a segment RECOGNISED as writing (`writeKind`) and to every stage of a pipeline that feeds a
549
+ // shell or xargs; round 27's inversion refused 14 of 17 everyday commands (`npx playwright test specs/…`, `git add specs`,
550
+ // `ls specs 2>/dev/null`) and still let `sed -E -i.bak` and `echo rm ledger/x | sh` through (measured).
551
+ // @implements A-SPEC-728 (rule 34) — a segment recognised only by a redirect has only its redirect targets read
552
+ // (`terraform plan -state=state/x > plan.txt` was refused); every other segment that is not recognisably read-only is
553
+ // judged by the enumerated channels alone (round 29).
554
+ // Rule 35 (owner decision 2026-09-26): that channel net is removed — it refused `terraform state rm`, `docker run --rm …
555
+ // specs/` and `npx jest specs/rm.test.ts` (measured); an unrecognised wrapper or runner is a named residual.
556
+ const underStore = (text) => text.replace(childRe, (_f, pre, q, p) => `${pre}${q}${axChildren}/${p}`);
557
+ // @implements A-SPEC-728 (rule 39) — when the bases are unknown, for any reason, a literal cd may have gone unapplied; if one
558
+ // of them lands in the store (by identity: `axl -> .ax` counts) from the start or from any base, a segment recognised as
559
+ // writing is judged at the store and at each protected child too, glob-leading words included. Rule 38 read the whole
560
+ // store whenever the bases overflowed, which refused `(cd client && npm test) && … | tee test.log` (measured — a
561
+ // regression); rule 37 read it never, which let 64 no-op cds before `eval 'cd axl/specs/01_req'` carry `sed -i` into the
562
+ // store. Past 16,384 argument-base pairs the store is read without looking.
563
+ const rootAx = path.join(root, '.ax');
564
+ const storeBases = cb.unknown !== null && cdReachesStore(cb, start, rootAx) ? [rootAx, ...write_target_1.AX_PROTECTED_CHILDREN.map((c) => path.join(rootAx, c))] : [];
565
+ const fed = axChildren === null && storeBases.length === 0 ? new Set() : feedsAShell(segments);
566
+ for (const [i, s] of segments.entries()) {
567
+ if ((axChildren !== null || storeBases.length > 0) && !s.data) {
568
+ const kind = fed.has(i) ? 'command' : writeKind(s.text);
569
+ if (axChildren !== null && kind === 'command')
570
+ add(underStore(s.text));
571
+ else if (axChildren !== null && kind === 'redirect')
572
+ add(redirectTargetsUnder(s.text, axChildren));
573
+ if (kind !== null)
574
+ for (const b of storeBases)
575
+ add(rewrite(s.text, b, true));
576
+ }
577
+ if (s.data) {
578
+ add(s.text);
579
+ continue;
580
+ }
581
+ if (s.base === null) {
582
+ add(s.text);
583
+ if (s.maybe || keys.bases.length > 0) {
584
+ // @implements A-SPEC-728 (rule 44) — past 8 climb bases the command is too large to judge (60 rewrites of 256 KB — measured).
585
+ const climbs = (0, write_target_1.axClimbBases)(root, keys, s.text);
586
+ if (climbs.length > write_target_1.AX_CLIMB_BASES_MAX)
587
+ throw new RangeError(`a command too large to judge at every directory it may run in under .ax (more than ${write_target_1.AX_CLIMB_BASES_MAX} climbs)`);
588
+ for (const k of keys.bases)
589
+ add(rewrite(s.text, k));
590
+ for (const k of climbs)
591
+ add(rewrite(s.text, k, false, /^\.\.(?:[\\/]|$)/));
592
+ }
593
+ continue;
594
+ }
595
+ const dir = under(s.base);
596
+ add(dir === root ? s.text : rewrite(s.text, dir));
597
+ for (const k of keys.bases)
598
+ if (k !== dir)
599
+ add(rewrite(s.text, k));
600
+ }
601
+ return forms.join('\n');
602
+ }
603
+ /** @implements A-SPEC-728 (rule 39) — the largest text the leading-cd flattening builds before it refuses. */
604
+ const FLATTENED_MAX = 16 * 1024 * 1024;
605
+ /** @implements A-SPEC-728 (rule 44) — the largest text the per-segment flattening builds before it refuses. */
606
+ const FORMS_MAX = 32 * 1024 * 1024;
607
+ function normalizeCommandPaths(cmd, followCd = true) {
305
608
  let out = cmd.replace(/(?<![:\w])\.\//g, '').replace(/([^:])\/{2,}/g, '$1/');
609
+ if (!followCd)
610
+ return out;
306
611
  const cdChain = /(^|[;&|]\s*)cd\s+(['"]?)([^\s;&|'"]+)\2\s*(?:&&|;)\s*/;
307
612
  for (let m = cdChain.exec(out); m; m = cdChain.exec(out)) {
308
- const dir = m[3].replace(/\/+$/, '');
613
+ const dir = (0, linear_match_1.trimTrailing)(m[3], '/');
309
614
  const rest = out.slice(m.index + m[0].length);
310
- // Prefix bare relative paths in the remainder with the cd target so path rules see the real path.
311
- const rewritten = rest.replace(/(^|[\s>|])(?![-/~'"])([\w@.][\w@./-]*)/g, (full, pre, p) => /^[A-Za-z0-9_.@-]+$/.test(p) || p.includes('/') ? `${pre}${dir}/${p}` : full);
312
- out = out.slice(0, m.index + (m[1] ? m[1].length : 0)) + rewritten;
615
+ // Every word of the rest may take the cd's directory in front of it: past 16 MiB the command is too large to judge
616
+ // (a 2 KB directory and 75,000 words built 151 MB — measured); the hook's fail-closed catch denies it.
617
+ let words = 1;
618
+ for (let i = 0; i < rest.length; i++) {
619
+ const c = rest.charCodeAt(i);
620
+ if (c === 32 || c === 9 || c === 10 || c === 62 || c === 124)
621
+ words++;
622
+ }
623
+ if (out.length + words * (dir.length + 1) > FLATTENED_MAX)
624
+ throw new RangeError('a command too large to judge after its leading cd');
625
+ out = out.slice(0, m.index + (m[1] ? m[1].length : 0)) + prefixBareRelative(rest, dir);
313
626
  }
314
627
  return out;
315
628
  }
316
629
  // File-mutating shell verbs beyond redirect/removal: these WRITE a target path, so a protected path
317
630
  // as their argument is the same governance breach as `>` or `rm` (probe: tee/cp/install slipped).
318
- const WRITE_VERB_AX_RE = new RegExp(String.raw `\b(?:tee|cp|install|dd|ln|mv|rsync)\b[^;&|\n]*\.ax/(?:${PROTECTED_AX_ALT})\b`, 'i');
631
+ const WRITE_VERB_AX_RE = (0, linear_match_1.headThenTail)(/\b(?:tee|cp|install|dd|ln|mv|rsync)\b/i, SEG, new RegExp(String.raw `\.ax/(?:${PROTECTED_AX_ALT})\b`, 'i'));
319
632
  // An interpreter one-liner naming a protected path: `node -e "...appendFileSync('.ax/ledger/...')"`,
320
633
  // `python3 -c "open('.ax/ledger/...','a')"`. Read-only one-liners are not distinguishable from writes
321
634
  // here, so this is deliberately conservative on the .ax governance surface only.
322
- const INTERPRETER_AX_RE = new RegExp(String.raw `\b(?:node|python3?|ruby|perl|deno|bun)\b[^;&|\n]*-(?:e|c|-eval)\b[^\n]*\.ax/(?:${PROTECTED_AX_ALT})\b`, 'i');
635
+ const INTERPRETER_AX_RE = (0, linear_match_1.headMidTail)(/\b(?:node|python3?|ruby|perl|deno|bun)\b/i, /[;&|]/, /-(?:e|c|-eval)\b/i, /\n/, new RegExp(String.raw `\.ax/(?:${PROTECTED_AX_ALT})\b`, 'i'));
323
636
  /**
324
637
  * Commands that only read. Everything else over a governance path is a write.
325
638
  *
@@ -344,8 +657,33 @@ const READ_ONLY_GIT = new Set([
344
657
  'show', 'log', 'status', 'diff', 'ls-tree', 'ls-files', 'blame', 'cat-file', 'rev-parse',
345
658
  'merge-base', 'describe',
346
659
  ]);
347
- /** An in-place edit flag, including bundled forms: `-i`, `--in-place`, `-pi`, `-ipe`. */
348
- const IN_PLACE_FLAG_RE = /^--in-place\b|^-[A-Za-z]*i[A-Za-z]*$/;
660
+ /** Is `t` a spelling of the long option `--<full>` that getopt_long accepts (an unambiguous prefix of `min`+ letters)? */
661
+ function longOption(t, full, min) {
662
+ if (!t.startsWith('--'))
663
+ return false;
664
+ const name = t.slice(2).split('=')[0];
665
+ return name.length >= min && full.startsWith(name);
666
+ }
667
+ /**
668
+ * sed's in-place flag in every spelling.
669
+ *
670
+ * @implements A-SPEC-728 (rule 33) — a short cluster holding `i` or `I` before an option that takes a value (`-E -i.bak`,
671
+ * `-n -i~`, BSD `-I ''`), and any abbreviation of `--in-place`: each edited the file on macOS while read as a read, because
672
+ * the flag was matched only as letters without a suffix (measured).
673
+ */
674
+ function sedInPlaceFlag(t) {
675
+ if (longOption(t, 'in-place', 1))
676
+ return true;
677
+ if (!/^-[^-]/.test(t))
678
+ return false;
679
+ for (const ch of t.slice(1)) {
680
+ if (ch === 'i' || ch === 'I')
681
+ return true;
682
+ if (ch === 'e' || ch === 'f' || ch === 'l')
683
+ return false; // the rest is that option's value
684
+ }
685
+ return false;
686
+ }
349
687
  /**
350
688
  * Split a command into the clauses that run separately.
351
689
  *
@@ -375,16 +713,537 @@ function isReadOnlyShellClause(clause) {
375
713
  const tokens = clause.split(/\s+/).filter(Boolean);
376
714
  if (tokens.length === 0)
377
715
  return false;
716
+ // @implements A-SPEC-728 (rule 34) — leading assignments are the command's environment (`LC_ALL=C sort x` read as a write).
717
+ let assigned = 0;
718
+ while (assigned < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[assigned]))
719
+ assigned++;
720
+ if (assigned > 0)
721
+ return assigned < tokens.length && isReadOnlyShellClause(tokens.slice(assigned).join(' '));
378
722
  const name = tokens[0].replace(/^.*\//, ''); // /usr/bin/grep -> grep
379
- if (name === 'git')
380
- return tokens.length > 1 && READ_ONLY_GIT.has(tokens[1]);
381
- if (name === 'sed' || name === 'perl') {
382
- return !tokens.slice(1).some((t) => IN_PLACE_FLAG_RE.test(t));
723
+ // @implements A-SPEC-737 — each of these read commands has a form that writes a named file, and
724
+ // the gate allowed all of them onto .ax/specs (measured through the built hook).
725
+ const rest = tokens.slice(1);
726
+ // @implements A-SPEC-728 (round 18) — `env [options] cmd` is as read-only as `cmd`: with the wrapper's
727
+ // chdir now moving the base, `env -C .ax cat ledger/x` reached this rule as "not recognisably read-only".
728
+ if (name === 'env') {
729
+ // Rule 34: a run of `env` words is walked, not recursed (10,000 of them exhausted the worker's heap — measured).
730
+ let k = 0;
731
+ while (k < tokens.length && tokens[k].replace(/^.*\//, '') === 'env') {
732
+ k++;
733
+ while (k < tokens.length) {
734
+ const t = tokens[k];
735
+ if (/^[A-Za-z_]\w*=/.test(t)) {
736
+ k++;
737
+ continue;
738
+ }
739
+ if (t === '--') {
740
+ k++;
741
+ break;
742
+ }
743
+ if (!t.startsWith('-'))
744
+ break;
745
+ k++;
746
+ if (/^(?:-u|-C|-S|--unset|--chdir|--split-string)$/.test(t))
747
+ k++;
748
+ }
749
+ }
750
+ return k < tokens.length && isReadOnlyShellClause(tokens.slice(k).join(' '));
751
+ }
752
+ if (name === 'git') {
753
+ return tokens.length > 1 && READ_ONLY_GIT.has(tokens[1]) && !rest.some((t) => t.startsWith('--output'));
383
754
  }
755
+ // @implements A-SPEC-737 (round 2) — sed `w`/`s///w`, awk `> FILENAME`/`-i inplace`, perl open(),
756
+ // rg --pre and `sort -o<path>` all wrote into .ax/specs while allowed as reads. A programmable
757
+ // reader is a read only in a recognisable read form, judged on quote-aware words.
758
+ if (name === 'perl')
759
+ return false;
760
+ if (name === 'sed')
761
+ return sedIsRead(clauseWords(clause).slice(1));
762
+ if (name === 'awk')
763
+ return awkIsRead(clause, clauseWords(clause).slice(1));
764
+ if (name === 'rg')
765
+ return !rest.some((t) => t.startsWith('--pre'));
766
+ if (name === 'find')
767
+ return !rest.some((t) => FIND_ACTS.has(t));
768
+ if (name === 'sort') {
769
+ // Rule 33: getopt_long abbreviations (`--o=`, `--outp=` wrote the file on macOS — measured).
770
+ return !rest.some((t) => longOption(t, 'output', 1) || longOption(t, 'compress-program', 2) || SORT_OUTPUT_FLAG_RE.test(t));
771
+ }
772
+ if (name === 'uniq')
773
+ return rest.filter((t) => !t.startsWith('-')).length < 2;
384
774
  return READ_ONLY_SHELL.has(name);
385
775
  }
776
+ /** `find` primaries that write, delete or run something. */
777
+ const FIND_ACTS = new Set(['-delete', '-exec', '-execdir', '-ok', '-okdir', '-fprint', '-fprint0', '-fprintf', '-fls']);
778
+ /** Commands that write or remove a path they are given, by name. */
779
+ const WRITE_COMMANDS = new Set([
780
+ 'rm', 'rmdir', 'unlink', 'mv', 'cp', 'tee', 'truncate', 'touch', 'dd', 'install', 'ln', 'link', 'rsync', 'shred', 'chmod',
781
+ 'chown', 'chgrp', 'chflags', 'mkdir', 'mkfifo', 'mknod', 'patch', 'tar', 'unzip', 'gzip', 'gunzip', 'bzip2', 'bunzip2', 'xz',
782
+ 'unxz', 'zstd', 'zip', '7z', '7za', 'cpio', 'curl', 'wget', 'ditto', 'sponge', 'ed', 'ex', 'vi', 'vim', 'nvim', 'nano', 'emacs',
783
+ 'trash', 'trash-put', 'srm', 'rimraf', 'rename', 'prename', 'setfattr', 'xattr', 'split', 'csplit',
784
+ // Rule 34: GNU-prefixed tools (Homebrew coreutils), and more writers by name.
785
+ 'grm', 'grmdir', 'gunlink', 'gmv', 'gcp', 'gtee', 'gtruncate', 'gtouch', 'gdd', 'ginstall', 'gln', 'gshred', 'gchmod', 'gchown',
786
+ 'gmkdir', 'scp', 'bsdtar', 'gtar', 'mktemp',
787
+ ]);
788
+ /** Programmable readers: a write only in a form the store rule does not read as read-only. */
789
+ const READER_FORMS = new Set(['sed', 'gsed', 'awk', 'gawk', 'mawk', 'nawk', 'sort', 'uniq', 'rg', 'find']);
790
+ /** `git` sub-commands that write the working tree. */
791
+ const GIT_WRITES = new Set([
792
+ 'checkout', 'restore', 'reset', 'rm', 'mv', 'stash', 'clean', 'apply', 'am', 'merge', 'pull', 'rebase', 'cherry-pick', 'revert',
793
+ 'switch', 'worktree', 'submodule', 'clone', 'init', 'archive', 'format-patch', 'bundle', 'read-tree', 'checkout-index',
794
+ 'sparse-checkout', 'filter-branch', 'filter-repo', 'mergetool', 'merge-file',
795
+ ]);
796
+ const SHELL_NAMES = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'fish']);
797
+ /** Programs that read the program they run from their input. */
798
+ const STDIN_RUNNERS = new Set([...SHELL_NAMES, 'eval', 'source', '.']);
799
+ /** Words a command hides behind, and which of their options take a value. */
800
+ const PROGRAM_WRAPPERS = new Set(['env', 'command', 'builtin', 'exec', 'nohup', 'time', 'nice', 'sudo', 'doas', 'stdbuf', 'timeout',
801
+ 'busybox', 'xargs', 'parallel', '!', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', 'coproc',
802
+ // Rule 34: zsh precommands, and wrappers that run the command after them.
803
+ 'noglob', 'nocorrect', '-', 'ionice', 'caffeinate', 'setsid', 'chronic', 'unbuffer', 'arch', 'flock', 'watch', 'strace', 'npx', 'bunx', 'pnpx']);
804
+ const WRAPPER_VALUED = {
805
+ env: /^(?:-u|-C|--unset|--chdir)$/, doas: /^-[uC]$/, nice: /^-n$|^--adjustment$/,
806
+ sudo: /^-[ugCDhprtUT]$|^--(?:user|group|chdir|host|prompt|role|type|other-user|close-from|command-timeout)$/,
807
+ timeout: /^-[sk]$|^--(?:signal|kill-after)$/, stdbuf: /^-[ioe]$/, exec: /^-a$/, ionice: /^-[cnp]$|^--(?:class|classdata|pid)$/,
808
+ xargs: /^-[IaEdLlnPs]$|^--(?:arg-file|delimiter|eof|max-args|max-procs|max-chars|replace|max-lines)$/,
809
+ flock: /^-[wE]$|^--(?:timeout|conflict-exit-code)$/, watch: /^-n$|^--interval$/, strace: /^-[oeEpPsSuUIba]$/, npx: /^-p$|^--package$/,
810
+ };
811
+ /** A redirect word: an operator, with or without its target attached (`2>/dev/null`, `>`, `2>&1`, `<`). */
812
+ const REDIRECT_WORD = /^(?:[0-9]*|&)(?:>>?|<<<?|<>|>&|<&)[|!]?/;
813
+ /**
814
+ * A redirect into a file: not `/dev/null`, the standard streams, the terminal, `/dev/fd/N`, `>&N` or `>&-`.
815
+ * Rule 34: `>>` and `>|` into `/dev/null` are not writes (the `>{1,2}` backtracked and read the second `>` as a target).
816
+ */
817
+ const REDIRECT_INTO_FILE = /(?:^|[^<>])>{1,2}(?!>)[|!]?[ \t]*(?![|!])(?!&[ \t]*(?:[0-9]+|-)(?![^\s;&|)])|\/dev\/(?:null|stdout|stderr|tty|fd\/[0-9]+)(?![^\s;&|)]))\S|<>/;
818
+ const commandName = (w) => w.replace(/^\\/, '').replace(/^.*\//, '').replace(/\.exe$/i, '').toLowerCase();
819
+ /** Words re-quoted for a reader that splits them again (`clauseWords`). */
820
+ const quoteWords = (ws) => ws.map((w) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(w) ? w : `'${w.replace(/'/g, "'\\''")}'`)).join(' ');
821
+ /**
822
+ * The program a clause's words run, behind assignments, redirects and wrappers, with its arguments.
823
+ *
824
+ * @implements A-SPEC-728 (rule 34) — leading redirects (`2>/dev/null rm …` read the program as `null`), zsh precommands, a
825
+ * `case` arm's pattern, sudo's long valued options, `exec -a`, `env -S` (the command it holds) and `pnpm`/`yarn dlx|exec`;
826
+ * there is no word cap (a 64-word cap returned the 65th wrapper as the program — measured).
827
+ */
828
+ function programOf(input) {
829
+ let words = [...input];
830
+ let i = 0;
831
+ let splits = 0;
832
+ for (let n = 0; i < words.length; n++) {
833
+ if (n > 100_000)
834
+ return { name: '', args: [], word: '', unknown: true };
835
+ const w = words[i];
836
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) {
837
+ i++;
838
+ continue;
839
+ }
840
+ const redirect = REDIRECT_WORD.exec(w);
841
+ if (redirect !== null) {
842
+ i += redirect[0].length === w.length ? 2 : 1;
843
+ continue;
844
+ }
845
+ if (w === 'case') {
846
+ let k = i + 1;
847
+ while (k < words.length && !/\)$/.test(words[k]))
848
+ k++;
849
+ i = k + 1;
850
+ continue;
851
+ }
852
+ if (/^[^$`(]+\)$/.test(w)) {
853
+ i++;
854
+ continue;
855
+ } // a case arm's pattern
856
+ const base = commandName(w);
857
+ // Rule 35: `npm exec` too, and the runner's own options.
858
+ if ((base === 'pnpm' || base === 'yarn' || base === 'npm') && (words[i + 1] === 'dlx' || words[i + 1] === 'exec')) {
859
+ i += 2;
860
+ while (i < words.length && words[i].startsWith('-')) {
861
+ const o = words[i++];
862
+ if (o === '--')
863
+ break;
864
+ if (/^(?:-p|--package|-w|--workspace)$/.test(o))
865
+ i++;
866
+ }
867
+ continue;
868
+ }
869
+ if (!PROGRAM_WRAPPERS.has(base))
870
+ break;
871
+ i++;
872
+ const valued = WRAPPER_VALUED[base];
873
+ let split = null;
874
+ while (i < words.length && words[i].startsWith('-') && words[i] !== '-') {
875
+ const o = words[i++];
876
+ if (o === '--')
877
+ break;
878
+ if (base === 'env' && (o === '-S' || o === '--split-string' || /^-S./.test(o) || o.startsWith('--split-string='))) {
879
+ split = o === '-S' || o === '--split-string' ? words[i++] ?? '' : o.startsWith('-S') ? o.slice(2) : o.slice(o.indexOf('=') + 1);
880
+ break;
881
+ }
882
+ if (valued?.test(o) && i < words.length)
883
+ i++;
884
+ }
885
+ // Rule 35: at most 64 re-splits (nested `env -S` copied the rest each time: 17.7 s at 300 KB — measured); past them the
886
+ // program is unknown, read as a write.
887
+ if (split !== null) {
888
+ if (++splits > 64)
889
+ return { name: '', args: [], word: '', unknown: true };
890
+ words = [...clauseWords(split), ...words.slice(i)];
891
+ i = 0;
892
+ continue;
893
+ }
894
+ if (base === 'timeout' && i < words.length && /^[0-9.]+[smhd]?$/.test(words[i]))
895
+ i++;
896
+ if (base === 'nice' && i < words.length && /^-?[0-9]+$/.test(words[i]))
897
+ i++;
898
+ if (base === 'flock' && i < words.length)
899
+ i++; // the lock file
900
+ }
901
+ return i < words.length ? { name: commandName(words[i]), args: words.slice(i + 1), word: words[i] } : null;
902
+ }
903
+ /** Each interpreter's one-liner flags, and the letters that take a value (the rest of the cluster is that value). */
904
+ /** Rule 35: node's long options that take a separate value (`node --import tsx -e "…"` read `tsx` as the script — measured). */
905
+ const NODE_VALUED_LONG = /^--(?:import|require|loader|experimental-loader|env-file|conditions|input-type|title|inspect-port|redirect-warnings|report-directory|diagnostic-dir|heapsnapshot-signal|stack-trace-limit|openssl-config|icu-data-dir|watch-path|disable-warning)$/;
906
+ const ONE_LINERS = [
907
+ { name: /^python[0-9.]*$/, flags: 'c', valued: 'WXmQ', longValued: /^--check-hash-based-pycs$/ },
908
+ { name: /^(?:node|nodejs|tsx)$/, flags: 'ep', valued: 'rC', long: /^--(?:eval|print)(?:=|$)/, longValued: NODE_VALUED_LONG },
909
+ { name: /^ts-node(?:-esm)?$/, flags: 'ep', valued: 'rCPO', long: /^--(?:eval|print)(?:=|$)/, longValued: /^--(?:require|project|compiler|compiler-options|cwd|dir|scope-dir)$/ },
910
+ { name: /^(?:deno|bun)$/, flags: 'e', valued: '', long: /^--(?:eval|print)(?:=|$)/ },
911
+ { name: /^ruby$/, flags: 'ei', valued: 'IrCEFKxW0T' },
912
+ { name: /^perl$/, flags: 'eEi', valued: 'IMmxl0CdDV' },
913
+ { name: /^php$/, flags: 'r', valued: 'cdfz' },
914
+ { name: /^pwsh$/, flags: 'c', valued: '', long: /^-(?:command|encodedcommand|ec)$/i },
915
+ { name: /^osascript$/, flags: 'e', valued: '' },
916
+ ];
917
+ /** Rule 34: an interpreter's own one-liner or in-place flag, among the options before its first operand. */
918
+ function runsOneLiner(name, args) {
919
+ const spec = ONE_LINERS.find((o) => o.name.test(name));
920
+ if (spec === undefined)
921
+ return false;
922
+ if ((name === 'deno' || name === 'bun') && args[0] === 'eval')
923
+ return true;
924
+ for (let k = 0; k < args.length; k++) {
925
+ const a = args[k];
926
+ if (spec.long?.test(a))
927
+ return true;
928
+ if (a === '--' || !a.startsWith('-') || a === '-')
929
+ return false;
930
+ if (a.startsWith('--')) {
931
+ if (spec.longValued?.test(a))
932
+ k++;
933
+ continue;
934
+ }
935
+ for (let c = 1; c < a.length; c++) {
936
+ if (spec.flags.includes(a[c]))
937
+ return true;
938
+ if (spec.valued.includes(a[c])) {
939
+ if (c === a.length - 1)
940
+ k++;
941
+ break;
942
+ }
943
+ }
944
+ }
945
+ return false;
946
+ }
947
+ /**
948
+ * The text with quoted content blanked in place (quotes kept, length kept), so a `>` inside a string is not a redirect.
949
+ * Rule 34: ANSI-C `$'…'` is read with its escapes (`$'it\'s'` hid a following `>`).
950
+ */
951
+ function maskQuoted(t) {
952
+ let out = '', quote = '';
953
+ for (let i = 0; i < t.length; i++) {
954
+ const ch = t[i];
955
+ if (quote === 'ansi') {
956
+ if (ch === '\\' && i + 1 < t.length) {
957
+ out += ' ';
958
+ i++;
959
+ continue;
960
+ }
961
+ if (ch === "'") {
962
+ quote = '';
963
+ out += ch;
964
+ }
965
+ else
966
+ out += ' ';
967
+ continue;
968
+ }
969
+ if (quote !== '') {
970
+ if (ch === quote) {
971
+ quote = '';
972
+ out += ch;
973
+ }
974
+ else if (ch === '\\' && quote === '"' && i + 1 < t.length) {
975
+ out += ' ';
976
+ i++;
977
+ }
978
+ else
979
+ out += ' ';
980
+ continue;
981
+ }
982
+ if (ch === '\\' && i + 1 < t.length) {
983
+ out += 'xx';
984
+ i++;
985
+ continue;
986
+ }
987
+ if (ch === '$' && t[i + 1] === "'") {
988
+ quote = 'ansi';
989
+ out += "$'";
990
+ i++;
991
+ continue;
992
+ }
993
+ if (ch === "'" || ch === '"')
994
+ quote = ch;
995
+ out += ch;
996
+ }
997
+ return out;
998
+ }
999
+ /** Rule 36: each shell's options that take a separate value (their value is not the script operand). */
1000
+ const SHELL_VALUED = {
1001
+ default: /^(?:[-+][oO]|--rcfile|--init-file)$/,
1002
+ zsh: /^(?:[-+][oO]|--emulate)$/,
1003
+ mksh: /^(?:[-+][oO]|-T)$/,
1004
+ fish: /^(?:-[dfpDo]|--(?:debug|features|profile|profile-startup|debug-stack-frames|debug-output))$/,
1005
+ };
1006
+ /** Does the program write, by what it is? */
1007
+ function programWrites(prog, text) {
1008
+ const { name, args, word } = prog;
1009
+ if (prog.unknown)
1010
+ return true;
1011
+ if (/[$`]/.test(word))
1012
+ return true; // Rule 34: an expanded command word (`$RM`) may be any program
1013
+ if (WRITE_COMMANDS.has(name))
1014
+ return true;
1015
+ if (READER_FORMS.has(name))
1016
+ return !isReadOnlyShellClause(quoteWords([name, ...args]));
1017
+ if (name === 'git') {
1018
+ let k = 0;
1019
+ while (k < args.length && args[k].startsWith('-'))
1020
+ k += /^(?:-C|-c|--git-dir|--work-tree|--namespace|--exec-path)$/.test(args[k]) ? 2 : 1;
1021
+ const sub = args[k] ?? '';
1022
+ return GIT_WRITES.has(sub) || (READ_ONLY_GIT.has(sub) && args.slice(k + 1).some((a) => a.startsWith('--output') || a === '-o'));
1023
+ }
1024
+ if (name === 'yq' || name === 'jq')
1025
+ return args.some((a) => /^-[A-Za-z]*i/.test(a) || a.startsWith('--inplace'));
1026
+ // Rule 34: a shell that runs a program — a `c` cluster, a here-string, a process substitution — and `eval` with words.
1027
+ if (SHELL_NAMES.has(name) || name === 'su') {
1028
+ // Rule 35: among the options before the script operand (`sh ./run.sh -c specs/x` was read as a program — measured).
1029
+ // Rule 36: every argument of `su` (its user comes first); each shell's valued options; fish's `-C` runs a program.
1030
+ const valued = SHELL_VALUED[name] ?? SHELL_VALUED.default;
1031
+ for (let k = 0; k < args.length; k++) {
1032
+ const a = args[k];
1033
+ if (/^-(?=[A-Za-z]*c)[A-Za-z]+$/.test(a) || /^--command(?:=|$)/.test(a) || a.startsWith('<('))
1034
+ return true;
1035
+ if (name === 'fish' && /^(?:-C|--init-command)(?:=|$)/.test(a))
1036
+ return true;
1037
+ if (name === 'su') {
1038
+ if (/^(?:-[sgGw]|--(?:shell|group|supp-group|whitelist-environment))$/.test(a))
1039
+ k++;
1040
+ continue;
1041
+ }
1042
+ if (a === '--' || !/^[-+]/.test(a))
1043
+ break;
1044
+ if (valued.test(a))
1045
+ k++;
1046
+ }
1047
+ return /<<</.test(text);
1048
+ }
1049
+ if (name === 'eval')
1050
+ return args.length > 0;
1051
+ if (name === 'source' || name === '.')
1052
+ return args.some((a) => a === '/dev/stdin' || a.startsWith('<(')) || /<<</.test(text);
1053
+ return runsOneLiner(name, args);
1054
+ }
1055
+ /**
1056
+ * How a segment is recognised as writing: by what it runs (`command`), only by a redirect into a file (`redirect`), or not.
1057
+ *
1058
+ * @implements A-SPEC-728 (rules 33–34) — what it does not recognise passes: since REQ-739 the harness asks about it (owner
1059
+ * decision 2026-09-26). A segment recognised only by a redirect has only its redirect targets read under the store.
1060
+ */
1061
+ function writeKind(t) {
1062
+ const text = t.trim().replace(/^[\s({!]+/, '');
1063
+ const prog = programOf(clauseWords(text));
1064
+ if (prog !== null && programWrites(prog, text))
1065
+ return 'command';
1066
+ return REDIRECT_INTO_FILE.test(maskQuoted(t)) ? 'redirect' : null;
1067
+ }
1068
+ /**
1069
+ * The segments of every pipeline that feeds a shell, `eval` or `source`, or an xargs/parallel that runs a shell or a writer —
1070
+ * each stage's text may be what runs.
1071
+ *
1072
+ * @implements A-SPEC-728 (rules 33–34) — `echo rm ledger/provenance.jsonl | sh` passed as a read of `echo`; rule 34: xargs
1073
+ * passes arguments, not programs (`find specs | xargs grep foo` and 17 more read pipelines were refused — measured).
1074
+ */
1075
+ function feedsAShell(segments) {
1076
+ const out = new Set();
1077
+ let group = [];
1078
+ let feeds = false;
1079
+ for (const [i, s] of segments.entries()) {
1080
+ if (s.nested)
1081
+ continue; // a program string's own segments sit between its parent's stages
1082
+ if (group.length > 0 && !s.data) {
1083
+ const text = s.text.trim().replace(/^[\s({!]+/, '');
1084
+ const words = clauseWords(text);
1085
+ const first = words.length > 0 ? commandName(words[0]) : '';
1086
+ const prog = programOf(words);
1087
+ if (prog !== null && (STDIN_RUNNERS.has(prog.name) || prog.name === 'su'))
1088
+ feeds = true;
1089
+ else if ((first === 'xargs' || first === 'parallel') && prog !== null && programWrites(prog, text))
1090
+ feeds = true;
1091
+ }
1092
+ group.push(i);
1093
+ if (s.sep === '|' || s.sep === '|&')
1094
+ continue;
1095
+ if (feeds)
1096
+ for (const k of group)
1097
+ out.add(k);
1098
+ group = [];
1099
+ feeds = false;
1100
+ }
1101
+ if (feeds)
1102
+ for (const k of group)
1103
+ out.add(k);
1104
+ return out;
1105
+ }
1106
+ /** `sort -o FILE`, including bundled short flags and an attached value: `-uo`, `-o`, `-oFILE`. */
1107
+ const SORT_OUTPUT_FLAG_RE = /^-[A-Za-z]*o/;
1108
+ /** Words of one clause with shell quotes removed (single, double, backslash). Nothing is expanded. */
1109
+ function clauseWords(clause) {
1110
+ const out = [];
1111
+ let cur = '', inWord = false, quote = '';
1112
+ for (let i = 0; i < clause.length; i++) {
1113
+ const ch = clause[i];
1114
+ if (quote === "'") {
1115
+ if (ch === "'")
1116
+ quote = '';
1117
+ else
1118
+ cur += ch;
1119
+ continue;
1120
+ }
1121
+ if (quote === '"') {
1122
+ if (ch === '"')
1123
+ quote = '';
1124
+ else if (ch === '\\' && i + 1 < clause.length)
1125
+ cur += clause[++i];
1126
+ else
1127
+ cur += ch;
1128
+ continue;
1129
+ }
1130
+ if (/\s/.test(ch)) {
1131
+ if (inWord) {
1132
+ out.push(cur);
1133
+ cur = '';
1134
+ inWord = false;
1135
+ }
1136
+ continue;
1137
+ }
1138
+ inWord = true;
1139
+ if (ch === "'" || ch === '"')
1140
+ quote = ch;
1141
+ else if (ch === '\\' && i + 1 < clause.length)
1142
+ cur += clause[++i];
1143
+ else
1144
+ cur += ch;
1145
+ }
1146
+ if (inWord)
1147
+ out.push(cur);
1148
+ return out;
1149
+ }
1150
+ const SED_ADDR = String.raw `(?:\d+(?:~\d+)?|\$|/(?:[^/\\]|\\.)*/[IM]?)`;
1151
+ const SED_RANGE = `(?:${SED_ADDR}(?:,(?:${SED_ADDR}|[+~]\\d+))?)?\\s*!?\\s*`;
1152
+ /** One sed command that only prints: an address or range, then p/d/q/=/l/n/N/P/D or nothing. */
1153
+ const SED_PRINT_RE = new RegExp(`^${SED_RANGE}[pdq=lnNPD]?$`);
1154
+ /** `s` or `y` whose flags cannot write or execute (no w, W, e). */
1155
+ const SED_SUBST_RE = new RegExp(String.raw `^${SED_RANGE}(?:s(.)(?:(?!\1)[^\\]|\\.)*\1(?:(?!\1)[^\\]|\\.)*\1[gpiImM0-9]*|y(.)(?:(?!\2)[^\\]|\\.)*\2(?:(?!\2)[^\\]|\\.)*\2)$`);
1156
+ function sedIsRead(args) {
1157
+ const scripts = [];
1158
+ let operandSeen = false;
1159
+ for (let i = 0; i < args.length; i++) {
1160
+ const t = args[i];
1161
+ if (sedInPlaceFlag(t) || t === '-f' || longOption(t, 'file', 2) || /^-[A-Za-z]*f/.test(t))
1162
+ return false;
1163
+ if (t === '-e' || (longOption(t, 'expression', 1) && !t.includes('='))) {
1164
+ if (i + 1 >= args.length)
1165
+ return false;
1166
+ scripts.push(args[++i]);
1167
+ continue;
1168
+ }
1169
+ if (longOption(t, 'expression', 1)) {
1170
+ scripts.push(t.slice(t.indexOf('=') + 1));
1171
+ continue;
1172
+ }
1173
+ if (t.startsWith('-') && t !== '-')
1174
+ continue;
1175
+ if (scripts.length === 0 && !operandSeen) {
1176
+ scripts.push(t);
1177
+ operandSeen = true;
1178
+ }
1179
+ }
1180
+ return scripts.every((sc) => sc.length <= 4096 && (SED_PRINT_RE.test(sc.trim()) || SED_SUBST_RE.test(sc.trim())));
1181
+ }
1182
+ const AWK_OPTION_RE = /^(?:-[ifl]|-E|--include|--file|--load|--exec)/;
1183
+ const AWK_CALL_RE = /\bsystem\s*\(|\bgetline\b|\binplace\b/;
1184
+ /**
1185
+ * `print`/`printf` followed by `>` before the statement ends. A single left-to-right pass: the regex
1186
+ * form `\bprintf?\b[^;}]*>` restarted its scan at every `print` (quadratic, and the hook's timeout
1187
+ * fails open — A-SPEC-728's lesson).
1188
+ */
1189
+ function awkPrintRedirects(text) {
1190
+ let armed = false;
1191
+ for (let i = 0; i < text.length; i++) {
1192
+ const ch = text[i];
1193
+ if (ch === ';' || ch === '}') {
1194
+ armed = false;
1195
+ continue;
1196
+ }
1197
+ if (ch === '>' && armed)
1198
+ return true;
1199
+ if (ch === 'p' && text.startsWith('print', i) && !/\w/.test(text[i - 1] ?? '')) {
1200
+ const end = text[i + 5] === 'f' ? i + 6 : i + 5;
1201
+ if (!/\w/.test(text[end] ?? ''))
1202
+ armed = true;
1203
+ }
1204
+ }
1205
+ return false;
1206
+ }
1207
+ function awkIsRead(clause, args) {
1208
+ return !args.some((t) => AWK_OPTION_RE.test(t)) && !AWK_CALL_RE.test(clause) && !awkPrintRedirects(clause);
1209
+ }
1210
+ /**
1211
+ * @implements A-SPEC-737 — `for f in .ax/specs/*.md; do cat "$f"; done` reads, but the splitter hands
1212
+ * over `for …`, `do cat …` and `done`, none of them a known read. A loop is a read when its word list
1213
+ * runs nothing, every body clause is a read, and no body clause substitutes a command or redirects
1214
+ * output anywhere but /dev/null or a descriptor: the loop variable can carry a .ax path the gate
1215
+ * cannot see.
1216
+ */
1217
+ const FOR_HEAD_RE = /^for\s+[A-Za-z_][A-Za-z0-9_]*\s+in\b/;
1218
+ const SUBSTITUTION_RE = /\$\(|`|<\(|>\(/;
1219
+ const OUTPUT_REDIRECT_RE = />(?!\s*(?:\/dev\/null\b|&\d))/;
1220
+ function clausesAreReads(clauses, isRead) {
1221
+ let inLoop = false;
1222
+ for (const raw of clauses) {
1223
+ let c = raw;
1224
+ if (FOR_HEAD_RE.test(c)) {
1225
+ if (inLoop || SUBSTITUTION_RE.test(c))
1226
+ return false;
1227
+ inLoop = true;
1228
+ continue;
1229
+ }
1230
+ if (inLoop && /^done$/.test(c)) {
1231
+ inLoop = false;
1232
+ continue;
1233
+ }
1234
+ if (inLoop && c === 'do')
1235
+ continue; // the newline form: `do` on its own line
1236
+ if (inLoop && /^do\s/.test(c))
1237
+ c = c.slice(2).trim();
1238
+ if (inLoop && (SUBSTITUTION_RE.test(c) || OUTPUT_REDIRECT_RE.test(c)))
1239
+ return false;
1240
+ if (!isRead(c))
1241
+ return false;
1242
+ }
1243
+ return !inLoop;
1244
+ }
386
1245
  /** Append-only evidence: restoring it deletes records rather than undoing an edit. */
387
- const LEDGER_PATH_RE = /(^|[\s'"=(/])\.ax\/ledger(\/|\b)/;
1246
+ const LEDGER_PATH_RE = /(^|[\s'"=(/])\.ax\/ledger(\/|\b)/i;
388
1247
  /**
389
1248
  * A restore that moves the working tree TOWARD the committed state.
390
1249
  *
@@ -429,14 +1288,28 @@ function shellWritesProtectedAx(ncmd) {
429
1288
  // @implements A-SPEC-227 — the ledger exemption is cancelled here, not inside the restore check,
430
1289
  // because it is a property of the TARGET rather than of the command shape.
431
1290
  const restoreAllowed = !LEDGER_PATH_RE.test(ncmd);
432
- return !splitShellClauses(ncmd).every((c) => isReadOnlyShellClause(c) || (restoreAllowed && isIndexRestoreClause(c)));
1291
+ return !clausesAreReads(splitShellClauses(ncmd), (c) => isReadOnlyShellClause(c) || (restoreAllowed && isIndexRestoreClause(c)));
433
1292
  }
434
1293
  /**
435
1294
  * @implements A-SPEC-125.1
436
1295
  * Reversibility axis: can the action's effect be undone? Conservative default —
437
1296
  * unknown kinds and ambiguous (tracked===undefined) states never resolve to 'auto'.
438
1297
  */
1298
+ /**
1299
+ * @implements A-SPEC-728 (round 24) — the command is judged as written AND as the shell joins it (quote removal of plain
1300
+ * words, an `eval`/`-c` program's escaped words): `r''m -rf /usr/local`, `r\m -rf .git`, `g''it reset --hard` were allowed
1301
+ * while their plain forms were denied (measured). The stricter verdict stands.
1302
+ */
439
1303
  function classifyReversibility(action) {
1304
+ const raw = action.command ?? '';
1305
+ const joined = raw === '' ? raw : (0, write_target_1.joinShellText)(raw);
1306
+ if (joined === raw)
1307
+ return classifyReversibilityAsWritten(action);
1308
+ const a = classifyReversibilityAsWritten(action);
1309
+ const b = classifyReversibilityAsWritten({ ...action, command: joined });
1310
+ return (0, risk_types_1.maxLevel)(a.level, b.level) === a.level ? a : b;
1311
+ }
1312
+ function classifyReversibilityAsWritten(action) {
440
1313
  const axis = 'reversibility';
441
1314
  const cmd = action.command ?? '';
442
1315
  // Command-based hard-hitl checks run regardless of `kind` — a dangerous shell command
@@ -454,11 +1327,25 @@ function classifyReversibility(action) {
454
1327
  // Protected-path checks run on the NORMALIZED command so `//`, `./`, and `cd <dir> &&` forms cannot
455
1328
  // dodge the rules, and cover every mutation channel: removal verbs, redirect clobber, file-writing
456
1329
  // verbs (tee/cp/install/…), and interpreter one-liners naming a governance path.
457
- const ncmd = scopeAxToProject(normalizeCommandPaths(cmd), action.projectRoot);
458
- if ((REMOVAL_VERB_RE.test(ncmd) && CMD_PROTECTED_AX_RE.test(ncmd)) || CLOBBER_AX_RE.test(ncmd)
459
- || WRITE_VERB_AX_RE.test(ncmd) || INTERPRETER_AX_RE.test(ncmd)) {
460
- return { axis, level: 'hard-hitl', reasons: ['removal command targets a protected .ax governance path'] };
461
- }
1330
+ // @implements A-SPEC-728 (round 9) — the cd-flattened text AND the text as written: flattening
1331
+ // followed a cd the shell never ran (`cd /nonexistent && true; echo x > .ax/ledger/p.jsonl` became an
1332
+ // other-project path and was allowed — measured). Judging both only ever adds refusals.
1333
+ const flat = scopeAxToProject(normalizeCommandPaths(cmd), action.projectRoot);
1334
+ const asWritten = scopeAxToProject(normalizeCommandPaths(cmd, false), action.projectRoot);
1335
+ // Round 10: and with every segment at the base the certain-cd model gives it (a second cd into .ax).
1336
+ const bySegment = action.projectRoot ? scopeAxToProject(normalizeCommandPaths(segmentFlattened(cmd, action.projectRoot, action.cwd ?? action.projectRoot), false), action.projectRoot) : asWritten;
1337
+ const ncmd = [...new Set([flat, asWritten, bySegment])].join('\n');
1338
+ // @implements A-SPEC-737 — one reason served all four channels, so an interpreter READ was refused as
1339
+ // a "removal command" and the author could not tell what to change. Each channel names itself.
1340
+ const axChannel = REMOVAL_VERB_RE.test(ncmd) && CMD_PROTECTED_AX_RE.test(ncmd)
1341
+ ? 'removal, move or copy command targets a protected .ax governance path'
1342
+ : CLOBBER_AX_RE.test(ncmd) ? 'output redirection writes into a protected .ax governance path'
1343
+ : WRITE_VERB_AX_RE.test(ncmd) ? 'file-writing command (tee/cp/install/dd/ln/mv/rsync) targets a protected .ax governance path'
1344
+ : INTERPRETER_AX_RE.test(ncmd)
1345
+ ? 'interpreter one-liner names a protected .ax governance path — a read cannot be told from a write here; read with cat, head, grep or sed -n instead'
1346
+ : undefined;
1347
+ if (axChannel)
1348
+ return { axis, level: 'hard-hitl', reasons: [axChannel] };
462
1349
  // @implements A-SPEC-226 — the four enumerations above are kept, not replaced. Keeping them makes
463
1350
  // this addition purely monotonic: what was blocked stays blocked, and only previously-missed
464
1351
  // shapes become blocked. Replacing them would make it impossible to tell in one step whether this