@holmes-lab/holmes-kit 0.35.4 → 0.35.6

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,69 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
  <!-- @implements A-SPEC-209 -->
8
+ ## [0.35.6] - 2026-10-05
9
+
10
+ ### Added
11
+
12
+ - **A registered binding can be re-applied from inside the session** (A-SPEC-752.10). The new MCP tool
13
+ `runtime_binding` previews (`operation: "preview"`, the default) and applies (`operation: "apply"`) the plan
14
+ `holmes-kit runtime-binding setup` would make for the workspace the session is in, with `activate_hooks` naming the
15
+ harnesses whose Holmes hooks to restore. It takes no package argument: it plans only for the package and release
16
+ package the operator registry already names, so which build governs a workspace is still decided in a terminal, and
17
+ a workspace the registry does not name is refused. `apply` shows the plan digest and the files in the approval
18
+ dialog and writes only on an explicit approve answer there. A denial, an unanswered dialog, a client without the
19
+ form dialog and autonomous approval all write nothing; the request the CLI would file is filed and returned
20
+ instead. A plan with conflicts is not applied, and a plan that changed between the preview and the answer is
21
+ refused. An approved apply is recorded in the provenance ledger with the plan digest, like a terminal grant.
22
+ Limit: native trust of a hook in Codex is still given in Codex's own `/hooks` review.
23
+
24
+ ## [0.35.5] - 2026-10-05
25
+
26
+ ### Added
27
+
28
+ - **`doctor` says when a source checkout's hooks are not the hooks its sessions run** (A-SPEC-751.4). A checkout of
29
+ this package whose sessions are routed to another install (the usual arrangement for developing Holmes-Kit itself:
30
+ a broken edit cannot then switch off its own gate) gets a `development hooks` row. It compares every compiled file
31
+ under `dist/holmes` by content, and has both packages' PreToolUse programs judge the same eight hook payloads in a
32
+ temporary project; nothing in a payload is executed. WARN names the files and the payloads decided differently, and
33
+ says when both sides carry one build id although their code differs. PASS means the two are identical. The row adds
34
+ about two seconds and does not appear in a consumer project.
35
+
36
+ ### Changed
37
+
38
+ - **Claude's SessionStart hook is routed like the other hooks** (A-SPEC-751.5). On a machine with a runtime registry
39
+ the PreToolUse, Stop and MCP entries already went through the operator dispatcher, while an existing SessionStart
40
+ entry kept pointing at one package's `session-start.js`. `runtime-binding setup` now writes
41
+ `claude-session-start.js` beside the registry and rewrites an existing Holmes SessionStart entry in the Claude
42
+ settings files it manages to it; a settings file without such an entry gains none. A session start is not a gate:
43
+ whatever goes wrong in that entry, it exits 0 with no output and never holds a session up. Nothing is wired for
44
+ Codex or Antigravity — measured: Antigravity calls a SessionStart hook but passes none of eight output shapes to the
45
+ model, and Codex does not call an untrusted project hook.
46
+
47
+ ### Security
48
+
49
+ - **A binding plan no longer switches the Codex gate off** (A-SPEC-752.9). Codex keeps a hook's enable state under a
50
+ positional key (`<hooks file>:<event>:<group>:<hook>`). `runtime-binding setup` could remove the running Holmes
51
+ entry from the user hooks file and write the dispatcher entry at a position whose key said `enabled = false`; the
52
+ gate was written and never ran, in every workspace on the machine, and the preview showed only file differences.
53
+ Measured: Codex then ran a command the gate refuses. A gate the plan would write into a switched-off place is now a
54
+ conflict that names the key and what to do, and the plan is not applied; with `--activate-hooks codex` the gate is
55
+ written to the workspace's project hooks file instead. If you ran `runtime-binding setup` with 0.35.2–0.35.4 on a
56
+ machine where a Holmes hook was switched off in Codex, run `holmes-kit doctor`: `FAIL codex user hooks` means the
57
+ gate is not running there.
58
+
59
+ ### Fixed
60
+
61
+ - **The installer apply is refused with its own wording wherever its operation word sits** (A-SPEC-753.3). The
62
+ session-side refusal of `holmes-kit runtime-binding setup|remove` read one exact grammar, while the CLI takes the
63
+ operation word anywhere after `runtime-binding`; a trailing `&& true`, a redirect, a line break or a leading
64
+ `cd … &&` also fell outside it, so the refusal that names the act and gives the operator the command did not fire.
65
+ Any command of the line that runs the Holmes CLI with `runtime-binding`, a literal `setup` or `remove` and no
66
+ `--dry-run` is now refused as governance wiring, and the operator part carries that one command as written.
67
+ Outside the rule, as before: a runner or wrapper before the CLI word (`npx`, `env`, `sudo`), an operation word that
68
+ is not literal, any substitution, and a command whose own text holds a line break — there the CLI's own approval is
69
+ the barrier.
70
+
8
71
  ## [0.35.4] - 2026-10-05
9
72
 
10
73
  ### Security
package/README.md CHANGED
@@ -24,6 +24,8 @@ Measured at `173b99650442` (specs `sha256:215f84d4e9f4`) — reproduce with `hol
24
24
  ### 🛡️ Currently Supported Features (Production Features)
25
25
 
26
26
  - **The protected store is recognised however a shell command spells it** *(new in 0.35.2 — security fix, upgrade recommended)*: through 0.35.1 a path into `.ax/specs`, `.ax/ledger`, `.ax/approvals` or `.ax/state` written directly after a shell expansion, a variable, or a character the shell removes at run time was not seen as protected, so a removal, move or overwrite of governance state could pass the gate. The store spelling now counts wherever it appears in a command, and an output redirect to a computed target is not a read. Reads still pass. A directory that merely ends in `.ax` and has a child named like the store's is judged as the store. Limit: a path assembled so the spelling never appears in the command text is outside this rule.
27
+ - **Re-apply a registered runtime binding without leaving the session** *(new in 0.35.6)*: the MCP tool `runtime_binding` previews and applies the plan `runtime-binding setup` would make for the registered workspace, including `activate_hooks`. It never chooses a build — it uses the package the operator registry already names — and it writes only when you answer approve in the approval dialog, which shows the plan digest and the files. No answer, a denial, a client without the dialog, or autonomous approval write nothing and leave the usual queue request. Native hook trust in Codex is still given in Codex's `/hooks`.
28
+ - **`doctor` shows when a checkout's hooks are not the ones its sessions run** *(new in 0.35.5)*: when you develop Holmes-Kit itself with sessions routed to a released install, the `development hooks` row compares the compiled files and has both hook programs judge the same payloads, so a hook change that is not live yet is visible instead of assumed. In the same release, `runtime-binding setup` refuses a plan that would write the Codex gate where Codex has it switched off *(security fix — if you ran setup with 0.35.2–0.35.4, check `doctor` for `FAIL codex user hooks`)*.
27
29
  - **No in-session shortcut around a person while autonomy is on** *(new in 0.35.4 — security fix, upgrade recommended)*: on a client without the MCP form dialog, the `approval_commit` continuation is no longer offered or accepted while autonomous approval is on — the request goes to the approval queue. Its only human check is the host's own tool confirmation, which an allow rule or auto mode removes. With autonomy off it works as before; seals made through it are recorded as `host-gated:<harness>`.
28
30
  - **An unanswered approval is held, never approved** *(new in 0.35.3 — security fix, upgrade recommended)*: with autonomous approval on, an in-session approval dialog that ran out of time used to be recorded as an approval (actor `autonomous-timeout:<harness>`) — for exactly the seals and critical-finding resolutions autonomy reserves for a person. An unanswered dialog now returns the request to the approval queue in every mode. To audit earlier sessions, search the provenance ledger for `autonomous-timeout`.
29
31
  - **Approvals that fit how people work** *(new in 0.35.2)*: an approval for a request that carries the approved content's digest (a spec seal) no longer expires after 30 minutes — it stays valid until used, revoked, or the content changes (`--ttl` still bounds it; requests without a digest keep the default). With autonomous approval on, a gate change declared `gate-behavior: tightens — …` or `gate-behavior: wording — …` is sealed without the operator; any other gate change still asks, and a seal handed to the operator says which rule handed it over. On a machine with a runtime registry the in-session approval dialog is reachable again, and `init`/`upgrade` no longer replace wiring the registry owns. Not yet changed: the in-session dialog's own time limit.
package/dist/.build-id CHANGED
@@ -1 +1 @@
1
- 3c807953-muurfu01
1
+ be58f332-muva91ep
@@ -67,7 +67,7 @@ exports.wiringHandshakeChecks = wiringHandshakeChecks;
67
67
  exports.semanticCoverageCheck = semanticCoverageCheck;
68
68
  exports.semanticTierVerdict = semanticTierVerdict;
69
69
  exports.detectTreeKeyTemporary = detectTreeKeyTemporary;
70
- // @implements A-SPEC-733, A-SPEC-727, A-SPEC-721, A-SPEC-738, A-SPEC-734, A-SPEC-751, A-SPEC-751.2
70
+ // @implements A-SPEC-751.4, A-SPEC-733, A-SPEC-727, A-SPEC-721, A-SPEC-738, A-SPEC-734, A-SPEC-751, A-SPEC-751.2
71
71
  // @implements A-SPEC-704, A-SPEC-710, A-SPEC-712
72
72
  const doctor_guidance_1 = require("./doctor-guidance");
73
73
  // @implements A-SPEC-264, A-SPEC-423, A-SPEC-549.1, A-SPEC-590
@@ -208,6 +208,7 @@ function resolvesToPackage(filePath, packageRoot) {
208
208
  }
209
209
  }
210
210
  const runtime_binding_1 = require("./runtime-binding");
211
+ const hook_divergence_1 = require("./hook-divergence");
211
212
  const binding_1 = require("../runtime/binding");
212
213
  const RUNTIME_REPAIR = 'Run runtime-binding status and runtime-binding setup --dry-run to review the operator installation.';
213
214
  function routedNativeState(raw, command) {
@@ -738,6 +739,16 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
738
739
  }
739
740
  add('runtime binding', report.conflicts.length ? 'FAIL' : 'WARN', `${s.mode}: workspace=${s.workspaceRoot}; package=${s.packageRoot}; build=${s.buildId}${own}; specs=${s.specsRoot}; live activation unverified`
740
741
  + (report.conflicts.length ? `; ${report.conflicts.join('; ')}` : ''), 'Use runtime-binding status and setup --dry-run to inspect routed wiring. Native hook trust and enable state remain operator-controlled.');
742
+ // @implements A-SPEC-751.4 — a source checkout whose sessions are routed to another package: say whether the
743
+ // hooks it builds are the hooks those sessions run. A consumer project holds no package source and gets no row.
744
+ const checkoutRoot = [target ?? process.cwd(), packageRoot].find((candidate) => {
745
+ const candidateReal = real(candidate);
746
+ return candidateReal !== null && candidateReal !== routedReal && (0, hook_divergence_1.isPackageCheckout)(candidate);
747
+ });
748
+ if (routedReal !== null && checkoutRoot !== undefined) {
749
+ const development = (0, hook_divergence_1.developmentHooksCheck)({ routedPackageRoot: s.packageRoot, routedBuild: s.buildId, checkoutRoot });
750
+ add('development hooks', development.level, development.detail, development.fix);
751
+ }
741
752
  }
742
753
  catch (e) {
743
754
  add('runtime binding', 'FAIL', e.message, 'Repair the registered build or preview runtime-binding setup; never silently fall back to a release.');
@@ -0,0 +1,28 @@
1
+ export interface HookProbe {
2
+ label: string;
3
+ tool: string;
4
+ input: Record<string, unknown>;
5
+ }
6
+ export interface VerdictDifference {
7
+ label: string;
8
+ routed: string;
9
+ checkout: string;
10
+ }
11
+ export interface DevelopmentHooksReport {
12
+ level: 'PASS' | 'WARN';
13
+ detail: string;
14
+ fix?: string;
15
+ totalFiles: number;
16
+ differingFiles: string[];
17
+ differingVerdicts: VerdictDifference[];
18
+ }
19
+ /** One payload per kind of judgement. Labels are what the row prints; the commands are judged, never run. */
20
+ export declare const HOOK_PROBES: readonly HookProbe[];
21
+ /** A source checkout of this package: its hook source and the hook it compiled are both there. */
22
+ export declare function isPackageCheckout(root: string): boolean;
23
+ export declare function developmentHooksCheck(input: {
24
+ routedPackageRoot: string;
25
+ routedBuild: string;
26
+ checkoutRoot: string;
27
+ tmpDir?: string;
28
+ }): DevelopmentHooksReport;
@@ -0,0 +1,189 @@
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.HOOK_PROBES = void 0;
37
+ exports.isPackageCheckout = isPackageCheckout;
38
+ exports.developmentHooksCheck = developmentHooksCheck;
39
+ // @implements A-SPEC-751.4
40
+ /**
41
+ * Whether the hook programs a source checkout builds are the ones its sessions run.
42
+ *
43
+ * The maintenance workspace is bound to a released install on purpose: a broken edit must not be able to switch off
44
+ * its own gate. The cost is that a hook change in the checkout is live in no harness until it is published and the
45
+ * install upgraded — and, measured 2026-10-05, nothing said so: every harness's wired entry allowed a payload the
46
+ * checkout's own hook refused, while doctor printed one build id for both (the checkout's dist had been compiled
47
+ * again without a new id).
48
+ *
49
+ * Two comparisons, both by content and never by file time (A-SPEC-673's measured reason: mtime lies):
50
+ * - bytes: every compiled file under `dist/holmes` on both sides;
51
+ * - verdicts: a fixed set of hook payloads judged by each side's PreToolUse program in a temporary governed
52
+ * project. A hook only judges; nothing in a payload is executed, and the workspace is not written.
53
+ */
54
+ const fs = __importStar(require("node:fs"));
55
+ const os = __importStar(require("node:os"));
56
+ const path = __importStar(require("node:path"));
57
+ const node_crypto_1 = require("node:crypto");
58
+ const node_child_process_1 = require("node:child_process");
59
+ const HOOK = path.join('dist', 'holmes', 'hooks', 'pre-tool-use.js');
60
+ const PROBE_TIMEOUT_MS = 15_000;
61
+ /** One payload per kind of judgement. Labels are what the row prints; the commands are judged, never run. */
62
+ exports.HOOK_PROBES = [
63
+ { label: 'read-only command', tool: 'Bash', input: { command: 'git status' } },
64
+ { label: 'removal in the protected store', tool: 'Bash', input: { command: 'rm -rf .ax/specs/01_req' } },
65
+ { label: 'store path glued to an expansion', tool: 'Bash', input: { command: 'rm${IFS}-rf${IFS}.ax/specs' } },
66
+ { label: 'environment listing', tool: 'Bash', input: { command: 'env' } },
67
+ { label: 'installer apply, exact', tool: 'Bash', input: { command: 'holmes-kit runtime-binding setup --workspace /w' } },
68
+ { label: 'installer apply, rearranged', tool: 'Bash', input: { command: 'holmes-kit runtime-binding --workspace /w remove' } },
69
+ { label: 'unspecified code write', tool: 'Write', input: { file_path: 'src/probe.ts', content: 'export const probe = 1;\n' } },
70
+ { label: 'patch that adds a code file', tool: 'apply_patch', input: { command: '*** Begin Patch\n*** Add File: src/probe.ts\n+export const probe = 1;\n*** End Patch' } },
71
+ ];
72
+ /** A source checkout of this package: its hook source and the hook it compiled are both there. */
73
+ function isPackageCheckout(root) {
74
+ try {
75
+ return fs.statSync(path.join(root, 'src', 'holmes', 'hooks', 'pre-tool-use.ts')).isFile()
76
+ && fs.statSync(path.join(root, HOOK)).isFile();
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ }
82
+ function compiledFiles(packageRoot) {
83
+ const base = path.join(packageRoot, 'dist', 'holmes');
84
+ const found = new Map();
85
+ const walk = (dir) => {
86
+ let entries;
87
+ try {
88
+ entries = fs.readdirSync(dir, { withFileTypes: true });
89
+ }
90
+ catch {
91
+ return;
92
+ }
93
+ for (const entry of entries) {
94
+ const at = path.join(dir, entry.name);
95
+ if (entry.isDirectory())
96
+ walk(at);
97
+ else if (entry.isFile() && entry.name.endsWith('.js')) {
98
+ try {
99
+ found.set(path.relative(base, at).split(path.sep).join('/'), (0, node_crypto_1.createHash)('sha256').update(fs.readFileSync(at)).digest('hex'));
100
+ }
101
+ catch { /* unreadable: absent on this side */ }
102
+ }
103
+ }
104
+ };
105
+ walk(base);
106
+ return found;
107
+ }
108
+ /** A temporary governed project: one approved requirement, so the hook judges as it does in a governed workspace. */
109
+ function probeProject(parent) {
110
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(parent, 'holmes-hook-probe-')));
111
+ const spec = path.join(root, '.ax', 'specs', '01_req', 'REQ-900.md');
112
+ fs.mkdirSync(path.dirname(spec), { recursive: true });
113
+ fs.writeFileSync(spec, '---\nid: REQ-900\ntype: REQ\ntitle: probe\nstatus: approved\n---\n');
114
+ return root;
115
+ }
116
+ function decisionOf(packageRoot, probe, project) {
117
+ const env = { ...process.env, CLAUDE_PROJECT_DIR: project, HOLMES_SPECS: path.join(project, '.ax', 'specs') };
118
+ for (const name of ['HOLMES_APPROVAL', 'HOLMES_ROLE', 'HOLMES_AUTONOMOUS_APPROVAL'])
119
+ delete env[name];
120
+ const input = JSON.stringify({ session_id: 'doctor-development-hooks', hook_event_name: 'PreToolUse', cwd: project, tool_name: probe.tool, tool_input: probe.input });
121
+ let stdout;
122
+ try {
123
+ const result = (0, node_child_process_1.spawnSync)(process.execPath, [path.join(packageRoot, HOOK)], { input, cwd: project, env, encoding: 'utf8', timeout: PROBE_TIMEOUT_MS, windowsHide: true });
124
+ stdout = result.stdout ?? '';
125
+ }
126
+ catch {
127
+ return 'no answer';
128
+ }
129
+ try {
130
+ const parsed = JSON.parse(stdout);
131
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.hookSpecificOutput !== 'object' || parsed.hookSpecificOutput === null)
132
+ return 'no answer';
133
+ const decision = parsed.hookSpecificOutput.permissionDecision;
134
+ return typeof decision === 'string' && decision !== '' ? decision : 'none';
135
+ }
136
+ catch {
137
+ return 'no answer';
138
+ }
139
+ }
140
+ function developmentHooksCheck(input) {
141
+ const routed = compiledFiles(input.routedPackageRoot);
142
+ const checkout = compiledFiles(input.checkoutRoot);
143
+ const names = [...new Set([...routed.keys(), ...checkout.keys()])].sort();
144
+ const differingFiles = names.filter((name) => routed.get(name) !== checkout.get(name));
145
+ const differingVerdicts = [];
146
+ for (const probe of exports.HOOK_PROBES) {
147
+ // One project per probe and per side: a refusal may leave a record there, and it must not colour the next answer.
148
+ const decisions = [input.routedPackageRoot, input.checkoutRoot].map((packageRoot) => {
149
+ let project = null;
150
+ try {
151
+ project = probeProject(input.tmpDir ?? os.tmpdir());
152
+ return decisionOf(packageRoot, probe, project);
153
+ }
154
+ catch {
155
+ return 'no answer';
156
+ }
157
+ finally {
158
+ if (project !== null) {
159
+ try {
160
+ fs.rmSync(project, { recursive: true, force: true });
161
+ }
162
+ catch { /* best effort */ }
163
+ }
164
+ }
165
+ });
166
+ if (decisions[0] !== decisions[1] || decisions[0] === 'no answer')
167
+ differingVerdicts.push({ label: probe.label, routed: decisions[0], checkout: decisions[1] });
168
+ }
169
+ let checkoutBuild = 'unknown';
170
+ try {
171
+ checkoutBuild = fs.readFileSync(path.join(input.checkoutRoot, 'dist', '.build-id'), 'utf8').trim() || 'unknown';
172
+ }
173
+ catch { /* no build id */ }
174
+ const where = `sessions here run ${input.routedPackageRoot} (build ${input.routedBuild}); the checkout is ${input.checkoutRoot} (build ${checkoutBuild})`;
175
+ if (differingFiles.length === 0 && differingVerdicts.length === 0) {
176
+ return { level: 'PASS', totalFiles: names.length, differingFiles, differingVerdicts,
177
+ detail: `${where}; all ${names.length} compiled files are identical and ${exports.HOOK_PROBES.length} hook payloads get the same decision from both` };
178
+ }
179
+ const shown = differingFiles.slice(0, 3).join(', ') + (differingFiles.length > 3 ? `, +${differingFiles.length - 3} more` : '');
180
+ const verdicts = differingVerdicts.length === 0
181
+ ? `the ${exports.HOOK_PROBES.length} hook payloads tried get the same decision from both`
182
+ : `${differingVerdicts.length} of ${exports.HOOK_PROBES.length} hook payloads are decided differently — `
183
+ + differingVerdicts.map((v) => `${v.label}: sessions ${v.routed}, checkout ${v.checkout}`).join('; ');
184
+ const sameId = differingFiles.length > 0 && checkoutBuild !== 'unknown' && checkoutBuild === input.routedBuild
185
+ ? '; both carry the same build id, so the checkout\'s dist was compiled again without a new id' : '';
186
+ return { level: 'WARN', totalFiles: names.length, differingFiles, differingVerdicts,
187
+ detail: `${where}; ${differingFiles.length} of ${names.length} compiled files differ${differingFiles.length ? ` (${shown})` : ''}; ${verdicts}${sameId}`,
188
+ fix: 'Hook changes in this checkout are not live in any harness until they are published and the routed install is upgraded. To try them in a session before that, build a candidate and bind it with runtime-binding setup.' };
189
+ }
@@ -12,6 +12,8 @@ export interface RuntimeBindingOptions {
12
12
  installerPackageRoot?: string;
13
13
  approval?: Approval;
14
14
  activateHooks?: string[];
15
+ /** @implements A-SPEC-752.10 — the digest a reviewer was shown; a plan that computes to another one is not applied. */
16
+ expectedPlanDigest?: string;
15
17
  }
16
18
  export declare function runtimeHookCommand(registryPath: string, harness: RuntimeHarness, entry: RuntimeEntry): string;
17
19
  /**
@@ -41,7 +41,7 @@ exports.registryOwnedWiring = registryOwnedWiring;
41
41
  exports.runtimeBindingStatus = runtimeBindingStatus;
42
42
  exports.runRuntimeBinding = runRuntimeBinding;
43
43
  exports.trackedWorkspacePaths = trackedWorkspacePaths;
44
- // @implements A-SPEC-751, A-SPEC-752, A-SPEC-752.7, A-SPEC-752.8
44
+ // @implements A-SPEC-752.10, A-SPEC-752.9, A-SPEC-751.5, A-SPEC-751, A-SPEC-752, A-SPEC-752.7, A-SPEC-752.8
45
45
  const fs = __importStar(require("node:fs"));
46
46
  const os = __importStar(require("node:os"));
47
47
  const path = __importStar(require("node:path"));
@@ -195,7 +195,7 @@ function runRuntimeBinding(opts) {
195
195
  if (!path.isAbsolute(opts.registryPath))
196
196
  throw new Error('Registry path must be absolute');
197
197
  if (['binding.js', 'dispatch.js', 'hook-process.js', 'installation.json'].includes(path.basename(opts.registryPath))
198
- || /^(?:claude|codex|antigravity)-(?:mcp|pre-tool-use|stop)\.js$/.test(path.basename(opts.registryPath)))
198
+ || /^(?:claude|codex|antigravity)-(?:mcp|pre-tool-use|stop|session-start)\.js$/.test(path.basename(opts.registryPath)))
199
199
  throw new Error('Registry filename conflicts with an installed runtime file');
200
200
  const root = (0, binding_1.workspaceRoot)(opts.workspace);
201
201
  if ((0, binding_1.canonicalDirectory)(opts.workspace) !== root)
@@ -246,6 +246,35 @@ function runRuntimeBinding(opts) {
246
246
  wrappers.set(`${harness}:${entry}`, file);
247
247
  }
248
248
  }
249
+ // @implements A-SPEC-751.5 — Claude's SessionStart hook is routed too. It is not a gate, so it is not one of the
250
+ // lifecycles planned per event below; only an entry that already runs a Holmes session-start program is rewritten.
251
+ const sessionStartWrapper = path.join(dir, 'claude-session-start.js');
252
+ add(sessionStartWrapper, `// @implements A-SPEC-751.5\nrequire('./dispatch.js').runDispatch(${JSON.stringify({ registryPath: destination, harness: 'claude', entry: 'session-start' })});\n`);
253
+ const sessionStartCommand = runtimeHookCommand(destination, 'claude', 'session-start');
254
+ const routeSessionStart = (file) => {
255
+ const raw = planned.get(file)?.after ?? readOptional(file);
256
+ if (raw === null)
257
+ return;
258
+ const doc = document(raw, file);
259
+ const groups = doc.hooks?.SessionStart;
260
+ if (!Array.isArray(groups))
261
+ return;
262
+ let changed = false;
263
+ for (const group of groups) {
264
+ if (!object(group) || !Array.isArray(group.hooks))
265
+ continue;
266
+ for (const hook of group.hooks) {
267
+ if (!object(hook) || typeof hook.command !== 'string' || hook.command === sessionStartCommand)
268
+ continue;
269
+ if (/dist[/\\]+holmes[/\\]+hooks[/\\]+session-start\.js/.test(hook.command)) {
270
+ hook.command = sessionStartCommand;
271
+ changed = true;
272
+ }
273
+ }
274
+ }
275
+ if (changed)
276
+ add(file, json(doc));
277
+ };
249
278
  const command = (harness, entry) => runtimeHookCommand(destination, harness, entry);
250
279
  const owns = (cmd) => {
251
280
  if (typeof cmd !== 'string')
@@ -419,20 +448,73 @@ function runRuntimeBinding(opts) {
419
448
  }
420
449
  const codexFiles = [codexHooks, path.join(root, '.codex/hooks.json')];
421
450
  const codexDocs = codexFiles.map((f) => document(readOptional(f), f));
422
- const codexEvents = codexFiles.map(() => new Set());
423
- for (const event of ['PreToolUse', 'Stop']) {
424
- const existing = codexDocs.findIndex((d, source) => Array.isArray(d.hooks?.[event])
425
- && d.hooks[event].some((g, group) => Array.isArray(g?.hooks)
426
- && g.hooks.some((h, hook) => owns(h?.command) && !disabledGlobalCodex(codexFiles[source], event, group, hook))));
427
- // Explicit development activation adds missing lifecycles only to this project.
428
- // Filling an empty user lifecycle would also activate every consumer workspace.
429
- const empty = codexDocs.findIndex((d) => Array.isArray(d.hooks?.[event]) && d.hooks[event].length === 0);
430
- const owner = existing >= 0 ? existing : activate.has('codex') ? 1 : empty >= 0 ? empty : 0;
431
- codexEvents[owner].add(event);
432
- if (owner === 1)
433
- codexProjectEvents.add(event);
451
+ // @implements A-SPEC-752.9 — Codex keys a hook's enable state by position (<file>:<event>:<group>:<hook>). Measured
452
+ // 2026-10-05: the plan removed two Holmes groups from the user file and wrote one at index 0, whose key said
453
+ // `enabled = false`; the gate was written and never ran. A gate the plan writes is looked up by its own key.
454
+ const planCodex = (forced) => {
455
+ codexProjectEvents.clear();
456
+ const events = codexFiles.map(() => new Set());
457
+ for (const event of ['PreToolUse', 'Stop']) {
458
+ const existing = codexDocs.findIndex((d, source) => Array.isArray(d.hooks?.[event])
459
+ && d.hooks[event].some((g, group) => Array.isArray(g?.hooks)
460
+ && g.hooks.some((h, hook) => owns(h?.command) && !disabledGlobalCodex(codexFiles[source], event, group, hook))));
461
+ // Explicit development activation adds missing lifecycles only to this project.
462
+ // Filling an empty user lifecycle would also activate every consumer workspace.
463
+ const empty = codexDocs.findIndex((d) => Array.isArray(d.hooks?.[event]) && d.hooks[event].length === 0);
464
+ const owner = forced.has(event) ? 1 : existing >= 0 ? existing : activate.has('codex') ? 1 : empty >= 0 ? empty : 0;
465
+ events[owner].add(event);
466
+ if (owner === 1)
467
+ codexProjectEvents.add(event);
468
+ }
469
+ codexFiles.forEach((f, i) => native(f, 'codex', events[i]));
470
+ return events;
471
+ };
472
+ const switchedOffKeys = [];
473
+ for (const configFile of [codexConfig, path.join(root, '.codex/config.toml')]) {
474
+ const configState = (0, codex_toml_1.parseCodexConfig)(readOptional(configFile) ?? '');
475
+ if (configState.ok)
476
+ for (const [key, state] of Object.entries(configState.doc.hooks?.state ?? {}))
477
+ if (object(state) && state.enabled === false)
478
+ switchedOffKeys.push(key);
479
+ }
480
+ const gatesSwitchedOff = (events) => {
481
+ const found = [];
482
+ codexFiles.forEach((file, source) => {
483
+ const doc = document(planned.get(file)?.after ?? readOptional(file), file);
484
+ // An entry that already stood there, switched off, is not something this plan writes: doctor reports it.
485
+ const standing = document(readOptional(file), file);
486
+ const aliases = new Set([file]);
487
+ if (fs.existsSync(file)) {
488
+ aliases.add(fs.realpathSync(file));
489
+ aliases.add(fs.realpathSync.native(file));
490
+ }
491
+ for (const [event, keyEvent, entry] of [['PreToolUse', 'pre_tool_use', 'pre-tool-use'], ['Stop', 'stop', 'stop']]) {
492
+ if (!events[source].has(event) || !Array.isArray(doc.hooks?.[event]))
493
+ continue;
494
+ doc.hooks[event].forEach((g, i) => (Array.isArray(g?.hooks) ? g.hooks : []).forEach((h, j) => {
495
+ if (h?.command !== command('codex', entry))
496
+ return;
497
+ if (JSON.stringify(standing.hooks?.[event]?.[i]?.hooks?.[j]) === JSON.stringify(h))
498
+ return;
499
+ const key = switchedOffKeys.find((k) => [...aliases].some((alias) => normalized(k) === normalized(`${alias}:${keyEvent}:${i}:${j}`)));
500
+ if (key !== undefined)
501
+ found.push({ source, event, key });
502
+ }));
503
+ }
504
+ });
505
+ return found;
506
+ };
507
+ let codexEvents = planCodex(new Set());
508
+ // Explicit activation may use the project file; nothing else may choose another place on its own.
509
+ const toProject = new Set(gatesSwitchedOff(codexEvents).filter((g) => g.source === 0 && activate.has('codex')).map((g) => g.event));
510
+ if (toProject.size > 0)
511
+ codexEvents = planCodex(toProject);
512
+ for (const gate of gatesSwitchedOff(codexEvents)) {
513
+ conflicts.push(`the Codex ${gate.event} gate would be written where Codex has it switched off (${gate.key} is enabled = false), so it would not run; `
514
+ + (gate.source === 0 && !activate.has('codex')
515
+ ? "re-run with --activate-hooks codex to write this workspace's project hooks file, or switch that hook on in Codex (/hooks) and preview again"
516
+ : 'switch that hook on in Codex (/hooks) and preview again'));
434
517
  }
435
- codexFiles.forEach((f, i) => native(f, 'codex', codexEvents[i]));
436
518
  // Native disabled state is indexed by source/group/hook. Keeping its bytes while moving
437
519
  // the disabled gate would silently enable it. Refuse that migration, never mint trust.
438
520
  // Keep each layer's disabled keys: a project enable override does not change
@@ -485,6 +567,7 @@ function runRuntimeBinding(opts) {
485
567
  claudeEvents[existing >= 0 ? existing : activate.has('claude') ? 1 : empty >= 0 ? empty : 1].add(event);
486
568
  }
487
569
  claudeFiles.forEach((f, i) => native(f, 'claude', claudeEvents[i]));
570
+ claudeFiles.forEach(routeSessionStart);
488
571
  mcp(path.join(root, '.mcp.json'), 'claude');
489
572
  mcp(path.join(root, '.agents/mcp_config.json'), 'antigravity');
490
573
  const agyUser = (0, agents_1.agyUserHooksPath)(home);
@@ -562,6 +645,11 @@ function runRuntimeBinding(opts) {
562
645
  const changes = [...planned.values()].filter((c) => c.before !== c.after);
563
646
  const planDigest = (0, runtime_binding_approval_1.runtimePlanDigest)({ operation: opts.operation, root, selection, releasePackageRoot: next.releasePackageRoot,
564
647
  releaseBuild, activateHooks: [...activate].sort() }, changes);
648
+ // @implements A-SPEC-752.10 — what is applied is what was reviewed: the in-session dialog shows a digest, and a
649
+ // file that moved while the dialog was open makes this another plan.
650
+ if (opts.expectedPlanDigest !== undefined && opts.expectedPlanDigest !== planDigest) {
651
+ throw new Error(`Runtime plan changed since it was reviewed (reviewed ${opts.expectedPlanDigest}, now ${planDigest}); nothing written — preview it again`);
652
+ }
565
653
  if (!opts.dryRun) {
566
654
  if (conflicts.length)
567
655
  throw new Error(`Runtime configuration conflicts; nothing written: ${conflicts.join('; ')}`);
@@ -12,4 +12,12 @@ export interface ArgumentRoles {
12
12
  * know the act to name it. One command, every word certain, no substitution and no redirect — anything else is null.
13
13
  */
14
14
  export declare function installerInvocationOf(command: string, cwd?: string | null): 'preview' | 'apply' | null;
15
+ /**
16
+ * @implements A-SPEC-753.3 — the installer apply in ANY shape: the CLI takes its operation word wherever it sits, and
17
+ * a second command, a redirect or a trailing line break is not the exact grammar above. Returns the source text of
18
+ * the one command that applies (first word to last, as written), or null. A command line that cannot be parsed or
19
+ * holds a substitution is not judged here; neither is a runner before the CLI word or an operation that is not literal.
20
+ * A command whose own text holds a line break is not returned: that text would go into a refusal reason (A-SPEC-753.2).
21
+ */
22
+ export declare function installerApplyIn(command: string, cwd?: string | null): string | null;
15
23
  export declare function shellArgumentRoles(command: string, cwd?: string | null): ArgumentRoles;
@@ -34,8 +34,9 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.installerInvocationOf = installerInvocationOf;
37
+ exports.installerApplyIn = installerApplyIn;
37
38
  exports.shellArgumentRoles = shellArgumentRoles;
38
- // @implements A-SPEC-753
39
+ // @implements A-SPEC-753.3, A-SPEC-753
39
40
  const path = __importStar(require("node:path"));
40
41
  const shell_syntax_1 = require("./shell-syntax");
41
42
  const LIMIT = 256 * 1024;
@@ -188,6 +189,53 @@ function installerInvocationOf(command, cwd = null) {
188
189
  const installer = installerWords(parsed.commands[0].words, ['setup', 'remove'], true);
189
190
  return installer === null ? null : installer.preview ? 'preview' : 'apply';
190
191
  }
192
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
193
+ /**
194
+ * @implements A-SPEC-753.3 — the installer apply in ANY shape: the CLI takes its operation word wherever it sits, and
195
+ * a second command, a redirect or a trailing line break is not the exact grammar above. Returns the source text of
196
+ * the one command that applies (first word to last, as written), or null. A command line that cannot be parsed or
197
+ * holds a substitution is not judged here; neither is a runner before the CLI word or an operation that is not literal.
198
+ * A command whose own text holds a line break is not returned: that text would go into a refusal reason (A-SPEC-753.2).
199
+ */
200
+ function installerApplyIn(command, cwd = null) {
201
+ if (command.length > LIMIT)
202
+ return null;
203
+ const parsed = (0, shell_syntax_1.shellWords)(command, process.env, undefined, cwd, true);
204
+ if (parsed.overflow || parsed.subs.length)
205
+ return null;
206
+ for (const one of parsed.commands) {
207
+ let at = 0;
208
+ while (at < one.words.length && one.words[at].known && ASSIGNMENT.test(one.words[at].text))
209
+ at++;
210
+ const words = one.words.slice(at);
211
+ const literal = (i) => (words[i] && words[i].known && !words[i].glob ? words[i].text : null);
212
+ let next;
213
+ if (['node', 'nodejs'].includes(nameOf(literal(0) ?? ''))) {
214
+ if (!/(?:^|\/)bin\/holmes-kit\.js$/.test((literal(1) ?? '').replace(/\\/g, '/')))
215
+ continue;
216
+ next = 2;
217
+ }
218
+ else if (literal(0) !== null && installerBinName(literal(0)) === 'holmes-kit')
219
+ next = 1;
220
+ else
221
+ continue;
222
+ if (literal(next) !== 'runtime-binding')
223
+ continue;
224
+ const after = words.slice(next + 1);
225
+ if (!after.some(w => w.known && !w.glob && (w.text === 'setup' || w.text === 'remove')))
226
+ continue;
227
+ if (after.some(w => w.text === '--dry-run'))
228
+ continue;
229
+ const start = one.words[0].sourceStart, end = one.words[one.words.length - 1].sourceEnd;
230
+ if (start === undefined || end === undefined)
231
+ continue;
232
+ const text = command.slice(start, end);
233
+ if (text.includes('\n') || text.includes('\r'))
234
+ continue;
235
+ return text;
236
+ }
237
+ return null;
238
+ }
191
239
  function shellArgumentRoles(command, cwd = null) {
192
240
  const original = { governanceText: command, serverText: command, outputPaths: [] };
193
241
  if (command.length > LIMIT)
@@ -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-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
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
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.
@@ -1457,10 +1457,16 @@ function evaluateHook(input, specsDir, opts) {
1457
1457
  // build governs a workspace. Measured 2026-10-04, it was refused under the server-start wording below with
1458
1458
  // nothing for the operator to run. It stays refused; the reason names the act and carries the command. No
1459
1459
  // request id is printed: none exists until the operator runs the command, which files it.
1460
- if (!legacySessionApproval && (0, shell_argument_roles_1.installerInvocationOf)(command) === 'apply') {
1460
+ // @implements A-SPEC-753.3 — the exact grammar first; otherwise any command of the line that applies. The
1461
+ // operator part is that one command as written, not the whole line.
1462
+ const installerExact = legacySessionApproval ? null : (0, shell_argument_roles_1.installerInvocationOf)(command);
1463
+ const installerApply = legacySessionApproval ? null
1464
+ : installerExact === 'apply' ? command
1465
+ : installerExact === null ? (0, shell_argument_roles_1.installerApplyIn)(command) : null;
1466
+ if (installerApply !== null) {
1461
1467
  return {
1462
1468
  permissionDecision: 'deny',
1463
- permissionDecisionReason: '[Holmes-Kit] runtime-binding setup/remove changes which Holmes build governs a workspace (governance wiring); the operator runs it, not the session. It prints the request id to approve; after the grant the operator runs the same command again. Use --dry-run to preview it here. Operator: ' + command,
1469
+ permissionDecisionReason: '[Holmes-Kit] runtime-binding setup/remove changes which Holmes build governs a workspace (governance wiring); the operator runs it, not the session. It prints the request id to approve; after the grant the operator runs the same command again. Use --dry-run to preview it here. Operator: ' + installerApply,
1464
1470
  };
1465
1471
  }
1466
1472
  if (!legacySessionApproval && startsHolmesServer(command)) {
@@ -32,7 +32,8 @@ const npx_bin_1 = require("../project/npx-bin");
32
32
  * a fake elicitor.
33
33
  */
34
34
  /** Approval kinds that may ask in-session. Widening this set is a spec revision, not a drive-by. */
35
- exports.ELICITABLE_KINDS = new Set(['spec-approve', 'review-resolve']);
35
+ // @implements A-SPEC-752.10 — `governance-wiring`: re-applying the binding the registry already names (never choosing one).
36
+ exports.ELICITABLE_KINDS = new Set(['spec-approve', 'review-resolve', 'governance-wiring']);
36
37
  /** The `HOLMES_ELICIT` values that turn the in-client prompt OFF. */
37
38
  const ELICIT_DISABLED_TOKENS = new Set(['off', '0', 'false', 'no', 'disabled']);
38
39
  /**
@@ -0,0 +1,45 @@
1
+ import { Approval } from '../../guardrail/risk-gate';
2
+ import { ElicitOutcome } from '../elicit-approval';
3
+ export interface RuntimeBindingToolContext {
4
+ foreignRootReason(root?: string): string | null;
5
+ projectRootOf(root: string): string;
6
+ tryElicit(kind: string, target: string, summary: string): Promise<ElicitOutcome>;
7
+ elicitApproval(reason: string | undefined): Approval;
8
+ registryPath(): string;
9
+ home?: string;
10
+ installerPackageRoot?: string;
11
+ }
12
+ export declare function createRuntimeBindingToolHandlers(context: RuntimeBindingToolContext): {
13
+ runtime_binding(a: {
14
+ root: string;
15
+ operation?: string;
16
+ activate_hooks?: string[];
17
+ }): Promise<{
18
+ ok: boolean;
19
+ applied: boolean;
20
+ reason: string;
21
+ } | {
22
+ planDigest: string;
23
+ conflicts: string[];
24
+ changes: {
25
+ path: string;
26
+ added: number;
27
+ removed: number;
28
+ }[];
29
+ ok: boolean;
30
+ applied: boolean;
31
+ operation: string;
32
+ reason?: undefined;
33
+ } | {
34
+ planDigest: string;
35
+ conflicts: string[];
36
+ changes: {
37
+ path: string;
38
+ added: number;
39
+ removed: number;
40
+ }[];
41
+ ok: boolean;
42
+ applied: boolean;
43
+ reason?: undefined;
44
+ }>;
45
+ };
@@ -0,0 +1,135 @@
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.createRuntimeBindingToolHandlers = createRuntimeBindingToolHandlers;
37
+ // @implements A-SPEC-752.10
38
+ /**
39
+ * `runtime_binding` — re-apply the binding the operator registry ALREADY names for this workspace, from inside the
40
+ * session, on the owner's explicit answer in the approval dialog.
41
+ *
42
+ * What the out-of-band rule protects is the choice of which build governs a workspace. This tool makes no such
43
+ * choice: it takes no package argument, and plans for the package and release package the registry holds. It
44
+ * refreshes the dispatcher files and the wiring and can restore a harness's hooks — the act a reviewed plan waited
45
+ * three session restarts for on 2026-10-05, because only a terminal could perform it.
46
+ *
47
+ * Only an explicit approve answer applies a plan. A denial, an unanswered dialog, a client without the form dialog,
48
+ * autonomous approval: none of them write anything; the same queue request the CLI files is filed and returned.
49
+ */
50
+ const fs = __importStar(require("node:fs"));
51
+ const path = __importStar(require("node:path"));
52
+ const node_crypto_1 = require("node:crypto");
53
+ const binding_1 = require("../../runtime/binding");
54
+ const runtime_binding_1 = require("../../cli/runtime-binding");
55
+ const HARNESSES = ['claude', 'codex', 'antigravity'];
56
+ /** How many lines a change adds and removes — what a reviewer needs from a tool answer; the contents stay on disk. */
57
+ function lineCounts(change) {
58
+ const before = (change.before ?? '').split('\n');
59
+ const after = change.after.split('\n');
60
+ const was = new Set(before);
61
+ const now = new Set(after);
62
+ return { path: change.path, added: after.filter((line) => !was.has(line)).length, removed: before.filter((line) => !now.has(line)).length };
63
+ }
64
+ function createRuntimeBindingToolHandlers(context) {
65
+ return {
66
+ async runtime_binding(a) {
67
+ const foreign = context.foreignRootReason(a.root);
68
+ if (foreign)
69
+ return { ok: false, applied: false, reason: foreign };
70
+ const operation = a.operation ?? 'preview';
71
+ if (operation !== 'preview' && operation !== 'apply')
72
+ return { ok: false, applied: false, reason: 'runtime_binding: operation is preview or apply' };
73
+ const activate = a.activate_hooks ?? [];
74
+ if (!Array.isArray(activate) || activate.some((h) => !HARNESSES.includes(h))) {
75
+ return { ok: false, applied: false, reason: `runtime_binding: activate_hooks takes only ${HARNESSES.join(', ')}` };
76
+ }
77
+ 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
+ let root;
81
+ let binding;
82
+ let releasePackageRoot;
83
+ try {
84
+ 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
+ }
91
+ catch (e) {
92
+ return { ok: false, applied: false, reason: `runtime_binding: ${e.message}` };
93
+ }
94
+ if (binding === undefined)
95
+ return unregistered;
96
+ const options = { operation: 'setup', workspace: root, packageRoot: binding.packageRoot, releasePackageRoot, registryPath,
97
+ activateHooks: activate, ...(context.home !== undefined ? { home: context.home } : {}),
98
+ ...(context.installerPackageRoot !== undefined ? { installerPackageRoot: context.installerPackageRoot } : {}) };
99
+ let plan;
100
+ try {
101
+ plan = (0, runtime_binding_1.runRuntimeBinding)({ ...options, dryRun: true });
102
+ }
103
+ catch (e) {
104
+ return { ok: false, applied: false, reason: `runtime_binding: ${e.message}` };
105
+ }
106
+ const changes = plan.changes.map(lineCounts);
107
+ const answer = { planDigest: plan.planDigest, conflicts: plan.conflicts, changes };
108
+ if (operation === 'preview')
109
+ return { ok: true, applied: false, operation, ...answer };
110
+ if (plan.conflicts.length > 0)
111
+ return { ok: false, applied: false, reason: `runtime_binding: the plan has conflicts and was not applied — ${plan.conflicts.join('; ')}`, ...answer };
112
+ if (plan.changes.length === 0)
113
+ return { ok: true, applied: false, reason: 'runtime_binding: the wiring already matches the registered binding; nothing to apply', ...answer };
114
+ const names = [...new Set(plan.changes.map((c) => path.basename(c.path)))].join(', ');
115
+ const out = await context.tryElicit('governance-wiring', root, `plan ${plan.planDigest.slice(0, 19)}… — ${plan.changes.length} file(s): ${names}`);
116
+ const approved = out.kind === 'answered' && out.decision.granted;
117
+ try {
118
+ // Without an approve answer no approval is passed: the planner then applies only if the operator already
119
+ // granted this exact plan in a terminal, and otherwise files the request and refuses — the CLI's own path.
120
+ // The single-use nonce is what makes the planner write the authorization to the ledger (actor, plan digest):
121
+ // an answer given in a dialog must leave the same audit line a terminal grant does.
122
+ (0, runtime_binding_1.runRuntimeBinding)({ ...options, dryRun: false, expectedPlanDigest: plan.planDigest,
123
+ ...(approved ? { approval: { ...context.elicitApproval(out.kind === 'answered' ? out.decision.reason : undefined), nonce: (0, node_crypto_1.randomUUID)() } } : {}) });
124
+ return { ok: true, applied: true, ...answer };
125
+ }
126
+ catch (e) {
127
+ const message = e.message;
128
+ const request = /\brequest (req-[0-9a-f]+)/.exec(message)?.[1];
129
+ const dialog = out.kind === 'answered' ? (approved ? 'approved in the dialog, but ' : `declined in the dialog${out.decision.reason ? ` (${out.decision.reason})` : ''}; `)
130
+ : out.kind === 'expired' ? 'the approval dialog was not answered; ' : 'no approval dialog could be shown in this session; ';
131
+ return { ok: false, applied: false, reason: `runtime_binding: nothing was applied — ${dialog}${message}`, ...(request ? { request } : {}), ...answer };
132
+ }
133
+ },
134
+ };
135
+ }
@@ -53,6 +53,12 @@ export interface ElicitOpts {
53
53
  continuations: ApprovalContinuationStore;
54
54
  runId: string;
55
55
  };
56
+ /** @implements A-SPEC-752.10 — test seam for `runtime_binding`: an isolated registry, home and installer package. */
57
+ runtimeBinding?: {
58
+ registryPath?: string;
59
+ home?: string;
60
+ installerPackageRoot?: string;
61
+ };
56
62
  }
57
63
  /**
58
64
  * @implements A-SPEC-299
@@ -652,6 +658,38 @@ declare function makeRawHandlers(store: SpecStore, opts?: ElicitOpts): {
652
658
  reason: string;
653
659
  }[];
654
660
  }>;
661
+ runtime_binding(a: {
662
+ root: string;
663
+ operation?: string;
664
+ activate_hooks?: string[];
665
+ }): Promise<{
666
+ ok: boolean;
667
+ applied: boolean;
668
+ reason: string;
669
+ } | {
670
+ planDigest: string;
671
+ conflicts: string[];
672
+ changes: {
673
+ path: string;
674
+ added: number;
675
+ removed: number;
676
+ }[];
677
+ ok: boolean;
678
+ applied: boolean;
679
+ operation: string;
680
+ reason?: undefined;
681
+ } | {
682
+ planDigest: string;
683
+ conflicts: string[];
684
+ changes: {
685
+ path: string;
686
+ added: number;
687
+ removed: number;
688
+ }[];
689
+ ok: boolean;
690
+ applied: boolean;
691
+ reason?: undefined;
692
+ }>;
655
693
  workspace_preflight(a: {
656
694
  root: string;
657
695
  harness?: import("../cli/agents").Agent;
@@ -69,6 +69,8 @@ const spec_authoring_1 = require("./handlers/spec-authoring");
69
69
  const spec_lifecycle_1 = require("./handlers/spec-lifecycle");
70
70
  const spec_approval_1 = require("./handlers/spec-approval");
71
71
  const workspace_identity_2 = require("./handlers/workspace-identity");
72
+ const runtime_binding_tool_1 = require("./handlers/runtime-binding-tool");
73
+ const runtime_binding_1 = require("../cli/runtime-binding");
72
74
  const workspace_preflight_1 = require("./handlers/workspace-preflight");
73
75
  const operator_inspection_1 = require("./handlers/operator-inspection");
74
76
  const phase_queries_1 = require("./handlers/phase-queries");
@@ -1030,6 +1032,17 @@ function makeRawHandlers(store, opts) {
1030
1032
  // rtm_impact+4, rtm_reindex..review_record, review_prepare..risk_check, risk_check±, and the tail).
1031
1033
  ledger_reconcile: operatorInspection.ledger_reconcile,
1032
1034
  ...(0, workspace_preflight_1.createWorkspacePreflightHandlers)({ storeRoot: store instanceof spec_store_1.LocalMarkdownRepository ? store.specsRoot : undefined }),
1035
+ // @implements A-SPEC-752.10 — same unpinned slot. Re-applies the registered binding on the owner's answer in the
1036
+ // dialog; never autonomous.
1037
+ ...(0, runtime_binding_tool_1.createRuntimeBindingToolHandlers)({
1038
+ foreignRootReason: (root) => foreignRootReason(store, root),
1039
+ projectRootOf,
1040
+ tryElicit,
1041
+ elicitApproval,
1042
+ registryPath: () => opts?.runtimeBinding?.registryPath ?? (0, runtime_binding_1.defaultRuntimeRegistry)(),
1043
+ ...(opts?.runtimeBinding?.home !== undefined ? { home: opts.runtimeBinding.home } : {}),
1044
+ ...(opts?.runtimeBinding?.installerPackageRoot !== undefined ? { installerPackageRoot: opts.runtimeBinding.installerPackageRoot } : {}),
1045
+ }),
1033
1046
  // @implements A-SPEC-700.2 — same unpinned slot: `spec_retire..spec_unseal` is a pinned run.
1034
1047
  spec_reconcile: specLifecycle.spec_reconcile,
1035
1048
  rtm_impact: graphOperations.rtm_impact,
@@ -76,6 +76,19 @@ exports.TOOL_SCHEMAS = {
76
76
  description: 'Read-only diagnosis of this live MCP server workspace binding. Mismatched roots are not scanned. Identity and checkout are inspected only for a matching root. Does not rebind, initialize, register or prove client hook enforcement.',
77
77
  inputSchema: { type: 'object', properties: { root: ROOT_ANY, harness: { type: 'string', enum: [...agents_1.AGENTS] } }, required: ['root'] },
78
78
  },
79
+ // @implements A-SPEC-752.10
80
+ runtime_binding: {
81
+ description: 'Re-apply the runtime binding the operator registry ALREADY names for this workspace: refresh the dispatcher files and harness wiring, optionally restoring a harness\'s hooks. `preview` (default) writes nothing and returns the plan digest, conflicts and per-file line counts. `apply` opens the in-session approval dialog and writes the plan only on an explicit approve answer there; any other outcome writes nothing and returns the pending request. It cannot register a workspace or choose which build governs it — that is `holmes-kit runtime-binding setup`, run by the operator in a terminal. Native hook trust in each harness stays the operator\'s.',
82
+ inputSchema: {
83
+ type: 'object',
84
+ properties: {
85
+ root: ROOT_ANY,
86
+ operation: { type: 'string', enum: ['preview', 'apply'], description: 'Defaults to preview.' },
87
+ activate_hooks: { type: 'array', items: { type: 'string', enum: ['claude', 'codex', 'antigravity'] }, description: 'Harnesses whose Holmes hooks to restore in this workspace.' },
88
+ },
89
+ required: ['root'],
90
+ },
91
+ },
79
92
  workspace_identity: {
80
93
  description: 'Inspect canonical workspace and local replica identity without writes by default. Explicit initialize creates a Git-shareable .ax/workspace.json and registers this checkout; register requires an existing canonical identity. Preserve legacy specs and ledgers; these identifiers grant no approval authority. Share the manifest through Git and keep .ax/state local. Registered MCP writes include holmes-execution/1 provenance and require a reader supporting that schema; matching package versions alone do not establish this capability.',
81
94
  inputSchema: {
@@ -14,7 +14,7 @@ export interface RuntimeSelection {
14
14
  specsRoot: string;
15
15
  }
16
16
  export type RuntimeHarness = 'claude' | 'codex' | 'antigravity';
17
- export type RuntimeEntry = 'mcp' | 'pre-tool-use' | 'stop';
17
+ export type RuntimeEntry = 'mcp' | 'pre-tool-use' | 'stop' | 'session-start';
18
18
  export declare const RUNTIME_ENTRIES: string[];
19
19
  export declare function readBounded(file: string, max?: number): string;
20
20
  export declare function canonicalDirectory(value: string): string;
@@ -42,7 +42,7 @@ exports.validateRegistry = validateRegistry;
42
42
  exports.readRuntimeRegistry = readRuntimeRegistry;
43
43
  exports.verifyRuntime = verifyRuntime;
44
44
  exports.selectRuntime = selectRuntime;
45
- // @implements A-SPEC-751
45
+ // @implements A-SPEC-751, A-SPEC-751.5
46
46
  const fs = __importStar(require("node:fs"));
47
47
  const path = __importStar(require("node:path"));
48
48
  exports.RUNTIME_ENTRIES = ['bin/holmes-mcp.js', 'bin/holmes-hook-antigravity.js', 'bin/holmes-stop-antigravity.js',
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.runDispatch = runDispatch;
37
- // @implements A-SPEC-751, A-SPEC-751.1, A-SPEC-754
37
+ // @implements A-SPEC-751, A-SPEC-751.1, A-SPEC-751.5, A-SPEC-754
38
38
  const path = __importStar(require("node:path"));
39
39
  const node_child_process_1 = require("node:child_process");
40
40
  const binding_1 = require("./binding");
@@ -88,6 +88,37 @@ async function runDispatch(opts) {
88
88
  let selectedBuild;
89
89
  let selectedPackage;
90
90
  let selectedWorkspace = process.cwd();
91
+ // @implements A-SPEC-751.5 — a session start is not a gate: whatever goes wrong, it ends with exit 0 and nothing on
92
+ // standard output (the reason goes to standard error). It never emits a refusal and never holds a session up.
93
+ if (opts.entry === 'session-start') {
94
+ try {
95
+ if (opts.harness !== 'claude')
96
+ throw new Error('session-start is routed for claude only');
97
+ const budget = (0, hook_process_1.boundedHookBudget)(opts.hookBudgetMs, hook_process_1.HOOK_BUDGET_MS);
98
+ const input = await hookInput(budget);
99
+ const hints = hintsFromInput(input);
100
+ if (process.env.CLAUDE_PROJECT_DIR)
101
+ hints.push(process.env.CLAUDE_PROJECT_DIR);
102
+ const selection = (0, binding_1.selectRuntime)((0, binding_1.readRuntimeRegistry)(opts.registryPath), { cwd: process.cwd(), workspaceHints: hints, specsHint: process.env.HOLMES_SPECS });
103
+ const child = (0, node_child_process_1.spawn)(process.execPath, [path.join(selection.packageRoot, 'dist/holmes/hooks/session-start.js')], {
104
+ cwd: selection.workspaceRoot,
105
+ env: { ...process.env, HOLMES_SPECS: selection.specsRoot, CLAUDE_PROJECT_DIR: selection.workspaceRoot },
106
+ stdio: ['pipe', 'pipe', 'inherit'], detached: process.platform !== 'win32', windowsHide: true,
107
+ });
108
+ const result = await (0, hook_process_1.runHookChild)(child, input, budget - (performance.now() - started), (0, hook_process_1.boundedHookBudget)(opts.cleanupBudgetMs, hook_process_1.HOOK_CLEANUP_MS));
109
+ if (result.code !== 0 || result.signal)
110
+ throw new Error(`session-start program ended with ${result.signal ?? `exit ${result.code}`}`);
111
+ if (result.bytes.length) {
112
+ JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(result.bytes));
113
+ process.stdout.write(result.bytes);
114
+ }
115
+ }
116
+ catch (error) {
117
+ process.stderr.write(`[Holmes-Kit] session-start was skipped: ${error.message}\n`);
118
+ }
119
+ process.exitCode = 0;
120
+ return;
121
+ }
91
122
  try {
92
123
  if (!['claude', 'codex', 'antigravity'].includes(opts.harness) || !['mcp', 'pre-tool-use', 'stop'].includes(opts.entry))
93
124
  throw new Error('Invalid runtime dispatcher entry or harness');
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.4",
4
+ "version": "0.35.6",
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",