@holmes-lab/holmes-kit 0.30.0 → 0.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +505 -0
  2. package/README.md +10 -1
  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.d.ts +41 -0
  9. package/dist/holmes/cli/agents.js +382 -2
  10. package/dist/holmes/cli/attest.d.ts +2 -0
  11. package/dist/holmes/cli/attest.js +66 -15
  12. package/dist/holmes/cli/ci-gate.js +16 -1
  13. package/dist/holmes/cli/claude-switches.d.ts +95 -0
  14. package/dist/holmes/cli/claude-switches.js +967 -0
  15. package/dist/holmes/cli/codex-hooks.d.ts +77 -0
  16. package/dist/holmes/cli/codex-hooks.js +802 -0
  17. package/dist/holmes/cli/codex-oracle.d.ts +194 -0
  18. package/dist/holmes/cli/codex-oracle.js +1245 -0
  19. package/dist/holmes/cli/codex-toml.d.ts +35 -0
  20. package/dist/holmes/cli/codex-toml.js +321 -52
  21. package/dist/holmes/cli/doctor.d.ts +98 -8
  22. package/dist/holmes/cli/doctor.js +1328 -94
  23. package/dist/holmes/cli/index.js +26 -11
  24. package/dist/holmes/cli/init.d.ts +11 -0
  25. package/dist/holmes/cli/init.js +736 -44
  26. package/dist/holmes/cli/mcp-launcher.d.ts +64 -6
  27. package/dist/holmes/cli/mcp-launcher.js +189 -6
  28. package/dist/holmes/cli/mcp-version.js +13 -2
  29. package/dist/holmes/cli/settings-merge.js +8 -2
  30. package/dist/holmes/cli/upgrade.d.ts +18 -0
  31. package/dist/holmes/cli/upgrade.js +129 -24
  32. package/dist/holmes/cli/workspace-scope.d.ts +22 -0
  33. package/dist/holmes/cli/workspace-scope.js +375 -0
  34. package/dist/holmes/cpg/cpg-scanner.d.ts +29 -0
  35. package/dist/holmes/cpg/cpg-scanner.js +403 -3
  36. package/dist/holmes/cpg/cycle-detect.js +2 -1
  37. package/dist/holmes/cpg/forbidden-edges.js +9 -2
  38. package/dist/holmes/cpg/required-calls.js +8 -1
  39. package/dist/holmes/governance/constitution-debt.js +3 -2
  40. package/dist/holmes/governance/constitution.js +15 -3
  41. package/dist/holmes/governance/provenance-chain.js +3 -2
  42. package/dist/holmes/governance/push-gate-runner.js +4 -3
  43. package/dist/holmes/guardrail/dependency-delta.js +4 -3
  44. package/dist/holmes/guardrail/linear-match.d.ts +57 -0
  45. package/dist/holmes/guardrail/linear-match.js +256 -0
  46. package/dist/holmes/guardrail/risk-classifier.d.ts +6 -7
  47. package/dist/holmes/guardrail/risk-classifier.js +931 -44
  48. package/dist/holmes/guardrail/risk-types.d.ts +6 -0
  49. package/dist/holmes/guardrail/scope-judgment.d.ts +4 -24
  50. package/dist/holmes/guardrail/scope-judgment.js +100 -23
  51. package/dist/holmes/guardrail/shell-words.d.ts +42 -0
  52. package/dist/holmes/guardrail/shell-words.js +1720 -0
  53. package/dist/holmes/guardrail/write-target.d.ts +168 -3
  54. package/dist/holmes/guardrail/write-target.js +2379 -87
  55. package/dist/holmes/hooks/adapters/antigravity.d.ts +3 -1
  56. package/dist/holmes/hooks/adapters/antigravity.js +115 -11
  57. package/dist/holmes/hooks/pre-tool-use.d.ts +32 -6
  58. package/dist/holmes/hooks/pre-tool-use.js +923 -87
  59. package/dist/holmes/hooks/rtm-refresh-child.js +3 -1
  60. package/dist/holmes/hooks/rtm-refresh.js +8 -4
  61. package/dist/holmes/hooks/session-start.d.ts +10 -0
  62. package/dist/holmes/hooks/session-start.js +31 -7
  63. package/dist/holmes/hooks/stop.d.ts +2 -1
  64. package/dist/holmes/hooks/stop.js +197 -91
  65. package/dist/holmes/mcp/approval-commit.d.ts +5 -6
  66. package/dist/holmes/mcp/approval-commit.js +18 -2
  67. package/dist/holmes/mcp/elicit-approval.js +4 -2
  68. package/dist/holmes/mcp/handlers/graph-operations.js +3 -2
  69. package/dist/holmes/mcp/handlers/maintenance-analysis.js +11 -5
  70. package/dist/holmes/mcp/handlers/maintenance-evidence.js +3 -2
  71. package/dist/holmes/mcp/handlers/phase-queries.d.ts +22 -7
  72. package/dist/holmes/mcp/handlers/phase-queries.js +81 -2
  73. package/dist/holmes/mcp/handlers/requirement-triage.js +5 -3
  74. package/dist/holmes/mcp/handlers/review-evidence.js +8 -2
  75. package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +11 -0
  76. package/dist/holmes/mcp/handlers/slice-orchestration.js +115 -16
  77. package/dist/holmes/mcp/handlers/spec-approval.d.ts +9 -0
  78. package/dist/holmes/mcp/handlers/spec-approval.js +110 -17
  79. package/dist/holmes/mcp/handlers/spec-authoring.js +17 -2
  80. package/dist/holmes/mcp/handlers/spec-queries.d.ts +39 -3
  81. package/dist/holmes/mcp/handlers/spec-queries.js +114 -7
  82. package/dist/holmes/mcp/handlers/test-execution.js +9 -3
  83. package/dist/holmes/mcp/handlers.d.ts +81 -9
  84. package/dist/holmes/mcp/handlers.js +70 -23
  85. package/dist/holmes/mcp/harness-attestation.d.ts +20 -0
  86. package/dist/holmes/mcp/harness-attestation.js +179 -0
  87. package/dist/holmes/mcp/requirement-triage-evidence.d.ts +36 -0
  88. package/dist/holmes/mcp/requirement-triage-evidence.js +160 -4
  89. package/dist/holmes/mcp/server.js +20 -1
  90. package/dist/holmes/mcp/tool-schemas.js +26 -9
  91. package/dist/holmes/mcp/validate-args.js +12 -0
  92. package/dist/holmes/project/bounded-io.d.ts +102 -0
  93. package/dist/holmes/project/bounded-io.js +212 -0
  94. package/dist/holmes/project/change-source.js +3 -1
  95. package/dist/holmes/project/ci-runs.js +3 -2
  96. package/dist/holmes/project/ignore.d.ts +31 -2
  97. package/dist/holmes/project/ignore.js +409 -50
  98. package/dist/holmes/project/regular-file-guard.d.ts +13 -0
  99. package/dist/holmes/project/regular-file-guard.js +149 -0
  100. package/dist/holmes/project/root.js +12 -3
  101. package/dist/holmes/reverse/anchor.js +4 -3
  102. package/dist/holmes/reverse/scan.js +6 -2
  103. package/dist/holmes/review/commit-text.js +3 -2
  104. package/dist/holmes/review/condition-hunk-replay.js +3 -2
  105. package/dist/holmes/review/failed-test-names.js +13 -10
  106. package/dist/holmes/review/findings.js +3 -1
  107. package/dist/holmes/review/kills-check.js +6 -1
  108. package/dist/holmes/review/point-in-time-replay.js +5 -4
  109. package/dist/holmes/review/replay-corpus.js +5 -4
  110. package/dist/holmes/review/run-replay.js +3 -2
  111. package/dist/holmes/review/temporal-prior.js +3 -2
  112. package/dist/holmes/review/test-evidence.js +3 -2
  113. package/dist/holmes/review/test-outcomes.js +3 -2
  114. package/dist/holmes/review/test-runner.d.ts +6 -0
  115. package/dist/holmes/review/test-runner.js +36 -15
  116. package/dist/holmes/rtm/advisory-outcomes.js +3 -2
  117. package/dist/holmes/rtm/anchor-ids.js +42 -2
  118. package/dist/holmes/rtm/file-anchors.js +4 -1
  119. package/dist/holmes/rtm/ftt-fulfilment.js +8 -3
  120. package/dist/holmes/rtm/git-changes.js +3 -1
  121. package/dist/holmes/rtm/graph-store.js +3 -2
  122. package/dist/holmes/rtm/test-scope.js +9 -4
  123. package/dist/holmes/spec/compat-impact.d.ts +25 -4
  124. package/dist/holmes/spec/compat-impact.js +682 -11
  125. package/dist/holmes/spec/entity-git-snapshot.js +3 -2
  126. package/dist/holmes/spec/entity-integration.js +3 -2
  127. package/dist/holmes/spec/entity-renumber-transaction.d.ts +19 -0
  128. package/dist/holmes/spec/entity-renumber-transaction.js +79 -6
  129. package/dist/holmes/spec/remote-spec-refs.js +3 -2
  130. package/dist/holmes/spec/renumber.js +25 -10
  131. package/dist/holmes/spec/spec-parser.js +9 -3
  132. package/dist/holmes/spec/yaml-scalar.js +2 -2
  133. package/dist/holmes/update/refresh.d.ts +5 -0
  134. package/dist/holmes/update/refresh.js +26 -1
  135. package/dist/holmes/update/update-notice.d.ts +6 -0
  136. package/dist/holmes/update/update-notice.js +18 -1
  137. package/dist/holmes/update/upgrade-plan.d.ts +28 -0
  138. package/dist/holmes/update/upgrade-plan.js +31 -2
  139. package/package.json +11 -4
@@ -33,28 +33,41 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.STRIPPED_FOR_PROBE = void 0;
36
+ exports.terminalSafe = exports.STRIPPED_FOR_PROBE = void 0;
37
+ exports.isInstallScript = isInstallScript;
37
38
  exports.resolvesToPackage = resolvesToPackage;
38
39
  exports.globalInstallDir = globalInstallDir;
39
40
  exports.npmCliEntry = npmCliEntry;
40
41
  exports.probeWritable = probeWritable;
41
42
  exports.prefixVerdict = prefixVerdict;
42
43
  exports.grammarProbe = grammarProbe;
44
+ exports.npmHome = npmHome;
43
45
  exports.resolveDepDir = resolveDepDir;
44
46
  exports.gatherNativeEvidence = gatherNativeEvidence;
45
47
  exports.probeEnv = probeEnv;
46
48
  exports.resolveWiringPath = resolveWiringPath;
47
49
  exports.runDoctor = runDoctor;
50
+ exports.resetWiringSpawns = resetWiringSpawns;
51
+ exports.wiringSpawnShared = wiringSpawnShared;
48
52
  exports.wiringSpawnCheck = wiringSpawnCheck;
53
+ exports.mcpProbeEnv = mcpProbeEnv;
49
54
  exports.pushGateCheck = pushGateCheck;
50
55
  exports.ciMatrixCheck = ciMatrixCheck;
56
+ exports.checksJson = checksJson;
51
57
  exports.formatChecks = formatChecks;
52
58
  exports.codexWiredTarget = codexWiredTarget;
59
+ exports.wiringLauncherChecks = wiringLauncherChecks;
60
+ exports.wiringVersionChecks = wiringVersionChecks;
61
+ exports.harnessClause = harnessClause;
62
+ exports.npxLaunchWritten = npxLaunchWritten;
63
+ exports.probeRefusal = probeRefusal;
64
+ exports.probeSpawn = probeSpawn;
65
+ exports.probeContext = probeContext;
53
66
  exports.wiringHandshakeChecks = wiringHandshakeChecks;
54
67
  exports.semanticCoverageCheck = semanticCoverageCheck;
55
68
  exports.semanticTierVerdict = semanticTierVerdict;
56
69
  exports.detectTreeKeyTemporary = detectTreeKeyTemporary;
57
- // @implements A-SPEC-721
70
+ // @implements A-SPEC-733, A-SPEC-727, A-SPEC-721, A-SPEC-738, A-SPEC-734
58
71
  // @implements A-SPEC-704, A-SPEC-710, A-SPEC-712
59
72
  const doctor_guidance_1 = require("./doctor-guidance");
60
73
  // @implements A-SPEC-264, A-SPEC-423, A-SPEC-549.1, A-SPEC-590
@@ -84,20 +97,95 @@ const settings_merge_1 = require("./settings-merge");
84
97
  const playbook_skills_1 = require("./playbook-skills");
85
98
  const init_1 = require("./init");
86
99
  const mcp_version_1 = require("./mcp-version");
100
+ const codex_hooks_1 = require("./codex-hooks");
101
+ const codex_oracle_1 = require("./codex-oracle");
87
102
  const codex_toml_1 = require("./codex-toml");
88
103
  const agents_1 = require("./agents");
89
104
  const mcp_launcher_1 = require("./mcp-launcher");
105
+ const workspace_scope_1 = require("./workspace-scope");
106
+ const claude_switches_1 = require("./claude-switches");
90
107
  const tool_schemas_1 = require("../mcp/tool-schemas");
91
108
  const mcp_schema_cost_1 = require("./mcp-schema-cost");
109
+ /**
110
+ * @implements A-SPEC-251.2 (round 42) — a hook script named by a relative path: each harness resolves it against the session's
111
+ * directory, so doctor neither resolves it against its own (target wiring flipped between PASS and FAIL with doctor's working
112
+ * directory — measured) nor confirms it.
113
+ */
114
+ const relativeScript = (p) => p !== '' && !(0, claude_switches_1.isAbsoluteScript)(p);
115
+ const RELATIVE_FIX = 'Re-run `holmes-kit init --force` in the target to write absolute paths.';
116
+ const relativeDetail = (rel) => `hook script(s) named by a relative path (${(0, codex_oracle_1.cappedList)(rel)}), which the harness resolves against the session's current directory — not confirmed`;
117
+ /** Round 44: wiring arguments walked per launch. */
118
+ const WIRING_ARGS_JUDGED = 16;
119
+ /** Round 43: distinct hook scripts one wiring check judges (1,000 committed entries held doctor for 106 s — measured). */
120
+ const HOOK_SCRIPTS_JUDGED = 16;
121
+ /**
122
+ * @implements A-SPEC-251.2 (round 43) — each wiring-derived script is walked once per doctor run: whether it is this install,
123
+ * another existing file, missing, on a path doctor never looks up (`refused`), or past the walk's bound (`unknown`).
124
+ */
125
+ function scriptJudge(packageRoot) {
126
+ const memo = new Map();
127
+ return (p) => {
128
+ let v = memo.get(p);
129
+ if (v === undefined) {
130
+ if (p === '')
131
+ v = 'missing';
132
+ else if (resolvesToPackage(p, packageRoot))
133
+ v = 'this';
134
+ else {
135
+ const w = (0, codex_oracle_1.localRealpath)(p);
136
+ v = w.exhausted ? 'unknown' : w.refused ? 'refused' : w.path !== null ? 'other' : 'missing';
137
+ }
138
+ memo.set(p, v);
139
+ }
140
+ return v;
141
+ };
142
+ }
143
+ const UNKNOWN_DETAIL = (u) => `hook script(s) whose path doctor could not walk within its bound (${(0, codex_oracle_1.cappedList)(u)}) — not confirmed`;
144
+ /** Round 43: a wired settings file as Claude reads it — past 2 MiB it is not read (the check parsed any size — measured). */
145
+ function readSettingsBounded(file) {
146
+ if (fs.statSync(file).size > claude_switches_1.CLAUDE_SETTINGS_MAX_BYTES)
147
+ return 'large';
148
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
149
+ }
150
+ /**
151
+ * @implements A-SPEC-251.2 (round 45) — whether `p` is this install's own `bin/<name>`, by `resolvesToPackage`'s rule: a path
152
+ * inside the install as written is compared as written; any other is compared by its walked real path (round 44 compared the walk
153
+ * of an install on a path doctor never looks up — null — and read a false FAIL, measured).
154
+ */
155
+ function isInstallScript(p, name, packageRoot) {
156
+ const lexical = path.resolve(p);
157
+ const own = path.join(path.resolve(packageRoot), 'bin', name);
158
+ // Round 46: a spelling that differs only by case is decided by the file system, through the walk (a case-insensitive disk runs
159
+ // `<install>/BIN/…` as the script; round 45 read it as another file — measured).
160
+ if (lexical.startsWith(path.resolve(packageRoot) + path.sep) && (lexical === own || lexical.toLowerCase() !== own.toLowerCase()))
161
+ return lexical === own;
162
+ const walked = (0, codex_oracle_1.localRealpath)(lexical);
163
+ if (walked.path === null)
164
+ return false;
165
+ try {
166
+ return walked.path === fs.realpathSync.native(own);
167
+ }
168
+ catch {
169
+ return false;
170
+ }
171
+ }
92
172
  /**
93
173
  * Checks if a script path belongs to the packageRoot, supporting symlinked global installs.
94
174
  */
95
175
  function resolvesToPackage(filePath, packageRoot) {
96
- if (!filePath || !fs.existsSync(filePath))
176
+ if (!filePath)
177
+ return false;
178
+ // @implements A-SPEC-251.2 (round 38) — a path inside this install as written is looked up where the install runs (an
179
+ // install under `/net` read FAIL in every harness once round 37 walked first — code reading).
180
+ const lexical = path.resolve(filePath);
181
+ if (lexical.startsWith(path.resolve(packageRoot) + path.sep))
182
+ return fs.existsSync(lexical);
183
+ // @implements A-SPEC-251.2 (round 37) — a hook script path from a wiring is walked before it is looked up (a settings hook
184
+ // through a committed `lnk -> /net/…` and an Antigravity `args` path on `/net` were looked up — measured).
185
+ const walked = (0, codex_oracle_1.localRealpath)(lexical);
186
+ if (walked.refused || walked.path === null || !fs.existsSync(walked.path))
97
187
  return false;
98
188
  try {
99
- if (path.resolve(filePath).startsWith(path.resolve(packageRoot) + path.sep))
100
- return true;
101
189
  // @implements A-SPEC-586.2 — canonical, not merely real: the JS `realpathSync` walks lstat and
102
190
  // leaves a Windows 8.3 short name (`HOLMES~1`) as it is, so the very hook path init writes for a
103
191
  // spaced install read as "another install". `realpathSync.native` asks the OS for the final
@@ -110,7 +198,8 @@ function resolvesToPackage(filePath, packageRoot) {
110
198
  return fs.realpathSync(p);
111
199
  }
112
200
  };
113
- const realFile = canonical(filePath);
201
+ // Round 38: the walked path, never the spelling (`lnk/../x/…` was re-resolved through `lnk -> /net/…` — measured).
202
+ const realFile = canonical(walked.path);
114
203
  const realPkg = canonical(packageRoot);
115
204
  return realFile.startsWith(realPkg + path.sep);
116
205
  }
@@ -119,6 +208,8 @@ function resolvesToPackage(filePath, packageRoot) {
119
208
  }
120
209
  }
121
210
  const worktree_readiness_1 = require("./worktree-readiness");
211
+ const linear_match_1 = require("../guardrail/linear-match");
212
+ const bounded_io_1 = require("../project/bounded-io");
122
213
  const GRAMMARS = [
123
214
  'tree-sitter-typescript', 'tree-sitter-python', 'tree-sitter-c-sharp', 'tree-sitter-java',
124
215
  'tree-sitter-go', 'tree-sitter-rust', 'tree-sitter-cpp',
@@ -146,7 +237,7 @@ exports.STRIPPED_FOR_PROBE = ['HOLMES_APPROVAL', 'HOLMES_SPECS'];
146
237
  */
147
238
  function globalInstallDir(prefix, platform) {
148
239
  return platform === 'win32'
149
- ? `${prefix.replace(/[\\/]+$/, '')}\\node_modules`
240
+ ? `${(0, linear_match_1.trimTrailing)(prefix, '\\/')}\\node_modules`
150
241
  : `${prefix.replace(/\/+$/, '')}/lib/node_modules`;
151
242
  }
152
243
  /**
@@ -162,16 +253,26 @@ function globalInstallDir(prefix, platform) {
162
253
  * matches neither (measured) — null there, and the caller keeps the plain-'npm' spawn, which is
163
254
  * today's behavior and has no .cmd problem on POSIX. env/execPath are injectable for tests only.
164
255
  */
165
- function npmCliEntry(env = process.env, execPath = process.execPath) {
256
+ function npmCliEntry(env = process.env, execPath = process.execPath, keep = () => true) {
166
257
  const fromEnv = env.npm_execpath;
167
- if (fromEnv && path.basename(fromEnv) === 'npm-cli.js' && fs.existsSync(fromEnv))
258
+ // @implements A-SPEC-251.2 (round 52, sixth repair) — only a file the probe keeps: doctor started the `npm-cli.js` this
259
+ // variable named three times a run, inside the workspace or linked into it (measured).
260
+ const kept = (f) => { try {
261
+ return keep(f) && keep(fs.realpathSync.native(f));
262
+ }
263
+ catch {
264
+ return false;
265
+ } };
266
+ if (fromEnv && path.basename(fromEnv) === 'npm-cli.js' && fs.existsSync(fromEnv) && kept(fromEnv))
168
267
  return fromEnv;
169
268
  const bin = path.dirname(execPath);
170
269
  for (const cand of [
171
270
  path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
172
271
  path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
173
272
  ]) {
174
- if (fs.existsSync(cand))
273
+ // Seventh repair: the candidates beside doctor's node too — a node inside the workspace (nodeenv in the project) has the
274
+ // workspace's `npm-cli.js` beside it, which the sixth repair's refusal of `npm_execpath` fell through to (measured).
275
+ if (fs.existsSync(cand) && kept(cand))
175
276
  return cand;
176
277
  }
177
278
  return null;
@@ -282,9 +383,32 @@ function grammarProbe(packageRoot) {
282
383
  }
283
384
  }
284
385
  /** A short spawn whose failure means "not observed" — never a verdict. */
285
- function observe(file, args) {
386
+ function observe(file, args, cwd) {
387
+ try {
388
+ return (0, node_child_process_1.execFileSync)(file, args, { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], cwd }).trim();
389
+ }
390
+ catch {
391
+ return undefined;
392
+ }
393
+ }
394
+ /**
395
+ * @implements A-SPEC-251.2 (round 26) — every npm child doctor starts: npm's own weekly update check (started by every
396
+ * command, raced, not awaited) sent a request per doctor run, to the registry the target's `.npmrc` named (measured).
397
+ * The global questions are asked from the home directory, so no target's `.npmrc` is read for them.
398
+ */
399
+ const NPM_QUIET = ['--no-update-notifier'];
400
+ /**
401
+ * @implements A-SPEC-251.2 (round 27) — the home directory, only when it is one: a missing HOME made the spawn fail as
402
+ * `spawnSync npm ENOENT`, which named npm as missing (measured); the npm child then keeps the default directory.
403
+ */
404
+ function npmHome(home = (() => { try {
405
+ return os.homedir();
406
+ }
407
+ catch {
408
+ return '';
409
+ } })()) {
286
410
  try {
287
- return (0, node_child_process_1.execFileSync)(file, args, { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
411
+ return home !== '' && fs.statSync(home).isDirectory() ? home : undefined;
288
412
  }
289
413
  catch {
290
414
  return undefined;
@@ -297,7 +421,9 @@ function observe(file, args) {
297
421
  * is deliberately unobserved rather than mistaken for this target's installed gate.
298
422
  */
299
423
  function installedCodexPluginForTarget(target, readPluginList) {
300
- const raw = readPluginList?.() ?? observe('codex', ['plugin', 'list', '--marketplace', agents_1.CODEX_MARKETPLACE, '--json']);
424
+ // A-SPEC-738 (round 12): an injected reader is the ONLY reader (a stub returning undefined fell through
425
+ // to the real `codex plugin list` in the caller's environment — measured).
426
+ const raw = readPluginList ? readPluginList() : observe('codex', ['plugin', 'list', '--marketplace', agents_1.CODEX_MARKETPLACE, '--json']);
301
427
  if (raw === undefined)
302
428
  return false;
303
429
  try {
@@ -351,7 +477,7 @@ function resolveDepDir(fromRoot, name) {
351
477
  return null;
352
478
  }
353
479
  }
354
- function gatherNativeEvidence(packageRoot) {
480
+ function gatherNativeEvidence(packageRoot, target = process.cwd()) {
355
481
  const name = 'better-sqlite3';
356
482
  // @implements A-SPEC-583.1 — resolved, not joined. A hoisted install is the npm default.
357
483
  const pkgDir = resolveDepDir(packageRoot, name);
@@ -371,10 +497,10 @@ function gatherNativeEvidence(packageRoot) {
371
497
  catch (e) {
372
498
  loadError = e.message.split('\n')[0];
373
499
  }
374
- const npmCli = npmCliEntry();
375
- const npmVersion = npmCli !== null ? observe(process.execPath, [npmCli, '--version']) : observe('npm', ['--version']);
500
+ const npmCli = npmCliEntry(process.env, process.execPath, probeContext(target).keep);
501
+ const npmVersion = npmCli !== null ? observe(process.execPath, [npmCli, '--version', ...NPM_QUIET], npmHome()) : observe('npm', ['--version', ...NPM_QUIET], npmHome());
376
502
  const npmMajor = npmVersion !== undefined && /^\d+/.test(npmVersion) ? Number(npmVersion.match(/^\d+/)[0]) : undefined;
377
- const prefix = npmCli !== null ? observe(process.execPath, [npmCli, 'config', 'get', 'prefix']) : observe('npm', ['config', 'get', 'prefix']);
503
+ const prefix = npmCli !== null ? observe(process.execPath, [npmCli, 'config', 'get', 'prefix', ...NPM_QUIET], npmHome()) : observe('npm', ['config', 'get', 'prefix', ...NPM_QUIET], npmHome());
378
504
  const kind = (0, native_deps_1.installKind)(packageRoot, prefix ? globalInstallDir(prefix, process.platform) : undefined);
379
505
  let coverage = 'uncovered';
380
506
  const policyJson = kind === 'repo' ? path.join(packageRoot, 'package.json')
@@ -420,8 +546,11 @@ function probeEnv(parent) {
420
546
  function wiredSettingsPath(target) {
421
547
  const carries = (which) => {
422
548
  try {
423
- const s = JSON.parse(fs.readFileSync((0, init_1.settingsPathOf)(target, which), 'utf8'));
424
- return Object.values(s.hooks ?? {}).some((groups) => (groups ?? []).some((g) => (g.hooks ?? []).some((h) => (0, settings_merge_1.isHolmesCommand)(h.command))));
549
+ const s = readSettingsBounded((0, init_1.settingsPathOf)(target, which));
550
+ if (s === 'large')
551
+ return false;
552
+ return Object.values(s.hooks ?? {}).some((groups) => Array.isArray(groups)
553
+ && groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => (0, settings_merge_1.isHolmesCommand)(h?.command))));
425
554
  }
426
555
  catch {
427
556
  return false;
@@ -453,6 +582,10 @@ function resolveWiringPath(target, arg) {
453
582
  async function runDoctor(packageRoot, target, opts, extraChecks) {
454
583
  const checks = (0, doctor_guidance_1.guidanceChecks)(packageRoot, target ?? process.cwd());
455
584
  const add = (name, level, detail, fix) => checks.push({ name, level, detail, fix });
585
+ // Round 43: every wiring-derived script is walked once per run.
586
+ const judge = scriptJudge(packageRoot);
587
+ // Round 50: and every launch started once per run.
588
+ resetWiringSpawns();
456
589
  // 1. Build output — also the "prepare didn't run" detector.
457
590
  const serverJs = path.join(packageRoot, 'dist', 'holmes', 'mcp', 'server.js');
458
591
  const hookJs = path.join(packageRoot, 'dist', 'holmes', 'hooks', 'pre-tool-use.js');
@@ -496,7 +629,7 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
496
629
  // node-gyp rebuild). Its failure has at least five causes with five different remedies, so the
497
630
  // verdict is computed from evidence (A-SPEC-580), never from the load error's wording alone.
498
631
  {
499
- const v = (0, native_deps_1.nativeVerdict)(gatherNativeEvidence(packageRoot));
632
+ const v = (0, native_deps_1.nativeVerdict)(gatherNativeEvidence(packageRoot, target ?? process.cwd()));
500
633
  add('better-sqlite3', v.level, v.detail, v.fix);
501
634
  }
502
635
  // 5. Hooks actually gate — prove it with a live allow AND a live deny (exit 2).
@@ -542,15 +675,17 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
542
675
  // disagrees with someone's mental model is how a correct answer still gets distrusted.
543
676
  const excluded = exports.STRIPPED_FOR_PROBE.filter((k) => process.env[k] !== undefined);
544
677
  const note = excluded.length ? ` (probe excluded ${excluded.join(', ')} — an approval legitimately allows what this check expects denied)` : '';
545
- add('PreToolUse gate', ok ? 'PASS' : 'FAIL', ok ? `allows a benign command; denies a catastrophic delete (exit 2)${note}` : `allow exit=${allow.status}, deny exit=${deny.status}${note}`, ok ? undefined : 'The guardrail is not enforcing. Re-check the build output and reinstall.');
678
+ add('PreToolUse gate', ok ? 'PASS' : 'FAIL',
679
+ // A-SPEC-251.2 (round 32): since REQ-739 a benign command passes without a decision — the gate grants nothing.
680
+ ok ? `passes a benign command to the harness without a decision; denies a catastrophic delete (exit 2)${note}` : `pass exit=${allow.status}, deny exit=${deny.status}${note}`, ok ? undefined : 'The guardrail is not enforcing. Re-check the build output and reinstall.');
546
681
  const stop = run(stopJs, { session_id: 'doctor' });
547
- add('Stop gate', stop.status === 0 ? 'PASS' : 'WARN', `exit=${stop.status}${stop.stderr ? ` — ${String(stop.stderr).slice(0, 160)}` : ''}`);
682
+ add('Stop gate', stop.status === 0 ? 'PASS' : 'WARN', `exit=${stop.status}${stop.stderr ? ` — ${(0, codex_oracle_1.clipText)(String(stop.stderr), 160)}` : ''}`);
548
683
  }
549
684
  // 6. MCP server handshake — initialize, THEN tools/list. This must be async: the protocol is a
550
685
  // round-trip, and a spawnSync that writes everything and closes stdin makes the server exit
551
686
  // before it answers (a false FAIL this check produced on its first run).
552
687
  if (built) {
553
- checks.push(await mcpHandshakeCheck(packageRoot));
688
+ checks.push(await mcpHandshakeCheck(packageRoot, target ?? process.cwd()));
554
689
  // @implements A-SPEC-652.2 — the handshake above proves THIS install; the wiring may run a
555
690
  // cached npx copy instead, and a corrupt cache entry dies before any handshake (measured
556
691
  // 2026-09-15: "Connection closed" at session start, npm ENOENT on the entry's package.json).
@@ -562,6 +697,15 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
562
697
  // A doctor run with no target has no harness wiring to prove — skipped, not failed.
563
698
  if (target)
564
699
  checks.push(...await wiringHandshakeChecks(target, opts?.codexConfigPath));
700
+ // @implements A-SPEC-251.2 (0.31.0) — an npx wiring hands each session workspace the server's launch.
701
+ if (target)
702
+ checks.push(...wiringLauncherChecks(target, opts?.codexConfigPath));
703
+ // @implements A-SPEC-251.2 (confirmation round 22) — the drift check for the Codex and Antigravity wirings too.
704
+ if (target) {
705
+ const cli = (0, mcp_launcher_1.readPackageVersion)(packageRoot);
706
+ if (cli)
707
+ checks.push(...wiringVersionChecks(target, opts?.codexConfigPath, cli));
708
+ }
565
709
  }
566
710
  // 7. Target wiring — do the configured commands point at THIS installed package and exist?
567
711
  if (target) {
@@ -573,27 +717,70 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
573
717
  // install. Both checks now read the file the target actually uses.
574
718
  const sp = wiredSettingsPath(target);
575
719
  try {
576
- const settings = JSON.parse(fs.readFileSync(sp, 'utf8'));
720
+ const settings = readSettingsBounded(sp);
577
721
  const cmds = [];
578
- for (const groups of Object.values(settings.hooks ?? {})) {
579
- for (const g of groups ?? [])
580
- for (const h of g.hooks ?? [])
581
- if ((0, settings_merge_1.isHolmesCommand)(h.command))
722
+ for (const groups of settings === 'large' ? [] : Object.values(settings.hooks ?? {})) {
723
+ if (!Array.isArray(groups))
724
+ continue; // A-SPEC-251.2 round 34: a key beside the events Claude drops
725
+ for (const g of groups)
726
+ for (const h of Array.isArray(g?.hooks) ? g.hooks : [])
727
+ if ((0, settings_merge_1.isHolmesCommand)(h?.command))
582
728
  cmds.push(h.command);
583
729
  }
584
- if (cmds.length === 0)
730
+ if (settings === 'large')
731
+ add('target wiring', 'WARN', `${sp} is larger than ${claude_switches_1.CLAUDE_SETTINGS_MAX_BYTES / (1024 * 1024)} MiB, which Claude does not read — not judged`, 'Run `holmes-kit init` in the target.');
732
+ else if (cmds.length === 0)
585
733
  add('target wiring', 'WARN', `no holmes hooks found in ${sp}`, 'Run `holmes-kit init` in the target.');
586
734
  else {
587
- const stale = cmds.filter((c) => {
588
- const p = (0, settings_merge_1.hookScriptPath)(c);
589
- return !resolvesToPackage(p, packageRoot);
590
- });
591
- add('target wiring', stale.length === 0 ? 'PASS' : 'FAIL', stale.length === 0 ? `${cmds.length} holmes hook(s) resolve to this install` : `stale/foreign command(s): ${stale.join(' | ')}`, stale.length === 0 ? undefined : 'Re-run `holmes-kit init --force` in the target to refresh the absolute paths.');
735
+ // Round 43: each distinct script once, and at most 16 of them.
736
+ const scripts = [...new Set(cmds.map((c) => (0, settings_merge_1.hookScriptPath)(c)))];
737
+ const rel = scripts.filter(relativeScript);
738
+ const abs = scripts.filter((p) => !relativeScript(p));
739
+ const judged = abs.slice(0, HOOK_SCRIPTS_JUDGED).map((p) => ({ p, v: judge(p) }));
740
+ const staleScripts = new Set(judged.filter((j) => j.v !== 'this' && j.v !== 'unknown').map((j) => j.p));
741
+ const stale = [...new Set(cmds.filter((c) => staleScripts.has((0, settings_merge_1.hookScriptPath)(c))))];
742
+ const unknown = judged.filter((j) => j.v === 'unknown').map((j) => j.p);
743
+ // @implements A-SPEC-251.2 (round 46) — Claude runs a command hook in the session's directory: a `node` the launcher finds
744
+ // there first (a relative PATH entry; win32 looks in the directory first) is the workspace's, not node.
745
+ // Round 47: by how it was found — a relative PATH entry or the directory is FAIL, an absolute entry into the workspace WARN.
746
+ const realTargetHere = (() => { try {
747
+ return fs.realpathSync.native(target);
748
+ }
749
+ catch {
750
+ return path.resolve(target);
751
+ } })();
752
+ const claudeNode = cmds.some((c) => /^node\s/.test(c.trim())) ? (0, mcp_launcher_1.gateNodeFinding)(target, (place) => !(0, workspace_scope_1.targetHoldsHome)(realTargetHere) && ((0, workspace_scope_1.inWorkspace)(realTargetHere, place) || (0, workspace_scope_1.isWithin)(path.resolve(target), place)), false) : null;
753
+ if (stale.length > 0)
754
+ add('target wiring', 'FAIL', `stale/foreign command(s): ${(0, codex_oracle_1.cappedList)(stale)}`, 'Re-run `holmes-kit init --force` in the target to refresh the absolute paths.');
755
+ else if (claudeNode !== null && claudeNode.level === 'FAIL')
756
+ add('target wiring', 'FAIL', `Claude runs the hook commands in ${target}, where "node" is found as ${(0, codex_oracle_1.clipText)(claudeNode.file)} through that directory or a relative PATH entry — whatever file is there runs as the gate`, 'Remove that file, or the relative entry in PATH that finds it.');
757
+ else if (claudeNode !== null)
758
+ add('target wiring', 'WARN', (0, mcp_launcher_1.gateNodeUnconfirmed)(claudeNode, (s) => (0, codex_oracle_1.clipText)(s)), 'Confirm that file is node, or put the node you trust first in PATH.');
759
+ else if (rel.length > 0)
760
+ add('target wiring', 'WARN', relativeDetail(rel), RELATIVE_FIX);
761
+ else if (unknown.length > 0)
762
+ add('target wiring', 'WARN', UNKNOWN_DETAIL(unknown), RELATIVE_FIX);
763
+ else if (abs.length > HOOK_SCRIPTS_JUDGED)
764
+ add('target wiring', 'WARN', `${abs.length} distinct holmes hook scripts, of which only the first ${HOOK_SCRIPTS_JUDGED} were judged — not confirmed`, RELATIVE_FIX);
765
+ else
766
+ add('target wiring', 'PASS', `${cmds.length} holmes hook(s) resolve to this install`);
592
767
  }
593
768
  }
594
769
  catch {
595
770
  add('target wiring', 'WARN', `could not read ${sp}`, 'Run `holmes-kit init` in the target.');
596
771
  }
772
+ // @implements A-SPEC-251.2 (round 30) — the files that switch Claude's hooks off (a committed `disableAllHooks`
773
+ // left every check above PASS while no hook ran — measured). Asked wherever the target carries Claude wiring.
774
+ // Round 31: only where Holmes's Claude wiring is (a target whose `.mcp.json` named another server got a FAIL — measured).
775
+ // Round 40: the canonical gate's script is judged against this install (a gate naming a missing old install read PASS).
776
+ if (holmesClaudeWired(target)) {
777
+ // Round 42: a path doctor refuses to look up (network) is unknown, not missing (a `/net/…` gate read FAIL — measured).
778
+ // Round 43: and so is one past the walk's bound; each script is walked once.
779
+ checks.push((0, claude_switches_1.claudeHookSwitchesCheck)(target, undefined, (script) => {
780
+ const v = judge(script);
781
+ return v === 'refused' || v === 'unknown' ? 'unknown' : v;
782
+ }));
783
+ }
597
784
  }
598
785
  // @implements A-SPEC-142
599
786
  // Recovery layer. WARN and never FAIL: no gate decision reads a playbook, so their absence changes
@@ -719,7 +906,8 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
719
906
  : [];
720
907
  if (onDisk.length > 0) {
721
908
  // Throws outside a git repo -> caught below -> no check added (no tracking concept).
722
- const tracked = new Set((0, node_child_process_1.execFileSync)('git', ['ls-files', '.ax/ledger'], {
909
+ // A-SPEC-734 (round 15): with the fsmonitor hook off (a slow hook dropped this row).
910
+ const tracked = new Set((0, node_child_process_1.execFileSync)('git', ['-c', 'core.fsmonitor=false', 'ls-files', '.ax/ledger'], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER,
723
911
  cwd: target, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
724
912
  }).split('\n').map((l) => l.trim().split('/').pop()).filter(Boolean));
725
913
  const untracked = onDisk.filter((f) => !tracked.has(f));
@@ -918,7 +1106,7 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
918
1106
  const families = found.filter((i) => i.kind === 'family-coexistence');
919
1107
  add('spec id preemption collision', collisions.length === 0 ? 'PASS' : 'WARN', collisions.length === 0
920
1108
  ? `No id is claimed by two different specs${scopeNote}`
921
- : collisions.map((c) => `${c.id}: ${c.files.join(' ↔ ')} (${c.detail})`).join('; ') + scopeNote, collisions.length === 0 ? undefined
1109
+ : collisions.map((c) => (0, codex_oracle_1.clipText)(`${c.id}: ${c.files.join(' ↔ ')} (${c.detail})`, 400)).join('; ') + scopeNote, collisions.length === 0 ? undefined
922
1110
  // @implements A-SPEC-700.1 — this line still told people to renumber BY HAND "until REQ-255" long after
923
1111
  // REQ-255 shipped, sending people to handwork the tool replaces. No plan is offered HERE:
924
1112
  // both copies sit in one store, so there is no published/unpublished side to choose by.
@@ -1052,6 +1240,8 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1052
1240
  const cli = (0, mcp_launcher_1.readPackageVersion)(packageRoot);
1053
1241
  if (server && typeof server.command === 'string' && Array.isArray(server.args) && cli) {
1054
1242
  const readPkgVersionAt = (dir) => {
1243
+ if (!(0, codex_oracle_1.openableLocalPath)(dir) || (0, codex_oracle_1.localRealpath)(path.join(dir, 'package.json')).refused)
1244
+ return undefined; // A-SPEC-251.2 rounds 35–37: never a network path, the file itself included
1055
1245
  try {
1056
1246
  const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
1057
1247
  return pkg?.name === '@holmes-lab/holmes-kit' && typeof pkg.version === 'string' ? pkg.version : undefined;
@@ -1060,12 +1250,15 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1060
1250
  return undefined;
1061
1251
  }
1062
1252
  };
1063
- const launch = (0, mcp_version_1.mcpLaunchVersion)({ command: server.command, args: server.args }, readPkgVersionAt);
1253
+ // @implements A-SPEC-251.2 (confirmation round 24) — a relative node path is the target's (doctor run with
1254
+ // `--target` from elsewhere said nothing — measured), as the Codex and Antigravity checks read it.
1255
+ const args = server.command === 'node' && typeof server.args[0] === 'string' ? [resolveWiringPath(target, server.args[0]), ...server.args.slice(1)] : server.args;
1256
+ const launch = (0, mcp_version_1.mcpLaunchVersion)({ command: server.command, args }, readPkgVersionAt);
1064
1257
  const verdict = (0, mcp_version_1.versionDriftVerdict)(launch, cli);
1065
1258
  if (verdict === 'drift') {
1066
- add('mcp server version', 'WARN', `This project's MCP server launches holmes-kit ${launch}, but this CLI is ${cli} — the old server keeps starting until it is rewired`,
1259
+ add('mcp server version', 'WARN', `This project's MCP server launches holmes-kit ${(0, codex_oracle_1.clipText)(String(launch), 40)}, but this CLI is ${cli} — the old server keeps starting until it is rewired`,
1067
1260
  // @implements A-SPEC-544.1 — one command installs + re-pins every workspace; init --force is the per-workspace path.
1068
- `Run ${(0, npx_bin_1.npxBin)()} holmes-kit upgrade to install the latest and re-pin every workspace (to fix only this workspace, ${(0, npx_bin_1.npxBin)()} holmes-kit init --force).`);
1261
+ `Run ${(0, npx_bin_1.npxBin)()} holmes-kit upgrade to install the latest and re-pin the workspaces that use this install (to fix only this workspace, ${(0, npx_bin_1.npxBin)()} holmes-kit init --force).`);
1069
1262
  }
1070
1263
  else if (verdict === 'match') {
1071
1264
  add('mcp server version', 'PASS', `MCP server version ${launch} matches this CLI`);
@@ -1090,10 +1283,36 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1090
1283
  try {
1091
1284
  const server = JSON.parse(fs.readFileSync(mcpPath, 'utf8'))
1092
1285
  .mcpServers?.[init_1.SERVER_NAME];
1093
- if (!server || typeof server.command !== 'string' || !Array.isArray(server.args)) {
1286
+ // Round 52 (fourth repair): an argument that is not a string is not a runnable launch (`npx 1 [object Object] null x`
1287
+ // was started here while the handshake said it could not read the wiring — measured).
1288
+ if (!server || typeof server.command !== 'string' || !Array.isArray(server.args) || !server.args.every((a) => typeof a === 'string')) {
1094
1289
  add('mcp wiring spawn', 'WARN', `.mcp.json carries no runnable ${init_1.SERVER_NAME} entry`, 'Run `holmes-kit init` in the target to write the wiring.');
1095
1290
  }
1096
- else if (server.command === 'node') {
1291
+ else if (launchBaseOf(target, (() => { try {
1292
+ return fs.realpathSync.native(target);
1293
+ }
1294
+ catch {
1295
+ return path.resolve(target);
1296
+ } })(), server.command) === null) {
1297
+ // @implements A-SPEC-251.2 (round 28) — a launch holmes-kit does not write is not spawned here either (a
1298
+ // workspace wrapper ran in this check and again in the handshake — measured).
1299
+ add('mcp wiring spawn', 'WARN', `not run: \`${(0, codex_oracle_1.clipText)((0, codex_oracle_1.launchText)({ command: server.command, args: server.args }))}\` is not a launch holmes-kit writes (see 'claude wiring identity')`, 'Run `holmes-kit init --target <dir> --agent claude --force` from the install you mean to use.');
1300
+ }
1301
+ else if (launchBaseOf(target, (() => { try {
1302
+ return fs.realpathSync.native(target);
1303
+ }
1304
+ catch {
1305
+ return path.resolve(target);
1306
+ } })(), server.command) === 'npx') {
1307
+ // Tenth repair (owner decision): judged by its shape, never started.
1308
+ const v = npxShapeCheck('claude', { command: server.command, args: server.args });
1309
+ add('mcp wiring spawn', v.level, v.detail, v.fix);
1310
+ }
1311
+ else if (probeRefusal(server.command, server.args, target, probeContext(target)) !== null) {
1312
+ // Third repair: what the handshake does not start is not started here either.
1313
+ add('mcp wiring spawn', 'WARN', `not run: \`${(0, codex_oracle_1.clipText)((0, codex_oracle_1.launchText)({ command: server.command, args: server.args }))}\` — ${probeRefusal(server.command, server.args, target, probeContext(target)) ?? ''} (see 'claude wiring identity')`, 'Run doctor with the node whose directory holds the launcher, outside the workspace.');
1314
+ }
1315
+ else if ((0, codex_oracle_1.launcherBase)(server.command) === 'node') {
1097
1316
  // @implements A-SPEC-323
1098
1317
  // Existence only, and it no longer stands in for the handshake. This branch used to be
1099
1318
  // the whole check for the common wiring, so "the file is there" was reported as if the
@@ -1103,14 +1322,36 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1103
1322
  // as written, because what the operator must fix is the wiring file, not our arithmetic.
1104
1323
  const bin = server.args[0] ?? '';
1105
1324
  const binAt = resolveWiringPath(target, bin);
1106
- add('mcp wiring spawn', fs.existsSync(binAt) ? 'PASS' : 'FAIL', fs.existsSync(binAt) ? `node wiring resolves: ${bin} (handshake proven separately)` : `node wiring points at a missing file: ${bin}`, fs.existsSync(binAt) ? undefined : 'Run `holmes-kit init` in the target to rewire the absolute path.');
1325
+ // A-SPEC-251.2 (round 32): not PASS for a file that is not this install's server (it said "node wiring
1326
+ // resolves" beside the identity FAIL of a workspace `bin/holmes-mcp.js` — measured).
1327
+ const ownBin = (() => { try {
1328
+ return fs.realpathSync.native(path.join(packageRoot, 'bin', 'holmes-mcp.js'));
1329
+ }
1330
+ catch {
1331
+ return null;
1332
+ } })();
1333
+ // A-SPEC-251.2 (round 35): a network or device path is never looked up.
1334
+ const walkedBin = (0, codex_oracle_1.localRealpath)(binAt);
1335
+ const binReal = walkedBin.path;
1336
+ if (walkedBin.refused) {
1337
+ add('mcp wiring spawn', 'WARN', walkedBin.exhausted
1338
+ ? `not run: \`${(0, codex_oracle_1.clipText)(bin)}\` reaches past doctor's walk bound (${codex_oracle_1.MAX_WALK_STEPS} components), so it is never opened`
1339
+ : `not run: \`${(0, codex_oracle_1.clipText)(bin)}\` is a network or device path, which is never opened`, 'Run `holmes-kit init --target <dir> --agent claude --force` from the install you mean to use.');
1340
+ }
1341
+ else if (binReal !== null && ownBin !== null && (binReal !== ownBin || server.args.length !== 1)) {
1342
+ add('mcp wiring spawn', 'WARN', `not run: \`${(0, codex_oracle_1.clipText)((0, codex_oracle_1.launchText)({ command: server.command, args: server.args }))}\` is not this install's server (see 'claude wiring identity')`, 'Run `holmes-kit init --target <dir> --agent claude --force` from the install you mean to use.');
1343
+ }
1344
+ else
1345
+ // A-SPEC-251.2 (round 39): existence from the walked path, never the spelling (`<t>/lnk/../x/bin/holmes-mcp.js` was
1346
+ // looked up through `lnk -> /net/…` — measured).
1347
+ add('mcp wiring spawn', binReal !== null ? 'PASS' : 'FAIL', binReal !== null ? `node wiring resolves: ${(0, codex_oracle_1.clipText)(bin)} (handshake proven separately)` : `node wiring points at a missing file: ${(0, codex_oracle_1.clipText)(bin)}`, binReal !== null ? undefined : 'Run `holmes-kit init` in the target to rewire the absolute path.');
1107
1348
  }
1108
1349
  else {
1109
1350
  // @implements A-SPEC-581.1 — the SIBLING of the handshake spawn, and it must move with
1110
1351
  // it. Measured on a consumer install: the same npx wiring read PASS from the handshake
1111
1352
  // (launched in the target) and FAIL here (launched in doctor's cwd) — two checks, one
1112
1353
  // wiring, opposite verdicts.
1113
- checks.push(await wiringSpawnCheck(server.command, server.args, undefined, undefined, target));
1354
+ checks.push(await wiringSpawnShared(server.command, server.args, target));
1114
1355
  }
1115
1356
  }
1116
1357
  catch {
@@ -1123,31 +1364,108 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1123
1364
  const agyHooks = path.join(target, '.agents', 'hooks.json');
1124
1365
  if (fs.existsSync(agyHooks)) {
1125
1366
  try {
1126
- const h = JSON.parse(fs.readFileSync(agyHooks, 'utf8'));
1367
+ // Round 47: not read past 2 MiB (a 400 MiB file ended doctor out of memory — measured).
1368
+ if (fs.statSync(agyHooks).size > agents_1.AGY_HOOKS_MAX_BYTES)
1369
+ throw new RangeError('large');
1370
+ const agyRaw = fs.readFileSync(agyHooks, 'utf8');
1371
+ const h = JSON.parse(agyRaw);
1127
1372
  const entry = h['holmes-kit'];
1373
+ // @implements A-SPEC-251.2 (round 46) — agy loads nothing from a file one named hook of which fails its parser, reads field
1374
+ // names case-insensitively, merges a user-level entry by name, and runs `node` from `<target>/.agents`.
1375
+ const fileProblem = (0, agents_1.agyHooksFileProblem)(agyRaw, h);
1376
+ const userHooks = opts?.agyUserHooksPath ?? (0, agents_1.agyUserHooksPath)();
1377
+ // Round 47: the user-level file and agy's other workspace roots (`.agent`, `_agents`, `_agent`, up to the repository root).
1378
+ const switches = (0, agents_1.agySwitches)(target, userHooks);
1379
+ const user = { off: switches.offIn !== null, unconfirmed: switches.unconfirmed };
1380
+ const offIn = switches.offIn ?? userHooks;
1381
+ const realTargetAgy = (() => { try {
1382
+ return fs.realpathSync.native(target);
1383
+ }
1384
+ catch {
1385
+ return path.resolve(target);
1386
+ } })();
1387
+ const agyNode = (0, mcp_launcher_1.gateNodeFinding)(path.join(target, '.agents'), (place) => !(0, workspace_scope_1.targetHoldsHome)(realTargetAgy) && ((0, workspace_scope_1.inWorkspace)(realTargetAgy, place) || (0, workspace_scope_1.isWithin)(path.resolve(target), place)));
1128
1388
  const pre = entry?.PreToolUse?.[0];
1129
1389
  // @implements A-SPEC-541.1 — the hook script path now lives in args[0] (command is bare
1130
1390
  // 'node'); older wirings joined it into the command string. Read args first, fall back to
1131
1391
  // parsing the string so a pre-539 hooks.json is still judged correctly.
1132
- const scriptOf = (e) => (Array.isArray(e?.args) && typeof e?.args[0] === 'string') ? e.args[0] : (0, settings_merge_1.hookScriptPath)(e?.command ?? '');
1133
- const stale = [scriptOf(pre?.hooks?.[0]), scriptOf(entry?.Stop?.[0])]
1134
- .filter((p2) => !resolvesToPackage(p2, packageRoot));
1392
+ // @implements A-SPEC-251.2 (round 43) — agy runs only the `command` string: it ignores `args` and keeps quotes (the
1393
+ // launcher contract measured in agents.ts). `args[0]` was read first, so a command running another file read PASS
1394
+ // (measured). A missing entry is judged as a missing script, as before; any other shape is not confirmed.
1395
+ const scriptOf = (e) => {
1396
+ const c = typeof e?.command === 'string' ? e.command : '';
1397
+ // Round 45: agy runs the command through `sh -c` (`cmd /c` on Windows) — only a path of characters both read literally is
1398
+ // confirmed (round 44 admitted `'`, which sh cannot parse — measured).
1399
+ const m = /^node (\S+)$/.exec(c)?.[1];
1400
+ return c === '' ? '' : m !== undefined && agents_1.AGY_LITERAL_PATH.test(m) ? m : null;
1401
+ };
1402
+ const shapes = [scriptOf(pre?.hooks?.[0]), scriptOf(entry?.Stop?.[0])];
1403
+ const scripts = shapes.filter((p2) => p2 !== null);
1404
+ // @implements A-SPEC-251.2 (round 44) — each entry runs its own script of this install: the Stop script as PreToolUse read
1405
+ // PASS while agy ran no gate (it answered `rm -rf /` with `{}` — measured).
1406
+ const wrongFile = shapes.some((p2, i) => p2 !== null && p2 !== '' && !relativeScript(p2) && judge(p2) === 'this'
1407
+ && !isInstallScript(p2, i === 0 ? 'holmes-hook-antigravity.js' : 'holmes-stop-antigravity.js', packageRoot));
1408
+ const stale = scripts.filter((p2) => !relativeScript(p2) && judge(p2) !== 'this' && judge(p2) !== 'unknown');
1409
+ const rel = scripts.filter(relativeScript);
1410
+ const unknownAgy = scripts.filter((p2) => !relativeScript(p2) && judge(p2) === 'unknown');
1411
+ const enabled = entry?.enabled;
1135
1412
  if (entry === undefined) {
1136
1413
  add('antigravity wiring', 'WARN', `${agyHooks} has no holmes-kit entry`, 'holmes-kit init --target <dir> --agent antigravity');
1137
1414
  }
1415
+ else if (enabled === false) {
1416
+ // @implements A-SPEC-251.2 (round 45) — agy's own documentation: `"enabled": false` switches every handler of the entry off.
1417
+ add('antigravity wiring', 'FAIL', `the holmes-kit entry in ${agyHooks} is switched off ("enabled": false), so agy runs no gate`, 'Remove "enabled": false from the holmes-kit entry, or run holmes-kit init --target <dir> --agent antigravity --force.');
1418
+ }
1419
+ else if (enabled !== undefined && typeof enabled !== 'boolean') {
1420
+ add('antigravity wiring', 'WARN', `the holmes-kit entry's "enabled" is not true or false (${(0, codex_oracle_1.clipText)(JSON.stringify(enabled), 60)}), so whether agy runs it is not confirmed`, 'Remove "enabled" from the holmes-kit entry, or set it to true.');
1421
+ }
1138
1422
  else if (stale.length > 0) {
1139
- add('antigravity wiring', 'FAIL', `hook path(s) not pointing at this install: ${stale.join(' | ')}`, 'Run holmes-kit init --target <dir> --agent antigravity --force to refresh the absolute paths.');
1423
+ add('antigravity wiring', 'FAIL', `hook path(s) not pointing at this install: ${stale.map((p2) => (0, codex_oracle_1.clipText)(p2)).join(' | ')}`, 'Run holmes-kit init --target <dir> --agent antigravity --force to refresh the absolute paths.');
1424
+ }
1425
+ else if (wrongFile) {
1426
+ add('antigravity wiring', 'FAIL', 'a holmes hook entry runs another file of this install than its own script (PreToolUse must run bin/holmes-hook-antigravity.js, Stop bin/holmes-stop-antigravity.js), so agy runs no gate', 'Run holmes-kit init --target <dir> --agent antigravity --force.');
1427
+ }
1428
+ else if (user.off && enabled !== true) {
1429
+ add('antigravity wiring', 'FAIL', `the holmes-kit entry is switched off in ${(0, codex_oracle_1.clipText)(offIn, 400)} ("enabled": false) — agy merges entries of one name from every hooks file, so it runs no gate here`, `Remove the holmes-kit entry (or its "enabled": false) from ${(0, codex_oracle_1.clipText)(offIn, 400)}, or switch it on again with /hooks in agy.`);
1430
+ }
1431
+ else if (agyNode !== null && agyNode.level === 'FAIL') {
1432
+ add('antigravity wiring', 'FAIL', `agy runs the hook command in ${path.join(target, '.agents')}, where "node" is found as ${(0, codex_oracle_1.clipText)(agyNode.file)} through that directory or a relative PATH entry — whatever file is there runs as the gate`, 'Remove that file, or the relative entry in PATH that finds it.');
1433
+ }
1434
+ else if (fileProblem !== null) {
1435
+ add('antigravity wiring', 'WARN', `agy may load nothing from ${agyHooks}: ${fileProblem} — agy drops the whole file when one named hook fails its parser, so the gate is not confirmed`, 'Fix or remove that entry: agy documents `enabled` (true/false) per named hook, and `type` "command", a non-empty `command` and a whole-number `timeout` per handler, with field names spelled exactly.');
1436
+ }
1437
+ else if (user.off || user.unconfirmed !== null) {
1438
+ add('antigravity wiring', 'WARN', user.unconfirmed ?? `the holmes-kit entry is switched off in ${(0, codex_oracle_1.clipText)(offIn, 400)} while this entry sets "enabled" — which one agy reads depends on the order it merges them, so the gate is not confirmed`, `Remove the holmes-kit entry from ${(0, codex_oracle_1.clipText)(offIn, 400)}.`);
1439
+ }
1440
+ else if (agyNode !== null) {
1441
+ add('antigravity wiring', 'WARN', (0, mcp_launcher_1.gateNodeUnconfirmed)(agyNode, (s) => (0, codex_oracle_1.clipText)(s)), 'Confirm that file is node, or put the node you trust first in PATH.');
1442
+ }
1443
+ else if (rel.length > 0) {
1444
+ add('antigravity wiring', 'WARN', relativeDetail(rel), RELATIVE_FIX);
1445
+ }
1446
+ else if (shapes.includes(null)) {
1447
+ add('antigravity wiring', 'WARN', 'a holmes hook entry is not the command init writes (`node <absolute path>` of letters, digits and - _ . / : @ + , =): agy runs only the command string, through sh -c (cmd /c on Windows), and ignores args — so it is not confirmed', 'Run holmes-kit init --target <dir> --agent antigravity --force.');
1448
+ }
1449
+ else if (unknownAgy.length > 0) {
1450
+ add('antigravity wiring', 'WARN', UNKNOWN_DETAIL(unknownAgy), 'Run holmes-kit init --target <dir> --agent antigravity --force.');
1140
1451
  }
1141
1452
  else if ((pre?.matcher ?? '') !== '*') {
1142
1453
  // A narrow matcher lets other tools pass the gate — a silent hole, so say it.
1143
- add('antigravity wiring', 'WARN', `The PreToolUse matcher is '${pre?.matcher ?? ''}' — unless it is '*', other tools never reach the gate`, "Restore the matcher to '*'.");
1454
+ add('antigravity wiring', 'WARN', `The PreToolUse matcher is '${(0, claude_switches_1.printable)((0, codex_oracle_1.clipText)(String(pre?.matcher ?? ''), 80))}' — unless it is '*', other tools never reach the gate`, "Restore the matcher to '*'.");
1455
+ }
1456
+ else if (!(0, agents_1.agyCanonicalFile)(h, agyRaw)) {
1457
+ // @implements A-SPEC-251.2 (round 47, owner decision 2026-09-27) — only the file init writes is confirmed.
1458
+ add('antigravity wiring', 'WARN', `${agyHooks} is not the file holmes-kit init writes (other named hooks, or other keys or values in the holmes-kit entry) — how agy reads and merges it is not confirmed`, 'Keep only the holmes-kit entry as init writes it (holmes-kit init --target <dir> --agent antigravity --force restores it), or confirm by hand that the gate blocks.');
1144
1459
  }
1145
1460
  else {
1146
1461
  add('antigravity wiring', 'PASS', 'PreToolUse and Stop point at this install');
1147
1462
  }
1148
1463
  }
1149
- catch {
1150
- add('antigravity wiring', 'FAIL', `${agyHooks} cannot be read (not JSON)`, 'Fix or delete the file and rewire.');
1464
+ catch (e) {
1465
+ if (e instanceof RangeError && e.message === 'large')
1466
+ add('antigravity wiring', 'WARN', `${agyHooks} is larger than ${agents_1.AGY_HOOKS_MAX_BYTES / (1024 * 1024)} MiB and was not read — not confirmed`, 'Fix or delete the file and rewire.');
1467
+ else
1468
+ add('antigravity wiring', 'FAIL', `${agyHooks} cannot be read (not JSON)`, 'Fix or delete the file and rewire.');
1151
1469
  }
1152
1470
  // Are the skills visible to that harness — a broken link makes skills silently disappear.
1153
1471
  const agySkills = path.join(target, '.agents', 'skills');
@@ -1160,74 +1478,249 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1160
1478
  // install. A leftover JSON with no config.toml is a stale wiring in a location Codex ignores → WARN.
1161
1479
  const cdxToml = opts?.codexConfigPath ?? (0, codex_toml_1.defaultCodexConfigPath)();
1162
1480
  const cdxJson = path.join(target, '.codex', 'mcp_config.json');
1481
+ // @implements A-SPEC-738 — whether Codex loads these files is Codex's answer where codex is
1482
+ // installed (asked once, over copies, locally); the emulation below is the labelled fallback.
1483
+ const cdxHooksPath = opts?.codexHooksPath ?? (0, codex_hooks_1.defaultCodexHooksPath)();
1484
+ const codexChecksFrom = checks.length;
1485
+ let codexAnswer;
1486
+ const codexVerdict = () => {
1487
+ if (codexAnswer !== undefined)
1488
+ return codexAnswer;
1489
+ const bytes = (p) => { try {
1490
+ return fs.existsSync(p) ? fs.readFileSync(p) : null;
1491
+ }
1492
+ catch {
1493
+ return null;
1494
+ } };
1495
+ const input = { configBytes: bytes(cdxToml), hooksBytes: bytes(cdxHooksPath), cwd: target, realConfigPath: cdxToml, realHooksPath: cdxHooksPath };
1496
+ if (opts?.codexOracle)
1497
+ codexAnswer = opts.codexOracle(input);
1498
+ else {
1499
+ const found = (0, codex_oracle_1.findCodex)(process.env, process.platform);
1500
+ codexAnswer = found.found ? (0, codex_oracle_1.askCodex)({ codex: found.codex, ...input }) : { available: false, reason: found.reason };
1501
+ }
1502
+ return codexAnswer;
1503
+ };
1163
1504
  // @implements A-SPEC-721 — the active config is user-level and shared by every workspace. It is
1164
1505
  // judged for THIS target only when it carries Holmes's table or the target is Codex-wired;
1165
1506
  // otherwise a Claude- or Antigravity-only workspace would inherit another tool's diagnosis.
1166
1507
  const targetWantsCodex = codexWiredTarget(target);
1167
1508
  let cdxRaw;
1509
+ // @implements A-SPEC-731 (round 6) — decoded strictly: Codex refuses a config that is not UTF-8.
1510
+ let cdxUndecodable = null;
1168
1511
  if (fs.existsSync(cdxToml)) {
1169
1512
  try {
1170
- cdxRaw = fs.readFileSync(cdxToml, 'utf8');
1513
+ const d = (0, codex_toml_1.readCodexConfigBytes)(fs.readFileSync(cdxToml));
1514
+ if (d.ok)
1515
+ cdxRaw = d.text;
1516
+ else {
1517
+ cdxRaw = null;
1518
+ cdxUndecodable = d.reason;
1519
+ }
1171
1520
  }
1172
1521
  catch {
1173
1522
  cdxRaw = null;
1174
1523
  }
1175
1524
  }
1176
1525
  const cdxHolmes = typeof cdxRaw === 'string' && (0, codex_toml_1.mentionsHolmes)(cdxRaw);
1177
- if ((cdxRaw === null && targetWantsCodex) || cdxHolmes) {
1526
+ /**
1527
+ * @implements A-SPEC-738 (round 12/13/14) — the EFFECTIVE Holmes table and every other server Codex runs,
1528
+ * judged against the user file's own tables (`raw` null: the user file has none). Adds the WARN lines and
1529
+ * returns the authority another layer hands a server; the caller FAILs on it. Round 14: also when the user
1530
+ * file has no Holmes table, the user file's own second server is attributed to it, second servers without
1531
+ * authority are one line naming at most ten, and a relative HOLMES_SPECS or CLAUDE_PROJECT_DIR redirects.
1532
+ */
1533
+ const judgeEffectiveCodex = (v, raw, fixedSpecs) => {
1534
+ if (!v.available)
1535
+ return [];
1536
+ const own = raw === null ? null : ownHolmesTable(raw);
1537
+ const layer = "another layer — a trusted project's .codex/config.toml (or a profile) —";
1538
+ const redirect = (0, codex_oracle_1.tableRedirection)(v.holmesTable, own);
1539
+ if (redirect.specs !== null && redirect.specs !== fixedSpecs) {
1540
+ const absolute = path.isAbsolute(redirect.specs) || path.win32.isAbsolute(redirect.specs);
1541
+ add('codex wiring env', 'WARN', absolute
1542
+ ? `${layer} pins HOLMES_SPECS to ${(0, codex_oracle_1.clipText)(redirect.specs)} for [mcp_servers.${init_1.SERVER_NAME}]: every Codex session there is bound to that one project's specs (judged by Codex)`
1543
+ : `${layer} sets HOLMES_SPECS = ${(0, codex_oracle_1.clipText)(redirect.specs)} for [mcp_servers.${init_1.SERVER_NAME}]: the server binds its spec store to that path under the session workspace, not to .ax/specs (judged by Codex)`, 'Remove the env.HOLMES_SPECS setting from that layer, then restart Codex.');
1544
+ }
1545
+ if (redirect.projectDir !== null) {
1546
+ add('codex wiring env', 'WARN', `${layer} sets CLAUDE_PROJECT_DIR = ${(0, codex_oracle_1.clipText)(redirect.projectDir)} for [mcp_servers.${init_1.SERVER_NAME}]: the server resolves its spec store under that directory, not the session workspace (judged by Codex)`, 'Remove the env.CLAUDE_PROJECT_DIR setting from that layer, then restart Codex.');
1547
+ }
1548
+ if (redirect.cwd !== null) {
1549
+ add('codex wiring env', 'WARN', `${layer} sets cwd = ${(0, codex_oracle_1.clipText)(redirect.cwd)} for [mcp_servers.${init_1.SERVER_NAME}]: the server binds its spec store to that directory, not the session workspace (judged by Codex)`, 'Remove the cwd setting from that layer, then restart Codex.');
1550
+ }
1551
+ // @implements A-SPEC-738 (round 16) — every layer node launch is checked against this install (shared cap).
1552
+ // Round 18: and every layer npx launch against this install's version.
1553
+ const install = { bin: (() => { try {
1554
+ return fs.realpathSync.native(path.join(packageRoot, 'bin', 'holmes-mcp.js'));
1555
+ }
1556
+ catch {
1557
+ return null;
1558
+ } })(), budget: { left: codex_oracle_1.INSTALL_CHECKS_MAX }, version: (0, mcp_launcher_1.readPackageVersion)(packageRoot) ?? null };
1559
+ const found = (0, codex_oracle_1.envFindings)(v.holmesTable, own, true, install);
1560
+ if (found.addedFromLayer.length > 0) {
1561
+ add('codex wiring env', 'WARN', `${layer} adds or changes ${(0, codex_oracle_1.cappedList)(found.addedFromLayer)} in the environment of [mcp_servers.${init_1.SERVER_NAME}] (judged by Codex)`, 'Remove those env settings from that layer unless you put them there, then restart Codex.');
1562
+ }
1563
+ if (found.authorityOwn.length > 0 || found.envVarsOwn.length > 0) {
1564
+ add('codex wiring env', 'WARN', `${cdxToml} gives [mcp_servers.${init_1.SERVER_NAME}] the authority variable(s) ${(0, codex_oracle_1.cappedList)([...found.authorityOwn, ...found.envVarsOwn])} — every Codex session's Holmes server holds that channel`, 'Remove them unless this machine is meant to approve or relax the gate for every session.');
1565
+ }
1566
+ const authority = [...found.authorityFromLayer, ...found.envVarsFromLayer.map((k) => (k === codex_oracle_1.UNREADABLE_ENV_VAR ? k : `env_vars ${k}`))];
1567
+ const plain = [];
1568
+ for (const s of v.otherHolmesServers ?? []) {
1569
+ const holmes = s.holmes !== false;
1570
+ const f = (0, codex_oracle_1.envFindings)(s.table, raw === null ? null : (0, codex_oracle_1.ownHolmesTableOf)(raw, s.name), holmes, install);
1571
+ const what = holmes ? `a second Holmes server [mcp_servers.${(0, codex_oracle_1.clipText)(s.name, 80)}]` : `the server [mcp_servers.${(0, codex_oracle_1.clipText)(s.name, 80)}]`;
1572
+ const fromLayer = [...f.authorityFromLayer, ...f.envVarsFromLayer];
1573
+ const ownAuth = [...f.authorityOwn, ...f.envVarsOwn];
1574
+ if (fromLayer.length > 0)
1575
+ authority.push(`${what} with ${(0, codex_oracle_1.cappedList)(fromLayer)}`);
1576
+ else if (ownAuth.length > 0) {
1577
+ add('codex wiring env', 'WARN', `${cdxToml} gives ${what} the authority variable(s) ${(0, codex_oracle_1.cappedList)(ownAuth)} — every Codex session runs that server with that channel`, 'Remove them unless this machine is meant to approve or relax the gate for every session.');
1578
+ }
1579
+ else if (holmes)
1580
+ plain.push(s.name);
1581
+ }
1582
+ if (plain.length > 0) {
1583
+ const named = plain.slice(0, 10).map((n) => `[mcp_servers.${(0, codex_oracle_1.clipText)(n, 80)}]`).join(', ');
1584
+ add('codex wiring second server', 'WARN', `Codex's effective configuration runs ${plain.length === 1 ? 'a second Holmes server' : `${plain.length} other Holmes servers`} ${named}${plain.length > 10 ? ` and ${plain.length - 10} more` : ''}, each with its own environment (judged by Codex)`, 'Remove those servers unless you configured them deliberately, then restart Codex.');
1585
+ }
1586
+ return authority;
1587
+ };
1588
+ if ((cdxRaw === null && (targetWantsCodex || cdxUndecodable !== null)) || cdxHolmes) {
1178
1589
  const raw = cdxRaw ?? null;
1179
1590
  if (raw === null) {
1180
- add('codex wiring', 'FAIL', `${cdxToml} cannot be read`, 'Check the file permissions, or delete it and rewire.');
1591
+ add('codex wiring', 'FAIL', cdxUndecodable ? `${cdxToml}: ${cdxUndecodable}` : `${cdxToml} cannot be read`, 'Check the file permissions, or delete it and rewire.');
1181
1592
  }
1182
1593
  else {
1183
1594
  if ((0, codex_toml_1.unownedHolmesShape)(raw)) {
1184
1595
  add('codex wiring shape', 'WARN', `${cdxToml} configures ${init_1.SERVER_NAME} in a shape holmes-kit does not own (dotted keys, an inline table under [mcp_servers], or a ${init_1.SERVER_NAME} subtable outside its table) — rewriting it would declare the table twice and Codex would reject the whole shared file`, `Edit ${cdxToml} by hand to a single [mcp_servers.${init_1.SERVER_NAME}] table (or remove the ${init_1.SERVER_NAME} settings), then run holmes-kit init --target <dir> --agent codex.`);
1185
1596
  }
1186
- const entry = (0, codex_toml_1.readCodexHolmesEntry)(raw);
1597
+ const ownEntry = (0, codex_toml_1.readCodexHolmesEntry)(raw);
1598
+ /** A-SPEC-738 (round 13): authority another layer hands the server (FAIL below). */
1599
+ let codexAuthority = [];
1600
+ // @implements A-SPEC-738 (round 2) — the entry Codex will RUN is judged: a trusted project layer
1601
+ // can replace the user file's table (measured: an old install passed as "resolves to this install").
1602
+ const effective = (() => {
1603
+ const v = codexVerdict();
1604
+ if (!v.available || !v.holmesTable || typeof v.holmesTable.command !== 'string')
1605
+ return null;
1606
+ // No `args` in the answer means unknown, not empty: compare the command alone then.
1607
+ const args = Array.isArray(v.holmesTable.args) ? v.holmesTable.args.filter((a) => typeof a === 'string') : (ownEntry?.args ?? []);
1608
+ return { command: v.holmesTable.command, args };
1609
+ })();
1610
+ const overridden = ownEntry !== null && effective !== null && JSON.stringify([ownEntry.command, ownEntry.args]) !== JSON.stringify([effective.command, effective.args]);
1611
+ const entry = overridden ? effective : ownEntry;
1612
+ if (overridden) {
1613
+ add('codex wiring override', 'WARN', `another configuration layer (a trusted project's .codex/config.toml or a profile) replaces [mcp_servers.${init_1.SERVER_NAME}] from ${cdxToml}: Codex runs \`${(0, codex_oracle_1.launchText)(effective)}\` — the lines below judge that entry`, 'Remove the overriding table, or rewire it with holmes-kit init --target <dir> --agent codex.');
1614
+ }
1187
1615
  const fixedSpecs = (0, codex_toml_1.readCodexFixedSpecs)(raw);
1188
1616
  if (fixedSpecs !== null && (path.isAbsolute(fixedSpecs) || path.win32.isAbsolute(fixedSpecs))) {
1189
- add('codex wiring env', 'WARN', `${cdxToml} pins HOLMES_SPECS to ${fixedSpecs} — this config is shared by every workspace, so every Codex session is bound to that one project's specs`, 'Rewire with holmes-kit init --target <dir> --agent codex --force; the entry it writes omits HOLMES_SPECS so the server follows the session workspace.');
1617
+ add('codex wiring env', 'WARN', `${cdxToml} pins HOLMES_SPECS to ${(0, codex_oracle_1.clipText)(fixedSpecs)} — this config is shared by every workspace, so every Codex session is bound to that one project's specs`, 'Rewire with holmes-kit init --target <dir> --agent codex --force; the entry it writes omits HOLMES_SPECS so the server follows the session workspace.');
1190
1618
  }
1619
+ // @implements A-SPEC-738 (round 12/13/14) — the EFFECTIVE table and every other server Codex runs.
1620
+ codexAuthority = judgeEffectiveCodex(codexVerdict(), raw, fixedSpecs);
1191
1621
  // @implements A-SPEC-585 — an invalid basic-string escape (a raw Windows backslash path is the
1192
1622
  // measured case) is not "half-done": Codex refuses the whole file, and the reader must not
1193
1623
  // hand doctor a mangled path to judge. Name the escape and the line.
1194
- const badEscape = entry ? null : (0, codex_toml_1.invalidTomlEscape)(raw);
1195
- if (!entry && badEscape) {
1624
+ // @implements A-SPEC-738 — Codex's own verdict wins both ways where it is available.
1625
+ const verdict = codexVerdict();
1626
+ const badEscape = entry || verdict.available ? null : (0, codex_toml_1.invalidTomlEscape)(raw);
1627
+ // @implements A-SPEC-731 (round 6) — judged even when our entry reads fine: another server, the
1628
+ // `model` key or an out-of-range integer makes Codex refuse the whole file (measured PASS ×2).
1629
+ // @implements A-SPEC-738 (round 6) — a layer's refusal names the LAYER: `<user file> does not load`
1630
+ // and `Fix <user file>` blamed the file that loads alone (measured 5/5 layer faults).
1631
+ const layerOnly = verdict.available && verdict.configError === null && verdict.otherConfigError !== undefined ? (0, codex_oracle_1.clipText)(verdict.otherConfigError.trim(), 600) : null;
1632
+ const loadProblem = verdict.available
1633
+ ? (verdict.configError !== null ? `Codex refuses it: ${(0, codex_oracle_1.clipText)(verdict.configError.trim(), 600)}` : null)
1634
+ : (0, codex_toml_1.codexConfigLoadProblem)(raw);
1635
+ const tableProblem = codexTableProblem(verdict.available ? verdict.holmesTable : ownHolmesTable(raw), verdict.available, entry !== null);
1636
+ if (layerOnly !== null) {
1637
+ add('codex wiring', 'FAIL', `Codex refuses this workspace's configuration because of another layer — ${layerOnly}; ${cdxToml} loads alone, but nothing from Codex loads here until that layer is fixed`, `Fix ${(0, codex_oracle_1.layerFileNamed)(layerOnly) ?? 'the .codex/config.toml in the workspace or an ancestor that Codex refuses'} by hand, then re-run holmes-kit doctor.`);
1638
+ }
1639
+ else if (loadProblem || (!entry && badEscape)) {
1640
+ // @implements A-SPEC-731 (round 4) — Codex refuses a config that does not parse, whole.
1641
+ add('codex wiring', 'FAIL', `${cdxToml} does not load (${badEscape ? `invalid escape ${badEscape.escape} on line ${badEscape.line} inside [mcp_servers.${init_1.SERVER_NAME}] — on Windows, double each backslash ("C:\\\\path") or use a single-quoted literal string ('C:\\path')` : loadProblem}) — Codex refuses the whole shared file, so no MCP server loads from it`, badEscape ? 'Rewire with holmes-kit init --target <dir> --agent codex (it repairs its own table and writes valid TOML).' : `Fix ${cdxToml} by hand, then run holmes-kit init --target <dir> --agent codex.`);
1642
+ }
1643
+ else if (codexAuthority.length > 0) {
1644
+ // @implements A-SPEC-738 (round 13) — measured: a layer's forged HOLMES_APPROVAL passed as PASS.
1645
+ // Round 14: before the half-done WARN (measured: `!entry` hid a layer's authority).
1646
+ add('codex wiring', 'FAIL', `another layer — a trusted project's .codex/config.toml (or a profile) — hands the Holmes server an approval, autonomy, gate or egress-consent channel, or a launch or environment holmes-kit cannot judge: ${(0, codex_oracle_1.cappedList)(codexAuthority)} (judged by Codex)`, 'Remove those settings from that layer (a .codex/config.toml in the workspace or an ancestor, or the profile), then restart Codex.');
1647
+ }
1648
+ else if (!entry && badEscape) {
1196
1649
  add('codex wiring', 'WARN', `${cdxToml} has an invalid escape ${badEscape.escape} on line ${badEscape.line} inside [mcp_servers.${init_1.SERVER_NAME}] — Codex refuses this file. On Windows, double each backslash ("C:\\\\path") or use a single-quoted literal string ('C:\\path').`, 'Rewire with holmes-kit init --target <dir> --agent codex --force (it writes valid TOML).');
1197
1650
  }
1198
1651
  else if (!entry) {
1199
- add('codex wiring', 'WARN', `${cdxToml} has no runnable [mcp_servers.${init_1.SERVER_NAME}] entry — a half-done wiring`, 'Rewire with holmes-kit init --target <dir> --agent codex.');
1652
+ // @implements A-SPEC-738 (round 15) — name the launch another layer supplies (it was never named).
1653
+ // Round 16: "from another layer" only when the launch differs from this file's own table (a user's own
1654
+ // `command = "holmes-mcp"` was attributed to a layer — measured).
1655
+ const effectiveLaunch = verdict.available && verdict.holmesTable !== null && typeof verdict.holmesTable.command === 'string' ? verdict.holmesTable : null;
1656
+ const ownTable = ownHolmesTable(raw);
1657
+ const fromLayer = effectiveLaunch !== null && (ownTable === null || (0, codex_oracle_1.launchKey)(effectiveLaunch) !== (0, codex_oracle_1.launchKey)(ownTable));
1658
+ add('codex wiring', 'WARN', `${cdxToml} has no runnable [mcp_servers.${init_1.SERVER_NAME}] entry — a half-done wiring${effectiveLaunch !== null ? `; Codex runs \`${(0, codex_oracle_1.launchText)(effectiveLaunch)}\` ${fromLayer ? 'from another layer' : 'from this file'}` : ''}`, 'Rewire with holmes-kit init --target <dir> --agent codex.');
1200
1659
  }
1201
- else if (entry.command === 'node') {
1660
+ else if (tableProblem) {
1661
+ // @implements A-SPEC-738 (round 7) — a setting the user file does not contain came from a layer
1662
+ // (measured: `<user file>: sets enabled = false … Remove the enabled = false line` for a trusted
1663
+ // project's setting).
1664
+ const own = ownHolmesTable(raw);
1665
+ const fromLayer = verdict.available && ((/enabled = false/.test(tableProblem.detail) && own?.enabled !== false)
1666
+ || (/sets enabled_tools = \[\]/.test(tableProblem.detail) && !(Array.isArray(own?.enabled_tools) && own.enabled_tools.length === 0))
1667
+ || (/governance tools/.test(tableProblem.detail) && (0, codex_oracle_1.hollowedGateTools)(own) === null)
1668
+ || (/environment_id/.test(tableProblem.detail) && (own?.environment_id === undefined || own.environment_id === null)));
1669
+ add('codex wiring', tableProblem.level, fromLayer ? `another layer — a trusted project's .codex/config.toml (or a profile) — ${tableProblem.detail}` : `${cdxToml}: ${tableProblem.detail}`, fromLayer ? 'Remove that setting from the layer (a .codex/config.toml in the workspace or an ancestor, or the profile), then restart Codex.' : tableProblem.fix);
1670
+ }
1671
+ else if ((0, codex_toml_1.codexHolmesDisabled)(raw)) {
1672
+ // @implements A-SPEC-727 (round 10) — Codex loads the table but starts nothing (measured PASS).
1673
+ add('codex wiring', 'FAIL', `${cdxToml} sets enabled = false in [mcp_servers.${init_1.SERVER_NAME}] — Codex does not start the Holmes MCP server`, `Remove the enabled = false line (or set it true) in ${cdxToml}, then restart Codex.`);
1674
+ }
1675
+ else if ((0, codex_oracle_1.launcherBase)(entry.command) === 'node') {
1202
1676
  // @implements A-SPEC-266 — "resolves to this install" is not enough on existence alone: a
1203
1677
  // node wiring must point at holmes-mcp.js. Passing any existing file (e.g. /etc/hosts) makes
1204
1678
  // the "resolves" claim stronger than the check (adversarial round, Finding 2). Verify the
1205
1679
  // basename too, to close that gap.
1206
1680
  const bin = entry.args[0] ?? '';
1681
+ // @implements A-SPEC-738 (round 15) — a network path is never opened (on Windows it contacts the host).
1207
1682
  // @implements A-SPEC-581.1 — against the TARGET, not the cwd.
1208
- const binAt = resolveWiringPath(target, bin);
1683
+ const binAt = (path.isAbsolute(bin) || path.win32.isAbsolute(bin)) ? bin : resolveWiringPath(target, bin);
1209
1684
  // Resolve the link before judging the name (round-2 F4): a symlink literally named
1210
1685
  // `holmes-mcp.js` pointing at /etc/hosts must not read as "resolves to this install".
1211
- const realBin = (() => { try {
1212
- return fs.realpathSync(binAt);
1686
+ // @implements A-SPEC-738 (round 18) — resolved by the walk that never looks a network path up.
1687
+ const walked = binAt === '' ? { path: null, refused: false } : (0, codex_oracle_1.openableLocalPath)(binAt) ? (0, codex_oracle_1.localRealpath)(binAt) : { path: null, refused: true };
1688
+ const network = walked.refused;
1689
+ const realBin = walked.path ?? '';
1690
+ const resolvesHere = realBin !== '' && path.basename(realBin) === 'holmes-mcp.js';
1691
+ // @implements A-SPEC-738 (round 15) — "this install" only for this install's entry; a layer's launch
1692
+ // of any other holmes-mcp.js is not this gate (it said "resolves to this install" — measured).
1693
+ const thisBin = (() => { try {
1694
+ return fs.realpathSync.native(path.join(packageRoot, 'bin', 'holmes-mcp.js'));
1213
1695
  }
1214
1696
  catch {
1215
1697
  return '';
1216
1698
  } })();
1217
- const resolvesHere = realBin !== '' && path.basename(realBin) === 'holmes-mcp.js';
1218
- add('codex wiring', resolvesHere ? 'PASS' : 'FAIL', resolvesHere ? `MCP wiring resolves to this install: ${bin}`
1219
- : (fs.existsSync(binAt) ? `MCP wiring points at a file that is not holmes-mcp.js: ${bin}` : `MCP wiring points at a missing file: ${bin}`), resolvesHere ? undefined : 'Run holmes-kit init --target <dir> --agent codex --force to refresh the absolute path.');
1699
+ const isThis = resolvesHere && realBin === thisBin;
1700
+ if (overridden && !isThis) {
1701
+ add('codex wiring', 'FAIL', network
1702
+ ? `another layer runs the Holmes server from a network path (${(0, codex_oracle_1.clipText)(bin)}), which doctor does not open`
1703
+ : `another layer runs a holmes-mcp.js that is not this install's: ${(0, codex_oracle_1.clipText)(bin)}${realBin !== '' && realBin !== bin ? ` (${(0, codex_oracle_1.clipText)(realBin)})` : ''}`, 'Remove the overriding [mcp_servers.holmes-kit] table from that layer, or rewire it with holmes-kit init --target <dir> --agent codex.');
1704
+ }
1705
+ else {
1706
+ add('codex wiring', resolvesHere ? 'PASS' : 'FAIL', resolvesHere ? (isThis ? `MCP wiring resolves to this install: ${(0, codex_oracle_1.clipText)(bin)}` : `MCP wiring resolves to holmes-mcp.js at ${(0, codex_oracle_1.clipText)(realBin)}: ${(0, codex_oracle_1.clipText)(bin)}`)
1707
+ : (network ? `MCP wiring points at a network path doctor does not open: ${(0, codex_oracle_1.clipText)(bin)}` : realBin !== '' ? `MCP wiring points at a file that is not holmes-mcp.js: ${(0, codex_oracle_1.clipText)(bin)}` : `MCP wiring points at a missing file: ${(0, codex_oracle_1.clipText)(bin)}`), resolvesHere ? undefined : 'Run holmes-kit init --target <dir> --agent codex --force to refresh the absolute path.');
1708
+ }
1220
1709
  }
1221
1710
  else {
1222
- const pin = (0, mcp_version_1.mcpLaunchVersion)({ command: entry.command, args: entry.args });
1711
+ const pin = (0, mcp_version_1.mcpLaunchVersion)({ command: (0, codex_oracle_1.launcherBase)(entry.command) ?? entry.command, args: entry.args });
1223
1712
  // @implements A-SPEC-569.4 — parity with the .mcp.json drift check (A-SPEC-251.2): a pin
1224
1713
  // that RESOLVES is not enough, because a stale pin quietly keeps launching yesterday's
1225
1714
  // gate. Same verdict function (non-semver pins like @latest judge 'unknown' → PASS, not
1226
1715
  // an inverted "stale" WARN), same fix shape; an unreadable pin stays FAIL as before.
1227
1716
  const cliVer = (0, mcp_launcher_1.readPackageVersion)(packageRoot); // same accessor as the .mcp.json check — one source of truth
1228
1717
  const drift = cliVer ? (0, mcp_version_1.versionDriftVerdict)(pin, cliVer) : 'unknown';
1229
- if (pin === null) {
1230
- add('codex wiring', 'FAIL', `cannot read a launch version from the wiring: ${entry.command} ${entry.args.join(' ')}`, 'Rewire with holmes-kit init --target <dir> --agent codex.');
1718
+ if (!entry.args.includes('holmes-mcp')) {
1719
+ // @implements A-SPEC-738 (round 15) — a pin passes only when npx runs holmes-mcp.
1720
+ add('codex wiring', 'FAIL', `the launch does not run holmes-mcp: ${(0, codex_oracle_1.launchText)(entry)}`, 'Rewire with holmes-kit init --target <dir> --agent codex.');
1721
+ }
1722
+ else if (pin === null) {
1723
+ add('codex wiring', 'FAIL', `cannot read a launch version from the wiring: ${(0, codex_oracle_1.launchText)(entry)}`, 'Rewire with holmes-kit init --target <dir> --agent codex.');
1231
1724
  }
1232
1725
  else if (drift === 'drift') {
1233
1726
  add('codex wiring', 'WARN', `resolves via the npx pin ${pin}, but this install is ${cliVer} — a stale pin keeps launching the old server`, 'Rewire with holmes-kit init --target <dir> --agent codex --force to refresh the pin.');
@@ -1262,18 +1755,26 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1262
1755
  const stopCmd = h.hooks?.Stop?.[0]?.command ?? '';
1263
1756
  const stale = [preCmd, stopCmd].filter((c) => {
1264
1757
  const p2 = (0, settings_merge_1.hookScriptPath)(c);
1265
- return !resolvesToPackage(p2, packageRoot);
1758
+ return !relativeScript(p2) && judge(p2) !== 'this' && judge(p2) !== 'unknown';
1266
1759
  });
1760
+ const unknownCdx = [preCmd, stopCmd].map((c) => (0, settings_merge_1.hookScriptPath)(c)).filter((p2) => !relativeScript(p2) && judge(p2) === 'unknown');
1761
+ const rel = [preCmd, stopCmd].map((c) => (0, settings_merge_1.hookScriptPath)(c)).filter(relativeScript);
1267
1762
  const installedPlugin = installedCodexPluginForTarget(target, opts?.readCodexPluginList);
1268
1763
  if (installedPlugin) {
1269
1764
  add('codex plugin install', 'PASS', 'The Holmes-Kit plugin snapshot is installed and enabled for this workspace. This proves new Codex sessions can load the plugin, not that the current live session already loaded its hooks.');
1270
1765
  }
1271
1766
  if (stale.length > 0) {
1272
- add('codex gate', 'FAIL', `hook command(s) not pointing at this install: ${stale.join(' | ')}`, 'Run holmes-kit init --target <dir> --agent codex --force to refresh the absolute paths.');
1767
+ add('codex gate', 'FAIL', `hook command(s) not pointing at this install: ${stale.map((c) => (0, codex_oracle_1.clipText)(c)).join(' | ')}`, 'Run holmes-kit init --target <dir> --agent codex --force to refresh the absolute paths.');
1273
1768
  }
1274
1769
  else if (manifest.hooks !== './hooks.json') {
1275
1770
  // The one path measured to load. `./hooks/hooks.json` parses fine and never fires.
1276
- add('codex gate', 'FAIL', `the plugin manifest's hooks is not './hooks.json': ${String(manifest.hooks)} — Codex does not load it`, 'Rewire with holmes-kit init --target <dir> --agent codex --force.');
1771
+ add('codex gate', 'FAIL', `the plugin manifest's hooks is not './hooks.json': ${(0, codex_oracle_1.clipText)(String(manifest.hooks))} — Codex does not load it`, 'Rewire with holmes-kit init --target <dir> --agent codex --force.');
1772
+ }
1773
+ else if (rel.length > 0) {
1774
+ add('codex gate', 'WARN', relativeDetail(rel), 'Rewire with holmes-kit init --target <dir> --agent codex --force to write absolute paths.');
1775
+ }
1776
+ else if (unknownCdx.length > 0) {
1777
+ add('codex gate', 'WARN', UNKNOWN_DETAIL(unknownCdx), 'Rewire with holmes-kit init --target <dir> --agent codex --force.');
1277
1778
  }
1278
1779
  else if (!fs.existsSync(cdxMarketplaceNew)) {
1279
1780
  // @implements A-SPEC-533.3 — hooks are correct, but the marketplace manifest is only at
@@ -1284,7 +1785,7 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1284
1785
  else {
1285
1786
  add('codex gate', 'WARN', installedPlugin
1286
1787
  ? 'The installed plugin is available to new Codex sessions, but this process cannot prove that the current live session loaded its hooks.'
1287
- : 'The plugin wiring is correct — but the gate is not enforced until it is installed (Codex only loads plugins from an installed marketplace, and doctor cannot verify installation offline)', installedPlugin ? 'Start a new Codex session in this workspace and run workspace_preflight.' : `Run ${installCmds}, then use it in a new session.`);
1788
+ : 'The plugin wiring is correct for codex-cli ≤0.154 — there the gate is not enforced until the plugin is installed (Codex only loads plugins from an installed marketplace, and doctor cannot verify installation offline). codex-cli 0.155+ does not load plugin hooks at all; see `codex user hooks`.', installedPlugin ? 'Start a new Codex session in this workspace and run workspace_preflight.' : `Run ${installCmds}, then use it in a new session.`);
1288
1789
  }
1289
1790
  }
1290
1791
  catch {
@@ -1300,7 +1801,140 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1300
1801
  add('codex wiring', 'WARN', `codex wiring sits in a legacy location Codex does not read (${cdxJson}); the active entry belongs in ${cdxToml}`, `Run holmes-kit init --target <dir> --agent codex to write the active entry to ${cdxToml}; it leaves the legacy file in place for you to delete.`);
1301
1802
  }
1302
1803
  else if (targetWantsCodex) {
1303
- add('codex wiring', 'WARN', `this workspace is wired for Codex, but ${cdxToml} (the config Codex loads) has no [mcp_servers.${init_1.SERVER_NAME}] entry — Holmes MCP tools are not active in Codex sessions`, 'Run holmes-kit init --target <dir> --agent codex.');
1804
+ // @implements A-SPEC-738 (round 14) — a Holmes table only a layer provides is judged, not reported "not
1805
+ // active" (measured: a trusted layer's table with a forged HOLMES_APPROVAL read as "not active").
1806
+ const v = codexVerdict();
1807
+ const layerTable = v.available ? v.holmesTable : null;
1808
+ const authority = v.available && (layerTable !== null || (v.otherHolmesServers ?? []).length > 0)
1809
+ ? judgeEffectiveCodex(v, typeof cdxRaw === 'string' ? cdxRaw : null, null) : [];
1810
+ if (authority.length > 0) {
1811
+ add('codex wiring', 'FAIL', `another layer — a trusted project's .codex/config.toml (or a profile) — hands a Holmes server Codex runs here an approval, autonomy, gate or egress-consent channel, or a launch or environment holmes-kit cannot judge: ${(0, codex_oracle_1.cappedList)(authority)} (judged by Codex)`, 'Remove those settings from that layer (a .codex/config.toml in the workspace or an ancestor, or the profile), then restart Codex.');
1812
+ }
1813
+ else if (layerTable !== null) {
1814
+ // @implements A-SPEC-738 (round 19) — clipped (a 900 KB launch made a 900 KB WARN — measured).
1815
+ const cmd = (0, codex_oracle_1.launchText)(layerTable);
1816
+ add('codex wiring', 'WARN', `this workspace is wired for Codex, and Codex runs a [mcp_servers.${init_1.SERVER_NAME}] entry that another layer — a trusted project's .codex/config.toml (or a profile) — provides (\`${cmd}\`); ${cdxToml} has none, so the entry Codex runs is not this install's wiring`, 'Run holmes-kit init --target <dir> --agent codex so the user file carries the entry, or remove the table from that layer.');
1817
+ }
1818
+ else {
1819
+ add('codex wiring', 'WARN', `this workspace is wired for Codex, but ${cdxToml} (the config Codex loads) has no [mcp_servers.${init_1.SERVER_NAME}] entry — Holmes MCP tools are not active in Codex sessions`, 'Run holmes-kit init --target <dir> --agent codex.');
1820
+ }
1821
+ }
1822
+ // @implements A-SPEC-727 — codex-cli 0.155 loads the gate from the user-level hooks file, and runs
1823
+ // it only after the user trusts it once. Trust lives inside Codex and cannot be observed offline,
1824
+ // so "present" is never a PASS: the one step Holmes cannot take is named instead.
1825
+ {
1826
+ const hooksPath = cdxHooksPath;
1827
+ let hooksRaw = null;
1828
+ let unreadable = false;
1829
+ let undecodable = false;
1830
+ try {
1831
+ if (fs.existsSync(hooksPath)) {
1832
+ // @implements A-SPEC-727 (round 6) — strict UTF-8, as Codex reads it.
1833
+ const d = (0, codex_hooks_1.decodeCodexHooksBytes)(fs.readFileSync(hooksPath));
1834
+ if (d.ok)
1835
+ hooksRaw = d.text;
1836
+ else
1837
+ undecodable = true;
1838
+ }
1839
+ }
1840
+ catch {
1841
+ unreadable = true;
1842
+ }
1843
+ const state = undecodable ? { state: 'invalid', reason: 'not valid UTF-8' }
1844
+ : hooksRaw === null ? null : (0, codex_hooks_1.inspectCodexUserHooks)(hooksRaw);
1845
+ // @implements A-SPEC-738 — Codex drops a hooks file it cannot parse whole (and lists no hook when it
1846
+ // refuses config.toml): its own message decides, before any reading of ours.
1847
+ const hookVerdict = hooksRaw !== null || targetWantsCodex || unreadable || undecodable ? codexVerdict() : undefined;
1848
+ if (hookVerdict?.available && (hookVerdict.otherHookProblems ?? []).length > 0) {
1849
+ add('codex other hooks', 'WARN', `Codex could not load another hooks source (not the Holmes gate): ${(0, codex_oracle_1.cappedList)((hookVerdict.otherHookProblems ?? []).map((e) => e.trim()))}`, 'Fix that file by hand; the Holmes gate in the user hooks file is judged separately.');
1850
+ }
1851
+ // @implements A-SPEC-738 (round 2) — a hook disabled in /hooks is keyed by the REAL hooks path in
1852
+ // config.toml, so a copy cannot show it (measured): read it from the user's config.
1853
+ const disabledHere = (0, codex_oracle_1.holmesPreToolDisabled)(typeof cdxRaw === 'string' ? cdxRaw : null, hooksRaw, hooksPath);
1854
+ const configRefusal = hookVerdict?.available ? (hookVerdict.configError ?? hookVerdict.otherConfigError ?? null) : null;
1855
+ if (configRefusal !== null && configRefusal !== undefined) {
1856
+ // Round 6: the fix names the layer where the refusal is the layer's.
1857
+ const layerFix = hookVerdict?.available && hookVerdict.configError === null
1858
+ ? `Fix ${(0, codex_oracle_1.layerFileNamed)(configRefusal) ?? 'the .codex/config.toml in the workspace or an ancestor that Codex refuses'} by hand, then re-run holmes-kit doctor.`
1859
+ : `Fix ${opts?.codexConfigPath ?? (0, codex_toml_1.defaultCodexConfigPath)()} by hand, then re-run holmes-kit doctor.`;
1860
+ add('codex user hooks', 'FAIL', `Codex refuses the configuration, so it lists no hooks at all: ${(0, codex_oracle_1.clipText)(configRefusal.trim(), 600)}`, layerFix);
1861
+ }
1862
+ else if (hookVerdict?.available && hookVerdict.hookErrors.length > 0) {
1863
+ add('codex user hooks', 'FAIL', `Codex does not load the Holmes gate: ${(0, codex_oracle_1.cappedList)(hookVerdict.hookErrors.map((e) => e.trim()))}`, `Fix ${hookVerdict.hookErrors.some((e) => /config\.toml/i.test(e)) ? (opts?.codexConfigPath ?? (0, codex_toml_1.defaultCodexConfigPath)()) : hooksPath} by hand (or run holmes-kit init --target <dir> --agent codex), then trust the hooks once with /hooks in codex.`);
1864
+ }
1865
+ else if (unreadable || state?.state === 'invalid') {
1866
+ add('codex user hooks', 'FAIL', `${hooksPath} cannot be read${state?.state === 'invalid' ? ` (${state.reason})` : ''} — Codex cannot load the Holmes gate from it`, 'Fix or remove the file, then run holmes-kit init --target <dir> --agent codex.');
1867
+ }
1868
+ else if (state?.state === 'wired') {
1869
+ // The file is user-level: whichever install last ran init owns every workspace's gate, so a
1870
+ // path to another (or a deleted) install is named, as the plugin and Claude checks do.
1871
+ const stale = state.all.filter((p2) => !resolvesToPackage(p2, packageRoot));
1872
+ // Another install of the SAME holmes-kit version (a second npx cache, global vs npx) runs the
1873
+ // same gate — but only if it IS holmes-kit and its kernel file is there.
1874
+ const pkgOf = (root) => {
1875
+ try {
1876
+ return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
1877
+ }
1878
+ catch {
1879
+ return null;
1880
+ }
1881
+ };
1882
+ const ours = pkgOf(packageRoot);
1883
+ const sameVersion = stale.length > 0 && ours?.version !== undefined
1884
+ && stale.every((p2) => {
1885
+ // A-SPEC-251.2 round 37: a network path is not looked up (read as another install).
1886
+ const walkedP2 = (0, codex_oracle_1.localRealpath)(path.resolve(p2));
1887
+ if (walkedP2.refused || walkedP2.path === null)
1888
+ return false;
1889
+ const theirs = pkgOf(path.resolve(path.dirname(walkedP2.path), '..', '..', '..'));
1890
+ return theirs?.name === ours.name && theirs?.version === ours.version;
1891
+ });
1892
+ // Every finding is reported; the most severe level wins (one must not hide another).
1893
+ const issues = [];
1894
+ if (stale.length > 0) {
1895
+ issues.push({ level: sameVersion || !targetWantsCodex ? 'WARN' : 'FAIL',
1896
+ text: `hook command(s) in ${hooksPath} not pointing at this install${sameVersion ? ` (another install of the same version ${ours?.version})` : ''}: ${stale.map((c) => (0, codex_oracle_1.clipText)(c)).join(' | ')}`,
1897
+ fix: 'Run holmes-kit init --target <dir> --agent codex to point them at this install, then trust them once with /hooks in codex.' });
1898
+ }
1899
+ if (disabledHere) {
1900
+ issues.push({ level: 'FAIL', text: `the Holmes PreToolUse hook from ${hooksPath} is disabled in ${opts?.codexConfigPath ?? (0, codex_toml_1.defaultCodexConfigPath)()} ([hooks.state] enabled = false) — tool calls are not gated`,
1901
+ fix: 'Re-enable it with /hooks in codex.' });
1902
+ }
1903
+ else if (hookVerdict?.available && !hookVerdict.hooks.some((h) => h.enabled && /^pre_?tool_?use$/i.test(h.event) && (0, codex_oracle_1.isHolmesPreToolCommand)(h.command))) {
1904
+ issues.push({ level: 'FAIL', text: `Codex lists no enabled Holmes PreToolUse hook from ${hooksPath} — hooks switched off (e.g. [features] hooks = false), or a matcher or entry Codex drops — so tool calls are not gated`,
1905
+ fix: 'Run holmes-kit init --target <dir> --agent codex, then trust the hooks once with /hooks in codex.' });
1906
+ }
1907
+ else if (state.preToolUse.length === 0) {
1908
+ issues.push({ level: 'FAIL', text: `${hooksPath} has Holmes hooks but no pre-tool-use kernel under PreToolUse — tool calls are not gated`,
1909
+ fix: 'Run holmes-kit init --target <dir> --agent codex, then trust the hooks once with /hooks in codex.' });
1910
+ }
1911
+ const narrowed = state.preMatchers.filter((m) => m !== '.*');
1912
+ if (narrowed.length > 0) {
1913
+ issues.push({ level: 'WARN', text: `the Holmes PreToolUse matcher in ${hooksPath} is ${narrowed.map((m) => (m === '' ? '(none)' : (0, codex_oracle_1.clipText)(m, 80))).join(' | ')}, not the shipped .* — a tool the matcher does not catch never reaches the gate`,
1914
+ fix: 'Run holmes-kit init --target <dir> --agent codex to restore it, then trust it again with /hooks in codex.' });
1915
+ }
1916
+ if (issues.length > 0) {
1917
+ add('codex user hooks', issues.some((i) => i.level === 'FAIL') ? 'FAIL' : 'WARN', issues.map((i) => i.text).join('; '), issues.map((i) => i.fix).filter((f, i, a) => a.indexOf(f) === i).join(' '));
1918
+ }
1919
+ else {
1920
+ add('codex user hooks', 'WARN', `the Holmes gate hooks are wired in ${hooksPath}, but Codex runs a hook only after you trust it once, and doctor cannot verify that trust offline`, 'Open codex and run /hooks, then trust the holmes-kit PreToolUse and Stop hooks.');
1921
+ }
1922
+ }
1923
+ else if (targetWantsCodex) {
1924
+ add('codex user hooks', 'WARN', `this workspace is wired for Codex, but ${hooksPath} has no Holmes gate hook — codex-cli 0.155 no longer loads plugin hooks, so tool calls are not gated`, 'Run holmes-kit init --target <dir> --agent codex, then trust the hooks once with /hooks in codex.');
1925
+ }
1926
+ }
1927
+ // @implements A-SPEC-738 — every Codex load verdict says whose it is.
1928
+ {
1929
+ const lines = checks.slice(codexChecksFrom).filter((c) => c.name === 'codex wiring' || c.name === 'codex user hooks');
1930
+ if (lines.length > 0) {
1931
+ const v = codexVerdict();
1932
+ const label = v.available ? ' (judged by Codex)' : ` (approximate — holmes-kit's own reading: ${v.reason})`;
1933
+ // Round 14: a detail that already says so is not labelled twice.
1934
+ for (const c of lines)
1935
+ if (!c.detail.trimEnd().endsWith('(judged by Codex)'))
1936
+ c.detail += label;
1937
+ }
1304
1938
  }
1305
1939
  try {
1306
1940
  const sp = wiredSettingsPath(target);
@@ -1311,7 +1945,7 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1311
1945
  const drifted = wired.filter((m) => m !== init_1.MATCHERS.guardrail);
1312
1946
  add('hook matcher', drifted.length === 0 ? 'PASS' : 'WARN', drifted.length === 0
1313
1947
  ? `The wired matcher equals the shipped default (${init_1.MATCHERS.guardrail})`
1314
- : `wired ${drifted.join(' | ')} / shipped default ${init_1.MATCHERS.guardrail} — a tool the matcher does not catch never reaches the hook`, drifted.length === 0 ? undefined : 'Run holmes-kit init --target <dir> --force to refresh it, and restart Claude Code.');
1948
+ : `wired ${drifted.slice(0, 10).map((m) => (0, codex_oracle_1.clipText)(String(m), 80)).join(' | ')}${drifted.length > 10 ? ` and ${drifted.length - 10} more` : ''} / shipped default ${init_1.MATCHERS.guardrail} — a tool the matcher does not catch never reaches the hook`, drifted.length === 0 ? undefined : 'Run holmes-kit init --target <dir> --force to refresh it, and restart Claude Code.');
1315
1949
  }
1316
1950
  catch { /* an unreadable settings file is `target wiring`'s business, not this check's */ }
1317
1951
  }
@@ -1325,10 +1959,11 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1325
1959
  // and this check was a permanent WARN on every Windows machine. npm's own JS entry run with
1326
1960
  // THIS node binary removes the shim; when no entry is found (e.g. Homebrew's Cellar layout —
1327
1961
  // measured), the plain name keeps today's POSIX behavior, where there is no .cmd problem.
1328
- const npmCli = npmCliEntry();
1962
+ const npmCli = npmCliEntry(process.env, process.execPath, probeContext(target ?? process.cwd()).keep);
1963
+ // @implements A-SPEC-734 (round 13) — bounded like `observe` (a FIFO `.npmrc` hung doctor past 120 s — measured).
1329
1964
  const prefix = (npmCli !== null
1330
- ? (0, node_child_process_1.execFileSync)(process.execPath, [npmCli, 'config', 'get', 'prefix'], { encoding: 'utf8' })
1331
- : (0, node_child_process_1.execFileSync)('npm', ['config', 'get', 'prefix'], { encoding: 'utf8' })).trim();
1965
+ ? (0, node_child_process_1.execFileSync)(process.execPath, [npmCli, 'config', 'get', 'prefix', ...NPM_QUIET], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], cwd: npmHome() })
1966
+ : (0, node_child_process_1.execFileSync)('npm', ['config', 'get', 'prefix', ...NPM_QUIET], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], cwd: npmHome() })).trim();
1332
1967
  const dir = globalInstallDir(prefix, process.platform);
1333
1968
  let probe = dir;
1334
1969
  while (!fs.existsSync(probe)) {
@@ -1440,6 +2075,22 @@ function cleanupOnSignal(dir) {
1440
2075
  // harness will actually run reaches a server — the gap the dead npx form lived in.
1441
2076
  // @implements A-SPEC-499.1 — exported for the prescription tests; `platform` is injectable so the
1442
2077
  // win32 branch is testable off-Windows.
2078
+ /**
2079
+ * @implements A-SPEC-251.2 (round 50) — one launch (same command, arguments and directory) is started once in a doctor run and
2080
+ * its answer shared: an npx wiring that cannot reach the registry was waited on for 30 s by the handshake and again by the
2081
+ * spawn check, and once more per harness (61.6 s for one agent — measured).
2082
+ */
2083
+ const wiringSpawns = new Map();
2084
+ function resetWiringSpawns() { wiringSpawns.clear(); }
2085
+ function wiringSpawnShared(command, args, cwd) {
2086
+ const key = JSON.stringify([command, args, cwd]);
2087
+ let answer = wiringSpawns.get(key);
2088
+ if (answer === undefined) {
2089
+ answer = wiringSpawnCheck(command, args, undefined, undefined, cwd);
2090
+ wiringSpawns.set(key, answer);
2091
+ }
2092
+ return answer.then((c) => ({ ...c }));
2093
+ }
1443
2094
  function wiringSpawnCheck(command, args, timeoutMs = 30000, platform = process.platform,
1444
2095
  // @implements A-SPEC-581.1 — the directory the wiring is launched FROM. A harness starts the
1445
2096
  // server in the project, so a relative arg (`bin/holmes-mcp.js`, the .mcp.json convention)
@@ -1448,11 +2099,14 @@ function wiringSpawnCheck(command, args, timeoutMs = 30000, platform = process.p
1448
2099
  cwd) {
1449
2100
  // The DISPLAYED command stays the original wiring string even when the win32 adapter rewraps the
1450
2101
  // execution — the user compares this against their wiring file, not against cmd.exe plumbing.
1451
- const quoted = `${command} ${args.join(' ')}`;
2102
+ const quoted = (0, codex_oracle_1.clipText)(`${command} ${args.join(' ')}`); // round 23: a 64 KB path made a 64 KB line
1452
2103
  // @implements A-SPEC-499.1 — Windows field measurement: four wiring checks on a correctly rewired
1453
2104
  // 0.3.1 target all died `spawn npx ENOENT`, because `npx` is `npx.cmd` there and a plain spawn
1454
2105
  // cannot execute a .cmd shim. The adapter reroutes through cmd.exe; posix is value-identical.
1455
- const spec = (0, spawn_spec_1.spawnSpecFor)(command, args, platform);
2106
+ // Round 52 (repair): never a bare word — see `probeSpawn`.
2107
+ const context = probeContext(cwd ?? process.cwd());
2108
+ // Tenth repair (owner decision): only node launches reach here — an npx wiring is judged by its shape and never started.
2109
+ const spec = probeSpawn(command, args, cwd ?? process.cwd(), { platform, ownInside: context.ownInside, keep: context.keep });
1456
2110
  // The re-init prescription is only honest when the wiring might actually be stale. A command the
1457
2111
  // OS cannot find (ENOENT) re-inits into the identical failure forever — the measured loop.
1458
2112
  const enoentFix = `The \`${command}\` command was not found (PATH or platform) — if the wiring string is correct, re-init does not help. Run the same command directly in a shell to check.`;
@@ -1474,8 +2128,15 @@ cwd) {
1474
2128
  fix: `${fix ?? ''} Close the remaining diagnostic process for \`${command}\`, then retry doctor.` }));
1475
2129
  };
1476
2130
  const timer = setTimeout(() => finish('FAIL', `wiring did not answer initialize within ${timeoutMs / 1000}s: \`${quoted}\``, `Re-run \`holmes-kit init\` in the target to rewrite the wiring for \`${command}\`, then re-run doctor.`), timeoutMs);
2131
+ if (spec === null) {
2132
+ finish('FAIL', `wiring could not be spawned: \`${quoted}\` — ${probeRefusal(command, args, cwd ?? process.cwd(), { platform, ownInside: context.ownInside, keep: context.keep }) ?? 'nothing to start'}`, enoentFix);
2133
+ return;
2134
+ }
1477
2135
  try {
1478
- child = (0, node_child_process_1.spawn)(spec.command, spec.args, { ...probe_process_1.PROBE_SPAWN_OPTIONS, stdio: ['pipe', 'pipe', 'pipe'], ...(cwd === undefined ? {} : { cwd }) });
2136
+ // @implements A-SPEC-251.2 (confirmation round 25) — a probe must not phone home: the server a handshake starts
2137
+ // ran its detached update refresh, a direct GET to registry.npmjs.org, eleven times in one probe run (measured).
2138
+ // Round 52: every probe has doctor's node's directory first in PATH, so a bare `node` is doctor's own.
2139
+ child = (0, node_child_process_1.spawn)(spec.file, spec.args, { ...probe_process_1.PROBE_SPAWN_OPTIONS, ...(spec.verbatim === true ? { windowsVerbatimArguments: true } : {}), stdio: ['pipe', 'pipe', 'pipe'], env: { ...(0, mcp_launcher_1.probeEnv)(process.env, platform, context.keep), HOLMES_NO_UPDATE_CHECK: '1' }, ...(cwd === undefined ? {} : { cwd }) });
1479
2140
  (0, probe_process_1.trackProbeProcess)(child);
1480
2141
  }
1481
2142
  catch (e) {
@@ -1517,7 +2178,15 @@ cwd) {
1517
2178
  child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'holmes-doctor', version: '1' } } }) + '\n');
1518
2179
  });
1519
2180
  }
1520
- function mcpHandshakeCheck(packageRoot, timeoutMs = 15000) {
2181
+ /**
2182
+ * @implements A-SPEC-251.2 (round 52, fourth repair) — the environment of the 'MCP server' probe's child: the wiring
2183
+ * probes' PATH (doctor's node's directory, then the absolute entries outside the workspace). With the environment handed
2184
+ * over as it was, the server's supervisor (`HOLMES_MCP_AUTORELOAD=1`) started the `node` the workspace had put on PATH.
2185
+ */
2186
+ function mcpProbeEnv(env, target, platform = process.platform) {
2187
+ return { ...(0, mcp_launcher_1.probeEnv)(env, platform, probeContext(target).keep), HOLMES_NO_UPDATE_CHECK: '1' };
2188
+ }
2189
+ function mcpHandshakeCheck(packageRoot, target, timeoutMs = 15000) {
1521
2190
  return new Promise((resolve) => {
1522
2191
  const mcpCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'holmes-doctor-mcp-'));
1523
2192
  let child;
@@ -1551,7 +2220,7 @@ function mcpHandshakeCheck(packageRoot, timeoutMs = 15000) {
1551
2220
  };
1552
2221
  cleanupOnSignal(mcpCwd);
1553
2222
  try {
1554
- child = (0, node_child_process_1.spawn)(process.execPath, [path.join(packageRoot, 'bin', 'holmes-mcp.js')], { ...probe_process_1.PROBE_SPAWN_OPTIONS, stdio: ['pipe', 'pipe', 'pipe'], cwd: mcpCwd });
2223
+ child = (0, node_child_process_1.spawn)(process.execPath, [path.join(packageRoot, 'bin', 'holmes-mcp.js')], { ...probe_process_1.PROBE_SPAWN_OPTIONS, stdio: ['pipe', 'pipe', 'pipe'], env: mcpProbeEnv(process.env, target), cwd: mcpCwd });
1555
2224
  (0, probe_process_1.trackProbeProcess)(child);
1556
2225
  }
1557
2226
  catch (error) {
@@ -1687,14 +2356,14 @@ function ciMatrixCheck(target) {
1687
2356
  const runs = (0, ci_runs_1.readCiRuns)(target);
1688
2357
  let head;
1689
2358
  try {
1690
- head = (0, node_child_process_1.execFileSync)('git', ['rev-parse', 'HEAD'], { cwd: target, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
2359
+ head = (0, node_child_process_1.execFileSync)('git', ['rev-parse', 'HEAD'], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, cwd: target, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
1691
2360
  }
1692
2361
  catch {
1693
2362
  head = undefined;
1694
2363
  }
1695
2364
  const behind = (rev) => {
1696
2365
  try {
1697
- return Number((0, node_child_process_1.execFileSync)('git', ['rev-list', '--count', `${rev}..HEAD`], { cwd: target, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());
2366
+ return Number((0, node_child_process_1.execFileSync)('git', ['rev-list', '--count', `${rev}..HEAD`], { timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER, cwd: target, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());
1698
2367
  }
1699
2368
  catch {
1700
2369
  return undefined;
@@ -1710,10 +2379,21 @@ function ciMatrixCheck(target) {
1710
2379
  return null;
1711
2380
  } // diagnosis must never crash doctor
1712
2381
  }
2382
+ /**
2383
+ * @implements A-SPEC-251.2 (round 43) — no control character from a file reaches the terminal (an `env` key holding ESC and BEL
2384
+ * retitled it and cleared the screen — measured); line breaks and tabs stay. `--json` escapes them already.
2385
+ */
2386
+ // Round 44: also the line separators and the bidirectional controls (U+2028 and U+202E reached the terminal — measured).
2387
+ const terminalSafe = (s) => s.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
2388
+ exports.terminalSafe = terminalSafe;
2389
+ /** Round 44: `--json` — JSON.stringify leaves C1 and the line separators raw; they are escaped as JSON escapes. */
2390
+ function checksJson(checks) {
2391
+ return JSON.stringify(checks, null, 2).replace(/[\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
2392
+ }
1713
2393
  function formatChecks(checks) {
1714
2394
  const lines = checks.map((c) => {
1715
- const head = `${c.level.padEnd(4)} ${c.name} — ${c.detail}`;
1716
- return c.fix && c.level !== 'PASS' ? `${head}\n fix: ${c.fix}` : head;
2395
+ const head = `${c.level.padEnd(4)} ${c.name} — ${(0, exports.terminalSafe)(c.detail)}`;
2396
+ return c.fix && c.level !== 'PASS' ? `${head}\n fix: ${(0, exports.terminalSafe)(c.fix)}` : head;
1717
2397
  });
1718
2398
  const fails = checks.filter((c) => c.level === 'FAIL').length;
1719
2399
  const warns = checks.filter((c) => c.level === 'WARN').length;
@@ -1749,7 +2429,8 @@ function codexWiredTarget(target) {
1749
2429
  || fs.existsSync(path.join(target, '.codex', 'config.toml'))
1750
2430
  || fs.existsSync(path.join(target, '.codex', 'mcp_config.json'));
1751
2431
  }
1752
- async function wiringHandshakeChecks(target, codexConfigPath = (0, codex_toml_1.defaultCodexConfigPath)()) {
2432
+ /** The Holmes wirings of the three harnesses, read the way the handshake reads them (nothing is started). */
2433
+ function holmesWirings(target, codexConfigPath) {
1753
2434
  const wirings = [
1754
2435
  {
1755
2436
  label: 'claude', file: path.join(target, '.mcp.json'),
@@ -1769,7 +2450,6 @@ async function wiringHandshakeChecks(target, codexConfigPath = (0, codex_toml_1.
1769
2450
  // An absent wiring is not a dead one — the harness simply is not wired here.
1770
2451
  if (!fs.existsSync(wiring.file))
1771
2452
  continue;
1772
- const name = `${wiring.label} wiring handshake`;
1773
2453
  let raw = null;
1774
2454
  try {
1775
2455
  raw = fs.readFileSync(wiring.file, 'utf8');
@@ -1788,23 +2468,535 @@ async function wiringHandshakeChecks(target, codexConfigPath = (0, codex_toml_1.
1788
2468
  catch {
1789
2469
  entry = null;
1790
2470
  }
2471
+ out.push({ label: wiring.label, file: wiring.file, entry });
2472
+ }
2473
+ return out;
2474
+ }
2475
+ /**
2476
+ * @implements A-SPEC-251.2 (0.31.0) — each harness whose Holmes wiring runs npx gets a WARN: npx runs npm in every
2477
+ * session workspace, and that workspace's .npmrc (node-options, registry) and node_modules replaced the server
2478
+ * (measured 2026-09-25/26). A node wiring gets no line.
2479
+ */
2480
+ function wiringLauncherChecks(target, codexConfigPath = (0, codex_toml_1.defaultCodexConfigPath)()) {
2481
+ const out = [];
2482
+ for (const { label, entry } of holmesWirings(target, codexConfigPath)) {
2483
+ if (entry === null || !runsThroughNpm(entry))
2484
+ continue;
2485
+ out.push({ name: `${label} wiring launcher`, level: 'WARN',
2486
+ detail: `The ${label} wiring starts the Holmes server through a package runner (\`${(0, codex_oracle_1.launchText)(entry)}\`), which resolves the package in each session workspace: that workspace's .npmrc (node-options, registry) and node_modules can replace the server`,
2487
+ fix: `Install holmes-kit (npm install -g @holmes-lab/holmes-kit, or as a devDependency), then run holmes-kit init --target <dir> --agent ${label} --force — the wiring becomes node <install>/bin/holmes-mcp.js.` });
2488
+ }
2489
+ return out;
2490
+ }
2491
+ /**
2492
+ * @implements A-SPEC-251.2 — whether a launch runs the server through a package runner that reads the session
2493
+ * workspace's npm configuration and `node_modules`: any spelling of npx on any OS (a wiring written on Windows is
2494
+ * committed and read elsewhere), `bunx`, `npm exec`/`npm x`, `pnpm dlx`/`pnpm exec`, `yarn dlx`, and `cmd /c npx …`
2495
+ * (confirmation round 22: these got no WARN).
2496
+ */
2497
+ function runsThroughNpm(entry) {
2498
+ // Round 23: iterative over the first 64 words (a recursion on `cmd /c` overflowed the stack at 8,000 levels), words
2499
+ // split on spaces (`cmd /c "npx -y …"` is one string), a runner found anywhere (`cmd /d /c npx`, `env npx`), and a
2500
+ // package manager's exec verb found past its options (`npm --yes exec`, `bun x`) — confirmation round 23, measured.
2501
+ const words = [];
2502
+ for (const w of [entry.command, ...entry.args]) {
2503
+ for (const part of String(w).slice(0, 4096).split(/\s+/)) {
2504
+ if (part !== '')
2505
+ words.push(part);
2506
+ if (words.length >= 64)
2507
+ break;
2508
+ }
2509
+ if (words.length >= 64)
2510
+ break;
2511
+ }
2512
+ const base = (w) => (w.split(/[\\/]/).pop() ?? '').toLowerCase().replace(/^["']|["']$/g, '').replace(/\.(?:cmd|exe|ps1)$/, '');
2513
+ for (let i = 0; i < words.length; i++) {
2514
+ const b = base(words[i]);
2515
+ if (b === 'npx' || b === 'bunx' || b === 'pnpx')
2516
+ return true;
2517
+ if (b === 'npm' || b === 'pnpm' || b === 'yarn' || b === 'bun') {
2518
+ let j = i + 1;
2519
+ while (j < words.length && words[j].startsWith('-'))
2520
+ j++;
2521
+ const verb = (words[j] ?? '').toLowerCase();
2522
+ if (verb === 'exec' || verb === 'x' || verb === 'dlx')
2523
+ return true;
2524
+ }
2525
+ }
2526
+ return false;
2527
+ }
2528
+ /**
2529
+ * @implements A-SPEC-251.2 (confirmation round 22) — the version a Codex or Antigravity wiring launches, against this
2530
+ * CLI (Claude's `.mcp.json` has its own 'mcp server version' line). Codex and Antigravity node wirings pointing at a
2531
+ * 0.20.0 install read PASS or nothing (measured). Offline: the pin, or the local package.json above the node bin.
2532
+ */
2533
+ function wiringVersionChecks(target, codexConfigPath = (0, codex_toml_1.defaultCodexConfigPath)(), cliVersion) {
2534
+ const readPkgVersionAt = (dir) => {
2535
+ if (!(0, codex_oracle_1.openableLocalPath)(dir) || (0, codex_oracle_1.localRealpath)(path.join(dir, 'package.json')).refused)
2536
+ return undefined; // A-SPEC-251.2 rounds 35–37: never a network path, the file itself included
2537
+ try {
2538
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
2539
+ return pkg?.name === '@holmes-lab/holmes-kit' && typeof pkg.version === 'string' ? pkg.version : undefined;
2540
+ }
2541
+ catch {
2542
+ return undefined;
2543
+ }
2544
+ };
2545
+ const out = [];
2546
+ for (const { label, entry } of holmesWirings(target, codexConfigPath)) {
2547
+ if (label === 'claude' || entry === null)
2548
+ continue;
2549
+ const base = (0, codex_oracle_1.launcherBase)(entry.command) ?? entry.command;
2550
+ // Codex's npx pin already has its drift line under 'codex wiring' (A-SPEC-569.4).
2551
+ if (label === 'codex' && base !== 'node')
2552
+ continue;
2553
+ const args = base === 'node' && entry.args.length > 0 ? [resolveWiringPath(target, entry.args[0]), ...entry.args.slice(1)] : entry.args;
2554
+ const launch = (0, mcp_version_1.mcpLaunchVersion)({ command: base, args }, readPkgVersionAt);
2555
+ const verdict = (0, mcp_version_1.versionDriftVerdict)(launch, cliVersion);
2556
+ if (verdict === 'drift') {
2557
+ out.push({ name: `${label} mcp server version`, level: 'WARN',
2558
+ detail: `The ${label} wiring launches holmes-kit ${(0, codex_oracle_1.clipText)(String(launch), 40)}, but this CLI is ${cliVersion} — the old server keeps starting until it is rewired`,
2559
+ fix: `Run holmes-kit init --target <dir> --agent ${label} --force from the install you mean to use.` });
2560
+ }
2561
+ else if (verdict === 'match')
2562
+ out.push({ name: `${label} mcp server version`, level: 'PASS', detail: `MCP server version ${launch} matches this CLI` });
2563
+ }
2564
+ return out;
2565
+ }
2566
+ /**
2567
+ * @implements A-SPEC-251.2 (round 33) — whether a path's walk passes through a process-dependent directory, taken one
2568
+ * component at a time (empty and `.` components skipped, `..` from the real path so far): `//proc/…`, `/usr/../proc/…`,
2569
+ * `/./proc/…` and `//dev/fd/../cwd/…` passed round 32's text check and ran a wrapper (Linux — measured).
2570
+ */
2571
+ function passesThroughProcess(w) {
2572
+ let cur = '/';
2573
+ // @implements A-SPEC-251.2 (round 45) — one walk budget for the whole command: each `..` walked the path so far again, and 300
2574
+ // `L/..` pairs through a self-looping link held doctor for 26.8 s (measured). Past it the command is process-dependent (never run).
2575
+ const budget = { left: 16_384 };
2576
+ for (const comp of w.split('/')) {
2577
+ if (comp === '' || comp === '.')
2578
+ continue;
2579
+ // Round 35: the real path so far is walked without network lookups; a network path is read as process-dependent (never run).
2580
+ if (comp === '..') {
2581
+ const walked = (0, claude_switches_1.localPhysicalRealpath)(cur, budget);
2582
+ if (walked.refused || walked.exhausted || budget.left <= 0)
2583
+ return true;
2584
+ cur = path.posix.dirname(walked.path ?? cur);
2585
+ }
2586
+ else
2587
+ cur = cur === '/' ? `/${comp}` : `${cur}/${comp}`;
2588
+ // Round 34: a thread's own (`/proc/<x>/task/<tid>/cwd`) too.
2589
+ if (/^\/proc\/[^/]+\/(?:task\/[^/]+\/)?(?:cwd|root|fd)(?:\/|$)/.test(cur) || /^\/dev\/fd(?:\/|$)/.test(cur) || /^\/dev\/std(?:in|out|err)$/.test(cur))
2590
+ return true;
2591
+ }
2592
+ return false;
2593
+ }
2594
+ /**
2595
+ * @implements A-SPEC-251.2 (round 30) — where a wiring's command runs from, found as the launcher finds it. A path is
2596
+ * resolved as execve does, from the text as written (`sl/../node` with `sl` a link: folded as text it named a missing
2597
+ * file, the failed look-up read as "outside", and the kernel ran `deep/node` — measured); a path that cannot be resolved
2598
+ * is `unresolved`, not node. A bare command is `inside` when the launcher's look-up finds it in the workspace.
2599
+ */
2600
+ /** Whether the file that runs doctor is the `node` of its own directory (and that directory can lead PATH). */
2601
+ function ownNodeBeside(platform = process.platform) {
2602
+ const dir = path.dirname(process.execPath);
2603
+ if (dir.includes(platform === 'win32' ? ';' : ':'))
2604
+ return false;
2605
+ try {
2606
+ return fs.realpathSync.native(path.join(dir, platform === 'win32' ? 'node.exe' : 'node')) === fs.realpathSync.native(process.execPath);
2607
+ }
2608
+ catch {
2609
+ return false;
2610
+ }
2611
+ }
2612
+ /** The word `node` (with `.exe` where it runs). */
2613
+ function isNodeWord(w, platform = process.platform) {
2614
+ return platform === 'win32' ? /^node(?:\.exe)?$/i.test(w) : w === 'node';
2615
+ }
2616
+ /** One answer for both questions — what a probe starts, or why it starts nothing. */
2617
+ function probeAnswer(command, args, cwd, opts) {
2618
+ const platform = opts.platform ?? process.platform;
2619
+ const env = opts.env ?? process.env;
2620
+ const ownNode = opts.ownNode ?? ownNodeBeside(platform);
2621
+ const ownDir = opts.ownDir ?? path.dirname(process.execPath);
2622
+ const unspeakable = 'the command line holds a character the command interpreter would expand or end on (%, a double quote, a line break)';
2623
+ // The interpreter's command line is built whole and handed over verbatim — `/s /c "<line>"` strips the outer pair, and
2624
+ // Node's own quoting would turn the inner quotes into `\"`. The file is always quoted, and so is a token the interpreter
2625
+ // would split or act on (`C:\Users\R&D\…\npx.cmd` ended the command at `&` — code reading and the function's output, not
2626
+ // measured on Windows).
2627
+ const viaShell = (file) => {
2628
+ if ([file, ...args].some((t) => /[%"\r\n]/.test(t)))
2629
+ return { refused: unspeakable };
2630
+ // Fifth repair: `ComSpec` only as an absolute path the probe keeps — `ComSpec=cmd.exe` made the probe start a bare word
2631
+ // (code reading and the function's output, not measured on Windows).
2632
+ // Sixth repair: a drive-letter path only — a path starting `\\\\` or `//` (a share, a device) was taken as absolute, asked
2633
+ // about on disk and started; it is dropped before any file-system call. ComSpec only when its file is cmd.exe.
2634
+ const onDrive = (p) => /^[A-Za-z]:[\\/]/.test(p) && (opts.keep?.(p) ?? true);
2635
+ const root = env.SystemRoot || env.SYSTEMROOT || '';
2636
+ const named = env.ComSpec || env.COMSPEC || '';
2637
+ const comspec = onDrive(named) && path.win32.basename(named).toLowerCase() === 'cmd.exe' ? named
2638
+ : path.win32.join(onDrive(root) ? root : 'C:\\Windows', 'System32', 'cmd.exe');
2639
+ const quoted = [`"${file}"`, ...args.map((t) => (/[\s&|<>^()!,;=]/.test(t) ? `"${t}"` : t))];
2640
+ return { spec: { file: comspec, args: ['/d', '/s', '/c', `"${quoted.join(' ')}"`], verbatim: true } };
2641
+ };
2642
+ const spelled = /[\\/]/.test(command);
2643
+ if (!spelled && isNodeWord(command, platform))
2644
+ return { spec: { file: process.execPath, args: [...args] } };
2645
+ // Another command may be a script that finds its interpreter through PATH (`#!/usr/bin/env node`): where the file that
2646
+ // runs doctor is not the `node` of its directory, the directory in front of PATH holds no `node` (measured).
2647
+ if (!ownNode)
2648
+ return { refused: ownDir.includes(platform === 'win32' ? ';' : ':')
2649
+ ? "the directory of doctor's node holds the PATH delimiter, so it cannot lead PATH and what this command starts through PATH is not doctor's"
2650
+ : "the file that runs doctor is not the node of its own directory, so what this command starts through PATH is not doctor's" };
2651
+ if (spelled) {
2652
+ const shaped = (0, spawn_spec_1.spawnSpecFor)(command, args, platform);
2653
+ return shaped.command === 'cmd.exe' ? viaShell(command) : { spec: { file: shaped.command, args: shaped.args } };
2654
+ }
2655
+ if (opts.ownInside === true)
2656
+ return { refused: "doctor's own node lies inside the workspace, and so does what stands beside it" };
2657
+ // Third repair (owner decision 2026-09-28): another word is only the file of that name BESIDE doctor's node.
2658
+ const hit = (0, mcp_launcher_1.launcherFind)(cwd, command, platform, ownDir, env.PATHEXT, false);
2659
+ if (hit === null)
2660
+ return { refused: `\`${(0, codex_oracle_1.clipText)(command, 80)}\` does not stand beside doctor's node (${(0, codex_oracle_1.clipText)(ownDir, 200)})` };
2661
+ // Sixth repair: the file beside doctor's node is judged along its link chain (`<nvm>/bin/npx -> <ws>/tools/npx` was started).
2662
+ if (opts.keep !== undefined && (0, mcp_launcher_1.launcherFoundInside)(hit.file, (place) => opts.keep?.(place) === false)) {
2663
+ return { refused: `the \`${(0, codex_oracle_1.clipText)(command, 80)}\` beside doctor's node (${(0, codex_oracle_1.clipText)(hit.file, 200)}) lies inside the workspace, or a link on its way does` };
2664
+ }
2665
+ return platform === 'win32' && /\.(?:cmd|bat)$/i.test(hit.file) ? viaShell(hit.file) : { spec: { file: hit.file, args: [...args] } };
2666
+ }
2667
+ /** Fifth repair: what the harness line says doctor did — it checked the server only where the launch was run. */
2668
+ function harnessClause(ran) {
2669
+ return ran ? 'doctor checked the server through its own node' : 'doctor did not run it';
2670
+ }
2671
+ /**
2672
+ * @implements A-SPEC-251.2 (round 52, tenth repair; owner decision 2026-09-29) — the npx launch holmes-kit writes: the bare
2673
+ * command `npx` and exactly `-y -p @holmes-lab/holmes-kit@<version> holmes-mcp`. doctor starts no npx wiring: npx runs npm,
2674
+ * and npm walks up from where it starts, reading `.npmrc` and putting every parent's `node_modules/.bin` on PATH — each place
2675
+ * doctor started it (the target, an empty temporary directory, one pinned with `--prefix`, a root only the user could
2676
+ * write) ran a program someone else chose, or failed where the harness would not (oracle waves 60 to 63).
2677
+ */
2678
+ function npxLaunchWritten(command, args) {
2679
+ if (command !== 'npx' || args.length !== 4 || !args.every((a) => typeof a === 'string'))
2680
+ return false;
2681
+ const [y, p, pkg, bin] = args;
2682
+ const version = pkg.startsWith(`${mcp_launcher_1.MCP_PACKAGE}@`) ? pkg.slice(mcp_launcher_1.MCP_PACKAGE.length + 1) : '';
2683
+ return y === '-y' && p === '-p' && bin === 'holmes-mcp' && version.length <= 128
2684
+ && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version);
2685
+ }
2686
+ /** The verdict on an npx wiring, from its shape alone. */
2687
+ function npxShapeCheck(label, entry) {
2688
+ const shown = (0, codex_oracle_1.clipText)((0, codex_oracle_1.launchText)({ command: entry.command, args: entry.args }));
2689
+ return npxLaunchWritten(entry.command, entry.args)
2690
+ ? { level: 'PASS', detail: `The ${label} wiring runs \`${shown}\`, the npx launch holmes-kit writes — confirmed by its shape, not started: npx runs npm in the harness's workspace` }
2691
+ : { level: 'WARN', detail: `The ${label} wiring runs \`${shown}\`; it was not run — not the npx launch holmes-kit writes`,
2692
+ fix: `Run holmes-kit init --target <dir> --agent ${label} --force to rewrite the wiring.` };
2693
+ }
2694
+ /** Why `probeSpawn` starts nothing for this command, or null when it starts something. */
2695
+ function probeRefusal(command, args, cwd, opts = {}) {
2696
+ const answer = probeAnswer(command, args, cwd, opts);
2697
+ return 'refused' in answer ? answer.refused : null;
2698
+ }
2699
+ function probeSpawn(command, args, cwd, opts = {}) {
2700
+ const answer = probeAnswer(command, args, cwd, opts);
2701
+ return 'spec' in answer ? answer.spec : null;
2702
+ }
2703
+ /**
2704
+ * What a probe started from `target` is given: whether doctor's node lies inside the workspace, and which PATH entries its
2705
+ * children keep (absolute ones outside the workspace; with a target that holds the home directory, every absolute one).
2706
+ */
2707
+ function probeContext(target) {
2708
+ const realTarget = (() => { try {
2709
+ return fs.realpathSync.native(target);
2710
+ }
2711
+ catch {
2712
+ return path.resolve(target);
2713
+ } })();
2714
+ if ((0, workspace_scope_1.targetHoldsHome)(realTarget))
2715
+ return { ownInside: false, keep: () => true };
2716
+ const inside = (p) => {
2717
+ const real = (() => { try {
2718
+ return fs.realpathSync.native(p);
2719
+ }
2720
+ catch {
2721
+ return path.resolve(p);
2722
+ } })();
2723
+ return (0, workspace_scope_1.inWorkspace)(realTarget, real) || (0, workspace_scope_1.isWithin)(path.resolve(target), path.resolve(p));
2724
+ };
2725
+ return { ownInside: inside(path.dirname(process.execPath)), keep: (entry) => !inside(entry) };
2726
+ }
2727
+ /**
2728
+ * @implements A-SPEC-251.2 (round 52, repair) — what the HARNESS would find for a bare command on its own PATH, without
2729
+ * running it: through a relative entry or the directory, or a file whose link chain passes through the workspace. With a
2730
+ * target that holds the home directory an absolute entry's hit is the user's install (round 51).
2731
+ */
2732
+ function harnessPlace(target, realTarget, w) {
2733
+ if (w === '' || w.startsWith('-') || /[\\/]/.test(w))
2734
+ return null;
2735
+ const hit = (0, mcp_launcher_1.launcherFind)(target, w);
2736
+ // Fourth repair: a PATH that holds no launcher is said (the probe runs doctor's own node, so `spawn node ENOENT` was gone
2737
+ // and three PASS lines were all that was left — measured).
2738
+ if (hit === null)
2739
+ return { place: 'not-found', file: '' };
2740
+ if (hit.relative)
2741
+ return { place: 'found-relative', file: hit.file };
2742
+ if ((0, workspace_scope_1.targetHoldsHome)(realTarget))
2743
+ return null;
2744
+ return (0, mcp_launcher_1.launcherFoundInside)(hit.file, (place) => (0, workspace_scope_1.inWorkspace)(realTarget, place) || (0, workspace_scope_1.isWithin)(path.resolve(target), place)) ? { place: 'found-inside', file: hit.file } : null;
2745
+ }
2746
+ function commandPlace(target, realTarget, w) {
2747
+ const roots = (0, workspace_scope_1.workspaceRoots)(realTarget);
2748
+ if (w === '' || w.startsWith('-'))
2749
+ return 'bare';
2750
+ if (!/[\\/]/.test(w)) {
2751
+ // @implements A-SPEC-251.2 (round 51) — what is RUN follows what is diagnosed: found through a relative PATH entry or
2752
+ // the directory, or through a link lying in the workspace, the command is the workspace's and is not run (doctor said
2753
+ // FAIL "whatever file is there runs as the gate" and started that file through the handshake — measured).
2754
+ // Round 52: judged under the PATH the probe is started with — doctor's own node's directory first. What is found there
2755
+ // as doctor's own node is always run; the home exemption is for the diagnosis only (as leave to run it started a `node`
2756
+ // the target carried — a regression of round 51, measured).
2757
+ // Round 52 (repair): the word `node` is never looked up — the probe starts process.execPath itself (`probeSpawn`).
2758
+ // Third repair: another bare word is only what stands beside doctor's node (`probeSpawn`); whether it is started is
2759
+ // `probeRefusal`'s answer, asked where the wiring is about to be run.
2760
+ return 'bare';
2761
+ }
2762
+ // @implements A-SPEC-251.2 (round 31) — a relative path means something only in the checkout's layout: it is the
2763
+ // workspace's (`../../tools/node` from a submodule package with its own `.git` file, or from an archive with no `.git`,
2764
+ // ran the super-repository's wrapper — measured). An absolute path spelled under the target or its repository is too.
2765
+ if (!path.isAbsolute(w))
2766
+ return 'inside';
2767
+ // Round 32: a path whose meaning depends on the process is relative too (`/proc/self/cwd/../../tools/node` passed round
2768
+ // 31 on Linux — measured).
2769
+ if (w.startsWith('/') && passesThroughProcess(w))
2770
+ return 'inside';
2771
+ if ([path.resolve(target), ...roots].some((r) => (0, workspace_scope_1.isWithin)(r, path.resolve(w))))
2772
+ return 'inside';
2773
+ // Round 35: a network or device path is never looked up (`/net/<host>/…`, `//host/…`): unresolved, never run.
2774
+ const walked = (0, claude_switches_1.localPhysicalRealpath)(w);
2775
+ if (walked.path === null)
2776
+ return 'unresolved';
2777
+ return (0, workspace_scope_1.inWorkspace)(realTarget, walked.path) ? 'inside' : 'outside';
2778
+ }
2779
+ /**
2780
+ * @implements A-SPEC-251.2 (round 31) — node or npx as the launcher runs it: a bare name, or an absolute path outside the
2781
+ * workspace whose REAL file is node/npx (or this node). A committed link `bin/node -> …/make` read as node by its
2782
+ * spelling and ran the repository's Makefile inside doctor (measured).
2783
+ */
2784
+ function launchBaseOf(target, realTarget, command) {
2785
+ const named = (0, codex_oracle_1.launcherBase)(command);
2786
+ if (named === null)
2787
+ return null;
2788
+ const place = commandPlace(target, realTarget, command);
2789
+ if (place === 'bare')
2790
+ return named;
2791
+ if (place === 'unresolved')
2792
+ return null;
2793
+ let real;
2794
+ {
2795
+ const walked = (0, claude_switches_1.localPhysicalRealpath)(path.isAbsolute(command) ? command : `${target}${path.sep}${command}`);
2796
+ if (walked.path === null)
2797
+ return null;
2798
+ real = walked.path;
2799
+ }
2800
+ if ((0, workspace_scope_1.inWorkspace)(realTarget, real))
2801
+ return null;
2802
+ const self = (() => { try {
2803
+ return fs.realpathSync.native(process.execPath);
2804
+ }
2805
+ catch {
2806
+ return process.execPath;
2807
+ } })();
2808
+ // Round 32: the very file a bare `node`/`npx` resolves to from the target is the launcher too — an absolute Volta or
2809
+ // mise shim (`volta-shim`, `mise`, `node22`) read as "not this install" in round 31 (measured); a workspace link to it
2810
+ // (devbox, pixi) likewise. A name check alone is only for a path spelled outside the workspace.
2811
+ const bare = (0, mcp_launcher_1.launcherLookup)(target, named);
2812
+ const bareReal = (() => { if (bare === null)
2813
+ return null; try {
2814
+ return fs.realpathSync.native(bare);
2815
+ }
2816
+ catch {
2817
+ return null;
2818
+ } })();
2819
+ if (real === self || (bareReal !== null && real === bareReal && !(0, workspace_scope_1.inWorkspace)(realTarget, bareReal)))
2820
+ return named;
2821
+ if (place !== 'outside')
2822
+ return null;
2823
+ const file = path.basename(real).toLowerCase();
2824
+ if (named === 'node' && (file === 'node' || file === 'node.exe'))
2825
+ return 'node';
2826
+ if (named === 'npx' && (file === 'npx' || file === 'npx-cli.js' || file === 'npx.cmd'))
2827
+ return 'npx';
2828
+ return null;
2829
+ }
2830
+ /** @implements A-SPEC-251.2 (round 31) — Holmes's Claude wiring: its hooks in a settings file, or its `.mcp.json` entry. */
2831
+ function holmesClaudeWired(target) {
2832
+ const read = (f) => { try {
2833
+ return JSON.parse((0, bounded_io_1.readRegularTextSync)(f).replace(/^\uFEFF/, ''));
2834
+ }
2835
+ catch {
2836
+ return null;
2837
+ } };
2838
+ const mcp = read(path.join(target, '.mcp.json'));
2839
+ if (mcp !== null && typeof mcp === 'object' && mcp.mcpServers && typeof mcp.mcpServers === 'object' && init_1.SERVER_NAME in mcp.mcpServers)
2840
+ return true;
2841
+ for (const f of ['settings.json', 'settings.local.json']) {
2842
+ const st = read(path.join(target, '.claude', f));
2843
+ if (st === null || typeof st !== 'object')
2844
+ continue;
2845
+ // Round 32: a hook structure of the wrong shape cannot say whether Holmes is wired — ask (a TypeError lost the whole
2846
+ // report, and with it the file's `disableAllHooks` — measured).
2847
+ const hooks = st.hooks;
2848
+ if (hooks === undefined)
2849
+ continue;
2850
+ if (hooks === null || typeof hooks !== 'object' || Array.isArray(hooks))
2851
+ return true;
2852
+ for (const groups of Object.values(hooks)) {
2853
+ if (!Array.isArray(groups))
2854
+ return true;
2855
+ for (const g of groups) {
2856
+ const hs = g?.hooks;
2857
+ if (hs === undefined)
2858
+ continue;
2859
+ if (!Array.isArray(hs))
2860
+ return true;
2861
+ for (const h of hs)
2862
+ if (typeof h?.command === 'string' && (0, settings_merge_1.isHolmesCommand)(h.command))
2863
+ return true;
2864
+ }
2865
+ }
2866
+ }
2867
+ return false;
2868
+ }
2869
+ /** Round 45: an argument spelled inside the target, by text alone (no look-up). */
2870
+ function spelledInside(target, realTarget, w) {
2871
+ if (w === '' || w.startsWith('-') || !/[\\/]/.test(w))
2872
+ return false;
2873
+ const p = resolveWiringPath(target, w);
2874
+ return (0, workspace_scope_1.isWithin)(path.resolve(target), p) || (0, workspace_scope_1.isWithin)(realTarget, p);
2875
+ }
2876
+ /** Whether an argument names a file inside the workspace (node resolves a script argument as text, then opens it). */
2877
+ function argInWorkspace(target, realTarget, w) {
2878
+ if (w === '' || w.startsWith('-') || !/[\\/]/.test(w))
2879
+ return false;
2880
+ // Round 35: node resolves the argument as text, then opens it — a network path is never looked up (read as the workspace's).
2881
+ const walked = (0, codex_oracle_1.localRealpath)(resolveWiringPath(target, w));
2882
+ // Round 45: a walk past its bound confirms nothing — the argument is the workspace's when it is spelled inside it (round 44 read
2883
+ // it as not the workspace's and advised running doctor from "the install it names").
2884
+ if (walked.exhausted)
2885
+ return spelledInside(target, realTarget, w);
2886
+ if (walked.refused)
2887
+ return true;
2888
+ if (walked.path === null)
2889
+ return false;
2890
+ return (0, workspace_scope_1.inWorkspace)(realTarget, walked.path);
2891
+ }
2892
+ async function wiringHandshakeChecks(target, codexConfigPath = (0, codex_toml_1.defaultCodexConfigPath)(), packageRoot = path.resolve(__dirname, '..', '..', '..')) {
2893
+ const out = [];
2894
+ const ownBin = (() => { try {
2895
+ return fs.realpathSync.native(path.join(packageRoot, 'bin', 'holmes-mcp.js'));
2896
+ }
2897
+ catch {
2898
+ return null;
2899
+ } })();
2900
+ const realTarget = (() => { try {
2901
+ return fs.realpathSync.native(target);
2902
+ }
2903
+ catch {
2904
+ return path.resolve(target);
2905
+ } })();
2906
+ for (const wiring of holmesWirings(target, codexConfigPath)) {
2907
+ const name = `${wiring.label} wiring handshake`;
2908
+ const entry = wiring.entry;
1791
2909
  if (!entry) {
1792
2910
  out.push({ name, level: 'WARN', detail: `Could not read a runnable ${init_1.SERVER_NAME} wiring from ${wiring.file}`,
1793
2911
  fix: `Rewire with holmes-kit init --target <dir> --agent ${wiring.label}.` });
1794
2912
  continue;
1795
2913
  }
1796
- if (entry.command === 'node') {
2914
+ // @implements A-SPEC-251.2 (round 27/28) — Claude's and Antigravity's wiring must run THIS install's server, as a
2915
+ // Codex layer's must (A-SPEC-738 rules 23–25), however the launch is spelled: round 27 checked only the literal
2916
+ // command `node`, and `/opt/homebrew/bin/node …`, `sh bin/run.sh`, an executable script, `env node …` and `Node …`
2917
+ // ran a workspace wrapper that set HOLMES_APPROVAL and passed (measured). A launch that is not exactly `node <this
2918
+ // install's bin/holmes-mcp.js>` is not run: a FAIL when it names a path inside the workspace, else a WARN. The npx
2919
+ // launch keeps its own handling (named residual).
2920
+ // Round 29: a node or npx is the bare command or a program outside the workspace — a workspace `bin/node`, `./node`,
2921
+ // `tools/node` or `bin/npx` given this install's bin ran and passed (measured).
2922
+ // Round 30: placed where the launcher finds it, against the target and its repository; Codex's node tables too (a
2923
+ // relative `bin/holmes-mcp.js` ran the workspace's wrapper — measured).
2924
+ const place = commandPlace(target, realTarget, entry.command);
2925
+ const base = launchBaseOf(target, realTarget, entry.command);
2926
+ if (ownBin !== null && base !== 'npx') {
2927
+ const bin = entry.args[0] ?? '';
2928
+ // Round 35: a network path is never looked up — it is judged (and refused) below, not called missing.
2929
+ // Round 36: walked, not only read as text (a committed link `link -> /net/…` was looked up — measured).
2930
+ const argWalk = base === 'node' ? (0, codex_oracle_1.localRealpath)(resolveWiringPath(target, bin)) : null;
2931
+ if (argWalk !== null && !argWalk.refused && argWalk.path === null) {
2932
+ out.push({ name, level: 'FAIL', detail: `The wiring points at a missing file: ${(0, codex_oracle_1.clipText)(bin)}`,
2933
+ fix: `Run holmes-kit init --target <dir> --agent ${wiring.label} --force to refresh the path.` });
2934
+ continue;
2935
+ }
2936
+ const walked = base === 'node' ? (0, codex_oracle_1.localRealpath)(resolveWiringPath(target, bin)) : null;
2937
+ if (walked === null || walked.refused || walked.path !== ownBin || entry.args.length !== 1) {
2938
+ // @implements A-SPEC-251.2 (round 44) — at most 16 arguments are walked (4,000 arguments through a link chain held doctor
2939
+ // for 25.6 s — measured); the launch is not run either way.
2940
+ // Round 45: the arguments past 16 are judged by their spelling, not walked.
2941
+ const inside = place === 'inside' || entry.args.slice(0, WIRING_ARGS_JUDGED).some((w) => argInWorkspace(target, realTarget, w))
2942
+ || entry.args.slice(WIRING_ARGS_JUDGED).some((w) => spelledInside(target, realTarget, w));
2943
+ const unconfirmed = place === 'outside' && (0, codex_oracle_1.launcherBase)(entry.command) !== null && base === null;
2944
+ const shown = (0, codex_oracle_1.clipText)((0, codex_oracle_1.launchText)({ command: entry.command, args: entry.args }));
2945
+ out.push({ name: `${wiring.label} wiring identity`, level: inside ? 'FAIL' : 'WARN',
2946
+ detail: walked !== null && walked.path === ownBin
2947
+ ? `The ${wiring.label} wiring passes extra arguments to this install's server (\`${shown}\`); it was not run`
2948
+ : place === 'unresolved' && !inside
2949
+ ? `The ${wiring.label} wiring runs \`${shown}\`, whose command path cannot be resolved; it was not run`
2950
+ : unconfirmed && !inside
2951
+ ? `The ${wiring.label} wiring runs \`${shown}\`, whose program could not be confirmed as node (its real file is neither named ${(0, codex_oracle_1.launcherBase)(entry.command)} nor the one PATH finds); it was not run`
2952
+ : inside
2953
+ ? `The ${wiring.label} wiring runs \`${shown}\`, which names a file inside the workspace, not this install's server (${(0, codex_oracle_1.clipText)(ownBin)}); it was not run`
2954
+ : `The ${wiring.label} wiring runs \`${shown}\`, not this install's server (${(0, codex_oracle_1.clipText)(ownBin)}); it was not run — run doctor from the install it names, or rewire`,
2955
+ fix: `Run holmes-kit init --target <dir> --agent ${wiring.label} --force from the install you mean to use.` });
2956
+ continue;
2957
+ }
2958
+ }
2959
+ else if (entry.command === 'node') {
1797
2960
  const bin = entry.args[0] ?? '';
1798
2961
  // @implements A-SPEC-581.1 — the handshake covers ALL THREE harnesses, so the cwd-dependent
1799
2962
  // read here was the widest instance of the same defect.
1800
- if (!fs.existsSync(resolveWiringPath(target, bin))) {
1801
- out.push({ name, level: 'FAIL', detail: `The wiring points at a missing file: ${bin}`,
2963
+ // A-SPEC-251.2 (round 39): the walked path, never the spelling (a `lnk/../x` spelling was looked up through the link).
2964
+ const walkedArg = (0, codex_oracle_1.localRealpath)(resolveWiringPath(target, bin));
2965
+ if (walkedArg.refused || walkedArg.path === null) {
2966
+ out.push({ name, level: 'FAIL', detail: walkedArg.refused ? (walkedArg.exhausted ? `The wiring points past doctor's walk bound (${codex_oracle_1.MAX_WALK_STEPS} components), which is never opened: ${(0, codex_oracle_1.clipText)(bin)}` : `The wiring points at a network or device path, which is never opened: ${(0, codex_oracle_1.clipText)(bin)}`) : `The wiring points at a missing file: ${(0, codex_oracle_1.clipText)(bin)}`,
1802
2967
  fix: `Run holmes-kit init --target <dir> --agent ${wiring.label} --force to refresh the path.` });
1803
2968
  continue;
1804
2969
  }
1805
2970
  }
2971
+ // Round 52 (repair): what the harness would find for the command is said, not run — the probe below starts doctor's own node.
2972
+ // Second repair: for every bare launcher word, not `node` alone.
2973
+ const harness = (0, codex_oracle_1.launcherBase)(entry.command) !== null ? harnessPlace(target, realTarget, entry.command) : null;
2974
+ // Tenth repair (owner decision): an npx wiring is judged by its shape and never started.
2975
+ const shapeOnly = base === 'npx';
2976
+ // Third repair: a launch the probe would not start is said so, with its reason, and not started.
2977
+ const refused = shapeOnly ? null : probeRefusal(entry.command, entry.args, target, probeContext(target));
2978
+ if (harness !== null) {
2979
+ if (harness.place === 'not-found')
2980
+ out.push({ name: `${wiring.label} wiring identity`, level: 'WARN',
2981
+ detail: `The ${wiring.label} wiring runs \`${(0, codex_oracle_1.clipText)((0, codex_oracle_1.launchText)({ command: entry.command, args: entry.args }))}\`, and the command \`${(0, codex_oracle_1.clipText)(entry.command, 80)}\` is not found on the harness's PATH — the harness could not start it; ${harnessClause(!shapeOnly && refused === null)}`,
2982
+ fix: `Start the harness with a PATH that holds ${(0, codex_oracle_1.clipText)(entry.command, 80)}, or rewire with holmes-kit init --target <dir> --agent ${wiring.label} --force.` });
2983
+ else
2984
+ out.push({ name: `${wiring.label} wiring identity`, level: harness.place === 'found-relative' ? 'FAIL' : 'WARN',
2985
+ detail: `The ${wiring.label} wiring runs \`${(0, codex_oracle_1.clipText)((0, codex_oracle_1.launchText)({ command: entry.command, args: entry.args }))}\`, and the command \`${(0, codex_oracle_1.clipText)(entry.command, 80)}\` is found ${harness.place === 'found-relative' ? 'through the directory or a relative PATH entry' : 'inside the workspace'} (${(0, codex_oracle_1.clipText)(harness.file, 400)}) on the harness's PATH — the harness would start that file; ${harnessClause(!shapeOnly && refused === null)}`,
2986
+ fix: harness.place === 'found-relative' ? 'Remove that file, or the relative entry in PATH that finds it.' : `Confirm that file is the ${(0, codex_oracle_1.clipText)(entry.command, 80)} you trust, or put the one you trust first in PATH.` });
2987
+ }
2988
+ if (shapeOnly) {
2989
+ out.push({ ...npxShapeCheck(wiring.label, entry), name });
2990
+ continue;
2991
+ }
2992
+ if (refused !== null) {
2993
+ out.push({ name: `${wiring.label} wiring identity`, level: 'WARN',
2994
+ detail: `The ${wiring.label} wiring runs \`${(0, codex_oracle_1.clipText)((0, codex_oracle_1.launchText)({ command: entry.command, args: entry.args }))}\`; it was not run — ${refused}`,
2995
+ fix: 'Run doctor with the node whose directory holds the launcher (node and npx of one install), outside the workspace.' });
2996
+ continue;
2997
+ }
1806
2998
  // @implements A-SPEC-581.1 — launched FROM the target, exactly as the harness would.
1807
- const check = await wiringSpawnCheck(entry.command, entry.args, undefined, undefined, target);
2999
+ const check = await wiringSpawnShared(entry.command, entry.args, target);
1808
3000
  out.push({ ...check, name });
1809
3001
  }
1810
3002
  return out;
@@ -1814,6 +3006,10 @@ function entryOf(value) {
1814
3006
  const e = value;
1815
3007
  if (!e || typeof e.command !== 'string' || !Array.isArray(e.args))
1816
3008
  return null;
3009
+ // @implements A-SPEC-251.2 (confirmation round 23) — a non-string argument is not a runnable launch (a TypeError left
3010
+ // doctor without a report — measured).
3011
+ if (!e.args.every((a) => typeof a === 'string'))
3012
+ return null;
1817
3013
  return { command: e.command, args: e.args };
1818
3014
  }
1819
3015
  /**
@@ -1878,7 +3074,7 @@ function semanticTierVerdict(t) {
1878
3074
  : t.keySource === 'file' ? '~/.holmes/credentials.json' : 'unknown';
1879
3075
  return {
1880
3076
  level: 'PASS',
1881
- detail: `Semantic search tier: cloud (${t.model}, key source: ${src}) — spec prose, file paths, and symbol names are sent to an external service (Google API). Setting the key is consent to that transfer, and the value is never printed into this report.`,
3077
+ detail: `Semantic search tier: cloud (${(0, codex_oracle_1.clipText)(String(t.model), 80)}, key source: ${src}) — spec prose, file paths, and symbol names are sent to an external service (Google API). Setting the key is consent to that transfer, and the value is never printed into this report.`,
1882
3078
  };
1883
3079
  }
1884
3080
  if (t.tier === 'local') {
@@ -1947,3 +3143,41 @@ function detectTreeKeyTemporary(root) {
1947
3143
  return { found: false };
1948
3144
  }
1949
3145
  }
3146
+ /**
3147
+ * @implements A-SPEC-738 — the Holmes table as Codex reads it: present, not emptied of tools. Measured
3148
+ * on codex-cli 0.155.1: `enabled_tools = []` loads and lists 0 tools; an `environment_id` Codex does
3149
+ * not know fails at start-up.
3150
+ */
3151
+ function codexTableProblem(table, judgedByCodex, ownEntryRead) {
3152
+ if (table === null || table === undefined) {
3153
+ return judgedByCodex && ownEntryRead
3154
+ ? { level: 'FAIL', detail: `Codex's effective configuration has no [mcp_servers.${init_1.SERVER_NAME}] (a profile or another layer replaces it), so the Holmes MCP server does not start`, fix: 'Remove the overriding layer, or rewire with holmes-kit init --target <dir> --agent codex.' }
3155
+ : null;
3156
+ }
3157
+ if (table.enabled === false) {
3158
+ return { level: 'FAIL', detail: `[mcp_servers.${init_1.SERVER_NAME}] sets enabled = false — Codex does not start the Holmes MCP server`, fix: 'Remove the enabled = false line (or set it true), then restart Codex.' };
3159
+ }
3160
+ if (Array.isArray(table.enabled_tools) && table.enabled_tools.length === 0) {
3161
+ return { level: 'FAIL', detail: `[mcp_servers.${init_1.SERVER_NAME}] sets enabled_tools = [] — Codex starts the server but offers none of its tools`, fix: 'Remove the enabled_tools line, then restart Codex.' };
3162
+ }
3163
+ // @implements A-SPEC-738 (round 12) — a tool list that takes a gate tool away hollows the gate (measured:
3164
+ // a trusted layer's `disabled_tools` covering every Holmes tool passed as "resolves").
3165
+ const hollow = (0, codex_oracle_1.hollowedGateTools)(table);
3166
+ if (hollow !== null) {
3167
+ return { level: 'FAIL', detail: `[mcp_servers.${init_1.SERVER_NAME}] disables the governance tools ${hollow} (disabled_tools / enabled_tools) — the gate cannot act`, fix: 'Remove the disabled_tools/enabled_tools setting, then restart Codex.' };
3168
+ }
3169
+ // Codex reports `local` for an entry that sets none (measured), so only another id is a finding.
3170
+ if (table.environment_id !== undefined && table.environment_id !== null && table.environment_id !== 'local') {
3171
+ return { level: 'WARN', detail: `[mcp_servers.${init_1.SERVER_NAME}] sets environment_id = ${(0, codex_oracle_1.clipText)(JSON.stringify(table.environment_id))} — Codex starts the server only in that environment, and an id it does not know fails at start-up`, fix: 'Remove the environment_id line unless you configured that environment, then restart Codex.' };
3172
+ }
3173
+ return null;
3174
+ }
3175
+ /** Holmes's table read by the emulation, for the fallback path of `codexTableProblem`. */
3176
+ function ownHolmesTable(raw) {
3177
+ const parsed = (0, codex_toml_1.parseCodexConfig)(raw);
3178
+ if (!parsed.ok)
3179
+ return null;
3180
+ const servers = parsed.doc.mcp_servers;
3181
+ const table = servers && Object.prototype.hasOwnProperty.call(servers, init_1.SERVER_NAME) ? servers[init_1.SERVER_NAME] : null;
3182
+ return table !== null && typeof table === 'object' ? table : null;
3183
+ }