@holmes-lab/holmes-kit 0.35.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 (37) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +5 -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/risk-classifier.js +45 -24
  16. package/dist/holmes/guardrail/shell-argument-roles.d.ts +15 -0
  17. package/dist/holmes/guardrail/shell-argument-roles.js +209 -0
  18. package/dist/holmes/guardrail/shell-syntax.d.ts +20 -0
  19. package/dist/holmes/guardrail/shell-syntax.js +489 -0
  20. package/dist/holmes/guardrail/shell-words.d.ts +2 -18
  21. package/dist/holmes/guardrail/shell-words.js +15 -441
  22. package/dist/holmes/guardrail/write-target.d.ts +54 -0
  23. package/dist/holmes/guardrail/write-target.js +327 -1
  24. package/dist/holmes/hooks/pre-tool-use.d.ts +12 -0
  25. package/dist/holmes/hooks/pre-tool-use.js +377 -66
  26. package/dist/holmes/mcp/handlers.d.ts +9 -1
  27. package/dist/holmes/mcp/handlers.js +6 -4
  28. package/dist/holmes/mcp/operator-recovery.d.ts +9 -0
  29. package/dist/holmes/mcp/operator-recovery.js +63 -0
  30. package/dist/holmes/runtime/binding.d.ts +30 -0
  31. package/dist/holmes/runtime/binding.js +164 -0
  32. package/dist/holmes/runtime/dispatch.d.ts +9 -0
  33. package/dist/holmes/runtime/dispatch.js +169 -0
  34. package/dist/holmes/runtime/hook-process.d.ts +11 -0
  35. package/dist/holmes/runtime/hook-process.js +130 -0
  36. package/docs/install-guide.md +65 -0
  37. package/package.json +1 -1
@@ -0,0 +1,63 @@
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.operatorRecovery = operatorRecovery;
37
+ // @implements A-SPEC-754
38
+ const path = __importStar(require("node:path"));
39
+ const unsafeDisplay = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;
40
+ function literal(value, platform) {
41
+ return platform === 'win32' ? `'${value.replace(/'/g, "''")}'` : `'${value.replace(/'/g, `'\\''`)}'`;
42
+ }
43
+ /** Formatting only: the caller must return pending text only after a successful enqueue. */
44
+ function operatorRecovery(root, target, operation, options) {
45
+ const platform = options?.platform ?? process.platform;
46
+ const executable = options?.executable ?? process.execPath;
47
+ // Both src/holmes/mcp (tests) and dist/holmes/mcp (installed) have the same depth.
48
+ const cli = options?.cli ?? path.resolve(__dirname, '../../..', 'bin/holmes-kit.js');
49
+ const commandSafe = [root, executable, cli].every(value => value.length > 0 && value.length <= 2048 && !unsafeDisplay.test(value));
50
+ const command = commandSafe ? `${platform === 'win32' ? '& ' : ''}${literal(executable, platform)} ${literal(cli, platform)} approve --target ${literal(root, platform)}` : '';
51
+ const display = (value) => JSON.stringify(value.slice(0, 300)).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
52
+ return {
53
+ reviewCommand: command || 'the installed Holmes-Kit approval UI (path cannot be safely displayed; no command emitted)',
54
+ pendingHint(id) {
55
+ if (!/^req-[a-f0-9]{12}$/.test(id))
56
+ return '';
57
+ if (!command)
58
+ return `\n[승인 대기 ${id}] The request was recorded. Use the installed approval UI; a path exceeds the safe command display limit. No truncated command is provided.`;
59
+ return `\n[승인 대기 ${id}] 운영자: ${command} --grant ${literal(id, platform)}`
60
+ + `\nAfter official approval, retry ${operation ? display(operation) : 'the original MCP operation'} for target ${display(target)} in the same workspace. Do not retry until approval is available.`;
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,30 @@
1
+ export interface RuntimeRegistry {
2
+ version: 1;
3
+ releasePackageRoot: string;
4
+ bindings: {
5
+ workspaceRoot: string;
6
+ packageRoot: string;
7
+ }[];
8
+ }
9
+ export interface RuntimeSelection {
10
+ mode: 'development' | 'release';
11
+ workspaceRoot: string;
12
+ packageRoot: string;
13
+ buildId: string;
14
+ specsRoot: string;
15
+ }
16
+ export type RuntimeHarness = 'claude' | 'codex' | 'antigravity';
17
+ export type RuntimeEntry = 'mcp' | 'pre-tool-use' | 'stop';
18
+ export declare const RUNTIME_ENTRIES: string[];
19
+ export declare function readBounded(file: string, max?: number): string;
20
+ export declare function canonicalDirectory(value: string): string;
21
+ export declare function workspaceRoot(cwd: string): string;
22
+ export declare function inside(root: string, target: string): boolean;
23
+ export declare function validateRegistry(input: unknown): RuntimeRegistry;
24
+ export declare function readRuntimeRegistry(file: string): RuntimeRegistry;
25
+ export declare function verifyRuntime(packageRoot: string): string;
26
+ export declare function selectRuntime(registry: RuntimeRegistry, context: {
27
+ cwd: string;
28
+ workspaceHints?: string[];
29
+ specsHint?: string;
30
+ }): RuntimeSelection;
@@ -0,0 +1,164 @@
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.RUNTIME_ENTRIES = void 0;
37
+ exports.readBounded = readBounded;
38
+ exports.canonicalDirectory = canonicalDirectory;
39
+ exports.workspaceRoot = workspaceRoot;
40
+ exports.inside = inside;
41
+ exports.validateRegistry = validateRegistry;
42
+ exports.readRuntimeRegistry = readRuntimeRegistry;
43
+ exports.verifyRuntime = verifyRuntime;
44
+ exports.selectRuntime = selectRuntime;
45
+ // @implements A-SPEC-751
46
+ const fs = __importStar(require("node:fs"));
47
+ const path = __importStar(require("node:path"));
48
+ exports.RUNTIME_ENTRIES = ['bin/holmes-mcp.js', 'bin/holmes-hook-antigravity.js', 'bin/holmes-stop-antigravity.js',
49
+ 'dist/holmes/hooks/pre-tool-use.js', 'dist/holmes/hooks/stop.js'];
50
+ function readBounded(file, max = 2 * 1024 * 1024) {
51
+ // O_NONBLOCK prevents a raced FIFO from holding a lifecycle hook indefinitely.
52
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0));
53
+ try {
54
+ const st = fs.fstatSync(fd);
55
+ if (!st.isFile() || st.size > max)
56
+ throw new Error(`Not a bounded regular file: ${file}`);
57
+ const bytes = Buffer.alloc(max + 1);
58
+ let length = 0;
59
+ while (length < bytes.length) {
60
+ const n = fs.readSync(fd, bytes, length, bytes.length - length, null);
61
+ if (!n)
62
+ break;
63
+ length += n;
64
+ }
65
+ if (length > max)
66
+ throw new Error(`File exceeds size limit: ${file}`);
67
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, length));
68
+ }
69
+ finally {
70
+ fs.closeSync(fd);
71
+ }
72
+ }
73
+ function canonicalDirectory(value) {
74
+ if (typeof value !== 'string' || !path.isAbsolute(value))
75
+ throw new Error('Runtime paths must be absolute');
76
+ const real = fs.realpathSync.native(value);
77
+ if (!fs.statSync(real).isDirectory())
78
+ throw new Error(`Not a directory: ${value}`);
79
+ return real;
80
+ }
81
+ function workspaceRoot(cwd) {
82
+ const initial = canonicalDirectory(cwd);
83
+ for (let at = initial;; at = path.dirname(at)) {
84
+ if (fs.existsSync(path.join(at, '.ax')) || fs.existsSync(path.join(at, '.git')))
85
+ return at;
86
+ if (path.dirname(at) === at)
87
+ return initial;
88
+ }
89
+ }
90
+ function inside(root, target) {
91
+ const rel = path.relative(root, target);
92
+ return rel === '' || (!path.isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${path.sep}`));
93
+ }
94
+ function validateRegistry(input) {
95
+ const r = input;
96
+ if (!r || r.version !== 1 || !Array.isArray(r.bindings) || r.bindings.length > 1000)
97
+ throw new Error('Invalid runtime registry schema');
98
+ const canonical = (p) => {
99
+ const c = canonicalDirectory(p);
100
+ if (c !== p)
101
+ throw new Error(`Registry path is no longer canonical: ${p}; register its current location explicitly`);
102
+ return c;
103
+ };
104
+ const releasePackageRoot = canonical(r.releasePackageRoot);
105
+ const seen = new Set();
106
+ const bindings = r.bindings.map((b) => {
107
+ if (!b || typeof b !== 'object')
108
+ throw new Error('Invalid runtime binding');
109
+ const root = canonical(b.workspaceRoot);
110
+ if (seen.has(root))
111
+ throw new Error(`Duplicate runtime binding: ${root}`);
112
+ seen.add(root);
113
+ return { workspaceRoot: root, packageRoot: canonical(b.packageRoot) };
114
+ });
115
+ return { version: 1, releasePackageRoot, bindings };
116
+ }
117
+ function readRuntimeRegistry(file) {
118
+ if (!path.isAbsolute(file))
119
+ throw new Error('Runtime registry path must be absolute');
120
+ try {
121
+ return validateRegistry(JSON.parse(readBounded(file)));
122
+ }
123
+ catch (e) {
124
+ throw new Error(`Cannot use runtime registry ${file}: ${e.message}. Repair runtime-binding setup.`);
125
+ }
126
+ }
127
+ function verifyRuntime(packageRoot) {
128
+ try {
129
+ const pkg = JSON.parse(readBounded(path.join(packageRoot, 'package.json'), 128 * 1024));
130
+ if (pkg.name !== '@holmes-lab/holmes-kit')
131
+ throw new Error('Unexpected package name');
132
+ for (const relative of exports.RUNTIME_ENTRIES) {
133
+ const entry = fs.realpathSync.native(path.join(packageRoot, relative));
134
+ if (!inside(packageRoot, entry) || !fs.statSync(entry).isFile())
135
+ throw new Error(`Invalid entrypoint ${relative}`);
136
+ }
137
+ const buildId = readBounded(path.join(packageRoot, 'dist/.build-id'), 1024).trim();
138
+ if (!buildId || /[\x00-\x1f\x7f]/.test(buildId))
139
+ throw new Error('Invalid build identity');
140
+ return buildId;
141
+ }
142
+ catch (e) {
143
+ throw new Error(`Runtime build unavailable at ${packageRoot}: ${e.message}. Run npm run build in that checkout or repair the installed package; no release fallback.`);
144
+ }
145
+ }
146
+ function selectRuntime(registry, context) {
147
+ const checked = validateRegistry(registry);
148
+ const root = workspaceRoot(context.cwd);
149
+ for (const hint of context.workspaceHints ?? []) {
150
+ if (workspaceRoot(hint) !== root)
151
+ throw new Error('Conflicting runtime workspace hints; repair harness wiring');
152
+ }
153
+ const specsRoot = path.join(root, '.ax', 'specs');
154
+ const governanceRoot = path.join(root, '.ax');
155
+ if (fs.existsSync(governanceRoot) && !inside(root, fs.realpathSync.native(governanceRoot)))
156
+ throw new Error('Governance directory escapes the selected workspace');
157
+ if (context.specsHint && path.resolve(root, context.specsHint) !== specsRoot)
158
+ throw new Error('Conflicting HOLMES_SPECS; remove the fixed spec-store override');
159
+ if (fs.existsSync(specsRoot) && !inside(root, fs.realpathSync.native(specsRoot)))
160
+ throw new Error('Spec store escapes the selected workspace');
161
+ const binding = checked.bindings.find((b) => b.workspaceRoot === root);
162
+ const packageRoot = binding?.packageRoot ?? checked.releasePackageRoot;
163
+ return { mode: binding ? 'development' : 'release', workspaceRoot: root, packageRoot, buildId: verifyRuntime(packageRoot), specsRoot };
164
+ }
@@ -0,0 +1,9 @@
1
+ import type { RuntimeHarness, RuntimeEntry } from './binding';
2
+ export interface DispatchOptions {
3
+ registryPath: string;
4
+ harness: RuntimeHarness;
5
+ entry: RuntimeEntry;
6
+ hookBudgetMs?: number;
7
+ cleanupBudgetMs?: number;
8
+ }
9
+ export declare function runDispatch(opts: DispatchOptions): Promise<void>;
@@ -0,0 +1,169 @@
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.runDispatch = runDispatch;
37
+ // @implements A-SPEC-751, A-SPEC-751.1, A-SPEC-754
38
+ const path = __importStar(require("node:path"));
39
+ const node_child_process_1 = require("node:child_process");
40
+ const binding_1 = require("./binding");
41
+ const hook_process_1 = require("./hook-process");
42
+ function hookInput(budget) {
43
+ return new Promise((resolve, reject) => {
44
+ const chunks = [];
45
+ let length = 0;
46
+ const timeout = setTimeout(() => finish(new Error('Hook input deadline exceeded')), budget);
47
+ const finish = (error) => {
48
+ clearTimeout(timeout);
49
+ process.stdin.removeListener('data', data);
50
+ process.stdin.removeListener('end', end);
51
+ process.stdin.removeListener('error', fail);
52
+ process.stdin.pause();
53
+ if (error)
54
+ reject(error);
55
+ else
56
+ resolve(Buffer.concat(chunks));
57
+ };
58
+ const data = (chunk) => { length += chunk.length; if (length > 2 * 1024 * 1024)
59
+ finish(new Error('Hook input exceeds 2 MiB'));
60
+ else
61
+ chunks.push(chunk); };
62
+ const end = () => finish();
63
+ const fail = (error) => finish(error);
64
+ process.stdin.on('data', data).once('end', end).once('error', fail);
65
+ });
66
+ }
67
+ function hintsFromInput(input) {
68
+ const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(input));
69
+ if (!value || typeof value !== 'object' || Array.isArray(value))
70
+ throw new Error('Invalid hook input object');
71
+ const hints = [];
72
+ for (const name of ['cwd', 'project_dir']) {
73
+ if (value[name] !== undefined) {
74
+ if (typeof value[name] !== 'string' || !value[name])
75
+ throw new Error(`Invalid hook ${name}`);
76
+ hints.push(value[name]);
77
+ }
78
+ }
79
+ if (value.workspacePaths !== undefined) {
80
+ if (!Array.isArray(value.workspacePaths) || !value.workspacePaths.length || value.workspacePaths.some((v) => typeof v !== 'string' || !v))
81
+ throw new Error('Invalid workspacePaths');
82
+ hints.push(...value.workspacePaths);
83
+ }
84
+ return hints;
85
+ }
86
+ async function runDispatch(opts) {
87
+ const started = performance.now();
88
+ let selectedBuild;
89
+ let selectedPackage;
90
+ let selectedWorkspace = process.cwd();
91
+ try {
92
+ if (!['claude', 'codex', 'antigravity'].includes(opts.harness) || !['mcp', 'pre-tool-use', 'stop'].includes(opts.entry))
93
+ throw new Error('Invalid runtime dispatcher entry or harness');
94
+ const hookBudget = (0, hook_process_1.boundedHookBudget)(opts.hookBudgetMs, hook_process_1.HOOK_BUDGET_MS);
95
+ const cleanupBudget = (0, hook_process_1.boundedHookBudget)(opts.cleanupBudgetMs, hook_process_1.HOOK_CLEANUP_MS);
96
+ const input = opts.entry === 'mcp' ? undefined : await hookInput(hookBudget);
97
+ const hints = input ? hintsFromInput(input) : [];
98
+ if (process.env.CLAUDE_PROJECT_DIR)
99
+ hints.push(process.env.CLAUDE_PROJECT_DIR);
100
+ const selection = (0, binding_1.selectRuntime)((0, binding_1.readRuntimeRegistry)(opts.registryPath), { cwd: process.cwd(), workspaceHints: hints, specsHint: process.env.HOLMES_SPECS });
101
+ selectedBuild = selection.buildId;
102
+ selectedPackage = selection.packageRoot;
103
+ selectedWorkspace = selection.workspaceRoot;
104
+ const relative = opts.entry === 'mcp' ? 'bin/holmes-mcp.js'
105
+ : opts.harness === 'antigravity' ? (opts.entry === 'stop' ? 'bin/holmes-stop-antigravity.js' : 'bin/holmes-hook-antigravity.js')
106
+ : `dist/holmes/hooks/${opts.entry}.js`;
107
+ const remaining = hookBudget - (performance.now() - started);
108
+ if (input && remaining <= 0)
109
+ throw new Error('Hook input/selection deadline exceeded');
110
+ if (opts.entry === 'mcp') {
111
+ // This is a dedicated transport process, not a reusable multi-server host.
112
+ // Keep its genuine parent and argv for native attestation. The selected
113
+ // entry still owns build validation, package dependencies and autoreload.
114
+ process.chdir(selection.workspaceRoot);
115
+ process.env.HOLMES_SPECS = selection.specsRoot;
116
+ process.env.CLAUDE_PROJECT_DIR = selection.workspaceRoot;
117
+ require(path.join(selection.packageRoot, relative));
118
+ return;
119
+ }
120
+ const child = (0, node_child_process_1.spawn)(process.execPath, [path.join(selection.packageRoot, relative)], {
121
+ cwd: selection.workspaceRoot,
122
+ env: { ...process.env, HOLMES_SPECS: selection.specsRoot, CLAUDE_PROJECT_DIR: selection.workspaceRoot },
123
+ stdio: ['pipe', input ? 'pipe' : 'inherit', 'inherit'],
124
+ detached: input !== undefined && process.platform !== 'win32', windowsHide: true,
125
+ });
126
+ if (input) {
127
+ const result = await (0, hook_process_1.runHookChild)(child, input, remaining, cleanupBudget);
128
+ if (result.signal) {
129
+ process.kill(process.pid, result.signal);
130
+ return;
131
+ }
132
+ if (!result.bytes.length && result.code !== 0)
133
+ throw new Error(`Selected hook runtime failed (exit ${result.code}) without a decision`);
134
+ if (result.bytes.length) {
135
+ try {
136
+ JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(result.bytes));
137
+ }
138
+ catch {
139
+ throw new Error('Selected hook runtime returned invalid JSON');
140
+ }
141
+ process.stdout.write(result.bytes);
142
+ }
143
+ process.exitCode = result.code ?? 1;
144
+ return;
145
+ }
146
+ }
147
+ catch (error) {
148
+ const shellWord = (word) => process.platform === 'win32' ? JSON.stringify(word) : `'${word.replace(/'/g, `'\\''`)}'`;
149
+ const cli = selectedPackage ? `${shellWord(process.execPath)} ${shellWord(path.join(selectedPackage, 'bin/holmes-kit.js'))}` : 'holmes-kit';
150
+ const recovery = opts.entry === 'mcp' ? '' : ` [${opts.harness}/${opts.entry}${selectedBuild ? ` build ${selectedBuild}` : ''}]. Diagnose with ${cli} runtime-binding status --workspace ${shellWord(selectedWorkspace)} --registry ${shellWord(opts.registryPath)} and ${cli} doctor --target ${shellWord(selectedWorkspace)} --registry ${shellWord(opts.registryPath)}. Repair the selected runtime through the approved installation workflow, then retry the original operation. Pending governance findings remain unresolved.`;
151
+ const reason = `[Holmes-Kit] Runtime dispatch refused: ${error.message}${recovery}`;
152
+ process.stderr.write(`${reason}\n`);
153
+ // A partially loaded entry may have opened handles; exitCode alone would
154
+ // leave a failed transport alive indefinitely.
155
+ if (opts.entry === 'mcp') {
156
+ process.exit(1);
157
+ }
158
+ const output = opts.harness === 'antigravity' ? { decision: opts.entry === 'stop' ? 'continue' : 'deny', reason }
159
+ : opts.entry === 'stop' ? { decision: 'block', reason }
160
+ : { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } };
161
+ process.stdout.write(`${JSON.stringify(output)}\n`);
162
+ process.exitCode = 0;
163
+ }
164
+ }
165
+ if (require.main === module) {
166
+ const args = process.argv.slice(2);
167
+ const value = (name) => args[args.indexOf(name) + 1];
168
+ void runDispatch({ registryPath: value('--registry'), harness: value('--harness'), entry: value('--entry') });
169
+ }
@@ -0,0 +1,11 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ export declare const HOOK_BUDGET_MS = 18000;
3
+ export declare const HOOK_CLEANUP_MS = 8000;
4
+ export declare function boundedHookBudget(value: number | undefined, maximum: number): number;
5
+ export interface HookChildResult {
6
+ bytes: Buffer;
7
+ code: number | null;
8
+ signal: NodeJS.Signals | null;
9
+ }
10
+ /** Bounded hook transport only. Persistent MCP transports do not call this function. */
11
+ export declare function runHookChild(child: ChildProcess, input: Buffer, remainingMs: number, cleanupMs: number): Promise<HookChildResult>;
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HOOK_CLEANUP_MS = exports.HOOK_BUDGET_MS = void 0;
4
+ exports.boundedHookBudget = boundedHookBudget;
5
+ exports.runHookChild = runHookChild;
6
+ // @implements A-SPEC-751.1
7
+ const node_child_process_1 = require("node:child_process");
8
+ exports.HOOK_BUDGET_MS = 18_000;
9
+ exports.HOOK_CLEANUP_MS = 8_000;
10
+ function boundedHookBudget(value, maximum) {
11
+ if (value === undefined)
12
+ return maximum;
13
+ if (!Number.isInteger(value) || value <= 0 || value > maximum)
14
+ throw new Error('Invalid hook deadline budget');
15
+ return value;
16
+ }
17
+ const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
18
+ /** Only a child spawned by this dispatcher may be supplied. Never enumerate unrelated PIDs. */
19
+ async function stopOwnedChild(child, closed, budget) {
20
+ const until = performance.now() + budget;
21
+ let failure;
22
+ try {
23
+ if (child.pid && process.platform === 'win32' && !closed()) {
24
+ failure = await new Promise(resolve => {
25
+ const killer = (0, node_child_process_1.spawn)('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
26
+ let settled = false;
27
+ const finish = (reason) => {
28
+ if (settled)
29
+ return;
30
+ settled = true;
31
+ clearTimeout(timer);
32
+ resolve(reason);
33
+ };
34
+ const timer = setTimeout(() => { killer.kill('SIGKILL'); killer.unref(); finish('process tree cleanup timed out'); }, Math.max(1, until - performance.now()));
35
+ killer.once('error', () => finish('process tree cleanup could not start'));
36
+ killer.once('close', code => finish(code === 0 ? undefined : `process tree cleanup exited ${code}`));
37
+ });
38
+ }
39
+ else if (child.pid && process.platform !== 'win32') {
40
+ const kill = (signal) => {
41
+ try {
42
+ process.kill(-child.pid, signal);
43
+ }
44
+ catch (error) {
45
+ if (error.code !== 'ESRCH')
46
+ throw error;
47
+ }
48
+ };
49
+ kill('SIGTERM');
50
+ await delay(Math.min(100, budget / 4));
51
+ // A wrapper can exit first while its descendant keeps a pipe open or ignores SIGTERM.
52
+ kill('SIGKILL');
53
+ }
54
+ }
55
+ catch {
56
+ failure = 'owned process tree cleanup failed';
57
+ }
58
+ child.stdin?.destroy();
59
+ child.stdout?.destroy();
60
+ child.stderr?.destroy();
61
+ while (!closed() && performance.now() < until)
62
+ await delay(Math.min(20, Math.max(1, until - performance.now())));
63
+ if (!closed()) {
64
+ child.unref();
65
+ return failure ?? 'child closure could not be confirmed before cleanup deadline';
66
+ }
67
+ return failure;
68
+ }
69
+ /** Bounded hook transport only. Persistent MCP transports do not call this function. */
70
+ function runHookChild(child, input, remainingMs, cleanupMs) {
71
+ return new Promise((resolve, reject) => {
72
+ const output = [];
73
+ let bytes = 0;
74
+ let closed = false;
75
+ let finishing = false;
76
+ let externalSignal;
77
+ const signals = ['SIGTERM', 'SIGINT', 'SIGHUP'];
78
+ const handlers = signals.map(signal => () => {
79
+ externalSignal ??= signal;
80
+ void finish(undefined, { bytes: Buffer.alloc(0), code: null, signal: externalSignal }, true);
81
+ });
82
+ const timer = setTimeout(() => { void finish(new Error('Selected hook runtime deadline exceeded'), undefined, true); }, Math.max(1, remainingMs));
83
+ const finish = async (error, result, stop = false) => {
84
+ if (finishing)
85
+ return;
86
+ finishing = true;
87
+ clearTimeout(timer);
88
+ let cleanupFailure;
89
+ if (stop)
90
+ cleanupFailure = await stopOwnedChild(child, () => closed, cleanupMs);
91
+ if (externalSignal) {
92
+ error = undefined;
93
+ result = { bytes: Buffer.alloc(0), code: null, signal: externalSignal };
94
+ }
95
+ signals.forEach((signal, i) => process.removeListener(signal, handlers[i]));
96
+ child.stdout?.removeListener('data', onData);
97
+ child.stdin?.removeListener('error', onInputError);
98
+ if (cleanupFailure) {
99
+ if (result?.signal)
100
+ process.stderr.write(`[Holmes-Kit] ${cleanupFailure}\n`);
101
+ else
102
+ error = new Error(`${error?.message ?? 'Hook transport failed'}; cleanup unconfirmed: ${cleanupFailure}`);
103
+ }
104
+ if (error)
105
+ reject(error);
106
+ else
107
+ resolve(result);
108
+ };
109
+ const onData = (chunk) => {
110
+ if (finishing)
111
+ return;
112
+ bytes += chunk.length;
113
+ if (bytes > 2 * 1024 * 1024)
114
+ void finish(new Error('Hook output exceeds 2 MiB'), undefined, true);
115
+ else
116
+ output.push(chunk);
117
+ };
118
+ const onInputError = (error) => { if (error.code !== 'EPIPE')
119
+ void finish(new Error('Hook input delivery failed'), undefined, true); };
120
+ child.stdout.on('data', onData);
121
+ child.stdin.on('error', onInputError);
122
+ child.once('error', error => { void finish(error, undefined, true); });
123
+ child.once('close', (code, signal) => {
124
+ closed = true;
125
+ void finish(undefined, { bytes: Buffer.concat(output), code, signal }, signal !== null);
126
+ });
127
+ signals.forEach((signal, i) => process.on(signal, handlers[i]));
128
+ child.stdin.end(input);
129
+ });
130
+ }
@@ -17,6 +17,71 @@ worked on the first try. Find your row, run its one command.
17
17
  The local install is the path verified end to end, on macOS and Windows, against the public
18
18
  registry. The wiring `init` writes uses absolute paths, so nothing needs to be on `PATH`.
19
19
 
20
+ ## Development and consumer runtime binding
21
+
22
+ Maintainers can register a built development package without replacing the release used by consumer
23
+ projects. This explicit installation is separate from ordinary `init`. It applies to Claude Code, Codex
24
+ and Antigravity through a shared resolver; successful setup is not proof that a native session loaded or
25
+ trusted its hooks.
26
+
27
+ Choose three absolute paths: the development workspace, its complete built Holmes-Kit package, and the
28
+ installed release package. The built package must contain its CLI, MCP entry, compiled hooks and build ID.
29
+ Use the built package's CLI to preview the installation (replace the example paths):
30
+
31
+ ```sh
32
+ node "/absolute/development-package/bin/holmes-kit.js" runtime-binding setup --workspace "/absolute/workspace" --package "/absolute/development-package" --release-package "/absolute/release-package" --dry-run
33
+ ```
34
+
35
+ The default registry is `~/.holmes/runtime/bindings.json`. An explicit `--registry` selects another
36
+ operator-controlled destination; keep that same path on setup, status and doctor calls. A repository marker
37
+ cannot register executable code. Linked worktrees and independent nested workspaces require their own
38
+ binding; missing development builds never silently fall back to the release.
39
+
40
+ Review the exact changed files and resolve every conflict. Then run the same setup without `--dry-run`
41
+ from the operator terminal. If it prints an approval request, that invocation has not applied the plan.
42
+ Review and grant only that current request through the same built CLI:
43
+
44
+ ```sh
45
+ node "/absolute/development-package/bin/holmes-kit.js" approve --target "/absolute/workspace" --grant "<request-id>"
46
+ ```
47
+
48
+ Retry the unchanged setup after successful approval. If the plan changed, review its new request instead
49
+ of reusing an old grant. A fully validated zero-change setup needs no additional approval; replacing a build
50
+ at the same path or migrating an old installation receipt is still a real change.
51
+
52
+ Ordinary setup preserves disabled lifecycle entries and native trust. To restore selected Holmes hook
53
+ entries, include `--activate-hooks claude,codex,antigravity` (or a subset) in the preview and apply commands.
54
+ Native trust and global disable switches remain native review steps. Do not manufacture trust records or
55
+ assume a new project hook suppresses another user/plugin hook.
56
+
57
+ After installation, inspect selection and diagnosis:
58
+
59
+ ```sh
60
+ node "/absolute/development-package/bin/holmes-kit.js" runtime-binding status --workspace "/absolute/workspace"
61
+ node "/absolute/development-package/bin/holmes-kit.js" doctor --target "/absolute/workspace"
62
+ ```
63
+
64
+ For a custom registry, add its `--registry` argument to both commands. Reconnect the MCP server if it still
65
+ reports the old build. In a fresh native session, compare MCP and hook package/build/workspace/spec store,
66
+ then observe permission, refusal, official recovery, original task resumption and normal Stop. Repeat in
67
+ each harness and in an unregistered consumer workspace. `binding: matched`, doctor output and generated
68
+ configuration alone do not establish live enforcement.
69
+
70
+ **Approval recovery:** the dedicated MCP dispatcher loads the validated package entry in the same process,
71
+ preserving its genuine native parent. The entry retains its opt-in autoreload supervisor; that chain or
72
+ another host may still be unable to attest. Such routes use the official operator queue without relaxing
73
+ native identity checks. Follow the displayed command: it names the running package's CLI, bound workspace
74
+ and recorded request ID. Do not keep retrying the same refused action without a new decision. Retry the
75
+ original MCP operation after the grant is recognized. Held questions and denial reasons must first be
76
+ addressed; expired, wrong-scope or consumed authority needs an official decision. A chat acknowledgement
77
+ is not a grant. Validate the actual newly installed session before claiming that recovery works there.
78
+
79
+ Routed hooks bound input/selection/execution to 18 seconds and owned-process cleanup to another 8 seconds.
80
+ On timeout or malformed output they return native refusal guidance with status/doctor commands. Repair the
81
+ selected package through a reviewed installation, then retry the original operation. Cleanup uncertainty
82
+ and pending findings remain visible. These bounds do not guarantee that every native host or operating-system
83
+ failure is recoverable without operator action. MCP itself has no hook lifetime deadline.
84
+
20
85
  ## Before `npm install -g`: check your prefix
21
86
 
22
87
  ```
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "//": "@implements A-SPEC-209",
3
3
  "name": "@holmes-lab/holmes-kit",
4
- "version": "0.35.0",
4
+ "version": "0.35.1",
5
5
  "description": "Holmes-Kit — deterministic Agentic Software Engineering (ASE) harness with causal traceability (spec chain + D-CPG + RTM + phase guardrail)",
6
6
  "main": "dist/holmes/mcp/server.js",
7
7
  "types": "dist/holmes/mcp/server.d.ts",