ctxtop 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/.antigravity-plugin/plugin.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHECKSUMS.sha256 +59 -42
  4. package/README.md +351 -330
  5. package/bin/ah-statusline.mjs +30 -0
  6. package/bin/ctxtop.mjs +330 -5
  7. package/config/default_flightcheck.json +19 -0
  8. package/config/modelCatalog.json +165 -0
  9. package/hooks/handlers/compact-lifecycle.mjs +323 -8
  10. package/hooks/handlers/config-change.mjs +402 -0
  11. package/hooks/handlers/hookIo.mjs +56 -0
  12. package/hooks/handlers/post-model-switch.mjs +111 -0
  13. package/hooks/handlers/post-tool-use.mjs +117 -16
  14. package/hooks/handlers/pre-model-switch.mjs +823 -24
  15. package/hooks/handlers/pre-tool-use.mjs +271 -4
  16. package/hooks/handlers/stop-gate.mjs +297 -11
  17. package/hooks/handlers/user-prompt-submit.mjs +224 -0
  18. package/hooks/hooks.json +50 -0
  19. package/hooks/post_tool_use.mjs +8 -0
  20. package/hooks/register.js +48 -9
  21. package/hooks/session_start.mjs +11 -1
  22. package/hooks/stop.mjs +11 -1
  23. package/package.json +11 -4
  24. package/packages/antigravity/package.json +1 -1
  25. package/packages/claude-code/package.json +1 -1
  26. package/packages/core/package.json +1 -1
  27. package/packages/engine-node/package.json +1 -1
  28. package/packages/mcp/package.json +1 -1
  29. package/packages/mcp/src/server.mjs +1 -1
  30. package/packages/pro/package.json +1 -1
  31. package/plugin.json +1 -1
  32. package/sidecars/horizon-daemon/server.mjs +38 -2
  33. package/skills/handoff/SKILL.md +8 -0
  34. package/src/adapters/antigravity/index.mjs +31 -1
  35. package/src/adapters/claude-code/index.mjs +40 -1
  36. package/src/cli/horizon_hud.mjs +254 -52
  37. package/src/config/modelCatalog.json +84 -0
  38. package/src/core/bucket_b_runtime.mjs +1200 -0
  39. package/src/core/constants.mjs +191 -4
  40. package/src/core/detectors_det01_to_16.mjs +54 -5
  41. package/src/core/doc_indexer.mjs +338 -0
  42. package/src/core/layer5_hygiene.mjs +118 -0
  43. package/src/core/parser.mjs +2 -1
  44. package/src/core/paths.mjs +3 -2
  45. package/src/core/rsl_clash_auditor.mjs +423 -0
  46. package/src/core/rsl_distiller.mjs +372 -0
  47. package/src/core/rsl_ledger.mjs +969 -0
  48. package/src/core/rsl_triage.mjs +909 -0
  49. package/src/core/session_auditor.mjs +658 -0
  50. package/src/core/shield_manager.mjs +1417 -0
  51. package/src/core/task_quota_router.mjs +1 -1
  52. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
  53. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  54. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  55. package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
  56. package/src/core-isomorphic/config/anthropicModelCatalog.json +404 -1
  57. package/src/core-isomorphic/config/catalogLoader.mjs +546 -46
  58. package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
  59. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
  60. package/src/core-isomorphic/economics/cacheGravity.mjs +18 -0
  61. package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
  62. package/src/core-isomorphic/economics/driftLatency.mjs +114 -0
  63. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  64. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  65. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  66. package/src/core-isomorphic/guards/circuitBreakers.mjs +191 -191
  67. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
  68. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
  69. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
  70. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  71. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
  72. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  73. package/src/core-isomorphic/index.js +1 -0
  74. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +36 -12
  75. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +293 -237
  76. package/src/core-isomorphic/ui/modViews.mjs +35 -9
  77. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  78. package/src/diagnostics/doctorEngine.mjs +95 -3
  79. package/src/engine-node/db/probe.mjs +234 -2
  80. package/src/engine-node/index.mjs +3 -0
  81. package/src/engine-node/sensors/blindspots.mjs +13 -6
  82. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  83. package/src/hooks/claude_rsl_hook.mjs +288 -0
  84. package/src/hooks/post_invocation.mjs +196 -4
  85. package/src/hooks/pre_invocation.mjs +732 -22
  86. package/src/hooks/session_start.mjs +39 -1
  87. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  88. package/src/utils/sessionCalibration.mjs +657 -0
  89. package/src/webview/horizon_panel.html +1325 -317
@@ -345,9 +345,10 @@ export function deriveSurfaceMetrics(state = {}, options = {}) {
345
345
  totalInputTokens,
346
346
  options
347
347
  );
348
- const liveSubagentIsolatedUSD = Number(
349
- ((liveSubagentIsolatedTokens / 1_000_000) * Number(activeRatesForSub.inputPer1M || 3)).toFixed(6)
350
- );
348
+ const liveSubagentIsolatedUSD =
349
+ activeRatesForSub && !activeRatesForSub.unknownModel && Number.isFinite(activeRatesForSub.inputPer1M)
350
+ ? Number(((liveSubagentIsolatedTokens / 1_000_000) * activeRatesForSub.inputPer1M).toFixed(6))
351
+ : 0;
351
352
 
352
353
  // Use explicit options.savedUSD / options.savedTokens if passed, else max of ledger + session
353
354
  const savedUSD =
@@ -478,10 +479,14 @@ export function deriveSurfaceMetrics(state = {}, options = {}) {
478
479
  totalInputTokens,
479
480
  options
480
481
  );
481
- const mWrite =
482
- ttlTier === '1h' ? activeRates.multipliers.write1h : activeRates.multipliers.write5m;
483
- const mRead = activeRates.multipliers.read;
484
- breakEvenReadsPerWrite = Number(((mWrite - 1) / (1 - mRead)).toFixed(3));
482
+ if (activeRates && !activeRates.unknownModel && activeRates.multipliers) {
483
+ const mWrite =
484
+ ttlTier === '1h' ? activeRates.multipliers.write1h : activeRates.multipliers.write5m;
485
+ const mRead = activeRates.multipliers.read;
486
+ breakEvenReadsPerWrite = Number(((mWrite - 1) / (1 - mRead)).toFixed(3));
487
+ } else {
488
+ breakEvenReadsPerWrite = null;
489
+ }
485
490
  }
486
491
  const sessionFiveMinRoiTarget = Number(roi.sessionFiveMinRoiTarget || 1.39);
487
492
 
@@ -1346,6 +1351,23 @@ export function renderAdvancedViewPane(state = {}, options = {}) {
1346
1351
  };
1347
1352
  }
1348
1353
 
1354
+ /**
1355
+ * Pure zero-Node formatter for the Claude Code `statusLine` RSL budget segment.
1356
+ *
1357
+ * @param {object} rsl
1358
+ * @returns {string}
1359
+ */
1360
+ export function formatRslStatusSegment(rsl) {
1361
+ if (!rsl || typeof rsl !== 'object') return '';
1362
+ const rules = Math.max(0, Number(rsl.activeRules ?? 0));
1363
+ const tokens = Math.max(0, Number(rsl.ruleBudgetTokens ?? 0));
1364
+ const clashes = Math.max(0, Number(rsl.clashCount ?? 0));
1365
+ const budgetStr =
1366
+ tokens >= 1000 ? `${(tokens / 1000).toFixed(1).replace(/\.0$/, '')}k` : String(tokens);
1367
+ const base = `RSL: ${rules} rules | Budget: ${budgetStr}/20k`;
1368
+ return clashes > 0 ? `${base} | ${clashes} clash!` : base;
1369
+ }
1370
+
1349
1371
  /**
1350
1372
  * 4. Renders a single-line terminal `statusLine` adapting cleanly to terminal column width
1351
1373
  * (`80`, `110`, `144`, or arbitrary column count).
@@ -1415,6 +1437,9 @@ export function renderStatusLine(state = {}, options = {}) {
1415
1437
  const retStr = state.prefixRetention?.measured ? ` · ${formatRetentionCompact(state.prefixRetention)}` : '';
1416
1438
  const swarmTok = layoutTier === 'wide-144' ? formatSwarmCompact(computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() })) : '';
1417
1439
  const swarmStr = swarmTok ? ` · ${swarmTok}` : '';
1440
+ const rslData = options.rsl || state.rsl || null;
1441
+ const rslTok = layoutTier !== 'compact-80' && rslData ? formatRslStatusSegment(rslData) : '';
1442
+ const rslStr = rslTok ? ` · ${rslTok}` : '';
1418
1443
 
1419
1444
  let p = '';
1420
1445
  let a = '';
@@ -1423,8 +1448,8 @@ export function renderStatusLine(state = {}, options = {}) {
1423
1448
  a = `AH ${g.ansiCodeBar} ${tokStr} C:${metrics.cacheHitPct}% ${ttlStr} ${pill}${loopStr} ${savedStr}`;
1424
1449
  } else {
1425
1450
  const shortModel = g.modelId.replace(/^claude-/, '');
1426
- p = `AH ${g.bracketedBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}`;
1427
- a = `AH ${g.ansiCodeBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}`;
1451
+ p = `AH ${g.bracketedBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}${rslStr}`;
1452
+ a = `AH ${g.ansiCodeBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}${rslStr}`;
1428
1453
  }
1429
1454
 
1430
1455
  chosenGrid = g;
@@ -1474,5 +1499,6 @@ export default {
1474
1499
  renderSimpleViewPane,
1475
1500
  renderSimpleHudPane,
1476
1501
  renderAdvancedViewPane,
1502
+ formatRslStatusSegment,
1477
1503
  renderStatusLine
1478
1504
  };
@@ -0,0 +1,396 @@
1
+ /**
2
+ * @file src/diagnostics/claudeHookCapabilities.mjs
3
+ * Startup feature-check for undocumented Claude Code hook contracts (`PreModelSwitch`,
4
+ * `permissionBehavior === "ask"`, payload keys `from_model`/`to_model`/`prompt_cache_warm`,
5
+ * and absence of `PreEffortChange`).
6
+ *
7
+ * Scans the installed Claude Code binary/bundle in bounded 4 MB chunks with 256-byte overlap,
8
+ * caches results by `(binaryPath, size, mtimeMs)` under `.attention-horizon/cache/ah_claude_capabilities.json`,
9
+ * and logs a non-fatal runtime diagnostic if the installed binary drops the hook contract.
10
+ */
11
+
12
+ import { execFileSync } from 'node:child_process';
13
+ import {
14
+ fs,
15
+ path,
16
+ os,
17
+ readJsonSafe,
18
+ writeJsonAtomic
19
+ } from '../utils/nodeIo.mjs';
20
+ import { recordRuntimeDiagnostic } from '../core-isomorphic/utils/runtime.mjs';
21
+
22
+ const CHUNK_BYTES = 4 * 1024 * 1024;
23
+ const OVERLAP_BYTES = 256;
24
+
25
+ const CAPABILITY_MARKERS = Object.freeze({
26
+ preModelSwitchSupported: 'PreModelSwitch',
27
+ postModelSwitchSupported: 'PostModelSwitch',
28
+ preEffortChangeSupported: 'PreEffortChange',
29
+ hasFromModelKey: 'from_model',
30
+ hasToModelKey: 'to_model',
31
+ hasPromptCacheWarmKey: 'prompt_cache_warm',
32
+ hasContextTokensKey: 'context_tokens',
33
+ hasAskBehavior: 'permissionBehavior==="ask"',
34
+ hasAskDialog: 'A PreModelSwitch hook asked',
35
+ sdkSetModelHooked: 'blocked_by_hook'
36
+ });
37
+
38
+ /**
39
+ * Resolves the underlying JS bundle or native binary when given a Windows `.cmd` / POSIX wrapper.
40
+ * @param {string} candidatePath
41
+ * @returns {string}
42
+ */
43
+ function unwrapClaudeShim(candidatePath) {
44
+ if (!candidatePath || !fs.existsSync(candidatePath)) return candidatePath;
45
+ const ext = path.extname(candidatePath).toLowerCase();
46
+ const dir = path.dirname(candidatePath);
47
+
48
+ if (ext === '.cmd' || ext === '.bat') {
49
+ const pkgBase = path.join(dir, 'node_modules', '@anthropic-ai', 'claude-code');
50
+ const exeInPkg = path.join(pkgBase, 'bin', 'claude.exe');
51
+ const jsInPkg = path.join(pkgBase, 'cli.js');
52
+ if (fs.existsSync(exeInPkg)) return exeInPkg;
53
+ if (fs.existsSync(jsInPkg)) return jsInPkg;
54
+ }
55
+
56
+ return candidatePath;
57
+ }
58
+
59
+ /**
60
+ * Resolves the active `claude` binary/bundle path from options, `CLAUDE_BIN`, or `PATH`.
61
+ * @param {object} [options={}]
62
+ * @returns {string | null}
63
+ */
64
+ export function resolveClaudeBinaryPath(options = {}) {
65
+ const candidates = [];
66
+ if (typeof options.claudeBinPath === 'string' && options.claudeBinPath.trim()) {
67
+ candidates.push(options.claudeBinPath.trim());
68
+ }
69
+ const envBin = globalThis.process?.env?.CLAUDE_BIN;
70
+ if (typeof envBin === 'string' && envBin.trim()) {
71
+ candidates.push(envBin.trim());
72
+ }
73
+
74
+ if (candidates.length === 0) {
75
+ const pathEnv = String(globalThis.process?.env?.PATH || '');
76
+ const sep = globalThis.process?.platform === 'win32' ? ';' : ':';
77
+ const names =
78
+ globalThis.process?.platform === 'win32'
79
+ ? ['claude.exe', 'claude.cmd', 'claude']
80
+ : ['claude'];
81
+ for (const dir of pathEnv.split(sep).filter(Boolean)) {
82
+ for (const name of names) {
83
+ candidates.push(path.join(dir, name));
84
+ }
85
+ }
86
+
87
+ // Standard local CLI & benchmark runtime locations (no hardcoded usernames)
88
+ const homeDir = options.homeDir || os.homedir();
89
+ const tmpDir = os.tmpdir();
90
+ if (homeDir) {
91
+ for (const name of names) {
92
+ candidates.push(path.join(homeDir, '.local', 'bin', name));
93
+ candidates.push(path.join(homeDir, '.claude', 'local', name));
94
+ candidates.push(
95
+ path.join(homeDir, '.claude', 'local', 'node_modules', '@anthropic-ai', 'claude-code', 'bin', name)
96
+ );
97
+ }
98
+ }
99
+ try {
100
+ if (tmpDir && fs.existsSync(tmpDir)) {
101
+ for (const ent of fs.readdirSync(tmpDir)) {
102
+ if (ent.includes('model-switch-runtime')) {
103
+ for (const name of names) {
104
+ candidates.push(
105
+ path.join(tmpDir, ent, 'cli', 'node_modules', '@anthropic-ai', 'claude-code', 'bin', name)
106
+ );
107
+ }
108
+ }
109
+ }
110
+ }
111
+ } catch {
112
+ // Ignore temp directory scan errors
113
+ }
114
+ }
115
+
116
+ for (const raw of candidates) {
117
+ try {
118
+ const unwrapped = unwrapClaudeShim(raw);
119
+ if (unwrapped && fs.existsSync(unwrapped)) {
120
+ const st = fs.statSync(unwrapped);
121
+ if (st.isFile()) return unwrapped;
122
+ }
123
+ } catch {
124
+ // Skip inaccessible candidate
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+
130
+ /**
131
+ * Reads sibling `@anthropic-ai/claude-code/package.json` (fast, zero subprocess) or optionally
132
+ * queries `claude --version` when `options.probeVersion === true`.
133
+ *
134
+ * @param {string} binPath
135
+ * @param {object} [options={}]
136
+ * @returns {string | null}
137
+ */
138
+ function detectClaudeVersion(binPath, options = {}) {
139
+ const pkgCandidates = [
140
+ path.join(path.dirname(binPath), 'package.json'),
141
+ path.join(path.dirname(binPath), '..', 'package.json')
142
+ ];
143
+ for (const pkgPath of pkgCandidates) {
144
+ const parsed = readJsonSafe(pkgPath, null, options);
145
+ if (parsed && parsed.name === '@anthropic-ai/claude-code' && typeof parsed.version === 'string') {
146
+ return parsed.version;
147
+ }
148
+ }
149
+
150
+ if (options.probeVersion === true) {
151
+ try {
152
+ const out = execFileSync(binPath, ['--version'], {
153
+ encoding: 'utf8',
154
+ timeout: 3000,
155
+ stdio: ['ignore', 'pipe', 'ignore']
156
+ }).trim();
157
+ const match = out.match(/(\d+\.\d+\.\d+(?:[-+][^\s]+)?)/);
158
+ if (match) return match[1];
159
+ } catch {
160
+ // Ignore version subprocess failure
161
+ }
162
+ }
163
+ return null;
164
+ }
165
+
166
+ /**
167
+ * Streams a file in bounded 4 MB overlapping chunks to test exact ASCII substring markers
168
+ * without loading large standalone binaries wholly into V8 heap memory.
169
+ *
170
+ * @param {string} binPath
171
+ * @returns {Record<string, boolean>}
172
+ */
173
+ function scanBinaryMarkersChunked(binPath) {
174
+ const foundFlags = Object.fromEntries(Object.keys(CAPABILITY_MARKERS).map((k) => [k, false]));
175
+ const markerEntries = Object.entries(CAPABILITY_MARKERS);
176
+ const buf = Buffer.allocUnsafe(CHUNK_BYTES);
177
+ const fd = fs.openSync(binPath, 'r');
178
+ try {
179
+ let tail = '';
180
+ let bytesRead;
181
+ while ((bytesRead = fs.readSync(fd, buf, 0, CHUNK_BYTES, null)) > 0) {
182
+ const chunkStr = tail + buf.subarray(0, bytesRead).toString('latin1');
183
+ let allFound = true;
184
+ for (const [key, marker] of markerEntries) {
185
+ if (!foundFlags[key]) {
186
+ if (chunkStr.includes(marker)) {
187
+ foundFlags[key] = true;
188
+ } else {
189
+ allFound = false;
190
+ }
191
+ }
192
+ }
193
+ if (allFound) break;
194
+ tail = chunkStr.slice(Math.max(0, chunkStr.length - OVERLAP_BYTES));
195
+ }
196
+ } finally {
197
+ fs.closeSync(fd);
198
+ }
199
+ return foundFlags;
200
+ }
201
+
202
+ /**
203
+ * Inspects the installed Claude Code CLI/bundle for `PreModelSwitch` support and contract parity.
204
+ *
205
+ * @param {object} [options={}]
206
+ * @returns {{
207
+ * found: boolean,
208
+ * binaryPath: string | null,
209
+ * claudeVersion: string | null,
210
+ * preModelSwitchSupported: boolean | null,
211
+ * postModelSwitchSupported: boolean | null,
212
+ * preEffortChangeSupported: boolean | null,
213
+ * supportsAskDecision: boolean | null,
214
+ * sdkSetModelHooked: boolean | null,
215
+ * payloadKeys: { from_model: boolean, to_model: boolean, prompt_cache_warm: boolean, context_tokens: boolean } | null,
216
+ * contractValid: boolean | null,
217
+ * cached: boolean,
218
+ * warning: string | null
219
+ * }}
220
+ */
221
+ export function inspectClaudeBinaryCapabilities(options = {}) {
222
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
223
+ const binPath = resolveClaudeBinaryPath(options);
224
+ if (!binPath) {
225
+ return {
226
+ found: false,
227
+ binaryPath: null,
228
+ claudeVersion: null,
229
+ preModelSwitchSupported: null,
230
+ postModelSwitchSupported: null,
231
+ preEffortChangeSupported: null,
232
+ supportsAskDecision: null,
233
+ sdkSetModelHooked: null,
234
+ payloadKeys: null,
235
+ contractValid: null,
236
+ cached: false,
237
+ warning: null
238
+ };
239
+ }
240
+
241
+ let stat;
242
+ try {
243
+ stat = fs.statSync(binPath);
244
+ } catch {
245
+ return {
246
+ found: false,
247
+ binaryPath: null,
248
+ claudeVersion: null,
249
+ preModelSwitchSupported: null,
250
+ postModelSwitchSupported: null,
251
+ preEffortChangeSupported: null,
252
+ supportsAskDecision: null,
253
+ sdkSetModelHooked: null,
254
+ payloadKeys: null,
255
+ contractValid: null,
256
+ cached: false,
257
+ warning: null
258
+ };
259
+ }
260
+
261
+ const cacheBaseDir = options.homeDir || cwd;
262
+ const cachePath =
263
+ options.cachePath ||
264
+ path.join(cacheBaseDir, '.attention-horizon', 'cache', 'ah_claude_capabilities.json');
265
+ if (!options.bypassCache) {
266
+ const cached = readJsonSafe(cachePath, null, options);
267
+ if (
268
+ cached &&
269
+ cached.binaryPath === binPath &&
270
+ cached.size === stat.size &&
271
+ cached.mtimeMs === stat.mtimeMs &&
272
+ cached.result &&
273
+ typeof cached.result.contractValid === 'boolean'
274
+ ) {
275
+ return { ...cached.result, cached: true };
276
+ }
277
+ }
278
+
279
+ const markers = scanBinaryMarkersChunked(binPath);
280
+ const claudeVersion = options.claudeVersion || detectClaudeVersion(binPath, options);
281
+ const payloadKeys = {
282
+ from_model: markers.hasFromModelKey,
283
+ to_model: markers.hasToModelKey,
284
+ prompt_cache_warm: markers.hasPromptCacheWarmKey,
285
+ context_tokens: markers.hasContextTokensKey
286
+ };
287
+ const supportsAskDecision = Boolean(markers.hasAskBehavior || markers.hasAskDialog);
288
+ const contractValid = Boolean(
289
+ markers.preModelSwitchSupported &&
290
+ payloadKeys.from_model &&
291
+ payloadKeys.to_model &&
292
+ payloadKeys.prompt_cache_warm &&
293
+ supportsAskDecision
294
+ );
295
+
296
+ const warning = contractValid
297
+ ? null
298
+ : `[Highbeam Startup Check] Claude Code (${claudeVersion || 'unknown'}) does not expose the expected undocumented PreModelSwitch hook contract; DET-08 native /model interception is unavailable.`;
299
+
300
+ if (warning && options.recordDiagnostic !== false) {
301
+ recordRuntimeDiagnostic(
302
+ 'claudeHookCapabilities',
303
+ 'inspectClaudeBinaryCapabilities',
304
+ new Error(warning),
305
+ { ...options, cwd }
306
+ );
307
+ }
308
+
309
+ const result = {
310
+ found: true,
311
+ binaryPath: binPath,
312
+ claudeVersion,
313
+ preModelSwitchSupported: markers.preModelSwitchSupported,
314
+ postModelSwitchSupported: markers.postModelSwitchSupported,
315
+ preEffortChangeSupported: markers.preEffortChangeSupported,
316
+ supportsAskDecision,
317
+ sdkSetModelHooked: markers.sdkSetModelHooked,
318
+ payloadKeys,
319
+ contractValid,
320
+ cached: false,
321
+ warning
322
+ };
323
+
324
+ if (options.writeCache !== false && (options.cwd || options.cachePath)) {
325
+ writeJsonAtomic(
326
+ cachePath,
327
+ {
328
+ binaryPath: binPath,
329
+ size: stat.size,
330
+ mtimeMs: stat.mtimeMs,
331
+ result
332
+ },
333
+ options
334
+ );
335
+ }
336
+
337
+ return result;
338
+ }
339
+
340
+ /**
341
+ * Extracts all selectable model IDs and official aliases from an installed Claude Code binary
342
+ * in bounded 4 MB chunks (Item 1.3).
343
+ *
344
+ * @param {string} binPath
345
+ * @returns {{
346
+ * found: boolean,
347
+ * modelIds: string[],
348
+ * aliases: string[],
349
+ * allSelectable: string[]
350
+ * }}
351
+ */
352
+ export function extractClaudeSelectableModelsFromBinary(binPath) {
353
+ if (!binPath || !fs.existsSync(binPath)) {
354
+ return { found: false, modelIds: [], aliases: [], allSelectable: [] };
355
+ }
356
+ const modelIds = new Set();
357
+ const aliases = new Set();
358
+ const buf = Buffer.allocUnsafe(CHUNK_BYTES);
359
+ const overlap = 8192;
360
+ const fd = fs.openSync(binPath, 'r');
361
+ try {
362
+ let tail = '';
363
+ let bytesRead;
364
+ while ((bytesRead = fs.readSync(fd, buf, 0, CHUNK_BYTES, null)) > 0) {
365
+ const chunkStr = tail + buf.subarray(0, bytesRead).toString('latin1');
366
+ if (chunkStr.includes('family:') && chunkStr.includes('display_name:')) {
367
+ for (const m of chunkStr.matchAll(/\{id:"(claude-[a-z0-9-]+)",family:"(?:haiku|sonnet|opus|fable|mythos)"/g)) {
368
+ modelIds.add(m[1]);
369
+ }
370
+ }
371
+ const aliasArrMatch = chunkStr.match(/\[("sonnet","opus"[^\]]{0,240})\]/);
372
+ if (aliasArrMatch) {
373
+ for (const m of aliasArrMatch[1].matchAll(/"([a-z0-9[\]-]+)"/g)) {
374
+ aliases.add(m[1]);
375
+ }
376
+ }
377
+ tail = chunkStr.slice(Math.max(0, chunkStr.length - overlap));
378
+ }
379
+ } finally {
380
+ fs.closeSync(fd);
381
+ }
382
+ const sortedIds = Array.from(modelIds).sort();
383
+ const sortedAliases = Array.from(aliases).sort();
384
+ return {
385
+ found: true,
386
+ modelIds: sortedIds,
387
+ aliases: sortedAliases,
388
+ allSelectable: Array.from(new Set([...sortedIds, ...sortedAliases]))
389
+ };
390
+ }
391
+
392
+ export default {
393
+ resolveClaudeBinaryPath,
394
+ inspectClaudeBinaryCapabilities,
395
+ extractClaudeSelectableModelsFromBinary
396
+ };
@@ -15,8 +15,17 @@ import {
15
15
  getDiagnosticsFilePath,
16
16
  readRuntimeDiagnostics
17
17
  } from '../utils/nodeIo.mjs';
18
- import { loadModelCatalog } from '../core-isomorphic/config/catalogLoader.mjs';
18
+ import {
19
+ isKnownCatalogModel,
20
+ loadModelCatalog
21
+ } from '../core-isomorphic/config/catalogLoader.mjs';
19
22
  import { loadHorizonConfig } from '../core-isomorphic/config/horizonConfig.mjs';
23
+ import { inspectClaudeBinaryCapabilities } from './claudeHookCapabilities.mjs';
24
+ import { readModelSwitchTelemetry } from '../utils/modelSwitchTelemetry.mjs';
25
+ import { auditAntigravityRulesIntegrity } from '../core/layer5_hygiene.mjs';
26
+ import { auditClaudeAutoMemory } from '../core/shield_manager.mjs';
27
+ import { auditProseRuleHookCandidates } from '../core/bucket_b_runtime.mjs';
28
+ import { auditWorkspaceRuleClashes } from '../core/rsl_clash_auditor.mjs';
20
29
 
21
30
  /**
22
31
  * Redacts the user's OS home directory from any diagnostic string.
@@ -185,14 +194,97 @@ export function runDoctorDiagnostics(options = {}) {
185
194
  detail: `20 detectors configured (FlightMode=${config.flightMode}, overrides=${customDetectors})`
186
195
  });
187
196
 
197
+ const agRulesAudit = auditAntigravityRulesIntegrity({ workspacePath: cwd });
198
+ const claudeMemAudit = auditClaudeAutoMemory({
199
+ cwd,
200
+ homeDir: options.homeDir,
201
+ memoryDir: options.memoryDir,
202
+ memoryFilePath: options.memoryFilePath
203
+ });
204
+ const memoryRuleIntegrity = {
205
+ ok: !options.strictRulesCheck || !(agRulesAudit.triggered || claudeMemAudit.triggered),
206
+ warning: Boolean(agRulesAudit.triggered || claudeMemAudit.triggered),
207
+ issues: [...(agRulesAudit.issues || []), ...(claudeMemAudit.issues || [])],
208
+ antigravityRules: agRulesAudit,
209
+ claudeAutoMemory: claudeMemAudit
210
+ };
211
+
212
+ const proseHookCandidates = auditProseRuleHookCandidates(cwd);
213
+ const rslClashAudit = auditWorkspaceRuleClashes(cwd);
188
214
  const hookDiagnostics = inspectHookDiagnostics({ ...options, cwd });
189
- const ok = checks.every((c) => c.ok);
215
+
216
+ // Item 1.2: Warn cleanly when the configured or active session model has no price catalog entry
217
+ const candidateModelSources = [
218
+ options.model,
219
+ options.activeModel,
220
+ config?.model,
221
+ readJsonSafe(path.join(cwd, '.claude', 'settings.local.json'), null, options)?.model,
222
+ readJsonSafe(path.join(cwd, '.claude', 'settings.json'), null, options)?.model,
223
+ readJsonSafe(
224
+ path.join(options.homeDir || os.homedir() || '', '.claude', 'settings.json'),
225
+ null,
226
+ options
227
+ )?.model,
228
+ options.env?.ANTHROPIC_MODEL,
229
+ options.env?.CLAUDE_MODEL,
230
+ globalThis.process?.env?.ANTHROPIC_MODEL,
231
+ globalThis.process?.env?.CLAUDE_MODEL
232
+ ].filter((m) => typeof m === 'string' && m.trim().length > 0);
233
+ const unknownConfiguredModels = Array.from(
234
+ new Set(
235
+ candidateModelSources
236
+ .map((m) => m.trim())
237
+ .filter((m) => !isKnownCatalogModel(m, { ...options, cwd }))
238
+ )
239
+ );
240
+ const warnings = [];
241
+ if (unknownConfiguredModels.length > 0) {
242
+ const warnDetail = `Configured model(s) [${unknownConfiguredModels.join(', ')}] not in price catalog; dollar figures and price-based holds are disabled (unknown model state).`;
243
+ warnings.push(warnDetail);
244
+ checks.push({
245
+ id: 'model_catalog_coverage',
246
+ status: 'WARN',
247
+ ok: true,
248
+ detail: warnDetail
249
+ });
250
+ }
251
+
252
+ const modelSwitchTelemetry = readModelSwitchTelemetry({
253
+ homeDir: options.homeDir,
254
+ telemetryPath: options.telemetryPath
255
+ });
256
+ const claudeCapabilities = inspectClaudeBinaryCapabilities({
257
+ ...options,
258
+ cwd,
259
+ recordDiagnostic: false
260
+ });
261
+ if (rslClashAudit.clashCount > 0) {
262
+ const clashMsg = `${rslClashAudit.clashCount} RSL rule conflict(s) detected: ${rslClashAudit.clashes.slice(0, 2).map((c) => c.reason).join('; ')}`;
263
+ warnings.push(clashMsg);
264
+ checks.push({
265
+ id: 'rsl_rule_clashes',
266
+ status: 'WARN',
267
+ ok: true,
268
+ detail: clashMsg
269
+ });
270
+ }
271
+ const ok =
272
+ checks.every((c) => c.ok) &&
273
+ memoryRuleIntegrity.ok &&
274
+ (!options.strictClaudeCheck || Boolean(claudeCapabilities.found && claudeCapabilities.contractValid));
190
275
 
191
276
  return {
192
277
  ok,
193
278
  nodeVersion,
194
279
  checks,
195
- hookDiagnostics
280
+ warnings,
281
+ claudeCapabilities,
282
+ hookDiagnostics,
283
+ modelSwitchTelemetry,
284
+ memoryRuleIntegrity,
285
+ proseHookCandidates,
286
+ rslRuleClashes: rslClashAudit.clashCount,
287
+ rslClashes: rslClashAudit.clashes.slice(0, 5)
196
288
  };
197
289
  }
198
290