@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,236 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_UNSCORED = exports.WINDOW_COMMITS_MAX = void 0;
4
+ exports.projectGit = projectGit;
5
+ exports.parseGitLogZ = parseGitLogZ;
6
+ exports.rangeFiles = rangeFiles;
7
+ exports.sameRequest = sameRequest;
8
+ exports.nextAnalysis = nextAnalysis;
9
+ exports.byTime = byTime;
10
+ exports.decideWindow = decideWindow;
11
+ exports.windowsFor = windowsFor;
12
+ exports.isScorable = isScorable;
13
+ exports.scoreOutcome = scoreOutcome;
14
+ exports.fileScores = fileScores;
15
+ const bounded_io_1 = require("../project/bounded-io");
16
+ const test_files_1 = require("../cpg/test-files");
17
+ /** A range with more commits than this is unattributable: read whole or not at all, never truncated. */
18
+ exports.WINDOW_COMMITS_MAX = 500;
19
+ /** What a project scores by default leaves out besides `.ax/` (configurable as `calibration.unscoredPaths`). */
20
+ exports.DEFAULT_UNSCORED = ['docs/', '*.md'];
21
+ /** The project's git: run in the project root, so `--relative` and `-- .` mean the project, not the repository. */
22
+ function projectGit(root) {
23
+ return (args) => {
24
+ const r = (0, bounded_io_1.gitOnce)(root, args, 'worktree');
25
+ const code = r.error?.code;
26
+ return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '', ...(r.error ? { error: { code: code ?? 'ERROR' } } : {}) };
27
+ };
28
+ }
29
+ const RS = '\x1e';
30
+ const US = '\x1f';
31
+ /** `git log -z --name-only --format=%x1e%H%x1f%cI` → commits, as git printed them; one naming no file is skipped. */
32
+ function parseGitLogZ(text) {
33
+ const out = [];
34
+ for (const record of text.split(RS)) {
35
+ if (record === '')
36
+ continue;
37
+ const end = record.indexOf('\0');
38
+ const header = end < 0 ? record : record.slice(0, end);
39
+ const sha = header.split(US)[0]?.trim();
40
+ if (!sha)
41
+ continue;
42
+ const files = (end < 0 ? '' : record.slice(end + 1)).replace(/^\n/, '').split('\0').filter((f) => f !== '');
43
+ if (files.length === 0)
44
+ continue;
45
+ out.push({ sha, files });
46
+ }
47
+ return out;
48
+ }
49
+ const NOT_A_REPO = /not a git repository/i;
50
+ const UNKNOWN_OBJECT = /not a valid (object|commit)|bad object|unknown revision|no such commit/i;
51
+ function failure(r) {
52
+ if (r.error)
53
+ return { ok: false, failed: r.error.code ?? 'error' };
54
+ if (r.status === 128 && NOT_A_REPO.test(r.stderr))
55
+ return { ok: false, unattributable: 'not-a-repository' };
56
+ return { ok: false, failed: `exit ${r.status ?? 'signal'}` };
57
+ }
58
+ /**
59
+ * The commits in `from..to` that touch the project, oldest first. `from` must be an ancestor of `to` (otherwise the
60
+ * two analyses were on different lines of history, or a HEAD was rewritten: `diverged`); the count is read before the
61
+ * log so a range over the cap is refused, not cut.
62
+ */
63
+ function rangeFiles(git, from, to) {
64
+ const anc = git(['merge-base', '--is-ancestor', from, to]);
65
+ if (anc.status === 1 && !anc.error)
66
+ return { ok: false, unattributable: 'diverged' };
67
+ if (anc.status !== 0 || anc.error) {
68
+ if (!anc.error && anc.status === 128 && UNKNOWN_OBJECT.test(anc.stderr))
69
+ return { ok: false, unattributable: 'diverged' };
70
+ return failure(anc);
71
+ }
72
+ const range = `${from}..${to}`;
73
+ const count = git(['rev-list', '--count', '--no-merges', range, '--', '.']);
74
+ if (count.status !== 0 || count.error)
75
+ return failure(count);
76
+ const n = Number.parseInt(count.stdout.trim(), 10);
77
+ if (!Number.isFinite(n))
78
+ return { ok: false, failed: 'unreadable count' };
79
+ if (n === 0)
80
+ return { ok: true, commits: [] };
81
+ if (n > exports.WINDOW_COMMITS_MAX)
82
+ return { ok: false, unattributable: 'too-wide' };
83
+ const log = git(['log', '-z', '--no-merges', '-M', '--relative', '--name-only', '--format=%x1e%H%x1f%cI', range, '--', '.']);
84
+ if (log.status !== 0 || log.error)
85
+ return failure(log);
86
+ return { ok: true, commits: parseGitLogZ(log.stdout).reverse() };
87
+ }
88
+ const instant = (a) => {
89
+ const t = Date.parse(a.recordedAt);
90
+ return Number.isFinite(t) ? t : Number.NEGATIVE_INFINITY;
91
+ };
92
+ const headOf = (a) => {
93
+ const h = a.graphBasis?.head;
94
+ return typeof h === 'string' && h !== '' ? h : undefined;
95
+ };
96
+ /** Whether two analyses asked the same thing: null when either did not record its request. */
97
+ function sameRequest(a, b) {
98
+ return typeof a.request === 'string' && typeof b.request === 'string' ? a.request === b.request : null;
99
+ }
100
+ /** The persisted analysis recorded next after `a` (open or closed), by time; undefined when `a` is the last. */
101
+ function nextAnalysis(sorted, a) {
102
+ const t = instant(a);
103
+ return sorted.find((b) => instant(b) > t);
104
+ }
105
+ /** Sorted by recorded time, then digest — the one order every reader of the windows uses. */
106
+ function byTime(all) {
107
+ return [...all].sort((x, y) => instant(x) - instant(y) || x.digest.localeCompare(y.digest));
108
+ }
109
+ /** The window of `a` given the analysis that ends it; `rangeOf` reads git. */
110
+ function decideWindow(a, next, rangeOf) {
111
+ if (!next)
112
+ return { kind: 'pending' };
113
+ const from = headOf(a), to = headOf(next);
114
+ if (!from || !to)
115
+ return { kind: 'unattributable', reason: 'no-head' };
116
+ const superseded = () => ({ kind: 'superseded', by: next.digest, sameRequest: sameRequest(a, next) });
117
+ if (from === to)
118
+ return superseded();
119
+ const r = rangeOf(from, to);
120
+ if (!r.ok)
121
+ return 'failed' in r ? { kind: 'failed', why: r.failed } : { kind: 'unattributable', reason: r.unattributable };
122
+ if (r.commits.length === 0)
123
+ return superseded();
124
+ const files = [...new Set(r.commits.flatMap((c) => c.files))].sort((x, y) => x.localeCompare(y));
125
+ return { kind: 'commits', from, to, shas: r.commits.map((c) => c.sha), files };
126
+ }
127
+ /** The window of every analysis in `open`, ended by the next analysis in `all`. */
128
+ function windowsFor(all, open, git) {
129
+ const sorted = byTime(all);
130
+ const out = new Map();
131
+ for (const a of open)
132
+ out.set(a.digest, decideWindow(a, nextAnalysis(sorted, a), (f, t) => rangeFiles(git, f, t)));
133
+ return out;
134
+ }
135
+ /** `.ax/` is never scorable; the rest by `unscored`: `dir/` a prefix, `*.ext` a suffix, anything else an exact path. */
136
+ function isScorable(file, unscored = exports.DEFAULT_UNSCORED) {
137
+ const f = file.replace(/\\/g, '/');
138
+ if (f.startsWith('.ax/'))
139
+ return false;
140
+ for (const u of unscored) {
141
+ if (u.endsWith('/') ? f.startsWith(u) : u.startsWith('*.') ? f.toLowerCase().endsWith(u.slice(1).toLowerCase()) : f === u)
142
+ return false;
143
+ }
144
+ return true;
145
+ }
146
+ function tally(actual, predicted) {
147
+ const p = new Set(predicted);
148
+ let hits = 0;
149
+ for (const f of new Set(actual))
150
+ if (p.has(f))
151
+ hits++;
152
+ return { hits, actual: new Set(actual).size, predicted: p.size };
153
+ }
154
+ const cutOf = (t) => ({ recall: t.actual === 0 ? 0 : t.hits / t.actual, precision: t.predicted === 0 ? 0 : t.hits / t.predicted });
155
+ /** Source files against `predicted.files` (and `rankedFiles`), test files against `predicted.tests`. */
156
+ function scoreOutcome(a, opts = {}) {
157
+ const actual = (a.outcome?.actualFiles ?? []).filter((f) => isScorable(f, opts.unscored));
158
+ const src = actual.filter((f) => !(0, test_files_1.isTestFile)(f.replace(/\\/g, '/')));
159
+ const tests = actual.filter((f) => (0, test_files_1.isTestFile)(f.replace(/\\/g, '/')));
160
+ const files = a.predicted.files;
161
+ const ranked = a.predicted.rankedFiles;
162
+ return {
163
+ source: src.length === 0 ? null : {
164
+ at10: cutOf(tally(src, files)),
165
+ ranked: ranked ? cutOf(tally(src, ranked)) : null,
166
+ ceiling: files.length === 0 ? 0 : Math.min(files.length, new Set(src).size) / files.length,
167
+ },
168
+ tests: tests.length === 0 ? null : cutOf(tally(tests, a.predicted.tests)),
169
+ };
170
+ }
171
+ const round = (x) => Math.round(x * 1e4) / 1e4;
172
+ const mean = (xs) => xs.length === 0 ? null : round(xs.reduce((s, x) => s + x, 0) / xs.length);
173
+ class Acc {
174
+ r = [];
175
+ p = [];
176
+ t = { hits: 0, actual: 0, predicted: 0 };
177
+ add(x) { const c = cutOf(x); this.r.push(c.recall); this.p.push(c.precision); this.t.hits += x.hits; this.t.actual += x.actual; this.t.predicted += x.predicted; }
178
+ macro() { return { recall: mean(this.r), precision: mean(this.p) }; }
179
+ micro() {
180
+ if (this.r.length === 0)
181
+ return { recall: null, precision: null };
182
+ return { recall: this.t.actual === 0 ? 0 : round(this.t.hits / this.t.actual), precision: this.t.predicted === 0 ? 0 : round(this.t.hits / this.t.predicted) };
183
+ }
184
+ }
185
+ /** Counts per window kind and reason, and macro and micro averages over the `commits` windows. */
186
+ function fileScores(artifacts, opts = {}) {
187
+ const windows = { commits: 0, superseded: { sameRequest: 0, otherRequest: 0, unknown: 0 }, unattributable: {}, unwindowed: 0 };
188
+ let noScorable = 0;
189
+ const at10 = new Acc(), ranked = new Acc(), tests = new Acc();
190
+ const ceilings = [];
191
+ for (const a of artifacts) {
192
+ const o = a.outcome;
193
+ if (!o)
194
+ continue;
195
+ const w = o.window;
196
+ if (w?.kind === 'superseded') {
197
+ if (w.sameRequest === true)
198
+ windows.superseded.sameRequest++;
199
+ else if (w.sameRequest === false)
200
+ windows.superseded.otherRequest++;
201
+ else
202
+ windows.superseded.unknown++;
203
+ continue;
204
+ }
205
+ if (w?.kind === 'unattributable' && w.reason) {
206
+ windows.unattributable[w.reason] = (windows.unattributable[w.reason] ?? 0) + 1;
207
+ continue;
208
+ }
209
+ if (w?.kind !== 'commits') {
210
+ windows.unwindowed++;
211
+ continue;
212
+ }
213
+ windows.commits++;
214
+ const s = scoreOutcome(a, opts);
215
+ if (!s.source && !s.tests) {
216
+ noScorable++;
217
+ continue;
218
+ }
219
+ const actual = o.actualFiles.filter((f) => isScorable(f, opts.unscored));
220
+ const src = actual.filter((f) => !(0, test_files_1.isTestFile)(f.replace(/\\/g, '/')));
221
+ if (s.source) {
222
+ at10.add(tally(src, a.predicted.files));
223
+ ceilings.push(s.source.ceiling);
224
+ if (a.predicted.rankedFiles)
225
+ ranked.add(tally(src, a.predicted.rankedFiles));
226
+ }
227
+ if (s.tests)
228
+ tests.add(tally(actual.filter((f) => (0, test_files_1.isTestFile)(f.replace(/\\/g, '/'))), a.predicted.tests));
229
+ }
230
+ return {
231
+ windows, scored: at10.r.length, noScorable,
232
+ at10: { macro: at10.macro(), micro: at10.micro(), ceiling: mean(ceilings) },
233
+ rankedN: ranked.r.length, ranked: { macro: ranked.macro(), micro: ranked.micro() },
234
+ testsN: tests.r.length, tests: { macro: tests.macro(), micro: tests.micro() },
235
+ };
236
+ }
@@ -454,7 +454,7 @@ exports.TOOL_SCHEMAS = {
454
454
  since: str('Baseline label to compare against when no git range is given (default `last-green`, recorded by a passing full test_run). Works with or without version control.'),
455
455
  mark: str('Baseline label to record when a full run passes (default `last-green`). Nothing is recorded for a red, skipped or scoped run.'),
456
456
  // @implements A-SPEC-128.4
457
- full: bool('Run the whole suite, whatever changed — the run the push gate accepts as evidence. It runs every execution unit (the root, and each directory with its own build or runner configuration) in its own directory, over the files git sees minus ax.config.json testRun.excludeDirs (a slash makes an entry a root-relative path; without one it is a directory name). Afterwards every detected test must have run (notExecuted) and every build root with code must have an executed test (untestedCode). A refusal is fix-tests, collect, rerun or environment. The budget defaults to 120 minutes. Refused together with base/head or mutate.'),
457
+ full: bool('Run the whole suite, whatever changed — the run the push gate accepts as evidence. It runs every execution unit (the root, and each directory with its own build or runner configuration) in its own directory, over the files git sees minus the directories the owner excludes in ax.config.json (an entry with a slash is a root-relative path; without one it is a directory name). Afterwards every detected test must have run (notExecuted) and every build root with code must have an executed test (untestedCode). A refusal is fix-tests, collect, rerun or environment. The budget defaults to 120 minutes. Refused together with base/head or mutate.'),
458
458
  mutate: str('T-SPEC id (e.g. T-SPEC-129.1). When set, runs that spec’s declared `kills` mutations against the A-SPEC’s source and reports which SURVIVED — a discriminating-power gap. Selective, opt-in; the ordinary run is skipped.'),
459
459
  workers: num('jest worker count, passed as `--maxWorkers`: an integer from 1 to 64; any other number is refused before the run, and null reads as omitted. Optional — omit to keep the project’s own setting. The answer’s `workers` is the count jest applied (null when none). Runners other than jest take no count; when a count was given and such a runner ran, the answer lists them in `workersIgnoredBy`; when nothing took it, `workersIgnored` says why (`mutate`, `no jest group`, `nothing ran`).'),
460
460
  timeoutMinutes: num('The time budget in minutes for each runner child of the run (jest, the other adapters, a mutation’s jest run): an integer from 1 to 180; when omitted or null, 30, or 120 for a full: true run; any other number is refused before the run. A run with a child past it ends "not judged": it records no evidence, and a full run records a full attempt that the push gate refuses. The answer and the evidence carry the applied value.'),
@@ -0,0 +1,4 @@
1
+ /** `--specs <v>` or `--specs=<v>` in words: the value, undefined when absent, 'unreadable' when named without a value. */
2
+ export declare function specsArgOf(words: readonly string[]): string | undefined | 'unreadable';
3
+ /** The same, from a hook command line as it stands in a settings file; a line the shell reader cannot split is unreadable. */
4
+ export declare function specsArgOfCommand(command: string): string | undefined | 'unreadable';
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.specsArgOf = specsArgOf;
4
+ exports.specsArgOfCommand = specsArgOfCommand;
5
+ // @implements A-SPEC-772.16
6
+ /**
7
+ * The spec store a Holmes hook command names with `--specs` — one reader for the hook (its argv) and for init (the
8
+ * command text in settings, read as the shell splits it). Review B of 772.15: init read `--specs "x"` with a regex, so a
9
+ * hand-written `--specs docs/specs` (which the hook reads) came back as the default store and a plain init reset it.
10
+ */
11
+ const shell_syntax_1 = require("../guardrail/shell-syntax");
12
+ /** `--specs <v>` or `--specs=<v>` in words: the value, undefined when absent, 'unreadable' when named without a value. */
13
+ function specsArgOf(words) {
14
+ for (let i = 0; i < words.length; i++) {
15
+ const w = words[i];
16
+ if (w.startsWith('--specs='))
17
+ return w.slice('--specs='.length) || 'unreadable';
18
+ if (w === '--specs') {
19
+ const v = words[i + 1];
20
+ return v === undefined || v === '' || v.startsWith('--') ? 'unreadable' : v;
21
+ }
22
+ }
23
+ return undefined;
24
+ }
25
+ /** The same, from a hook command line as it stands in a settings file; a line the shell reader cannot split is unreadable. */
26
+ function specsArgOfCommand(command) {
27
+ try {
28
+ const parsed = (0, shell_syntax_1.shellWords)(command, {}, undefined, null, true);
29
+ if (parsed.overflow || parsed.subs.length > 0 || parsed.commands.length !== 1)
30
+ return /--specs/.test(command) ? 'unreadable' : undefined;
31
+ const words = parsed.commands[0].words;
32
+ if (words.some((w) => !w.known))
33
+ return /--specs/.test(command) ? 'unreadable' : undefined;
34
+ return specsArgOf(words.map((w) => w.text));
35
+ }
36
+ catch {
37
+ return /--specs/.test(command) ? 'unreadable' : undefined;
38
+ }
39
+ }
@@ -0,0 +1,11 @@
1
+ export type InstallKind = 'repo' | 'local' | 'global' | 'npx' | 'unknown';
2
+ /** This package's root, from this module's place (src/holmes/project or dist/holmes/project). */
3
+ export declare function holmesPackageRoot(): string;
4
+ /** Where this package lives — the layout decides which package.json (if any) holds the policy. */
5
+ export declare function installKind(packageRoot: string, globalDir?: string, opts?: {
6
+ platform?: string;
7
+ }): InstallKind;
8
+ /** P, when the install is global by its prefix layout (not under npm's default prefix). */
9
+ export declare function installPrefix(packageRoot: string, globalDir?: string, opts?: {
10
+ platform?: string;
11
+ }): string | undefined;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.holmesPackageRoot = holmesPackageRoot;
37
+ exports.installKind = installKind;
38
+ exports.installPrefix = installPrefix;
39
+ // @implements A-SPEC-580.9
40
+ /**
41
+ * Where a holmes-kit install lives, read from its layout — the one reader every recovery surface asks (doctor,
42
+ * workspace_preflight, the named driver error, the MCP launcher). Moved from cli/native-deps (A-SPEC-580.9; the rules
43
+ * are A-SPEC-580.7's and 580.8's) so that rtm/ and project/ read it without importing cli/.
44
+ */
45
+ const fs = __importStar(require("node:fs"));
46
+ const path = __importStar(require("node:path"));
47
+ const HOLMES_PKG = '@holmes-lab/holmes-kit';
48
+ /** win32 shims npm writes beside a prefix's node_modules (A-SPEC-580.8). */
49
+ const WIN_SHIMS = ['holmes-kit.cmd', 'holmes-mcp.cmd', 'holmes-kit.ps1'];
50
+ /** This package's root, from this module's place (src/holmes/project or dist/holmes/project). */
51
+ function holmesPackageRoot() {
52
+ return path.resolve(__dirname, '..', '..', '..');
53
+ }
54
+ /** Where this package lives — the layout decides which package.json (if any) holds the policy. */
55
+ function installKind(packageRoot, globalDir, opts = {}) {
56
+ return layoutOf(packageRoot, globalDir, opts.platform ?? process.platform).kind;
57
+ }
58
+ /** P, when the install is global by its prefix layout (not under npm's default prefix). */
59
+ function installPrefix(packageRoot, globalDir, opts = {}) {
60
+ return layoutOf(packageRoot, globalDir, opts.platform ?? process.platform).prefix;
61
+ }
62
+ function layoutOf(packageRoot, globalDir, platform) {
63
+ const norm = packageRoot.replace(/\\/g, '/').replace(/\/+$/, '');
64
+ if (norm.split('/').includes('_npx'))
65
+ return { kind: 'npx' };
66
+ if (globalDir) {
67
+ const g = globalDir.replace(/\\/g, '/').replace(/\/+$/, '');
68
+ if (norm.toLowerCase().startsWith(`${g.toLowerCase()}/`))
69
+ return { kind: 'global' };
70
+ }
71
+ // the base as given (a win32 prefix keeps its backslashes) and as normalized
72
+ const given = /^(.*)[\\/]node_modules[\\/]@holmes-lab[\\/]holmes-kit[\\/]*$/.exec(packageRoot);
73
+ const m = /^(.*)\/node_modules\/@holmes-lab\/holmes-kit$/.exec(norm);
74
+ if (m === null || given === null)
75
+ return { kind: 'repo' };
76
+ // the layout decides, not the default prefix alone (`npm i -g --prefix P`): a project whose package.json names
77
+ // holmes-kit is local; else `<P>/lib/node_modules` with npm's `<P>/bin/holmes-kit` (POSIX), or a holmes-kit/holmes-mcp
78
+ // shim beside `<P>/node_modules` (win32), is a prefix's global layout
79
+ const base = m[1];
80
+ if (namesHolmes(path.join(base, 'package.json')))
81
+ return { kind: 'local' };
82
+ if (platform === 'win32') {
83
+ if (WIN_SHIMS.some((s) => isFile(path.join(base, s))))
84
+ return { kind: 'global', prefix: given[1] };
85
+ }
86
+ else if (/\/lib$/.test(base)) {
87
+ const P = base.slice(0, -'/lib'.length);
88
+ // npm's mark is a file (its bin link), not a directory of that name
89
+ if (isFile(path.join(P, 'bin', 'holmes-kit')))
90
+ return { kind: 'global', prefix: given[1].replace(/[\\/]lib$/, '') };
91
+ }
92
+ return { kind: 'local' };
93
+ }
94
+ const isFile = (p) => { try {
95
+ return fs.statSync(p).isFile();
96
+ }
97
+ catch {
98
+ return false;
99
+ } };
100
+ /** Whether a package.json names holmes-kit in any dependency section (optional and peer count too). */
101
+ function namesHolmes(file) {
102
+ try {
103
+ const j = JSON.parse(fs.readFileSync(file, 'utf8'));
104
+ return ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].some((k) => j[k]?.[HOLMES_PKG] !== undefined);
105
+ }
106
+ catch {
107
+ return false;
108
+ }
109
+ }
@@ -60,7 +60,10 @@ export type PolicyProblem = {
60
60
  kind: 'missing-from-lock';
61
61
  name: string;
62
62
  };
63
- /** The exact command npm 12 documents for a pinned approval. */
63
+ /**
64
+ * The exact command npm 12 documents for a pinned approval. @implements A-SPEC-580.4 — an unknown version (empty)
65
+ * gives the unpinned form, never a broken `name@`.
66
+ */
64
67
  export declare function approveCommand(name: string, version: string, npmBin?: string): string;
65
68
  /**
66
69
  * How `allowScripts` covers one package at one version, under npm 12's rules: a pinned `true`
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // @implements A-SPEC-595
2
+ // @implements A-SPEC-595, A-SPEC-580.4
3
3
  // @implements A-SPEC-579
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.PREBUILT_NATIVE_DEPS = exports.NATIVE_INSTALL_SCRIPT_DEPS = void 0;
@@ -42,9 +42,12 @@ exports.PREBUILT_NATIVE_DEPS = [
42
42
  'tree-sitter', 'tree-sitter-typescript', 'tree-sitter-python', 'tree-sitter-c-sharp',
43
43
  'tree-sitter-java', 'tree-sitter-go', 'tree-sitter-rust', 'tree-sitter-cpp',
44
44
  ];
45
- /** The exact command npm 12 documents for a pinned approval. */
45
+ /**
46
+ * The exact command npm 12 documents for a pinned approval. @implements A-SPEC-580.4 — an unknown version (empty)
47
+ * gives the unpinned form, never a broken `name@`.
48
+ */
46
49
  function approveCommand(name, version, npmBin = 'npm') {
47
- return `${npmBin} install-scripts approve ${name}@${version}`;
50
+ return version ? `${npmBin} install-scripts approve ${name}@${version}` : `${npmBin} install-scripts approve ${name}`;
48
51
  }
49
52
  /** Split an allowScripts key into its package name and optional pinned version (scopes kept). */
50
53
  function splitKey(key) {
@@ -0,0 +1,29 @@
1
+ export interface NativeRecovery {
2
+ /** The rebuild for a global install. */
3
+ global: string[];
4
+ /** Other ways for a global install: allow the script at install time, or persist the allowance in user config. */
5
+ globalAlternatives: string[];
6
+ /** A project install: approve the one script, then rebuild (never `--allow-scripts`). */
7
+ project: string[];
8
+ /** A-SPEC-580.10: a line to show beside the global commands ('' when none) — the prefix a placeholder stands for. */
9
+ note: string;
10
+ }
11
+ /** The word a command carries for a prefix outside the safe set (A-SPEC-580.10). */
12
+ export declare const PREFIX_PLACEHOLDER = "<PREFIX>";
13
+ /** What the surfaces that do not know npm's default prefix say instead of a `--prefix` command (A-SPEC-580.10). */
14
+ export declare const DOCTOR_PREFIX_SENTENCE = "Installed with a prefix (`npm i -g --prefix P`)? `holmes-kit doctor` prints the exact command.";
15
+ /**
16
+ * @implements A-SPEC-580.10 — the only paths put into a command: letters, digits, `_ . : / \ -`, not starting with
17
+ * `-`, not a bare drive (`C:` means that drive's current directory). Holmes builds no shell escaping — no quoting is
18
+ * right for bash, zsh, PowerShell 5.1/7, cmd and Git Bash at once (580.8 leaked `{}` and `$`, 580.9 `,` and `’`).
19
+ */
20
+ export declare function isSafePrefix(p: string, platform: string): boolean;
21
+ /** `packageVersion`, when known, pins the project approval (`pkg@version`); unknown or empty gives the unpinned form. */
22
+ export declare function nativeRecovery(a: {
23
+ platform: string;
24
+ packageName: string;
25
+ packageVersion?: string;
26
+ prefix?: string;
27
+ }): NativeRecovery;
28
+ /** Commands joined so each runs only if the one before succeeded, in the shell that platform's user has. */
29
+ export declare function joinCommands(cmds: readonly string[], platform: string): string;
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DOCTOR_PREFIX_SENTENCE = exports.PREFIX_PLACEHOLDER = void 0;
4
+ exports.isSafePrefix = isSafePrefix;
5
+ exports.nativeRecovery = nativeRecovery;
6
+ exports.joinCommands = joinCommands;
7
+ // @implements A-SPEC-580.4, A-SPEC-580.8, A-SPEC-580.9, A-SPEC-580.10, A-SPEC-580.11
8
+ /**
9
+ * The one source of the commands that rebuild a native dependency (better-sqlite3), in npm 12.1.0's measured syntax
10
+ * (Windows 11, npm 12.1.0, 2026-11-15):
11
+ * - `npm rebuild --help` lists `--allow-scripts <package-list>`, and the config docs say passing it "during a
12
+ * project-scoped `npm install`, `ci`, `update`, or `rebuild` is an error". So the flag goes on the global rebuild
13
+ * only; a project approves first (`npm install-scripts approve <pkg>`), then rebuilds.
14
+ * - Global installs "have no project `package.json` to write to"; the docs give the install-time flag or
15
+ * `npm config set allow-scripts=<pkg> --location=user` as the ways to allow the script there.
16
+ * - PowerShell 5.1 does not parse `&&`, so a win32 join checks `$LASTEXITCODE` (doctor's form).
17
+ *
18
+ * Pure and dependency-free beyond the npm binary name: the rtm layer, preflight, doctor and the MCP launcher read it.
19
+ */
20
+ const npx_bin_1 = require("./npx-bin");
21
+ const install_scripts_policy_1 = require("./install-scripts-policy");
22
+ const HOLMES_PKG = '@holmes-lab/holmes-kit';
23
+ /** The word a command carries for a prefix outside the safe set (A-SPEC-580.10). */
24
+ exports.PREFIX_PLACEHOLDER = '<PREFIX>';
25
+ /** What the surfaces that do not know npm's default prefix say instead of a `--prefix` command (A-SPEC-580.10). */
26
+ exports.DOCTOR_PREFIX_SENTENCE = 'Installed with a prefix (`npm i -g --prefix P`)? `holmes-kit doctor` prints the exact command.';
27
+ /**
28
+ * @implements A-SPEC-580.10 — the only paths put into a command: letters, digits, `_ . : / \ -`, not starting with
29
+ * `-`, not a bare drive (`C:` means that drive's current directory). Holmes builds no shell escaping — no quoting is
30
+ * right for bash, zsh, PowerShell 5.1/7, cmd and Git Bash at once (580.8 leaked `{}` and `$`, 580.9 `,` and `’`).
31
+ */
32
+ // @implements A-SPEC-580.11 — `\` is a path separator on win32 only; on POSIX shells it escapes, so such a P is a placeholder
33
+ function isSafePrefix(p, platform) {
34
+ return (platform === 'win32' ? /^[A-Za-z0-9_.:/\\-]+$/ : /^[A-Za-z0-9_.:/-]+$/).test(p) && !p.startsWith('-') && !/^[A-Za-z]:$/.test(p);
35
+ }
36
+ /** `packageVersion`, when known, pins the project approval (`pkg@version`); unknown or empty gives the unpinned form. */
37
+ // @implements A-SPEC-580.8 — `prefix` (a global install found by its prefix layout) puts `--prefix <P>` on the global
38
+ // commands: `-g` alone targets npm's default prefix.
39
+ // @implements A-SPEC-580.10 — a safe P goes in as it is; any other P becomes `<PREFIX>` and `note` shows P on its own.
40
+ function nativeRecovery(a) {
41
+ const npm = (0, npx_bin_1.npmBin)(a.platform);
42
+ const pkg = a.packageName;
43
+ // A-SPEC-580.9: an empty or `.` prefix is none (it would swallow the package name)
44
+ const P = a.prefix === undefined || a.prefix === '' || a.prefix === '.' ? undefined : a.prefix;
45
+ const safe = P !== undefined && isSafePrefix(P, a.platform);
46
+ const at = P === undefined ? '' : ` --prefix ${safe ? P : exports.PREFIX_PLACEHOLDER}`;
47
+ let note = '';
48
+ if (P !== undefined && !safe)
49
+ note = `prefix: ${P} — replace ${exports.PREFIX_PLACEHOLDER} with it, quoted by your shell's rules.`;
50
+ else if (safe && a.platform === 'win32' && P.includes('\\'))
51
+ note = 'The --prefix path is written for PowerShell or cmd — in Git Bash, quote the path.';
52
+ return {
53
+ global: [`${npm} rebuild -g${at} ${pkg} --foreground-scripts --allow-scripts=${pkg}`],
54
+ globalAlternatives: [`${npm} install -g${at} ${HOLMES_PKG} --allow-scripts=${pkg}`, `${npm} config set allow-scripts=${pkg} --location=user`],
55
+ project: [(0, install_scripts_policy_1.approveCommand)(pkg, a.packageVersion ?? '', npm), `${npm} rebuild ${pkg} --foreground-scripts`],
56
+ note,
57
+ };
58
+ }
59
+ /** Commands joined so each runs only if the one before succeeded, in the shell that platform's user has. */
60
+ function joinCommands(cmds, platform) {
61
+ return cmds.join(platform === 'win32' ? "; if ($LASTEXITCODE -ne 0) { throw 'Native dependency recovery failed' }; " : ' && ');
62
+ }
@@ -5,8 +5,14 @@ export declare function cleanSubprocessEnv(env?: NodeJS.ProcessEnv): NodeJS.Proc
5
5
  * never removed. Measured 2026-11-12/13: a full test_run in a HEAD worktree handed its children the checkout's path, and a
6
6
  * test that started a stdio server judged the live work tree's specs, not the snapshot the evidence names.
7
7
  */
8
+ /**
9
+ * @implements A-SPEC-714.1 — the variables that name another repository as a test corpus (replay-corpus.ts reads them as
10
+ * that repository's root). One declared list; a census test pins it against every source read of a *CORPUS* name.
11
+ */
12
+ export declare const EXTERNAL_CORPUS_ENV_KEYS: readonly string[];
8
13
  export declare function cleanTestEnv(env?: NodeJS.ProcessEnv, opts?: {
9
14
  projectDir?: string;
15
+ externalAccess?: 'forbidden';
10
16
  }): NodeJS.ProcessEnv;
11
17
  /**
12
18
  * Where a project begins, for a harness that must not require version control.
@@ -33,13 +33,13 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.canonicalPath = exports.MARKER = void 0;
36
+ exports.canonicalPath = exports.MARKER = exports.EXTERNAL_CORPUS_ENV_KEYS = void 0;
37
37
  exports.cleanSubprocessEnv = cleanSubprocessEnv;
38
38
  exports.cleanTestEnv = cleanTestEnv;
39
39
  exports.isProjectDir = isProjectDir;
40
40
  exports.sameCanonicalDirectory = sameCanonicalDirectory;
41
41
  exports.resolveProjectRoot = resolveProjectRoot;
42
- // @implements A-SPEC-205, A-SPEC-627, A-SPEC-734, A-SPEC-102.31, A-SPEC-102.32, A-SPEC-794.47, A-SPEC-794.57, A-SPEC-794.58, A-SPEC-794.119
42
+ // @implements A-SPEC-205, A-SPEC-627, A-SPEC-734, A-SPEC-102.31, A-SPEC-102.32, A-SPEC-794.47, A-SPEC-794.57, A-SPEC-794.58, A-SPEC-794.119, A-SPEC-714.1
43
43
  // @implements A-SPEC-128
44
44
  const fs = __importStar(require("node:fs"));
45
45
  const path = __importStar(require("node:path"));
@@ -115,10 +115,22 @@ const TEST_SCRUB_KEYS = new Set(['HOLMES_SPECS', 'HOLMES_GATE_BYPASS', 'HOLMES_M
115
115
  * never removed. Measured 2026-11-12/13: a full test_run in a HEAD worktree handed its children the checkout's path, and a
116
116
  * test that started a stdio server judged the live work tree's specs, not the snapshot the evidence names.
117
117
  */
118
+ /**
119
+ * @implements A-SPEC-714.1 — the variables that name another repository as a test corpus (replay-corpus.ts reads them as
120
+ * that repository's root). One declared list; a census test pins it against every source read of a *CORPUS* name.
121
+ */
122
+ exports.EXTERNAL_CORPUS_ENV_KEYS = ['HOLMES_CONSUMER_CORPUS', 'HOLMES_GEMINI_CLI_CORPUS'];
123
+ /** A corpus variable added without updating the list is still caught by its name. */
124
+ const EXTERNAL_CORPUS_ENV_RULE = /^HOLMES_[A-Z0-9_]+_CORPUS$/;
118
125
  function cleanTestEnv(env = process.env, opts = {}) {
119
126
  const cleaned = cleanSubprocessEnv(env);
127
+ const forbidden = opts.externalAccess === 'forbidden';
120
128
  for (const k of Object.keys(cleaned)) {
121
- if (TEST_SCRUB_KEYS.has(k.toUpperCase()))
129
+ const upper = k.toUpperCase();
130
+ if (TEST_SCRUB_KEYS.has(upper))
131
+ delete cleaned[k];
132
+ // @implements A-SPEC-714.1 — an external-access-forbidden run (the release lane) carries no external corpus root
133
+ else if (forbidden && (exports.EXTERNAL_CORPUS_ENV_KEYS.includes(upper) || EXTERNAL_CORPUS_ENV_RULE.test(upper)))
122
134
  delete cleaned[k];
123
135
  }
124
136
  if (opts.projectDir !== undefined) {
@@ -0,0 +1,20 @@
1
+ /** The receipt's file name, beside the runtime registry (`<home>/.holmes/runtime/` by default). */
2
+ export declare const RECEIPT_FILE = "installation.json";
3
+ /** The digest a receipt row records for a file's content. */
4
+ export declare const receiptDigest: (content: string | Buffer) => string;
5
+ /**
6
+ * The last well-formed row whose path is one of `paths`, null when no row names the path. `'malformed'` when `files` is
7
+ * not an array.
8
+ *
9
+ * Two policies, on purpose (A-SPEC-794.133):
10
+ * - strict (the default, principle 7): any row that is not `{path: string, digest: string}` spoils the receipt. Its answer
11
+ * only excuses, so it fails closed.
12
+ * - tolerant (the cli ownership reader): a malformed row is skipped. Disowning on an unrelated bad row would let init
13
+ * rewrite a reviewed wiring file (A-SPEC-752.8).
14
+ */
15
+ export declare function lastReceiptRow(files: unknown, paths: readonly string[], opts?: {
16
+ tolerant?: boolean;
17
+ }): {
18
+ path: string;
19
+ digest: string;
20
+ } | null | 'malformed';