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
@@ -4,17 +4,246 @@
4
4
  * and `HysteresisLock` for Claude Code Highbeam.
5
5
  *
6
6
  * Implements the algebraic cross-model break-even equation:
7
- * C* = [ O * (P_out,curr - P_out,target) ] / [ P_write5m,target - P_read,curr ]
8
- * - Opus 5.5 -> Sonnet 5.5 (O = 1,500): C* = 6,522 tokens
9
- * - Opus 4.6 -> Sonnet 4.6 (O = 1,500): C* = 4,615 tokens
7
+ * C* = [ O * (P_out,curr - P_out,target) ] / [ P_write,target - P_read,curr ]
8
+ * with all rates and thresholds derived dynamically from the price catalog at runtime.
10
9
  */
11
10
 
12
11
  import {
12
+ BUILTIN_CATALOG,
13
+ isKnownCatalogModel,
13
14
  normalizeModelId,
14
15
  computeTotalPromptTokens,
15
16
  resolveEffectiveRates
16
17
  } from '../config/catalogLoader.mjs';
17
18
 
19
+ export const DEFAULT_FALLBACK_INITIAL_PREFIX_TOKENS = 9000;
20
+ export const DEFAULT_REQUESTS_PER_TURN = 1.0;
21
+
22
+ /**
23
+ * Per-model `DET-09` capability matrix for mid-session `effort` changes with provenance:
24
+ * - `claude-sonnet-4-6`: invalidates whole prefix (`EF1_46`: 0% cache read, +38.7% cost) -> `yes`
25
+ * - `claude-opus-4-6`: invalidates whole prefix (earlier article experiment) -> `yes`
26
+ * - `claude-sonnet-5-5`: keeps cache (`r2_effort.csv` & R2 rerun, n = 3: 99.3% cache read, thinking 1.47-1.57x) -> `no`
27
+ * - `claude-opus-5-5`: keeps cache (`currency_55.csv` `effort_only_55`: 26,130 vs 26,126 read; behaviour unverified) -> `no`
28
+ * - All other models: `unknown` (warn as before, labelled `"unverified for this model"`).
29
+ */
30
+ export const MODEL_EFFORT_CACHE_CAPABILITIES = Object.freeze({
31
+ 'claude-sonnet-4-6': Object.freeze({
32
+ modelId: 'claude-sonnet-4-6',
33
+ invalidatesCache: 'yes',
34
+ invalidationScope: 'whole_prefix',
35
+ status: 'measured',
36
+ provenance: 'EF1_46 (Sonnet 4.6: 0% cache read, +38.7% cost)'
37
+ }),
38
+ 'claude-opus-4-6': Object.freeze({
39
+ modelId: 'claude-opus-4-6',
40
+ invalidatesCache: 'yes',
41
+ invalidationScope: 'whole_prefix',
42
+ status: 'measured',
43
+ provenance: 'earlier article experiment (Opus 4.6 effort-only invalidation)'
44
+ }),
45
+ 'claude-sonnet-5-5': Object.freeze({
46
+ modelId: 'claude-sonnet-5-5',
47
+ invalidatesCache: 'no',
48
+ invalidationScope: 'none',
49
+ status: 'measured, n = 3 with behaviour change',
50
+ provenance:
51
+ 'r2_effort.csv & R2 behavioural rerun (Sonnet 5.5, n = 3: cache kept 99.3%, thinking 1.47-1.57x control)'
52
+ }),
53
+ 'claude-opus-5-5': Object.freeze({
54
+ modelId: 'claude-opus-5-5',
55
+ invalidatesCache: 'no',
56
+ invalidationScope: 'none',
57
+ status: 'measured for cache only; behaviour unverified',
58
+ provenance:
59
+ 'currency_55.csv effort_only_55 (Opus 5.5: cache kept 26,130 vs 26,126 control; behaviour unverified)'
60
+ })
61
+ });
62
+
63
+ /**
64
+ * Resolves `DET-09` mid-session `effort` cache-invalidation capability for a model.
65
+ * @param {string} [modelId='']
66
+ * @param {object} [options={}]
67
+ */
68
+ export function getEffortMutationCacheCapability(modelId = '', options = {}) {
69
+ const known = isKnownCatalogModel(modelId, options);
70
+ const normalized = known ? normalizeModelId(modelId, options) : 'unknown';
71
+ const entry = known ? MODEL_EFFORT_CACHE_CAPABILITIES[normalized] : null;
72
+ if (entry) {
73
+ return entry;
74
+ }
75
+ return {
76
+ modelId: known ? normalized : String(modelId || 'unknown'),
77
+ invalidatesCache: 'unknown',
78
+ invalidationScope: 'unknown',
79
+ status: 'unverified for this model',
80
+ label: 'unverified for this model',
81
+ provenance: 'unverified for this model (not in EF1_46, R2, or currency_55)'
82
+ };
83
+ }
84
+
85
+ /**
86
+ * Placeholder empirical survival prior derived from 496 Antigravity IDE workstation sessions
87
+ * (376 single-prompt/subagent, 120 interactive) measured in API requests (`api_requests`),
88
+ * NOT native Claude Code session logs. Converted to turns using the session's `requestsPerTurn`.
89
+ */
90
+ export const EMPIRICAL_SESSION_API_CALL_PRIOR = Object.freeze({
91
+ isPlaceholderPrior: true,
92
+ provenance: 'placeholder_antigravity_ide_workstation_logs_not_claude_code',
93
+ unit: 'api_requests',
94
+ note: 'Placeholder distribution derived from 496 Antigravity IDE workstation planner runs (376 subagent/single-prompt, 120 interactive) in API requests, NOT Claude Code telemetry; convert to turns via observed requestsPerTurn.',
95
+ sampleCount: 496,
96
+ interactiveSampleCount: 120,
97
+ unconditionalMedian: 62,
98
+ unconditionalP25: 35,
99
+ unconditionalP75: 96,
100
+ survivalBuckets: Object.freeze([
101
+ { label: '0-3_requests', maxTurn: 3, remainingMedian: 59 },
102
+ { label: '4-6_requests', maxTurn: 6, remainingMedian: 57 },
103
+ { label: '7-12_requests', maxTurn: 12, remainingMedian: 54 },
104
+ { label: '13-24_requests', maxTurn: 24, remainingMedian: 47 },
105
+ { label: '25+_requests', maxTurn: Infinity, remainingMedian: 34 }
106
+ ])
107
+ });
108
+
109
+ /**
110
+ * Resolves a finite positive API-requests-per-turn ratio from session observations,
111
+ * falling back cleanly to `DEFAULT_REQUESTS_PER_TURN` (1.0).
112
+ */
113
+ export function resolveRequestsPerTurn(context = {}, options = {}) {
114
+ const explicitRpt = Number(context.requestsPerTurn ?? options.requestsPerTurn);
115
+ if (Number.isFinite(explicitRpt) && explicitRpt > 0) {
116
+ return {
117
+ requestsPerTurn: Number(explicitRpt.toFixed(4)),
118
+ source: 'observed_requests_per_turn'
119
+ };
120
+ }
121
+ const turns = Math.max(0, Number(context.turnsCompleted ?? context.currentTurn ?? 0));
122
+ const calls = Number(context.apiCallsCompleted ?? options.apiCallsCompleted);
123
+ if (turns > 0 && Number.isFinite(calls) && calls > 0) {
124
+ return {
125
+ requestsPerTurn: Number((calls / turns).toFixed(4)),
126
+ source: 'derived_api_calls_per_turn'
127
+ };
128
+ }
129
+ return {
130
+ requestsPerTurn: DEFAULT_REQUESTS_PER_TURN,
131
+ source: 'default_1.0'
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Estimates expected remaining **turns** for a running session (`C1e` / `rule_v2`) by combining:
137
+ * 1. Conditional survival remaining **API requests** from local Claude Code transcripts (`>= 5` sessions)
138
+ * or the labeled placeholder 496-session Antigravity prior, converted via `requestsPerTurn`.
139
+ * 2. Context-ceiling compaction bound (using dynamic `contextCeiling`, observed Turn-0/1 prefix,
140
+ * and observed growth per API request -> converted to turns).
141
+ *
142
+ * Returns `expectedRemainingTurns = min(empiricalResidualTurns, turnsUntilCompact)`.
143
+ *
144
+ * @param {object} [context={}]
145
+ * @param {object} [options={}]
146
+ * @returns {object}
147
+ */
148
+ export function estimateEmpiricalRemainingTurns(context = {}, options = {}) {
149
+ const turnsCompleted = Math.max(0, Number(context.turnsCompleted ?? context.currentTurn ?? 0));
150
+ const cachedTokens = Math.max(0, Number(context.cachedTokens ?? 0));
151
+ const contextCeiling = Math.max(10_000, Number(context.contextCeiling || 200_000));
152
+ const autoCompactLimitTokens = Math.max(
153
+ 10_000,
154
+ Number(context.autoCompactLimitTokens || Math.round(contextCeiling * 0.8))
155
+ );
156
+ const rptInfo = resolveRequestsPerTurn(context, options);
157
+ const requestsPerTurn = rptInfo.requestsPerTurn;
158
+ const rawApiCalls = Number(context.apiCallsCompleted ?? options.apiCallsCompleted);
159
+ const apiCallsCompleted =
160
+ Number.isFinite(rawApiCalls) && rawApiCalls >= 0
161
+ ? rawApiCalls
162
+ : Math.round(turnsCompleted * requestsPerTurn);
163
+
164
+ let empiricalResidualRequests;
165
+ let priorBucket = '25+_requests';
166
+ let source = 'placeholder_antigravity_496_prior';
167
+ let isPlaceholderPrior = true;
168
+ let priorProvenance = EMPIRICAL_SESSION_API_CALL_PRIOR.provenance;
169
+ const hist = options.historicalSessionApiCalls;
170
+ if (Array.isArray(hist) && hist.length >= 5) {
171
+ source = 'local_transcripts';
172
+ isPlaceholderPrior = false;
173
+ priorProvenance = 'local_claude_code_transcripts';
174
+ const survivors = hist
175
+ .map((n) => Number(n))
176
+ .filter((n) => Number.isFinite(n) && n > apiCallsCompleted)
177
+ .map((n) => n - apiCallsCompleted)
178
+ .sort((a, b) => a - b);
179
+ if (survivors.length > 0) {
180
+ empiricalResidualRequests = survivors[Math.floor((survivors.length - 1) / 2)];
181
+ priorBucket = `local_survivors_${survivors.length}`;
182
+ } else {
183
+ const sorted = hist
184
+ .map((n) => Number(n))
185
+ .filter((n) => Number.isFinite(n) && n > 0)
186
+ .sort((a, b) => a - b);
187
+ empiricalResidualRequests = sorted.length > 0
188
+ ? Math.max(1, sorted[Math.floor((sorted.length - 1) * 0.25)])
189
+ : 10;
190
+ priorBucket = 'local_p25_fallback';
191
+ }
192
+ } else {
193
+ const bucket = EMPIRICAL_SESSION_API_CALL_PRIOR.survivalBuckets.find(
194
+ (b) => apiCallsCompleted <= b.maxTurn
195
+ );
196
+ empiricalResidualRequests = bucket ? bucket.remainingMedian : 34;
197
+ priorBucket = bucket ? bucket.label : '25+_requests';
198
+ }
199
+
200
+ const baselinePrefix =
201
+ Number(context.initialPrefixTokens) > 0
202
+ ? Number(context.initialPrefixTokens)
203
+ : turnsCompleted === 0 && cachedTokens > 0
204
+ ? cachedTokens
205
+ : DEFAULT_FALLBACK_INITIAL_PREFIX_TOKENS;
206
+ const explicitGrowthPerTurn = Number(context.contextGrowthPerTurn);
207
+ const observedGrowthPerRequest =
208
+ Number.isFinite(explicitGrowthPerTurn) && explicitGrowthPerTurn > 0 && requestsPerTurn > 0
209
+ ? explicitGrowthPerTurn / requestsPerTurn
210
+ : apiCallsCompleted > 0 && cachedTokens > baselinePrefix
211
+ ? (cachedTokens - baselinePrefix) / apiCallsCompleted
212
+ : 600;
213
+ const avgDeltaTokensPerCall = Math.min(12_000, Math.max(300, observedGrowthPerRequest));
214
+ const callsUntilCompact =
215
+ cachedTokens >= autoCompactLimitTokens
216
+ ? 1
217
+ : Math.max(1, Math.floor((autoCompactLimitTokens - cachedTokens) / avgDeltaTokensPerCall));
218
+
219
+ const expectedRemainingRequests = Math.min(empiricalResidualRequests, callsUntilCompact);
220
+ const expectedRemainingTurns = Number(
221
+ (expectedRemainingRequests / requestsPerTurn).toFixed(2)
222
+ );
223
+ // Prior residual requests are counted before the switch turn executes; 1 turn is consumed by the switch itself.
224
+ const postSwitchRemainingTurns = Number(Math.max(0, expectedRemainingTurns - 1).toFixed(2));
225
+
226
+ return {
227
+ expectedRemainingTurns,
228
+ postSwitchRemainingTurns,
229
+ expectedRemainingRequests,
230
+ empiricalResidual: expectedRemainingRequests,
231
+ empiricalResidualRequests,
232
+ callsUntilCompact,
233
+ requestsPerTurn,
234
+ requestsPerTurnSource: rptInfo.source,
235
+ horizonUnit: 'turns',
236
+ priorNativeUnit: EMPIRICAL_SESSION_API_CALL_PRIOR.unit,
237
+ priorBucket,
238
+ isPlaceholderPrior,
239
+ priorProvenance,
240
+ initialPrefixTokensUsed: baselinePrefix,
241
+ contextCeilingUsed: contextCeiling,
242
+ autoCompactLimitTokensUsed: autoCompactLimitTokens,
243
+ source
244
+ };
245
+ }
246
+
18
247
  export const FLIGHT_MODES = Object.freeze({
19
248
  OFF: 'OFF',
20
249
  SILENT: 'SILENT',
@@ -23,6 +252,7 @@ export const FLIGHT_MODES = Object.freeze({
23
252
  });
24
253
 
25
254
  export const DEFAULT_EXPECTED_OUTPUT_TOKENS = 1500;
255
+ export const DEFAULT_DET09_OUTPUT_DELTA_TOKENS = 800;
26
256
 
27
257
  const PREFIX_INSTRUCTION_FILE_REGEX =
28
258
  /(?:^|\/)(?:CLAUDE(?:\.local)?\.md|AGENTS\.md|\.mcp\.json)$|(?:^|\/)\.claude\/(?:CLAUDE\.md|rules\/.+\.md)$/i;
@@ -43,9 +273,10 @@ export const DEFAULT_ADVISORY_COOLDOWN_TURNS = 3;
43
273
 
44
274
  /**
45
275
  * Maps an active model to its natural one-tier downshift peer for cross-model break-even C* (`ISS-006`).
276
+ * Break-even thresholds are computed dynamically from `anthropicModelCatalog.json` rates at runtime.
46
277
  * - claude-fable-5-2 / claude-fable-5-1 -> claude-opus-5-5
47
- * - claude-opus-5-5 -> claude-sonnet-5-5 (C* = 6,522 at O = 1,500)
48
- * - claude-opus-4-6 / claude-opus-4-5 -> claude-sonnet-4-6 (C* = 4,615 at O = 1,500)
278
+ * - claude-opus-5-5 -> claude-sonnet-5-5
279
+ * - claude-opus-4-6 / claude-opus-4-5 -> claude-sonnet-4-6
49
280
  * - claude-sonnet-5-5 -> claude-haiku-5-5
50
281
  * - claude-sonnet-4-6 / claude-sonnet-4-5 -> claude-haiku-4-5
51
282
  * - claude-haiku-4-5 -> claude-haiku-5-5
@@ -56,17 +287,35 @@ export const DEFAULT_ADVISORY_COOLDOWN_TURNS = 3;
56
287
  export function resolveNaturalDownshiftPeer(modelId = 'claude-opus-5-5') {
57
288
  const norm = normalizeModelId(modelId);
58
289
  switch (norm) {
290
+ case 'claude-mythos-5-2':
291
+ case 'claude-mythos-5-1':
292
+ case 'claude-mythos-5':
59
293
  case 'claude-fable-5-2':
60
294
  case 'claude-fable-5-1':
295
+ case 'claude-fable-5':
61
296
  return 'claude-opus-5-5';
62
297
  case 'claude-opus-5-5':
63
298
  return 'claude-sonnet-5-5';
299
+ case 'claude-opus-5':
300
+ return 'claude-sonnet-5';
301
+ case 'claude-opus-4-8':
302
+ case 'claude-opus-4-7':
64
303
  case 'claude-opus-4-6':
304
+ case 'claude-opus-4-5':
305
+ case 'claude-opus-4-1':
306
+ case 'claude-opus-4-0':
65
307
  return 'claude-sonnet-4-6';
66
308
  case 'claude-sonnet-5-5':
309
+ case 'claude-sonnet-5':
67
310
  return 'claude-haiku-5-5';
68
311
  case 'claude-sonnet-4-6':
312
+ case 'claude-sonnet-4-5':
313
+ case 'claude-sonnet-4-0':
69
314
  return 'claude-haiku-4-5';
315
+ case 'claude-3-7-sonnet':
316
+ case 'claude-3-5-sonnet':
317
+ case 'claude-3-5-haiku':
318
+ return 'claude-3-5-haiku';
70
319
  case 'claude-haiku-4-5':
71
320
  case 'claude-haiku-5-5':
72
321
  return 'claude-haiku-5-5';
@@ -125,23 +374,83 @@ export function isSilentOrOffMode(mode = 'COACH') {
125
374
  * @param {object} [options={}]
126
375
  */
127
376
  export function computeBreakEvenCachedTokens(params = {}, options = {}) {
128
- const rawCurrentModel = params.currentModel || 'claude-opus-5-5';
129
- const rawTargetModel = params.targetModel || 'claude-sonnet-5-5';
130
- const currentModel = normalizeModelId(rawCurrentModel);
131
- const targetModel = normalizeModelId(rawTargetModel);
377
+ const rawCurrentModel = params.currentModel ?? 'claude-opus-5-5';
378
+ const rawTargetModel = params.targetModel ?? 'claude-sonnet-5-5';
132
379
  const expectedOutputTokens = Math.max(
133
380
  0,
134
381
  Number(params.expectedOutputTokens ?? DEFAULT_EXPECTED_OUTPUT_TOKENS)
135
382
  );
136
383
  const cachedTokens = Math.max(0, Number(params.cachedTokens ?? 0));
137
384
  const uncachedDeltaTokens = Math.max(0, Number(params.uncachedDeltaTokens ?? 0));
385
+ const uncachedWriteTokens = Math.max(0, Number(params.uncachedWriteTokens ?? 0));
386
+ const request1UncachedTokens = uncachedDeltaTokens + uncachedWriteTokens;
138
387
  const cacheWarm = params.cacheWarm !== undefined ? Boolean(params.cacheWarm) : cachedTokens > 0;
139
388
  const ttlTier = params.cacheTtlTier === '1h' ? '1h' : '5m';
140
389
 
141
390
  const totalPromptTokens = Math.max(
142
- cachedTokens + uncachedDeltaTokens,
391
+ cachedTokens + request1UncachedTokens,
143
392
  computeTotalPromptTokens(params)
144
393
  );
394
+
395
+ const currentKnown =
396
+ params.currentModel !== undefined ? isKnownCatalogModel(rawCurrentModel, options) : true;
397
+ const targetKnown =
398
+ params.targetModel !== undefined ? isKnownCatalogModel(rawTargetModel, options) : true;
399
+
400
+ if (!currentKnown || !targetKnown) {
401
+ const unknownModelIds = [];
402
+ if (!currentKnown) unknownModelIds.push(String(rawCurrentModel));
403
+ if (!targetKnown && String(rawTargetModel) !== String(rawCurrentModel)) {
404
+ unknownModelIds.push(String(rawTargetModel));
405
+ }
406
+ const rawRemaining = params.expectedRemainingTurns ?? options.expectedRemainingTurns;
407
+ const hasExplicitRemaining =
408
+ rawRemaining !== undefined &&
409
+ rawRemaining !== null &&
410
+ Number.isFinite(Number(rawRemaining));
411
+ const useEmpirical = Boolean(
412
+ params.useEmpiricalHorizonPrior ?? options.useEmpiricalHorizonPrior
413
+ );
414
+ return {
415
+ unknownModel: true,
416
+ unknownModelIds,
417
+ currentModel: String(rawCurrentModel || ''),
418
+ targetModel: String(rawTargetModel || ''),
419
+ expectedOutputTokens,
420
+ cachedTokens,
421
+ uncachedDeltaTokens,
422
+ uncachedWriteTokens,
423
+ totalPromptTokens,
424
+ cacheWarm,
425
+ cacheTtlTier: ttlTier,
426
+ writeMultiplierLabel: ttlTier === '1h' ? '2.0x' : '1.25x',
427
+ isCapabilityUpshift: false,
428
+ breakEvenTokens: null,
429
+ rates: null,
430
+ stayOnCurrentModelUSD: null,
431
+ switchToTargetModelUSD: null,
432
+ coldWritePenaltyUSD: null,
433
+ perTurnPostSwitchSavingUSD: null,
434
+ averagePostSwitchSavingUSD: null,
435
+ paybackTurns: null,
436
+ paybackWarmRequests: null,
437
+ switchTurnWarmReads: 0,
438
+ totalWarmReadsToPayback: null,
439
+ asymptoticWarmRequestRatio: null,
440
+ contextGrowthPerTurn: Math.max(0, Number(params.contextGrowthPerTurn ?? 0)),
441
+ expectedRemainingTurns: hasExplicitRemaining ? Math.max(0, Number(rawRemaining)) : null,
442
+ postSwitchRemainingTurns: hasExplicitRemaining ? Math.max(0, Number(rawRemaining)) : null,
443
+ horizonMaxCachedTokens: null,
444
+ horizonNetSavingsUSD: null,
445
+ horizonPriorSource: null,
446
+ ruleVersion: hasExplicitRemaining || useEmpirical ? 'rule_v2' : 'rule_v1',
447
+ shouldHold: false,
448
+ shouldHoldModel: false
449
+ };
450
+ }
451
+
452
+ const currentModel = normalizeModelId(rawCurrentModel);
453
+ const targetModel = normalizeModelId(rawTargetModel);
145
454
  const currRates = resolveEffectiveRates(rawCurrentModel, totalPromptTokens, options);
146
455
  const targetRates = resolveEffectiveRates(rawTargetModel, totalPromptTokens, options);
147
456
 
@@ -153,13 +462,77 @@ export function computeBreakEvenCachedTokens(params = {}, options = {}) {
153
462
 
154
463
  const isCapabilityUpshift = pOutCurr <= pOutTarget;
155
464
 
465
+ // Resolve requests/turn and post-switch turn horizon BEFORE cost math so multi-request turns scale read savings cleanly.
466
+ const observedContextCeilingRaw = Number(
467
+ params.contextCeiling ?? params.contextWindowSize ?? options.contextCeiling
468
+ );
469
+ const resolvedContextCeiling =
470
+ Number.isFinite(observedContextCeilingRaw) && observedContextCeilingRaw >= 10_000
471
+ ? Math.round(observedContextCeilingRaw)
472
+ : currRates.contextCeiling;
473
+ const rptInfo = resolveRequestsPerTurn(params, options);
474
+
475
+ const rawRemainingTurns = params.expectedRemainingTurns ?? options.expectedRemainingTurns;
476
+ const hasExplicitRemaining =
477
+ rawRemainingTurns !== undefined &&
478
+ rawRemainingTurns !== null &&
479
+ Number.isFinite(Number(rawRemainingTurns));
480
+ const useEmpiricalHorizonPrior = Boolean(
481
+ params.useEmpiricalHorizonPrior ?? options.useEmpiricalHorizonPrior
482
+ );
483
+ let expectedRemainingTurns = null;
484
+ let postSwitchRemainingTurns = null;
485
+ let expectedRemainingRequests = null;
486
+ let horizonPriorSource = null;
487
+ let priorBucket = null;
488
+ let priorNativeUnit = null;
489
+ let requestsPerTurnUsed = rptInfo.requestsPerTurn;
490
+ let isPlaceholderPrior = false;
491
+ let priorProvenance = null;
492
+ let initialPrefixTokensUsed =
493
+ Number(params.initialPrefixTokens) > 0 ? Number(params.initialPrefixTokens) : null;
494
+ if (hasExplicitRemaining) {
495
+ expectedRemainingTurns = Math.max(0, Number(rawRemainingTurns));
496
+ const explicitIncludesSwitchTurn = Boolean(params.horizonIncludesSwitchTurn);
497
+ postSwitchRemainingTurns = explicitIncludesSwitchTurn
498
+ ? Number(Math.max(0, expectedRemainingTurns - 1).toFixed(2))
499
+ : expectedRemainingTurns;
500
+ horizonPriorSource = 'explicit';
501
+ priorBucket = 'explicit_turns';
502
+ priorNativeUnit = 'turns';
503
+ } else if (useEmpiricalHorizonPrior) {
504
+ const prior = estimateEmpiricalRemainingTurns(
505
+ {
506
+ turnsCompleted: params.turnsCompleted ?? params.currentTurn ?? 0,
507
+ apiCallsCompleted: params.apiCallsCompleted,
508
+ requestsPerTurn: params.requestsPerTurn,
509
+ contextGrowthPerTurn: params.contextGrowthPerTurn,
510
+ cachedTokens,
511
+ contextCeiling: resolvedContextCeiling,
512
+ autoCompactLimitTokens: params.autoCompactLimitTokens,
513
+ initialPrefixTokens: params.initialPrefixTokens
514
+ },
515
+ options
516
+ );
517
+ expectedRemainingTurns = prior.expectedRemainingTurns;
518
+ postSwitchRemainingTurns = prior.postSwitchRemainingTurns;
519
+ expectedRemainingRequests = prior.expectedRemainingRequests;
520
+ horizonPriorSource = prior.source;
521
+ priorBucket = prior.priorBucket;
522
+ priorNativeUnit = prior.priorNativeUnit;
523
+ requestsPerTurnUsed = prior.requestsPerTurn;
524
+ isPlaceholderPrior = prior.isPlaceholderPrior;
525
+ priorProvenance = prior.priorProvenance;
526
+ initialPrefixTokensUsed = prior.initialPrefixTokensUsed;
527
+ }
528
+
156
529
  let breakEvenTokens = 0;
157
530
  if (currentModel === targetModel || isCapabilityUpshift) {
158
531
  breakEvenTokens = 0;
159
532
  } else {
160
533
  const numeratorUSD =
161
534
  (expectedOutputTokens / 1_000_000) * (pOutCurr - pOutTarget) +
162
- (uncachedDeltaTokens / 1_000_000) * (pWriteCurr - pWriteTarget);
535
+ (request1UncachedTokens / 1_000_000) * (pWriteCurr - pWriteTarget);
163
536
  const denominator = pWriteTarget - pReadCurr;
164
537
  if (numeratorUSD <= 0) {
165
538
  breakEvenTokens = 0;
@@ -170,18 +543,25 @@ export function computeBreakEvenCachedTokens(params = {}, options = {}) {
170
543
  }
171
544
  }
172
545
 
173
- // Exact USD turn cost if staying on currentModel vs switching to targetModel
546
+ // Exact USD switch-turn cost: request 1 pays cache write on cold target (and uncachedWriteTokens even on stay); requests 2..R read at warm rate.
547
+ const effectiveRpt = currentModel === targetModel ? 1 : Math.max(1, requestsPerTurnUsed);
548
+ const extraWarmReadsOnSwitchTurn = Math.max(0, effectiveRpt - 1);
549
+ const combinedReq1Tokens = cachedTokens + request1UncachedTokens;
174
550
  const stayPrefixCostUSD = cacheWarm
175
- ? (cachedTokens / 1_000_000) * pReadCurr + (uncachedDeltaTokens / 1_000_000) * pWriteCurr
176
- : ((cachedTokens + uncachedDeltaTokens) / 1_000_000) * pWriteCurr;
551
+ ? (cachedTokens / 1_000_000) * pReadCurr +
552
+ (request1UncachedTokens / 1_000_000) * pWriteCurr +
553
+ extraWarmReadsOnSwitchTurn * (combinedReq1Tokens / 1_000_000) * pReadCurr
554
+ : (combinedReq1Tokens / 1_000_000) * pWriteCurr +
555
+ extraWarmReadsOnSwitchTurn * (combinedReq1Tokens / 1_000_000) * pReadCurr;
177
556
  const stayOutputCostUSD = (expectedOutputTokens / 1_000_000) * pOutCurr;
178
557
  const stayOnCurrentModelUSD = stayPrefixCostUSD + stayOutputCostUSD;
179
558
 
180
- // Switching to a different model invalidates the isolated per-model cache, forcing a full cold write
559
+ // Switching to a different model invalidates the isolated per-model cache on Request 1, forcing a cold write
181
560
  const switchPrefixCostUSD =
182
561
  currentModel === targetModel && cacheWarm
183
562
  ? stayPrefixCostUSD
184
- : ((cachedTokens + uncachedDeltaTokens) / 1_000_000) * pWriteTarget;
563
+ : (combinedReq1Tokens / 1_000_000) * pWriteTarget +
564
+ extraWarmReadsOnSwitchTurn * (combinedReq1Tokens / 1_000_000) * targetRates.readPer1M;
185
565
  const switchOutputCostUSD = (expectedOutputTokens / 1_000_000) * pOutTarget;
186
566
  const switchToTargetModelUSD = switchPrefixCostUSD + switchOutputCostUSD;
187
567
 
@@ -189,8 +569,126 @@ export function computeBreakEvenCachedTokens(params = {}, options = {}) {
189
569
  (switchToTargetModelUSD - stayOnCurrentModelUSD).toFixed(6)
190
570
  );
191
571
 
192
- // Never hold/deny on capability upshifts (pOutCurr <= pOutTarget) or when coldWritePenaltyUSD <= 0 (`ISS-006`)
193
- const shouldHoldModel = Boolean(
572
+ // Horizon-aware payback (`C1e` / `rule_v2`, opt-in via `expectedRemainingTurns` or `useEmpiricalHorizonPrior`):
573
+ // perTurnPostSwitchSavingUSD = R * ((C + cw_1)/1M) * (P_read,curr - P_read,target)
574
+ // + (Delta_post/1M) * (P_write,curr - P_write,target)
575
+ // + (O/1M) * (P_out,curr - P_out,target)
576
+ // paybackTurns = coldWritePenaltyUSD / perTurnPostSwitchSavingUSD
577
+ // When `expectedRemainingTurns` is unset (`undefined`/`null`), `shouldHoldModel` preserves `rule_v1`.
578
+ const postSwitchDeltaTokens = Math.max(
579
+ 0,
580
+ Number(params.postSwitchDeltaTokens ?? uncachedDeltaTokens)
581
+ );
582
+ const contextGrowthPerTurn = Math.max(0, Number(params.contextGrowthPerTurn ?? 0));
583
+ const effectivePostSwitchDeltaTokens =
584
+ contextGrowthPerTurn > 0 && params.postSwitchDeltaTokens === undefined
585
+ ? contextGrowthPerTurn
586
+ : postSwitchDeltaTokens;
587
+
588
+ const rawPerTurnPostSwitchSavingUSD =
589
+ currentModel === targetModel || isCapabilityUpshift
590
+ ? 0
591
+ : effectiveRpt *
592
+ (combinedReq1Tokens / 1_000_000) *
593
+ (pReadCurr - targetRates.readPer1M) +
594
+ (effectivePostSwitchDeltaTokens / 1_000_000) * (pWriteCurr - pWriteTarget) +
595
+ (expectedOutputTokens / 1_000_000) * (pOutCurr - pOutTarget);
596
+ const perTurnPostSwitchSavingUSD = Number(
597
+ Math.max(0, rawPerTurnPostSwitchSavingUSD).toFixed(6)
598
+ );
599
+
600
+ const growthCoeffA =
601
+ currentModel === targetModel || isCapabilityUpshift || contextGrowthPerTurn <= 0
602
+ ? 0
603
+ : 0.5 *
604
+ effectiveRpt *
605
+ (contextGrowthPerTurn / 1_000_000) *
606
+ (pReadCurr - targetRates.readPer1M);
607
+
608
+ const hasHorizonTurns = postSwitchRemainingTurns !== null;
609
+ const averagePostSwitchSavingUSD =
610
+ hasHorizonTurns && postSwitchRemainingTurns > 1 && growthCoeffA !== 0
611
+ ? Number(
612
+ Math.max(
613
+ 0,
614
+ rawPerTurnPostSwitchSavingUSD + (postSwitchRemainingTurns - 1) * growthCoeffA
615
+ ).toFixed(6)
616
+ )
617
+ : perTurnPostSwitchSavingUSD;
618
+
619
+ let paybackTurns;
620
+ if (coldWritePenaltyUSD <= 0) {
621
+ paybackTurns = 0;
622
+ } else if (growthCoeffA > 0) {
623
+ const s0 = Math.max(0, rawPerTurnPostSwitchSavingUSD);
624
+ const bCoeff = s0 - growthCoeffA;
625
+ const disc = bCoeff * bCoeff + 4 * growthCoeffA * coldWritePenaltyUSD;
626
+ paybackTurns =
627
+ disc >= 0
628
+ ? Number(((-bCoeff + Math.sqrt(disc)) / (2 * growthCoeffA)).toFixed(4))
629
+ : Infinity;
630
+ } else {
631
+ paybackTurns =
632
+ perTurnPostSwitchSavingUSD > 0
633
+ ? Number((coldWritePenaltyUSD / perTurnPostSwitchSavingUSD).toFixed(4))
634
+ : Infinity;
635
+ }
636
+
637
+ const paybackWarmRequests =
638
+ coldWritePenaltyUSD <= 0
639
+ ? 0
640
+ : Number.isFinite(paybackTurns)
641
+ ? Number((paybackTurns * effectiveRpt).toFixed(2))
642
+ : Infinity;
643
+ const switchTurnWarmReads = extraWarmReadsOnSwitchTurn;
644
+ const totalWarmReadsToPayback =
645
+ coldWritePenaltyUSD <= 0
646
+ ? 0
647
+ : Number.isFinite(paybackWarmRequests)
648
+ ? Number((switchTurnWarmReads + paybackWarmRequests).toFixed(2))
649
+ : Infinity;
650
+ const warmReadSpread = pReadCurr - targetRates.readPer1M;
651
+ const asymptoticWarmRequestRatio =
652
+ currentModel === targetModel || isCapabilityUpshift || warmReadSpread <= 0
653
+ ? null
654
+ : Number(((pWriteTarget - pReadCurr) / warmReadSpread).toFixed(2));
655
+
656
+ // Exact horizon-aware break-even context C_max for post-switch turns H_post and requests/turn R:
657
+ // C_max = (O * (P_out,A - P_out,B) * (H_post + 1)) / ((P_write,B - P_read,A) - ((H_post + 1) * R - 1) * (P_read,A - P_read,B))
658
+ let horizonMaxCachedTokens = null;
659
+ if (hasHorizonTurns) {
660
+ if (currentModel === targetModel || isCapabilityUpshift) {
661
+ horizonMaxCachedTokens = 0;
662
+ } else {
663
+ const warmReadDiffPer1M = pReadCurr - targetRates.readPer1M;
664
+ const postSwitchWarmReadsTotal = (postSwitchRemainingTurns + 1) * effectiveRpt - 1;
665
+ const cMaxDen = (pWriteTarget - pReadCurr) - postSwitchWarmReadsTotal * warmReadDiffPer1M;
666
+ const cMaxNumUSD =
667
+ (expectedOutputTokens / 1_000_000) *
668
+ (pOutCurr - pOutTarget) *
669
+ (postSwitchRemainingTurns + 1);
670
+ if (cMaxDen <= 0) {
671
+ horizonMaxCachedTokens = Infinity;
672
+ } else if (cMaxNumUSD <= 0) {
673
+ horizonMaxCachedTokens = 0;
674
+ } else {
675
+ horizonMaxCachedTokens = Math.round((cMaxNumUSD * 1_000_000) / cMaxDen);
676
+ }
677
+ }
678
+ }
679
+
680
+ const horizonNetSavingsUSD = hasHorizonTurns
681
+ ? Number(
682
+ (
683
+ postSwitchRemainingTurns *
684
+ (Math.max(0, rawPerTurnPostSwitchSavingUSD) +
685
+ (postSwitchRemainingTurns > 1 ? (postSwitchRemainingTurns - 1) * growthCoeffA : 0)) -
686
+ coldWritePenaltyUSD
687
+ ).toFixed(6)
688
+ )
689
+ : null;
690
+
691
+ const singleTurnShouldHold = Boolean(
194
692
  currentModel !== targetModel &&
195
693
  !isCapabilityUpshift &&
196
694
  cacheWarm &&
@@ -198,28 +696,64 @@ export function computeBreakEvenCachedTokens(params = {}, options = {}) {
198
696
  cachedTokens > breakEvenTokens
199
697
  );
200
698
 
699
+ // Never hold/deny on capability upshifts, coldWritePenaltyUSD <= 0, or unbounded horizon limit C_max = Infinity
700
+ const shouldHoldModel = hasHorizonTurns
701
+ ? Boolean(
702
+ singleTurnShouldHold &&
703
+ horizonMaxCachedTokens !== Infinity &&
704
+ postSwitchRemainingTurns < paybackTurns
705
+ )
706
+ : singleTurnShouldHold;
707
+
201
708
  return {
709
+ unknownModel: false,
710
+ unknownModelIds: [],
202
711
  currentModel,
203
712
  targetModel,
204
713
  expectedOutputTokens,
205
714
  cachedTokens,
206
715
  uncachedDeltaTokens,
716
+ uncachedWriteTokens,
207
717
  totalPromptTokens,
208
718
  cacheWarm,
209
719
  cacheTtlTier: ttlTier,
210
720
  writeMultiplierLabel: ttlTier === '1h' ? '2.0x' : '1.25x',
211
721
  isCapabilityUpshift,
212
722
  breakEvenTokens,
723
+ horizonMaxCachedTokens,
213
724
  rates: {
214
725
  currentOutputPer1M: pOutCurr,
215
726
  targetOutputPer1M: pOutTarget,
216
727
  currentReadPer1M: pReadCurr,
728
+ targetReadPer1M: targetRates.readPer1M,
217
729
  currentWritePer1M: pWriteCurr,
218
730
  targetWritePer1M: pWriteTarget
219
731
  },
220
732
  stayOnCurrentModelUSD: Number(stayOnCurrentModelUSD.toFixed(6)),
221
733
  switchToTargetModelUSD: Number(switchToTargetModelUSD.toFixed(6)),
222
734
  coldWritePenaltyUSD,
735
+ perTurnPostSwitchSavingUSD,
736
+ averagePostSwitchSavingUSD,
737
+ paybackTurns,
738
+ paybackWarmRequests,
739
+ switchTurnWarmReads,
740
+ totalWarmReadsToPayback,
741
+ asymptoticWarmRequestRatio,
742
+ contextGrowthPerTurn,
743
+ expectedRemainingTurns,
744
+ postSwitchRemainingTurns,
745
+ expectedRemainingRequests,
746
+ horizonUnit: 'turns',
747
+ priorNativeUnit,
748
+ priorBucket,
749
+ requestsPerTurn: requestsPerTurnUsed,
750
+ isPlaceholderPrior,
751
+ priorProvenance,
752
+ contextCeilingUsed: resolvedContextCeiling,
753
+ initialPrefixTokensUsed,
754
+ horizonNetSavingsUSD,
755
+ horizonPriorSource,
756
+ ruleVersion: hasHorizonTurns ? 'rule_v2' : 'rule_v1',
223
757
  shouldHold: shouldHoldModel,
224
758
  shouldHoldModel
225
759
  };
@@ -504,7 +1038,44 @@ export class CacheGravityRouter {
504
1038
  };
505
1039
  }
506
1040
 
507
- if (breakEven.shouldHoldModel) {
1041
+ if (breakEven.unknownModel) {
1042
+ const unknownList = breakEven.unknownModelIds.join(', ');
1043
+ const warning = `[Highbeam DET-08 Advisory] Prices are unknown for ${unknownList}; passing model switch through without price-based hold.`;
1044
+ return {
1045
+ detectorId: 'DET-08',
1046
+ mode: this.mode,
1047
+ decision: 'allow',
1048
+ blocked: false,
1049
+ advisory: true,
1050
+ unknownModel: true,
1051
+ warning,
1052
+ hysteresisLocked: false,
1053
+ breakEven,
1054
+ recommendedModel: breakEven.targetModel,
1055
+ subagentDelegation: null,
1056
+ reason: warning
1057
+ };
1058
+ }
1059
+
1060
+ const rawMinPenalty =
1061
+ request.minSwitchPenaltyUSD ?? this.options.minSwitchPenaltyUSD;
1062
+ const minSwitchPenaltyUSD =
1063
+ rawMinPenalty !== undefined && rawMinPenalty !== null && Number.isFinite(Number(rawMinPenalty))
1064
+ ? Math.max(0, Number(rawMinPenalty))
1065
+ : 0.02;
1066
+ const rawNotablePenalty =
1067
+ request.notableAllowPenaltyUSD ?? this.options.notableAllowPenaltyUSD;
1068
+ const notableAllowPenaltyUSD =
1069
+ rawNotablePenalty !== undefined &&
1070
+ rawNotablePenalty !== null &&
1071
+ Number.isFinite(Number(rawNotablePenalty))
1072
+ ? Math.max(0, Number(rawNotablePenalty))
1073
+ : minSwitchPenaltyUSD;
1074
+ const belowMinSwitchPenaltyUSD = Boolean(
1075
+ breakEven.shouldHoldModel && breakEven.coldWritePenaltyUSD < minSwitchPenaltyUSD
1076
+ );
1077
+
1078
+ if (breakEven.shouldHoldModel && !belowMinSwitchPenaltyUSD) {
508
1079
  // Unconditional prefix-loss protection: exempt from 3-turn advisory cooldown
509
1080
  const writeMultLabel = breakEven.cacheTtlTier === '1h' ? '2.0x' : '1.25x';
510
1081
  const subagentDelegation = {
@@ -516,12 +1087,26 @@ export class CacheGravityRouter {
516
1087
  reason: `Delegate routine file search/exploration to an isolated Explore/Task subagent on claude-haiku-5-5 (<2k context) while keeping main-thread ${breakEven.currentModel} cache warm.`
517
1088
  };
518
1089
 
1090
+ const paybackDetail =
1091
+ Number.isFinite(breakEven.paybackWarmRequests) && breakEven.paybackWarmRequests > 0
1092
+ ? `; payback ~${breakEven.paybackWarmRequests.toFixed(1)} post-switch warm requests (~${breakEven.paybackTurns.toFixed(1)} turns) at +$${breakEven.perTurnPostSwitchSavingUSD.toFixed(4)}/turn post-switch saving`
1093
+ : '';
1094
+ const horizonDetail =
1095
+ breakEven.postSwitchRemainingTurns !== null
1096
+ ? `; estimated post-switch horizon ~${breakEven.postSwitchRemainingTurns} turns`
1097
+ : '';
1098
+ const thresholdClause =
1099
+ breakEven.postSwitchRemainingTurns !== null &&
1100
+ Number.isFinite(breakEven.horizonMaxCachedTokens)
1101
+ ? `exceeds horizon break-even C_max = ${breakEven.horizonMaxCachedTokens.toLocaleString()} tokens and `
1102
+ : '';
519
1103
  const reasonText =
520
1104
  `[DET-08 Warm KV-Cache Hold] Switching from ${breakEven.currentModel} to ${breakEven.targetModel} ` +
521
- `with ${breakEven.cachedTokens.toLocaleString()} warm cached tokens exceeds break-even ` +
522
- `C* = ${breakEven.breakEvenTokens.toLocaleString()} tokens and incurs a ` +
523
- `+$${breakEven.coldWritePenaltyUSD.toFixed(4)} cold ${writeMultLabel} prefix rewrite penalty. ` +
524
- `Keep main thread on ${breakEven.currentModel} or spawn an Explore subagent on claude-haiku-5-5.`;
1105
+ `with ${breakEven.cachedTokens.toLocaleString()} warm cached tokens ${thresholdClause}incurs a ` +
1106
+ `+$${breakEven.coldWritePenaltyUSD.toFixed(4)} cold ${writeMultLabel} prefix rewrite penalty` +
1107
+ `${paybackDetail}${horizonDetail}. ` +
1108
+ `Keep main thread on ${breakEven.currentModel} or confirm if this session will run past payback ` +
1109
+ `(in headless -p/SDK, override via "DET-08": "warn" in .attention-horizon/config.json or pass expectedRemainingTurns).`;
525
1110
 
526
1111
  // In COACH mode (default), remain 100% advisory and non-blocking unless strictBlock is explicitly set
527
1112
  if (this.mode === FLIGHT_MODES.COACH && !request.strictBlock && !this.options.strictBlock) {
@@ -531,6 +1116,10 @@ export class CacheGravityRouter {
531
1116
  decision: 'allow',
532
1117
  blocked: false,
533
1118
  advisory: true,
1119
+ belowMinSwitchPenaltyUSD: false,
1120
+ minSwitchPenaltyUSD,
1121
+ notableAllowPenaltyUSD,
1122
+ notableAllowNote: null,
534
1123
  hysteresisLocked: false,
535
1124
  breakEven,
536
1125
  recommendedModel: breakEven.currentModel,
@@ -549,6 +1138,10 @@ export class CacheGravityRouter {
549
1138
  decision: autoDecision,
550
1139
  blocked: true,
551
1140
  advisory: false,
1141
+ belowMinSwitchPenaltyUSD: false,
1142
+ minSwitchPenaltyUSD,
1143
+ notableAllowPenaltyUSD,
1144
+ notableAllowNote: null,
552
1145
  hysteresisLocked: false,
553
1146
  breakEven,
554
1147
  recommendedModel: breakEven.currentModel,
@@ -557,16 +1150,71 @@ export class CacheGravityRouter {
557
1150
  };
558
1151
  }
559
1152
 
560
- // Advisory evaluation when cache is cold, below C*, or a capability upshift
1153
+ // Advisory evaluation when cache is cold, below C*, suppressed below minSwitchPenaltyUSD, or capability upshift
561
1154
  const cooldownSuppressed = this.isCooldownActive(currentTurn, false);
562
1155
  if (!cooldownSuppressed && this.mode === FLIGHT_MODES.COACH) {
563
1156
  this.lastAdvisoryTurn = currentTurn;
564
1157
  }
565
1158
 
566
- const allowReason =
567
- breakEven.isCapabilityUpshift && breakEven.currentModel !== breakEven.targetModel
1159
+ const isNotablePenalty = Boolean(
1160
+ !belowMinSwitchPenaltyUSD &&
1161
+ breakEven.currentModel !== breakEven.targetModel &&
1162
+ !breakEven.isCapabilityUpshift &&
1163
+ breakEven.cacheWarm &&
1164
+ breakEven.coldWritePenaltyUSD > 0 &&
1165
+ breakEven.coldWritePenaltyUSD >= notableAllowPenaltyUSD
1166
+ );
1167
+
1168
+ const rawTurnsForDisplay =
1169
+ request.turnsCompleted ?? request.currentTurn ?? breakEven.turnsCompleted;
1170
+ const netDollarDisplaySuppressed = Boolean(
1171
+ request.suppressNetDollarDisplay ??
1172
+ (rawTurnsForDisplay !== undefined &&
1173
+ rawTurnsForDisplay !== null &&
1174
+ Number.isFinite(Number(rawTurnsForDisplay)) &&
1175
+ Number(rawTurnsForDisplay) < 5)
1176
+ );
1177
+
1178
+ let notableAllowNote = null;
1179
+ if (isNotablePenalty) {
1180
+ const paybackFragment =
1181
+ Number.isFinite(breakEven.paybackWarmRequests) && breakEven.paybackWarmRequests > 0
1182
+ ? `, pays back in ~${breakEven.paybackWarmRequests.toFixed(1)} post-switch warm requests (~${breakEven.paybackTurns.toFixed(1)} turns)`
1183
+ : '';
1184
+ const cMaxFragment =
1185
+ breakEven.postSwitchRemainingTurns !== null && breakEven.horizonMaxCachedTokens !== null
1186
+ ? breakEven.horizonMaxCachedTokens === Infinity
1187
+ ? '; horizon limit C_max = unbounded'
1188
+ : `; horizon limit C_max = ${breakEven.horizonMaxCachedTokens.toLocaleString()} tokens`
1189
+ : '';
1190
+ const horizonFragment =
1191
+ breakEven.postSwitchRemainingTurns !== null && Number.isFinite(breakEven.horizonNetSavingsUSD)
1192
+ ? netDollarDisplaySuppressed
1193
+ ? ` (post-switch horizon ~${breakEven.postSwitchRemainingTurns} turns, <5 observed turns: net USD omitted${cMaxFragment})`
1194
+ : ` (post-switch horizon ~${breakEven.postSwitchRemainingTurns} turns, net ${breakEven.horizonNetSavingsUSD >= 0 ? '+$' : '-$'}${Math.abs(breakEven.horizonNetSavingsUSD).toFixed(4)}${cMaxFragment})`
1195
+ : '';
1196
+ const displayedPerTurnSaving =
1197
+ breakEven.contextGrowthPerTurn > 0 &&
1198
+ breakEven.postSwitchRemainingTurns !== null &&
1199
+ breakEven.postSwitchRemainingTurns > 1
1200
+ ? breakEven.averagePostSwitchSavingUSD
1201
+ : breakEven.perTurnPostSwitchSavingUSD;
1202
+ notableAllowNote =
1203
+ `[Highbeam] Allowing ${breakEven.currentModel} -> ${breakEven.targetModel}: ` +
1204
+ `+$${breakEven.coldWritePenaltyUSD.toFixed(4)} cold ${breakEven.writeMultiplierLabel} cache rewrite penalty, ` +
1205
+ `saves ~$${displayedPerTurnSaving.toFixed(4)}/turn${paybackFragment}${horizonFragment}.`;
1206
+ }
1207
+
1208
+ const allowReason = belowMinSwitchPenaltyUSD
1209
+ ? `Model switch to ${breakEven.targetModel} permitted silently (cold write penalty +$${breakEven.coldWritePenaltyUSD.toFixed(4)} < minSwitchPenaltyUSD $${minSwitchPenaltyUSD.toFixed(4)}).`
1210
+ : breakEven.isCapabilityUpshift && breakEven.currentModel !== breakEven.targetModel
568
1211
  ? `Capability upshift from ${breakEven.currentModel} to ${breakEven.targetModel} permitted without warm-cache hold.`
569
- : `Model switch to ${breakEven.targetModel} is within break-even threshold (cached ${breakEven.cachedTokens.toLocaleString()} <= C* ${breakEven.breakEvenTokens.toLocaleString()}).`;
1212
+ : breakEven.postSwitchRemainingTurns !== null &&
1213
+ (breakEven.horizonMaxCachedTokens === Infinity ||
1214
+ (breakEven.cachedTokens > breakEven.breakEvenTokens &&
1215
+ breakEven.postSwitchRemainingTurns >= breakEven.paybackTurns))
1216
+ ? `Model switch to ${breakEven.targetModel} permitted under horizon payback (${breakEven.postSwitchRemainingTurns} post-switch turns >= ~${breakEven.paybackWarmRequests} warm requests (~${breakEven.paybackTurns} turns); horizon limit ${breakEven.horizonMaxCachedTokens === Infinity ? 'C_max = unbounded' : `C_max = ${breakEven.horizonMaxCachedTokens.toLocaleString()} tokens`}${netDollarDisplaySuppressed ? '' : `; projected net saving ${breakEven.horizonNetSavingsUSD >= 0 ? '+$' : '-$'}${Math.abs(breakEven.horizonNetSavingsUSD).toFixed(4)}`}).`
1217
+ : `Model switch to ${breakEven.targetModel} immediate switch-turn output credit offsets cold rewrite (cached ${breakEven.cachedTokens.toLocaleString()} <= ${breakEven.breakEvenTokens.toLocaleString()} tokens).`;
570
1218
 
571
1219
  return {
572
1220
  detectorId: 'DET-08',
@@ -574,6 +1222,11 @@ export class CacheGravityRouter {
574
1222
  decision: 'allow',
575
1223
  blocked: false,
576
1224
  advisory: false,
1225
+ belowMinSwitchPenaltyUSD,
1226
+ minSwitchPenaltyUSD,
1227
+ notableAllowPenaltyUSD,
1228
+ notableAllowNote,
1229
+ netDollarDisplaySuppressed,
577
1230
  cooldownSuppressed,
578
1231
  hysteresisLocked: false,
579
1232
  breakEven,
@@ -585,8 +1238,9 @@ export class CacheGravityRouter {
585
1238
 
586
1239
  /**
587
1240
  * Evaluates a mid-session top-level `effort`, `thinking`, `system_prompt`, or `mcp_tools`
588
- * mutation (`DET-09`). When the cache is warm, queues the mutation in `PostCompactMutationQueue`
589
- * so it takes effect immediately after compaction without invalidating the warm cache prefix.
1241
+ * mutation (`DET-09`). Because Claude Code does not expose a native `/effort` pre-hook,
1242
+ * this acts as an advisory/post-hoc warning or host-mediated `PostCompactMutationQueue` entry
1243
+ * rather than an interactive `/effort` TUI blocker.
590
1244
  *
591
1245
  * @param {object} [mutationRequest={}]
592
1246
  * @param {'effort'|'thinking'|'speed'|'system_prompt'|'mcp_tools'} [mutationRequest.type='effort']
@@ -598,21 +1252,7 @@ export class CacheGravityRouter {
598
1252
  * @param {'5m'|'1h'} [mutationRequest.cacheTtlTier='5m']
599
1253
  */
600
1254
  interceptTopLevelMutation(mutationRequest = {}) {
601
- const rawModel = mutationRequest.currentModel || mutationRequest.modelId || 'claude-opus-5-5';
602
- const modelId = normalizeModelId(rawModel);
603
- const cachedTokens = Math.max(0, Number(mutationRequest.cachedTokens ?? 0));
604
- const hasTtlField =
605
- mutationRequest.ttlRemainingSeconds !== undefined &&
606
- mutationRequest.ttlRemainingSeconds !== null;
607
- const ttlRemainingSeconds = hasTtlField ? Number(mutationRequest.ttlRemainingSeconds) : null;
608
- const ttlExpired = hasTtlField && ttlRemainingSeconds <= 0;
609
-
610
- const cacheWarm = ttlExpired
611
- ? false
612
- : mutationRequest.cacheWarm !== undefined
613
- ? Boolean(mutationRequest.cacheWarm)
614
- : cachedTokens > 0;
615
-
1255
+ const explicitModel = mutationRequest.currentModel ?? mutationRequest.modelId;
616
1256
  const targetFilePath = String(
617
1257
  mutationRequest.filePath || mutationRequest.file_path || mutationRequest.path || ''
618
1258
  ).trim();
@@ -633,6 +1273,76 @@ export class CacheGravityRouter {
633
1273
  };
634
1274
  }
635
1275
 
1276
+ const mutationType =
1277
+ mutationRequest.type || (targetFilePath ? 'system_prompt' : 'effort');
1278
+
1279
+ if (explicitModel !== undefined && !isKnownCatalogModel(explicitModel, this.options)) {
1280
+ const effortCap = mutationType === 'effort'
1281
+ ? getEffortMutationCacheCapability(explicitModel, this.options)
1282
+ : null;
1283
+ if (isSilentOrOffMode(this.mode)) {
1284
+ return {
1285
+ detectorId: 'DET-09',
1286
+ triggered: false,
1287
+ queued: false,
1288
+ decision: 'allow',
1289
+ unknownModel: true,
1290
+ effortCacheCapability: effortCap,
1291
+ avoidedRewritePenaltyUSD: null,
1292
+ queueSize: this.mutationQueue.size(),
1293
+ reason: null
1294
+ };
1295
+ }
1296
+ const effortClause =
1297
+ mutationType === 'effort' ? ' (effort cache behavior unverified for this model)' : '';
1298
+ const warning = `[Highbeam DET-09 Advisory] Prices are unknown for ${String(explicitModel)}${effortClause}; passing mutation through without price-based hold.`;
1299
+ return {
1300
+ detectorId: 'DET-09',
1301
+ triggered: false,
1302
+ queued: false,
1303
+ decision: 'allow',
1304
+ advisory: true,
1305
+ unknownModel: true,
1306
+ effortCacheCapability: effortCap,
1307
+ warning,
1308
+ avoidedRewritePenaltyUSD: null,
1309
+ queueSize: this.mutationQueue.size(),
1310
+ reason: warning
1311
+ };
1312
+ }
1313
+
1314
+ const rawModel = explicitModel || 'claude-opus-5-5';
1315
+ const modelId = normalizeModelId(rawModel);
1316
+ const effortCap =
1317
+ mutationType === 'effort' ? getEffortMutationCacheCapability(modelId, this.options) : null;
1318
+
1319
+ if (effortCap && effortCap.invalidatesCache === 'no') {
1320
+ return {
1321
+ detectorId: 'DET-09',
1322
+ triggered: false,
1323
+ queued: false,
1324
+ decision: 'allow',
1325
+ advisory: false,
1326
+ effortCacheCapability: effortCap,
1327
+ avoidedRewritePenaltyUSD: 0,
1328
+ queueSize: this.mutationQueue.size(),
1329
+ reason: null
1330
+ };
1331
+ }
1332
+
1333
+ const cachedTokens = Math.max(0, Number(mutationRequest.cachedTokens ?? 0));
1334
+ const hasTtlField =
1335
+ mutationRequest.ttlRemainingSeconds !== undefined &&
1336
+ mutationRequest.ttlRemainingSeconds !== null;
1337
+ const ttlRemainingSeconds = hasTtlField ? Number(mutationRequest.ttlRemainingSeconds) : null;
1338
+ const ttlExpired = hasTtlField && ttlRemainingSeconds <= 0;
1339
+
1340
+ const cacheWarm = ttlExpired
1341
+ ? false
1342
+ : mutationRequest.cacheWarm !== undefined
1343
+ ? Boolean(mutationRequest.cacheWarm)
1344
+ : cachedTokens > 0;
1345
+
636
1346
  const ttlTier = mutationRequest.cacheTtlTier === '1h' ? '1h' : '5m';
637
1347
  const totalPromptTokens = Math.max(cachedTokens, computeTotalPromptTokens(mutationRequest));
638
1348
  const rates = resolveEffectiveRates(rawModel, totalPromptTokens, this.options);
@@ -644,6 +1354,7 @@ export class CacheGravityRouter {
644
1354
  triggered: false,
645
1355
  queued: false,
646
1356
  decision: 'allow',
1357
+ effortCacheCapability: effortCap,
647
1358
  avoidedRewritePenaltyUSD: 0,
648
1359
  queueSize: this.mutationQueue.size(),
649
1360
  reason: 'Cache is cold or router is OFF/SILENT; top-level mutation may apply immediately.'
@@ -654,8 +1365,43 @@ export class CacheGravityRouter {
654
1365
  ((cachedTokens / 1_000_000) * (writeRate - rates.readPer1M)).toFixed(6)
655
1366
  );
656
1367
 
657
- const mutationType =
658
- mutationRequest.type || (targetFilePath ? 'system_prompt' : 'effort');
1368
+ const enableDet09Threshold = Boolean(
1369
+ mutationRequest.enableDet09Threshold ?? this.options.enableDet09Threshold ?? false
1370
+ );
1371
+ const det09BreakEven = computeDet09BreakEvenTokens(
1372
+ {
1373
+ ...mutationRequest,
1374
+ currentModel: rawModel,
1375
+ cachedTokens,
1376
+ cacheTtlTier: ttlTier,
1377
+ totalPromptTokens
1378
+ },
1379
+ this.options
1380
+ );
1381
+
1382
+ if (enableDet09Threshold && cachedTokens <= det09BreakEven.breakEvenTokens) {
1383
+ return {
1384
+ detectorId: 'DET-09',
1385
+ triggered: false,
1386
+ queued: false,
1387
+ decision: 'allow',
1388
+ belowBreakEvenThreshold: true,
1389
+ effortCacheCapability: effortCap,
1390
+ breakEvenTokens: det09BreakEven.breakEvenTokens,
1391
+ avoidedRewritePenaltyUSD,
1392
+ queueSize: this.mutationQueue.size(),
1393
+ reason:
1394
+ `Top-level mutation within DET-09 break-even threshold ` +
1395
+ `(cached ${cachedTokens.toLocaleString()} <= C*_mut ${det09BreakEven.breakEvenTokens.toLocaleString()} tokens).`
1396
+ };
1397
+ }
1398
+
1399
+ const effortLabel =
1400
+ effortCap?.invalidatesCache === 'unknown'
1401
+ ? ' (unverified for this model)'
1402
+ : effortCap?.provenance
1403
+ ? ` (${effortCap.provenance})`
1404
+ : '';
659
1405
  const entry = this.mutationQueue.enqueue({
660
1406
  type: mutationType,
661
1407
  key: mutationRequest.key || targetFilePath || mutationType,
@@ -663,7 +1409,7 @@ export class CacheGravityRouter {
663
1409
  cachedTokens,
664
1410
  avoidedRewritePenaltyUSD,
665
1411
  reason:
666
- `[DET-09 Top-Level Mutation Deferred] Mutating top-level ${mutationType} ` +
1412
+ `[DET-09 Top-Level Mutation Deferred] Mutating top-level ${mutationType}${effortLabel} ` +
667
1413
  `while ${cachedTokens.toLocaleString()} tokens are warm on ${modelId} would invalidate the ` +
668
1414
  `Anthropic prompt cache prefix (+$${avoidedRewritePenaltyUSD.toFixed(4)} rewrite spike). ` +
669
1415
  `Queued in PostCompactMutationQueue to apply after next compaction.`
@@ -674,7 +1420,9 @@ export class CacheGravityRouter {
674
1420
  triggered: true,
675
1421
  queued: true,
676
1422
  decision: 'defer',
1423
+ effortCacheCapability: effortCap,
677
1424
  entry,
1425
+ breakEvenTokens: enableDet09Threshold ? det09BreakEven.breakEvenTokens : 0,
678
1426
  avoidedRewritePenaltyUSD,
679
1427
  queueSize: this.mutationQueue.size(),
680
1428
  reason: entry.reason
@@ -682,6 +1430,79 @@ export class CacheGravityRouter {
682
1430
  }
683
1431
  }
684
1432
 
1433
+ /**
1434
+ * Computes the `DET-09` warm-prefix mutation break-even threshold `C*_mut` (`C1d`):
1435
+ * C*_mut = (Delta_O * P_out) / (P_write - P_read)
1436
+ * Below `C*_mut`, the one-time cold prefix rewrite penalty `(C / 1M) * (P_write - P_read)`
1437
+ * is smaller than the per-turn output-equivalent cost of deferring the mutation.
1438
+ *
1439
+ * @param {object} [params={}]
1440
+ * @param {object} [options={}]
1441
+ */
1442
+ export function computeDet09BreakEvenTokens(params = {}, options = {}) {
1443
+ const explicitMin = params.det09MinCachedTokens ?? options.det09MinCachedTokens;
1444
+ const rawModel = params.currentModel || params.modelId || 'claude-opus-5-5';
1445
+ const ttlTier = params.cacheTtlTier === '1h' ? '1h' : '5m';
1446
+ const totalPromptTokens = Math.max(
1447
+ Number(params.cachedTokens ?? 0),
1448
+ computeTotalPromptTokens(params)
1449
+ );
1450
+ const rates = resolveEffectiveRates(rawModel, totalPromptTokens, options);
1451
+ if (rates.unknownModel) {
1452
+ return {
1453
+ unknownModel: true,
1454
+ breakEvenTokens: null,
1455
+ outputDeltaTokens: null,
1456
+ writeRatePer1M: null,
1457
+ readRatePer1M: null,
1458
+ outputRatePer1M: null
1459
+ };
1460
+ }
1461
+ const writeRate = ttlTier === '1h' ? rates.write1hPer1M : rates.write5mPer1M;
1462
+ const denominator = writeRate - rates.readPer1M;
1463
+
1464
+ if (explicitMin !== undefined && explicitMin !== null && Number.isFinite(Number(explicitMin))) {
1465
+ return {
1466
+ breakEvenTokens: Math.max(0, Math.round(Number(explicitMin))),
1467
+ outputDeltaTokens: null,
1468
+ writeRatePer1M: writeRate,
1469
+ readRatePer1M: rates.readPer1M,
1470
+ outputRatePer1M: rates.outputPer1M
1471
+ };
1472
+ }
1473
+
1474
+ const effortTable = BUILTIN_CATALOG.effortExpectedOutputTokens || {};
1475
+ const currEff = String(params.currentEffort || '').toLowerCase().trim();
1476
+ const nextEff = String(params.value || '').toLowerCase().trim();
1477
+ let outputDeltaTokens = Number(
1478
+ params.det09OutputDeltaTokens ?? options.det09OutputDeltaTokens ?? NaN
1479
+ );
1480
+ if (!Number.isFinite(outputDeltaTokens) || outputDeltaTokens < 0) {
1481
+ if (
1482
+ effortTable[currEff] !== undefined &&
1483
+ effortTable[nextEff] !== undefined &&
1484
+ effortTable[currEff] !== effortTable[nextEff]
1485
+ ) {
1486
+ outputDeltaTokens = Math.abs(effortTable[nextEff] - effortTable[currEff]);
1487
+ } else {
1488
+ outputDeltaTokens = DEFAULT_DET09_OUTPUT_DELTA_TOKENS;
1489
+ }
1490
+ }
1491
+
1492
+ const breakEvenTokens =
1493
+ denominator <= 0
1494
+ ? Infinity
1495
+ : Math.max(0, Math.round((outputDeltaTokens * rates.outputPer1M) / denominator));
1496
+
1497
+ return {
1498
+ breakEvenTokens,
1499
+ outputDeltaTokens,
1500
+ writeRatePer1M: writeRate,
1501
+ readRatePer1M: rates.readPer1M,
1502
+ outputRatePer1M: rates.outputPer1M
1503
+ };
1504
+ }
1505
+
685
1506
  /**
686
1507
  * Convenience functional wrapper for `DET-09` Warm-Prefix Mutation Fence (`PostCompactMutationQueue`).
687
1508
  *
@@ -706,12 +1527,18 @@ export function evaluatePreModelSwitch(request = {}, options = {}) {
706
1527
  export default {
707
1528
  FLIGHT_MODES,
708
1529
  DEFAULT_EXPECTED_OUTPUT_TOKENS,
1530
+ DEFAULT_DET09_OUTPUT_DELTA_TOKENS,
709
1531
  DEFAULT_ADVISORY_COOLDOWN_TURNS,
1532
+ MODEL_EFFORT_CACHE_CAPABILITIES,
1533
+ getEffortMutationCacheCapability,
1534
+ EMPIRICAL_SESSION_API_CALL_PRIOR,
1535
+ estimateEmpiricalRemainingTurns,
710
1536
  normalizeFlightMode,
711
1537
  isSilentOrOffMode,
712
1538
  isPrefixInstructionFile,
713
1539
  resolveNaturalDownshiftPeer,
714
1540
  computeBreakEvenCachedTokens,
1541
+ computeDet09BreakEvenTokens,
715
1542
  evaluatePreModelSwitch,
716
1543
  evaluateDet09PrefixMutationFence,
717
1544
  PostCompactMutationQueue,