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
@@ -0,0 +1,402 @@
1
+ /**
2
+ * @file hooks/handlers/config-change.mjs
3
+ * Tier 2 Command Hook handler for Claude Code `ConfigChange` (`#1 MID_SESSION_CACHE_BUST`).
4
+ *
5
+ * Guards warm prompt-cache prefixes (`cachedTokens > 25,000`, `ttlSeconds > 0`) against
6
+ * mid-session settings/plugin/MCP mutations that trigger full uncached prefix rewrites:
7
+ * - `/effort` / `effortLevel` on Anthropic models without unified effort-invariant caching
8
+ * - `fastMode` toggle on warm prefix
9
+ * - `mcpServers` / `enabledPlugins` / `plugins` / `tools` (`tools_changed` prefix bust)
10
+ * - Mid-session `model` downshift (`Opus -> Sonnet`), queuing `pendingDownshiftModel`
11
+ * until `PostCompact` so the downshift executes at $0 cold-cache penalty.
12
+ */
13
+
14
+ import { readLiveStateSnapshot } from '../../src/core-isomorphic/telemetry/telemetryBridge.mjs';
15
+ import {
16
+ computeTotalPromptTokens,
17
+ isKnownCatalogModel,
18
+ normalizeModelId,
19
+ resolveEffectiveRates
20
+ } from '../../src/core-isomorphic/config/catalogLoader.mjs';
21
+ import { loadHorizonConfig, resolveDetectorOverride } from '../../src/core-isomorphic/config/horizonConfig.mjs';
22
+ import {
23
+ CacheGravityRouter,
24
+ FLIGHT_MODES,
25
+ getEffortMutationCacheCapability,
26
+ isSilentOrOffMode,
27
+ normalizeFlightMode
28
+ } from '../../src/core-isomorphic/coach/cacheGravityRouter.mjs';
29
+ import {
30
+ readBreakerStateSnapshot,
31
+ writeBreakerStateSnapshot
32
+ } from '../../src/core-isomorphic/guards/circuitBreakers.mjs';
33
+ import { recordInterventionSavings } from '../../src/core-isomorphic/coach/savedQuotaLedger.mjs';
34
+ import {
35
+ isCliEntrypoint,
36
+ readStdinJsonAsync,
37
+ exitPassThrough,
38
+ exitDiagnosticZero,
39
+ exitWithStdoutJson
40
+ } from './hookIo.mjs';
41
+
42
+ export const WARM_CACHE_CONFIG_GUARD_FLOOR_TOKENS = 25_000;
43
+
44
+ const CACHE_BUSTING_KEY_PATTERNS = [
45
+ { regex: /^(?:effort|effortLevel|reasoningEffort|thinkingBudget)$/i, kind: 'effort' },
46
+ { regex: /^(?:fastMode|fast_mode)$/i, kind: 'fastMode' },
47
+ { regex: /^(?:mcpServers|mcp_servers|enabledPlugins|plugins|tools)$/i, kind: 'tools_changed' },
48
+ { regex: /^(?:model|defaultModel)$/i, kind: 'model' }
49
+ ];
50
+
51
+ function classifyConfigMutation(event = {}) {
52
+ const rawKey = String(
53
+ event.setting_key || event.settingKey || event.key || event.source || ''
54
+ ).trim();
55
+ for (const entry of CACHE_BUSTING_KEY_PATTERNS) {
56
+ if (entry.regex.test(rawKey)) {
57
+ return { busting: true, kind: entry.kind, key: rawKey };
58
+ }
59
+ }
60
+ const sourceStr = String(event.source || '').toLowerCase();
61
+ if (sourceStr.includes('plugin') || sourceStr.includes('mcp')) {
62
+ return { busting: true, kind: 'tools_changed', key: rawKey || sourceStr };
63
+ }
64
+ return { busting: false, kind: null, key: rawKey };
65
+ }
66
+
67
+ function isOpusToSonnetDownshift(oldModel = '', newModel = '') {
68
+ const prev = normalizeModelId(oldModel);
69
+ const next = normalizeModelId(newModel);
70
+ return prev.includes('opus') && next.includes('sonnet');
71
+ }
72
+
73
+ /**
74
+ * Evaluates a Claude Code `ConfigChange` hook payload against warm-cache gravity.
75
+ *
76
+ * @param {object} [event={}]
77
+ * @param {object} [options={}]
78
+ */
79
+ export function runConfigChangeHook(event = {}, options = {}) {
80
+ const sessionId = event.session_id || event.sessionId || 'default';
81
+ const cwdOptions = event.cwd && !options.cwd ? { ...options, cwd: event.cwd } : options;
82
+ const horizonConfig = options.horizonConfig || loadHorizonConfig(cwdOptions);
83
+ const liveState = options.telemetryState || readLiveStateSnapshot(sessionId, cwdOptions) || {};
84
+
85
+ const effectiveMode = normalizeFlightMode(
86
+ event.mode || options.mode || liveState.flightMode || horizonConfig.flightMode || 'COACH'
87
+ );
88
+ const detOverride = resolveDetectorOverride('DET-09', horizonConfig);
89
+
90
+ if (isSilentOrOffMode(effectiveMode) || detOverride === 'off') {
91
+ return {
92
+ exitCode: 0,
93
+ stdout: '',
94
+ stderr: '',
95
+ verdict: { triggered: false, decision: 'allow', reason: null }
96
+ };
97
+ }
98
+
99
+ const classification = classifyConfigMutation(event);
100
+ if (!classification.busting) {
101
+ return {
102
+ exitCode: 0,
103
+ stdout: '',
104
+ stderr: '',
105
+ verdict: { triggered: false, decision: 'allow', reason: null }
106
+ };
107
+ }
108
+
109
+ if (
110
+ event.old_value !== undefined &&
111
+ event.new_value !== undefined &&
112
+ JSON.stringify(event.old_value) === JSON.stringify(event.new_value)
113
+ ) {
114
+ return {
115
+ exitCode: 0,
116
+ stdout: '',
117
+ stderr: '',
118
+ verdict: { triggered: false, decision: 'allow', reason: 'Unchanged config value.' }
119
+ };
120
+ }
121
+
122
+ const cachedTokens = Math.max(
123
+ 0,
124
+ Number(
125
+ event.cached_tokens ??
126
+ event.cachedTokens ??
127
+ liveState?.contextWindow?.cachedTokens ??
128
+ liveState?.contextWindow?.cacheReadTokens ??
129
+ 0
130
+ )
131
+ );
132
+ const ttlSeconds = Number(
133
+ event.ttl_remaining_seconds ??
134
+ event.ttlRemainingSeconds ??
135
+ liveState?.promptCache?.ttlSeconds ??
136
+ 300
137
+ );
138
+ const cacheWarm =
139
+ ttlSeconds > 0 &&
140
+ Boolean(event.cache_warm ?? event.cacheWarm ?? liveState?.promptCache?.warm ?? cachedTokens > 0);
141
+ const floorTokens = Number(
142
+ options.warmCacheFloorTokens ?? WARM_CACHE_CONFIG_GUARD_FLOOR_TOKENS
143
+ );
144
+
145
+ if (!cacheWarm || cachedTokens < floorTokens) {
146
+ return {
147
+ exitCode: 0,
148
+ stdout: '',
149
+ stderr: '',
150
+ verdict: {
151
+ triggered: false,
152
+ decision: 'allow',
153
+ cachedTokens,
154
+ reason: 'Cache cold or below warm-prefix guard floor.'
155
+ }
156
+ };
157
+ }
158
+
159
+ const currentModel = String(
160
+ event.old_model ||
161
+ (classification.kind === 'model' ? event.old_value : null) ||
162
+ event.model ||
163
+ liveState.modelId ||
164
+ 'claude-opus-5-5'
165
+ );
166
+
167
+ // Gemini thinking-level changes preserve implicit cache; only Anthropic/Claude effort changes bust cached history
168
+ if (classification.kind === 'effort' && /gemini/i.test(currentModel)) {
169
+ return {
170
+ exitCode: 0,
171
+ stdout: '',
172
+ stderr: '',
173
+ verdict: {
174
+ triggered: false,
175
+ decision: 'allow',
176
+ reason: 'Gemini thinking-level adjustments preserve implicit prefix cache.'
177
+ }
178
+ };
179
+ }
180
+
181
+ // Item 1.2: Unknown model -> explicit unknownModel state (zero $ figures, no price-based hold, one-line advisory)
182
+ if (!isKnownCatalogModel(currentModel, cwdOptions)) {
183
+ const effortClause =
184
+ classification.kind === 'effort' ? ' (effort cache behavior unverified for this model)' : '';
185
+ const msg = `[Highbeam DET-09 Advisory] Prices are unknown for ${currentModel}${effortClause}; skipping price-based guard.`;
186
+ const stdoutJson = {
187
+ systemMessage: msg,
188
+ hookSpecificOutput: {
189
+ hookEventName: 'ConfigChange',
190
+ additionalContext: msg
191
+ }
192
+ };
193
+ return {
194
+ exitCode: 0,
195
+ stdout: JSON.stringify(stdoutJson),
196
+ stdoutJson,
197
+ stderr: '',
198
+ verdict: {
199
+ detectorId: 'DET-09',
200
+ triggered: false,
201
+ kind: classification.kind,
202
+ key: classification.key,
203
+ decision: 'allow',
204
+ advisory: true,
205
+ unknownModel: true,
206
+ cachedTokens,
207
+ avoidedRewritePenaltyUSD: null,
208
+ effortCacheCapability:
209
+ classification.kind === 'effort'
210
+ ? getEffortMutationCacheCapability(currentModel, cwdOptions)
211
+ : null,
212
+ reason: msg
213
+ }
214
+ };
215
+ }
216
+
217
+ // Item 3: DET-09 effort capability matrix (stay silent on measured cache-preserving models like Sonnet 5.5 / Opus 5.5)
218
+ const normalizedCurrentModel = normalizeModelId(currentModel);
219
+ const effortCap =
220
+ classification.kind === 'effort'
221
+ ? getEffortMutationCacheCapability(normalizedCurrentModel, cwdOptions)
222
+ : null;
223
+
224
+ if (effortCap && effortCap.invalidatesCache === 'no') {
225
+ return {
226
+ exitCode: 0,
227
+ stdout: '',
228
+ stderr: '',
229
+ verdict: {
230
+ detectorId: 'DET-09',
231
+ triggered: false,
232
+ kind: classification.kind,
233
+ key: classification.key,
234
+ decision: 'allow',
235
+ advisory: false,
236
+ cachedTokens,
237
+ avoidedRewritePenaltyUSD: 0,
238
+ effortCacheCapability: effortCap,
239
+ reason: null
240
+ }
241
+ };
242
+ }
243
+
244
+ const totalPromptTokens = Math.max(
245
+ cachedTokens,
246
+ computeTotalPromptTokens(liveState.contextWindow || { cacheReadTokens: cachedTokens })
247
+ );
248
+ const ttlTier = liveState?.promptCache?.ttlTier === '1h' ? '1h' : '5m';
249
+ const rates = resolveEffectiveRates(normalizedCurrentModel, totalPromptTokens, cwdOptions);
250
+ const writeRate = ttlTier === '1h' ? rates.write1hPer1M : rates.write5mPer1M;
251
+ const avoidedRewritePenaltyUSD = Number(
252
+ Math.max(0, (cachedTokens / 1_000_000) * (writeRate - rates.readPer1M)).toFixed(6)
253
+ );
254
+
255
+ const router = new CacheGravityRouter({ mode: effectiveMode, ...cwdOptions });
256
+ const priorSnap = readBreakerStateSnapshot(sessionId, cwdOptions) || {};
257
+ if (Array.isArray(priorSnap.queuedMutations)) {
258
+ router.mutationQueue.items = [...priorSnap.queuedMutations];
259
+ }
260
+
261
+ let nextPendingDownshift = priorSnap.pendingDownshiftModel || null;
262
+ let nextPendingDownshiftRecord = priorSnap.pending_downshift || null;
263
+ const newValStr =
264
+ typeof event.new_value === 'string'
265
+ ? event.new_value
266
+ : JSON.stringify(event.new_value ?? '');
267
+
268
+ if (classification.kind === 'model' && isOpusToSonnetDownshift(normalizedCurrentModel, newValStr)) {
269
+ nextPendingDownshift = normalizeModelId(newValStr);
270
+ nextPendingDownshiftRecord = {
271
+ fromModel: normalizedCurrentModel,
272
+ toModel: nextPendingDownshift,
273
+ recordedAt: new Date().toISOString()
274
+ };
275
+ }
276
+
277
+ router.mutationQueue.enqueue({
278
+ type: classification.kind,
279
+ key: classification.key,
280
+ value: event.new_value,
281
+ cachedTokens,
282
+ avoidedRewritePenaltyUSD,
283
+ reason: `Deferred ${classification.kind} change (${classification.key}) until PostCompact`
284
+ });
285
+
286
+ if (options.persistState !== false && Boolean(event.cwd || options.cwd || options.breakerStatePath)) {
287
+ writeBreakerStateSnapshot(
288
+ sessionId,
289
+ {
290
+ ...priorSnap,
291
+ updatedAt: Date.now(),
292
+ pendingDownshiftModel: nextPendingDownshift,
293
+ pending_downshift: nextPendingDownshiftRecord,
294
+ queuedMutations: router.mutationQueue.toJSON()
295
+ },
296
+ cwdOptions
297
+ );
298
+ }
299
+
300
+ const shouldBlock = effectiveMode === FLIGHT_MODES.AUTO_PILOT || detOverride === 'block';
301
+ const downshiftHint = nextPendingDownshift
302
+ ? ` Queued pending_downshift -> ${nextPendingDownshift} for next compaction.`
303
+ : ' Wait for /compact or spawn an isolated subagent instead.';
304
+ const effortLabel =
305
+ effortCap?.invalidatesCache === 'unknown'
306
+ ? ' (unverified for this model)'
307
+ : effortCap?.provenance
308
+ ? ` (${effortCap.provenance})`
309
+ : '';
310
+ const message =
311
+ `[Highbeam Quota Shield — Warm-Cache Config Bust (${classification.kind})${effortLabel}] ` +
312
+ `Changing "${classification.key}" while ${cachedTokens.toLocaleString()} tokens are warm on ${normalizedCurrentModel} ` +
313
+ `invalidates the prompt cache prefix (+$${avoidedRewritePenaltyUSD.toFixed(4)} cold rewrite tax).` +
314
+ downshiftHint;
315
+
316
+ if (
317
+ shouldBlock &&
318
+ avoidedRewritePenaltyUSD > 0 &&
319
+ options.recordLedger !== false &&
320
+ Boolean(event.cwd || options.cwd || options.ledgerPath || options.recordLedger)
321
+ ) {
322
+ recordInterventionSavings(
323
+ {
324
+ sessionId,
325
+ category: 'DET_09_CONFIG_CACHE_SHIELD',
326
+ modelId: normalizedCurrentModel,
327
+ savedTokens: cachedTokens,
328
+ savedUSD: avoidedRewritePenaltyUSD,
329
+ dedupeId: `${classification.kind}:${classification.key}:${cachedTokens}`,
330
+ detail: `Held warm-prefix ${classification.kind} mutation (${cachedTokens.toLocaleString()} tok)`
331
+ },
332
+ cwdOptions
333
+ );
334
+ }
335
+
336
+ const verdict = {
337
+ detectorId: 'DET-09',
338
+ triggered: true,
339
+ kind: classification.kind,
340
+ key: classification.key,
341
+ decision: shouldBlock ? 'block' : 'allow',
342
+ advisory: !shouldBlock,
343
+ cachedTokens,
344
+ avoidedRewritePenaltyUSD,
345
+ effortCacheCapability: effortCap,
346
+ pendingDownshiftModel: nextPendingDownshift,
347
+ pending_downshift: nextPendingDownshiftRecord,
348
+ reason: message
349
+ };
350
+
351
+ if (shouldBlock) {
352
+ const stdoutJson = {
353
+ decision: 'block',
354
+ reason: message
355
+ };
356
+ return {
357
+ exitCode: 0,
358
+ stdout: JSON.stringify(stdoutJson),
359
+ stdoutJson,
360
+ stderr: '',
361
+ verdict
362
+ };
363
+ }
364
+
365
+ const stdoutJson = {
366
+ systemMessage: message,
367
+ hookSpecificOutput: {
368
+ hookEventName: 'ConfigChange',
369
+ additionalContext: message
370
+ }
371
+ };
372
+ return {
373
+ exitCode: 0,
374
+ stdout: JSON.stringify(stdoutJson),
375
+ stdoutJson,
376
+ stderr: '',
377
+ verdict
378
+ };
379
+ }
380
+
381
+ export async function executeConfigChangeCli(cliOptions = {}) {
382
+ const readPayload = cliOptions.readPayload || readStdinJsonAsync;
383
+ const runHook = cliOptions.runHook || runConfigChangeHook;
384
+ const ioOverride = cliOptions.ioOverride || {};
385
+ try {
386
+ const payload = await readPayload(cliOptions.timeoutMs);
387
+ const res = runHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
388
+ if (res.stdout) {
389
+ exitWithStdoutJson(res.stdout, ioOverride);
390
+ } else {
391
+ exitPassThrough(ioOverride.exitFn);
392
+ }
393
+ } catch (err) {
394
+ exitDiagnosticZero(err?.message || String(err), 'ConfigChange', ioOverride);
395
+ }
396
+ }
397
+
398
+ if (isCliEntrypoint(import.meta.url)) {
399
+ executeConfigChangeCli().catch((err) => {
400
+ exitDiagnosticZero(err?.message || String(err), 'ConfigChange');
401
+ });
402
+ }
@@ -253,3 +253,59 @@ export function exitWithStdoutJson(payload, ioOverride = {}) {
253
253
  export function exitWithHookSpecificOutput(hookSpecificOutput, ioOverride = {}) {
254
254
  exitWithStdoutJson({ hookSpecificOutput }, ioOverride);
255
255
  }
256
+
257
+ /**
258
+ * Arms a self-timeout fail-closed watchdog below host hook kill deadline (`FM-8`).
259
+ * When triggered before `disarm()`, invokes `onTimeout()` and exits `2` via stderr.
260
+ *
261
+ * @param {object} [options={}]
262
+ */
263
+ export function armFailClosedWatchdog(options = {}) {
264
+ const timeoutMs = Math.max(50, Math.min(4500, Number(options.timeoutMs) || 3500));
265
+ const hookEventName = options.hookEventName || 'PreToolUse';
266
+ const ioOverride = options.ioOverride || {};
267
+ const exitFn = ioOverride.exitFn || globalThis.process?.exit;
268
+ const stderrWrite =
269
+ ioOverride.stderrWrite ||
270
+ ioOverride.writeStderr ||
271
+ ((s) => globalThis.process?.stderr?.write?.(s));
272
+ let settled = false;
273
+ let timedOut = false;
274
+
275
+ const timer = setTimeout(() => {
276
+ if (settled) return;
277
+ settled = true;
278
+ timedOut = true;
279
+ try {
280
+ if (typeof options.onTimeout === 'function') {
281
+ options.onTimeout({ timeoutMs, hookEventName });
282
+ }
283
+ } catch {
284
+ // ignore timeout callback failure and still fail closed
285
+ }
286
+ const msg = String(
287
+ options.reason ||
288
+ `[Hook Watchdog] ${hookEventName} exceeded ${timeoutMs}ms internal deadline; failing closed (exit 2).`
289
+ ).trim();
290
+ if (hookEventName === 'WorktreeCreate' || hookEventName === 'PermissionRequest') {
291
+ exitFn?.(0);
292
+ return;
293
+ }
294
+ stderrWrite?.(`${msg}\n`);
295
+ exitFn?.(2);
296
+ }, timeoutMs);
297
+
298
+ if (typeof timer.unref === 'function') {
299
+ timer.unref();
300
+ }
301
+
302
+ return {
303
+ timeoutMs,
304
+ isTimedOut: () => timedOut,
305
+ disarm: () => {
306
+ if (settled) return;
307
+ settled = true;
308
+ clearTimeout(timer);
309
+ }
310
+ };
311
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @file hooks/handlers/post-model-switch.mjs
3
+ * Standalone Node CLI handler for Claude Code `PostModelSwitch` (`DET-08` acceptance telemetry).
4
+ *
5
+ * Contract note (Claude Code 2.1.x):
6
+ * Any `stdout` emitted on `PostModelSwitch` with exit 0 is injected as model context on the
7
+ * next turn, so this handler MUST return empty `stdout` and `stderr` with exit code `0`.
8
+ */
9
+
10
+ import { recordPostModelSwitchEvent } from '../../src/utils/modelSwitchTelemetry.mjs';
11
+ import {
12
+ readBreakerStateSnapshot,
13
+ writeBreakerStateSnapshot
14
+ } from '../../src/core-isomorphic/guards/circuitBreakers.mjs';
15
+ import { isCliEntrypoint, readStdinJsonAsync, exitPassThrough } from './hookIo.mjs';
16
+
17
+ /**
18
+ * Evaluate `PostModelSwitch` payload and update local acceptance telemetry.
19
+ *
20
+ * @param {object} [event={}]
21
+ * @param {object} [options={}]
22
+ * @returns {{ exitCode: number, stdout: string, stderr: string, telemetryRecorded: boolean }}
23
+ */
24
+ export function runPostModelSwitchHook(event = {}, options = {}) {
25
+ let telemetryRecorded = false;
26
+ const shouldRecordTelemetry =
27
+ options.recordSwitchTelemetry !== false &&
28
+ Boolean(
29
+ options.cliInvocation ||
30
+ options.homeDir ||
31
+ options.telemetryPath ||
32
+ options.recordSwitchTelemetry ||
33
+ globalThis.process?.env?.AH_MODEL_SWITCH_TELEMETRY_PATH
34
+ );
35
+
36
+ if (shouldRecordTelemetry) {
37
+ try {
38
+ recordPostModelSwitchEvent(event, {
39
+ homeDir: options.homeDir,
40
+ telemetryPath: options.telemetryPath
41
+ });
42
+ telemetryRecorded = true;
43
+ } catch {
44
+ // Fail-open: never block or inject stdout context on PostModelSwitch telemetry error
45
+ }
46
+ }
47
+
48
+ // Item 4.4: Clear pending_downshift once the model switch actually executes
49
+ const shouldPersistBreaker =
50
+ options.persistState !== false &&
51
+ Boolean(event.cwd || options.cwd || options.breakerStatePath || options.cliInvocation);
52
+ if (shouldPersistBreaker) {
53
+ try {
54
+ const sessionId = event.session_id || event.sessionId || 'default';
55
+ const cwdOptions = event.cwd && !options.cwd ? { ...options, cwd: event.cwd } : options;
56
+ const snap = readBreakerStateSnapshot(sessionId, cwdOptions);
57
+ if (snap && (snap.pending_downshift || snap.pendingDownshiftModel || snap.justCompacted)) {
58
+ writeBreakerStateSnapshot(
59
+ sessionId,
60
+ {
61
+ ...snap,
62
+ updatedAt: Date.now(),
63
+ pending_downshift: null,
64
+ pendingDownshiftModel: null,
65
+ justCompacted: false
66
+ },
67
+ cwdOptions
68
+ );
69
+ }
70
+ } catch {
71
+ // Fail-open on local state cleanup
72
+ }
73
+ }
74
+
75
+ return {
76
+ exitCode: 0,
77
+ stdout: '',
78
+ stderr: '',
79
+ telemetryRecorded
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Fail-open CLI runner for `PostModelSwitch`.
85
+ * Always exits `0` with empty stdout/stderr so no extra context is injected.
86
+ *
87
+ * @param {object} [cliOptions={}]
88
+ */
89
+ export async function executePostModelSwitchCli(cliOptions = {}) {
90
+ const readPayload = cliOptions.readPayload || readStdinJsonAsync;
91
+ const runHook = cliOptions.runHook || runPostModelSwitchHook;
92
+ const ioOverride = cliOptions.ioOverride || {};
93
+ const isRealCliRun =
94
+ !cliOptions.ioOverride && !cliOptions.readPayload && !cliOptions.runHook;
95
+ try {
96
+ const payload = await readPayload(cliOptions.timeoutMs);
97
+ runHook(payload, {
98
+ cliInvocation: isRealCliRun,
99
+ ...(cliOptions.hookOptions || {})
100
+ });
101
+ } catch {
102
+ // Fail-open on stdin parse timeout or telemetry errors
103
+ }
104
+ exitPassThrough(ioOverride.exitFn);
105
+ }
106
+
107
+ if (isCliEntrypoint(import.meta.url)) {
108
+ executePostModelSwitchCli().catch(() => {
109
+ exitPassThrough();
110
+ });
111
+ }