@holmes-lab/holmes-kit 0.35.23 → 0.35.24

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.
@@ -48,6 +48,30 @@ export interface InitOptions {
48
48
  autonomyInteractive?: boolean;
49
49
  /** @implements A-SPEC-752.8 — test override for the operator runtime registry whose receipt names owned wiring. */
50
50
  runtimeRegistryPath?: string;
51
+ /**
52
+ * @implements A-SPEC-772.2 — doctor's reading of the Codex hooks (trust, switch-off, Stop timeout), passed in by the
53
+ * CLI: doctor imports init, so init must not import doctor (no import cycles, A-SPEC-574.3).
54
+ */
55
+ codexHookReading?: (target: string, codexConfigPath?: string) => CodexHookReading;
56
+ }
57
+ export interface CodexHookReading {
58
+ check: {
59
+ level: string;
60
+ detail: string;
61
+ } | null;
62
+ reading: {
63
+ codexPre: boolean;
64
+ codexStop: boolean;
65
+ dormant: {
66
+ file: string;
67
+ timeout: number | null;
68
+ }[];
69
+ untrusted: string[];
70
+ /** @implements A-SPEC-772.5 */ shortStops?: {
71
+ file: string;
72
+ runs: boolean;
73
+ }[];
74
+ };
51
75
  }
52
76
  export interface FileChange {
53
77
  path: string;
@@ -36,7 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.settingsPathOf = exports.MATCHERS = exports.SERVER_NAME = void 0;
37
37
  exports.buildHookPlan = buildHookPlan;
38
38
  exports.runInit = runInit;
39
- // @implements A-SPEC-727, A-SPEC-724, A-SPEC-721, A-SPEC-738, A-SPEC-752.8
39
+ // @implements A-SPEC-727, A-SPEC-724, A-SPEC-721, A-SPEC-738, A-SPEC-752.8, A-SPEC-772.2, A-SPEC-772.4, A-SPEC-772.5, A-SPEC-772.6
40
40
  // @implements A-SPEC-709
41
41
  // @implements A-SPEC-769.11
42
42
  // @implements A-SPEC-340
@@ -1180,9 +1180,11 @@ function runInitUnguarded(opts) {
1180
1180
  }
1181
1181
  if (leftOwned.length > 0) {
1182
1182
  const names = leftOwned.map((l) => l.path);
1183
- const codexLeft = names.some((p) => /[\\/]\.codex[\\/]/.test(p) || p === (opts.codexConfigPath ?? '') || p === (opts.codexHooksPath ?? ''));
1183
+ // @implements A-SPEC-772.6 — also wherever CODEX_HOME puts the user-level files (not only a `.codex` folder).
1184
+ const codexLeft = names.some((p) => /[\\/]\.codex[\\/]/.test(p) || p === (opts.codexConfigPath ?? (0, codex_toml_1.defaultCodexConfigPath)()) || p === (opts.codexHooksPath ?? (0, codex_hooks_1.defaultCodexHooksPath)()));
1185
+ // @implements A-SPEC-772.6 — the dry run's "would wire … the user-level gate hooks" is a claim about those files too.
1184
1186
  const claims = (m) => (names.some((p) => m.includes(p)) && /wired|active|repaired|written/.test(m))
1185
- || (codexLeft && /pre-tool gate runs from the user-level Codex hooks file|codex: the gate is enforced \(hooks wired\)|codex: tools and instructions wired/.test(m));
1187
+ || (codexLeft && /pre-tool gate runs from the user-level Codex hooks file|codex: the gate is enforced \(hooks wired\)|codex: tools and instructions wired|codex: would wire .*user-level gate hooks/.test(m));
1186
1188
  for (let i = messages.length - 1; i >= 0; i--)
1187
1189
  if (claims(messages[i]))
1188
1190
  messages.splice(i, 1);
@@ -1191,6 +1193,10 @@ function runInitUnguarded(opts) {
1191
1193
  ? `${l.path}: left as it is — owned by the operator runtime registry. Preview a change to it with: holmes-kit runtime-binding setup --dry-run`
1192
1194
  : `${l.path}: left as it is — owned by the operator runtime registry, but the registry's receipt and the file disagree. Inspect with: holmes-kit runtime-binding status, then preview with: holmes-kit runtime-binding setup --dry-run`);
1193
1195
  }
1196
+ // @implements A-SPEC-772.2 — the withdrawn Codex claim is replaced by what is known, never by "enforced".
1197
+ // @implements A-SPEC-772.6 — not when removing: the line describes a wiring the run takes away.
1198
+ if (codexLeft && !opts.remove && (opts.agents ?? []).includes('codex'))
1199
+ messages.push(...registryCodexLines(opts));
1194
1200
  }
1195
1201
  }
1196
1202
  // @implements A-SPEC-251.1 (round 27) — no write, removal or link goes through a link the repository carries out of the
@@ -1359,3 +1365,49 @@ function runInitUnguarded(opts) {
1359
1365
  }
1360
1366
  return { ok: true, exitCode: 0, messages, changes, removals };
1361
1367
  }
1368
+ /**
1369
+ * @implements A-SPEC-772.2 — what init can say about Codex when the operator registry owns the user-level Codex files:
1370
+ * the routing the dispatcher selects and the trust state of the routed gates (doctor's reading), plus the operator act
1371
+ * when a running Codex Stop keeps a timeout below 75 s. Measured 2026-10-17: init said nothing about Codex here, and the
1372
+ * registry-owned Stop timeout was 30 s.
1373
+ */
1374
+ function registryCodexLines(opts) {
1375
+ let routing;
1376
+ try {
1377
+ const s = (0, runtime_binding_1.runtimeBindingStatus)(opts.runtimeRegistryPath ?? (0, runtime_binding_1.defaultRuntimeRegistry)(), opts.target).selection;
1378
+ routing = `routed by the operator registry (${s.mode}, build ${s.buildId})`;
1379
+ }
1380
+ catch (e) {
1381
+ routing = `routing unknown: ${(0, codex_oracle_1.clipText)(e.message, 300)}`;
1382
+ }
1383
+ const lines = [];
1384
+ let gates = 'hook trust not read';
1385
+ try {
1386
+ const read = opts.codexHookReading?.(opts.target, opts.codexConfigPath);
1387
+ const check = read?.check ?? null;
1388
+ const reading = read?.reading;
1389
+ if (check !== null && reading !== undefined) {
1390
+ const pre = reading.codexPre ? 'PreToolUse gate trusted' : 'PreToolUse gate not trusted or switched off — trust it with /hooks';
1391
+ const stop = reading.codexStop ? 'Stop gate trusted'
1392
+ : reading.untrusted.length ? 'Stop gate wired but not yet trusted — /hooks'
1393
+ : reading.dormant.length ? 'Stop gate switched off' : 'no Stop gate';
1394
+ gates = `${pre}, ${stop}`;
1395
+ const hooksFile = opts.codexHooksPath ?? (0, codex_hooks_1.defaultCodexHooksPath)();
1396
+ // @implements A-SPEC-772.5 — read the short Stops themselves, not the row's level: a RUNNING one is FAIL (772.3).
1397
+ const short = (reading.shortStops ?? []).find((s) => s.file === hooksFile);
1398
+ if (short !== undefined) {
1399
+ lines.push(`${hooksFile}: Codex Stop hook timeout below 75 s — ${short.runs ? 'Codex can kill the Stop before its 60 s deadline answers' : 'it will be killed before its 60 s deadline answers once you trust it'}. Operator: holmes-kit runtime-binding setup (rewrites it at 75 s), then trust it once with /hooks.`);
1400
+ }
1401
+ }
1402
+ }
1403
+ catch { /* the reading is advisory; the routing line still stands */ }
1404
+ // @implements A-SPEC-772.6 — Codex does not load the hooks of a project it marks untrusted.
1405
+ let trust = '';
1406
+ try {
1407
+ const key = (0, runtime_binding_1.codexProjectUntrusted)(opts.target, opts.codexConfigPath ?? (0, codex_toml_1.defaultCodexConfigPath)());
1408
+ if (key !== null)
1409
+ trust = `; Codex marks ${key} untrusted — project hooks do not load`;
1410
+ }
1411
+ catch { /* advisory */ }
1412
+ return [`codex: ${routing} — ${gates}${trust}; live activation unverified (workspace_preflight with harness codex reports observations).`, ...lines];
1413
+ }
@@ -25,6 +25,11 @@ export declare function runtimeHookCommand(registryPath: string, harness: Runtim
25
25
  * A list of keys to keep missed ones that switch Holmes off, so the view names what it drops (A-SPEC-752.6).
26
26
  */
27
27
  export declare function wiringViewOf(file: string, content: string): string;
28
+ /**
29
+ * @implements A-SPEC-772.6 — the `projects` key that marks `target` (or a directory above it) untrusted in a Codex
30
+ * config, or null. Codex does not load an untrusted project's hooks.
31
+ */
32
+ export declare function codexProjectUntrusted(target: string, configPath: string): string | null;
28
33
  /**
29
34
  * @implements A-SPEC-752.8 — whether the installation receipt beside the operator registry lists `file`, and whether the
30
35
  * file still matches it. Measured 2026-10-04: init rewrote the user-level Codex files a setup plan had written, because
@@ -60,7 +65,11 @@ export declare function runtimeBindingStatus(registryPath: string, workspace: st
60
65
  }[];
61
66
  duplicateRoutes: DuplicateRoute[];
62
67
  router: "changed" | "intact";
63
- activation: "unverified";
68
+ routerOutdated: string[];
69
+ activation: "observed" | "unverified";
70
+ observed: Record<string, string>;
71
+ observedUnrouted: Record<string, string>;
72
+ observedOther: Record<string, string>;
64
73
  };
65
74
  export declare function runRuntimeBinding(opts: RuntimeBindingOptions): unknown;
66
75
  /**
@@ -36,13 +36,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.defaultRuntimeRegistry = void 0;
37
37
  exports.runtimeHookCommand = runtimeHookCommand;
38
38
  exports.wiringViewOf = wiringViewOf;
39
+ exports.codexProjectUntrusted = codexProjectUntrusted;
39
40
  exports.registryWiringOwnership = registryWiringOwnership;
40
41
  exports.registryOwnedWiring = registryOwnedWiring;
41
42
  exports.codexDuplicateRoutes = codexDuplicateRoutes;
42
43
  exports.runtimeBindingStatus = runtimeBindingStatus;
43
44
  exports.runRuntimeBinding = runRuntimeBinding;
44
45
  exports.trackedWorkspacePaths = trackedWorkspacePaths;
45
- // @implements A-SPEC-769.10, A-SPEC-752.11, A-SPEC-752.12, A-SPEC-752.13, A-SPEC-752.14, A-SPEC-752.15, A-SPEC-752.16, A-SPEC-752.17, A-SPEC-752.10, A-SPEC-752.9, A-SPEC-751.5, A-SPEC-751.6, A-SPEC-751, A-SPEC-752, A-SPEC-752.7, A-SPEC-752.8
46
+ // @implements A-SPEC-769.10, A-SPEC-752.11, A-SPEC-752.12, A-SPEC-752.13, A-SPEC-752.14, A-SPEC-752.15, A-SPEC-752.16, A-SPEC-752.17, A-SPEC-752.10, A-SPEC-752.9, A-SPEC-751.5, A-SPEC-751.6, A-SPEC-751, A-SPEC-752, A-SPEC-752.7, A-SPEC-752.8, A-SPEC-772.1, A-SPEC-772.2, A-SPEC-772.5, A-SPEC-772.6, A-SPEC-772.7, A-SPEC-772.8, A-SPEC-772.9, A-SPEC-772.10, A-SPEC-772.11
46
47
  const fs = __importStar(require("node:fs"));
47
48
  const os = __importStar(require("node:os"));
48
49
  const path = __importStar(require("node:path"));
@@ -55,6 +56,7 @@ const runtime_binding_approval_1 = require("./runtime-binding-approval");
55
56
  const codex_toml_1 = require("./codex-toml");
56
57
  const codex_hooks_1 = require("./codex-hooks");
57
58
  const agents_1 = require("./agents");
59
+ const heartbeat_1 = require("../hooks/heartbeat");
58
60
  const defaultRuntimeRegistry = () => path.join(os.homedir(), '.holmes', 'runtime', 'bindings.json');
59
61
  exports.defaultRuntimeRegistry = defaultRuntimeRegistry;
60
62
  const digest = (s) => (0, node_crypto_1.createHash)('sha256').update(s).digest('hex');
@@ -116,6 +118,9 @@ function runtimeHookCommand(registryPath, harness, entry) {
116
118
  */
117
119
  function wiringViewOf(file, content) {
118
120
  const name = path.basename(file);
121
+ // @implements A-SPEC-772.5 — every config.toml Holmes wires is Codex's, wherever CODEX_HOME puts it.
122
+ if (name === 'config.toml')
123
+ return codexConfigView(content);
119
124
  if ((name !== 'settings.json' && name !== 'settings.local.json') || path.basename(path.dirname(file)) !== '.claude')
120
125
  return content;
121
126
  let doc;
@@ -131,6 +136,77 @@ function wiringViewOf(file, content) {
131
136
  const { model: _model, ...rest } = doc;
132
137
  return JSON.stringify(rest);
133
138
  }
139
+ /**
140
+ * @implements A-SPEC-772.2 — Codex writes its own trust records (`hooks.state.*.trusted_hash`), project trust
141
+ * (`projects`) and notices (`tui`) into `~/.codex/config.toml` (measured 2026-10-17), so a whole-file digest disagreed
142
+ * with the receipt forever. The view drops exactly those; an `enabled` switch, which can turn Holmes off, stays.
143
+ */
144
+ function codexConfigView(content) {
145
+ const parsed = (0, codex_toml_1.parseCodexConfig)(content);
146
+ if (!parsed.ok)
147
+ return content;
148
+ const doc = JSON.parse(JSON.stringify(parsed.doc));
149
+ delete doc.tui;
150
+ // @implements A-SPEC-772.6 — `projects` is Codex's own per-repository trust, shared by every repository on the machine:
151
+ // one "No" anywhere made the receipt disagree forever (round 2). An untrusted governed workspace is named instead by
152
+ // `codexProjectUntrusted`.
153
+ delete doc.projects;
154
+ const hooks = doc.hooks;
155
+ if (object(hooks) && object(hooks.state)) {
156
+ const state = hooks.state;
157
+ for (const [key, entry] of Object.entries(state)) {
158
+ if (!object(entry))
159
+ continue;
160
+ delete entry.trusted_hash;
161
+ // @implements A-SPEC-772.5 — Codex's own re-enabling is not a change of wiring; a switch-off is.
162
+ if (entry.enabled === true)
163
+ delete entry.enabled;
164
+ if (Object.keys(entry).length === 0)
165
+ delete state[key];
166
+ }
167
+ if (Object.keys(state).length === 0)
168
+ delete hooks.state;
169
+ if (Object.keys(hooks).length === 0)
170
+ delete doc.hooks;
171
+ }
172
+ const sorted = (v) => Array.isArray(v) ? v.map(sorted)
173
+ : object(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sorted(v[k])])) : v;
174
+ return JSON.stringify(sorted(doc));
175
+ }
176
+ /**
177
+ * @implements A-SPEC-772.6 — the `projects` key that marks `target` (or a directory above it) untrusted in a Codex
178
+ * config, or null. Codex does not load an untrusted project's hooks.
179
+ */
180
+ function codexProjectUntrusted(target, configPath) {
181
+ const raw = readOptional(configPath);
182
+ if (raw === null)
183
+ return null;
184
+ const parsed = (0, codex_toml_1.parseCodexConfig)(raw);
185
+ if (!parsed.ok)
186
+ return null;
187
+ const projects = parsed.doc.projects;
188
+ if (!object(projects))
189
+ return null;
190
+ let real = target;
191
+ try {
192
+ real = fs.realpathSync.native(target);
193
+ }
194
+ catch { /* as given */ }
195
+ // @implements A-SPEC-772.7 — the most specific key that contains the target decides (Codex looks up the exact project
196
+ // first): a trusted workspace under an untrusted parent is trusted.
197
+ let best = null;
198
+ for (const [key, entry] of Object.entries(projects)) {
199
+ if (!object(entry) || !path.isAbsolute(key))
200
+ continue;
201
+ const k = path.resolve(key);
202
+ if (![target, real].some((t) => (0, binding_1.inside)(k, t)))
203
+ continue;
204
+ const depth = k.split(path.sep).length;
205
+ if (best === null || depth > best.depth)
206
+ best = { key, depth, untrusted: entry.trust_level === 'untrusted' };
207
+ }
208
+ return best !== null && best.untrusted ? best.key : null;
209
+ }
134
210
  /**
135
211
  * @implements A-SPEC-752.8 — whether the installation receipt beside the operator registry lists `file`, and whether the
136
212
  * file still matches it. Measured 2026-10-04: init rewrote the user-level Codex files a setup plan had written, because
@@ -293,7 +369,52 @@ function runtimeBindingStatus(registryPath, workspace, opts) {
293
369
  }
294
370
  // @implements A-SPEC-769.8 — reported beside the receipt verdicts; it changes neither `conflicts` nor `router`.
295
371
  const duplicateRoutes = codexDuplicateRoutes(opts?.codexHome ?? path.join(os.homedir(), '.codex'), workspace);
296
- return { selection, conflicts, drift, duplicateRoutes, router: routerChanged ? 'changed' : 'intact', activation: 'unverified' };
372
+ // @implements A-SPEC-772.1 — a hook observed running in the selected workspace is reported, per harness.
373
+ const beats = (0, heartbeat_1.readHookHeartbeats)(selection.workspaceRoot);
374
+ const observed = {};
375
+ const observedUnrouted = {};
376
+ const observedOther = {};
377
+ const wiringEnv = { ...process.env, ...(opts?.codexHome ? { CODEX_HOME: opts.codexHome } : {}) };
378
+ const now = Date.now();
379
+ for (const harness of agents_1.AGENTS) {
380
+ const wiring = (0, heartbeat_1.hookWiringFiles)(selection.workspaceRoot, harness, wiringEnv);
381
+ // @implements A-SPEC-772.7 — each event on its own: a routed PreToolUse is not hidden by a later Stop of another mode.
382
+ for (const event of ['pre-tool-use', 'stop']) {
383
+ const beat = beats[harness][event];
384
+ if (beat === undefined)
385
+ continue;
386
+ const one = { ...beats, [harness]: { [event]: beat } };
387
+ // @implements A-SPEC-772.5 — only a hook that ran under THIS selection (its mode and build) is its activation.
388
+ // @implements A-SPEC-772.6 — not when the harness's wiring changed after it.
389
+ const o = (0, heartbeat_1.observationOf)(one, harness, now, wiring);
390
+ if (o.state !== 'observed')
391
+ continue;
392
+ const latest = (rec) => { if (!rec[harness] || rec[harness] < o.at)
393
+ rec[harness] = o.at; };
394
+ // @implements A-SPEC-772.9 — activation is the PreToolUse GATE of this selection; a Stop alone does not count.
395
+ if (event === 'pre-tool-use' && o.mode === selection.mode && o.buildId === selection.buildId)
396
+ latest(observed);
397
+ // @implements A-SPEC-772.7 — a run without routing evidence is reported apart from activation.
398
+ else if (o.mode === 'unknown')
399
+ latest(observedUnrouted);
400
+ // @implements A-SPEC-772.10 — every other observation (a Stop of this selection, another build or mode) is named.
401
+ // @implements A-SPEC-772.11 — each uncounted event, PreToolUse first (events loop in that order); the latest
402
+ // alone hid an other-build PreToolUse behind the turn-end Stop (round 7).
403
+ else {
404
+ const entry = `${event} at ${o.at} (build ${o.buildId}, ${o.mode})`;
405
+ observedOther[harness] = observedOther[harness] ? `${observedOther[harness]}; ${entry}` : entry;
406
+ }
407
+ }
408
+ }
409
+ const activation = Object.keys(observed).length > 0 ? 'observed' : 'unverified';
410
+ // @implements A-SPEC-772.7 — the deployed dispatcher of 2026-10-15 did not pass HOLMES_HOOK_MODE while `router` said
411
+ // intact (round 3). @implements A-SPEC-772.8 — judged by that capability, not by bytes: one machine-wide copy serves
412
+ // every binding, so comparing it with the selected package was outdated forever for a development binding (round 4).
413
+ const routerOutdated = [];
414
+ const deployedDispatch = readOptional(path.join(path.dirname(registryPath), 'dispatch.js'));
415
+ if (deployedDispatch !== null && !deployedDispatch.includes('HOLMES_HOOK_MODE'))
416
+ routerOutdated.push('dispatch.js');
417
+ return { selection, conflicts, drift, duplicateRoutes, router: routerChanged ? 'changed' : 'intact', routerOutdated, activation, observed, observedUnrouted, observedOther };
297
418
  }
298
419
  function runRuntimeBinding(opts) {
299
420
  if (opts.activateHooks !== undefined && (!Array.isArray(opts.activateHooks)
@@ -37,7 +37,7 @@ exports.TOOL_MAP = void 0;
37
37
  exports.shippedHookTimeoutMs = shippedHookTimeoutMs;
38
38
  exports.adaptPreToolUse = adaptPreToolUse;
39
39
  exports.adaptStop = adaptStop;
40
- // @implements A-SPEC-193
40
+ // @implements A-SPEC-193, A-SPEC-772.1
41
41
  // @implements A-SPEC-734
42
42
  // @implements A-SPEC-769.10, A-SPEC-769.11
43
43
  const fs = __importStar(require("node:fs"));
@@ -73,7 +73,8 @@ function shippedHookTimeoutMs(hookPath) {
73
73
  const runShippedHook = (hookPath, payload, cwd) => {
74
74
  const r = (0, node_child_process_1.spawnSync)(process.execPath, [hookPath], {
75
75
  cwd, input: payload, encoding: 'utf8', timeout: shippedHookTimeoutMs(hookPath),
76
- env: { ...process.env },
76
+ // @implements A-SPEC-772.1 — the kernel cannot tell an Antigravity call from its translated input; name it.
77
+ env: { ...process.env, HOLMES_HOOK_HARNESS: 'antigravity' },
77
78
  });
78
79
  // @implements A-SPEC-734 (round 16) — three-harness parity: the hook's "not judged" notices reach the harness as
79
80
  // they do for Claude and Codex (the adapter dropped every one — measured).
@@ -0,0 +1,47 @@
1
+ import { Agent } from '../cli/agent-registry';
2
+ export declare const HEARTBEAT_DIR: string;
3
+ export type HookEvent = 'pre-tool-use' | 'stop';
4
+ declare const SCHEMA = "holmes-hook-heartbeat/1";
5
+ export declare const OBSERVED_WITHIN_MS: number;
6
+ /** @implements A-SPEC-772.7 — `unknown`: no routing evidence (a direct-wired kernel and an older deployed dispatcher look alike). */
7
+ export interface HookBeat {
8
+ schema: typeof SCHEMA;
9
+ harness: Agent;
10
+ event: HookEvent;
11
+ at: string;
12
+ buildId: string;
13
+ mode: 'development' | 'release' | 'unknown';
14
+ }
15
+ export type HookBeats = Record<Agent, Partial<Record<HookEvent, HookBeat>>>;
16
+ export type HookObservation = {
17
+ state: 'observed' | 'stale';
18
+ event: HookEvent;
19
+ at: string;
20
+ buildId: string;
21
+ mode: HookBeat['mode'];
22
+ ageMs: number;
23
+ reason?: 'wiring changed since';
24
+ } | {
25
+ state: 'never';
26
+ };
27
+ /** The harness a hook call belongs to, or null when the evidence is absent or contradicts itself. */
28
+ export declare function hookHarnessOf(input: unknown, env: Record<string, string | undefined>): Agent | null;
29
+ export declare function recordHookHeartbeat(opts: {
30
+ root: string;
31
+ event: HookEvent;
32
+ input: unknown;
33
+ env: Record<string, string | undefined>;
34
+ now?: number;
35
+ buildId?: string;
36
+ }): void;
37
+ export declare function readHookHeartbeats(root: string, now?: number): HookBeats;
38
+ /** The latest PreToolUse or Stop record of a harness: observed within 24 h, stale beyond, never without one. */
39
+ export declare function observationOf(beats: HookBeats, harness: Agent, now?: number, wiringFiles?: readonly string[], event?: HookEvent): HookObservation;
40
+ /**
41
+ * @implements A-SPEC-772.6 — the files whose change can stop a harness running its Holmes hooks in `root`: what Claude,
42
+ * Codex and Antigravity read their hooks from (Codex's workspace trust too; its user-level trust file is excluded).
43
+ */
44
+ export declare function hookWiringFiles(root: string, harness: Agent, env?: Record<string, string | undefined>): string[];
45
+ /** "3 min", "5 h", "2 d" — for a stale observation's detail. */
46
+ export declare function ageText(ms: number): string;
47
+ export {};
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.OBSERVED_WITHIN_MS = exports.HEARTBEAT_DIR = void 0;
37
+ exports.hookHarnessOf = hookHarnessOf;
38
+ exports.recordHookHeartbeat = recordHookHeartbeat;
39
+ exports.readHookHeartbeats = readHookHeartbeats;
40
+ exports.observationOf = observationOf;
41
+ exports.hookWiringFiles = hookWiringFiles;
42
+ exports.ageText = ageText;
43
+ // @implements A-SPEC-772.1, A-SPEC-772.5, A-SPEC-772.6, A-SPEC-772.7, A-SPEC-772.8, A-SPEC-772.9
44
+ /**
45
+ * Evidence that a harness's hooks actually ran in a workspace.
46
+ *
47
+ * Measured 2026-10-17: a Codex session in holmes-lab could not tell it was governed — the dispatcher routed it to the
48
+ * release build and its Stop hook had run, but nothing recorded either, so `workspace_preflight` and
49
+ * `runtime-binding status` could only say "unknown"/"unverified".
50
+ *
51
+ * The harness is told from the hook INPUT, never from the environment: a Codex hook launched from a Claude Code
52
+ * terminal received `CLAUDECODE=1`. Claude sends `prompt_id` and no `turn_id`; Codex sends `turn_id` and no
53
+ * `prompt_id`. Holmes's own launchers (the runtime dispatcher, the Antigravity adapter) name the harness explicitly in
54
+ * `HOLMES_HOOK_HARNESS`; when that and the shape both speak they must agree.
55
+ *
56
+ * Recording is off the decision path: one stat per call, at most one small write per harness and event per minute,
57
+ * and every failure is swallowed.
58
+ *
59
+ * @implements A-SPEC-772.5 — an observation is INFORMATION ONLY. Anyone who can run a hook program can produce one, so
60
+ * no gate, approval or seal may read it as authority.
61
+ */
62
+ const fs = __importStar(require("node:fs"));
63
+ const os = __importStar(require("node:os"));
64
+ const path = __importStar(require("node:path"));
65
+ // @implements A-SPEC-772.6 — the import-free registry: this module runs inside every hook call.
66
+ const agent_registry_1 = require("../cli/agent-registry");
67
+ exports.HEARTBEAT_DIR = path.join('.ax', 'state', 'hook-heartbeat');
68
+ const EVENTS = ['pre-tool-use', 'stop'];
69
+ const SCHEMA = 'holmes-hook-heartbeat/1';
70
+ const WRITE_EVERY_MS = 60_000;
71
+ exports.OBSERVED_WITHIN_MS = 24 * 3600_000;
72
+ const MAX_RECORD_BYTES = 4096;
73
+ const FUTURE_TOLERANCE_MS = 5 * 60_000;
74
+ const validBuildId = (id) => typeof id === 'string' && id.length > 0 && id.length <= 200 && !/[\x00-\x1f\x7f]/.test(id);
75
+ const isLink = (p) => { try {
76
+ return fs.lstatSync(p).isSymbolicLink();
77
+ }
78
+ catch {
79
+ return false;
80
+ } };
81
+ const isAgent = (v) => typeof v === 'string' && agent_registry_1.AGENTS.includes(v);
82
+ /** The harness a hook call belongs to, or null when the evidence is absent or contradicts itself. */
83
+ function hookHarnessOf(input, env) {
84
+ const o = input !== null && typeof input === 'object' ? input : {};
85
+ const hasPrompt = typeof o.prompt_id === 'string' && o.prompt_id !== '';
86
+ const hasTurn = typeof o.turn_id === 'string' && o.turn_id !== '';
87
+ const shape = hasPrompt && !hasTurn ? 'claude' : hasTurn && !hasPrompt ? 'codex' : null;
88
+ const named = env.HOLMES_HOOK_HARNESS;
89
+ if (named !== undefined && named !== '') {
90
+ if (!isAgent(named))
91
+ return null;
92
+ if (shape !== null && shape !== named)
93
+ return null;
94
+ return named;
95
+ }
96
+ return shape;
97
+ }
98
+ /** The running package's build id (dist/.build-id next to this compiled file), or 'unknown'. */
99
+ function runningBuildId() {
100
+ try {
101
+ const id = fs.readFileSync(path.resolve(__dirname, '..', '..', '.build-id'), 'utf8').trim();
102
+ return id && id.length <= 200 && !/[\x00-\x1f\x7f]/.test(id) ? id : 'unknown';
103
+ }
104
+ catch {
105
+ return 'unknown';
106
+ }
107
+ }
108
+ function recordHookHeartbeat(opts) {
109
+ try {
110
+ if (typeof opts.root !== 'string' || !EVENTS.includes(opts.event))
111
+ return;
112
+ // @implements A-SPEC-772.9 — a test that spawns the real kernel inside the repository turns recording off; an
113
+ // observation is information only, so the switch changes no decision.
114
+ if (opts.env.HOLMES_HEARTBEAT === 'off')
115
+ return;
116
+ if (!fs.existsSync(path.join(opts.root, '.ax')))
117
+ return;
118
+ const harness = hookHarnessOf(opts.input, opts.env);
119
+ if (harness === null)
120
+ return;
121
+ const now = opts.now ?? Date.now();
122
+ const dir = path.join(opts.root, exports.HEARTBEAT_DIR);
123
+ // @implements A-SPEC-772.5 — never write through a link out of the workspace.
124
+ if (isLink(path.join(opts.root, '.ax', 'state')) || isLink(dir))
125
+ return;
126
+ const file = path.join(dir, `${harness}.${opts.event}.json`);
127
+ // @implements A-SPEC-772.5 — a record "modified in the future" (clock stepped back, restored file) does not block.
128
+ try {
129
+ const age = now - fs.statSync(file).mtimeMs;
130
+ if (age >= 0 && age < WRITE_EVERY_MS)
131
+ return;
132
+ }
133
+ catch { /* no record yet */ }
134
+ const mode = opts.env.HOLMES_HOOK_MODE === 'development' || opts.env.HOLMES_HOOK_MODE === 'release' ? opts.env.HOLMES_HOOK_MODE : 'unknown';
135
+ const beat = { schema: SCHEMA, harness, event: opts.event, at: new Date(now).toISOString(), buildId: opts.buildId ?? runningBuildId(), mode };
136
+ fs.mkdirSync(dir, { recursive: true });
137
+ const tmp = path.join(dir, `.${harness}.${opts.event}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
138
+ fs.writeFileSync(tmp, JSON.stringify(beat), { flag: 'wx' });
139
+ try {
140
+ fs.renameSync(tmp, file);
141
+ }
142
+ catch {
143
+ try {
144
+ fs.rmSync(tmp, { force: true });
145
+ }
146
+ catch { /* ignore */ }
147
+ }
148
+ // The rate limit reads the record's mtime: make it the observation time, so an injected clock is honoured too.
149
+ try {
150
+ const t = new Date(now);
151
+ fs.utimesSync(file, t, t);
152
+ }
153
+ catch { /* ignore */ }
154
+ }
155
+ catch { /* recording never affects a hook */ }
156
+ }
157
+ function readBeat(file, harness, event, now) {
158
+ try {
159
+ const st = fs.lstatSync(file);
160
+ if (!st.isFile() || st.size > MAX_RECORD_BYTES)
161
+ return undefined;
162
+ const b = JSON.parse(fs.readFileSync(file, 'utf8'));
163
+ if (b?.schema !== SCHEMA || b.harness !== harness || b.event !== event)
164
+ return undefined;
165
+ // @implements A-SPEC-772.5 — a record from the future, or a build id the writer would refuse, is not evidence.
166
+ if (typeof b.at !== 'string' || !Number.isFinite(Date.parse(b.at)) || Date.parse(b.at) > now + FUTURE_TOLERANCE_MS || !validBuildId(b.buildId))
167
+ return undefined;
168
+ // @implements A-SPEC-772.7 — a record written as `direct` (before this repair) carried no routing evidence either.
169
+ if (b.mode === 'direct')
170
+ b.mode = 'unknown';
171
+ if (!['development', 'release', 'unknown'].includes(b.mode))
172
+ return undefined;
173
+ return b;
174
+ }
175
+ catch {
176
+ return undefined;
177
+ }
178
+ }
179
+ function readHookHeartbeats(root, now = Date.now()) {
180
+ const out = Object.fromEntries(agent_registry_1.AGENTS.map((a) => [a, {}]));
181
+ for (const harness of agent_registry_1.AGENTS) {
182
+ for (const event of EVENTS) {
183
+ const b = readBeat(path.join(root, exports.HEARTBEAT_DIR, `${harness}.${event}.json`), harness, event, now);
184
+ if (b)
185
+ out[harness][event] = b;
186
+ }
187
+ }
188
+ return out;
189
+ }
190
+ /** The latest PreToolUse or Stop record of a harness: observed within 24 h, stale beyond, never without one. */
191
+ function observationOf(beats, harness, now = Date.now(), wiringFiles, event) {
192
+ // @implements A-SPEC-772.8 — `event` narrows to one hook (the PreToolUse gate is what pass means).
193
+ const latest = EVENTS.filter((e) => event === undefined || e === event).map((e) => beats[harness]?.[e]).filter((b) => b !== undefined)
194
+ .sort((a, b) => Date.parse(b.at) - Date.parse(a.at))[0];
195
+ if (!latest)
196
+ return { state: 'never' };
197
+ const ageMs = now - Date.parse(latest.at);
198
+ const base = { event: latest.event, at: latest.at, buildId: latest.buildId, mode: latest.mode, ageMs };
199
+ // @implements A-SPEC-772.6 — a hook observed before its wiring changed proves nothing about the wiring now (setup
200
+ // rewrites hooks Codex must re-trust; /hooks can switch one off).
201
+ if (wiringFiles && Date.parse(latest.at) < latestMtime(wiringFiles, now))
202
+ return { state: 'stale', ...base, reason: 'wiring changed since' };
203
+ return { state: ageMs <= exports.OBSERVED_WITHIN_MS ? 'observed' : 'stale', ...base };
204
+ }
205
+ function latestMtime(files, now = Date.now()) {
206
+ let max = -Infinity;
207
+ // @implements A-SPEC-772.7 — a wiring file "modified in the future" (restored, clock skew) would make every record stale forever.
208
+ for (const f of files) {
209
+ try {
210
+ const m = fs.statSync(f).mtimeMs;
211
+ if (m <= now + FUTURE_TOLERANCE_MS)
212
+ max = Math.max(max, m);
213
+ }
214
+ catch { /* absent */ }
215
+ }
216
+ return max;
217
+ }
218
+ /**
219
+ * @implements A-SPEC-772.6 — the files whose change can stop a harness running its Holmes hooks in `root`: what Claude,
220
+ * Codex and Antigravity read their hooks from (Codex's workspace trust too; its user-level trust file is excluded).
221
+ */
222
+ function hookWiringFiles(root, harness, env = process.env) {
223
+ // @implements A-SPEC-772.7 — the home other readers use (os.homedir()) unless the caller names one.
224
+ const home = (process.platform === 'win32' ? env.USERPROFILE : env.HOME) || os.homedir();
225
+ if (harness === 'claude') {
226
+ const user = env.CLAUDE_CONFIG_DIR ? path.resolve(env.CLAUDE_CONFIG_DIR) : path.join(home, '.claude');
227
+ return [path.join(user, 'settings.json'), path.join(root, '.claude', 'settings.json'), path.join(root, '.claude', 'settings.local.json')];
228
+ }
229
+ if (harness === 'codex') {
230
+ // @implements A-SPEC-772.7 — the user-level config.toml is machine-shared: Codex and its desktop app rewrite it for
231
+ // other repositories and plugin syncs (measured), which flipped every workspace's observation.
232
+ // @implements A-SPEC-772.8 — the workspace's own Codex files are in. Known limit: a user-level `/hooks` switch-off
233
+ // or plugin disable lives in that shared file and is not detected here.
234
+ const codex = env.CODEX_HOME ? path.resolve(env.CODEX_HOME) : path.join(home, '.codex');
235
+ return [path.join(codex, 'hooks.json'), path.join(root, '.codex', 'hooks.json'), path.join(root, '.codex', 'config.toml'),
236
+ path.join(root, '.holmes', 'codex-plugin', 'holmes-kit', 'hooks.json')];
237
+ }
238
+ return [path.join(home, '.gemini', 'config', 'hooks.json'), path.join(root, '.agents', 'hooks.json')];
239
+ }
240
+ /** "3 min", "5 h", "2 d" — for a stale observation's detail. */
241
+ function ageText(ms) {
242
+ if (ms < 3600_000)
243
+ return `${Math.max(1, Math.round(ms / 60_000))} min`;
244
+ if (ms < 48 * 3600_000)
245
+ return `${Math.round(ms / 3600_000)} h`;
246
+ return `${Math.round(ms / 86_400_000)} d`;
247
+ }
@@ -48,7 +48,7 @@ exports.gateErrorDecision = gateErrorDecision;
48
48
  exports.wiredSpecsDir = wiredSpecsDir;
49
49
  exports.evaluateHook = evaluateHook;
50
50
  exports.readSpecsSync = readSpecsSync;
51
- // @implements A-SPEC-753.3, A-SPEC-134.2, A-SPEC-278, A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2
51
+ // @implements A-SPEC-753.3, A-SPEC-134.2, A-SPEC-278, A-SPEC-733, A-SPEC-734, A-SPEC-747, A-SPEC-477.1, A-SPEC-753, A-SPEC-163.7, A-SPEC-768.2, A-SPEC-772.1
52
52
  const shell_argument_roles_1 = require("../guardrail/shell-argument-roles");
53
53
  // @implements A-SPEC-549.3 — the hook's deny reasons are English here; hooks-english.test.ts drives
54
54
  // evaluateHook in this file to prove it.
@@ -2797,7 +2797,8 @@ if (require.main === module) {
2797
2797
  try {
2798
2798
  // @implements A-SPEC-144 — normalize BEFORE deciding: most of the measured bypasses were a
2799
2799
  // wrong type reaching code that assumed a string, not an interesting failure of the gate.
2800
- const input = normalizeHookInput(JSON.parse(buf || '{}'));
2800
+ const rawHookInput = JSON.parse(buf || '{}');
2801
+ const input = normalizeHookInput(rawHookInput);
2801
2802
  // @implements A-SPEC-149
2802
2803
  // The ONE place process context is read. `evaluateHook` no longer reaches for `process.cwd()`
2803
2804
  // or `process.env` on its own, so a caller always states which project it is judging and under
@@ -2837,6 +2838,10 @@ if (require.main === module) {
2837
2838
  return { root: process.cwd(), anchored: false };
2838
2839
  })();
2839
2840
  const hookProjectRoot = hookRoot.root;
2841
+ // @implements A-SPEC-772.1 — evidence that this harness's gate ran here; off the decision path, never throws.
2842
+ if (hookRoot.anchored) {
2843
+ require('./heartbeat').recordHookHeartbeat({ root: hookProjectRoot, event: 'pre-tool-use', input: rawHookInput, env: process.env });
2844
+ }
2840
2845
  // @implements A-SPEC-191 §17 (round 11) — and the SPECS the gate judges against come from the
2841
2846
  // same tree. Round-10 moved the project root here and left this path relative, so a session
2842
2847
  // opened in a subdirectory looked for `<sub>/.ax/specs`, found nothing, and `isGovernedProject`