@holmes-lab/holmes-kit 0.41.1 → 0.41.3

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 (105) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +29 -5
  3. package/bin/holmes-mcp.js +36 -1
  4. package/dist/.build-id +1 -1
  5. package/dist/holmes/cli/claude-switches.d.ts +9 -0
  6. package/dist/holmes/cli/claude-switches.js +11 -8
  7. package/dist/holmes/cli/doctor.d.ts +7 -1
  8. package/dist/holmes/cli/doctor.js +63 -20
  9. package/dist/holmes/cli/holmes-hook-id.d.ts +9 -0
  10. package/dist/holmes/cli/holmes-hook-id.js +22 -0
  11. package/dist/holmes/cli/hook-failure-posture.d.ts +44 -0
  12. package/dist/holmes/cli/hook-failure-posture.js +65 -0
  13. package/dist/holmes/cli/index.js +3 -1
  14. package/dist/holmes/cli/init.d.ts +6 -0
  15. package/dist/holmes/cli/init.js +151 -3
  16. package/dist/holmes/cli/native-deps.d.ts +10 -4
  17. package/dist/holmes/cli/native-deps.js +30 -29
  18. package/dist/holmes/cli/release-history.d.ts +21 -0
  19. package/dist/holmes/cli/release-history.js +116 -0
  20. package/dist/holmes/cli/run-wiring.js +4 -2
  21. package/dist/holmes/cli/runtime-binding.d.ts +24 -0
  22. package/dist/holmes/cli/runtime-binding.js +67 -25
  23. package/dist/holmes/cli/settings-merge.d.ts +3 -2
  24. package/dist/holmes/cli/settings-merge.js +11 -9
  25. package/dist/holmes/config/config.d.ts +6 -0
  26. package/dist/holmes/config/config.js +23 -3
  27. package/dist/holmes/config/judgement-keys.d.ts +20 -0
  28. package/dist/holmes/config/judgement-keys.js +100 -0
  29. package/dist/holmes/config/project-caps.js +3 -2
  30. package/dist/holmes/governance/autonomous-shell.js +1 -1
  31. package/dist/holmes/governance/autonomy.d.ts +27 -1
  32. package/dist/holmes/governance/autonomy.js +126 -6
  33. package/dist/holmes/governance/wiring-receipt.d.ts +7 -0
  34. package/dist/holmes/governance/wiring-receipt.js +84 -0
  35. package/dist/holmes/guardrail/cli-root.d.ts +31 -0
  36. package/dist/holmes/guardrail/cli-root.js +261 -0
  37. package/dist/holmes/guardrail/command-traits.d.ts +2 -0
  38. package/dist/holmes/guardrail/command-traits.js +26 -1
  39. package/dist/holmes/guardrail/impact-gate.d.ts +17 -1
  40. package/dist/holmes/guardrail/impact-gate.js +44 -5
  41. package/dist/holmes/guardrail/outward-acts.js +10 -3
  42. package/dist/holmes/guardrail/package-manager-acts.d.ts +41 -0
  43. package/dist/holmes/guardrail/package-manager-acts.js +1298 -0
  44. package/dist/holmes/guardrail/refusal-codes.js +9 -1
  45. package/dist/holmes/guardrail/shell-syntax.d.ts +3 -0
  46. package/dist/holmes/guardrail/shell-syntax.js +7 -2
  47. package/dist/holmes/guardrail/write-target.d.ts +20 -0
  48. package/dist/holmes/guardrail/write-target.js +168 -2
  49. package/dist/holmes/hooks/pre-tool-use.d.ts +110 -3
  50. package/dist/holmes/hooks/pre-tool-use.js +1208 -60
  51. package/dist/holmes/mcp/evidence-artifact.d.ts +112 -0
  52. package/dist/holmes/mcp/evidence-artifact.js +2 -0
  53. package/dist/holmes/mcp/handlers/maintenance-evidence.d.ts +2 -1
  54. package/dist/holmes/mcp/handlers/maintenance-evidence.js +24 -2
  55. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +1 -1
  56. package/dist/holmes/mcp/handlers/operator-inspection.js +2 -2
  57. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +1 -1
  58. package/dist/holmes/mcp/handlers/requirement-triage.js +3 -2
  59. package/dist/holmes/mcp/handlers/spec-approval.d.ts +1 -1
  60. package/dist/holmes/mcp/handlers/spec-approval.js +6 -6
  61. package/dist/holmes/mcp/handlers/test-execution.d.ts +8 -0
  62. package/dist/holmes/mcp/handlers/test-execution.js +12 -6
  63. package/dist/holmes/mcp/handlers.d.ts +16 -7
  64. package/dist/holmes/mcp/maintenance-evidence.d.ts +11 -82
  65. package/dist/holmes/mcp/maintenance-evidence.js +57 -2
  66. package/dist/holmes/mcp/outcome-replay.d.ts +18 -0
  67. package/dist/holmes/mcp/outcome-replay.js +85 -0
  68. package/dist/holmes/mcp/outcome-windows.d.ts +136 -0
  69. package/dist/holmes/mcp/outcome-windows.js +236 -0
  70. package/dist/holmes/mcp/tool-schemas.js +1 -1
  71. package/dist/holmes/project/hook-specs-arg.d.ts +4 -0
  72. package/dist/holmes/project/hook-specs-arg.js +39 -0
  73. package/dist/holmes/project/install-layout.d.ts +11 -0
  74. package/dist/holmes/project/install-layout.js +109 -0
  75. package/dist/holmes/project/install-scripts-policy.d.ts +4 -1
  76. package/dist/holmes/project/install-scripts-policy.js +6 -3
  77. package/dist/holmes/project/native-recovery.d.ts +29 -0
  78. package/dist/holmes/project/native-recovery.js +62 -0
  79. package/dist/holmes/project/root.d.ts +6 -0
  80. package/dist/holmes/project/root.js +15 -3
  81. package/dist/holmes/project/wiring-receipt-format.d.ts +20 -0
  82. package/dist/holmes/project/wiring-receipt-format.js +42 -0
  83. package/dist/holmes/project/workspace-preflight.d.ts +9 -0
  84. package/dist/holmes/project/workspace-preflight.js +40 -1
  85. package/dist/holmes/review/classification-replay.d.ts +53 -0
  86. package/dist/holmes/review/classification-replay.js +78 -0
  87. package/dist/holmes/review/head-worktree.js +5 -4
  88. package/dist/holmes/review/run-provenance.js +3 -2
  89. package/dist/holmes/review/test-evidence.js +2 -2
  90. package/dist/holmes/review/test-outcomes.js +3 -1
  91. package/dist/holmes/rtm/graph-store.d.ts +5 -0
  92. package/dist/holmes/rtm/graph-store.js +12 -4
  93. package/dist/holmes/rtm/native-driver.d.ts +42 -0
  94. package/dist/holmes/rtm/native-driver.js +147 -0
  95. package/dist/holmes/rtm/rtm-graph.js +11 -2
  96. package/dist/holmes/runtime/dispatch.d.ts +6 -0
  97. package/dist/holmes/runtime/dispatch.js +51 -2
  98. package/dist/holmes/runtime/hook-process.d.ts +6 -0
  99. package/dist/holmes/runtime/hook-process.js +3 -3
  100. package/dist/holmes/update/semver-strict.d.ts +3 -0
  101. package/dist/holmes/update/semver-strict.js +58 -0
  102. package/docs/install-guide.md +8 -1
  103. package/package.json +3 -2
  104. package/playbooks/tdd-slice/PLAYBOOK.md +1 -1
  105. package/release-history.json +181 -0
@@ -0,0 +1,1298 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.packageCopyCount = exports.packageWorkCount = exports.PACKAGE_FREE_COPY = exports.packageReadingCount = exports.LOCKFILES = void 0;
4
+ exports.holmesPackageAct = holmesPackageAct;
5
+ exports.manifestHolmesChange = manifestHolmesChange;
6
+ exports.shellManifestWrite = shellManifestWrite;
7
+ exports.isManifestName = isManifestName;
8
+ // @implements A-SPEC-794.134, A-SPEC-794.135, A-SPEC-794.136, A-SPEC-794.137, A-SPEC-794.138, A-SPEC-794.139, A-SPEC-794.140, A-SPEC-794.141, A-SPEC-794.142, A-SPEC-794.143, A-SPEC-794.144, A-SPEC-794.145, A-SPEC-794.146, A-SPEC-794.147, A-SPEC-794.148, A-SPEC-794.149, A-SPEC-794.150, A-SPEC-794.151, A-SPEC-794.152
9
+ /**
10
+ * Package-manager acts that can swap the holmes-kit governing the session (measured 2026-11-15: install, uninstall,
11
+ * update and link of `@holmes-lab/holmes-kit`, and an older version run through npx/dlx, were allowed).
12
+ *
13
+ * A-SPEC-794.139 inverts 794.137's contract on the owner's "close on accident prevention": only the known accident
14
+ * shapes against holmes-kit (P) are the owner's, and every other command is free whatever its options, environment or
15
+ * run-time words:
16
+ * (가) removal — a removal verb with P, or `npm pkg delete` of P's key;
17
+ * (나) a pinned install — P named at a version, range or tag that is not literally `latest` and not computed higher
18
+ * than the governing version, as an argument of any package-manager command but a read (a runner included,
19
+ * a report run excepted); or a swap — an npm: alias to P, a tarball, git or path whose name is P;
20
+ * (다) link — a link verb with P, or a directory (an argument, or the current one) whose package.json names P; a global
21
+ * install of a directory takes the same rule;
22
+ * (라) a manifest write that removes, lowers or swaps P's entry (manifestHolmesChange; `npm pkg set`, `yarn set
23
+ * resolution`).
24
+ * Entry: each simple command behind shell keywords and wrappers (commandOf), `corepack`, and `bash -c`/`eval` strings
25
+ * read again. Resisting forgery and evasion is out of scope (0.40); the honesty table records what is not judged. Pure:
26
+ * the hook supplies the directory reads and the governing version.
27
+ */
28
+ const shell_syntax_1 = require("./shell-syntax");
29
+ const PKG = '@holmes-lab/holmes-kit';
30
+ const MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
31
+ const RUNNER_HEADS = new Set(['npx', 'bunx', 'pnpx']);
32
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh']);
33
+ /** @implements A-SPEC-794.136 — the one lockfile list (the hook reads it; B-M3). */
34
+ exports.LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock'];
35
+ const LOCKS = new Set(exports.LOCKFILES);
36
+ /** @implements A-SPEC-794.139 — the shape table: each manager's verbs per shape (OCP: a verb is a row). */
37
+ const REMOVE_VERBS = new Set(['uninstall', 'un', 'remove', 'rm', 'r', 'unlink']);
38
+ const LINK_VERBS = new Set(['link', 'ln']);
39
+ const INSTALL_VERBS = new Set(['install', 'i', 'in', 'ins', 'inst', 'insta', 'instal', 'isnt', 'isnta', 'isntal', 'isntall',
40
+ 'add', 'a', 'update', 'up', 'upgrade', 'udpate', 'it', 'cit', 'install-test', 'install-ci-test', 'ci']);
41
+ const RUN_VERBS = new Set(['exec', 'x', 'dlx']);
42
+ /** Decision 3's exception: reads, free whatever they name. */
43
+ const READ_VERBS = new Set(['cache', 'access', 'sbom', 'diff', 'view', 'info', 'show', 'v', 'ls', 'll', 'la', 'list', 'outdated', 'explain', 'why', 'search',
44
+ 'docs', 'home', 'repo', 'bugs', 'pack', 'dist-tag', 'dist-tags', 'audit', 'fund', 'root', 'prefix', 'bin', 'help']);
45
+ /** Options whose next word is their value, never a specifier (a `=` form carries its own value). Per manager: pnpm's
46
+ * `-w` is `--workspace-root`, a flag. */
47
+ const VALUE_OPTIONS_COMMON = ['--prefix', '--registry', '--cache', '--store-dir', '--workspace', '--filter', '-F', '-C',
48
+ '--dir', '--cwd', '--loglevel', '--tag', '--before', '--userconfig', '--globalconfig', '--modules-dir', '--virtual-store-dir',
49
+ '--location', '--otp', '--scope', '--omit', '--include', '--install-strategy', '--node-options', '--shell', '-p', '--package', '-c', '--diff'];
50
+ const VALUE_OPTIONS = {
51
+ npm: new Set([...VALUE_OPTIONS_COMMON, '-w']), pnpm: new Set(VALUE_OPTIONS_COMMON), yarn: new Set(VALUE_OPTIONS_COMMON), bun: new Set(VALUE_OPTIONS_COMMON),
52
+ };
53
+ /** Verbs that run a project script: its arguments go to the script, which installs nothing of the manager's. */
54
+ const RUN_SCRIPT_VERBS = new Set(['run', 'run-script', 'rum', 'urn', 'test', 't', 'tst', 'start', 'stop', 'restart']);
55
+ /** A runner's options with a value: the package (`-p`), the command string (`-c`). */
56
+ const RUNNER_VALUE = new Set(['-p', '--package', '-c', '--call', '--node-options', '--shell']);
57
+ /** The runner subcommands that stay free with a version named: report writes only its own report (774.67). */
58
+ const FREE_RUN_SUBCOMMANDS = new Set(['report']);
59
+ /** The head word as the shell runs it: a path's basename, a Windows shim's extension dropped, case folded. */
60
+ const tool = (w) => (w.replace(/\\/g, '/').split('/').pop() ?? '').replace(/\.(?:cmd|exe|ps1|bat|js|cjs|mjs)$/i, '').toLowerCase();
61
+ /**
62
+ * The word names P exactly — as the package, an `npm:` alias target, a `pkg set` key (dotted or bracketed), a pnpm
63
+ * `a>P` or yarn `**\/P` pattern. `@holmes-lab/holmes-kit-plugin` and a path into the package do not name it.
64
+ */
65
+ const NAME = /(?:^|npm:|\.|=|>|\/|\[["']?)@holmes-lab\/holmes-kit(?=$|@|=|["']?\])/i;
66
+ const namesPkg = (w) => NAME.test(w);
67
+ /**
68
+ * @implements A-SPEC-794.143 (item 9) — whether a text may hold a holmes-kit shape and so is read again (a re-read body,
69
+ * a substitution): the package name, or `holmes-kit` in a tarball, git or path specifier.
70
+ */
71
+ const mentionsHolmes = (s) => /holmes-kit/i.test(s);
72
+ /**
73
+ * @implements A-SPEC-794.143 (item 2) — an escaped backtick or dollar is kept as a private character, not a
74
+ * substitution; a re-read body (`bash -c`, `eval`) restores it, one level of escaping removed, so what the inner shell
75
+ * substitutes is judged as a substitution there.
76
+ */
77
+ const ESC_TICK = '';
78
+ const ESC_DOLLAR = '';
79
+ const unescapeOnce = (s) => s.replace(//g, '`').replace(//g, '$');
80
+ /** cmd's `REM` at `k`: the word itself, alone or followed by a space. */
81
+ const remAt = (line, k) => /^rem$/i.test(line.slice(k, k + 3)) && (k + 3 === line.length || /\s/.test(line[k + 3]));
82
+ function preprocess(text, join, comments = 'posix', sqText = false) {
83
+ if (!/[`\\#<'"$]/.test(text) && !(comments === 'cmd' && /rem|::|\^/i.test(text)))
84
+ return text;
85
+ const lines = text.split('\n');
86
+ const terminators = terminatorIndex(lines);
87
+ const stack = ['top'];
88
+ const out = [];
89
+ let carry = '';
90
+ let continued = false; // the previous line ended in `\` + newline: its last word goes on
91
+ let block = false; // inside a PowerShell `<# … #>` block comment
92
+ for (let li = 0; li < lines.length; li++) {
93
+ const raw = lines[li];
94
+ const cr = raw.endsWith('\r');
95
+ let line = cr ? raw.slice(0, -1) : raw;
96
+ if (block) {
97
+ const e = line.indexOf('#>');
98
+ if (e < 0) {
99
+ out.push(carry);
100
+ carry = '';
101
+ continue;
102
+ }
103
+ block = false;
104
+ line = ` ${line.slice(e + 2)}`;
105
+ }
106
+ let cmdStart = true; // cmd: nothing but spaces since the line start or the last `&`, `|` or `(`
107
+ let buf = '';
108
+ const openers = [];
109
+ let openedTick = -1; // where this line opened a backtick substitution that is still open
110
+ let comment = false;
111
+ let closeAt = -2; // the next `))` on this line (searched once, moving forward: linear)
112
+ // @implements A-SPEC-794.143 (item 3) — after `\` + newline the word goes on unless a space stood before the `\`
113
+ const startsWord = !continued;
114
+ continued = false;
115
+ for (let i = 0; i < line.length; i++) {
116
+ const c = line[i];
117
+ const top = stack[stack.length - 1];
118
+ const atCmdStart = cmdStart;
119
+ cmdStart = c === '&' || c === '|' || c === '(' || (cmdStart && (c === ' ' || c === '\t'));
120
+ if (top === 'sq') {
121
+ buf += c;
122
+ if (c === "'")
123
+ stack.pop();
124
+ continue;
125
+ }
126
+ // @implements A-SPEC-794.145 (item 1) — an ANSI-C quote is a frame that survives line ends: `\x` is one escaped
127
+ // pair (the character, an inner `'` dropped) and only an unescaped `'` closes it
128
+ if (top === 'ansi') {
129
+ if (c === '\\' && i + 1 < line.length) {
130
+ if (line[i + 1] !== "'")
131
+ buf += line[i + 1];
132
+ i++;
133
+ continue;
134
+ }
135
+ if (c === "'")
136
+ stack.pop();
137
+ buf += c;
138
+ continue;
139
+ }
140
+ if (c === '\\') {
141
+ const n = line[i + 1];
142
+ if (n === undefined) {
143
+ buf += c;
144
+ continued = i > 0 && !/\s/.test(line[i - 1]);
145
+ continue;
146
+ } // a continuation
147
+ if (n === '`') {
148
+ buf += ESC_TICK;
149
+ i++;
150
+ continue;
151
+ } // (b): the character itself
152
+ if (n === '$') {
153
+ buf += ESC_DOLLAR;
154
+ i++;
155
+ continue;
156
+ }
157
+ buf += c + n;
158
+ i++;
159
+ continue;
160
+ }
161
+ if (top === 'arith') {
162
+ if (c === ')' && line[i + 1] === ')') {
163
+ stack.pop();
164
+ buf += '))';
165
+ i++;
166
+ }
167
+ else
168
+ buf += c;
169
+ continue;
170
+ }
171
+ if (c === '$' && line.startsWith('((', i + 1)) {
172
+ // @implements A-SPEC-794.143 (item 8) — a `$((` with no `))` after it on its line is two `$(` (a subshell)
173
+ if (closeAt !== -1 && closeAt < i)
174
+ closeAt = line.indexOf('))', i);
175
+ if (closeAt === -1) {
176
+ stack.push('paren', 'paren');
177
+ buf += '$((';
178
+ i += 2;
179
+ continue;
180
+ }
181
+ stack.push('arith');
182
+ buf += '$((';
183
+ i += 2;
184
+ continue;
185
+ }
186
+ if (c === '$' && line[i + 1] === '(') {
187
+ stack.push('paren');
188
+ buf += '$(';
189
+ i++;
190
+ continue;
191
+ }
192
+ // @implements A-SPEC-794.143 (item 4) — `$'…'` (ANSI-C) is rewritten as a plain single-quoted word with its quotes
193
+ // and escapes removed; A-SPEC-794.145 (item 1): read in the `ansi` frame, across lines
194
+ if (c === '$' && line[i + 1] === "'" && top !== 'dq') {
195
+ stack.push('ansi');
196
+ buf += "'";
197
+ i++;
198
+ continue;
199
+ }
200
+ // @implements A-SPEC-794.145 (item 5d) — a backtick-escaped `#` in a PowerShell body is text (measured on Windows)
201
+ if (comments === 'powershell' && c === '`' && line[i + 1] === '#') {
202
+ buf += "'#'";
203
+ i++;
204
+ continue;
205
+ }
206
+ if (c === '`') {
207
+ if (top === 'tick') {
208
+ stack.pop();
209
+ openedTick = -1;
210
+ }
211
+ else {
212
+ stack.push('tick');
213
+ openedTick = buf.length;
214
+ }
215
+ buf += c;
216
+ continue;
217
+ }
218
+ if (top === 'dq') {
219
+ if (c === '"')
220
+ stack.pop();
221
+ buf += c;
222
+ continue;
223
+ }
224
+ // unquoted: the top level, `$(…)` and a backtick substitution
225
+ // @implements A-SPEC-794.145 (item 4) — in a cmd body `'` is text and `^x` is the character x (measured on Windows)
226
+ if (comments === 'cmd' && sqText && c === "'") {
227
+ buf += "\\'";
228
+ continue;
229
+ }
230
+ if (comments === 'cmd' && c === '^' && i + 1 < line.length) {
231
+ buf += `\\${line[i + 1]}`;
232
+ i++;
233
+ continue;
234
+ }
235
+ if (comments === 'cmd' && c === '^')
236
+ continue; // A-SPEC-794.148 (Behavior 5): a line-end ^ is dropped (measured)
237
+ if (c === "'") {
238
+ stack.push('sq');
239
+ buf += c;
240
+ continue;
241
+ }
242
+ if (c === '"') {
243
+ stack.push('dq');
244
+ buf += c;
245
+ continue;
246
+ }
247
+ if (c === ')' && top === 'paren') {
248
+ stack.pop();
249
+ buf += c;
250
+ continue;
251
+ }
252
+ // A-SPEC-794.144: cmd's `REM`/`::` comment; PowerShell's `<# … #>` block
253
+ if (comments === 'cmd' && top === 'top' && atCmdStart
254
+ // A-SPEC-794.145 (item 4): `@REM` is REM (measured on Windows)
255
+ && (line.startsWith('::', i) || remAt(line, line[i] === '@' ? i + 1 : i))) {
256
+ comment = true;
257
+ break;
258
+ }
259
+ if (comments === 'powershell' && c === '<' && line[i + 1] === '#') {
260
+ const e = line.indexOf('#>', i + 2);
261
+ if (e < 0) {
262
+ block = true;
263
+ comment = true;
264
+ break;
265
+ }
266
+ buf += ' ';
267
+ i = e + 1;
268
+ continue;
269
+ }
270
+ if (c === '#' && (i === 0 ? startsWord : /[\s;&|(]/.test(line[i - 1]))) {
271
+ if (comments === 'cmd') {
272
+ buf += "'#'";
273
+ continue;
274
+ } // cmd: `#` is text (quoted so no later reading cuts there)
275
+ // @implements A-SPEC-794.143 (item 1) — a comment inside a backtick substitution ends at its closing backtick, inside
276
+ // `$(…)` at the closing `)`; at the top level it ends the line
277
+ if (top === 'tick' || top === 'paren') {
278
+ const end = line.indexOf(top === 'tick' ? '`' : ')', i);
279
+ if (end < 0) {
280
+ comment = true;
281
+ break;
282
+ }
283
+ i = end - 1;
284
+ continue;
285
+ }
286
+ comment = true;
287
+ break; // (d)
288
+ }
289
+ if (c === '<' && line[i + 1] === '<' && line[i + 2] !== '<' && line[i - 1] !== '<') {
290
+ let j = i + 2;
291
+ if (line[j] === '-')
292
+ j++;
293
+ while (line[j] === ' ' || line[j] === '\t')
294
+ j++;
295
+ let d = '';
296
+ if (line[j] === "'" || line[j] === '"') {
297
+ const e = line.indexOf(line[j], j + 1);
298
+ d = e < 0 ? '' : line.slice(j + 1, e);
299
+ j = e < 0 ? line.length : e + 1;
300
+ }
301
+ else {
302
+ if (line[j] === '\\')
303
+ j++;
304
+ const m = /^[^\s;&|()<>'"]+/.exec(line.slice(j, j + 512));
305
+ d = m ? m[0] : '';
306
+ j += d.length;
307
+ }
308
+ if (d !== '')
309
+ openers.push(d);
310
+ buf += line.slice(i, j);
311
+ i = j - 1;
312
+ continue;
313
+ }
314
+ buf += c;
315
+ }
316
+ // (c): a line ending in the backtick it opened, outside quotes and comments, continues (PowerShell)
317
+ if (join && !comment && openedTick >= 0 && openedTick === buf.length - 1 && stack[stack.length - 1] === 'tick') {
318
+ stack.pop();
319
+ carry += `${buf.slice(0, -1)} `;
320
+ continue;
321
+ }
322
+ out.push(carry + buf + (cr ? '\r' : ''));
323
+ carry = '';
324
+ // (a): the bodies of the here-documents this line opened, when every terminator exists
325
+ let end = li;
326
+ for (const d of openers) {
327
+ const j = nextTerminator(terminators, d, end);
328
+ if (j < 0) {
329
+ end = li;
330
+ break;
331
+ } // unterminated: nothing is dropped
332
+ end = j;
333
+ }
334
+ li = end;
335
+ }
336
+ if (carry !== '')
337
+ out.push(carry);
338
+ return out.join('\n');
339
+ }
340
+ /** Each candidate terminator line (tabs of `<<-` and spaces trimmed) → its line numbers, built once. */
341
+ function terminatorIndex(lines) {
342
+ const at = new Map();
343
+ lines.forEach((l, i) => {
344
+ const k = l.replace(/^\t+/, '').trim();
345
+ if (k === '' || k.length > 256)
346
+ return;
347
+ const xs = at.get(k);
348
+ if (xs === undefined)
349
+ at.set(k, [i]);
350
+ else
351
+ xs.push(i);
352
+ });
353
+ return at;
354
+ }
355
+ /** The first terminator line for `d` after line `i`, or -1 (a binary search: the pass stays linear). */
356
+ function nextTerminator(at, d, i) {
357
+ const xs = at.get(d);
358
+ if (xs === undefined)
359
+ return -1;
360
+ let lo = 0;
361
+ let hi = xs.length;
362
+ while (lo < hi) {
363
+ const mid = (lo + hi) >> 1;
364
+ if (xs[mid] <= i)
365
+ lo = mid + 1;
366
+ else
367
+ hi = mid;
368
+ }
369
+ return lo < xs.length ? xs[lo] : -1;
370
+ }
371
+ /** The value of a `pkg set` key (`devDependencies.P`, `devDependencies["P"]`) in a manifest text, or null. */
372
+ function existingEntry(manifest, key) {
373
+ if (manifest === null)
374
+ return null;
375
+ let j;
376
+ try {
377
+ j = JSON.parse(manifest);
378
+ }
379
+ catch (e) {
380
+ if (isLimit(e))
381
+ throw e;
382
+ return null;
383
+ }
384
+ const m = /^([A-Za-z]+)(?:\.|\[["']?)(@holmes-lab\/holmes-kit)["']?\]?$/i.exec(key);
385
+ if (m === null || j === null || typeof j !== 'object')
386
+ return null;
387
+ const section = j[m[1]];
388
+ const v = section && typeof section === 'object' ? section[PKG] : undefined;
389
+ return typeof v === 'string' ? v : null;
390
+ }
391
+ /** A Windows path head (`C:\nodejs\npm.cmd`, `.\node_modules\.bin\npm.cmd`) keeps its separators; a POSIX reading folds them. */
392
+ // a lone `\` before a newline is a line continuation, not a path: at least one character must follow it
393
+ const windowsPaths = (text) =>
394
+ // A-SPEC-794.143: only a drive (`C:\`) or a relative (`.\`, `..\`) head is a path — a bare `\\` is an escaped backslash
395
+ // A-SPEC-794.145 (item 5c): a UNC head (`\\host\share\…`) is a path again
396
+ // A-SPEC-794.148 (Behavior 4): also after cmd's `@` (`@C:\nodejs\npm.cmd`)
397
+ text.replace(/(^|[\s;&|(@])((?:[A-Za-z]:|\.{1,2}|\\\\[^\s\\;&|()'"]+)\\[^\s;&|()'"]+)/g, (_m, pre, p) => pre + p.replace(/\\/g, '/'))
398
+ // A-SPEC-794.149 (Behavior 6): a drive root or `.\`/`..\` alone before a space (`start /d C:\ U` — measured to run U)
399
+ .replace(/(^|[\s;&|(@])([A-Za-z]:|\.{1,2})\\(?=[ \t;&|()]|$)/g, (_m, pre, p) => `${pre}${p}/`);
400
+ /**
401
+ * major.minor.patch of a version or range's lower bound (`^0.42`, `0.42.0-beta.1`, `>=0.41.3`), or null.
402
+ * @implements A-SPEC-794.140 (item 5) — `>` and x-range parts (`0.41.x`, `0.41.*`) read as floors, an x part as 0.
403
+ */
404
+ function floorOf(spec) {
405
+ const m = /^\s*(?:\^|~|>=|>|=|v)?\s*(\d+)(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-[0-9A-Za-z.-]+)?(?:\s|$)/.exec(spec);
406
+ if (m === null)
407
+ return null;
408
+ const n = (s) => (s === undefined || /^[xX*]$/.test(s) ? 0 : Number(s));
409
+ return [Number(m[1]), n(m[2]), n(m[3])];
410
+ }
411
+ /** The x-range a value spells (`0.x`, `0.41.x`): the parts it fixes, or null for any other value. */
412
+ function xRangeOf(spec) {
413
+ const m = /^\s*v?(\d+)(?:\.(\d+))?(?:\.[xX*]|\.(\d+)\.[xX*])?\s*$|^\s*v?(\d+)\.[xX*](?:\.[xX*])?\s*$/.exec(spec);
414
+ if (m === null || !/[xX*]/.test(spec))
415
+ return null;
416
+ if (m[4] !== undefined)
417
+ return [Number(m[4])];
418
+ return [Number(m[1]), ...(m[2] !== undefined ? [Number(m[2])] : []), ...(m[3] !== undefined ? [Number(m[3])] : [])];
419
+ }
420
+ const cmp = (a, b) => { for (let i = 0; i < 3; i++)
421
+ if (a[i] !== b[i])
422
+ return a[i] - b[i]; return 0; };
423
+ /** Free: literally `latest` (any case), or a floor strictly higher than the governing version. */
424
+ function upward(version, current) {
425
+ if (version.toLowerCase() === 'latest')
426
+ return true;
427
+ const f = floorOf(version);
428
+ const c = current === undefined ? null : floorOf(current);
429
+ return f !== null && c !== null && cmp(f, c) > 0;
430
+ }
431
+ /** The version part of a word naming P (`P`, `P@x`, `foo@npm:P@x`); undefined when no version is written. */
432
+ const versionOf = (w) => {
433
+ const i = w.toLowerCase().lastIndexOf(PKG);
434
+ const rest = w.slice(i + PKG.length);
435
+ return rest.startsWith('@') ? rest.slice(1) : undefined;
436
+ };
437
+ /** A specifier that is a local path, tarball, git or URL (not a registry name). */
438
+ const PATHLIKE = /^(?:\.{1,2}(?:\/.*)?|~(?:\/.*)?|\/.*|[A-Za-z]:\/.*|file:.*|link:.*)$/;
439
+ const REMOTE = /^(?:git(?:\+[a-z]+)?:|git@|github:|gitlab:|bitbucket:|https?:)|^[^@./][^/\s]*\/[^/\s]+$/i;
440
+ const TARBALL = /\.(?:tgz|tar\.gz|tar)$/i;
441
+ /** (나)/(다) for one specifier word: the shape's name, or null. */
442
+ function specifierShape(w, ctx, readsDirs) {
443
+ const t = w.text;
444
+ if (namesPkg(t)) {
445
+ if (/npm:/i.test(t) && !/^@holmes-lab\/holmes-kit/i.test(t))
446
+ return 'installs another name as holmes-kit (an npm: alias swap)';
447
+ const v = versionOf(t);
448
+ if (!w.known && (v !== undefined || /@holmes-lab\/holmes-kit@?$/i.test(t)))
449
+ return 'installs holmes-kit at a version computed at run time';
450
+ if (v === undefined)
451
+ return null;
452
+ return upward(v, ctx.current) ? null : `installs holmes-kit at ${v === '' ? 'an empty version' : v}, which is not latest and not higher than the governing version`;
453
+ }
454
+ if (!w.known)
455
+ return null; // unreadable (`$(npm pack)`, `"$PWD"`): free, in the honesty table
456
+ const plain = t.replace(/^(?:file|link):/, '');
457
+ if (TARBALL.test(t) && /holmes-kit-\d/i.test(t.split('/').pop() ?? ''))
458
+ return 'installs a holmes-kit tarball';
459
+ if (!PATHLIKE.test(t) && REMOTE.test(t) && /(?:^|[/:])holmes-kit(?:\.git)?(?:#.*)?$/i.test(t))
460
+ return 'installs holmes-kit from git or a URL';
461
+ if (readsDirs && (PATHLIKE.test(t) || PATHLIKE.test(plain)) && ctx.nameAt?.(plain) === PKG)
462
+ return `installs the directory ${plain}, whose package.json names holmes-kit`;
463
+ return null;
464
+ }
465
+ /** Splits a manager command's words into options (with their values skipped), the verb and the positional words. */
466
+ function positionals(words, valueOptions) {
467
+ const opts = [];
468
+ const pos = [];
469
+ for (let i = 0; i < words.length; i++) {
470
+ const t = words[i].text;
471
+ if (t === '--') {
472
+ pos.push(...words.slice(i + 1));
473
+ break;
474
+ }
475
+ if (t.startsWith('-') && t.length > 1) {
476
+ opts.push(t);
477
+ if (valueOptions.has(t) && i + 1 < words.length) {
478
+ opts.push(words[i + 1].text);
479
+ i++;
480
+ }
481
+ continue;
482
+ }
483
+ pos.push(words[i]);
484
+ }
485
+ return { opts, pos };
486
+ }
487
+ /** A runner (npx, pnpx, bunx, npm exec/x, pnpm dlx/exec, yarn dlx, bun x): (나) when it runs P at a pinned version. */
488
+ function runnerShape(head, all, args, ctx) {
489
+ const packages = [];
490
+ // every -p/--package, before or after the run verb, in its separate, `=` and glued (`-p@…`) forms
491
+ for (let i = 0; i < all.length; i++) {
492
+ const t = all[i].text;
493
+ if ((t === '-p' || t === '--package') && all[i + 1] !== undefined)
494
+ packages.push(all[i + 1]);
495
+ else if (/^(?:--package|-p)=/.test(t))
496
+ packages.push({ ...all[i], text: t.replace(/^(?:--package|-p)=/, '') });
497
+ else if (/^-p@/.test(t))
498
+ packages.push({ ...all[i], text: t.slice(2) });
499
+ }
500
+ const { pos } = positionals(args.filter((w) => !/^(?:--package|-p)=|^-p@/.test(w.text)), RUNNER_VALUE);
501
+ const rest = pos.slice();
502
+ if (packages.length === 0 && rest[0] !== undefined)
503
+ packages.push(rest.shift());
504
+ const pinned = packages.map((p) => specifierShape(p, ctx, false)).find((s) => s !== null);
505
+ if (pinned === undefined)
506
+ return null;
507
+ const sub = rest[0]?.text === 'holmes-kit' ? rest[1]?.text : rest[0]?.text;
508
+ if (sub !== undefined && FREE_RUN_SUBCOMMANDS.has(sub))
509
+ return null;
510
+ return `${head} runs a holmes-kit version that is not latest (${pinned})`;
511
+ }
512
+ const PS_PARAMS = [
513
+ { name: 'command', kind: 'command' }, { name: 'file', kind: 'file' }, { name: 'encodedcommand', kind: 'encoded', alias: ['ec'] },
514
+ { name: 'executionpolicy', kind: 'value', alias: ['ep'] }, { name: 'windowstyle', kind: 'value' },
515
+ { name: 'workingdirectory', kind: 'value', alias: ['wd'] }, { name: 'version', kind: 'value' }, { name: 'inputformat', kind: 'value', alias: ['if'] },
516
+ { name: 'outputformat', kind: 'value', alias: ['of'] }, { name: 'configurationname', kind: 'value' }, { name: 'configurationfile', kind: 'value' },
517
+ { name: 'psconsolefile', kind: 'value' }, { name: 'custompipename', kind: 'value' }, { name: 'settingsfile', kind: 'value' },
518
+ { name: 'noprofile', kind: 'flag' }, { name: 'nologo', kind: 'flag' }, { name: 'noninteractive', kind: 'flag' }, { name: 'noexit', kind: 'flag' },
519
+ { name: 'interactive', kind: 'flag' }, { name: 'login', kind: 'flag' }, { name: 'sta', kind: 'flag' }, { name: 'mta', kind: 'flag' },
520
+ { name: 'help', kind: 'flag' },
521
+ ];
522
+ /** The parameter a `-x` or `/x` word names, or null (a word). */
523
+ function psParam(t) {
524
+ // A-SPEC-794.148 (Behavior 3): a Unicode dash starts a parameter (U+2013, U+2014 measured; U+2015 not)
525
+ if (!/^[-/–—―]/.test(t))
526
+ return null;
527
+ const name = t.slice(1).toLowerCase();
528
+ if (name === '')
529
+ return null;
530
+ const exact = PS_PARAMS.find((p) => p.name === name || (p.alias ?? []).includes(name));
531
+ if (exact !== undefined)
532
+ return exact.kind;
533
+ return PS_PARAMS.find((p) => p.name.startsWith(name))?.kind ?? null;
534
+ }
535
+ /**
536
+ * Where a PowerShell command line's bodies may start: after `-Command` (by prefix), or at the first word that names no
537
+ * parameter; and after any later `-Command` too — every candidate is judged and either refusal holds (a parameter this
538
+ * table does not know cannot hide a later `-c`). `-File` and `-EncodedCommand` end the reading.
539
+ */
540
+ function powershellBodies(w) {
541
+ // @implements A-SPEC-794.148 (Behavior 2) — one body (measured: the first -Command takes the rest as one line; a
542
+ // later -c is a word of it); only after an unknown -name, the first later -Command too: at most two, linear
543
+ let unknown = false;
544
+ for (let i = 1; i < w.length; i++) {
545
+ const t = w[i].text;
546
+ const k = psParam(t);
547
+ if (k === 'command')
548
+ return [i + 1];
549
+ if (k === 'file' || k === 'encoded')
550
+ return [];
551
+ if (k === 'value') {
552
+ i++;
553
+ continue;
554
+ }
555
+ if (k === null && !/^[-–—―]/.test(t)) {
556
+ if (!unknown)
557
+ return [i];
558
+ for (let j = i + 1; j < w.length; j++)
559
+ if (psParam(w[j].text) === 'command')
560
+ return [i, j + 1];
561
+ return [i];
562
+ }
563
+ if (k === null)
564
+ unknown = true;
565
+ }
566
+ return [];
567
+ }
568
+ /** cmd `start`'s switches from `i` on: `/x` and an empty title skipped, `/d`, `/affinity`, `/node`, `/machine` with a value. */
569
+ function skipStartSwitches(w, i) {
570
+ while (i < w.length && (w[i].text.startsWith('/') || w[i].text === ''))
571
+ i += /^\/(?:d|affinity|node|machine)$/i.test(w[i].text) ? 2 : 1;
572
+ return i;
573
+ }
574
+ /**
575
+ * @implements A-SPEC-794.151 — the one way the reader copies the words left: counted and charged against the work budget
576
+ * in the same place, so total work (steps + copies) stays within `256 + 4 × length` (a `start` level copying every word
577
+ * left escaped both the cap and the budget: levels × words).
578
+ */
579
+ function charge(n) {
580
+ // @implements A-SPEC-794.152 — a copy or scan of up to FREE_COPY words is free: only a tail of thousands of words is a
581
+ // cost problem, and charging every word over-blocked start chains of short arguments (the budget is in characters)
582
+ const due = work === null ? 0 : Math.max(0, n - work.freeCopy);
583
+ // checked before it is spent: a copy past what is left is not made (the counters never pass the budget)
584
+ if (work !== null && work.left < due) {
585
+ work.left = -1;
586
+ throw new WorkBudgetExceeded(PAST_BUDGET);
587
+ }
588
+ if (work !== null)
589
+ work.left -= due;
590
+ copied += n;
591
+ }
592
+ function copyFrom(words, i) {
593
+ charge(Math.max(0, words.length - i));
594
+ return words.slice(i);
595
+ }
596
+ /** One simple command, unwrapped: the shape's name, or null. */
597
+ function commandShape(words, ctx, depth) {
598
+ spend();
599
+ let w;
600
+ try {
601
+ w = (0, shell_syntax_1.commandOf)(words);
602
+ }
603
+ catch (e) {
604
+ if (isLimit(e))
605
+ throw e;
606
+ return null;
607
+ }
608
+ charge(w.length); // A-SPEC-794.151: commandOf returns a copy of the words left
609
+ if (w.length > 1 && tool(w[0].text) === 'corepack' && MANAGERS.has(tool(w[1].text)))
610
+ w = copyFrom(w, 1);
611
+ // the version managers and `script` run the command after them (B's missed wrappers): `volta run`, `mise exec --`,
612
+ // `nvm exec <v>`, `fnm exec`, `script -q <file>`
613
+ // A-SPEC-794.149: no fixed count — every step spends from the work budget (`@ @ @ @ @ U`, `call` × 5 run: measured)
614
+ // @implements A-SPEC-794.150 — the loop keeps an offset `o` into `all` and copies once when it leaves (a copy per step
615
+ // was quadratic within the budget); `hd` is the word at `o` with cmd's leading `@` stripped
616
+ const all = w;
617
+ let o = 0;
618
+ let hd = all[0]?.text ?? '';
619
+ const at = (i) => (i === 0 ? { ...all[o], text: hd } : all[o + i]);
620
+ const view = (from) => { const v = copyFrom(all, o + from); if (from === 0 && v.length > 0)
621
+ v[0] = at(0); return v; };
622
+ const move = (by) => { o += by; hd = all[o]?.text ?? ''; };
623
+ while (all.length - o > 1) {
624
+ spend();
625
+ const n = all.length - o;
626
+ // @implements A-SPEC-794.147 (item 7), A-SPEC-794.148 (Behavior 4) — cmd's `@` (however many, as its own word, or
627
+ // before a path) before a program is the program
628
+ if (/^@+$/.test(hd)) {
629
+ move(1);
630
+ continue;
631
+ }
632
+ if (/^@+/.test(hd))
633
+ hd = hd.replace(/^@+/, '');
634
+ const h = tool(hd);
635
+ const sub = all[o + 1]?.text;
636
+ const bare = !/[\\/]/.test(hd); // cmd's builtins only as bare words (`./start` is a program)
637
+ let from = -1;
638
+ // cmd's `call` and `start` run the command after them; `start` skips its `/x` switches, the value of `/d`,
639
+ // `/affinity`, `/node`, `/machine`, and a title it cannot tell from a program: both words are judged as the program
640
+ if (bare && h === 'call')
641
+ from = 1;
642
+ else if (bare && h === 'start') {
643
+ // @implements A-SPEC-794.149 — candidates bounded: the second (a title before the program) skips switches again
644
+ // and is not tried when the first word is itself a chain (`start`, `call`, `@`): the first candidate reads it.
645
+ // Each candidate is a nesting level; past NEST_MAX the budget is exceeded (the owner's)
646
+ // A-SPEC-794.151: the switches are read in place (index 1 on is never the stripped head); each candidate is one
647
+ // charged copy
648
+ from = skipStartSwitches(all, o + 1) - o;
649
+ if (from >= n)
650
+ return null;
651
+ if (work !== null && ++work.nest > NEST_MAX)
652
+ throw new WorkBudgetExceeded(PAST_BUDGET);
653
+ try {
654
+ const first = commandShape(copyFrom(all, o + from), ctx, depth);
655
+ // A-SPEC-794.150: a chain is `start`/`call` (any `@` before, any case) or `@` alone — not a title like `@t`
656
+ if (first !== null || /^@*(?:start|call)$|^@+$/i.test(all[o + from].text))
657
+ return first;
658
+ const second = skipStartSwitches(all, o + from + 1) - o;
659
+ return second < n ? commandShape(copyFrom(all, o + second), ctx, depth) : null;
660
+ }
661
+ finally {
662
+ if (work !== null)
663
+ work.nest--;
664
+ }
665
+ }
666
+ else if (h === 'corepack' && n > 1 && MANAGERS.has(tool(all[o + 1].text)))
667
+ from = 1;
668
+ if (h === 'volta' && sub === 'run')
669
+ from = 2;
670
+ else if (h === 'mise' && (sub === 'exec' || sub === 'x')) {
671
+ // the first `--` after the head: searched from the offset, not from the start of the words
672
+ let dd = -1;
673
+ for (let i = o + 1; i < all.length; i++)
674
+ if (all[i].text === '--') {
675
+ dd = i - o;
676
+ break;
677
+ }
678
+ charge((dd > 0 ? dd : all.length - o) - 1); // A-SPEC-794.152: the words scanned count like a copy
679
+ from = dd > 0 ? dd + 1 : 2;
680
+ }
681
+ else if (h === 'nvm' && (sub === 'exec' || sub === 'run'))
682
+ from = 3;
683
+ else if (h === 'fnm' && sub === 'exec') {
684
+ from = 2;
685
+ while (from < n && at(from).text.startsWith('-'))
686
+ from++;
687
+ if (at(from)?.text === '--')
688
+ from++;
689
+ }
690
+ else if (h === 'script') {
691
+ from = 1;
692
+ while (from < n && at(from).text.startsWith('-'))
693
+ from++;
694
+ from++;
695
+ }
696
+ if (from < 0 || from >= n)
697
+ break;
698
+ move(from);
699
+ }
700
+ w = o === 0 && hd === (all[0]?.text ?? '') ? all : view(0);
701
+ if (w.length === 0)
702
+ return null;
703
+ const head = tool(w[0].text);
704
+ // a Windows shell's command string (decision 8, cheap): `cmd /c …`, `powershell -Command "…"`, `pwsh -c "…"`
705
+ if ((head === 'cmd' || head === 'powershell' || head === 'pwsh') && depth < 3) {
706
+ const froms = head === 'cmd' ? (() => { const c = w.findIndex((x, i) => i > 0 && /^\/[ck]$/i.test(x.text)); return c > 0 ? [c + 1] : []; })()
707
+ : powershellBodies(w);
708
+ for (const from of froms) {
709
+ const body = from < w.length ? unescapeOnce(copyFrom(w, from).map((x) => x.text).join(' ')) : '';
710
+ const s = mentionsHolmes(body) ? holmesPackageAct(body, ctx, depth + 1, head === 'cmd' ? 'cmd' : 'powershell') : null;
711
+ if (s !== null)
712
+ return s;
713
+ }
714
+ return null;
715
+ }
716
+ // a runner that runs a package manager (`npx npm uninstall …`, `npx -y npm@10 i -g …`): the manager's command is judged
717
+ if (RUNNER_HEADS.has(head)) {
718
+ const first = w.find((x, i) => i > 0 && !x.text.startsWith('-'));
719
+ const m = first === undefined ? undefined : /^(npm|pnpm|yarn)(?:@[^\s]*)?$/.exec(first.text);
720
+ if (m && first !== undefined)
721
+ return commandShape([{ ...first, text: m[1] }, ...copyFrom(w, w.indexOf(first) + 1)], ctx, depth);
722
+ }
723
+ // decision 8: a shell's -c string and eval's arguments run; read them again as a command
724
+ if (SHELLS.has(head)) {
725
+ const c = w.findIndex((x, i) => i > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(x.text));
726
+ // A-SPEC-794.143 (item 2): the body is read again with one level of escaping removed
727
+ const raw = c > 0 ? w[c + 1]?.text : undefined;
728
+ const body = raw === undefined ? undefined : unescapeOnce(raw);
729
+ return body !== undefined && depth < 3 && mentionsHolmes(body) ? holmesPackageAct(body, ctx, depth + 1) : null;
730
+ }
731
+ if (head === 'eval') {
732
+ const body = unescapeOnce(copyFrom(w, 1).map((x) => x.text).join(' '));
733
+ return depth < 3 && mentionsHolmes(body) ? holmesPackageAct(body, ctx, depth + 1) : null;
734
+ }
735
+ const rest = copyFrom(w, 1);
736
+ if (RUNNER_HEADS.has(head))
737
+ return runnerShape(head, rest, rest, ctx);
738
+ if (!MANAGERS.has(head))
739
+ return null;
740
+ const { opts, pos } = positionals(rest, VALUE_OPTIONS[head]);
741
+ let verb = pos[0]?.text.toLowerCase();
742
+ let args = pos.slice(1);
743
+ // `yarn workspace <name> <verb …>` and `pnpm --filter` forms: the verb after the workspace name is the one judged
744
+ if (head === 'yarn' && verb === 'workspace' && args.length >= 2) {
745
+ verb = args[1].text.toLowerCase();
746
+ args = args.slice(2);
747
+ }
748
+ const global = opts.some((o) => o === '-g' || o === '--global' || o === '--location=global') || (opts.includes('--location') && opts[opts.indexOf('--location') + 1] === 'global');
749
+ let yarnGlobal = false;
750
+ if (head === 'yarn' && verb === 'global') {
751
+ yarnGlobal = true;
752
+ verb = args[0]?.text.toLowerCase();
753
+ args = args.slice(1);
754
+ }
755
+ if (verb === undefined)
756
+ return null;
757
+ if (READ_VERBS.has(verb) || RUN_SCRIPT_VERBS.has(verb))
758
+ return null;
759
+ // @implements A-SPEC-794.140 (item 8) — two-word reads (`yarn npm info`, `bun pm …`) and a dry-run install install nothing
760
+ if ((head === 'yarn' && verb === 'npm' && /^(?:info|view)$/.test(args[0]?.text ?? '')) || (head === 'bun' && verb === 'pm'))
761
+ return null;
762
+ if (opts.includes('--dry-run') && INSTALL_VERBS.has(verb))
763
+ return null;
764
+ // @implements A-SPEC-794.140 (item 9) — the target directory: `--prefix`, `-C`, `--dir`, `--cwd` name it; else here
765
+ // @implements A-SPEC-794.142 (item 4) — the `=` forms too (`--prefix=hk`, `--dir=hk`, `--cwd=hk`, `-C=hk`)
766
+ const DIR_OPTS = ['--prefix', '-C', '--dir', '--cwd'];
767
+ const dirOpt = DIR_OPTS.map((o) => opts.indexOf(o)).find((k) => k >= 0 && opts[k + 1] !== undefined);
768
+ const dirEq = opts.find((o) => DIR_OPTS.some((d) => o.startsWith(`${d}=`)));
769
+ const target = dirOpt !== undefined ? opts[dirOpt + 1] : dirEq !== undefined ? dirEq.slice(dirEq.indexOf('=') + 1) : '.';
770
+ const governing = ctx.current === undefined ? null : floorOf(ctx.current);
771
+ if (RUN_VERBS.has(verb) || (head === 'pnpm' && verb === 'exec')) {
772
+ const at = rest.indexOf(pos[0]);
773
+ return runnerShape(`${head} ${verb}`, rest, rest.slice(at + 1), ctx);
774
+ }
775
+ // (가) removal
776
+ if (REMOVE_VERBS.has(verb) && !(head !== 'npm' && verb === 'unlink')) {
777
+ if (args.some((a) => namesPkg(a.text)))
778
+ return `${head} ${verb} removes holmes-kit`;
779
+ return null;
780
+ }
781
+ if (verb === 'pkg') {
782
+ const sub = args[0]?.text;
783
+ if (sub === 'delete' && args.slice(1).some((a) => namesPkg(a.text)))
784
+ return 'npm pkg delete removes the holmes-kit entry';
785
+ if (sub === 'set') {
786
+ for (const a of args.slice(1)) {
787
+ const eq = a.text.indexOf('=');
788
+ if (eq < 0)
789
+ continue;
790
+ const key = a.text.slice(0, eq);
791
+ let v = a.text.slice(eq + 1);
792
+ // @implements A-SPEC-794.142 (item 6) — a --json value is parsed before it is judged
793
+ if (opts.includes('--json')) {
794
+ try {
795
+ const j = JSON.parse(v);
796
+ if (typeof j === 'string')
797
+ v = j;
798
+ }
799
+ catch { /* judged as written */ }
800
+ }
801
+ if (/^npm:@holmes-lab\/holmes-kit(?=$|@)/i.test(v))
802
+ return 'npm pkg set makes another entry an alias of holmes-kit';
803
+ if (!namesPkg(key))
804
+ continue;
805
+ // peer ranges state a compatibility: what installs is decided by the dependency keys (A-SPEC-794.140 item 5)
806
+ if (/^peerDependencies(?:Meta)?\b/.test(key))
807
+ continue;
808
+ // @implements A-SPEC-794.140 (item 4), A-SPEC-794.142 (item 6) — the value is judged as an Edit of the manifest
809
+ // would be: against the entry it replaces when the manifest can be read, else against the governing version
810
+ // @implements A-SPEC-794.143 (item 5) — with `-w`/`--workspace`, that workspace's manifest (the directory named, or
811
+ // one under packages/); not found: the governing version
812
+ // A-SPEC-794.145 (item 6): only npm's `-w` takes a workspace (pnpm's is `--workspace-root`, a flag)
813
+ const wsAt = opts.findIndex((o) => (o === '-w' && head === 'npm') || o === '--workspace');
814
+ const wsEq = opts.find((o) => o.startsWith('--workspace='));
815
+ const ws = wsAt >= 0 ? opts[wsAt + 1] : wsEq?.slice('--workspace='.length);
816
+ const manifestText = ws === undefined ? ctx.readManifest?.(target) ?? null
817
+ : ctx.readManifest?.(`${target}/${ws}`) ?? ctx.readManifest?.(`${target}/packages/${ws}`) ?? null;
818
+ const existing = existingEntry(manifestText, key);
819
+ const ref = existing === null ? governing : floorOf(existing);
820
+ if (!a.known || lowersOrSwaps(v, ref, existing === null ? ctx.current : undefined))
821
+ return `npm pkg set pins holmes-kit at ${v || 'an empty value'}`;
822
+ }
823
+ }
824
+ return null;
825
+ }
826
+ if (head === 'yarn' && verb === 'set' && args[0]?.text === 'resolution' && args.slice(1).some((a) => namesPkg(a.text))) {
827
+ const value = args[2];
828
+ // `npm:<range>` with no package name is that range of the same package (yarn's protocol), not a swap
829
+ const v = value?.text.replace(/^npm:(?=[\^~<>=\dvx*])/i, '');
830
+ return value === undefined || v === undefined || !value.known || lowersOrSwaps(v, governing, ctx.current) ? 'yarn set resolution pins holmes-kit' : null;
831
+ }
832
+ // (다) link: by name, or a directory whose package.json names P
833
+ if (LINK_VERBS.has(verb)) {
834
+ if (args.some((a) => namesPkg(a.text)))
835
+ return `${head} ${verb} links holmes-kit`;
836
+ const dirs = args.length === 0 ? [target] : args.filter((a) => a.known).map((a) => a.text);
837
+ const hit = dirs.find((d) => ctx.nameAt?.(d.replace(/^(?:file|link):/, '')) === PKG);
838
+ return hit !== undefined ? `${head} ${verb} links ${hit}, whose package.json names holmes-kit` : null;
839
+ }
840
+ // (나) a pinned or swapped P as an argument of any other verb; installs also read the directories they name
841
+ const installs = INSTALL_VERBS.has(verb) || yarnGlobal;
842
+ for (const a of args) {
843
+ const s = specifierShape(a, ctx, installs);
844
+ if (s !== null)
845
+ return `${head} ${verb} ${s}`;
846
+ }
847
+ // a global install's --prefix is where it installs, not what it installs: the directory installed is here
848
+ if (installs && global && args.length === 0 && ctx.nameAt?.('.') === PKG)
849
+ return `${head} ${verb} installs this directory globally, and its package.json names holmes-kit`;
850
+ return null;
851
+ }
852
+ /** The act's name, or null when the command is free. */
853
+ let readingCount = 0;
854
+ /** @implements A-SPEC-794.148 — how many readings holmesPackageAct has judged (for the linear test; no behavior). */
855
+ const packageReadingCount = () => readingCount;
856
+ exports.packageReadingCount = packageReadingCount;
857
+ /**
858
+ * @implements A-SPEC-794.149 — one work budget per top-level call, linear in the command's length. Every reading, every
859
+ * commandShape call and every wrapper step spends one unit; nested `start` candidates also count a nesting level.
860
+ * Past the budget, past NEST_MAX levels, or on a stack overflow, the command is the owner's — never silently free: no
861
+ * inner catch swallows either (they rethrow `isLimit`). Values measured against the corpora (see the release draft).
862
+ */
863
+ const WORK_BASE = 256;
864
+ const WORK_PER_CHAR = 4;
865
+ const NEST_MAX = 64;
866
+ class WorkBudgetExceeded extends Error {
867
+ }
868
+ let work = null;
869
+ /** @implements A-SPEC-794.152 — words one copy or scan takes without charge (measured: see the release draft). */
870
+ exports.PACKAGE_FREE_COPY = 1024;
871
+ let workSpent = 0;
872
+ const packageWorkCount = () => workSpent;
873
+ exports.packageWorkCount = packageWorkCount;
874
+ const PAST_BUDGET = 'the command is past the package reader\'s work budget (judged as the owner\'s)';
875
+ function spend() {
876
+ workSpent++;
877
+ if (work !== null && --work.left < 0)
878
+ throw new WorkBudgetExceeded(PAST_BUDGET);
879
+ }
880
+ // @implements A-SPEC-794.150 — the lexer's nesting limit is a limit too (it was swallowed as unreadable: silently free)
881
+ const isLimit = (e) => e instanceof WorkBudgetExceeded || e instanceof RangeError || e instanceof shell_syntax_1.NestingTooDeep;
882
+ /**
883
+ * @implements A-SPEC-794.150 — a reading of more than WORD_MAX words is the owner's before any wrapper is read: a cap on
884
+ * the input closes the class of steps whose cost grows with the words left (measured: the corpora hold at most 28 words,
885
+ * 86,000 agent commands at most 1,553; the outward judgement caps a clause at the same 20,000).
886
+ */
887
+ const WORD_MAX = 20_000;
888
+ const TOO_MANY_WORDS = `the command has more than ${WORD_MAX.toLocaleString('en-US')} words — too large for the package reader (judged as the owner's)`;
889
+ let copied = 0;
890
+ /** @implements A-SPEC-794.150 — how many words the wrapper loop has copied (for the linear test; no behavior). */
891
+ const packageCopyCount = () => copied;
892
+ exports.packageCopyCount = packageCopyCount;
893
+ function holmesPackageAct(command, ctx = {}, depth = 0, comments = 'posix') {
894
+ if (work !== null)
895
+ return readAct(command, ctx, depth, comments);
896
+ work = { left: ctx.workBudget ?? WORK_BASE + WORK_PER_CHAR * command.length, nest: 0, freeCopy: ctx.freeCopy ?? exports.PACKAGE_FREE_COPY };
897
+ try {
898
+ return readAct(command, ctx, depth, comments);
899
+ }
900
+ catch (e) {
901
+ if (isLimit(e))
902
+ return e instanceof WorkBudgetExceeded ? e.message : PAST_BUDGET;
903
+ throw e;
904
+ }
905
+ finally {
906
+ work = null;
907
+ }
908
+ }
909
+ function readAct(command, ctx, depth, comments) {
910
+ // @implements A-SPEC-794.142 (items 1, 3) — one preprocessing pass decides here-documents, escapes, comments and
911
+ // continuations; a continuation never frees: the text is read with and without joining, and either refusal holds
912
+ // (here-document bodies and quoted text are data in both readings)
913
+ const plain = preprocess(command, false, comments);
914
+ const joined = preprocess(command, true, comments);
915
+ const readings = joined === plain ? [plain] : [plain, joined];
916
+ readingCount += readings.length + (comments === 'cmd' ? 1 : 0); // A-SPEC-794.148: counted for the linear test
917
+ // @implements A-SPEC-794.145 (item 4) — in a cmd body `'` is text (measured on Windows), but what the program after it
918
+ // does with the quotes is its own: the body is also read with POSIX quotes, and either refusal holds
919
+ if (comments === 'cmd')
920
+ readings.push(preprocess(command, false, comments, true));
921
+ for (const reading of readings) {
922
+ spend();
923
+ const s = judgeText(windowsPaths(reading), ctx, depth);
924
+ if (s !== null)
925
+ return s;
926
+ }
927
+ return null;
928
+ }
929
+ /** One reading of a preprocessed command: each simple command in order (directory moves tracked), then substitutions. */
930
+ function judgeText(text, ctx, depth) {
931
+ const parsed = (0, shell_syntax_1.shellWords)(text, process.env, undefined, null, true);
932
+ // A-SPEC-794.150 — only a command that names holmes-kit (the reader judges only those, A-SPEC-794.137): a long read
933
+ // that does not is not this reader's to refuse (`grep -c x × 100,001 .ax/…` passes, A-SPEC-794.40)
934
+ if (mentionsHolmes(text) && parsed.commands.reduce((n, c) => n + c.words.length, 0) > WORD_MAX)
935
+ throw new WorkBudgetExceeded(TOO_MANY_WORDS);
936
+ // a `cd` or `pushd` moves where later directory words are read (decision 7: `cd hk && npm i -g .`); an unreadable move
937
+ // stops the reads. @implements A-SPEC-794.140 (item 10) — the directory is kept as segments, and past 64 it becomes
938
+ // unknown, so a long run of relative moves stays linear. @implements A-SPEC-794.142 (item 4) — `popd` pops a stack of
939
+ // directories (empty: the starting one), and `pushd -n` does not move
940
+ let base = [];
941
+ const stack = [];
942
+ for (const one of parsed.commands) {
943
+ let w = [];
944
+ try {
945
+ w = (0, shell_syntax_1.commandOf)(one.words);
946
+ }
947
+ catch (e) {
948
+ if (isLimit(e))
949
+ throw e; /* judged below as unreadable */
950
+ }
951
+ const mover = w.length > 0 ? tool(w[0].text) : '';
952
+ if (mover === 'popd') {
953
+ base = stack.length > 0 ? stack.pop() : [];
954
+ continue;
955
+ }
956
+ if (mover === 'cd' || mover === 'pushd') {
957
+ if (mover === 'pushd' && w.slice(1).some((x) => x.text === '-n'))
958
+ continue;
959
+ const to = w.slice(1).find((x) => !x.text.startsWith('-') || x.text === '-');
960
+ if (mover === 'pushd')
961
+ stack.push(base === null ? null : [...base]);
962
+ if (base === null || to === undefined || !to.known || to.text === '-')
963
+ base = null;
964
+ else if (to.text.startsWith('/'))
965
+ base = ['', ...to.text.split('/').filter((s) => s !== '')];
966
+ else {
967
+ base = [...base, ...to.text.split('/').filter((s) => s !== '' && s !== '.')];
968
+ if (base.length > 64)
969
+ base = null;
970
+ }
971
+ continue;
972
+ }
973
+ const at = base === null ? null : base.join('/');
974
+ const rel = (d) => (at === '' || d.startsWith('/') ? d : `${at}/${d}`);
975
+ const here = { current: ctx.current, nameAt: (d) => (at === null ? null : ctx.nameAt?.(rel(d)) ?? null),
976
+ readManifest: (d) => (at === null ? null : ctx.readManifest?.(rel(d)) ?? null) };
977
+ const s = commandShape(one.words, here, depth);
978
+ if (s !== null)
979
+ return s;
980
+ }
981
+ // A substitution runs: one holding the name is read again, to a depth of 3; deeper it is judged by the name alone
982
+ for (const sub of parsed.subs) {
983
+ if (!mentionsHolmes(sub))
984
+ continue;
985
+ if (depth >= 3)
986
+ return 'a package command names holmes-kit in substitutions nested too deep to read';
987
+ const inner = holmesPackageAct(sub, ctx, depth + 1);
988
+ if (inner !== null)
989
+ return `a substitution runs a package command: ${inner}`;
990
+ }
991
+ return null;
992
+ }
993
+ // @implements A-SPEC-794.140 (item 5) — the keys that decide what installs; a peer range only states a compatibility
994
+ const DEP_KEYS = ['dependencies', 'devDependencies', 'optionalDependencies'];
995
+ const ALIAS = 'npm-alias:';
996
+ /**
997
+ * @implements A-SPEC-794.137 (c), A-SPEC-794.139 — every place a manifest can say how holmes-kit resolves, as path →
998
+ * value: the dependency keys (and an npm: alias to P under any name), and any key naming P at any depth under
999
+ * `overrides`, `pnpm.overrides` and `resolutions` (a `a>P`, `**\/P` or `foo/P` pattern included). null for a text
1000
+ * that does not parse.
1001
+ */
1002
+ function holmesPaths(text) {
1003
+ const out = new Map();
1004
+ if (text === null)
1005
+ return out;
1006
+ let j;
1007
+ try {
1008
+ j = JSON.parse(text);
1009
+ }
1010
+ catch (e) {
1011
+ if (isLimit(e))
1012
+ throw e;
1013
+ return null;
1014
+ }
1015
+ if (j === null || typeof j !== 'object')
1016
+ return null;
1017
+ for (const k of DEP_KEYS) {
1018
+ const v = j[k];
1019
+ if (!v || typeof v !== 'object')
1020
+ continue;
1021
+ if (PKG in v)
1022
+ out.set(`${k}.${PKG}`, JSON.stringify(v[PKG]));
1023
+ for (const [name, spec] of Object.entries(v)) {
1024
+ if (typeof spec === 'string' && /^npm:@holmes-lab\/holmes-kit(?=$|@)/i.test(spec))
1025
+ out.set(`${ALIAS}${k}.${name}`, JSON.stringify(spec));
1026
+ }
1027
+ }
1028
+ const walk = (node, at) => {
1029
+ if (node === null || typeof node !== 'object')
1030
+ return;
1031
+ for (const [key, value] of Object.entries(node)) {
1032
+ const p = `${at}.${key}`;
1033
+ if (/(?:^|>|\/)@holmes-lab\/holmes-kit(?=$|@)/i.test(key))
1034
+ out.set(p, JSON.stringify(value));
1035
+ walk(value, p);
1036
+ }
1037
+ };
1038
+ walk(j.overrides, 'overrides');
1039
+ walk(j.resolutions, 'resolutions');
1040
+ walk(j.pnpm?.overrides, 'pnpm.overrides');
1041
+ return out;
1042
+ }
1043
+ /** A value that swaps P for something else: an alias, a path, git, a URL, a workspace link, or a tag other than latest. */
1044
+ const SWAP = /^(?:npm:|file:|link:|workspace:|portal:|git(?:\+[a-z]+)?:|git@|github:|gitlab:|bitbucket:|https?:|\.{0,2}\/|~\/)/i;
1045
+ const isTag = (v) => /^[A-Za-z][\w.-]*$/.test(v) && v.toLowerCase() !== 'latest' && !/^v?\d/.test(v);
1046
+ /** A widening that keeps every version: `*`, `''`, `x`. */
1047
+ const ANY = /^\s*(?:\*|x|X|)\s*$/;
1048
+ /**
1049
+ * @implements A-SPEC-794.139 (decision 5), A-SPEC-794.140 (items 2–5) — whether a value of P's entry is an accident: a
1050
+ * swap, a tag other than latest, a floor lower than `ref`, an x-range that leaves `ref` out below, or an upper bound
1051
+ * only (`<`, `<=`) that leaves `ref` out. `ref` is the entry it replaces, else the highest P dependency floor before,
1052
+ * else the governing version. A `$P` override refers to the dependency itself and is free.
1053
+ */
1054
+ function lowersOrSwaps(after, ref, governingVersion) {
1055
+ if (typeof after !== 'string')
1056
+ return after !== undefined && after !== null && typeof after !== 'object';
1057
+ const v = after.trim();
1058
+ if (v.startsWith('$'))
1059
+ return false;
1060
+ // the swap and tag lines below lean on the fallback: an unparseable value is the owner's anyway (794.139 mutants D2, D3)
1061
+ if (SWAP.test(v))
1062
+ return true;
1063
+ if (v.toLowerCase() === 'latest' || ANY.test(v))
1064
+ return false;
1065
+ // @implements A-SPEC-794.142 (item 5) — when the reference is the governing version (an add where no entry was, an
1066
+ // earlier text that cannot be read), any range form is judged by whether it contains that version
1067
+ if (governingVersion !== undefined) {
1068
+ // A-SPEC-794.143 (items 6, 7): free when an alternative contains it or every alternative lies above it (a raise)
1069
+ const verdict = rangeVerdict(v, governingVersion);
1070
+ if (verdict !== null)
1071
+ return verdict === 'below';
1072
+ }
1073
+ const upper = /^<(=?)\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?\s*$/.exec(v);
1074
+ if (upper !== null) {
1075
+ if (ref === null)
1076
+ return false;
1077
+ const u = [Number(upper[2]), Number(upper[3] ?? 0), Number(upper[4] ?? 0)];
1078
+ return upper[1] === '=' ? cmp(u, ref) < 0 : cmp(u, ref) <= 0;
1079
+ }
1080
+ const x = xRangeOf(v);
1081
+ if (x !== null) {
1082
+ if (ref === null || x.every((p, i) => p === ref[i]))
1083
+ return false; // the range keeps `ref`
1084
+ return cmp([x[0], x[1] ?? 0, x[2] ?? 0], ref) < 0;
1085
+ }
1086
+ if (isTag(v))
1087
+ return true;
1088
+ const f = floorOf(v);
1089
+ if (f === null)
1090
+ return true; // a value the reader cannot place is not shown to keep P
1091
+ return ref !== null && cmp(f, ref) < 0;
1092
+ }
1093
+ /**
1094
+ * @implements A-SPEC-794.142 (item 5) — whether a semver range contains a version: alternatives (`||`), each a set of
1095
+ * comparators (space), each a caret, tilde, comparison (`>=`, `>`, `<=`, `<`, `=`) or partial/x version; a prerelease
1096
+ * tag on either side is ignored. null when the range cannot be read (the caller keeps it the owner's).
1097
+ */
1098
+ /**
1099
+ * @implements A-SPEC-794.143 (items 6, 7) — the range against the governing version, per alternative: 'contains' when
1100
+ * any alternative contains it, 'above' when every alternative lies wholly above it (a raise; `>v` at the floor is above),
1101
+ * else 'below' (an alternative allows only lower versions). A hyphen range `a - b` reads as `>=a <=b`. null: unreadable.
1102
+ */
1103
+ function rangeVerdict(range, version) {
1104
+ const ver = floorOf(version);
1105
+ if (ver === null)
1106
+ return null;
1107
+ const alts = range.split('||').map((a) => a.trim().replace(/(\S+)\s+-\s+(\S+)/, '>=$1 <=$2'));
1108
+ if (alts.some((a) => rangeContains(a, version) === null))
1109
+ return null;
1110
+ if (alts.some((a) => rangeContains(a, version) === true))
1111
+ return 'contains';
1112
+ const above = (alt) => {
1113
+ let best = null;
1114
+ for (const comp of alt.replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/).filter((x) => x !== '')) {
1115
+ const m = /^(\^|~|>=|>|=)?v?(\d+)(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?/.exec(comp);
1116
+ if (m === null)
1117
+ continue; // a `<` comparator never matches (A-SPEC-794.146: the dead `<` test removed)
1118
+ const lo = [Number(m[2]), /^\d+$/.test(m[3] ?? '') ? Number(m[3]) : 0, /^\d+$/.test(m[4] ?? '') ? Number(m[4]) : 0];
1119
+ if (best === null || cmp(lo, best.lo) > 0)
1120
+ best = { lo, strict: m[1] === '>' };
1121
+ }
1122
+ return best !== null && (cmp(best.lo, ver) > 0 || (best.strict && cmp(best.lo, ver) === 0));
1123
+ };
1124
+ return alts.every(above) ? 'above' : 'below';
1125
+ }
1126
+ function rangeContains(range, version) {
1127
+ const ver = floorOf(version);
1128
+ if (ver === null)
1129
+ return null;
1130
+ const part = (s) => (s === undefined || /^[xX*]$/.test(s) ? null : Number(s));
1131
+ let readable = true;
1132
+ const one = (comp) => {
1133
+ const m = /^(\^|~|>=|>|<=|<|=)?v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-[0-9A-Za-z.-]+)?$/.exec(comp);
1134
+ if (m === null) {
1135
+ readable = false;
1136
+ return false;
1137
+ }
1138
+ const [maj, min, pat] = [part(m[2]), part(m[3]), part(m[4])];
1139
+ const lo = [maj ?? 0, min ?? 0, pat ?? 0];
1140
+ const op = m[1] ?? '';
1141
+ if (op === '>=')
1142
+ return cmp(ver, lo) >= 0;
1143
+ if (op === '>')
1144
+ return cmp(ver, lo) > 0;
1145
+ if (op === '<=')
1146
+ return cmp(ver, lo) <= 0;
1147
+ if (op === '<')
1148
+ return cmp(ver, lo) < 0;
1149
+ let hi;
1150
+ if (op === '^')
1151
+ hi = maj === null ? [Infinity, 0, 0] : maj > 0 || min === null ? [maj + 1, 0, 0] : min > 0 || pat === null ? [0, min + 1, 0] : [0, 0, pat + 1];
1152
+ else if (op === '~')
1153
+ hi = maj === null ? [Infinity, 0, 0] : min === null ? [maj + 1, 0, 0] : [maj, min + 1, 0];
1154
+ else
1155
+ hi = maj === null ? [Infinity, 0, 0] : min === null ? [maj + 1, 0, 0] : pat === null ? [maj, min + 1, 0] : [maj, min, pat + 1]; // partial, x-range or exact
1156
+ return cmp(ver, lo) >= 0 && cmp(ver, hi) < 0;
1157
+ };
1158
+ const result = range.split('||').some((alt) => {
1159
+ const comps = alt.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/).filter((c) => c !== '');
1160
+ return comps.length > 0 && comps.every(one);
1161
+ });
1162
+ return readable ? result : null;
1163
+ }
1164
+ /** Whether a write to `file` removes, lowers or swaps how holmes-kit resolves in a manifest or lockfile. */
1165
+ function manifestHolmesChange(file, before, after, current) {
1166
+ const name = (file.replace(/\\/g, '/').split('/').pop() ?? '').toLowerCase();
1167
+ const governing = current === undefined ? null : floorOf(current);
1168
+ if (name === 'package.json') {
1169
+ const b = holmesPaths(before);
1170
+ const a = holmesPaths(after);
1171
+ // @implements A-SPEC-794.140 (item 6) — an earlier text that cannot be read (a merge conflict, a BOM) with a readable
1172
+ // later one: each P value of the later text is judged against the governing version
1173
+ if (b === null && a !== null) {
1174
+ const deps = [...a.keys()].filter((k) => DEP_KEYS.some((d) => k === `${d}.${PKG}`));
1175
+ if (deps.length === 0 && (before ?? '').includes(PKG))
1176
+ return true; // the entry is gone
1177
+ return [...a].some(([k, v]) => k.startsWith(ALIAS) || lowersOrSwaps(JSON.parse(v), governing, current));
1178
+ }
1179
+ if (a === null || b === null)
1180
+ return (after ?? '').includes(PKG) || (before ?? '').includes(PKG); // unreadable result naming it
1181
+ const depFloors = (m) => [...m].filter(([k]) => DEP_KEYS.some((d) => k === `${d}.${PKG}`))
1182
+ .map(([, v]) => { const x = JSON.parse(v); return typeof x === 'string' ? floorOf(x) : null; }).filter((x) => x !== null);
1183
+ const highest = (fs) => fs.reduce((m, f) => (m === null || cmp(f, m) > 0 ? f : m), null);
1184
+ const highestBefore = highest(depFloors(b));
1185
+ const refBefore = highestBefore ?? governing; // A-SPEC-794.140 (item 3): an add is measured against the governing version
1186
+ // decision 5: removing P from every dependency key is (가); a move between dependency keys is free
1187
+ const depKeys = (m) => [...m.keys()].filter((k) => DEP_KEYS.some((d) => k === `${d}.${PKG}`)).length;
1188
+ if (depKeys(b) > 0 && depKeys(a) === 0)
1189
+ return true;
1190
+ for (const key of new Set([...a.keys(), ...b.keys()])) {
1191
+ const x = b.get(key);
1192
+ const y = a.get(key);
1193
+ if (x === y || y === undefined)
1194
+ continue; // unchanged, or removed (removal of every dependency entry is above)
1195
+ const after = JSON.parse(y);
1196
+ // an alias to P added or changed: the command path judges it the same (its value is always `npm:…`, which the swap
1197
+ // test refuses too — 794.139 mutant D6 leans on that)
1198
+ if (key.startsWith(ALIAS))
1199
+ return true;
1200
+ const prev = x === undefined ? null : JSON.parse(x);
1201
+ const fromEntry = typeof prev === 'string' && floorOf(prev) !== null;
1202
+ const ref = fromEntry ? floorOf(prev) : refBefore;
1203
+ if (typeof after === 'object' && after !== null)
1204
+ continue; // a nested override object: its own keys are walked
1205
+ // A-SPEC-794.142 (item 5): with the governing version as the reference, a range is judged by containing it
1206
+ if (lowersOrSwaps(after, ref, !fromEntry && highestBefore === null ? current : undefined))
1207
+ return true;
1208
+ }
1209
+ return false;
1210
+ }
1211
+ if (LOCKS.has(name))
1212
+ return lockEntries(before) !== lockEntries(after);
1213
+ return false;
1214
+ }
1215
+ /** The lines of a lockfile text that belong to an entry naming the package (that line and the indented block under it). */
1216
+ function lockEntries(text) {
1217
+ if (text === null)
1218
+ return '';
1219
+ const lines = text.split(/\r?\n/);
1220
+ const out = [];
1221
+ for (let i = 0; i < lines.length; i++) {
1222
+ if (!lines[i].includes(PKG))
1223
+ continue;
1224
+ const indent = /^\s*/.exec(lines[i])?.[0].length ?? 0;
1225
+ out.push(lines[i]);
1226
+ for (let j = i + 1; j < lines.length; j++) {
1227
+ const ind = /^\s*/.exec(lines[j])?.[0].length ?? 0;
1228
+ if (lines[j].trim() !== '' && ind <= indent)
1229
+ break;
1230
+ out.push(lines[j]);
1231
+ }
1232
+ }
1233
+ return out.join('\n');
1234
+ }
1235
+ /**
1236
+ * @implements A-SPEC-794.136 (A-M1), A-SPEC-794.137, A-SPEC-794.139 (decision 6, unchanged) — a shell write over a
1237
+ * manifest or lockfile whose text names holmes-kit: the act's name, or null. A shell write cannot be read, so the file's
1238
+ * present text decides. `readText` reads a word as the shell resolves it in this segment (null: absent or unreadable).
1239
+ * Write signals: an output redirect, `tee`, `sed|perl|ruby -i`, `awk -i inplace`, and the destinations of `cp`, `mv`,
1240
+ * `install`, `dd of=`, `truncate`, `rm`.
1241
+ */
1242
+ function shellManifestWrite(command, readText) {
1243
+ if (!/package\.json|lock|shrinkwrap/.test(command))
1244
+ return null;
1245
+ let parsed;
1246
+ try {
1247
+ parsed = (0, shell_syntax_1.shellWords)(command, process.env, undefined, null, true);
1248
+ }
1249
+ catch {
1250
+ return null;
1251
+ } // [no-substitution: the wiring scan still judges]
1252
+ const judge = (w) => {
1253
+ // a file inside node_modules is an installed package's own: the deployed-package protection (794.113) judges it
1254
+ if (w.replace(/\\/g, '/').split('/').includes('node_modules'))
1255
+ return null;
1256
+ // @implements A-SPEC-794.140 (item 9, decision 6 fixed) — a lockfile follows the manifest on reinstall: deleting,
1257
+ // moving or overwriting one is free; a package.json naming P stays the owner's
1258
+ if ((w.replace(/\\/g, '/').split('/').pop() ?? '').toLowerCase() !== 'package.json')
1259
+ return null;
1260
+ const text = readText(w);
1261
+ return text !== null && text.includes(PKG) ? `a shell write to ${w}, which names holmes-kit` : null;
1262
+ };
1263
+ for (const one of parsed.commands) {
1264
+ for (const r of one.redirects) {
1265
+ const k = judge(r.text);
1266
+ if (k !== null)
1267
+ return k;
1268
+ }
1269
+ let at = 0;
1270
+ while (at < one.words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(one.words[at].text))
1271
+ at++;
1272
+ const head = tool(one.words[at]?.text ?? '');
1273
+ const args = one.words.slice(at + 1).map((w) => w.text);
1274
+ const positional = args.filter((a) => !a.startsWith('-'));
1275
+ let targets = [];
1276
+ if (head === 'tee' || head === 'rm' || head === 'truncate')
1277
+ targets = positional;
1278
+ else if ((head === 'sed' || head === 'gsed' || head === 'perl' || head === 'ruby') && args.some((a) => /^-[A-Za-z]*i/.test(a) || a.startsWith('--in-place')))
1279
+ targets = positional;
1280
+ else if ((head === 'awk' || head === 'gawk') && args.includes('inplace'))
1281
+ targets = positional;
1282
+ else if (head === 'cp' || head === 'mv' || head === 'install' || head === 'gcp' || head === 'gmv')
1283
+ targets = positional.slice(-1);
1284
+ else if (head === 'dd')
1285
+ targets = args.filter((a) => a.startsWith('of=')).map((a) => a.slice(3));
1286
+ for (const t of targets) {
1287
+ const k = judge(t);
1288
+ if (k !== null)
1289
+ return k;
1290
+ }
1291
+ }
1292
+ return null;
1293
+ }
1294
+ /** @implements A-SPEC-794.136 — whether a file name is a manifest or lockfile the holmes-kit entry can live in. */
1295
+ function isManifestName(file) {
1296
+ const name = (file.replace(/\\/g, '/').split('/').pop() ?? '').toLowerCase();
1297
+ return name === 'package.json' || LOCKS.has(name);
1298
+ }