@holmes-lab/holmes-kit 0.34.0 → 0.35.1

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 (46) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +6 -0
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/codex-oracle.js +36 -2
  5. package/dist/holmes/cli/doctor.d.ts +14 -1
  6. package/dist/holmes/cli/doctor.js +335 -71
  7. package/dist/holmes/cli/index.d.ts +1 -1
  8. package/dist/holmes/cli/index.js +38 -5
  9. package/dist/holmes/cli/runtime-binding-approval.d.ts +7 -0
  10. package/dist/holmes/cli/runtime-binding-approval.js +102 -0
  11. package/dist/holmes/cli/runtime-binding.d.ts +29 -0
  12. package/dist/holmes/cli/runtime-binding.js +570 -0
  13. package/dist/holmes/governance/approval-queue.d.ts +2 -0
  14. package/dist/holmes/governance/approval-queue.js +11 -4
  15. package/dist/holmes/guardrail/impact-gate.js +90 -5
  16. package/dist/holmes/guardrail/linear-match.js +8 -1
  17. package/dist/holmes/guardrail/risk-classifier.d.ts +6 -0
  18. package/dist/holmes/guardrail/risk-classifier.js +68 -23
  19. package/dist/holmes/guardrail/shell-argument-roles.d.ts +15 -0
  20. package/dist/holmes/guardrail/shell-argument-roles.js +209 -0
  21. package/dist/holmes/guardrail/shell-syntax.d.ts +20 -0
  22. package/dist/holmes/guardrail/shell-syntax.js +489 -0
  23. package/dist/holmes/guardrail/shell-words.d.ts +2 -18
  24. package/dist/holmes/guardrail/shell-words.js +67 -442
  25. package/dist/holmes/guardrail/write-target.d.ts +54 -0
  26. package/dist/holmes/guardrail/write-target.js +327 -1
  27. package/dist/holmes/hooks/pre-tool-use.d.ts +12 -0
  28. package/dist/holmes/hooks/pre-tool-use.js +377 -66
  29. package/dist/holmes/mcp/handlers/maintenance-analysis.js +4 -2
  30. package/dist/holmes/mcp/handlers/test-execution.js +6 -2
  31. package/dist/holmes/mcp/handlers.d.ts +9 -1
  32. package/dist/holmes/mcp/handlers.js +6 -4
  33. package/dist/holmes/mcp/maintenance-evidence.d.ts +16 -1
  34. package/dist/holmes/mcp/maintenance-evidence.js +29 -3
  35. package/dist/holmes/mcp/operator-recovery.d.ts +9 -0
  36. package/dist/holmes/mcp/operator-recovery.js +63 -0
  37. package/dist/holmes/rtm/test-scope.d.ts +9 -0
  38. package/dist/holmes/rtm/test-scope.js +284 -14
  39. package/dist/holmes/runtime/binding.d.ts +30 -0
  40. package/dist/holmes/runtime/binding.js +164 -0
  41. package/dist/holmes/runtime/dispatch.d.ts +9 -0
  42. package/dist/holmes/runtime/dispatch.js +169 -0
  43. package/dist/holmes/runtime/hook-process.d.ts +11 -0
  44. package/dist/holmes/runtime/hook-process.js +130 -0
  45. package/docs/install-guide.md +65 -0
  46. package/package.json +1 -1
@@ -0,0 +1,570 @@
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.defaultRuntimeRegistry = void 0;
37
+ exports.runtimeHookCommand = runtimeHookCommand;
38
+ exports.wiringViewOf = wiringViewOf;
39
+ exports.runtimeBindingStatus = runtimeBindingStatus;
40
+ exports.runRuntimeBinding = runRuntimeBinding;
41
+ // @implements A-SPEC-751, A-SPEC-752
42
+ const fs = __importStar(require("node:fs"));
43
+ const os = __importStar(require("node:os"));
44
+ const path = __importStar(require("node:path"));
45
+ const node_crypto_1 = require("node:crypto");
46
+ const smol_toml_1 = require("smol-toml");
47
+ const binding_1 = require("../runtime/binding");
48
+ const runtime_binding_approval_1 = require("./runtime-binding-approval");
49
+ const codex_toml_1 = require("./codex-toml");
50
+ const codex_hooks_1 = require("./codex-hooks");
51
+ const agents_1 = require("./agents");
52
+ const defaultRuntimeRegistry = () => path.join(os.homedir(), '.holmes', 'runtime', 'bindings.json');
53
+ exports.defaultRuntimeRegistry = defaultRuntimeRegistry;
54
+ const digest = (s) => (0, node_crypto_1.createHash)('sha256').update(s).digest('hex');
55
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
56
+ const json = (v) => `${JSON.stringify(v, null, 2)}\n`;
57
+ function readOptional(file) {
58
+ try {
59
+ return (0, binding_1.readBounded)(file);
60
+ }
61
+ catch (e) {
62
+ if (e.code === 'ENOENT')
63
+ return null;
64
+ throw e;
65
+ }
66
+ }
67
+ function document(raw, file) {
68
+ const parsed = raw === null ? {} : JSON.parse(raw);
69
+ if (!object(parsed))
70
+ throw new Error(`Invalid configuration object: ${file}`);
71
+ return parsed;
72
+ }
73
+ function canonicalFuture(file) {
74
+ let at = path.resolve(file);
75
+ const suffix = [];
76
+ while (!fs.existsSync(at)) {
77
+ suffix.unshift(path.basename(at));
78
+ const parent = path.dirname(at);
79
+ if (parent === at)
80
+ throw new Error(`Cannot resolve destination ${file}`);
81
+ at = parent;
82
+ }
83
+ return path.join(fs.realpathSync.native(at), ...suffix);
84
+ }
85
+ function quote(word) {
86
+ if (process.platform === 'win32') {
87
+ if (/["%\r\n!]/.test(word))
88
+ throw new Error('Hook path cannot be represented safely by this Windows shell');
89
+ return `"${word}"`;
90
+ }
91
+ return `'${word.replace(/'/g, `'\\''`)}'`;
92
+ }
93
+ function runtimeHookCommand(registryPath, harness, entry) {
94
+ const file = path.join(path.dirname(registryPath), `${harness}-${entry}.js`);
95
+ if (harness !== 'antigravity')
96
+ return `${quote(process.execPath)} ${quote(file)}`;
97
+ const node = (0, agents_1.shortPathIfSpaced)(process.execPath);
98
+ const script = (0, agents_1.shortPathIfSpaced)(file);
99
+ if (/\s/.test(node) || /\s/.test(script))
100
+ throw new Error('Antigravity needs a no-space operator destination (or a resolvable Windows short path)');
101
+ if (![node, script].every((s) => agents_1.AGY_LITERAL_PATH.test(s.replace(/\\/g, '/'))))
102
+ throw new Error('Antigravity needs shell-safe literal Node and operator paths');
103
+ return `${node.replace(/\\/g, '/')} ${script.replace(/\\/g, '/')}`;
104
+ }
105
+ /**
106
+ * @implements A-SPEC-752.5 — what the receipt records about a file. Claude Code rewrites its own settings file (measured
107
+ * 2026-10-04: a model switch), so a whole-byte digest called an unrelated edit changed wiring and gave a reviewed plan
108
+ * another digest. For that file the receipt is about a view of the document; every other file is recorded whole.
109
+ * A list of keys to keep missed ones that switch Holmes off, so the view names what it drops (A-SPEC-752.6).
110
+ */
111
+ function wiringViewOf(file, content) {
112
+ const name = path.basename(file);
113
+ if ((name !== 'settings.json' && name !== 'settings.local.json') || path.basename(path.dirname(file)) !== '.claude')
114
+ return content;
115
+ let doc;
116
+ try {
117
+ doc = JSON.parse(content);
118
+ }
119
+ catch {
120
+ return content;
121
+ }
122
+ if (!object(doc))
123
+ return content;
124
+ // @implements A-SPEC-752.6 — everything but `model`, the one key measured to change with no wiring change.
125
+ const { model: _model, ...rest } = doc;
126
+ return JSON.stringify(rest);
127
+ }
128
+ function runtimeBindingStatus(registryPath, workspace) {
129
+ const selection = (0, binding_1.selectRuntime)((0, binding_1.readRuntimeRegistry)(registryPath), { cwd: workspace });
130
+ const manifest = readOptional(path.join(path.dirname(registryPath), 'installation.json'));
131
+ const conflicts = [];
132
+ if (manifest === null)
133
+ conflicts.push('No installation receipt; registry selection alone does not establish wiring');
134
+ else {
135
+ const rows = document(manifest, 'installation.json').files;
136
+ if (!Array.isArray(rows))
137
+ throw new Error('Invalid runtime installation receipt');
138
+ for (const row of rows) {
139
+ if (!object(row) || typeof row.path !== 'string' || typeof row.digest !== 'string')
140
+ throw new Error('Invalid installation file record');
141
+ const current = readOptional(row.path);
142
+ // A-SPEC-752.5: the view's digest, or the whole file's for a row written before the view existed.
143
+ if (current === null || (digest(wiringViewOf(row.path, current)) !== row.digest && digest(current) !== row.digest))
144
+ conflicts.push(`Wiring changed or incomplete: ${row.path}`);
145
+ }
146
+ }
147
+ return { selection, conflicts, activation: 'unverified' };
148
+ }
149
+ function runRuntimeBinding(opts) {
150
+ if (opts.activateHooks !== undefined && (!Array.isArray(opts.activateHooks)
151
+ || opts.activateHooks.some((h) => !['claude', 'codex', 'antigravity'].includes(h))
152
+ || opts.operation !== 'setup'))
153
+ throw new Error('Hook activation requires setup and supported harness selectors');
154
+ const activate = new Set(opts.activateHooks ?? []);
155
+ if (opts.operation === 'status')
156
+ return runtimeBindingStatus(opts.registryPath, opts.workspace);
157
+ if (opts.operation !== 'setup' && opts.operation !== 'remove')
158
+ throw new Error('runtime-binding expects setup, status or remove');
159
+ if (!path.isAbsolute(opts.registryPath))
160
+ throw new Error('Registry path must be absolute');
161
+ if (['binding.js', 'dispatch.js', 'hook-process.js', 'installation.json'].includes(path.basename(opts.registryPath))
162
+ || /^(?:claude|codex|antigravity)-(?:mcp|pre-tool-use|stop)\.js$/.test(path.basename(opts.registryPath)))
163
+ throw new Error('Registry filename conflicts with an installed runtime file');
164
+ const root = (0, binding_1.workspaceRoot)(opts.workspace);
165
+ if ((0, binding_1.canonicalDirectory)(opts.workspace) !== root)
166
+ throw new Error('Register the workspace root, not a subdirectory');
167
+ const destination = canonicalFuture(opts.registryPath);
168
+ if (destination !== opts.registryPath || (0, binding_1.inside)(root, destination))
169
+ throw new Error('Operator registry must be canonical and outside the workspace');
170
+ const before = readOptional(opts.registryPath);
171
+ const previous = before === null ? null : (0, binding_1.readRuntimeRegistry)(opts.registryPath);
172
+ if (opts.operation === 'setup' && (!opts.packageRoot || !opts.releasePackageRoot))
173
+ throw new Error('setup requires --package and --release-package');
174
+ if (opts.operation === 'remove' && !previous)
175
+ throw new Error('No runtime registry to remove from');
176
+ const next = opts.operation === 'setup' ? {
177
+ version: 1,
178
+ releasePackageRoot: (0, binding_1.canonicalDirectory)(opts.releasePackageRoot),
179
+ bindings: [...(previous?.bindings ?? []).filter((b) => b.workspaceRoot !== root), { workspaceRoot: root, packageRoot: (0, binding_1.canonicalDirectory)(opts.packageRoot) }],
180
+ } : { ...previous, bindings: previous.bindings.filter((b) => b.workspaceRoot !== root) };
181
+ (0, binding_1.validateRegistry)(next);
182
+ for (const binding of next.bindings) {
183
+ if ((0, binding_1.inside)(binding.workspaceRoot, destination) || (0, binding_1.inside)(binding.packageRoot, destination))
184
+ throw new Error('Operator registry must be outside registered checkouts');
185
+ }
186
+ if ((0, binding_1.inside)(next.releasePackageRoot, destination))
187
+ throw new Error('Operator registry must be outside the release package');
188
+ const releaseBuild = (0, binding_1.verifyRuntime)(next.releasePackageRoot);
189
+ const selection = (0, binding_1.selectRuntime)(next, { cwd: root });
190
+ const after = `${JSON.stringify(next, null, 2)}\n`;
191
+ const planned = new Map();
192
+ const conflicts = [];
193
+ const add = (file, content) => {
194
+ if (canonicalFuture(file) !== path.resolve(file))
195
+ throw new Error(`Configuration symlink conflict: ${file}`);
196
+ const old = readOptional(file);
197
+ planned.set(file, { path: file, before: old, after: content });
198
+ };
199
+ const dir = path.dirname(destination);
200
+ const installer = opts.installerPackageRoot ?? path.resolve(__dirname, '../../..');
201
+ for (const name of ['binding', 'dispatch', 'hook-process']) {
202
+ const source = path.join(installer, 'dist/holmes/runtime', `${name}.js`);
203
+ add(path.join(dir, `${name}.js`), (0, binding_1.readBounded)(source));
204
+ }
205
+ const wrappers = new Map();
206
+ for (const harness of ['claude', 'codex', 'antigravity']) {
207
+ for (const entry of ['mcp', 'pre-tool-use', 'stop']) {
208
+ const file = path.join(dir, `${harness}-${entry}.js`);
209
+ add(file, `// @implements A-SPEC-751\nrequire('./dispatch.js').runDispatch(${JSON.stringify({ registryPath: destination, harness, entry })});\n`);
210
+ wrappers.set(`${harness}:${entry}`, file);
211
+ }
212
+ }
213
+ const command = (harness, entry) => runtimeHookCommand(destination, harness, entry);
214
+ const owns = (cmd) => {
215
+ if (typeof cmd !== 'string')
216
+ return false;
217
+ if ((0, codex_hooks_1.holmesKernelScript)(cmd))
218
+ return true;
219
+ if ([...wrappers.keys()].some((key) => { const [h, e] = key.split(':'); return cmd === command(h, e); }))
220
+ return true;
221
+ if (/holmes|pre-tool-use\.js|stop\.js/i.test(cmd))
222
+ throw new Error(`Unknown Holmes wrapper requires explicit migration: ${cmd}`);
223
+ return false;
224
+ };
225
+ const native = (file, harness, primary) => {
226
+ const hasPrimary = typeof primary === 'boolean' ? primary : primary.size > 0;
227
+ const raw = readOptional(file);
228
+ if (raw === null && !hasPrimary)
229
+ return;
230
+ const doc = document(raw, file);
231
+ if (doc.hooks !== undefined && !object(doc.hooks))
232
+ throw new Error(`Invalid hooks configuration: ${file}`);
233
+ const hooks = { ...(doc.hooks ?? {}) };
234
+ for (const event of ['PreToolUse', 'Stop']) {
235
+ if (hooks[event] !== undefined && !Array.isArray(hooks[event]))
236
+ throw new Error(`Invalid hook groups: ${file}`);
237
+ const groups = [];
238
+ for (const [groupIndex, g] of (hooks[event] ?? []).entries()) {
239
+ // Older project plugin generators wrote Stop as a flat command list. Migrate only
240
+ // that known legacy source; the active user hooks retain the native grouped schema.
241
+ if (file === path.join(root, agents_1.CODEX_PLUGIN_DIR, 'hooks.json') && !hasPrimary && event === 'Stop'
242
+ && object(g) && g.type === 'command' && typeof g.command === 'string' && g.hooks === undefined) {
243
+ if (!owns(g.command))
244
+ groups.push(g);
245
+ continue;
246
+ }
247
+ if (!object(g) || !Array.isArray(g.hooks))
248
+ throw new Error(`Invalid hook group: ${file}`);
249
+ const keep = g.hooks.filter((h, hookIndex) => {
250
+ if (!object(h))
251
+ throw new Error(`Invalid hook entry: ${file}`);
252
+ return !owns(h.command) || (harness === 'codex' && codexProjectEvents.has(event)
253
+ && disabledGlobalCodex(file, event, groupIndex, hookIndex));
254
+ });
255
+ if (keep.length)
256
+ groups.push({ ...g, hooks: keep });
257
+ }
258
+ const explicitlyEmpty = Array.isArray(hooks[event]) && hooks[event].length === 0;
259
+ if ((!explicitlyEmpty || activate.has(harness)) && (typeof primary === 'boolean' ? primary : primary.has(event)))
260
+ groups.push({ ...(event === 'PreToolUse' ? { matcher: '.*' } : {}), hooks: [{ type: 'command', command: command(harness, event === 'PreToolUse' ? 'pre-tool-use' : 'stop'), timeout: 30 }] });
261
+ if (groups.length || hooks[event] !== undefined)
262
+ hooks[event] = groups;
263
+ }
264
+ add(file, json({ ...doc, hooks }));
265
+ };
266
+ const mcp = (file, harness) => {
267
+ const doc = document(readOptional(file), file);
268
+ if (doc.mcpServers !== undefined && !object(doc.mcpServers))
269
+ throw new Error(`Invalid MCP configuration: ${file}`);
270
+ const servers = doc.mcpServers ?? {};
271
+ const old = servers['holmes-kit'] ?? {};
272
+ if (!object(old) || (old.env !== undefined && !object(old.env)))
273
+ throw new Error(`Invalid Holmes MCP entry: ${file}`);
274
+ assertMcpOwner(old, file);
275
+ const env = { ...(old.env ?? {}) };
276
+ delete env.HOLMES_SPECS;
277
+ add(file, json({ ...doc, mcpServers: { ...servers, 'holmes-kit': { ...old, command: process.execPath, args: [wrappers.get(`${harness}:mcp`)], env } } }));
278
+ };
279
+ const home = opts.home ?? os.homedir();
280
+ function assertMcpOwner(old, file) {
281
+ if (Object.keys(old).length === 0)
282
+ return;
283
+ const node = typeof old.command === 'string' && /(?:^|[/\\])node(?:\.exe)?$/.test(old.command);
284
+ const args = old.args;
285
+ const direct = Array.isArray(args) && args.length === 1 && typeof args[0] === 'string'
286
+ && (/(?:^|[/\\])bin[/\\]holmes-mcp\.js$/.test(args[0]) || [...wrappers.values()].includes(args[0]));
287
+ const pinned = old.command === 'npx' && Array.isArray(args) && args.length === 4 && args[0] === '-y' && args[1] === '-p'
288
+ && typeof args[2] === 'string' && /^@holmes-lab\/holmes-kit@[^\s]+$/.test(args[2]) && args[3] === 'holmes-mcp';
289
+ if (!(node && direct) && !pinned)
290
+ throw new Error(`Unknown MCP wrapper requires explicit migration: ${file}`);
291
+ }
292
+ const codexConfig = opts.home ? path.join(home, '.codex/config.toml') : (0, codex_toml_1.defaultCodexConfigPath)();
293
+ const codexHooks = opts.home ? path.join(home, '.codex/hooks.json') : (0, codex_hooks_1.defaultCodexHooksPath)();
294
+ const disabledGlobalKeys = new Set();
295
+ const codexProjectEvents = new Set();
296
+ const disabledGlobalCodex = (file, event, group, hook) => file === codexHooks
297
+ && disabledGlobalKeys.has(`${event === 'PreToolUse' ? 'pre_tool_use' : 'stop'}:${group}:${hook}`);
298
+ const toml = (file, primary) => {
299
+ const raw = readOptional(file);
300
+ if (raw === null && !primary)
301
+ return;
302
+ const parsed = (0, codex_toml_1.parseCodexConfig)(raw ?? '');
303
+ if (!parsed.ok)
304
+ throw new Error(`Invalid configuration ${file}: ${parsed.reason}`);
305
+ const old = parsed.doc.mcp_servers?.['holmes-kit'];
306
+ if (old === undefined && !primary)
307
+ return;
308
+ if (old !== undefined && !object(old))
309
+ throw new Error(`Invalid Holmes MCP entry: ${file}`);
310
+ if (old?.env !== undefined && !object(old.env))
311
+ throw new Error(`Invalid MCP environment: ${file}`);
312
+ assertMcpOwner(old ?? {}, file);
313
+ const env = { ...(old?.env ?? {}) };
314
+ delete env.HOLMES_SPECS;
315
+ const block = (0, smol_toml_1.stringify)({ mcp_servers: { 'holmes-kit': { ...old, command: process.execPath, args: [wrappers.get('codex:mcp')], env } } });
316
+ const merged = (0, codex_toml_1.mergeCodexToml)(raw, block);
317
+ if (!(0, codex_toml_1.parseCodexConfig)(merged).ok)
318
+ throw new Error(`Cannot safely merge configuration ${file}`);
319
+ add(file, merged);
320
+ };
321
+ const agy = (file, primary) => {
322
+ const raw = readOptional(file);
323
+ if (raw === null && !primary.size)
324
+ return;
325
+ const doc = document(raw, file);
326
+ const old = doc['holmes-kit'];
327
+ if (old === undefined && !primary.size)
328
+ return;
329
+ if (old !== undefined && !object(old))
330
+ throw new Error(`Invalid Antigravity configuration: ${file}`);
331
+ for (const event of ['PreToolUse', 'Stop']) {
332
+ if (old?.[event] === undefined)
333
+ continue;
334
+ if (!Array.isArray(old[event]))
335
+ throw new Error(`Invalid Antigravity hook list: ${file}`);
336
+ for (const group of old[event]) {
337
+ if (!object(group))
338
+ throw new Error(`Invalid Antigravity hook: ${file}`);
339
+ const entries = event === 'PreToolUse' ? group.hooks : [group];
340
+ if (!Array.isArray(entries))
341
+ throw new Error(`Invalid Antigravity hook group: ${file}`);
342
+ for (const h of entries) {
343
+ const cmd = h?.command;
344
+ const direct = typeof cmd === 'string' && /^(?:node|[^\s]+[/\\]node(?:\.exe)?) [^\s]+[/\\]bin[/\\]holmes-(?:hook|stop)-antigravity\.js$/.test(cmd);
345
+ if (!direct && cmd !== command('antigravity', event === 'PreToolUse' ? 'pre-tool-use' : 'stop'))
346
+ throw new Error(`Unknown Antigravity wrapper requires explicit migration: ${file}`);
347
+ }
348
+ }
349
+ }
350
+ // Preserve the native enable switch and fields other than our lifecycle entries.
351
+ const ours = { ...old };
352
+ if (activate.has('antigravity') && primary.size)
353
+ ours.enabled = true;
354
+ if (primary.has('PreToolUse')) {
355
+ ours.PreToolUse = !activate.has('antigravity') && Array.isArray(old?.PreToolUse) && old.PreToolUse.length === 0 ? [] : [{ matcher: '*', hooks: [{ command: command('antigravity', 'pre-tool-use') }] }];
356
+ }
357
+ else if (!(Array.isArray(old?.PreToolUse) && old.PreToolUse.length === 0))
358
+ delete ours.PreToolUse;
359
+ if (primary.has('Stop'))
360
+ ours.Stop = !activate.has('antigravity') && Array.isArray(old?.Stop) && old.Stop.length === 0 ? [] : [{ command: command('antigravity', 'stop') }];
361
+ else if (!(Array.isArray(old?.Stop) && old.Stop.length === 0))
362
+ delete ours.Stop;
363
+ add(file, json({ ...doc, 'holmes-kit': ours }));
364
+ };
365
+ try {
366
+ toml(codexConfig, true);
367
+ toml(path.join(root, '.codex/config.toml'), false);
368
+ const userNativeState = (0, codex_toml_1.parseCodexConfig)(readOptional(codexConfig) ?? '');
369
+ const normalized = (s) => process.platform === 'win32' ? s.toLowerCase() : s;
370
+ const globalAliases = new Set([codexHooks]);
371
+ if (fs.existsSync(codexHooks)) {
372
+ globalAliases.add(fs.realpathSync(codexHooks));
373
+ globalAliases.add(fs.realpathSync.native(codexHooks));
374
+ }
375
+ if (userNativeState.ok)
376
+ for (const [key, state] of Object.entries(userNativeState.doc.hooks?.state ?? {})) {
377
+ if (!object(state) || state.enabled !== false)
378
+ continue;
379
+ for (const file of globalAliases) {
380
+ if (normalized(key).startsWith(normalized(`${file}:`)))
381
+ disabledGlobalKeys.add(key.slice(file.length + 1));
382
+ }
383
+ }
384
+ const codexFiles = [codexHooks, path.join(root, '.codex/hooks.json')];
385
+ const codexDocs = codexFiles.map((f) => document(readOptional(f), f));
386
+ const codexEvents = codexFiles.map(() => new Set());
387
+ for (const event of ['PreToolUse', 'Stop']) {
388
+ const existing = codexDocs.findIndex((d, source) => Array.isArray(d.hooks?.[event])
389
+ && d.hooks[event].some((g, group) => Array.isArray(g?.hooks)
390
+ && g.hooks.some((h, hook) => owns(h?.command) && !disabledGlobalCodex(codexFiles[source], event, group, hook))));
391
+ // Explicit development activation adds missing lifecycles only to this project.
392
+ // Filling an empty user lifecycle would also activate every consumer workspace.
393
+ const empty = codexDocs.findIndex((d) => Array.isArray(d.hooks?.[event]) && d.hooks[event].length === 0);
394
+ const owner = existing >= 0 ? existing : activate.has('codex') ? 1 : empty >= 0 ? empty : 0;
395
+ codexEvents[owner].add(event);
396
+ if (owner === 1)
397
+ codexProjectEvents.add(event);
398
+ }
399
+ codexFiles.forEach((f, i) => native(f, 'codex', codexEvents[i]));
400
+ // Native disabled state is indexed by source/group/hook. Keeping its bytes while moving
401
+ // the disabled gate would silently enable it. Refuse that migration, never mint trust.
402
+ // Keep each layer's disabled keys: a project enable override does not change
403
+ // the user-level disabled state consumed by other workspaces.
404
+ const nativeStates = [];
405
+ for (const configFile of [codexConfig, path.join(root, '.codex/config.toml')]) {
406
+ const configState = (0, codex_toml_1.parseCodexConfig)(readOptional(configFile) ?? '');
407
+ if (configState.ok)
408
+ nativeStates.push(...Object.entries(configState.doc.hooks?.state ?? {}));
409
+ }
410
+ for (const hookFile of codexFiles) {
411
+ const oldHooks = document(readOptional(hookFile), hookFile);
412
+ const newHooks = document(planned.get(hookFile)?.after ?? readOptional(hookFile), hookFile);
413
+ const norm = (s) => process.platform === 'win32' ? s.toLowerCase() : s;
414
+ const paths = new Set([hookFile]);
415
+ if (fs.existsSync(hookFile)) {
416
+ paths.add(fs.realpathSync(hookFile));
417
+ paths.add(fs.realpathSync.native(hookFile));
418
+ }
419
+ for (const [key, state] of nativeStates) {
420
+ if (!object(state) || state.enabled !== false)
421
+ continue;
422
+ for (const file of paths)
423
+ for (const [event, keyEvent, entry] of [['PreToolUse', 'pre_tool_use', 'pre-tool-use'], ['Stop', 'stop', 'stop']]) {
424
+ const prefix = `${file}:${keyEvent}:`;
425
+ if (!norm(key).startsWith(norm(prefix)))
426
+ continue;
427
+ const indices = key.slice(prefix.length).match(/^(\d+):(\d+)$/);
428
+ if (!indices)
429
+ continue;
430
+ const i = Number(indices[1]);
431
+ const j = Number(indices[2]);
432
+ const old = oldHooks.hooks?.[event]?.[i]?.hooks?.[j];
433
+ const replacement = newHooks.hooks?.[event]?.[i]?.hooks?.[j];
434
+ if (old && JSON.stringify(replacement) !== JSON.stringify(old)
435
+ && !(owns(old.command) && replacement?.command === command('codex', entry))) {
436
+ throw new Error('A disabled Codex hook would move to a different native state key; review the hook layout before migration');
437
+ }
438
+ }
439
+ }
440
+ }
441
+ native(path.join(root, agents_1.CODEX_PLUGIN_DIR, 'hooks.json'), 'codex', false);
442
+ const claudeFiles = [path.join(home, '.claude/settings.json'), path.join(root, '.claude/settings.local.json'), path.join(root, '.claude/settings.json')];
443
+ const claudeDocs = claudeFiles.map((f) => document(readOptional(f), f));
444
+ const claudeEvents = claudeFiles.map(() => new Set());
445
+ for (const event of ['PreToolUse', 'Stop']) {
446
+ const existing = claudeDocs.findIndex((d) => Array.isArray(d.hooks?.[event]) && d.hooks[event].some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => owns(h?.command))));
447
+ const empty = claudeDocs.findIndex((d) => Array.isArray(d.hooks?.[event]) && d.hooks[event].length === 0);
448
+ // Keep an existing owner; otherwise honor an explicit empty source before creating a lifecycle.
449
+ claudeEvents[existing >= 0 ? existing : activate.has('claude') ? 1 : empty >= 0 ? empty : 1].add(event);
450
+ }
451
+ claudeFiles.forEach((f, i) => native(f, 'claude', claudeEvents[i]));
452
+ mcp(path.join(root, '.mcp.json'), 'claude');
453
+ mcp(path.join(root, '.agents/mcp_config.json'), 'antigravity');
454
+ const agyUser = (0, agents_1.agyUserHooksPath)(home);
455
+ const agyFiles = [agyUser, path.join(root, '.agents/hooks.json')];
456
+ const agyDocs = agyFiles.map((f) => document(readOptional(f), f)['holmes-kit']);
457
+ const agyEvents = agyFiles.map(() => new Set());
458
+ for (const event of ['PreToolUse', 'Stop']) {
459
+ const existing = agyDocs.findIndex((d, i) => object(d) && Array.isArray(d[event]) && d[event].length > 0
460
+ && !(activate.has('antigravity') && i === 0 && d.enabled === false));
461
+ const empty = agyDocs.findIndex((d) => object(d) && Array.isArray(d[event]) && d[event].length === 0);
462
+ agyEvents[existing >= 0 ? existing : activate.has('antigravity') ? 1 : empty >= 0 ? empty : 1].add(event);
463
+ }
464
+ agyFiles.forEach((f, i) => agy(f, agyEvents[i]));
465
+ // Installed plugin snapshots are independently loaded. Never imply changing the checkout copy suppresses them.
466
+ const plugins = path.join(path.dirname(codexConfig), 'plugins');
467
+ const cache = path.join(plugins, 'cache');
468
+ if (fs.existsSync(cache)) {
469
+ const vendors = fs.readdirSync(cache, { withFileTypes: true }).filter((d) => d.isDirectory() && /holmes/i.test(d.name));
470
+ const visit = (at, depth) => {
471
+ if (depth > 3)
472
+ return;
473
+ for (const d of fs.readdirSync(at, { withFileTypes: true })) {
474
+ const f = path.join(at, d.name);
475
+ if (d.isDirectory())
476
+ visit(f, depth + 1);
477
+ else if (d.isFile() && d.name === 'hooks.json' && /pre-tool-use|holmes-hook|holmes-stop/.test((0, binding_1.readBounded)(f)))
478
+ conflicts.push(`Cached Holmes hook source needs native plugin activation review: ${f}`);
479
+ }
480
+ };
481
+ for (const vendor of vendors)
482
+ visit(path.join(cache, vendor.name), 0);
483
+ }
484
+ }
485
+ catch (e) {
486
+ conflicts.push(e.message);
487
+ }
488
+ add(destination, after);
489
+ const manifestPath = path.join(dir, 'installation.json');
490
+ const receipt = readOptional(manifestPath);
491
+ const recorded = new Map();
492
+ const runtimeIdentities = {};
493
+ if (receipt !== null) {
494
+ const previousReceipt = document(receipt, manifestPath);
495
+ const rows = previousReceipt.files;
496
+ if (!Array.isArray(rows))
497
+ throw new Error('Invalid runtime installation receipt');
498
+ for (const row of rows) {
499
+ if (!object(row) || typeof row.path !== 'string' || !path.isAbsolute(row.path) || typeof row.digest !== 'string')
500
+ throw new Error('Invalid installation file record');
501
+ // A shared registry retains the wiring of every previously installed workspace.
502
+ recorded.set(row.path, { path: row.path, digest: row.digest });
503
+ }
504
+ if (previousReceipt.runtimeIdentities !== undefined) {
505
+ if (!object(previousReceipt.runtimeIdentities))
506
+ throw new Error('Invalid runtime identity receipt');
507
+ for (const [workspace, identity] of Object.entries(previousReceipt.runtimeIdentities)) {
508
+ if (!path.isAbsolute(workspace) || !object(identity)
509
+ || typeof identity.packageRoot !== 'string' || !path.isAbsolute(identity.packageRoot)
510
+ || typeof identity.releasePackageRoot !== 'string' || !path.isAbsolute(identity.releasePackageRoot)
511
+ || typeof identity.buildId !== 'string' || !identity.buildId.trim()
512
+ || typeof identity.releaseBuild !== 'string' || !identity.releaseBuild.trim())
513
+ throw new Error('Invalid runtime identity receipt');
514
+ runtimeIdentities[workspace] = identity;
515
+ }
516
+ }
517
+ }
518
+ // A-SPEC-752.5: a row records the wiring view of the planned content, so an unrelated rewrite of a Claude settings
519
+ // file leaves the receipt — and with it the plan — as it was.
520
+ for (const c of planned.values())
521
+ recorded.set(c.path, { path: c.path, digest: digest(wiringViewOf(c.path, c.after)) });
522
+ // Same-path builds still need a new reviewed plan. Legacy receipts gain identity only via apply.
523
+ runtimeIdentities[root] = { packageRoot: selection.packageRoot, buildId: selection.buildId,
524
+ releasePackageRoot: next.releasePackageRoot, releaseBuild };
525
+ add(manifestPath, json({ version: 1, files: [...recorded.values()], runtimeIdentities }));
526
+ const changes = [...planned.values()].filter((c) => c.before !== c.after);
527
+ const planDigest = (0, runtime_binding_approval_1.runtimePlanDigest)({ operation: opts.operation, root, selection, releasePackageRoot: next.releasePackageRoot,
528
+ releaseBuild, activateHooks: [...activate].sort() }, changes);
529
+ if (!opts.dryRun) {
530
+ if (conflicts.length)
531
+ throw new Error(`Runtime configuration conflicts; nothing written: ${conflicts.join('; ')}`);
532
+ // Check the entire reviewed snapshot before the first write, then again at each atomic replacement.
533
+ const check = () => {
534
+ for (const c of planned.values())
535
+ if (canonicalFuture(c.path) !== c.path || readOptional(c.path) !== c.before)
536
+ throw new Error(`Configuration changed since preview: ${c.path}`);
537
+ if ((0, binding_1.verifyRuntime)(selection.packageRoot) !== selection.buildId || (0, binding_1.verifyRuntime)(next.releasePackageRoot) !== releaseBuild)
538
+ throw new Error('Runtime build changed since preview');
539
+ };
540
+ check();
541
+ if (changes.length > 0)
542
+ (0, runtime_binding_approval_1.applyApprovedRuntimePlan)(root, planDigest, opts.approval, check, () => {
543
+ let written = 0;
544
+ try {
545
+ for (const c of changes) {
546
+ if (canonicalFuture(c.path) !== c.path || readOptional(c.path) !== c.before)
547
+ throw new Error(`Configuration changed during setup: ${c.path}`);
548
+ fs.mkdirSync(path.dirname(c.path), { recursive: true, mode: 0o700 });
549
+ const tmp = `${c.path}.${(0, node_crypto_1.randomUUID)()}.tmp`;
550
+ try {
551
+ const mode = c.before === null ? 0o600 : fs.statSync(c.path).mode & 0o777;
552
+ fs.writeFileSync(tmp, c.after, { flag: 'wx', mode });
553
+ fs.renameSync(tmp, c.path);
554
+ written++;
555
+ }
556
+ finally {
557
+ try {
558
+ fs.unlinkSync(tmp);
559
+ }
560
+ catch { /* renamed or never created */ }
561
+ }
562
+ }
563
+ }
564
+ catch (e) {
565
+ throw new Error(`Runtime setup incomplete after ${written} file(s): ${e.message}; run status and preview setup again`);
566
+ }
567
+ });
568
+ }
569
+ return { dryRun: opts.dryRun, changes, conflicts, selection, planDigest, activation: 'unverified' };
570
+ }
@@ -201,6 +201,8 @@ export declare function queueHint(root: string, req: {
201
201
  why: string;
202
202
  } & RequestDetails, opts?: {
203
203
  baseReasonBytes?: number;
204
+ reviewCommand?: string;
205
+ pendingHint?: (id: string) => string;
204
206
  }): string;
205
207
  /**
206
208
  * @implements A-SPEC-690
@@ -47,7 +47,7 @@ exports.queueHint = queueHint;
47
47
  exports.grantableRequests = grantableRequests;
48
48
  exports.openOccurrences = openOccurrences;
49
49
  exports.asPendingRequest = asPendingRequest;
50
- // @implements A-SPEC-244, A-SPEC-626
50
+ // @implements A-SPEC-244, A-SPEC-626, A-SPEC-752, A-SPEC-754
51
51
  const execution_context_1 = require("../project/execution-context");
52
52
  const root_1 = require("../project/root");
53
53
  const node_crypto_1 = require("node:crypto");
@@ -86,7 +86,7 @@ exports.QUEUE_RELPATH = path.join('.ax', 'approvals', 'queue.jsonl');
86
86
  // request went to the refusal log so the inbox stayed empty (measured 2026-09-14 on Windows: two
87
87
  // expired session dialogs, then `approve --list` answered "No requests awaiting approval").
88
88
  exports.DECISION_KINDS = new Set([
89
- 'spec-approve', 'config-write', 'autonomy-grant', 'spec-reappraisal', 'review-resolve',
89
+ 'spec-approve', 'config-write', 'autonomy-grant', 'spec-reappraisal', 'review-resolve', 'governance-wiring',
90
90
  ]);
91
91
  const REFUSALS_FILE_RE = /^refusals\.([^.]+)\.jsonl$/;
92
92
  function refusalsFilename(replica) {
@@ -491,7 +491,14 @@ function queueHint(root, req, opts) {
491
491
  // Round-6 established that flattening is not enough once text is folded, and gave `[v]` a
492
492
  // template-owned margin; this producer, read by the operator AND relayed by the agent, never got
493
493
  // one. The first row keeps the template's own opening; the rest sit under the margin.
494
- return (0, screen_safe_1.wrapColumns)(`\n[보류 — 운영자 질문: ${(0, screen_safe_1.flattenField)(held.question ?? '(질문 없음)', 300)}] 게이트는 닫혀 있습니다.`
494
+ const question = `\n[보류 — 운영자 질문: ${(0, screen_safe_1.flattenField)(held.question ?? '(질문 없음)', 300)}] 게이트는 닫혀 있습니다.`;
495
+ if (opts?.reviewCommand) {
496
+ // Fold only prose: inserted newlines/margins inside literal shell paths
497
+ // would change the command the operator is being asked to execute.
498
+ return (0, screen_safe_1.wrapColumns)(question + ' 이 질문에 대한 답을 사용자에게 보고하십시오. 결정은 운영자 승인 UI에서 내립니다.', 76, ' \u2502 ')
499
+ + `\n운영자 검토: ${opts.reviewCommand}`;
500
+ }
501
+ return (0, screen_safe_1.wrapColumns)(question
495
502
  + ` 이 질문에 대한 답을 사용자에게 보고하십시오. 결정은 운영자가 ${(0, npx_bin_1.npxBin)()} holmes-kit approve 에서 내립니다.`, 76, ' \u2502 ');
496
503
  }
497
504
  const decided = state.decisions[id];
@@ -501,7 +508,7 @@ function queueHint(root, req, opts) {
501
508
  // @implements A-SPEC-564.2 — the hint is composed BEFORE the enqueue so the refusal record can
502
509
  // carry its own feedback cost: reasonBytes = the caller's base reason + this hint, i.e. the text
503
510
  // that actually re-enters the conversation. Observation only — nothing reads it on a gate path.
504
- const hint = `${denialLine}\n[승인 대기 ${id}] 운영자: ${(0, npx_bin_1.npxBin)()} holmes-kit approve`;
511
+ const hint = denialLine + (opts?.pendingHint ? opts.pendingHint(id) : `\n[승인 대기 ${id}] 운영자: ${(0, npx_bin_1.npxBin)()} holmes-kit approve`);
505
512
  return enqueueApprovalRequest(root, { ...req, reasonBytes: (opts?.baseReasonBytes ?? 0) + hint.length })
506
513
  ? hint
507
514
  : denialLine;