@holmes-lab/holmes-kit 0.35.23 → 0.35.25

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 (44) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/README.md +5 -3
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/agent-registry.d.ts +7 -0
  5. package/dist/holmes/cli/agent-registry.js +10 -0
  6. package/dist/holmes/cli/agents.d.ts +2 -2
  7. package/dist/holmes/cli/agents.js +196 -6
  8. package/dist/holmes/cli/approve.js +4 -4
  9. package/dist/holmes/cli/doctor.d.ts +22 -0
  10. package/dist/holmes/cli/doctor.js +160 -11
  11. package/dist/holmes/cli/index.js +23 -1
  12. package/dist/holmes/cli/init.d.ts +24 -0
  13. package/dist/holmes/cli/init.js +55 -3
  14. package/dist/holmes/cli/runtime-binding-approval.js +3 -2
  15. package/dist/holmes/cli/runtime-binding.d.ts +10 -1
  16. package/dist/holmes/cli/runtime-binding.js +139 -2
  17. package/dist/holmes/cli/scratch.d.ts +12 -0
  18. package/dist/holmes/cli/scratch.js +20 -0
  19. package/dist/holmes/governance/approval-queue.js +4 -3
  20. package/dist/holmes/guardrail/impact-gate.d.ts +2 -0
  21. package/dist/holmes/guardrail/impact-gate.js +34 -11
  22. package/dist/holmes/guardrail/risk-classifier.js +14 -2
  23. package/dist/holmes/guardrail/risk-types.d.ts +1 -0
  24. package/dist/holmes/hooks/adapters/antigravity.js +3 -2
  25. package/dist/holmes/hooks/heartbeat.d.ts +47 -0
  26. package/dist/holmes/hooks/heartbeat.js +247 -0
  27. package/dist/holmes/hooks/pre-tool-use.d.ts +1 -1
  28. package/dist/holmes/hooks/pre-tool-use.js +46 -3
  29. package/dist/holmes/hooks/stop.d.ts +3 -1
  30. package/dist/holmes/hooks/stop.js +16 -4
  31. package/dist/holmes/mcp/elicit-approval.js +4 -4
  32. package/dist/holmes/mcp/handlers/runtime-binding-tool.d.ts +28 -0
  33. package/dist/holmes/mcp/handlers/runtime-binding-tool.js +42 -9
  34. package/dist/holmes/mcp/handlers/spec-approval.js +3 -2
  35. package/dist/holmes/mcp/handlers/workspace-preflight.js +2 -2
  36. package/dist/holmes/mcp/handlers.d.ts +27 -1
  37. package/dist/holmes/project/npx-bin.d.ts +26 -0
  38. package/dist/holmes/project/npx-bin.js +272 -2
  39. package/dist/holmes/project/scratch-root.d.ts +12 -0
  40. package/dist/holmes/project/scratch-root.js +132 -0
  41. package/dist/holmes/project/workspace-preflight.d.ts +3 -0
  42. package/dist/holmes/project/workspace-preflight.js +42 -2
  43. package/dist/holmes/runtime/dispatch.js +8 -4
  44. package/package.json +1 -1
@@ -0,0 +1,247 @@
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.OBSERVED_WITHIN_MS = exports.HEARTBEAT_DIR = void 0;
37
+ exports.hookHarnessOf = hookHarnessOf;
38
+ exports.recordHookHeartbeat = recordHookHeartbeat;
39
+ exports.readHookHeartbeats = readHookHeartbeats;
40
+ exports.observationOf = observationOf;
41
+ exports.hookWiringFiles = hookWiringFiles;
42
+ exports.ageText = ageText;
43
+ // @implements A-SPEC-772.1, A-SPEC-772.5, A-SPEC-772.6, A-SPEC-772.7, A-SPEC-772.8, A-SPEC-772.9
44
+ /**
45
+ * Evidence that a harness's hooks actually ran in a workspace.
46
+ *
47
+ * Measured 2026-10-17: a Codex session in holmes-lab could not tell it was governed — the dispatcher routed it to the
48
+ * release build and its Stop hook had run, but nothing recorded either, so `workspace_preflight` and
49
+ * `runtime-binding status` could only say "unknown"/"unverified".
50
+ *
51
+ * The harness is told from the hook INPUT, never from the environment: a Codex hook launched from a Claude Code
52
+ * terminal received `CLAUDECODE=1`. Claude sends `prompt_id` and no `turn_id`; Codex sends `turn_id` and no
53
+ * `prompt_id`. Holmes's own launchers (the runtime dispatcher, the Antigravity adapter) name the harness explicitly in
54
+ * `HOLMES_HOOK_HARNESS`; when that and the shape both speak they must agree.
55
+ *
56
+ * Recording is off the decision path: one stat per call, at most one small write per harness and event per minute,
57
+ * and every failure is swallowed.
58
+ *
59
+ * @implements A-SPEC-772.5 — an observation is INFORMATION ONLY. Anyone who can run a hook program can produce one, so
60
+ * no gate, approval or seal may read it as authority.
61
+ */
62
+ const fs = __importStar(require("node:fs"));
63
+ const os = __importStar(require("node:os"));
64
+ const path = __importStar(require("node:path"));
65
+ // @implements A-SPEC-772.6 — the import-free registry: this module runs inside every hook call.
66
+ const agent_registry_1 = require("../cli/agent-registry");
67
+ exports.HEARTBEAT_DIR = path.join('.ax', 'state', 'hook-heartbeat');
68
+ const EVENTS = ['pre-tool-use', 'stop'];
69
+ const SCHEMA = 'holmes-hook-heartbeat/1';
70
+ const WRITE_EVERY_MS = 60_000;
71
+ exports.OBSERVED_WITHIN_MS = 24 * 3600_000;
72
+ const MAX_RECORD_BYTES = 4096;
73
+ const FUTURE_TOLERANCE_MS = 5 * 60_000;
74
+ const validBuildId = (id) => typeof id === 'string' && id.length > 0 && id.length <= 200 && !/[\x00-\x1f\x7f]/.test(id);
75
+ const isLink = (p) => { try {
76
+ return fs.lstatSync(p).isSymbolicLink();
77
+ }
78
+ catch {
79
+ return false;
80
+ } };
81
+ const isAgent = (v) => typeof v === 'string' && agent_registry_1.AGENTS.includes(v);
82
+ /** The harness a hook call belongs to, or null when the evidence is absent or contradicts itself. */
83
+ function hookHarnessOf(input, env) {
84
+ const o = input !== null && typeof input === 'object' ? input : {};
85
+ const hasPrompt = typeof o.prompt_id === 'string' && o.prompt_id !== '';
86
+ const hasTurn = typeof o.turn_id === 'string' && o.turn_id !== '';
87
+ const shape = hasPrompt && !hasTurn ? 'claude' : hasTurn && !hasPrompt ? 'codex' : null;
88
+ const named = env.HOLMES_HOOK_HARNESS;
89
+ if (named !== undefined && named !== '') {
90
+ if (!isAgent(named))
91
+ return null;
92
+ if (shape !== null && shape !== named)
93
+ return null;
94
+ return named;
95
+ }
96
+ return shape;
97
+ }
98
+ /** The running package's build id (dist/.build-id next to this compiled file), or 'unknown'. */
99
+ function runningBuildId() {
100
+ try {
101
+ const id = fs.readFileSync(path.resolve(__dirname, '..', '..', '.build-id'), 'utf8').trim();
102
+ return id && id.length <= 200 && !/[\x00-\x1f\x7f]/.test(id) ? id : 'unknown';
103
+ }
104
+ catch {
105
+ return 'unknown';
106
+ }
107
+ }
108
+ function recordHookHeartbeat(opts) {
109
+ try {
110
+ if (typeof opts.root !== 'string' || !EVENTS.includes(opts.event))
111
+ return;
112
+ // @implements A-SPEC-772.9 — a test that spawns the real kernel inside the repository turns recording off; an
113
+ // observation is information only, so the switch changes no decision.
114
+ if (opts.env.HOLMES_HEARTBEAT === 'off')
115
+ return;
116
+ if (!fs.existsSync(path.join(opts.root, '.ax')))
117
+ return;
118
+ const harness = hookHarnessOf(opts.input, opts.env);
119
+ if (harness === null)
120
+ return;
121
+ const now = opts.now ?? Date.now();
122
+ const dir = path.join(opts.root, exports.HEARTBEAT_DIR);
123
+ // @implements A-SPEC-772.5 — never write through a link out of the workspace.
124
+ if (isLink(path.join(opts.root, '.ax', 'state')) || isLink(dir))
125
+ return;
126
+ const file = path.join(dir, `${harness}.${opts.event}.json`);
127
+ // @implements A-SPEC-772.5 — a record "modified in the future" (clock stepped back, restored file) does not block.
128
+ try {
129
+ const age = now - fs.statSync(file).mtimeMs;
130
+ if (age >= 0 && age < WRITE_EVERY_MS)
131
+ return;
132
+ }
133
+ catch { /* no record yet */ }
134
+ const mode = opts.env.HOLMES_HOOK_MODE === 'development' || opts.env.HOLMES_HOOK_MODE === 'release' ? opts.env.HOLMES_HOOK_MODE : 'unknown';
135
+ const beat = { schema: SCHEMA, harness, event: opts.event, at: new Date(now).toISOString(), buildId: opts.buildId ?? runningBuildId(), mode };
136
+ fs.mkdirSync(dir, { recursive: true });
137
+ const tmp = path.join(dir, `.${harness}.${opts.event}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
138
+ fs.writeFileSync(tmp, JSON.stringify(beat), { flag: 'wx' });
139
+ try {
140
+ fs.renameSync(tmp, file);
141
+ }
142
+ catch {
143
+ try {
144
+ fs.rmSync(tmp, { force: true });
145
+ }
146
+ catch { /* ignore */ }
147
+ }
148
+ // The rate limit reads the record's mtime: make it the observation time, so an injected clock is honoured too.
149
+ try {
150
+ const t = new Date(now);
151
+ fs.utimesSync(file, t, t);
152
+ }
153
+ catch { /* ignore */ }
154
+ }
155
+ catch { /* recording never affects a hook */ }
156
+ }
157
+ function readBeat(file, harness, event, now) {
158
+ try {
159
+ const st = fs.lstatSync(file);
160
+ if (!st.isFile() || st.size > MAX_RECORD_BYTES)
161
+ return undefined;
162
+ const b = JSON.parse(fs.readFileSync(file, 'utf8'));
163
+ if (b?.schema !== SCHEMA || b.harness !== harness || b.event !== event)
164
+ return undefined;
165
+ // @implements A-SPEC-772.5 — a record from the future, or a build id the writer would refuse, is not evidence.
166
+ if (typeof b.at !== 'string' || !Number.isFinite(Date.parse(b.at)) || Date.parse(b.at) > now + FUTURE_TOLERANCE_MS || !validBuildId(b.buildId))
167
+ return undefined;
168
+ // @implements A-SPEC-772.7 — a record written as `direct` (before this repair) carried no routing evidence either.
169
+ if (b.mode === 'direct')
170
+ b.mode = 'unknown';
171
+ if (!['development', 'release', 'unknown'].includes(b.mode))
172
+ return undefined;
173
+ return b;
174
+ }
175
+ catch {
176
+ return undefined;
177
+ }
178
+ }
179
+ function readHookHeartbeats(root, now = Date.now()) {
180
+ const out = Object.fromEntries(agent_registry_1.AGENTS.map((a) => [a, {}]));
181
+ for (const harness of agent_registry_1.AGENTS) {
182
+ for (const event of EVENTS) {
183
+ const b = readBeat(path.join(root, exports.HEARTBEAT_DIR, `${harness}.${event}.json`), harness, event, now);
184
+ if (b)
185
+ out[harness][event] = b;
186
+ }
187
+ }
188
+ return out;
189
+ }
190
+ /** The latest PreToolUse or Stop record of a harness: observed within 24 h, stale beyond, never without one. */
191
+ function observationOf(beats, harness, now = Date.now(), wiringFiles, event) {
192
+ // @implements A-SPEC-772.8 — `event` narrows to one hook (the PreToolUse gate is what pass means).
193
+ const latest = EVENTS.filter((e) => event === undefined || e === event).map((e) => beats[harness]?.[e]).filter((b) => b !== undefined)
194
+ .sort((a, b) => Date.parse(b.at) - Date.parse(a.at))[0];
195
+ if (!latest)
196
+ return { state: 'never' };
197
+ const ageMs = now - Date.parse(latest.at);
198
+ const base = { event: latest.event, at: latest.at, buildId: latest.buildId, mode: latest.mode, ageMs };
199
+ // @implements A-SPEC-772.6 — a hook observed before its wiring changed proves nothing about the wiring now (setup
200
+ // rewrites hooks Codex must re-trust; /hooks can switch one off).
201
+ if (wiringFiles && Date.parse(latest.at) < latestMtime(wiringFiles, now))
202
+ return { state: 'stale', ...base, reason: 'wiring changed since' };
203
+ return { state: ageMs <= exports.OBSERVED_WITHIN_MS ? 'observed' : 'stale', ...base };
204
+ }
205
+ function latestMtime(files, now = Date.now()) {
206
+ let max = -Infinity;
207
+ // @implements A-SPEC-772.7 — a wiring file "modified in the future" (restored, clock skew) would make every record stale forever.
208
+ for (const f of files) {
209
+ try {
210
+ const m = fs.statSync(f).mtimeMs;
211
+ if (m <= now + FUTURE_TOLERANCE_MS)
212
+ max = Math.max(max, m);
213
+ }
214
+ catch { /* absent */ }
215
+ }
216
+ return max;
217
+ }
218
+ /**
219
+ * @implements A-SPEC-772.6 — the files whose change can stop a harness running its Holmes hooks in `root`: what Claude,
220
+ * Codex and Antigravity read their hooks from (Codex's workspace trust too; its user-level trust file is excluded).
221
+ */
222
+ function hookWiringFiles(root, harness, env = process.env) {
223
+ // @implements A-SPEC-772.7 — the home other readers use (os.homedir()) unless the caller names one.
224
+ const home = (process.platform === 'win32' ? env.USERPROFILE : env.HOME) || os.homedir();
225
+ if (harness === 'claude') {
226
+ const user = env.CLAUDE_CONFIG_DIR ? path.resolve(env.CLAUDE_CONFIG_DIR) : path.join(home, '.claude');
227
+ return [path.join(user, 'settings.json'), path.join(root, '.claude', 'settings.json'), path.join(root, '.claude', 'settings.local.json')];
228
+ }
229
+ if (harness === 'codex') {
230
+ // @implements A-SPEC-772.7 — the user-level config.toml is machine-shared: Codex and its desktop app rewrite it for
231
+ // other repositories and plugin syncs (measured), which flipped every workspace's observation.
232
+ // @implements A-SPEC-772.8 — the workspace's own Codex files are in. Known limit: a user-level `/hooks` switch-off
233
+ // or plugin disable lives in that shared file and is not detected here.
234
+ const codex = env.CODEX_HOME ? path.resolve(env.CODEX_HOME) : path.join(home, '.codex');
235
+ return [path.join(codex, 'hooks.json'), path.join(root, '.codex', 'hooks.json'), path.join(root, '.codex', 'config.toml'),
236
+ path.join(root, '.holmes', 'codex-plugin', 'holmes-kit', 'hooks.json')];
237
+ }
238
+ return [path.join(home, '.gemini', 'config', 'hooks.json'), path.join(root, '.agents', 'hooks.json')];
239
+ }
240
+ /** "3 min", "5 h", "2 d" — for a stale observation's detail. */
241
+ function ageText(ms) {
242
+ if (ms < 3600_000)
243
+ return `${Math.max(1, Math.round(ms / 60_000))} min`;
244
+ if (ms < 48 * 3600_000)
245
+ return `${Math.round(ms / 3600_000)} h`;
246
+ return `${Math.round(ms / 86_400_000)} d`;
247
+ }
@@ -3,7 +3,7 @@ import { PatchTarget } from '../guardrail/write-target';
3
3
  import { Approval } from '../guardrail/risk-gate';
4
4
  import { RiskAction, RiskAssessment, RmSignal } from '../guardrail/risk-types';
5
5
  import { type PreEditEvidenceMode } from '../guardrail/impact-gate';
6
- export declare function resolveRmSignals(command: string, cwd: string, projectRoot?: string, specsDir?: string): Record<string, RmSignal> | undefined;
6
+ export declare function resolveRmSignals(command: string, cwd: string, projectRoot?: string, specsDir?: string, scratchTmpdir?: string): Record<string, RmSignal> | undefined;
7
7
  /**
8
8
  * @implements A-SPEC-149
9
9
  * The out-of-band approval channel, read at the ENTRY only. `evaluateHook` no longer calls this on
@@ -48,7 +48,7 @@ exports.gateErrorDecision = gateErrorDecision;
48
48
  exports.wiredSpecsDir = wiredSpecsDir;
49
49
  exports.evaluateHook = evaluateHook;
50
50
  exports.readSpecsSync = readSpecsSync;
51
- // @implements A-SPEC-753.3, A-SPEC-134.2, A-SPEC-278, A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2
51
+ // @implements A-SPEC-753.3, A-SPEC-773, A-SPEC-773.1, A-SPEC-773.2, A-SPEC-134.2,A-SPEC-278,A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2, A-SPEC-772.1
52
52
  const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
53
53
  // @implements A-SPEC-549.3 — the hook's deny reasons are English here; hooks-english.test.ts drives
54
54
  // evaluateHook in this file to prove it.
@@ -57,6 +57,7 @@ const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
57
57
  // @implements A-SPEC-194, A-SPEC-195
58
58
  const registry_1 = require("../messages/registry");
59
59
  const root_1 = require("../project/root");
60
+ const scratch_root_1 = require("../project/scratch-root");
60
61
  const fs = __importStar(require("node:fs"));
61
62
  const path = __importStar(require("node:path"));
62
63
  const os = __importStar(require("node:os"));
@@ -119,7 +120,44 @@ function unanswered(targets) {
119
120
  }
120
121
  return Object.keys(out).length ? out : undefined;
121
122
  }
122
- function resolveRmSignals(command, cwd, projectRoot, specsDir) {
123
+ /**
124
+ * @implements A-SPEC-773 — the git signals, plus `scratch: true` for each literal absolute target whose real path lies
125
+ * strictly under the trusted Holmes scratch root (owner decision 2026-10-17). Added whether or not the cwd is in a
126
+ * repository; the trust check runs once per call. `scratchTmpdir` is the temporary directory to read the root under
127
+ * (tests; the hook passes nothing and reads os.tmpdir()).
128
+ */
129
+ /** `rm`, option words, an optional `--`, then absolute targets — no separator, redirection, expansion or escape. */
130
+ const SCRATCH_TARGETS_MAX = 64;
131
+ const PLAIN_RM = /^rm(?:[ \t]+-[A-Za-z]+)*(?:[ \t]+--)?(?:[ \t]+\/[A-Za-z0-9._/-]+)+$/;
132
+ function resolveRmSignals(command, cwd, projectRoot, specsDir, scratchTmpdir) {
133
+ const signals = gitRmSignals(command, cwd, projectRoot, specsDir);
134
+ // @implements A-SPEC-773.1 — only a command that IS one plain rm. Round 1 (2026-10-17): `xargs`/`parallel` add
135
+ // targets at run time, an alias does, and a link or move earlier in the same command changes the real path after it
136
+ // was judged — 15 harmful commands were allowed with the root and refused without it.
137
+ if (!PLAIN_RM.test(command.trim()))
138
+ return signals;
139
+ const absolute = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_1.joinShellText)(command))])]
140
+ .filter((raw) => { const t = raw.replace(/^["']/, '').replace(/["']$/, ''); return path.isAbsolute(t) && !/[^A-Za-z0-9._/-]/.test(t) && !t.split('/').includes('..'); });
141
+ // @implements A-SPEC-773.2 — bounded like the git signals (round 8 of A-SPEC-728): at most 64 targets, each at most
142
+ // 4,096 characters and 256 components; past that, no target gets the signal and today's verdict stands.
143
+ if (absolute.length === 0 || absolute.length > SCRATCH_TARGETS_MAX)
144
+ return signals;
145
+ if (absolute.some((t) => t.length > 4096 || t.split('/').length > 256))
146
+ return signals;
147
+ const root = (0, scratch_root_1.trustedScratchRoot)(scratchTmpdir);
148
+ if (root === null)
149
+ return signals;
150
+ const out = { ...(signals ?? {}) };
151
+ let added = false;
152
+ for (const raw of absolute) {
153
+ if (!(0, scratch_root_1.isUnderScratchRoot)(raw.replace(/^["']/, '').replace(/["']$/, ''), root))
154
+ continue;
155
+ out[raw] = { ...(out[raw] ?? {}), scratch: true };
156
+ added = true;
157
+ }
158
+ return added ? out : signals;
159
+ }
160
+ function gitRmSignals(command, cwd, projectRoot, specsDir) {
123
161
  // A-SPEC-728 (round 24): the text as the shell joins it (`r\m -rf .git`, `eval rm\ -rf\ src`).
124
162
  const targets = [...new Set([...(0, risk_classifier_1.rmCommandTargets)(command), ...(0, risk_classifier_1.rmCommandTargets)((0, write_target_1.joinShellText)(command))])];
125
163
  if (targets.length === 0)
@@ -2797,7 +2835,8 @@ if (require.main === module) {
2797
2835
  try {
2798
2836
  // @implements A-SPEC-144 — normalize BEFORE deciding: most of the measured bypasses were a
2799
2837
  // wrong type reaching code that assumed a string, not an interesting failure of the gate.
2800
- const input = normalizeHookInput(JSON.parse(buf || '{}'));
2838
+ const rawHookInput = JSON.parse(buf || '{}');
2839
+ const input = normalizeHookInput(rawHookInput);
2801
2840
  // @implements A-SPEC-149
2802
2841
  // The ONE place process context is read. `evaluateHook` no longer reaches for `process.cwd()`
2803
2842
  // or `process.env` on its own, so a caller always states which project it is judging and under
@@ -2837,6 +2876,10 @@ if (require.main === module) {
2837
2876
  return { root: process.cwd(), anchored: false };
2838
2877
  })();
2839
2878
  const hookProjectRoot = hookRoot.root;
2879
+ // @implements A-SPEC-772.1 — evidence that this harness's gate ran here; off the decision path, never throws.
2880
+ if (hookRoot.anchored) {
2881
+ require('./heartbeat').recordHookHeartbeat({ root: hookProjectRoot, event: 'pre-tool-use', input: rawHookInput, env: process.env });
2882
+ }
2840
2883
  // @implements A-SPEC-191 §17 (round 11) — and the SPECS the gate judges against come from the
2841
2884
  // same tree. Round-10 moved the project root here and left this path relative, so a session
2842
2885
  // opened in a subdirectory looked for `<sub>/.ax/specs`, found nothing, and `isGovernedProject`
@@ -44,7 +44,7 @@ export interface StopEvidence {
44
44
  * printed under; absent means every line is printed as the session's. Never read for the verdict.
45
45
  */
46
46
  pendingRequests?: Pick<PendingRequest, 'id' | 'target'>[];
47
- /** The launcher the block text prints before `holmes-kit approve` (default: this platform's npx). */
47
+ /** The holmes-kit command the block text prints before `approve` (default: the issuing version, A-SPEC-770.3). */
48
48
  launcher?: string;
49
49
  /** A-SPEC id -> number of real test cases (`it(`/`test(`) found in test files anchored to it. */
50
50
  testCasesByAspec?: Record<string, number>;
@@ -355,6 +355,8 @@ export declare function decideStopGuard(wantsBlock: boolean, priorConsecutiveBlo
355
355
  };
356
356
  /** Test seam for the same reason as the two exports below — the CLI sets this on a real run. */
357
357
  export declare function __setWiredSpecsForTest(v: string | undefined): void;
358
+ /** @implements A-SPEC-770.7 — the approval command from this project's root (round 2: the Stop block passed none). */
359
+ export declare function stopLauncher(): string;
358
360
  /**
359
361
  * `readGuardCount`, degraded to 0 if it throws.
360
362
  *
@@ -56,13 +56,14 @@ exports.acknowledgeStop = acknowledgeStop;
56
56
  exports.describeTokenHealth = describeTokenHealth;
57
57
  exports.decideStopGuard = decideStopGuard;
58
58
  exports.__setWiredSpecsForTest = __setWiredSpecsForTest;
59
+ exports.stopLauncher = stopLauncher;
59
60
  exports.guardCountOrZero = guardCountOrZero;
60
61
  exports.readGuardCount = readGuardCount;
61
62
  exports.collectForbiddenEdgeJudgement = collectForbiddenEdgeJudgement;
62
63
  exports.stopSharedScan = stopSharedScan;
63
64
  exports.scanCodeCycles = scanCodeCycles;
64
65
  exports.writeGuardCount = writeGuardCount;
65
- // @implements A-SPEC-734
66
+ // @implements A-SPEC-734, A-SPEC-772.1, A-SPEC-770.3, A-SPEC-770.7
66
67
  // @implements A-SPEC-769.9, A-SPEC-769.10, A-SPEC-769.11
67
68
  const fs = __importStar(require("node:fs"));
68
69
  // @implements A-SPEC-549.3 — evaluateStop's messages are English here; the Hangul-absence guard
@@ -875,7 +876,7 @@ function evaluateStop(specs, evidence) {
875
876
  violations: structured,
876
877
  ...(tracked ? { tracked } : {}),
877
878
  // @implements A-SPEC-247.1 — the same lines, each under the heading that says who acts next. Text only.
878
- reason: stopBlockText(structured, evidence?.pendingRequests ?? [], evidence?.launcher ?? (0, npx_bin_1.npxBin)()),
879
+ reason: stopBlockText(structured, evidence?.pendingRequests ?? [], evidence?.launcher ?? stopLauncher()),
879
880
  };
880
881
  }
881
882
  /** The leading document id of an ART-4 detail (`T-SPEC-752.4: declared coverage …`). */
@@ -912,7 +913,7 @@ function stopBlockText(violations, pending, launcher) {
912
913
  : v.article === 'ART-7' ? v.findingId : undefined;
913
914
  const request = subject === undefined ? undefined : requestFor.get(subject);
914
915
  if (request !== undefined) {
915
- operator.push(`${line} — request ${request} is pending: the operator decides it, in the session's approval dialog or with ${launcher} holmes-kit approve`);
916
+ operator.push(`${line} — request ${request} is pending: the operator decides it, in the session's approval dialog or with ${launcher} approve`);
916
917
  }
917
918
  else if (v.article === 'ART-4') {
918
919
  session.push(`${line} — anchor real covering tests, or, when the design is withdrawn, retire the spec with spec_retire`);
@@ -1109,6 +1110,15 @@ function __setWiredSpecsForTest(v) { WIRED_SPECS = v; }
1109
1110
  * `git rev-parse --show-toplevel`, and the ART-4 loop called it per test file (1,000 tests: 16.7 s — measured).
1110
1111
  */
1111
1112
  let STOP_ROOT = null;
1113
+ /** @implements A-SPEC-770.7 — the approval command from this project's root (round 2: the Stop block passed none). */
1114
+ function stopLauncher() {
1115
+ try {
1116
+ return (0, npx_bin_1.holmesKitCommand)(stopProjectRoot());
1117
+ }
1118
+ catch {
1119
+ return (0, npx_bin_1.holmesKitCommand)();
1120
+ }
1121
+ }
1112
1122
  function stopProjectRoot() {
1113
1123
  const cwd = process.cwd();
1114
1124
  if (STOP_ROOT === null || STOP_ROOT.cwd !== cwd)
@@ -1393,6 +1403,8 @@ if (require.main === module) {
1393
1403
  // there is no project this hook has nothing to judge: no answer, no notice, no file.
1394
1404
  if (outsideAnyProject({ foundRoot: findProjectRoot(wired), specsDir, cwd: process.cwd() }))
1395
1405
  return;
1406
+ // @implements A-SPEC-772.1 — evidence that this harness's Stop gate ran here; off the decision path, never throws.
1407
+ require('./heartbeat').recordHookHeartbeat({ root: stopProjectRoot(), event: 'stop', input, env: process.env });
1396
1408
  const specs = (0, pre_tool_use_1.readSpecsSync)(specsDir);
1397
1409
  // H1 evidence: count EXECUTABLE test cases per anchored A-SPEC (countTestCases strips comments/
1398
1410
  // strings — sham-resistant). A scan FAILURE yields `undefined` (ART-4 skipped this turn, true
@@ -1741,7 +1753,7 @@ if (require.main === module) {
1741
1753
  else if (ackWaiting.length > 0) {
1742
1754
  // @implements A-SPEC-247 — acknowledged, not clean: name what is waiting so the user sees
1743
1755
  // the standing approval debt exactly once, and the agent knows the ball is not in its court.
1744
- process.stderr.write(`[Holmes-Kit] awaiting approval — items waiting on the owner's decision: ${ackWaiting.join(', ')}. Decide them at ${(0, npx_bin_1.npxBin)()} holmes-kit approve. (This debt does not re-block.)\n`);
1756
+ process.stderr.write(`[Holmes-Kit] awaiting approval — items waiting on the owner's decision: ${ackWaiting.join(', ')}. Decide them at ${stopLauncher()} approve. (This debt does not re-block.)\n`);
1745
1757
  }
1746
1758
  else if (guard.capped) {
1747
1759
  process.stderr.write(`[Holmes-Kit] governance gate YIELDING after ${exports.MAX_CONSECUTIVE_BLOCKS} consecutive blocks — issues remain UNRESOLVED:\n${out.reason ?? ''}\n`);
@@ -9,7 +9,7 @@ exports.buildDecisionForm = buildDecisionForm;
9
9
  exports.buildReasonForm = buildReasonForm;
10
10
  exports.runElicitFlow = runElicitFlow;
11
11
  exports.interpretElicitResult = interpretElicitResult;
12
- // @implements A-SPEC-718.2, A-SPEC-718, A-SPEC-263.1, A-SPEC-732
12
+ // @implements A-SPEC-718.2, A-SPEC-718, A-SPEC-263.1, A-SPEC-732, A-SPEC-770.3, A-SPEC-770.6
13
13
  const npx_bin_1 = require("../project/npx-bin");
14
14
  /**
15
15
  * The decision comes INTO the session (REQ-263): an approval-shaped refusal (spec_approve without a
@@ -91,7 +91,7 @@ function classifyElicitError(e, timeoutMs = exports.ELICIT_TIMEOUT_MS) {
91
91
  * Template-owned text with no interpolated attacker data.
92
92
  */
93
93
  function expiredNotice(waitedMs) {
94
- return `[세션 승인 다이얼로그 만료 — ${Math.round(waitedMs / 1000)}초 무응답] 요청은 승인 큐로 회송되었습니다. 결정: ${(0, npx_bin_1.npxBin)()} holmes-kit approve. `;
94
+ return `[세션 승인 다이얼로그 만료 — ${Math.round(waitedMs / 1000)}초 무응답] 요청은 승인 큐로 회송되었습니다. 결정: ${(0, npx_bin_1.holmesKitCommand)()} approve. `;
95
95
  }
96
96
  // FLATTEN attacker-influenced text (round-1): the model chooses spec titles and finding ids, and
97
97
  // interpolating them raw let a crafted title inject fake lines ("[시스템] … approve.") into the
@@ -110,7 +110,7 @@ const flat = (s, max) => s.replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029\u200b
110
110
  function buildDecisionForm(req, attempt, timeoutMs) {
111
111
  const redisplay = attempt > 1 ? `⚠ 재표시 ${attempt}/${exports.MAX_PRESENTATIONS} — 이전 다이얼로그는 만료되어 무효입니다\n` : '';
112
112
  // @implements A-SPEC-718.2 — one outcome for silence, in every mode: the request returns to the queue.
113
- const timeoutNotice = `⏱ ${timeoutMs / 1000}초 내 미결정 시 승인 큐로 회송됩니다(운영자: ${(0, npx_bin_1.npxBin)()} holmes-kit approve).`;
113
+ const timeoutNotice = `⏱ ${timeoutMs / 1000}초 내 미결정 시 승인 큐로 회송됩니다(운영자: ${(0, npx_bin_1.holmesKitCommand)()} approve).`;
114
114
  return {
115
115
  // @implements A-SPEC-497.1 — the forewarning is the LAST line and template-owned: it survives a
116
116
  // cap-filling summary (appended after the caps) and tells the human, before the clock runs out,
@@ -217,7 +217,7 @@ function interpretElicitResult(r) {
217
217
  // @implements A-SPEC-732 — the protocol cannot tell a person's decline from a client that declines
218
218
  // forms automatically (codex exec, measured 2026-09-24), so the reason names both and the fallback.
219
219
  if (r.action === 'decline')
220
- return { granted: false, reason: 'the session client declined the approval form (decline) — a person declined, or a client that cannot show forms (e.g. codex exec) declined automatically. If nobody saw the form, set HOLMES_ELICIT=off in the holmes-kit MCP server environment and decide with holmes-kit approve' };
220
+ return { granted: false, reason: 'the session client declined the approval form (decline) — a person declined, or a client that cannot show forms (e.g. codex exec) declined automatically. If nobody saw the form, set HOLMES_ELICIT=off in the holmes-kit MCP server environment and decide with ' + `${(0, npx_bin_1.holmesKitCommand)()} approve` }; // A-SPEC-770.6
221
221
  if (r.action !== 'accept')
222
222
  return null; // cancel, absent, anything else: no decision
223
223
  const content = r.content;
@@ -9,12 +9,27 @@ export interface RuntimeBindingToolContext {
9
9
  home?: string;
10
10
  installerPackageRoot?: string;
11
11
  }
12
+ type Routing = {
13
+ mode: 'release';
14
+ packageRoot: string;
15
+ buildId: string;
16
+ } | {
17
+ mode: 'unrouted';
18
+ } | {
19
+ mode: 'unroutable';
20
+ error: string;
21
+ };
12
22
  export declare function createRuntimeBindingToolHandlers(context: RuntimeBindingToolContext): {
13
23
  runtime_binding(a: {
14
24
  root: string;
15
25
  operation?: string;
16
26
  activate_hooks?: string[];
17
27
  }): Promise<{
28
+ ok: false;
29
+ applied: false;
30
+ routing: Routing;
31
+ reason: string;
32
+ } | {
18
33
  ok: boolean;
19
34
  applied: boolean;
20
35
  reason: string;
@@ -41,5 +56,18 @@ export declare function createRuntimeBindingToolHandlers(context: RuntimeBinding
41
56
  ok: boolean;
42
57
  applied: boolean;
43
58
  reason?: undefined;
59
+ } | {
60
+ planDigest: string;
61
+ conflicts: string[];
62
+ changes: {
63
+ path: string;
64
+ added: number;
65
+ removed: number;
66
+ }[];
67
+ request?: string | undefined;
68
+ ok: boolean;
69
+ applied: boolean;
70
+ reason: string;
44
71
  }>;
45
72
  };
73
+ export {};
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createRuntimeBindingToolHandlers = createRuntimeBindingToolHandlers;
37
- // @implements A-SPEC-752.10
37
+ // @implements A-SPEC-752.10, A-SPEC-772, A-SPEC-772.5
38
38
  /**
39
39
  * `runtime_binding` — re-apply the binding the operator registry ALREADY names for this workspace, from inside the
40
40
  * session, on the owner's explicit answer in the approval dialog.
@@ -53,6 +53,35 @@ const node_crypto_1 = require("node:crypto");
53
53
  const binding_1 = require("../../runtime/binding");
54
54
  const runtime_binding_1 = require("../../cli/runtime-binding");
55
55
  const HARNESSES = ['claude', 'codex', 'antigravity'];
56
+ const SETUP = '`holmes-kit runtime-binding setup` in a terminal';
57
+ /**
58
+ * @implements A-SPEC-772 — the answer for a workspace with no development binding names the routing that governs it.
59
+ * "Not registered" read as "not governed" (2026-10-17): the dispatcher routes such a workspace to the release build.
60
+ */
61
+ function unboundAnswer(registry, root, readError) {
62
+ let routing;
63
+ if (readError !== undefined)
64
+ routing = { mode: 'unroutable', error: readError };
65
+ else if (registry === null)
66
+ routing = { mode: 'unrouted' };
67
+ else {
68
+ try {
69
+ const s = (0, binding_1.selectRuntime)(registry, { cwd: root });
70
+ routing = { mode: 'release', packageRoot: s.packageRoot, buildId: s.buildId };
71
+ }
72
+ catch (e) {
73
+ routing = { mode: 'unroutable', error: e.message };
74
+ }
75
+ }
76
+ // @implements A-SPEC-772.5 — a registry file proves the routing of routed hooks, not that every harness is routed.
77
+ const which = 'Which applies to each harness: `holmes-kit runtime-binding status` and workspace_preflight with `harness`.';
78
+ const reason = routing.mode === 'release'
79
+ ? `runtime_binding: no development binding is registered for this workspace, so there is nothing to re-apply. Hooks routed through the operator runtime registry run the release build ${routing.buildId} (${routing.packageRoot}); hooks wired directly by \`holmes-kit init\` run the package their command names. ${which} Binding a development build is an operator act: ${SETUP}.`
80
+ : routing.mode === 'unrouted'
81
+ ? `runtime_binding: there is no operator runtime registry on this machine. Hooks wired by \`holmes-kit init\` run as wired; a hook still routed through the dispatcher refuses until the operator repairs the registry with ${SETUP}. ${which}`
82
+ : `runtime_binding: this workspace cannot be routed — ${routing.error} Hooks routed through the operator registry refuse until the operator repairs it with ${SETUP}.`;
83
+ return { ok: false, applied: false, routing, reason };
84
+ }
56
85
  /** How many lines a change adds and removes — what a reviewer needs from a tool answer; the contents stay on disk. */
57
86
  function lineCounts(change) {
58
87
  const before = (change.before ?? '').split('\n');
@@ -75,24 +104,28 @@ function createRuntimeBindingToolHandlers(context) {
75
104
  return { ok: false, applied: false, reason: `runtime_binding: activate_hooks takes only ${HARNESSES.join(', ')}` };
76
105
  }
77
106
  const registryPath = context.registryPath();
78
- const unregistered = { ok: false, applied: false,
79
- reason: 'runtime_binding: this workspace is not registered in the operator runtime registry. Registering a workspace, or choosing which build governs it, is done by the operator with `holmes-kit runtime-binding setup` in a terminal; this tool only re-applies a registered binding.' };
80
107
  let root;
81
108
  let binding;
82
109
  let releasePackageRoot;
110
+ let registry;
83
111
  try {
84
112
  root = fs.realpathSync.native(context.projectRootOf(a.root));
85
- if (!fs.existsSync(registryPath))
86
- return unregistered;
87
- const registry = (0, binding_1.readRuntimeRegistry)(registryPath);
88
- binding = registry.bindings.find((b) => b.workspaceRoot === root);
89
- releasePackageRoot = registry.releasePackageRoot;
90
113
  }
91
114
  catch (e) {
92
115
  return { ok: false, applied: false, reason: `runtime_binding: ${e.message}` };
93
116
  }
117
+ if (!fs.existsSync(registryPath))
118
+ return unboundAnswer(null, root);
119
+ try {
120
+ registry = (0, binding_1.readRuntimeRegistry)(registryPath);
121
+ }
122
+ catch (e) {
123
+ return unboundAnswer(null, root, e.message);
124
+ }
125
+ binding = registry.bindings.find((b) => b.workspaceRoot === root);
126
+ releasePackageRoot = registry.releasePackageRoot;
94
127
  if (binding === undefined)
95
- return unregistered;
128
+ return unboundAnswer(registry, root);
96
129
  const options = { operation: 'setup', workspace: root, packageRoot: binding.packageRoot, releasePackageRoot, registryPath,
97
130
  activateHooks: activate, ...(context.home !== undefined ? { home: context.home } : {}),
98
131
  ...(context.installerPackageRoot !== undefined ? { installerPackageRoot: context.installerPackageRoot } : {}) };
@@ -35,7 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createSpecApprovalHandlers = createSpecApprovalHandlers;
37
37
  exports.readProjectFile = readProjectFile;
38
- // @implements A-SPEC-718.3, A-SPEC-718.1, A-SPEC-718.2, A-SPEC-718, A-SPEC-551.1, A-SPEC-551.2, A-SPEC-627.1, A-SPEC-622, A-SPEC-100.2, A-SPEC-128, A-SPEC-132, A-SPEC-133, A-SPEC-151, A-SPEC-188, A-SPEC-189, A-SPEC-244, A-SPEC-245, A-SPEC-729
38
+ // @implements A-SPEC-718.3, A-SPEC-770.6, A-SPEC-718.1,A-SPEC-718.2, A-SPEC-718, A-SPEC-551.1, A-SPEC-551.2, A-SPEC-627.1, A-SPEC-622, A-SPEC-100.2, A-SPEC-128, A-SPEC-132, A-SPEC-133, A-SPEC-151, A-SPEC-188, A-SPEC-189, A-SPEC-244, A-SPEC-245, A-SPEC-729
39
39
  // @implements A-SPEC-631, A-SPEC-733
40
40
  const fs = __importStar(require("node:fs"));
41
41
  const compat_impact_1 = require("../../spec/compat-impact");
@@ -56,6 +56,7 @@ const review_targets_1 = require("../../review/review-targets");
56
56
  const requirement_triage_evidence_1 = require("../requirement-triage-evidence");
57
57
  const approval_policy_1 = require("../approval-policy");
58
58
  const approval_blockers_1 = require("../../spec/approval-blockers");
59
+ const npx_bin_1 = require("../../project/npx-bin");
59
60
  function createSpecApprovalHandlers(context) {
60
61
  const { store, resolver, projectRootOf, cachedScan, tryElicit, elicitApproval, autonomousApproval } = context;
61
62
  return {
@@ -365,7 +366,7 @@ function createSpecApprovalHandlers(context) {
365
366
  const bound = approveResolved.approval;
366
367
  if (typeof bound.subject === 'string' && bound.subject !== '' && bound.subject !== (0, spec_digest_1.specDigest)(cur.spec)) {
367
368
  const current = (0, spec_digest_1.specDigest)(cur.spec);
368
- return { ok: false, reason: `[grant ${bound.nonce ?? '?'} refused: stale-subject] the grant was minted for another content of ${a.id}; the operator must read the current content and decide again (revoke the stale grant with holmes-kit approve --revoke).`
369
+ return { ok: false, reason: `[grant ${bound.nonce ?? '?'} refused: stale-subject] the grant was minted for another content of ${a.id}; the operator must read the current content and decide again (revoke the stale grant with ${(0, npx_bin_1.holmesKitCommand)(a.root)} approve --revoke).`
369
370
  + context.refusalQueueHint(a.root, { kind: 'spec-approve', target: a.id, why: '스펙 봉인 승인', subject: current }) };
370
371
  }
371
372
  }
@@ -1,13 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createWorkspacePreflightHandlers = createWorkspacePreflightHandlers;
4
- // @implements A-SPEC-703
4
+ // @implements A-SPEC-703, A-SPEC-772.1
5
5
  const agents_1 = require("../../cli/agents");
6
6
  const workspace_preflight_1 = require("../../project/workspace-preflight");
7
7
  function createWorkspacePreflightHandlers(context) {
8
8
  return { async workspace_preflight(a) {
9
9
  if (a?.harness !== undefined && !agents_1.AGENTS.includes(a.harness))
10
10
  throw new Error('Unsupported harness.');
11
- return (0, workspace_preflight_1.inspectWorkspacePreflight)({ requestedRoot: a?.root, storeRoot: context.storeRoot });
11
+ return (0, workspace_preflight_1.inspectWorkspacePreflight)({ requestedRoot: a?.root, storeRoot: context.storeRoot, ...(a?.harness !== undefined ? { harness: a.harness } : {}) });
12
12
  } };
13
13
  }