@holmes-lab/holmes-kit 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +312 -0
  2. package/README.md +79 -5
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/approve-context.js +4 -3
  5. package/dist/holmes/cli/approve.js +22 -12
  6. package/dist/holmes/cli/autonomy.d.ts +21 -0
  7. package/dist/holmes/cli/autonomy.js +35 -5
  8. package/dist/holmes/cli/doctor.js +58 -6
  9. package/dist/holmes/cli/index.js +394 -267
  10. package/dist/holmes/cli/init.js +17 -6
  11. package/dist/holmes/cli/interactive-prompt.d.ts +39 -2
  12. package/dist/holmes/cli/interactive-prompt.js +98 -16
  13. package/dist/holmes/cli/ledger-witness.d.ts +61 -0
  14. package/dist/holmes/cli/ledger-witness.js +212 -0
  15. package/dist/holmes/cli/playbook-skills.d.ts +3 -56
  16. package/dist/holmes/cli/playbook-skills.js +26 -349
  17. package/dist/holmes/config/config.d.ts +21 -0
  18. package/dist/holmes/config/config.js +22 -3
  19. package/dist/holmes/governance/approval-queue.d.ts +65 -1
  20. package/dist/holmes/governance/approval-queue.js +279 -9
  21. package/dist/holmes/governance/autonomous-shell.d.ts +13 -1
  22. package/dist/holmes/governance/autonomous-shell.js +157 -4
  23. package/dist/holmes/governance/autonomy.d.ts +216 -0
  24. package/dist/holmes/governance/autonomy.js +1162 -10
  25. package/dist/holmes/governance/install-manifest.d.ts +7 -4
  26. package/dist/holmes/governance/install-manifest.js +144 -14
  27. package/dist/holmes/governance/ledger-witness.d.ts +63 -0
  28. package/dist/holmes/governance/ledger-witness.js +296 -0
  29. package/dist/holmes/governance/provenance-chain.d.ts +8 -1
  30. package/dist/holmes/governance/provenance-chain.js +23 -4
  31. package/dist/holmes/governance/push-gate-runner.d.ts +2 -0
  32. package/dist/holmes/governance/push-gate-runner.js +40 -3
  33. package/dist/holmes/governance/push-gate.d.ts +13 -2
  34. package/dist/holmes/governance/push-gate.js +106 -14
  35. package/dist/holmes/governance/recorded-pairs.d.ts +4 -0
  36. package/dist/holmes/governance/recorded-pairs.js +25 -1
  37. package/dist/holmes/governance/session-context.d.ts +7 -0
  38. package/dist/holmes/governance/session-context.js +34 -6
  39. package/dist/holmes/guardrail/advisory-line.d.ts +102 -0
  40. package/dist/holmes/guardrail/advisory-line.js +718 -0
  41. package/dist/holmes/guardrail/anchor-scope-text.d.ts +9 -0
  42. package/dist/holmes/guardrail/anchor-scope-text.js +7 -0
  43. package/dist/holmes/guardrail/command-traits.d.ts +102 -0
  44. package/dist/holmes/guardrail/command-traits.js +379 -0
  45. package/dist/holmes/guardrail/fixtures/manager-builtins.json +23 -0
  46. package/dist/holmes/guardrail/fixtures/npm-commands.json +7 -0
  47. package/dist/holmes/guardrail/impact-gate.d.ts +6 -0
  48. package/dist/holmes/guardrail/impact-gate.js +32 -5
  49. package/dist/holmes/guardrail/outward-acts.d.ts +47 -0
  50. package/dist/holmes/guardrail/outward-acts.js +1102 -0
  51. package/dist/holmes/guardrail/refusal-codes.js +8 -1
  52. package/dist/holmes/guardrail/refusal-templates.d.ts +15 -0
  53. package/dist/holmes/guardrail/refusal-templates.js +71 -0
  54. package/dist/holmes/guardrail/risk-classifier.d.ts +22 -6
  55. package/dist/holmes/guardrail/risk-classifier.js +12 -118
  56. package/dist/holmes/guardrail/shell-lexer.d.ts +69 -0
  57. package/dist/holmes/guardrail/shell-lexer.js +567 -0
  58. package/dist/holmes/guardrail/write-target.js +7 -1
  59. package/dist/holmes/hooks/pre-tool-use.d.ts +71 -0
  60. package/dist/holmes/hooks/pre-tool-use.js +1466 -14
  61. package/dist/holmes/hooks/session-start.js +27 -1
  62. package/dist/holmes/hooks/stop.d.ts +7 -0
  63. package/dist/holmes/hooks/stop.js +39 -2
  64. package/dist/holmes/mcp/elicit-approval.d.ts +0 -21
  65. package/dist/holmes/mcp/elicit-approval.js +5 -2
  66. package/dist/holmes/mcp/handlers/approval-ask.js +3 -2
  67. package/dist/holmes/mcp/handlers/entity-integration.d.ts +1 -1
  68. package/dist/holmes/mcp/handlers/entity-integration.js +9 -6
  69. package/dist/holmes/mcp/handlers/entity-renumber.js +2 -1
  70. package/dist/holmes/mcp/handlers/entity-store.js +7 -2
  71. package/dist/holmes/mcp/handlers/maintenance-analysis.d.ts +13 -0
  72. package/dist/holmes/mcp/handlers/maintenance-analysis.js +59 -2
  73. package/dist/holmes/mcp/handlers/operator-inspection.d.ts +2 -0
  74. package/dist/holmes/mcp/handlers/operator-inspection.js +25 -4
  75. package/dist/holmes/mcp/handlers/spec-approval.d.ts +3 -1
  76. package/dist/holmes/mcp/handlers/spec-approval.js +28 -10
  77. package/dist/holmes/mcp/handlers/spec-lifecycle.js +10 -7
  78. package/dist/holmes/mcp/handlers/test-execution.d.ts +470 -3
  79. package/dist/holmes/mcp/handlers/test-execution.js +201 -21
  80. package/dist/holmes/mcp/handlers.d.ts +473 -8
  81. package/dist/holmes/mcp/handlers.js +6 -1
  82. package/dist/holmes/mcp/maintenance-analyze.d.ts +5 -0
  83. package/dist/holmes/mcp/maintenance-analyze.js +4 -2
  84. package/dist/holmes/mcp/maintenance-evidence.d.ts +9 -0
  85. package/dist/holmes/mcp/maintenance-evidence.js +4 -1
  86. package/dist/holmes/mcp/tool-schemas.js +16 -10
  87. package/dist/holmes/project/baseline.d.ts +15 -2
  88. package/dist/holmes/project/baseline.js +11 -6
  89. package/dist/holmes/project/bounded-io.d.ts +1 -0
  90. package/dist/holmes/project/bounded-io.js +4 -2
  91. package/dist/holmes/project/change-source.d.ts +4 -0
  92. package/dist/holmes/project/change-source.js +13 -5
  93. package/dist/holmes/project/playbook-reference.d.ts +50 -0
  94. package/dist/holmes/project/playbook-reference.js +259 -0
  95. package/dist/holmes/project/playbook-skill-states.d.ts +94 -0
  96. package/dist/holmes/project/playbook-skill-states.js +396 -0
  97. package/dist/holmes/project/root.d.ts +9 -1
  98. package/dist/holmes/project/root.js +26 -3
  99. package/dist/holmes/project/running-package.d.ts +15 -0
  100. package/dist/holmes/project/running-package.js +87 -0
  101. package/dist/holmes/review/evidence-mode.d.ts +21 -0
  102. package/dist/holmes/review/evidence-mode.js +33 -0
  103. package/dist/holmes/review/head-worktree.d.ts +55 -0
  104. package/dist/holmes/review/head-worktree.js +329 -0
  105. package/dist/holmes/review/mrp.js +13 -3
  106. package/dist/holmes/review/run-provenance.d.ts +45 -0
  107. package/dist/holmes/review/run-provenance.js +314 -0
  108. package/dist/holmes/review/test-evidence.d.ts +174 -0
  109. package/dist/holmes/review/test-evidence.js +330 -2
  110. package/dist/holmes/review/test-reports.d.ts +94 -0
  111. package/dist/holmes/review/test-reports.js +382 -0
  112. package/dist/holmes/review/test-runner.d.ts +178 -65
  113. package/dist/holmes/review/test-runner.js +551 -319
  114. package/dist/holmes/review/test-units.d.ts +159 -0
  115. package/dist/holmes/review/test-units.js +814 -0
  116. package/dist/holmes/spec/entity-integration-transaction.d.ts +19 -2
  117. package/dist/holmes/spec/entity-integration-transaction.js +68 -7
  118. package/package.json +5 -2
  119. package/playbooks/publish/PLAYBOOK.md +2 -1
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The one place the full-run tokens live (A-SPEC-128.4 §5): the mode a full run records, the provenance input that says
3
+ * a baseline was verified by such a run, and the call a refusal names. The write side, the predicate, the trust check, the
4
+ * push gate and the merge-ready package all read these, so the spelling cannot drift between them.
5
+ */
6
+ export declare const FULL_MODE: "full";
7
+ /** @implements A-SPEC-128.5 — the mode a full record and a full anchor carry, as a type. */
8
+ export type FullMode = typeof FULL_MODE;
9
+ /** The provenance input a baseline anchor carries for the mode of the run that verified it. */
10
+ export declare function modeAnchor(mode: FullMode): string;
11
+ /** @implements A-SPEC-128.4 — the one call that clears a refusal: the refusal names it, and running it reaches allow. */
12
+ export declare const FULL_RUN_CALL = "test_run({root, full: true})";
13
+ /** @implements A-SPEC-128.5 — the default budget of a full run, and the ceiling a next call may ask for. */
14
+ export declare const FULL_RUN_DEFAULT_MINUTES = 120;
15
+ export declare const RUN_MINUTES_CEILING = 180;
16
+ /**
17
+ * @implements A-SPEC-128.8 — the one builder of what follows a stopped full run: the call with a doubled budget (up to the
18
+ * ceiling), keeping the worker count, or at the ceiling the sentence that says so. The test_run answer's `nextCall` and the
19
+ * push gate's stopped-attempt refusal both read it, so the two cannot drift (A L1, B M1).
20
+ */
21
+ export declare function nextFullCall(timeoutMinutes: number, workers?: number | null): string;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RUN_MINUTES_CEILING = exports.FULL_RUN_DEFAULT_MINUTES = exports.FULL_RUN_CALL = exports.FULL_MODE = void 0;
4
+ exports.modeAnchor = modeAnchor;
5
+ exports.nextFullCall = nextFullCall;
6
+ // @implements A-SPEC-128.4, A-SPEC-128.5, A-SPEC-128.8, A-SPEC-128.9
7
+ /**
8
+ * The one place the full-run tokens live (A-SPEC-128.4 §5): the mode a full run records, the provenance input that says
9
+ * a baseline was verified by such a run, and the call a refusal names. The write side, the predicate, the trust check, the
10
+ * push gate and the merge-ready package all read these, so the spelling cannot drift between them.
11
+ */
12
+ exports.FULL_MODE = 'full';
13
+ /** The provenance input a baseline anchor carries for the mode of the run that verified it. */
14
+ function modeAnchor(mode) {
15
+ return `mode:${mode}`;
16
+ }
17
+ /** @implements A-SPEC-128.4 — the one call that clears a refusal: the refusal names it, and running it reaches allow. */
18
+ exports.FULL_RUN_CALL = 'test_run({root, full: true})';
19
+ /** @implements A-SPEC-128.5 — the default budget of a full run, and the ceiling a next call may ask for. */
20
+ exports.FULL_RUN_DEFAULT_MINUTES = 120;
21
+ exports.RUN_MINUTES_CEILING = 180;
22
+ /**
23
+ * @implements A-SPEC-128.8 — the one builder of what follows a stopped full run: the call with a doubled budget (up to the
24
+ * ceiling), keeping the worker count, or at the ceiling the sentence that says so. The test_run answer's `nextCall` and the
25
+ * push gate's stopped-attempt refusal both read it, so the two cannot drift (A L1, B M1).
26
+ */
27
+ function nextFullCall(timeoutMinutes, workers) {
28
+ if (timeoutMinutes >= exports.RUN_MINUTES_CEILING) {
29
+ // @implements A-SPEC-128.9 — E4: no exclusion is suggested (following one hid a red suite); split it or ask the owner
30
+ return `budget ceiling reached (${exports.RUN_MINUTES_CEILING} minutes) — the suite does not finish within it; split the suite or ask the owner how this repository is verified`;
31
+ }
32
+ return `test_run({root, full: true, timeoutMinutes: ${Math.min(exports.RUN_MINUTES_CEILING, timeoutMinutes * 2)}${typeof workers === 'number' ? `, workers: ${workers}` : ''}})`;
33
+ }
@@ -0,0 +1,55 @@
1
+ /** L1: `<pid>-<base36 time>-<base36 random>`; the pid is the owner, so ownership needs no record that can be forged. */
2
+ export declare const ID_RE: RegExp;
3
+ export interface HeadWorktree {
4
+ /** The worktree's absolute path: the run's root. */
5
+ dir: string;
6
+ createMs: number;
7
+ prepareMs: number;
8
+ /** Removes the worktree through git, by its exact path; null, or the reason git could not (A-SPEC-128.15 L5); never throws. */
9
+ close(): string | null;
10
+ }
11
+ export type OpenedWorktree = {
12
+ ok: true;
13
+ wt: HeadWorktree;
14
+ } | {
15
+ ok: false;
16
+ reason: string;
17
+ };
18
+ export interface WorktreeOptions {
19
+ /** ax.config.json testRun.prepare as read from HEAD (the worktree) — never guessed. */
20
+ prepareOf: (dir: string) => string[] | undefined;
21
+ /** Runs one prepare child within `budgetMs`; throws like execFileSync on a non-zero exit or the bound. */
22
+ run: (cmd: string, args: string[], cwd: string, budgetMs: number) => string;
23
+ /** L4: the run's own budget in milliseconds (the handler owns the budget), which bounds the prepare too. */
24
+ prepareBudgetMs: number;
25
+ /** A-SPEC-128.16 W1: ax.config.json testRun.linkWalk as read from HEAD (the worktree); the default when absent. */
26
+ walkBoundOf?: (dir: string) => {
27
+ entries: number;
28
+ seconds: number;
29
+ } | undefined;
30
+ }
31
+ /** L1: the per-user base and this repository's key directory (sha256 of git's common directory); null without git. */
32
+ export declare function runKeyDir(root: string, tmpdir?: string): string | null;
33
+ /**
34
+ * E1, A-SPEC-128.15 O2: every symbolic link at any depth of a linked node_modules (links are resolved, never followed).
35
+ * The first that lands inside the work tree outside every node_modules is a reason naming it; a walk past its bound is a
36
+ * reason too; otherwise null.
37
+ */
38
+ export declare const LINK_WALK: {
39
+ entries: number;
40
+ seconds: number;
41
+ };
42
+ export declare function workTreeLink(rootReal: string, nmReal: string, label: string, bound?: {
43
+ entries: number;
44
+ seconds: number;
45
+ }): string | null;
46
+ /**
47
+ * L4: a package-manager install would write the work tree's node_modules through the link. A heuristic (A-SPEC-128.15
48
+ * L6): flag values are skipped, npx and corepack are read through, and a shell's command string is split into commands.
49
+ */
50
+ export declare function installPrepare(argv: string[]): boolean;
51
+ /**
52
+ * W1, L1–L4: a detached worktree of `head` under this repository's key directory, prepared (node_modules linked,
53
+ * testRun.prepare run) and ready to run; or the reason it could not be made.
54
+ */
55
+ export declare function openHeadWorktree(root: string, head: string, opts: WorktreeOptions): OpenedWorktree;
@@ -0,0 +1,329 @@
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.LINK_WALK = exports.ID_RE = void 0;
37
+ exports.runKeyDir = runKeyDir;
38
+ exports.workTreeLink = workTreeLink;
39
+ exports.installPrepare = installPrepare;
40
+ exports.openHeadWorktree = openHeadWorktree;
41
+ // @implements A-SPEC-128.13, A-SPEC-128.14, A-SPEC-128.15
42
+ /**
43
+ * A full test_run asks "is this commit green", so it runs on the commit: a clean detached worktree of HEAD
44
+ * (A-SPEC-128.13 W1, W2). Untracked, ignored, modified, assume-unchanged and skip-worktree files of the work tree never
45
+ * reach the run. This module owns the worktree's whole lifetime: where it lives, how it is made, the linked
46
+ * node_modules, the declared prepare command, and its removal. Every failure is a reason the caller reports as
47
+ * environment — nothing here throws to the caller.
48
+ *
49
+ * A-SPEC-128.14 moves it out of the repository, to `<tmp>/holmes-run-<user>/<key>/<id>/`: inside the repository jest
50
+ * collected the copy, pytest climbed to the work tree's untracked configuration, and an agent shell that `cd`ed there
51
+ * locked its session. Removal is git's alone and by exact path: holmes never deletes a directory and never prunes.
52
+ */
53
+ const crypto = __importStar(require("node:crypto"));
54
+ const fs = __importStar(require("node:fs"));
55
+ const os = __importStar(require("node:os"));
56
+ const path = __importStar(require("node:path"));
57
+ const node_child_process_1 = require("node:child_process");
58
+ const root_1 = require("../project/root");
59
+ const run_provenance_1 = require("./run-provenance");
60
+ const bounded_io_1 = require("../project/bounded-io");
61
+ /** L1: `<pid>-<base36 time>-<base36 random>`; the pid is the owner, so ownership needs no record that can be forged. */
62
+ exports.ID_RE = /^[1-9][0-9]*-[0-9a-z]+-[0-9a-z]{1,8}$/;
63
+ const git = (cwd, args) => (0, node_child_process_1.execFileSync)('git', ['-C', cwd, ...args], {
64
+ encoding: 'utf8', timeout: bounded_io_1.GIT_TIMEOUT_MS * 4, maxBuffer: 64 * 1024 * 1024, env: (0, root_1.cleanSubprocessEnv)(), stdio: ['ignore', 'pipe', 'pipe'],
65
+ });
66
+ const firstLine = (s) => (s.split('\n').find((l) => l.trim() !== '') ?? '').trim().slice(0, 200);
67
+ const alive = (pid) => { try {
68
+ process.kill(pid, 0);
69
+ return true;
70
+ }
71
+ catch (e) {
72
+ return e.code === 'EPERM';
73
+ } };
74
+ const real = (p) => { try {
75
+ return fs.realpathSync(p);
76
+ }
77
+ catch {
78
+ return null;
79
+ } };
80
+ const inside = (child, parent) => { const rel = path.relative(parent, child); return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel); };
81
+ /** L1: the per-user base and this repository's key directory (sha256 of git's common directory); null without git. */
82
+ function runKeyDir(root, tmpdir = os.tmpdir()) {
83
+ let common;
84
+ try {
85
+ common = real(path.resolve(root, git(root, ['rev-parse', '--git-common-dir']).trim()));
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ const base = real(tmpdir);
91
+ if (!common || !base)
92
+ return null;
93
+ const who = typeof process.getuid === 'function' ? String(process.getuid()) : os.userInfo().username.replace(/[^A-Za-z0-9_.-]/g, '_');
94
+ // A-SPEC-128.15 L5: `holmes-headwt-`, never `holmes-run-` — run exec sweeps `<tmp>/holmes-run-*` (run-exec.ts)
95
+ return path.join(base, `holmes-headwt-${who}`, crypto.createHash('sha256').update(common).digest('hex').slice(0, 16));
96
+ }
97
+ /** L1: an existing directory must be a real directory of this user; a missing one is made 0700. */
98
+ function ownDirectory(dir) {
99
+ let st = null;
100
+ try {
101
+ st = fs.lstatSync(dir);
102
+ }
103
+ catch {
104
+ st = null;
105
+ }
106
+ if (st === null) {
107
+ try {
108
+ fs.mkdirSync(dir, { mode: 0o700 });
109
+ return null;
110
+ }
111
+ catch (e) {
112
+ return `${dir} could not be made: ${firstLine(String(e.message ?? e))}`;
113
+ }
114
+ }
115
+ if (st.isSymbolicLink() || !st.isDirectory())
116
+ return `${dir} is a link or not a directory — holmes makes nothing there`;
117
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid())
118
+ return `${dir} belongs to another user — holmes makes nothing there`;
119
+ if (typeof process.getuid === 'function' && (st.mode & 0o022) !== 0)
120
+ return `${dir} is group- or world-writable — holmes makes nothing there`;
121
+ return null;
122
+ }
123
+ /** The worktree paths git lists for this repository, exactly as git spells them. */
124
+ function listedWorktrees(root) {
125
+ try {
126
+ return git(root, ['worktree', 'list', '--porcelain']).split('\n').filter((l) => l.startsWith('worktree ')).map((l) => l.slice('worktree '.length));
127
+ }
128
+ catch {
129
+ return [];
130
+ }
131
+ }
132
+ /** L3: git removes a worktree it lists at exactly this path — and its entry, when the directory is already gone. */
133
+ function removeListed(root, dir, noHooks) {
134
+ if (!listedWorktrees(root).includes(dir))
135
+ return null;
136
+ try {
137
+ git(root, ['-c', `core.hooksPath=${noHooks}`, 'worktree', 'remove', '--force', dir]);
138
+ return null;
139
+ }
140
+ catch (e) {
141
+ const err = e;
142
+ return `HEAD's worktree ${dir} could not be removed: ${firstLine(err.stderr || err.message || String(e))}`;
143
+ }
144
+ }
145
+ /** L3: leftovers — listed, a direct child of the key directory, id-shaped, and their pid gone. Nothing else. */
146
+ function removeStale(root, keyDir, noHooks) {
147
+ for (const w of listedWorktrees(root)) {
148
+ const id = path.basename(w);
149
+ if (path.dirname(w) !== keyDir || !exports.ID_RE.test(id) || alive(Number(id.split('-')[0])))
150
+ continue;
151
+ removeListed(root, w, noHooks);
152
+ }
153
+ }
154
+ /**
155
+ * E1, A-SPEC-128.15 O2: every symbolic link at any depth of a linked node_modules (links are resolved, never followed).
156
+ * The first that lands inside the work tree outside every node_modules is a reason naming it; a walk past its bound is a
157
+ * reason too; otherwise null.
158
+ */
159
+ exports.LINK_WALK = { entries: 500_000, seconds: 20 };
160
+ function workTreeLink(rootReal, nmReal, label, bound = exports.LINK_WALK) {
161
+ const t0 = Date.now();
162
+ const stack = [[nmReal, label]];
163
+ let seen = 0;
164
+ while (stack.length > 0) {
165
+ const [d, l] = stack.pop();
166
+ let kids = [];
167
+ // A-SPEC-128.16 W1: a directory the walk cannot read is not proven clean
168
+ try {
169
+ kids = fs.readdirSync(d, { withFileTypes: true });
170
+ }
171
+ catch (e) {
172
+ return `${l} cannot be read (${e.code ?? 'error'}) — HEAD's run cannot prove it loads no work-tree code through it`;
173
+ }
174
+ for (const k of kids) {
175
+ if (++seen > bound.entries || Date.now() - t0 > bound.seconds * 1000) {
176
+ return `${label} is too large to check within ${bound.entries} entries or ${bound.seconds} s — raise ax.config.json testRun.linkWalk ({ "entries": …, "seconds": … }) to let HEAD's run prove it loads no work-tree code`;
177
+ }
178
+ const abs = path.join(d, k.name);
179
+ if (k.isSymbolicLink()) {
180
+ const to = real(abs);
181
+ if (to !== null && inside(to, rootReal) && !path.relative(rootReal, to).split(path.sep).includes('node_modules')) {
182
+ return `${l}/${k.name} links into the work tree — HEAD's run would load uncommitted code through it (a workspace package); 0.40.x does not evidence a linked workspace`;
183
+ }
184
+ }
185
+ else if (k.isDirectory())
186
+ stack.push([abs, `${l}/${k.name}`]);
187
+ }
188
+ }
189
+ return null;
190
+ }
191
+ /** W2: link every gitignored node_modules of the work tree into the worktree at the same place, after E1's check. */
192
+ function linkNodeModules(root, dir, bound = exports.LINK_WALK) {
193
+ let ignored = [];
194
+ try {
195
+ ignored = git(root, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z']).split('\0').filter(Boolean);
196
+ }
197
+ catch {
198
+ ignored = [];
199
+ }
200
+ const roots = ignored.map((p) => p.replace(/\/+$/, ''))
201
+ .filter((p) => path.posix.basename(p) === 'node_modules' && !p.split('/').slice(0, -1).includes('node_modules'));
202
+ const rootReal = real(root) ?? root;
203
+ for (const rel of roots) {
204
+ const source = real(path.join(root, ...rel.split('/')));
205
+ if (source === null)
206
+ continue;
207
+ const reaching = workTreeLink(rootReal, source, rel, bound);
208
+ if (reaching !== null)
209
+ return reaching;
210
+ const target = path.join(dir, ...rel.split('/'));
211
+ if (fs.existsSync(target))
212
+ continue;
213
+ try {
214
+ fs.mkdirSync(path.dirname(target), { recursive: true });
215
+ fs.symlinkSync(source, target, process.platform === 'win32' ? 'junction' : 'dir');
216
+ }
217
+ catch (e) {
218
+ return `node_modules could not be linked into HEAD's worktree (${rel}): ${firstLine(String(e.message ?? e))}`;
219
+ }
220
+ }
221
+ return null;
222
+ }
223
+ const MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
224
+ const INSTALLS = new Set(['install', 'i', 'ci', 'add']);
225
+ const VALUE_FLAGS = new Set(['--prefix', '-C', '--cwd', '--dir', '--filter', '--workspace', '-w']);
226
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'cmd']);
227
+ /**
228
+ * L4: a package-manager install would write the work tree's node_modules through the link. A heuristic (A-SPEC-128.15
229
+ * L6): flag values are skipped, npx and corepack are read through, and a shell's command string is split into commands.
230
+ */
231
+ function installPrepare(argv) {
232
+ // A-SPEC-128.16 I1: a version suffix (pnpm@8) names the same tool
233
+ const tool = path.basename(argv[0] ?? '').replace(/\.(cmd|exe|ps1)$/i, '').replace(/(.)@[^/]*$/, '$1').toLowerCase();
234
+ if (SHELLS.has(tool)) {
235
+ return argv.slice(1).filter((a) => !/^[-/]/.test(a)).join(' ').split(/&&|\|\||[;|&\n]/).some((c) => installPrepare(c.trim().split(/\s+/).filter(Boolean)));
236
+ }
237
+ if (tool === 'npx' || tool === 'corepack') {
238
+ const i = argv.findIndex((a, n) => n > 0 && !a.startsWith('-'));
239
+ return i > 0 && installPrepare(argv.slice(i));
240
+ }
241
+ if (!MANAGERS.has(tool))
242
+ return false;
243
+ let verb;
244
+ for (let i = 1; i < argv.length; i++) {
245
+ if (VALUE_FLAGS.has(argv[i])) {
246
+ i++;
247
+ continue;
248
+ }
249
+ if (argv[i].startsWith('-'))
250
+ continue;
251
+ verb = argv[i];
252
+ // A-SPEC-128.16 I1: `npm exec -- pnpm install` / `pnpm exec pnpm install` read through to the tool they start
253
+ if (verb === 'exec' || verb === 'x' || verb === 'dlx') {
254
+ let rest = argv.slice(i + 1);
255
+ while (rest.length > 0 && rest[0] !== '--' && rest[0].startsWith('-'))
256
+ rest = rest.slice(1);
257
+ return installPrepare(rest[0] === '--' ? rest.slice(1) : rest);
258
+ }
259
+ break;
260
+ }
261
+ return verb === undefined ? tool === 'yarn' : INSTALLS.has(verb);
262
+ }
263
+ /**
264
+ * W1, L1–L4: a detached worktree of `head` under this repository's key directory, prepared (node_modules linked,
265
+ * testRun.prepare run) and ready to run; or the reason it could not be made.
266
+ */
267
+ function openHeadWorktree(root, head, opts) {
268
+ const keyDir = runKeyDir(root);
269
+ if (keyDir === null)
270
+ return { ok: false, reason: 'the run location could not be resolved (git common directory or the OS temporary directory)' };
271
+ const refused = ownDirectory(path.dirname(keyDir)) ?? ownDirectory(keyDir);
272
+ if (refused !== null)
273
+ return { ok: false, reason: refused };
274
+ const noHooks = path.join(keyDir, '.no-hooks'); // never created: git reads a missing hooks directory as no hooks
275
+ removeStale(root, keyDir, noHooks);
276
+ const id = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8) || '0'}`;
277
+ const dir = path.join(keyDir, id);
278
+ // A-SPEC-128.15 L5: the reason git could not remove it, and an empty key directory is not left behind
279
+ const close = () => {
280
+ const left = removeListed(root, dir, noHooks);
281
+ try {
282
+ fs.rmdirSync(keyDir);
283
+ }
284
+ catch { /* not empty, or gone */ }
285
+ return left;
286
+ };
287
+ const t0 = Date.now();
288
+ try {
289
+ // L2: no checkout by add (no hook, no sparsity inherited), then the whole commit with sparsity off for this call only
290
+ git(root, ['-c', `core.hooksPath=${noHooks}`, 'worktree', 'add', '--no-checkout', '--detach', '--quiet', dir, head]);
291
+ git(dir, ['-c', 'core.sparseCheckout=false', '-c', 'core.sparseCheckoutCone=false', '-c', `core.hooksPath=${noHooks}`, 'reset', '--hard', '-q', head]);
292
+ // A-SPEC-128.15 L5: sparsity inherited through the worktree's own config is turned off there, and only there
293
+ try {
294
+ if (git(dir, ['config', '--bool', 'extensions.worktreeConfig']).trim() === 'true' && git(dir, ['config', '--worktree', '--bool', 'core.sparseCheckout']).trim() === 'true') {
295
+ git(dir, ['config', '--worktree', 'core.sparseCheckout', 'false']);
296
+ }
297
+ }
298
+ catch { /* not sparse through its own config */ }
299
+ }
300
+ catch (e) {
301
+ close();
302
+ const err = e;
303
+ return { ok: false, reason: `HEAD's worktree could not be made: ${firstLine(err.stderr || err.message || String(e))}` };
304
+ }
305
+ const createMs = Date.now() - t0;
306
+ // A-SPEC-128.16 E4: after linking, node is asked where HEAD's package names resolve (NODE_PATH included)
307
+ const linked = linkNodeModules(root, dir, opts.walkBoundOf?.(dir) ?? exports.LINK_WALK) ?? (0, run_provenance_1.nodeNamesResolveToWorkTree)(dir, root, (0, root_1.cleanTestEnv)());
308
+ if (linked !== null) {
309
+ close();
310
+ return { ok: false, reason: linked };
311
+ }
312
+ const t1 = Date.now();
313
+ const prepare = opts.prepareOf(dir);
314
+ if (prepare && prepare.length > 0) {
315
+ if (installPrepare(prepare)) {
316
+ close();
317
+ return { ok: false, reason: `testRun.prepare installs packages (${prepare.join(' ')}) — node_modules is the work tree's, linked; an install would change it. Declare a build, not an install` };
318
+ }
319
+ try {
320
+ opts.run(prepare[0], prepare.slice(1), dir, opts.prepareBudgetMs);
321
+ }
322
+ catch (e) {
323
+ const err = e;
324
+ close();
325
+ return { ok: false, reason: `testRun.prepare failed (${prepare.join(' ')}): ${firstLine(err.stderr || err.stdout || err.message || String(e))}` };
326
+ }
327
+ }
328
+ return { ok: true, wt: { dir, createMs, prepareMs: Date.now() - t1, close } };
329
+ }
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.buildMrp = buildMrp;
37
- // @implements A-SPEC-102.6, A-SPEC-102.7
37
+ // @implements A-SPEC-102.6, A-SPEC-102.7, A-SPEC-128.2, A-SPEC-128.5, A-SPEC-128.6
38
38
  /**
39
39
  * @implements A-SPEC-102.6 — the merge-ready package: one artefact a person reads before approving a merge. It names
40
40
  * the spec chain behind the changed files, the test evidence for the head, the review verdict, and — explicitly —
@@ -44,6 +44,7 @@ const fs = __importStar(require("node:fs"));
44
44
  const path = __importStar(require("node:path"));
45
45
  const spec_parser_1 = require("../spec/spec-parser");
46
46
  const test_evidence_1 = require("./test-evidence");
47
+ const evidence_mode_1 = require("./evidence-mode");
47
48
  const verdicts_1 = require("./verdicts");
48
49
  function loadSpecs(dir, out = new Map(), depth = 0) {
49
50
  if (depth > 6)
@@ -89,8 +90,12 @@ function buildMrp(root, base, head) {
89
90
  return { aspec: id, status: a?.status ?? 'missing', tspec: tspec ? { id: tspec.id, status: tspec.status } : null, hspec: link(hId), req: link(reqId) };
90
91
  });
91
92
  const ev = (0, test_evidence_1.readTestEvidence)(root);
93
+ // @implements A-SPEC-128.2 — merge readiness reads full evidence only, as the push gate does
94
+ const fullEv = !!ev && (0, test_evidence_1.isFullEvidence)(ev);
95
+ // @implements A-SPEC-128.6 — through THE push-evidence predicate the writer and the gate read
96
+ const problem = (0, test_evidence_1.pushEvidenceProblem)(ev, range.head);
92
97
  const evidence = ev
93
- ? { head: ev.head, fresh: ev.head === range.head, passed: ev.passed,
98
+ ? { head: ev.head, fresh: problem === null, passed: ev.passed,
94
99
  executed: [...aspecs].reduce((n, id) => n + (ev.executedByAspec[id] ?? 0), 0) }
95
100
  : { fresh: false };
96
101
  const review = (0, verdicts_1.gateRange)(root, range.base, range.head, {});
@@ -111,8 +116,13 @@ function buildMrp(root, base, head) {
111
116
  else if (c.req.status !== 'approved')
112
117
  missing.push(`${c.req.id} is ${c.req.status}`);
113
118
  }
114
- if (!evidence.fresh || evidence.passed !== true)
119
+ // @implements A-SPEC-128.5 — the same call the push gate names
120
+ if (ev && !fullEv)
121
+ missing.push(`test evidence is not from a full run (${(0, test_evidence_1.evidenceKind)(ev)}) — run ${evidence_mode_1.FULL_RUN_CALL} at ${range.head}`);
122
+ else if (!ev || ev.head !== range.head || ev.passed !== true)
115
123
  missing.push(`test evidence is not fresh or not green for ${range.head}`);
124
+ else if (problem !== null)
125
+ missing.push(`test evidence is not push evidence: ${problem} — run ${evidence_mode_1.FULL_RUN_CALL} at ${range.head}`);
116
126
  missing.push(...review.reasons);
117
127
  const unique = [...new Set(missing)];
118
128
  return { base: range.base, head: range.head, files, chain, evidence, review, coverage: 'unmeasured', mutation: 'unmeasured', ready: unique.length === 0, missing: unique };
@@ -0,0 +1,45 @@
1
+ export declare const PLUGIN = "holmes_provenance";
2
+ /** Runs one child within the run's budget and process group (the runner's runBounded); throws on a non-zero exit. */
3
+ export type BoundedExec = (cmd: string, args: string[], opts: {
4
+ cwd: string;
5
+ env: NodeJS.ProcessEnv;
6
+ }) => string;
7
+ export declare const PYTHON_NAMES = 20000;
8
+ /**
9
+ * A-SPEC-128.17 N2: every dotted module name of HEAD's python files — each identifier suffix of each path, and each
10
+ * package on the way (namespace packages included), so no layout (src/, python/, packages/x/src/) is missed. `over` when
11
+ * the names pass the cap (testRun.pythonNames).
12
+ */
13
+ export declare function pythonNames(runRoot: string, cap?: number): {
14
+ names: string[];
15
+ over: boolean;
16
+ };
17
+ /**
18
+ * E3: where the interpreter resolves HEAD's names, asked in HEAD's worktree with the unit's environment; a reason or null.
19
+ * `-P` (python 3.11+) keeps the current directory off sys.path from the first import, so HEAD's own json.py or
20
+ * sysconfig.py never runs in the question; an older python fails it, and that is environment. The answer is written to
21
+ * a file, so nothing a .pth or an exit handler prints can be read as it (review A of 128.16, L1 and L2).
22
+ */
23
+ export declare function pythonEnvironmentResolves(python: string, cwd: string, names: string[], workTree: string, headTree: string, env: NodeJS.ProcessEnv, exec?: BoundedExec): string | null;
24
+ /** O1: the first loaded file inside the work tree, outside HEAD's worktree and every library directory, as a reason; or null. */
25
+ export declare function loadedFromWorkTree(recordFile: string, workTree: string, headTree: string): string | null;
26
+ /**
27
+ * The provenance of one full pytest unit in HEAD's worktree: P1's pinned configuration and confcutdir, E3's environment
28
+ * answer (`refused` when the environment resolves HEAD's names to the work tree), and O1's plugin with its judgement.
29
+ */
30
+ export declare function pytestRunProvenance(tmpDir: string, run: {
31
+ root: string;
32
+ sourceRoot: string;
33
+ }, unitCwd: string, python: string, env: NodeJS.ProcessEnv, exec?: BoundedExec): {
34
+ refused: string | null;
35
+ args: string[];
36
+ confcutdir: string;
37
+ env: (base: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
38
+ judge: (passed: boolean) => string | null;
39
+ };
40
+ /**
41
+ * E4: HEAD's package names (every package.json of the worktree outside node_modules), each resolved as node resolves a
42
+ * bare name — `node_modules/<name>` up the ancestors of every package directory, then each NODE_PATH entry. One that
43
+ * lands inside the work tree, outside HEAD's worktree and every node_modules, is a reason; otherwise null.
44
+ */
45
+ export declare function nodeNamesResolveToWorkTree(headTree: string, workTree: string, env: NodeJS.ProcessEnv): string | null;