@holmes-lab/holmes-kit 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +556 -0
  2. package/README.md +15 -5
  3. package/bin/holmes-hook-antigravity.js +4 -0
  4. package/bin/holmes-kit.js +4 -0
  5. package/bin/holmes-pre-push.js +3 -0
  6. package/bin/holmes-stop-antigravity.js +4 -0
  7. package/dist/.build-id +1 -1
  8. package/dist/holmes/cli/agents-guidance-history.d.ts +1 -1
  9. package/dist/holmes/cli/agents-guidance-history.js +11 -2
  10. package/dist/holmes/cli/agents-guidance.d.ts +1 -0
  11. package/dist/holmes/cli/agents-guidance.js +11 -8
  12. package/dist/holmes/cli/agents.d.ts +41 -0
  13. package/dist/holmes/cli/agents.js +382 -2
  14. package/dist/holmes/cli/attest.d.ts +2 -0
  15. package/dist/holmes/cli/attest.js +66 -15
  16. package/dist/holmes/cli/ci-gate.js +16 -1
  17. package/dist/holmes/cli/claude-switches.d.ts +95 -0
  18. package/dist/holmes/cli/claude-switches.js +967 -0
  19. package/dist/holmes/cli/codex-hooks.d.ts +77 -0
  20. package/dist/holmes/cli/codex-hooks.js +802 -0
  21. package/dist/holmes/cli/codex-oracle.d.ts +194 -0
  22. package/dist/holmes/cli/codex-oracle.js +1245 -0
  23. package/dist/holmes/cli/codex-toml.d.ts +58 -1
  24. package/dist/holmes/cli/codex-toml.js +456 -40
  25. package/dist/holmes/cli/doctor.d.ts +108 -8
  26. package/dist/holmes/cli/doctor.js +1408 -98
  27. package/dist/holmes/cli/index.js +23 -11
  28. package/dist/holmes/cli/init.d.ts +13 -0
  29. package/dist/holmes/cli/init.js +749 -77
  30. package/dist/holmes/cli/interactive-prompt.js +2 -2
  31. package/dist/holmes/cli/mcp-launcher.d.ts +64 -6
  32. package/dist/holmes/cli/mcp-launcher.js +189 -6
  33. package/dist/holmes/cli/mcp-version.js +13 -2
  34. package/dist/holmes/cli/settings-merge.js +8 -2
  35. package/dist/holmes/cli/upgrade.d.ts +13 -0
  36. package/dist/holmes/cli/upgrade.js +116 -23
  37. package/dist/holmes/cli/workspace-scope.d.ts +22 -0
  38. package/dist/holmes/cli/workspace-scope.js +375 -0
  39. package/dist/holmes/cli/worktree-readiness.d.ts +1 -0
  40. package/dist/holmes/cli/worktree-readiness.js +17 -3
  41. package/dist/holmes/cpg/cpg-scanner.d.ts +29 -0
  42. package/dist/holmes/cpg/cpg-scanner.js +403 -3
  43. package/dist/holmes/cpg/cycle-detect.js +2 -1
  44. package/dist/holmes/cpg/forbidden-edges.js +9 -2
  45. package/dist/holmes/cpg/required-calls.js +8 -1
  46. package/dist/holmes/governance/autonomy.d.ts +9 -0
  47. package/dist/holmes/governance/autonomy.js +28 -1
  48. package/dist/holmes/governance/constitution-debt.js +3 -2
  49. package/dist/holmes/governance/constitution.js +15 -3
  50. package/dist/holmes/governance/provenance-chain.js +3 -2
  51. package/dist/holmes/governance/push-gate-runner.js +4 -3
  52. package/dist/holmes/guardrail/dependency-delta.js +4 -3
  53. package/dist/holmes/guardrail/linear-match.d.ts +57 -0
  54. package/dist/holmes/guardrail/linear-match.js +256 -0
  55. package/dist/holmes/guardrail/risk-classifier.d.ts +6 -7
  56. package/dist/holmes/guardrail/risk-classifier.js +931 -44
  57. package/dist/holmes/guardrail/risk-types.d.ts +6 -0
  58. package/dist/holmes/guardrail/scope-judgment.d.ts +4 -24
  59. package/dist/holmes/guardrail/scope-judgment.js +100 -23
  60. package/dist/holmes/guardrail/shell-words.d.ts +42 -0
  61. package/dist/holmes/guardrail/shell-words.js +1720 -0
  62. package/dist/holmes/guardrail/write-target.d.ts +168 -3
  63. package/dist/holmes/guardrail/write-target.js +2379 -87
  64. package/dist/holmes/hooks/adapters/antigravity.d.ts +3 -1
  65. package/dist/holmes/hooks/adapters/antigravity.js +115 -11
  66. package/dist/holmes/hooks/pre-tool-use.d.ts +32 -6
  67. package/dist/holmes/hooks/pre-tool-use.js +923 -87
  68. package/dist/holmes/hooks/rtm-refresh-child.d.ts +22 -1
  69. package/dist/holmes/hooks/rtm-refresh-child.js +102 -18
  70. package/dist/holmes/hooks/rtm-refresh.d.ts +20 -1
  71. package/dist/holmes/hooks/rtm-refresh.js +60 -15
  72. package/dist/holmes/hooks/session-start.d.ts +10 -0
  73. package/dist/holmes/hooks/session-start.js +31 -7
  74. package/dist/holmes/hooks/stop.d.ts +2 -1
  75. package/dist/holmes/hooks/stop.js +197 -91
  76. package/dist/holmes/mcp/approval-adapters.d.ts +22 -0
  77. package/dist/holmes/mcp/approval-adapters.js +21 -0
  78. package/dist/holmes/mcp/approval-commit.d.ts +20 -0
  79. package/dist/holmes/mcp/approval-commit.js +108 -0
  80. package/dist/holmes/mcp/approval-intent.d.ts +44 -0
  81. package/dist/holmes/mcp/approval-intent.js +67 -0
  82. package/dist/holmes/mcp/approval-policy.d.ts +14 -0
  83. package/dist/holmes/mcp/approval-policy.js +18 -0
  84. package/dist/holmes/mcp/elicit-approval.d.ts +2 -0
  85. package/dist/holmes/mcp/elicit-approval.js +8 -3
  86. package/dist/holmes/mcp/handlers/graph-operations.d.ts +17 -1
  87. package/dist/holmes/mcp/handlers/graph-operations.js +15 -6
  88. package/dist/holmes/mcp/handlers/maintenance-analysis.js +11 -5
  89. package/dist/holmes/mcp/handlers/maintenance-evidence.js +3 -2
  90. package/dist/holmes/mcp/handlers/phase-queries.d.ts +22 -7
  91. package/dist/holmes/mcp/handlers/phase-queries.js +81 -2
  92. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +26 -0
  93. package/dist/holmes/mcp/handlers/requirement-triage.js +48 -11
  94. package/dist/holmes/mcp/handlers/review-evidence.d.ts +2 -1
  95. package/dist/holmes/mcp/handlers/review-evidence.js +15 -5
  96. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +18 -0
  97. package/dist/holmes/mcp/handlers/slice-orchestration.js +122 -16
  98. package/dist/holmes/mcp/handlers/spec-approval.d.ts +35 -2
  99. package/dist/holmes/mcp/handlers/spec-approval.js +175 -57
  100. package/dist/holmes/mcp/handlers/spec-authoring.js +36 -3
  101. package/dist/holmes/mcp/handlers/spec-queries.d.ts +39 -3
  102. package/dist/holmes/mcp/handlers/spec-queries.js +114 -7
  103. package/dist/holmes/mcp/handlers/test-execution.js +9 -3
  104. package/dist/holmes/mcp/handlers.d.ts +126 -8
  105. package/dist/holmes/mcp/handlers.js +109 -18
  106. package/dist/holmes/mcp/harness-attestation.d.ts +20 -0
  107. package/dist/holmes/mcp/harness-attestation.js +179 -0
  108. package/dist/holmes/mcp/maintenance-analyze.js +28 -4
  109. package/dist/holmes/mcp/maintenance-evidence.js +1 -1
  110. package/dist/holmes/mcp/requirement-triage-evidence.d.ts +72 -2
  111. package/dist/holmes/mcp/requirement-triage-evidence.js +227 -1
  112. package/dist/holmes/mcp/server.js +24 -3
  113. package/dist/holmes/mcp/supervisor.js +7 -3
  114. package/dist/holmes/mcp/tool-schemas.d.ts +8 -0
  115. package/dist/holmes/mcp/tool-schemas.js +54 -7
  116. package/dist/holmes/mcp/validate-args.js +12 -0
  117. package/dist/holmes/project/bounded-io.d.ts +102 -0
  118. package/dist/holmes/project/bounded-io.js +212 -0
  119. package/dist/holmes/project/change-source.js +3 -1
  120. package/dist/holmes/project/ci-runs.js +3 -2
  121. package/dist/holmes/project/ignore.d.ts +31 -2
  122. package/dist/holmes/project/ignore.js +409 -50
  123. package/dist/holmes/project/regular-file-guard.d.ts +13 -0
  124. package/dist/holmes/project/regular-file-guard.js +149 -0
  125. package/dist/holmes/project/root.js +12 -3
  126. package/dist/holmes/refresh/freshness-coordinator.d.ts +67 -0
  127. package/dist/holmes/refresh/freshness-coordinator.js +230 -0
  128. package/dist/holmes/reverse/anchor.js +4 -3
  129. package/dist/holmes/reverse/scan.js +6 -2
  130. package/dist/holmes/review/commit-text.js +3 -2
  131. package/dist/holmes/review/condition-hunk-replay.d.ts +12 -0
  132. package/dist/holmes/review/condition-hunk-replay.js +13 -2
  133. package/dist/holmes/review/condition-hunk-resolution.js +59 -8
  134. package/dist/holmes/review/failed-test-names.js +13 -10
  135. package/dist/holmes/review/findings.js +3 -1
  136. package/dist/holmes/review/kills-check.js +6 -1
  137. package/dist/holmes/review/point-in-time-replay.js +5 -4
  138. package/dist/holmes/review/replay-corpus.js +5 -4
  139. package/dist/holmes/review/requirement-triage-human-records.d.ts +59 -0
  140. package/dist/holmes/review/requirement-triage-human-records.js +119 -0
  141. package/dist/holmes/review/run-replay.js +3 -2
  142. package/dist/holmes/review/scope.js +6 -1
  143. package/dist/holmes/review/temporal-prior.js +3 -2
  144. package/dist/holmes/review/test-evidence.js +3 -2
  145. package/dist/holmes/review/test-outcomes.d.ts +28 -0
  146. package/dist/holmes/review/test-outcomes.js +92 -2
  147. package/dist/holmes/review/test-runner.d.ts +6 -0
  148. package/dist/holmes/review/test-runner.js +36 -15
  149. package/dist/holmes/rtm/advisory-outcomes.js +3 -2
  150. package/dist/holmes/rtm/anchor-ids.js +42 -2
  151. package/dist/holmes/rtm/file-anchors.js +4 -1
  152. package/dist/holmes/rtm/ftt-fulfilment.js +8 -3
  153. package/dist/holmes/rtm/git-changes.js +3 -1
  154. package/dist/holmes/rtm/graph-store.js +3 -2
  155. package/dist/holmes/rtm/test-scope.js +9 -4
  156. package/dist/holmes/spec/compat-impact.d.ts +25 -4
  157. package/dist/holmes/spec/compat-impact.js +682 -11
  158. package/dist/holmes/spec/entity-git-snapshot.js +3 -2
  159. package/dist/holmes/spec/entity-integration.js +3 -2
  160. package/dist/holmes/spec/entity-renumber-transaction.d.ts +19 -0
  161. package/dist/holmes/spec/entity-renumber-transaction.js +79 -6
  162. package/dist/holmes/spec/remote-spec-refs.js +3 -2
  163. package/dist/holmes/spec/renumber.js +25 -10
  164. package/dist/holmes/spec/spec-parser.js +9 -3
  165. package/dist/holmes/spec/yaml-scalar.js +2 -2
  166. package/dist/holmes/update/refresh.js +3 -1
  167. package/dist/holmes/update/update-notice.d.ts +6 -0
  168. package/dist/holmes/update/update-notice.js +18 -1
  169. package/package.json +11 -4
@@ -0,0 +1,1245 @@
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.ORACLE_WORKER_SOURCE = exports.MAX_WALK_STEPS = exports.MAX_LAUNCH_PATH = exports.launchKey = exports.INSTALL_CHECKS_MAX = exports.clipText = exports.escapeForDisplay = exports.UNREADABLE_ENV_VAR = exports.CONSENT_ENV = exports.AUTHORITY_ENV = exports.GATE_TOOLS = void 0;
37
+ exports.hollowedGateTools = hollowedGateTools;
38
+ exports.runsHolmesServer = runsHolmesServer;
39
+ exports.canonicalHolmesLaunch = canonicalHolmesLaunch;
40
+ exports.cappedList = cappedList;
41
+ exports.launcherBase = launcherBase;
42
+ exports.launchText = launchText;
43
+ exports.ownHolmesTableOf = ownHolmesTableOf;
44
+ exports.openableLocalPath = openableLocalPath;
45
+ exports.localRealpath = localRealpath;
46
+ exports.envFindings = envFindings;
47
+ exports.serverAuthority = serverAuthority;
48
+ exports.tableRedirection = tableRedirection;
49
+ exports.layerFileNamed = layerFileNamed;
50
+ exports.isHolmesPreToolCommand = isHolmesPreToolCommand;
51
+ exports.holmesPreToolDisabled = holmesPreToolDisabled;
52
+ exports.findCodex = findCodex;
53
+ exports.askCodex = askCodex;
54
+ // @implements A-SPEC-738
55
+ // Whether Codex loads a config.toml or hooks.json is Codex's question to answer. Ten rounds of
56
+ // emulating its loader each found new gaps — confirmation round 3 measured five more files we called
57
+ // loadable that codex-cli 0.155.1 refuses whole (and then lists no hooks, so the Holmes gate silently
58
+ // does not load). So where codex is installed we ask it: a short-lived `codex app-server` over COPIES
59
+ // in a temporary CODEX_HOME, with plugin sync switched off and every proxy pointed at a closed local
60
+ // port — measured: a default app-server contacts chatgpt.com and github.com; with
61
+ // `--disable plugins --disable remote_plugin` it contacted nothing. The real ~/.codex is never handed
62
+ // to Codex and never written. Without codex, callers fall back to the emulation and say so.
63
+ const fs = __importStar(require("node:fs"));
64
+ const os = __importStar(require("node:os"));
65
+ const path = __importStar(require("node:path"));
66
+ const node_child_process_1 = require("node:child_process");
67
+ const codex_toml_1 = require("./codex-toml");
68
+ const APP_SERVER_ARGS = ['app-server', '--disable', 'plugins', '--disable', 'remote_plugin'];
69
+ /** Channels that write or send outside the copy (measured: an [otel] gRPC exporter flushed to the
70
+ * user's collector; sqlite_home put Codex's databases outside the temporary home). */
71
+ // @implements A-SPEC-738 (round 3) — an override must never mask a value Codex would judge (measured:
72
+ // `[otel] exporter = "otlp-http"`, `[analytics] enabled = "yes"`, `sqlite_home = 5` are refusals, and
73
+ // the overrides replaced them). So a key is overridden only where no layer sets it — or, for
74
+ // sqlite_home, where every layer sets a string (then only the location changes). Where a layer keeps
75
+ // its own exporter, the group SIGKILL (no graceful flush) and the short run are the wall.
76
+ function isolationOverrides(home, layers) {
77
+ const sets = (k) => layers.some((l) => Object.prototype.hasOwnProperty.call(l, k));
78
+ const out = [];
79
+ // @implements A-SPEC-738 (round 7) — `otel` from the USER copy alone: Codex ignores `otel` in a project
80
+ // layer ("Ignored unsupported project-local config keys"), and counting the layer skipped the "none"
81
+ // override while an endpoint override synthesised a table without `protocol` — codex exited 1 (measured).
82
+ const otelLayers = layers.slice(0, 1);
83
+ if (!otelLayers.some((l) => Object.prototype.hasOwnProperty.call(l, 'otel')))
84
+ out.push('-c', 'otel.exporter="none"', '-c', 'otel.trace_exporter="none"', '-c', 'otel.metrics_exporter="none"');
85
+ // @implements A-SPEC-738 (round 10) — `sqlite_home` and `analytics` from the USER COPY alone: whether
86
+ // Codex reads a workspace layer depends on a trust the copy cannot show, and judging from every layer
87
+ // was wrong both ways (measured: an UNTRUSTED layer's `sqlite_home = 5` skipped the override and Codex
88
+ // created and migrated 15 SQLite files at the user's absolute path). The override is applied unless
89
+ // the copy's own value is one Codex refuses, which the override would mask; such a value in another
90
+ // layer declines the oracle (`layerDecline`).
91
+ const copy = layers[0] ?? {};
92
+ if (analyticsValid(copy))
93
+ out.push('-c', 'analytics.enabled=false');
94
+ if (sqliteHomeValid(copy))
95
+ out.push('-c', `sqlite_home=${JSON.stringify(home)}`);
96
+ void sets;
97
+ // @implements A-SPEC-738 (round 5) — an exporter a layer keeps is pointed at a closed address, a string
98
+ // for a string, so the value Codex judges keeps its shape (measured: a deep cwd queued enough spans
99
+ // for the batch processor to export mid-run to a LAN collector). Only where EVERY layer that sets that
100
+ // endpoint sets an http(s) URL — any other value is Codex's to judge, and an override would mask it.
101
+ const isTable = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
102
+ // @implements A-SPEC-738 (round 8) — a URI Codex's parser accepts, whatever the scheme (tonic dialled a
103
+ // `grpc://` collector that only `http(s)://` was overridden for — measured egress), and only such: a
104
+ // blank, tab or control character is a value Codex rejects (`invalid uri character`) that WHATWG
105
+ // `new URL` accepted, and overriding it swapped a fatal endpoint for a valid one.
106
+ // @implements A-SPEC-738 (round 9) — a NARROW allowlist, and the oracle declines the rest (`otelDecline`):
107
+ // two rounds of imitating Codex's URI parser were wrong both ways (a digit-leading or empty scheme and
108
+ // a DEL byte dialled the collector; `[::1]`, `127.1`, an empty authority made Codex exit 1 while the
109
+ // override let it load — measured). Only this shape is a string Codex reads the same as ours.
110
+ for (const k of ['exporter', 'trace_exporter', 'metrics_exporter']) {
111
+ for (const l of otelLayers) {
112
+ const e = isTable(l.otel) ? l.otel[k] : undefined;
113
+ if (!isTable(e) || overridableExporter(e) === null)
114
+ continue;
115
+ const [kind, t] = overridableExporter(e);
116
+ out.push('-c', `otel.${k}.${kind}.endpoint=${JSON.stringify(CLOSED_PROXY)}`);
117
+ if (kind === 'otlp-http')
118
+ out.push('-c', `otel.${k}.${kind}.protocol=${JSON.stringify(String(t.protocol))}`);
119
+ }
120
+ }
121
+ return out;
122
+ }
123
+ const isTableValue = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
124
+ /** The one (kind, table) pair of an exporter table the oracle may point at the closed address, or null. */
125
+ function overridableExporter(e) {
126
+ const kinds = Object.keys(e);
127
+ if (kinds.length !== 1)
128
+ return null;
129
+ const kind = kinds[0];
130
+ const t = e[kind];
131
+ if ((kind !== 'otlp-grpc' && kind !== 'otlp-http') || !isTableValue(t))
132
+ return null;
133
+ const ep = t.endpoint;
134
+ // Round 10: `_` in a label (`http://otel_collector:4317`, a Docker network name Codex's parser accepts).
135
+ if (typeof ep !== 'string' || ep.length > 2048 || !/^https?:\/\/[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*(?::\d{1,5})?(?:\/[A-Za-z0-9._~/-]*)?$/.test(ep))
136
+ return null;
137
+ if (kind === 'otlp-http' && t.protocol !== 'binary' && t.protocol !== 'json')
138
+ return null;
139
+ return [kind, t];
140
+ }
141
+ /** The `otel` key of the user copy the oracle cannot neutralize (an exporter TABLE outside the allowlist), or null. */
142
+ /** Whether `[analytics]` is absent or a table whose `enabled`, if set, is a boolean (anything else Codex refuses). */
143
+ function analyticsValid(layer) {
144
+ if (!Object.prototype.hasOwnProperty.call(layer, 'analytics'))
145
+ return true;
146
+ const a = layer.analytics;
147
+ return isTableValue(a) && (!Object.prototype.hasOwnProperty.call(a, 'enabled') || typeof a.enabled === 'boolean');
148
+ }
149
+ /** Whether `sqlite_home` is absent or a path string (round 11: Codex reads a TOML date as a path string too). */
150
+ function sqliteHomeValid(layer) {
151
+ if (!Object.prototype.hasOwnProperty.call(layer, 'sqlite_home'))
152
+ return true;
153
+ const v = layer.sqlite_home;
154
+ return typeof v === 'string' || v instanceof Date;
155
+ }
156
+ /**
157
+ * @implements A-SPEC-738 (round 10) — a workspace layer carrying a value the isolation overrides would
158
+ * mask (a non-string `sqlite_home`, a non-boolean `analytics.enabled`): the oracle cannot tell whether
159
+ * Codex reads that layer, and both guesses were wrong, so it declines before codex starts.
160
+ * @implements A-SPEC-738 (round 11) — and a layer setting the key AT ALL while the COPY's own value is
161
+ * one the override must not mask: Codex merges a trusted layer's valid value over the copy's invalid
162
+ * one, and with the override skipped the merged config loaded and created 15 SQLite files at the
163
+ * layer's path (measured).
164
+ */
165
+ function layerDecline(copy, others) {
166
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
167
+ for (const l of others) {
168
+ if (has(l, 'sqlite_home') && !sqliteHomeValid(l))
169
+ return 'a non-string sqlite_home';
170
+ if (has(l, 'sqlite_home') && !sqliteHomeValid(copy))
171
+ return "a sqlite_home beside the user file's own unjudgeable sqlite_home";
172
+ if (has(l, 'analytics') && !analyticsValid(l))
173
+ return 'a non-boolean analytics.enabled';
174
+ if (has(l, 'analytics') && !analyticsValid(copy))
175
+ return "an [analytics] table beside the user file's own unjudgeable analytics.enabled";
176
+ }
177
+ return null;
178
+ }
179
+ /** The MCP tools the governance procedure cannot do without (a table that disables one hollows the gate). */
180
+ exports.GATE_TOOLS = ['spec_create', 'spec_slice_init', 'spec_approve', 'spec_slice_approve', 'phase_check', 'test_run', 'maintenance_analyze', 'requirement_triage'];
181
+ /**
182
+ * @implements A-SPEC-738 (round 12) — the gate tools a `[mcp_servers.holmes-kit]` table takes away: a
183
+ * `disabled_tools` naming one, or a non-empty `enabled_tools` lacking one (measured: a trusted layer's
184
+ * `disabled_tools` covering every Holmes tool passed doctor as "resolves"). Null when none.
185
+ */
186
+ function hollowedGateTools(table) {
187
+ if (table === null)
188
+ return null;
189
+ const names = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : null);
190
+ const disabled = names(table.disabled_tools);
191
+ const enabled = names(table.enabled_tools);
192
+ const gone = new Set();
193
+ if (disabled)
194
+ for (const t of exports.GATE_TOOLS)
195
+ if (disabled.includes(t))
196
+ gone.add(t);
197
+ if (enabled && enabled.length > 0)
198
+ for (const t of exports.GATE_TOOLS)
199
+ if (!enabled.includes(t))
200
+ gone.add(t);
201
+ return gone.size > 0 ? [...gone].join(', ') : null;
202
+ }
203
+ /**
204
+ * @implements A-SPEC-738 (round 13) — the server-environment variables that carry AUTHORITY: an approval
205
+ * key, autonomy, a ledger key, a role or profile, or a switch that weakens or bypasses the gate.
206
+ */
207
+ exports.AUTHORITY_ENV = ['HOLMES_APPROVAL', 'HOLMES_AUTONOMOUS_APPROVAL', 'HOLMES_LEDGER_KEY', 'HOLMES_ROLE', 'HOLMES_MCP_PROFILE', 'HOLMES_ENV_CHANNEL',
208
+ 'HOLMES_ELICIT', 'HOLMES_GATE_BYPASS', 'HOLMES_GATE_OFF', 'HOLMES_OBSERVE_ONLY', 'HOLMES_CSPEC_OFF', 'HOLMES_CSPEC_DISABLE', 'HOLMES_STRUCTURAL_OFF', 'HOLMES_CONSTRAINTS_OFF'];
209
+ /**
210
+ * @implements A-SPEC-738 (round 14) — the egress-consent keys: the product treats the key AS consent to send
211
+ * data out (`semantic/credentials.ts`), the class of HOLMES_ROLE. The generic spellings count only on a
212
+ * Holmes server (another server may need its own Gemini key); the dedicated one counts everywhere.
213
+ */
214
+ exports.CONSENT_ENV = ['HOLMES_SEMANTIC_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_API_KEY'];
215
+ /**
216
+ * @implements A-SPEC-738 (round 15) — `HOME` and `USERPROFILE` locate the credential file the semantic tier
217
+ * reads (measured: a layer's `HOME` turned the server's tier to cloud), so on a Holmes server they are consent.
218
+ */
219
+ const CREDENTIAL_HOME = ['HOME', 'USERPROFILE'];
220
+ /** Round 14: compared without case — Windows reads `process.env` without case (`cleanSubprocessEnv` folds too). */
221
+ function isAuthorityKey(k, holmes) {
222
+ const u = k.toUpperCase();
223
+ return exports.AUTHORITY_ENV.includes(u) || u === 'HOLMES_SEMANTIC_API_KEY' || (holmes && (exports.CONSENT_ENV.includes(u) || CREDENTIAL_HOME.includes(u)));
224
+ }
225
+ /** Keys that bind the server's spec store (`resolveServerSpecsDir`), judged as redirects, not as added env. */
226
+ const REDIRECT_ENV = new Set(['HOLMES_SPECS', 'CLAUDE_PROJECT_DIR']);
227
+ /**
228
+ * @implements A-SPEC-738 (round 15) — keys a layer may add to a Holmes server that change nothing the gate
229
+ * judges (the added-env WARN). Every other non-`HOLMES_*` key — `PATH`, `NODE_OPTIONS`, `NODE_EXTRA_CA_CERTS`,
230
+ * proxies … — can run code in the server or redirect what it reads or sends: unjudgeable, a FAIL.
231
+ */
232
+ const BENIGN_ENV = /^(?:HOLMES_MCP_AUTORELOAD|HOLMES_NO_SEMANTIC_WARM|HOLMES_NO_UPDATE_CHECK|HOLMES_NO_AUTO_REPIN|HOLMES_SKIP_MODEL_INSTALL|HOLMES_DEBUG|NODE_NO_WARNINGS|NO_COLOR|FORCE_COLOR|TERM|COLORTERM|LANG|LANGUAGE|LC_[A-Z0-9_]+|TZ)$/;
233
+ /**
234
+ * @implements A-SPEC-738 (round 16) — the name a process receives: the text before the first `=` (Codex sets
235
+ * `KEY=VALUE` and the environment splits at the first `=`; a layer's `"HOLMES_AUTONOMOUS_APPROVAL=1" = "1"`
236
+ * reached the server as `HOLMES_AUTONOMOUS_APPROVAL=1=1` and turned autonomy on — measured).
237
+ */
238
+ const envName = (k) => { const i = k.indexOf('='); return i < 0 ? k : k.slice(0, i); };
239
+ /** Round 14: an `env_vars` entry in either form Codex accepts — a string, or a table whose `name` is a string; null = neither. */
240
+ function envVarName(x) {
241
+ if (typeof x === 'string')
242
+ return x;
243
+ if (isTableValue(x) && typeof x.name === 'string')
244
+ return x.name;
245
+ return null;
246
+ }
247
+ const asArray = (v) => (Array.isArray(v) ? v : []);
248
+ /** Named in findings for an `env_vars` entry in neither form: unjudgeable, so it counts as authority. */
249
+ exports.UNREADABLE_ENV_VAR = 'an env_vars entry the oracle cannot read';
250
+ /**
251
+ * @implements A-SPEC-738 (round 15) — recognition is LEXICAL and opens no file: a word naming `holmes-mcp`
252
+ * (a path component or program, `.js`/`.cmd`/`.ps1`/`.exe` shims included), ending in
253
+ * `dist/holmes/mcp/server(.js)`/`handlers(.js)`, or naming the package `@holmes-lab/holmes-kit`. Round 14 read
254
+ * real paths: a 30-link symlink chain took 46 s per ask outside the worker timeout, and on Windows opening a
255
+ * UNC word would contact its host (measured / reasoned). A bare `holmes-kit` is data.
256
+ */
257
+ const HOLMES_SERVER_WORD = /(?:^|[\\/\s'"`(=:,;])holmes-mcp(?:\.(?:js|cmd|ps1|exe))?(?![\w.-])|dist[\\/]+holmes[\\/]+mcp[\\/]+(?:server|handlers)(?:\.js)?(?![\w.-])|@holmes-lab[\\/]+holmes-kit(?![\w-])/i;
258
+ /** A word with its URLs blanked (a docs server's `https://…/holmes-mcp` is data); linear — each `://` is scanned once. */
259
+ function withoutUrls(w) {
260
+ let i = w.indexOf('://');
261
+ if (i === -1)
262
+ return w;
263
+ let out = '';
264
+ let last = 0;
265
+ while (i !== -1) {
266
+ let st = i;
267
+ while (st > last && /[A-Za-z0-9+.-]/.test(w[st - 1]))
268
+ st--;
269
+ let e = i + 3;
270
+ while (e < w.length && !/[\s'"`]/.test(w[e]))
271
+ e++;
272
+ out += w.slice(last, st) + ' ';
273
+ last = e;
274
+ i = w.indexOf('://', e);
275
+ }
276
+ return out + w.slice(last);
277
+ }
278
+ /** Whether a `[mcp_servers.*]` table runs a Holmes server, read from its words alone (every word, no cap). */
279
+ function runsHolmesServer(t) {
280
+ for (const w of [t.command, ...asArray(t.args)])
281
+ if (typeof w === 'string' && HOLMES_SERVER_WORD.test(withoutUrls(w)))
282
+ return true;
283
+ return false;
284
+ }
285
+ /**
286
+ * @implements A-SPEC-738 (round 15) — the two launches init writes: `node <path>/bin/holmes-mcp.js` (that one
287
+ * argument) and `npx -y -p @holmes-lab/holmes-kit@<version> holmes-mcp`. Anything else — an `env` wrapper,
288
+ * `--env-file`, `-r`/`--import`/`-e`, a shell `-c`, an extra argument — can set the server's environment.
289
+ */
290
+ function canonicalHolmesLaunch(t) {
291
+ if (typeof t.command !== 'string')
292
+ return false;
293
+ const args = asArray(t.args);
294
+ if (!args.every((a) => typeof a === 'string'))
295
+ return false;
296
+ const a = args;
297
+ // @implements A-SPEC-738 (round 17) — the command itself must be the bare `node`/`npx` init writes: a path
298
+ // whose last component reads `node` is a program the layer chose (`<ws>/tools/node` set HOLMES_APPROVAL — measured).
299
+ const base = t.command === 'node' || t.command === 'npx' ? t.command : '';
300
+ if (base === 'node' && a.length === 1 && !a[0].startsWith('-') && /(?:^|[\\/])bin[\\/]holmes-mcp\.js$/.test(a[0]))
301
+ return true;
302
+ return base === 'npx' && a.length === 4 && a[0] === '-y' && a[1] === '-p' && /^@holmes-lab\/holmes-kit@[0-9A-Za-z.+-]+$/.test(a[2]) && a[3] === 'holmes-mcp';
303
+ }
304
+ /** Round 18: one value in a message, clipped (a 900 KB env key made a 900 KB WARN — measured). */
305
+ /**
306
+ * @implements A-SPEC-251.2 (round 45) — a value from a file, clipped and made safe to print: a newline in a wiring value printed a
307
+ * forged `PASS` line (measured); control, line-separator and bidirectional characters are escaped.
308
+ */
309
+ const escapeForDisplay = (s) => s.replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
310
+ exports.escapeForDisplay = escapeForDisplay;
311
+ const clipText = (s, max = 200) => (0, exports.escapeForDisplay)(s.length > max ? `${s.slice(0, max)}…` : s);
312
+ exports.clipText = clipText;
313
+ /**
314
+ * Round 17: a list for one message line — ten items, then a count (a 1 MB layer produced a 1.5 MB line — measured).
315
+ * @implements A-SPEC-738 (round 18) — each item clipped too (one second server's 40,000 keys were one 2.2 MB item).
316
+ */
317
+ function cappedList(items, max = 10) {
318
+ const shown = items.slice(0, max).map((s) => (0, exports.clipText)(s)).join('; ');
319
+ return items.length <= max ? shown : `${shown}; and ${items.length - max} more`;
320
+ }
321
+ /**
322
+ * @implements A-SPEC-738 (round 18) — the user file's OWN launch spelled as a path to `node`/`npx` or with
323
+ * `.exe`/`.cmd` is node/npx to doctor (the user's `/opt/homebrew/bin/node` was FAIL "does not run holmes-mcp" —
324
+ * measured). A layer's launch stays canonical only when bare (round 17).
325
+ */
326
+ function launcherBase(command) {
327
+ const m = /^(node|npx)((?:\.exe|\.cmd)?)$/i.exec(command.split(/[\\/]/).pop() ?? '');
328
+ // Round 19: `.exe`/`.cmd` only where they run (on POSIX `node.exe` cannot be spawned; doctor said PASS).
329
+ if (m === null || (m[2] !== '' && process.platform !== 'win32'))
330
+ return null;
331
+ return m[1].toLowerCase();
332
+ }
333
+ /** A launch as one line for a message, clipped (a 1 MiB argument list must not flood doctor). */
334
+ function launchText(t) {
335
+ // Round 16: a URL transport has no command; it is named by its address.
336
+ const text = typeof t.command !== 'string' && typeof t.url === 'string' ? `url ${t.url}`
337
+ : [t.command, ...asArray(t.args)].map((w) => (typeof w === 'string' ? w : JSON.stringify(w))).join(' ');
338
+ return (0, exports.escapeForDisplay)(text.length > 160 ? `${text.slice(0, 160)}…` : text);
339
+ }
340
+ const ENV_SETTING_FLAG = /^(?:--env-file(?:-if-exists)?(?:=|$)|-r$|--require(?:=|$)|--import(?:=|$)|-e$|--eval(?:=|$)|--loader(?:=|$)|--experimental-loader(?:=|$)|-c$|\/c$)/i;
341
+ /** Round 15: what an own non-canonical launch sets in the server's environment through its words (WARN). */
342
+ function launchAssignments(t) {
343
+ const out = [];
344
+ for (const w of [t.command, ...asArray(t.args)]) {
345
+ if (typeof w !== 'string')
346
+ continue;
347
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=/.exec(w);
348
+ if (m !== null) {
349
+ const u = m[1].toUpperCase();
350
+ if (isAuthorityKey(m[1], true) || (!BENIGN_ENV.test(u) && !REDIRECT_ENV.has(u)))
351
+ out.push(`${m[1]}= in the launch`);
352
+ }
353
+ else if (ENV_SETTING_FLAG.test(w))
354
+ out.push(`${w.split('=')[0]} in the launch`);
355
+ }
356
+ return out;
357
+ }
358
+ /** The user file's own `[mcp_servers.<name>]` table (default `holmes-kit`), or null. */
359
+ function ownHolmesTableOf(configText, name = 'holmes-kit') {
360
+ if (configText === null)
361
+ return null;
362
+ const p = (0, codex_toml_1.parseCodexConfig)(configText);
363
+ if (!p.ok)
364
+ return null;
365
+ const servers = p.doc.mcp_servers;
366
+ const t = isTableValue(servers) && Object.prototype.hasOwnProperty.call(servers, name) ? servers[name] : null;
367
+ return isTableValue(t) ? t : null;
368
+ }
369
+ exports.INSTALL_CHECKS_MAX = 64;
370
+ /** Round 16: a launch as Codex runs it — an absent `args` is `[]` (the user's own `command = "holmes-mcp"` read as a layer's). */
371
+ const launchKey = (t) => JSON.stringify([t.command ?? null, Array.isArray(t.args) ? t.args : []]);
372
+ exports.launchKey = launchKey;
373
+ /** Why a layer's canonical node launch is not this install's, or null when it is (or the caller knows no install). */
374
+ /**
375
+ * @implements A-SPEC-738 (round 17) — the only paths the oracle's callers open to check an install: a drive-letter
376
+ * path or a `/` path. `\\?\`, `\??\`, `//`, `\\` (network or device namespaces) and `/net/` (an automounter root)
377
+ * are never opened — opening them can contact another host.
378
+ */
379
+ function openableLocalPath(p) {
380
+ // Round 18: either separator after the drive (`C:/…` is a local path — round 17 named it a network path).
381
+ if (/^[A-Za-z]:[\\/]/.test(p))
382
+ return !/[?*]/.test(p);
383
+ if (!p.startsWith('/') || p.startsWith('//'))
384
+ return false;
385
+ // Round 18: without `.`/`..` and without case (`/NET/h`, `/./net/h`, `/private/../net/h` reached realpath — measured).
386
+ return !/^\/net(?:\/|$)/i.test(path.posix.normalize(p));
387
+ }
388
+ /**
389
+ * @implements A-SPEC-738 (round 18) — a path resolved one component at a time: a link is followed only when its
390
+ * target is itself an openable local path, so no network, device or automounter path is ever looked up (a
391
+ * workspace link to `/net/<host>` reached `realpath` — measured). `refused`: such a path was met; `path`: the
392
+ * real path, null when the file is missing.
393
+ */
394
+ /** Round 19: no system opens a longer path (PATH_MAX); walking one is only cost (a 1 MB path took 47.9 s — measured). */
395
+ exports.MAX_LAUNCH_PATH = 4096;
396
+ /** Round 20: the raw argument's bound before it is resolved (resolving is linear; this keeps it cheap). */
397
+ const MAX_RAW_LAUNCH_PATH = 64 * 1024;
398
+ /**
399
+ * @implements A-SPEC-251.2 (round 43) — one walk follows at most this many components: 40 links of 300 components each made
400
+ * every walk ~12,000 look-ups, and 1,000 committed gate entries held doctor for 106 s (measured). Past it the walk is
401
+ * `exhausted` — not confirmed, never "missing".
402
+ */
403
+ exports.MAX_WALK_STEPS = 4096;
404
+ function localRealpath(p) {
405
+ if (p.length > MAX_RAW_LAUNCH_PATH)
406
+ return { path: null, refused: false };
407
+ if (!openableLocalPath(p))
408
+ return { path: null, refused: true };
409
+ if (!path.isAbsolute(p))
410
+ return { path: null, refused: false };
411
+ // @implements A-SPEC-738 (round 19) — `.` and `..` are removed as TEXT first, as node resolves `argv[1]`
412
+ // (`path.resolve`) before any link is followed: `<ws>/tools/link/../bin/holmes-mcp.js` ran the wrapper
413
+ // `<ws>/tools/bin/holmes-mcp.js` while the round-18 walk followed `..` through the link (measured).
414
+ const resolved = path.resolve(p);
415
+ // Round 20: the 4,096 bound applies to the path node opens (a 4,097-character path padded with `/.` is one it opens).
416
+ if (resolved.length > exports.MAX_LAUNCH_PATH)
417
+ return { path: null, refused: false };
418
+ if (!openableLocalPath(resolved))
419
+ return { path: null, refused: true };
420
+ const split = (q) => (process.platform === 'win32' ? q.split(/[\\/]+/) : q.split('/')).filter((c) => c !== '' && c !== '.');
421
+ const root0 = path.parse(resolved).root;
422
+ let done = root0;
423
+ // Round 19: a stack (pop is constant time); `shift` made the walk quadratic in the components.
424
+ const queue = split(resolved.slice(root0.length)).reverse();
425
+ let hops = 0;
426
+ let steps = 0;
427
+ while (queue.length > 0) {
428
+ // Round 44: refused too — a caller that decides whether to open a path on `refused` must not open this one (a stopped
429
+ // walk read as not refused let doctor open the spelled path through twelve links to `/net` — measured).
430
+ if (++steps > exports.MAX_WALK_STEPS)
431
+ return { path: null, refused: true, exhausted: true };
432
+ const c = queue.pop();
433
+ // Only a link target still holds `..`; `done` never holds a link, so `..` on it is what the system does.
434
+ if (c === '..') {
435
+ done = path.dirname(done);
436
+ continue;
437
+ }
438
+ const next = path.join(done, c);
439
+ if (!openableLocalPath(next))
440
+ return { path: null, refused: true };
441
+ let st;
442
+ try {
443
+ st = fs.lstatSync(next);
444
+ }
445
+ catch {
446
+ return { path: null, refused: false };
447
+ }
448
+ if (!st.isSymbolicLink()) {
449
+ done = next;
450
+ continue;
451
+ }
452
+ if (++hops > 40)
453
+ return { path: null, refused: false };
454
+ let target;
455
+ try {
456
+ target = fs.readlinkSync(next);
457
+ }
458
+ catch {
459
+ return { path: null, refused: false };
460
+ }
461
+ if (path.isAbsolute(target)) {
462
+ if (!openableLocalPath(target))
463
+ return { path: null, refused: true };
464
+ const r = path.parse(target).root;
465
+ done = r;
466
+ queue.push(...split(target.slice(r.length)).reverse());
467
+ }
468
+ else {
469
+ queue.push(...split(target).reverse());
470
+ }
471
+ }
472
+ try {
473
+ return { path: fs.realpathSync.native(done), refused: false };
474
+ }
475
+ catch {
476
+ return { path: null, refused: false };
477
+ }
478
+ }
479
+ function notThisInstall(t, install) {
480
+ // @implements A-SPEC-738 (round 20) — a layer's npx launch is authority whatever it pins: since REQ-251 an install is
481
+ // wired with node, and npx runs npm in the session workspace, whose `.npmrc` ran code in the server while doctor
482
+ // said PASS (measured). Round 18 accepted an exact pin.
483
+ if (t.command === 'npx')
484
+ return `the launch \`${launchText(t)}\` runs npm in the session workspace (npx), whose .npmrc and node_modules can replace the server`;
485
+ if (install === undefined)
486
+ return null;
487
+ if (install.bin === null || t.command !== 'node')
488
+ return null;
489
+ const arg = String(asArray(t.args)[0] ?? '');
490
+ if (!(path.isAbsolute(arg) || path.win32.isAbsolute(arg)))
491
+ return `the launch \`${launchText(t)}\` names a relative path, which cannot be checked against this install`;
492
+ // Round 20: the bound applies to the path node opens — after `.`/`..` are removed.
493
+ if (arg.length > MAX_RAW_LAUNCH_PATH || (path.isAbsolute(arg) && path.resolve(arg).length > exports.MAX_LAUNCH_PATH))
494
+ return `the launch \`${launchText(t)}\` names a path longer than ${exports.MAX_LAUNCH_PATH} characters, which is not checked`;
495
+ if (!openableLocalPath(arg))
496
+ return `the launch \`${launchText(t)}\` names a network or device path, which is never opened`;
497
+ if (install.budget.left <= 0)
498
+ return `the launch \`${launchText(t)}\` is beyond the ${exports.INSTALL_CHECKS_MAX} launches one run checks against this install`;
499
+ install.budget.left--;
500
+ const walked = localRealpath(arg);
501
+ if (walked.refused)
502
+ return walked.exhausted
503
+ ? `the launch \`${launchText(t)}\` reaches past doctor's walk bound (${exports.MAX_WALK_STEPS} components), so it is never opened`
504
+ : `the launch \`${launchText(t)}\` reaches a network or device path through a link, which is never opened`;
505
+ return walked.path === install.bin ? null : `the launch \`${launchText(t)}\` runs a holmes-mcp.js that is not this install's`;
506
+ }
507
+ function envFindings(effective, own, holmes = true, install) {
508
+ const out = { authorityFromLayer: [], authorityOwn: [], addedFromLayer: [], envVarsFromLayer: [], envVarsOwn: [] };
509
+ if (effective === null)
510
+ return out;
511
+ // @implements A-SPEC-738 (round 15) — a launch another layer provides or changes must be canonical, and then
512
+ // every authority key the server holds is the layer's (measured: a layer swapped the user's Gemini server's
513
+ // command for holmes-mcp.js and doctor blamed the user file).
514
+ const launchFromLayer = own === null || (0, exports.launchKey)(effective) !== (0, exports.launchKey)(own);
515
+ const hasLaunch = effective.command !== undefined || effective.args !== undefined;
516
+ if (holmes && hasLaunch && !canonicalHolmesLaunch(effective)) {
517
+ if (launchFromLayer)
518
+ out.authorityFromLayer.push(`the launch \`${launchText(effective)}\`, not one holmes-kit writes (it can set the server's environment)`);
519
+ else
520
+ out.authorityOwn.push(...launchAssignments(effective));
521
+ }
522
+ else if (holmes && hasLaunch && launchFromLayer) {
523
+ // Round 16: a canonical node launch from a layer must be this install's (a wrapper named bin/holmes-mcp.js
524
+ // that set HOLMES_APPROVAL passed as a WARN for a layer-only table and a second server — measured).
525
+ const why = notThisInstall(effective, install);
526
+ if (why !== null)
527
+ out.authorityFromLayer.push(why);
528
+ }
529
+ const env = isTableValue(effective.env) ? effective.env : {};
530
+ const ownEnv = own !== null && isTableValue(own.env) ? own.env : {};
531
+ for (const [k, v] of Object.entries(env)) {
532
+ const ownSame = Object.prototype.hasOwnProperty.call(ownEnv, k) && JSON.stringify(ownEnv[k]) === JSON.stringify(v);
533
+ const name = envName(k);
534
+ const u = name.toUpperCase();
535
+ // Round 16: a key holding `=` sets `name` to another value; on a Holmes server it is never a plain setting.
536
+ if (isAuthorityKey(name, holmes) || (holmes && name !== k)) {
537
+ const label = name === k ? k : `${name} (set through the key "${k.length > 80 ? `${k.slice(0, 80)}…` : k}")`;
538
+ (ownSame && !launchFromLayer ? out.authorityOwn : out.authorityFromLayer).push(label);
539
+ continue;
540
+ }
541
+ if (ownSame || REDIRECT_ENV.has(u))
542
+ continue;
543
+ // Round 16: a HOLMES_* key outside the benign set is unjudgeable too (HOLMES_PYTHON picked test_run's interpreter).
544
+ if (!holmes || BENIGN_ENV.test(u))
545
+ out.addedFromLayer.push(k);
546
+ else
547
+ out.authorityFromLayer.push(`${k} (an environment change holmes-kit cannot judge)`);
548
+ }
549
+ // Round 15: own names match exactly — a lowercase own name is another variable where the case matters.
550
+ const ownEntries = asArray(own?.env_vars);
551
+ const ownNames = new Set(ownEntries.map(envVarName).filter((n) => n !== null));
552
+ const ownRaw = new Set(ownEntries.map((x) => JSON.stringify(x)));
553
+ for (const x of asArray(effective.env_vars)) {
554
+ const raw = envVarName(x);
555
+ const k = raw === null ? null : envName(raw);
556
+ if (k === null) {
557
+ (ownRaw.has(JSON.stringify(x)) && !launchFromLayer ? out.envVarsOwn : out.envVarsFromLayer).push(exports.UNREADABLE_ENV_VAR);
558
+ continue;
559
+ }
560
+ const isOwn = ownNames.has(k);
561
+ if (isAuthorityKey(k, holmes))
562
+ (isOwn && !launchFromLayer ? out.envVarsOwn : out.envVarsFromLayer).push(k);
563
+ else if (!isOwn)
564
+ out.addedFromLayer.push(`env_vars ${k}`);
565
+ }
566
+ return out;
567
+ }
568
+ /** Authority a server's own table carries (env keys or `env_vars` entries of the authority class). */
569
+ function serverAuthority(t, holmes = true) {
570
+ const f = envFindings(t, null, holmes);
571
+ return [...f.authorityFromLayer, ...f.envVarsFromLayer];
572
+ }
573
+ /**
574
+ * The effective table's settings that bind the spec store elsewhere: `env.HOLMES_SPECS` and (round 14)
575
+ * `env.CLAUDE_PROJECT_DIR`, which `resolveServerSpecsDir` reads, and `cwd`.
576
+ * @implements A-SPEC-738 (round 14) — a relative HOLMES_SPECS redirects too (measured: the store bound to
577
+ * `<project>/vendor/decoy/.ax/specs`); only the default `.ax/specs` and the user file's own value are not.
578
+ */
579
+ function tableRedirection(table, own = null) {
580
+ if (table === null)
581
+ return { specs: null, cwd: null, projectDir: null };
582
+ const env = isTableValue(table.env) ? table.env : {};
583
+ const ownEnv = own !== null && isTableValue(own.env) ? own.env : {};
584
+ // Round 17: every key that differs only in case is judged (Windows reads one of them, which one is Codex's order).
585
+ const pick = (key, redirects = () => true) => {
586
+ for (const [k, v] of Object.entries(env)) {
587
+ if (k.includes('=') || k.toUpperCase() !== key || typeof v !== 'string' || v.trim() === '')
588
+ continue;
589
+ if (Object.prototype.hasOwnProperty.call(ownEnv, k) && ownEnv[k] === v)
590
+ continue;
591
+ if (redirects(v))
592
+ return v;
593
+ }
594
+ return null;
595
+ };
596
+ const specs = pick('HOLMES_SPECS', (v) => v.replace(/\\/g, '/').replace(/^(?:\.\/)+/, '').replace(/\/+$/, '') !== '.ax/specs');
597
+ const ownCwd = own !== null && typeof own.cwd === 'string' ? own.cwd : null;
598
+ const cwd = typeof table.cwd === 'string' && table.cwd !== '' && table.cwd !== ownCwd ? table.cwd : null;
599
+ return { specs, cwd, projectDir: pick('CLAUDE_PROJECT_DIR') };
600
+ }
601
+ /** Round 10/11: whether a verdict lists an enabled Holmes PreToolUse hook. */
602
+ const listsHolmesHook = (v) => v.hooks.some((h) => h.enabled && /^pretooluse$/i.test(h.event) && isHolmesPreToolCommand(h.command));
603
+ /**
604
+ * @implements A-SPEC-738 (round 11) — of two asks about the same target (as given, by its real path), the
605
+ * stricter answer per aspect: a refusal from either; the table absent > disabled > REPLACED (command or
606
+ * args differ from the copy's own entry) > as-is; the hooks list lacking the Holmes hook; the longer
607
+ * hook-error list; the union of other problems. Ties keep the given spelling's answer.
608
+ */
609
+ /**
610
+ * @implements A-SPEC-738 (round 14) — the two spellings' tables merged PER ASPECT: the ranked table keeps its
611
+ * command/args/enabled; `env` takes, key by key, a value that differs from the copy's own; `env_vars` and
612
+ * `disabled_tools` are unions, `enabled_tools` an intersection, and a `cwd` that differs from the copy's wins
613
+ * (measured: the link spelling's harmless env hid the real path's forged HOLMES_APPROVAL).
614
+ */
615
+ function mergedTable(ranked, other, copy) {
616
+ if (ranked === null || other === null)
617
+ return ranked;
618
+ const out = { ...ranked };
619
+ const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
620
+ const ownEnv = copy !== null && isTableValue(copy.env) ? copy.env : {};
621
+ if (isTableValue(ranked.env) || isTableValue(other.env)) {
622
+ const ea = isTableValue(ranked.env) ? ranked.env : {}, eb = isTableValue(other.env) ? other.env : {};
623
+ const env = { ...eb, ...ea };
624
+ for (const k of Object.keys(eb))
625
+ if (Object.prototype.hasOwnProperty.call(ea, k) && !same(ea[k], eb[k]) && same(ea[k], ownEnv[k]))
626
+ env[k] = eb[k];
627
+ out.env = env;
628
+ }
629
+ const union = (x, y) => {
630
+ const seen = new Set();
631
+ const res = [];
632
+ for (const v of [...asArray(x), ...asArray(y)]) {
633
+ const j = JSON.stringify(v);
634
+ if (!seen.has(j)) {
635
+ seen.add(j);
636
+ res.push(v);
637
+ }
638
+ }
639
+ return res;
640
+ };
641
+ if (Array.isArray(ranked.env_vars) || Array.isArray(other.env_vars))
642
+ out.env_vars = union(ranked.env_vars, other.env_vars);
643
+ if (Array.isArray(ranked.disabled_tools) || Array.isArray(other.disabled_tools))
644
+ out.disabled_tools = union(ranked.disabled_tools, other.disabled_tools);
645
+ // Round 15: the list that takes more gate tools away — an intersection produced `[]`, which neither spelling set.
646
+ const gone = (l) => (Array.isArray(l) ? (hollowedGateTools({ enabled_tools: l })?.split(', ').length ?? 0) : 0);
647
+ if (Array.isArray(other.enabled_tools) && gone(other.enabled_tools) > gone(ranked.enabled_tools))
648
+ out.enabled_tools = other.enabled_tools;
649
+ const ownCwd = copy?.cwd;
650
+ if (same(ranked.cwd, ownCwd) && !same(other.cwd, ownCwd))
651
+ out.cwd = other.cwd;
652
+ // Round 15: `environment_id` per aspect (measured: a real-path layer's `devbox` read PASS from the link).
653
+ if (other.environment_id !== undefined && same(ranked.environment_id, copy?.environment_id) && !same(other.environment_id, copy?.environment_id))
654
+ out.environment_id = other.environment_id;
655
+ return out;
656
+ }
657
+ function strictestOf(a, b, copyTable) {
658
+ // Round 12: `env`, `cwd` and the tool lists are part of the entry Codex runs.
659
+ const shape = (t) => (t === null ? null : JSON.stringify({ command: t.command ?? null, args: Array.isArray(t.args) ? t.args : [], env: t.env ?? null, cwd: t.cwd ?? null, disabled_tools: t.disabled_tools ?? null, enabled_tools: t.enabled_tools ?? null }));
660
+ // @implements A-SPEC-738 (round 15) — a replaced command/args outranks an env, cwd or tool-list difference
661
+ // (since round 12 both ranked 1 and the tie hid the real path's replacement — measured); of two different
662
+ // launches at the same rank, the one that is not a canonical shape is kept.
663
+ const launch = exports.launchKey;
664
+ const rank = (t) => {
665
+ if (t === null)
666
+ return 4;
667
+ if (t.enabled === false || (Array.isArray(t.enabled_tools) && t.enabled_tools.length === 0))
668
+ return 3;
669
+ if (copyTable !== null && launch(t) !== launch(copyTable))
670
+ return 2;
671
+ if (copyTable !== null && shape(t) !== shape(copyTable))
672
+ return 1;
673
+ return 0;
674
+ };
675
+ const ra = rank(a.holmesTable), rb = rank(b.holmesTable);
676
+ const bWins = rb > ra || (rb === ra && a.holmesTable !== null && b.holmesTable !== null && launch(a.holmesTable) !== launch(b.holmesTable)
677
+ && canonicalHolmesLaunch(a.holmesTable) && !canonicalHolmesLaunch(b.holmesTable));
678
+ const table = mergedTable(bWins ? b.holmesTable : a.holmesTable, bWins ? a.holmesTable : b.holmesTable, copyTable);
679
+ const hooks = listsHolmesHook(a) && !listsHolmesHook(b) ? b.hooks : a.hooks;
680
+ const hookErrors = b.hookErrors.length > a.hookErrors.length ? b.hookErrors : a.hookErrors;
681
+ const other = [...new Set([...(a.otherHookProblems ?? []), ...(b.otherHookProblems ?? [])])];
682
+ const otherConfigError = a.otherConfigError ?? b.otherConfigError;
683
+ // Round 13: every other Holmes server either spelling runs.
684
+ const servers = [...(a.otherHolmesServers ?? [])];
685
+ for (const s of b.otherHolmesServers ?? [])
686
+ if (!servers.some((x) => x.name === s.name && JSON.stringify(x.table) === JSON.stringify(s.table)))
687
+ servers.push(s);
688
+ return {
689
+ available: true,
690
+ configError: a.configError ?? b.configError,
691
+ holmesTable: table,
692
+ hookErrors,
693
+ hooks,
694
+ ...(other.length > 0 ? { otherHookProblems: other } : {}),
695
+ ...(otherConfigError !== undefined ? { otherConfigError } : {}),
696
+ ...(servers.length > 0 ? { otherHolmesServers: servers } : {}),
697
+ };
698
+ }
699
+ function otelDecline(copy) {
700
+ if (!isTableValue(copy.otel))
701
+ return null;
702
+ for (const k of ['exporter', 'trace_exporter', 'metrics_exporter']) {
703
+ const e = copy.otel[k];
704
+ if (isTableValue(e) && overridableExporter(e) === null)
705
+ return `otel.${k}`;
706
+ }
707
+ return null;
708
+ }
709
+ /**
710
+ * @implements A-SPEC-738 (round 10) — whether `file` is the user's own config (by real path), which is
711
+ * not a workspace layer: every workspace under `$HOME` otherwise counted `~/.codex/config.toml` as one
712
+ * and doubled the spawns on a refusal (measured 237 ms vs 145 ms).
713
+ */
714
+ const isUserFile = (file, userFile) => {
715
+ if (userFile === null)
716
+ return false;
717
+ try {
718
+ return fs.realpathSync.native(file) === userFile;
719
+ }
720
+ catch {
721
+ return false;
722
+ }
723
+ };
724
+ /** Whether a `.codex/config.toml` exists in `cwd` or an ancestor — a layer Codex may read besides the user file. */
725
+ function layerFileAbove(cwd, userFile = null) {
726
+ let dir = path.resolve(cwd);
727
+ for (let depth = 0; depth < 4096; depth++) {
728
+ const f = path.join(dir, '.codex', 'config.toml');
729
+ try {
730
+ if (fs.statSync(f).isFile() && !isUserFile(f, userFile))
731
+ return true;
732
+ }
733
+ catch { /* none here */ }
734
+ const parent = path.dirname(dir);
735
+ if (parent === dir)
736
+ return false;
737
+ dir = parent;
738
+ }
739
+ return false;
740
+ }
741
+ /**
742
+ * @implements A-SPEC-738 (round 6) — the layer file a refusal names (a path ending in `.codex/config.toml`,
743
+ * spaces included), or null when it names none: doctor's fix line points at it, not at the user file.
744
+ */
745
+ function layerFileNamed(message) {
746
+ const m = /((?:\/|[A-Za-z]:[\\/])[^\n]*?[\\/]\.codex[\\/]config\.toml)(?=:|\s|$)/.exec(message);
747
+ // Round 7: only a file that exists — a contrived message ran the first absolute path into a later
748
+ // `.codex/config.toml` and named a nonexistent file (measured).
749
+ return m && fs.existsSync(m[1]) ? m[1] : null;
750
+ }
751
+ /** A PreToolUse command Codex lists that runs the Holmes pre-tool kernel (any quoting). */
752
+ function isHolmesPreToolCommand(command) {
753
+ return typeof command === 'string' && /[\\/]dist[\\/]holmes[\\/]hooks[\\/]pre-tool-use\.js\b/.test(command);
754
+ }
755
+ /**
756
+ * @implements A-SPEC-738 (round 2, shared in round 5) — whether the user config's `[hooks.state]` disables
757
+ * the Holmes PreToolUse hook of `hooksText`. The state is keyed by the REAL hooks path, so a copy cannot
758
+ * show it (measured); init and doctor both read it here (round 5: init said "wired" while doctor FAILed).
759
+ * Only the Holmes group's own `pre_tool_use:<i>:<j>` counts; case-insensitive on Windows.
760
+ */
761
+ function holmesPreToolDisabled(configText, hooksText, hooksPath) {
762
+ if (configText === null)
763
+ return false;
764
+ const parsed = (0, codex_toml_1.parseCodexConfig)(configText);
765
+ if (!parsed.ok)
766
+ return false;
767
+ const st = parsed.doc.hooks?.state;
768
+ if (!st || typeof st !== 'object')
769
+ return false;
770
+ // Round 7: Codex canonicalises CODEX_HOME (links, case on a folding disk) before keying — compare the
771
+ // path as given, its JS real path and its native real path (on-disk case).
772
+ const real = (() => { try {
773
+ return fs.realpathSync(hooksPath);
774
+ }
775
+ catch {
776
+ return hooksPath;
777
+ } })();
778
+ const realNative = (() => { try {
779
+ return fs.realpathSync.native(hooksPath);
780
+ }
781
+ catch {
782
+ return hooksPath;
783
+ } })();
784
+ const indices = [];
785
+ try {
786
+ const groups = JSON.parse(hooksText ?? '{}').hooks?.PreToolUse ?? [];
787
+ groups.forEach((g, i) => (g?.hooks ?? []).forEach((h, j) => { if (isHolmesPreToolCommand(typeof h?.command === 'string' ? h.command : undefined))
788
+ indices.push(`${i}:${j}`); }));
789
+ }
790
+ catch {
791
+ return false;
792
+ }
793
+ const norm = (k) => (process.platform === 'win32' ? k.toLowerCase() : k);
794
+ const wanted = new Set(indices.flatMap((ix) => [`${hooksPath}:pre_tool_use:${ix}`, `${real}:pre_tool_use:${ix}`, `${realNative}:pre_tool_use:${ix}`]).map(norm));
795
+ return Object.entries(st).some(([k, v]) => wanted.has(norm(k)) && typeof v === 'object' && v !== null && v.enabled === false);
796
+ }
797
+ /** The layers Codex reads besides the user file: `.codex/config.toml` from `cwd` up to the root. */
798
+ function projectLayers(cwd, userFile = null) {
799
+ const docs = [];
800
+ let bad = null;
801
+ let dir = path.resolve(cwd);
802
+ // Round 6: to the filesystem root — a layer more than 63 directories up was invisible (measured).
803
+ for (let depth = 0; depth < 4096; depth++) {
804
+ const f = path.join(dir, '.codex', 'config.toml');
805
+ let st = null;
806
+ try {
807
+ st = fs.statSync(f);
808
+ }
809
+ catch {
810
+ st = null;
811
+ }
812
+ if (st !== null && st.isFile() && !isUserFile(f, userFile)) {
813
+ // @implements A-SPEC-738 (round 11) — a layer that exists but cannot be read, parsed or is over 1 MiB
814
+ // is UNJUDGEABLE, not absent (measured: a 1 MiB + 100 byte trusted layer holding `sqlite_home = 5`
815
+ // read as loads while Codex refused).
816
+ const key = (() => { try {
817
+ return fs.realpathSync.native(f);
818
+ }
819
+ catch {
820
+ return f;
821
+ } })();
822
+ if (st.size > 1024 * 1024) {
823
+ bad ??= f;
824
+ }
825
+ else {
826
+ try {
827
+ const p = (0, codex_toml_1.parseCodexConfig)(fs.readFileSync(f, 'utf8'));
828
+ if (p.ok)
829
+ docs.push({ file: key, doc: p.doc });
830
+ else
831
+ bad ??= f;
832
+ }
833
+ catch {
834
+ bad ??= f;
835
+ }
836
+ }
837
+ }
838
+ const parent = path.dirname(dir);
839
+ if (parent === dir)
840
+ break;
841
+ dir = parent;
842
+ }
843
+ return { docs, bad };
844
+ }
845
+ /** The only caller variables the oracle's codex sees (plus its own CODEX_HOME/HOME/proxies). */
846
+ const ENV_ALLOWLIST = ['PATH', 'Path', 'PATHEXT', 'SystemRoot', 'SYSTEMROOT', 'WINDIR', 'windir', 'COMSPEC', 'ComSpec', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL'];
847
+ /** Per user (a shared /tmp let another user pre-create the root — review, round 3). */
848
+ const ORACLE_ROOT = () => {
849
+ const who = typeof process.getuid === 'function' ? String(process.getuid()) : (() => { try {
850
+ return os.userInfo().username.replace(/[^\w.-]/g, '_');
851
+ }
852
+ catch {
853
+ return 'user';
854
+ } })();
855
+ return path.join(os.tmpdir(), `holmes-codex-oracle-${who}`);
856
+ };
857
+ /** The root must be this user's own directory, not a link (else another user could swap homes). */
858
+ function ownRoot() {
859
+ const base = ORACLE_ROOT();
860
+ fs.mkdirSync(base, { recursive: true, mode: 0o700 });
861
+ const st = fs.lstatSync(base);
862
+ if (!st.isDirectory() || st.isSymbolicLink())
863
+ throw new Error(`${base} is not a directory`);
864
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid())
865
+ throw new Error(`${base} belongs to another user`);
866
+ return base;
867
+ }
868
+ const CLOSED_PROXY = 'http://127.0.0.1:9';
869
+ /** Written into every temporary home the oracle makes; the sweep removes nothing without it (round 9). */
870
+ const ORACLE_MARKER = '.holmes-codex-oracle';
871
+ /** The first `codex` on PATH (PATHEXT on Windows), unless the oracle is switched off. */
872
+ function findCodex(env, platform) {
873
+ // Round 3: sweep interrupted runs' homes on every lookup, even with the oracle off.
874
+ // Only a root that is this user's own directory and not a link (a linked root let the sweep delete
875
+ // `<n>-*` entries elsewhere — measured).
876
+ try {
877
+ const root = ORACLE_ROOT();
878
+ const st = fs.lstatSync(root);
879
+ if (st.isDirectory() && !st.isSymbolicLink() && (typeof process.getuid !== 'function' || st.uid === process.getuid()))
880
+ sweepStaleHomes(root);
881
+ }
882
+ catch { /* nothing to sweep */ }
883
+ if ((env.HOLMES_CODEX_ORACLE ?? '').trim().toLowerCase() === 'off') {
884
+ return { found: false, reason: 'the Codex oracle is switched off (HOLMES_CODEX_ORACLE=off)' };
885
+ }
886
+ const win = platform === 'win32';
887
+ const dirs = (env.PATH ?? env.Path ?? '').split(win ? ';' : ':').filter((d) => d !== '');
888
+ const exts = win ? ['.exe', ...(env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').map((e) => e.toLowerCase()).filter((e) => e !== '.exe' && e !== '')] : [''];
889
+ for (const dir of dirs) {
890
+ // A relative entry resolved against the caller's cwd but ran against the target's (measured).
891
+ if (!path.isAbsolute(dir) && !(win && path.win32.isAbsolute(dir)))
892
+ continue;
893
+ for (const ext of exts) {
894
+ const candidate = path.join(dir, `codex${ext}`);
895
+ try {
896
+ const st = fs.statSync(candidate);
897
+ if (!st.isFile())
898
+ continue;
899
+ if (!win)
900
+ fs.accessSync(candidate, fs.constants.X_OK);
901
+ const shim = win && (ext === '.cmd' || ext === '.bat');
902
+ return { found: true, codex: { command: shim ? `"${candidate}"` : candidate, args: [], ...(shim ? { shell: true } : {}) } };
903
+ }
904
+ catch { /* not here */ }
905
+ }
906
+ }
907
+ return { found: false, reason: 'codex not found on PATH' };
908
+ }
909
+ /**
910
+ * The worker holds the conversation: the app-server exits WITHOUT answering when its stdin closes
911
+ * (measured), so a synchronous caller cannot drive it directly. Plain JavaScript, run with `node -e`.
912
+ */
913
+ const WORKER = [
914
+ "const { spawn } = require('child_process');",
915
+ 'const p = JSON.parse(process.argv[1]);',
916
+ "const env = Object.assign({}, process.env, p.extraEnv || {}, { CODEX_HOME: p.home, HOME: p.home, USERPROFILE: p.home, NO_PROXY: '', no_proxy: '' });",
917
+ "for (const k of ['HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'https_proxy', 'http_proxy', 'all_proxy']) env[k] = p.proxy;",
918
+ 'let done = false;',
919
+ 'const answers = {};',
920
+ "const win = process.platform === 'win32';",
921
+ "const child = spawn(p.command, p.args, { env, cwd: p.cwd, stdio: ['pipe', 'pipe', 'ignore'], shell: !!p.shell, windowsHide: true, detached: !win });",
922
+ // The whole group, hard: killing only a wrapper let the native server exit gracefully and flush
923
+ // telemetry (measured egress) — and linger as an orphan.
924
+ "const killAll = () => { try { if (win) require('child_process').spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }); else process.kill(-child.pid, 'SIGKILL'); } catch (e) { try { child.kill('SIGKILL'); } catch (e2) {} } };",
925
+ // Round 5 (measured): exiting straight after the write cut the answer at 64 KiB on macOS pipes.
926
+ "const finish = (out) => { if (done) return; done = true; killAll(); process.stdout.write(JSON.stringify(out) + '\\n', () => process.exit(0)); };",
927
+ // Round 4 (measured): Ctrl-C reached this worker but not codex in its own session; the orphan then
928
+ // exited gracefully and flushed the user's telemetry exporter. The group dies first, hard.
929
+ "for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => { killAll(); process.exit(1); });",
930
+ "const timer = setTimeout(() => finish({ ok: false, reason: 'codex app-server did not answer within ' + p.timeoutMs + ' ms (timeout)' }), p.timeoutMs);",
931
+ "child.on('error', (e) => finish({ ok: false, reason: 'codex could not be started: ' + e.message }));",
932
+ "child.on('exit', (code) => setTimeout(() => finish({ ok: false, reason: 'codex app-server exited (' + code + ') before answering' }), 100));",
933
+ "child.stdin.on('error', () => {});",
934
+ "const send = (m) => { try { child.stdin.write(JSON.stringify(m) + '\\n'); } catch (e) {} };",
935
+ "let buf = '';",
936
+ // Round 9 (measured): a multibyte character split across pipe chunks came back as U+FFFD.
937
+ "const dec = new (require('string_decoder').StringDecoder)('utf8');",
938
+ // Round 9: a signal to the PARENT alone left this worker and codex until the timeout — watch the parent.
939
+ "const ppid = process.ppid; setInterval(() => { let gone = process.ppid !== ppid; if (!gone) { try { process.kill(ppid, 0); } catch (e) { gone = true; } } if (gone) { killAll(); process.exit(1); } }, 500).unref();",
940
+ "child.stdout.on('data', (d) => {",
941
+ ' buf += dec.write(d);',
942
+ ' let i;',
943
+ " while ((i = buf.indexOf('\\n')) !== -1) {",
944
+ ' const line = buf.slice(0, i); buf = buf.slice(i + 1);',
945
+ ' let m; try { m = JSON.parse(line); } catch (e) { continue; }',
946
+ " if (m.id === 1) {",
947
+ " if (m.error) { finish({ ok: false, reason: 'codex refused initialize: ' + (m.error.message || '') }); return; }",
948
+ " send({ method: 'initialized' }); send({ id: 2, method: 'config/read', params: { cwd: p.cwd } }); send({ id: 3, method: 'hooks/list', params: { cwds: [p.cwd] } });",
949
+ ' } else if (m.id === 2 || m.id === 3) {',
950
+ // Round 10 (measured): a 25 MB hooks file's answer overflowed the parent's 64 MiB pipe buffer (ENOBUFS →
951
+ // approximate). Only what the verdict reads travels: per entry cwd/errors/warnings, per hook four fields.
952
+ " if (m.id === 3 && m.result && Array.isArray(m.result.data)) m.result = { data: m.result.data.map((e) => (e && typeof e === 'object') ? { cwd: e.cwd, errors: e.errors, warnings: e.warnings, hooks: Array.isArray(e.hooks) ? e.hooks.map((h) => (h && typeof h === 'object') ? { eventName: h.eventName, command: h.command, matcher: h.matcher, enabled: h.enabled } : h) : e.hooks } : e) };",
953
+ ' answers[m.id] = m;',
954
+ ' if (answers[2] && answers[3]) { clearTimeout(timer); finish({ ok: true, config: answers[2], hooks: answers[3] }); }',
955
+ ' }',
956
+ ' }',
957
+ '});',
958
+ "send({ id: 1, method: 'initialize', params: { clientInfo: { name: 'holmes-kit', version: 'oracle' } } });",
959
+ ].join('\n');
960
+ /** The worker source, for tests that drive it directly (A-SPEC-738 round 4: its signal handling). */
961
+ exports.ORACLE_WORKER_SOURCE = WORKER;
962
+ /** Ask the installed Codex whether these files load. Synchronous; never throws. */
963
+ function askCodex(input) {
964
+ const timeoutMs = input.timeoutMs ?? 15_000;
965
+ let home = null;
966
+ try {
967
+ const base = ownRoot();
968
+ sweepStaleHomes(base);
969
+ home = fs.mkdtempSync(path.join(base, `${process.pid}-`));
970
+ fs.chmodSync(home, 0o700);
971
+ // Round 9: the sweep removes only homes carrying this marker (a workspace placed under the root by
972
+ // its name pattern was deleted before codex started — measured).
973
+ fs.writeFileSync(path.join(home, ORACLE_MARKER), '', { mode: 0o600 });
974
+ if (input.configBytes !== null)
975
+ fs.writeFileSync(path.join(home, 'config.toml'), input.configBytes, { mode: 0o600 });
976
+ if (input.hooksBytes !== null)
977
+ fs.writeFileSync(path.join(home, 'hooks.json'), input.hooksBytes, { mode: 0o600 });
978
+ // @implements A-SPEC-738 (round 12) — the copy is capped like a layer (smol-toml is superlinear:
979
+ // 80,000 tables 1.7 s), and a copy the oracle's own parser cannot read runs with EVERY override; if
980
+ // Codex then loads it, the oracle declines below (an override may have masked a refusal — measured
981
+ // with the leap-second residual: `[analytics] enabled = "yes"` beside `23:59:60` read as "loads").
982
+ if (input.configBytes !== null && input.configBytes.length > 1024 * 1024)
983
+ return { available: false, reason: `config.toml is ${(input.configBytes.length / 1048576).toFixed(1)} MiB, over the 1 MiB the oracle reads` };
984
+ let copyUnreadable = false;
985
+ const copyLayer = input.configBytes === null ? {} : (() => { const p = (0, codex_toml_1.parseCodexConfig)(input.configBytes.toString('utf8')); if (p.ok)
986
+ return p.doc; copyUnreadable = true; return {}; })();
987
+ const declined = otelDecline(copyLayer);
988
+ if (declined !== null)
989
+ return { available: false, reason: `the configuration keeps an [otel] exporter the oracle cannot neutralize: ${declined}` };
990
+ // Round 10: the user file itself is not a workspace layer.
991
+ const userFile = (() => { try {
992
+ return input.realConfigPath ? fs.realpathSync.native(input.realConfigPath) : null;
993
+ }
994
+ catch {
995
+ return null;
996
+ } })();
997
+ // @implements A-SPEC-738 (round 7) — the target by its REAL path: a workspace reached through a link
998
+ // whose real git root carries a refusing layer answered "loads" while a session there runs on defaults.
999
+ // Round 8: asked as GIVEN and, when it differs, by the real path — Codex honours a project trust keyed by
1000
+ // either spelling, and the real-path-only ask dropped one keyed by the link (measured PASS while Codex
1001
+ // refused). The stricter answer wins.
1002
+ const realCwd = (() => { try {
1003
+ return fs.realpathSync.native(input.cwd);
1004
+ }
1005
+ catch {
1006
+ return input.cwd;
1007
+ } })();
1008
+ const cwd = input.cwd;
1009
+ // @implements A-SPEC-738 (round 11) — layers of BOTH spellings (Codex honours a trust keyed by either;
1010
+ // measured: a trusted layer above the link spelling was invisible and the override masked its refusal).
1011
+ const walked = [projectLayers(cwd, userFile), ...(realCwd !== cwd ? [projectLayers(realCwd, userFile)] : [])];
1012
+ const bad = walked.find((w) => w.bad !== null)?.bad ?? null;
1013
+ if (bad !== null)
1014
+ return { available: false, reason: `a workspace layer (${bad}) the oracle cannot read — over 1 MiB, unreadable or not TOML — may carry values the isolation overrides would mask` };
1015
+ const seenLayers = new Set();
1016
+ const others = [];
1017
+ for (const w of walked)
1018
+ for (const l of w.docs) {
1019
+ if (seenLayers.has(l.file))
1020
+ continue;
1021
+ seenLayers.add(l.file);
1022
+ others.push(l.doc);
1023
+ }
1024
+ const layerDeclined = layerDecline(copyLayer, others);
1025
+ if (layerDeclined !== null)
1026
+ return { available: false, reason: `a workspace .codex/config.toml sets ${layerDeclined} the oracle cannot judge from a copy (whether Codex reads that layer is a trust the copy cannot show)` };
1027
+ const overrides = isolationOverrides(home, [copyLayer, ...others]);
1028
+ const env = {};
1029
+ for (const k of ENV_ALLOWLIST)
1030
+ if (process.env[k] !== undefined)
1031
+ env[k] = process.env[k];
1032
+ const homeDir = home;
1033
+ const runOnce = (cwd) => {
1034
+ const payload = JSON.stringify({ command: input.codex.command, args: [...input.codex.args, ...APP_SERVER_ARGS, ...overrides], shell: input.codex.shell === true,
1035
+ home: homeDir, cwd, timeoutMs, proxy: CLOSED_PROXY, extraEnv: input.codex.env ?? {} });
1036
+ const r = (0, node_child_process_1.spawnSync)(process.execPath, ['-e', WORKER, payload], { encoding: 'utf8', timeout: timeoutMs + 5_000, windowsHide: true, maxBuffer: 64 * 1024 * 1024, env });
1037
+ if (r.error)
1038
+ return { ok: false, reason: `the Codex oracle worker failed: ${r.error.message}` };
1039
+ const last = (r.stdout ?? '').trim().split('\n').pop() ?? '';
1040
+ let out;
1041
+ try {
1042
+ out = JSON.parse(last);
1043
+ }
1044
+ catch {
1045
+ return { ok: false, reason: 'the Codex oracle worker gave no answer' };
1046
+ }
1047
+ if (out.ok !== true)
1048
+ return { ok: false, reason: typeof out.reason === 'string' ? out.reason : 'codex gave no answer' };
1049
+ return { ok: true, config: out.config ?? {}, hooks: out.hooks ?? {} };
1050
+ };
1051
+ const first = runOnce(cwd);
1052
+ if (!first.ok)
1053
+ return { available: false, reason: first.reason };
1054
+ let verdict = verdictOf(first.config, first.hooks, homeDir, input);
1055
+ // Round 13: on EVERY answer whose configError is null — the real-path ask and the neutral re-ask
1056
+ // included (measured: the neutral ask's override masked the user file's own refusal).
1057
+ const guard = (v) => (copyUnreadable && v.available && v.configError === null
1058
+ ? { available: false, reason: 'the oracle could not read the user copy that Codex loaded, so an isolation override may have masked a refusal' } : v);
1059
+ if (guard(verdict) !== verdict)
1060
+ return guard(verdict);
1061
+ let chosen = first;
1062
+ if (realCwd !== cwd && verdict.available && verdict.configError === null && verdict.otherConfigError === undefined) {
1063
+ const again = runOnce(realCwd);
1064
+ if (!again.ok)
1065
+ return { available: false, reason: again.reason };
1066
+ const v2 = verdictOf(again.config, again.hooks, homeDir, input);
1067
+ if (!v2.available)
1068
+ return v2;
1069
+ // @implements A-SPEC-738 (round 11) — the stricter answer PER ASPECT, never the whole verdict: a
1070
+ // whole swap hid the spelled session's disabled table, and a REPLACED table (a trusted real root's
1071
+ // `command = "/old/node"` answered `npx` for the link spelling) was not stricter (measured).
1072
+ if (v2.configError !== null && verdict.configError === null)
1073
+ chosen = again;
1074
+ const copyTable = (copyLayer.mcp_servers?.['holmes-kit'] ?? null);
1075
+ verdict = strictestOf(verdict, v2, copyTable);
1076
+ }
1077
+ // @implements A-SPEC-738 (round 4) — a layer's refusal hid the user file's own (measured): judge the
1078
+ // user file alone, from a cwd with no project layer (the temporary home).
1079
+ // @implements A-SPEC-738 (round 5) — a refusal need not name its file (measured: a trusted layer's
1080
+ // `experimental_thread_store_endpoint`, or a path with a space). Wherever a layer file exists, the
1081
+ // user file is asked about alone; no answer there is no verdict, never a guess that blames it.
1082
+ if (verdict.available && verdict.configError !== null && verdict.otherConfigError === undefined && chosen.config.error !== undefined && (layerFileAbove(cwd, userFile) || layerFileAbove(realCwd, userFile))) {
1083
+ const alone = runOnce(homeDir);
1084
+ if (!alone.ok)
1085
+ return { available: false, reason: `Codex refuses the configuration, and asking about the user file alone gave no answer (${alone.reason})` };
1086
+ const v2 = verdictOf(alone.config, alone.hooks, homeDir, input);
1087
+ if (!v2.available)
1088
+ return v2;
1089
+ // Round 9: when the user file refuses too, the first (layer-borne) message is kept beside it.
1090
+ return guard(v2.configError === null
1091
+ ? { ...verdict, configError: null, otherConfigError: verdict.configError }
1092
+ : { ...verdict, configError: v2.configError, ...(verdict.configError !== v2.configError ? { otherConfigError: verdict.configError } : {}) });
1093
+ }
1094
+ if (verdict.available && verdict.otherConfigError !== undefined && verdict.configError === null) {
1095
+ const alone = runOnce(homeDir);
1096
+ if (alone.ok) {
1097
+ const v2 = verdictOf(alone.config, alone.hooks, homeDir, input);
1098
+ if (v2.available && v2.configError !== null)
1099
+ return { ...verdict, configError: v2.configError };
1100
+ }
1101
+ }
1102
+ return guard(verdict);
1103
+ }
1104
+ catch (e) {
1105
+ return { available: false, reason: `the Codex oracle could not run: ${e.message}` };
1106
+ }
1107
+ finally {
1108
+ if (home !== null) {
1109
+ try {
1110
+ fs.rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
1111
+ }
1112
+ catch { /* best effort */ }
1113
+ }
1114
+ }
1115
+ }
1116
+ /** Remove temporary homes whose creating process is gone (an interrupted run skips its finally). */
1117
+ function sweepStaleHomes(base) {
1118
+ let names;
1119
+ try {
1120
+ names = fs.readdirSync(base);
1121
+ }
1122
+ catch {
1123
+ return;
1124
+ }
1125
+ for (const name of names) {
1126
+ const pid = Number(/^(\d+)-/.exec(name)?.[1]);
1127
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid)
1128
+ continue;
1129
+ let alive = true;
1130
+ try {
1131
+ process.kill(pid, 0);
1132
+ }
1133
+ catch (e) {
1134
+ alive = e.code === 'EPERM';
1135
+ }
1136
+ if (!alive && fs.existsSync(path.join(base, name, ORACLE_MARKER))) {
1137
+ try {
1138
+ fs.rmSync(path.join(base, name), { recursive: true, force: true });
1139
+ }
1140
+ catch { /* next time */ }
1141
+ }
1142
+ }
1143
+ }
1144
+ function verdictOf(config, hooks, home, input) {
1145
+ // Protocol errors are not verdicts (measured: an unknown method answers -32600 "Invalid request").
1146
+ if (hooks.error)
1147
+ return { available: false, reason: `codex answered hooks/list with an error: ${String(hooks.error.message ?? '')}` };
1148
+ // Longest spelling first: `/private/var/…` must be replaced before `/var/…` (review, round 3).
1149
+ const homes = [home, ...(() => { try {
1150
+ const r = fs.realpathSync(home);
1151
+ return r === home ? [] : [r];
1152
+ }
1153
+ catch {
1154
+ return [];
1155
+ } })()].sort((a, b) => b.length - a.length);
1156
+ const sep = (h) => [h + path.sep, h + '/'];
1157
+ const own = (m) => homes.some((h) => m.includes(h));
1158
+ const esc = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1159
+ // A file NEXT TO the copies (not config.toml/hooks.json themselves) that Codex could not read.
1160
+ // Round 4: a missing file whose message names no absolute path outside the copy (a relative
1161
+ // `model_catalog_json` — measured) is also the copy's blindness, not the user's error.
1162
+ const absOutside = (m) => (m.match(/(?:^|[\s'"(])((?:\/|[A-Za-z]:[\\/])[^\s:'"]+)/g) ?? []).some((a) => !homes.some((h) => a.includes(h)));
1163
+ const unseen = (m) => (/no such file|not found|failed to read/i.test(m)
1164
+ && homes.some((h) => new RegExp(esc(h) + String.raw `[\/](?!config\.toml\b|hooks\.json\b)[^\s:'"]+`).test(m)))
1165
+ || (/no such file or directory|os error 2\b/i.test(m) && !absOutside(m));
1166
+ const namesCopy = (m) => homes.some((h) => new RegExp(esc(h) + String.raw `[\/](?:config\.toml|hooks\.json)\b`).test(m));
1167
+ const toUser = (m) => {
1168
+ let out = m;
1169
+ for (const h of homes)
1170
+ for (const pre of sep(h)) {
1171
+ if (input.realConfigPath)
1172
+ out = out.split(pre + 'config.toml').join(input.realConfigPath);
1173
+ if (input.realHooksPath)
1174
+ out = out.split(pre + 'hooks.json').join(input.realHooksPath);
1175
+ }
1176
+ return out;
1177
+ };
1178
+ const entry = ((hooks.result?.data ?? [])[0] ?? {});
1179
+ // A hooks file Codex drops whole is reported only as a WARNING (measured: an mcp_tool `input` that
1180
+ // is a string — `errors` stayed empty and no hook was listed).
1181
+ const problems = [
1182
+ ...(entry.errors ?? []).map((e) => String(e?.message ?? '')),
1183
+ ...(entry.warnings ?? []).map((w) => String(w ?? '')).filter((w) => /^failed to parse hooks config/i.test(w)),
1184
+ ].filter((m) => m !== '');
1185
+ // @implements A-SPEC-738 (round 3) — refusals by CODE: every measured refusal is -32603 whatever its
1186
+ // message ("failed to resolve feature override precedence: …", "failed to read configuration
1187
+ // layers: …"); a protocol error is -32600. And by LAYER: hooks/list names the file that refused.
1188
+ // Round 4: another layer only when a message NAMES one — an absolute `…/.codex/config.toml` outside the
1189
+ // copy. The legacy `profile = "…"` refusal merely contains the text `config.toml` (measured).
1190
+ const LAYER_PATH = /(?:^|[\s'"(])(?:\/|[A-Za-z]:[\\/])[^\s'"]*[\\/]\.codex[\\/]config\.toml/;
1191
+ const otherLayer = problems.find((m) => !own(m) && LAYER_PATH.test(m));
1192
+ let configError = null;
1193
+ let otherConfigError;
1194
+ if (config.error) {
1195
+ const message = String(config.error.message ?? '');
1196
+ const code = config.error.code;
1197
+ if (code !== -32603 && !namesCopy(message))
1198
+ return { available: false, reason: `codex answered config/read with an error: ${message}` };
1199
+ if (otherLayer !== undefined && !namesCopy(message) && !problems.some((m) => namesCopy(m)))
1200
+ otherConfigError = otherLayer;
1201
+ else
1202
+ configError = message;
1203
+ }
1204
+ else {
1205
+ configError = problems.find((m) => own(m) && /config\.toml/i.test(m)) ?? null;
1206
+ if (configError === null && otherLayer !== undefined)
1207
+ otherConfigError = otherLayer;
1208
+ }
1209
+ // A configuration that reads files next to it cannot be judged from a copy (measured false refusal).
1210
+ if ((configError !== null && unseen(configError)) || problems.some(unseen)) {
1211
+ return { available: false, reason: 'the configuration reads files next to it, which a copy cannot see' };
1212
+ }
1213
+ const servers = (config.result?.config?.mcp_servers) ?? {};
1214
+ const table = Object.prototype.hasOwnProperty.call(servers, 'holmes-kit') ? servers['holmes-kit'] : null;
1215
+ // Round 13: another entry that runs a Holmes server is a second gate with its own environment.
1216
+ // @implements A-SPEC-738 (round 14/15) — recognised by the Holmes shape (lexically — round 15), and EVERY other enabled entry handed a HOLMES_* authority
1217
+ // key whatever its command (a shell or env wrapper, a link, a script path held elsewhere cannot hide it).
1218
+ // An entry with `enabled = false` is not started by Codex.
1219
+ const otherHolmesServers = [];
1220
+ for (const [name, t] of Object.entries(servers)) {
1221
+ if (name === 'holmes-kit' || !isTableValue(t) || t.enabled === false)
1222
+ continue;
1223
+ const holmes = runsHolmesServer(t);
1224
+ if (holmes || serverAuthority(t, false).length > 0)
1225
+ otherHolmesServers.push({ name, table: t, holmes });
1226
+ }
1227
+ const ownProblems = problems.filter(own);
1228
+ const otherProblems = problems.filter((m) => !own(m) && m !== otherConfigError && !(configError ?? '').includes(m));
1229
+ return {
1230
+ available: true,
1231
+ configError: configError === null ? null : toUser(configError),
1232
+ holmesTable: table !== null && typeof table === 'object' ? table : null,
1233
+ hookErrors: ownProblems.map(toUser),
1234
+ // Round 11: a hook entry that is not an object is skipped (a `null` threw and made the verdict approximate).
1235
+ hooks: (entry.hooks ?? []).filter((h) => !!h && typeof h === 'object' && !Array.isArray(h)).map((h) => ({
1236
+ event: String(h.eventName ?? ''),
1237
+ ...(typeof h.command === 'string' ? { command: h.command } : {}),
1238
+ matcher: typeof h.matcher === 'string' ? h.matcher : null,
1239
+ enabled: h.enabled !== false,
1240
+ })),
1241
+ ...(otherProblems.length > 0 ? { otherHookProblems: otherProblems } : {}),
1242
+ ...(otherHolmesServers.length > 0 ? { otherHolmesServers } : {}),
1243
+ ...(otherConfigError !== undefined ? { otherConfigError } : {}),
1244
+ };
1245
+ }