ctxtop 0.0.0-stage → 4.0.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.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2002 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +42 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +620 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +966 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/doctorEngine.mjs +203 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/coach/cacheGravityRouter.mjs
|
|
3
|
+
* Anthropic KV-Cache Flight Computer (`CacheGravityScorer`), `PostCompactMutationQueue`,
|
|
4
|
+
* and `HysteresisLock` for Claude Code Highbeam.
|
|
5
|
+
*
|
|
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
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
normalizeModelId,
|
|
14
|
+
computeTotalPromptTokens,
|
|
15
|
+
resolveEffectiveRates
|
|
16
|
+
} from '../config/catalogLoader.mjs';
|
|
17
|
+
|
|
18
|
+
export const FLIGHT_MODES = Object.freeze({
|
|
19
|
+
OFF: 'OFF',
|
|
20
|
+
SILENT: 'SILENT',
|
|
21
|
+
COACH: 'COACH',
|
|
22
|
+
AUTO_PILOT: 'AUTO_PILOT'
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_EXPECTED_OUTPUT_TOKENS = 1500;
|
|
26
|
+
|
|
27
|
+
const PREFIX_INSTRUCTION_FILE_REGEX =
|
|
28
|
+
/(?:^|\/)(?:CLAUDE(?:\.local)?\.md|AGENTS\.md|\.mcp\.json)$|(?:^|\/)\.claude\/(?:CLAUDE\.md|rules\/.+\.md)$/i;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Checks whether a workspace file path is a top-level prompt-prefix instruction or MCP config file
|
|
32
|
+
* whose mid-session modification invalidates the Anthropic KV-cache prefix (`DET-09`).
|
|
33
|
+
*
|
|
34
|
+
* @param {string} [filePath='']
|
|
35
|
+
* @returns {boolean}
|
|
36
|
+
*/
|
|
37
|
+
export function isPrefixInstructionFile(filePath = '') {
|
|
38
|
+
const norm = String(filePath || '').trim().replace(/\\/g, '/');
|
|
39
|
+
if (!norm) return false;
|
|
40
|
+
return PREFIX_INSTRUCTION_FILE_REGEX.test(norm);
|
|
41
|
+
}
|
|
42
|
+
export const DEFAULT_ADVISORY_COOLDOWN_TURNS = 3;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Maps an active model to its natural one-tier downshift peer for cross-model break-even C* (`ISS-006`).
|
|
46
|
+
* - 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)
|
|
49
|
+
* - claude-sonnet-5-5 -> claude-haiku-5-5
|
|
50
|
+
* - claude-sonnet-4-6 / claude-sonnet-4-5 -> claude-haiku-4-5
|
|
51
|
+
* - claude-haiku-4-5 -> claude-haiku-5-5
|
|
52
|
+
*
|
|
53
|
+
* @param {string} [modelId='claude-opus-5-5']
|
|
54
|
+
* @returns {string}
|
|
55
|
+
*/
|
|
56
|
+
export function resolveNaturalDownshiftPeer(modelId = 'claude-opus-5-5') {
|
|
57
|
+
const norm = normalizeModelId(modelId);
|
|
58
|
+
switch (norm) {
|
|
59
|
+
case 'claude-fable-5-2':
|
|
60
|
+
case 'claude-fable-5-1':
|
|
61
|
+
return 'claude-opus-5-5';
|
|
62
|
+
case 'claude-opus-5-5':
|
|
63
|
+
return 'claude-sonnet-5-5';
|
|
64
|
+
case 'claude-opus-4-6':
|
|
65
|
+
return 'claude-sonnet-4-6';
|
|
66
|
+
case 'claude-sonnet-5-5':
|
|
67
|
+
return 'claude-haiku-5-5';
|
|
68
|
+
case 'claude-sonnet-4-6':
|
|
69
|
+
return 'claude-haiku-4-5';
|
|
70
|
+
case 'claude-haiku-4-5':
|
|
71
|
+
case 'claude-haiku-5-5':
|
|
72
|
+
return 'claude-haiku-5-5';
|
|
73
|
+
default:
|
|
74
|
+
return 'claude-sonnet-5-5';
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Normalizes any flight mode string into `'OFF' | 'SILENT' | 'COACH' | 'AUTO_PILOT'`.
|
|
80
|
+
* @param {string} [rawMode='COACH']
|
|
81
|
+
* @returns {'OFF'|'SILENT'|'COACH'|'AUTO_PILOT'}
|
|
82
|
+
*/
|
|
83
|
+
export function normalizeFlightMode(rawMode = 'COACH') {
|
|
84
|
+
const cleaned = String(rawMode || 'COACH')
|
|
85
|
+
.toUpperCase()
|
|
86
|
+
.trim()
|
|
87
|
+
.replace(/[-\s]+/g, '_');
|
|
88
|
+
if (cleaned === 'OFF' || cleaned === 'DISABLED') return FLIGHT_MODES.OFF;
|
|
89
|
+
if (cleaned === 'SILENT' || cleaned === 'QUIET' || cleaned === 'MUTE') {
|
|
90
|
+
return FLIGHT_MODES.SILENT;
|
|
91
|
+
}
|
|
92
|
+
if (cleaned === 'AUTO_PILOT' || cleaned === 'AUTOPILOT' || cleaned === 'AUTO') {
|
|
93
|
+
return FLIGHT_MODES.AUTO_PILOT;
|
|
94
|
+
}
|
|
95
|
+
return FLIGHT_MODES.COACH;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Checks whether a flight mode suppresses non-security coach advisories (`OFF` or `SILENT`).
|
|
100
|
+
* @param {string} [mode='COACH']
|
|
101
|
+
* @returns {boolean}
|
|
102
|
+
*/
|
|
103
|
+
export function isSilentOrOffMode(mode = 'COACH') {
|
|
104
|
+
const norm = normalizeFlightMode(mode);
|
|
105
|
+
return norm === FLIGHT_MODES.OFF || norm === FLIGHT_MODES.SILENT;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Computes the exact cross-model break-even cached token threshold `C*` and USD turn costs.
|
|
110
|
+
*
|
|
111
|
+
* Equation:
|
|
112
|
+
* C* = (O * (P_out,curr - P_out,target)) / (P_write5m,target - P_read,curr)
|
|
113
|
+
*
|
|
114
|
+
* When `cachedTokens > C*` on a warm cache, switching from `currentModel` to `targetModel`
|
|
115
|
+
* costs MORE in cold `1.25x` prefix rewrite than it saves on output tokens.
|
|
116
|
+
*
|
|
117
|
+
* @param {object} [params={}]
|
|
118
|
+
* @param {string} [params.currentModel='claude-opus-5-5']
|
|
119
|
+
* @param {string} [params.targetModel='claude-sonnet-5-5']
|
|
120
|
+
* @param {number} [params.expectedOutputTokens=1500]
|
|
121
|
+
* @param {number} [params.cachedTokens=0]
|
|
122
|
+
* @param {number} [params.uncachedDeltaTokens=0]
|
|
123
|
+
* @param {boolean} [params.cacheWarm=true]
|
|
124
|
+
* @param {'5m'|'1h'} [params.cacheTtlTier='5m']
|
|
125
|
+
* @param {object} [options={}]
|
|
126
|
+
*/
|
|
127
|
+
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);
|
|
132
|
+
const expectedOutputTokens = Math.max(
|
|
133
|
+
0,
|
|
134
|
+
Number(params.expectedOutputTokens ?? DEFAULT_EXPECTED_OUTPUT_TOKENS)
|
|
135
|
+
);
|
|
136
|
+
const cachedTokens = Math.max(0, Number(params.cachedTokens ?? 0));
|
|
137
|
+
const uncachedDeltaTokens = Math.max(0, Number(params.uncachedDeltaTokens ?? 0));
|
|
138
|
+
const cacheWarm = params.cacheWarm !== undefined ? Boolean(params.cacheWarm) : cachedTokens > 0;
|
|
139
|
+
const ttlTier = params.cacheTtlTier === '1h' ? '1h' : '5m';
|
|
140
|
+
|
|
141
|
+
const totalPromptTokens = Math.max(
|
|
142
|
+
cachedTokens + uncachedDeltaTokens,
|
|
143
|
+
computeTotalPromptTokens(params)
|
|
144
|
+
);
|
|
145
|
+
const currRates = resolveEffectiveRates(rawCurrentModel, totalPromptTokens, options);
|
|
146
|
+
const targetRates = resolveEffectiveRates(rawTargetModel, totalPromptTokens, options);
|
|
147
|
+
|
|
148
|
+
const pOutCurr = currRates.outputPer1M;
|
|
149
|
+
const pOutTarget = targetRates.outputPer1M;
|
|
150
|
+
const pReadCurr = currRates.readPer1M;
|
|
151
|
+
const pWriteCurr = ttlTier === '1h' ? currRates.write1hPer1M : currRates.write5mPer1M;
|
|
152
|
+
const pWriteTarget = ttlTier === '1h' ? targetRates.write1hPer1M : targetRates.write5mPer1M;
|
|
153
|
+
|
|
154
|
+
const isCapabilityUpshift = pOutCurr <= pOutTarget;
|
|
155
|
+
|
|
156
|
+
let breakEvenTokens = 0;
|
|
157
|
+
if (currentModel === targetModel || isCapabilityUpshift) {
|
|
158
|
+
breakEvenTokens = 0;
|
|
159
|
+
} else {
|
|
160
|
+
const numeratorUSD =
|
|
161
|
+
(expectedOutputTokens / 1_000_000) * (pOutCurr - pOutTarget) +
|
|
162
|
+
(uncachedDeltaTokens / 1_000_000) * (pWriteCurr - pWriteTarget);
|
|
163
|
+
const denominator = pWriteTarget - pReadCurr;
|
|
164
|
+
if (numeratorUSD <= 0) {
|
|
165
|
+
breakEvenTokens = 0;
|
|
166
|
+
} else if (denominator <= 0) {
|
|
167
|
+
breakEvenTokens = Infinity;
|
|
168
|
+
} else {
|
|
169
|
+
breakEvenTokens = Math.round((numeratorUSD * 1_000_000) / denominator);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Exact USD turn cost if staying on currentModel vs switching to targetModel
|
|
174
|
+
const stayPrefixCostUSD = cacheWarm
|
|
175
|
+
? (cachedTokens / 1_000_000) * pReadCurr + (uncachedDeltaTokens / 1_000_000) * pWriteCurr
|
|
176
|
+
: ((cachedTokens + uncachedDeltaTokens) / 1_000_000) * pWriteCurr;
|
|
177
|
+
const stayOutputCostUSD = (expectedOutputTokens / 1_000_000) * pOutCurr;
|
|
178
|
+
const stayOnCurrentModelUSD = stayPrefixCostUSD + stayOutputCostUSD;
|
|
179
|
+
|
|
180
|
+
// Switching to a different model invalidates the isolated per-model cache, forcing a full cold write
|
|
181
|
+
const switchPrefixCostUSD =
|
|
182
|
+
currentModel === targetModel && cacheWarm
|
|
183
|
+
? stayPrefixCostUSD
|
|
184
|
+
: ((cachedTokens + uncachedDeltaTokens) / 1_000_000) * pWriteTarget;
|
|
185
|
+
const switchOutputCostUSD = (expectedOutputTokens / 1_000_000) * pOutTarget;
|
|
186
|
+
const switchToTargetModelUSD = switchPrefixCostUSD + switchOutputCostUSD;
|
|
187
|
+
|
|
188
|
+
const coldWritePenaltyUSD = Number(
|
|
189
|
+
(switchToTargetModelUSD - stayOnCurrentModelUSD).toFixed(6)
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
// Never hold/deny on capability upshifts (pOutCurr <= pOutTarget) or when coldWritePenaltyUSD <= 0 (`ISS-006`)
|
|
193
|
+
const shouldHoldModel = Boolean(
|
|
194
|
+
currentModel !== targetModel &&
|
|
195
|
+
!isCapabilityUpshift &&
|
|
196
|
+
cacheWarm &&
|
|
197
|
+
coldWritePenaltyUSD > 0 &&
|
|
198
|
+
cachedTokens > breakEvenTokens
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
currentModel,
|
|
203
|
+
targetModel,
|
|
204
|
+
expectedOutputTokens,
|
|
205
|
+
cachedTokens,
|
|
206
|
+
uncachedDeltaTokens,
|
|
207
|
+
totalPromptTokens,
|
|
208
|
+
cacheWarm,
|
|
209
|
+
cacheTtlTier: ttlTier,
|
|
210
|
+
writeMultiplierLabel: ttlTier === '1h' ? '2.0x' : '1.25x',
|
|
211
|
+
isCapabilityUpshift,
|
|
212
|
+
breakEvenTokens,
|
|
213
|
+
rates: {
|
|
214
|
+
currentOutputPer1M: pOutCurr,
|
|
215
|
+
targetOutputPer1M: pOutTarget,
|
|
216
|
+
currentReadPer1M: pReadCurr,
|
|
217
|
+
currentWritePer1M: pWriteCurr,
|
|
218
|
+
targetWritePer1M: pWriteTarget
|
|
219
|
+
},
|
|
220
|
+
stayOnCurrentModelUSD: Number(stayOnCurrentModelUSD.toFixed(6)),
|
|
221
|
+
switchToTargetModelUSD: Number(switchToTargetModelUSD.toFixed(6)),
|
|
222
|
+
coldWritePenaltyUSD,
|
|
223
|
+
shouldHold: shouldHoldModel,
|
|
224
|
+
shouldHoldModel
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Queue for deferring top-level `effort`, `thinking`, `system_prompt`, or `mcp_tools`
|
|
230
|
+
* mutations until immediately after context compaction (`PostCompact`), avoiding mid-session
|
|
231
|
+
* full-prefix cache invalidation (`DET-09`).
|
|
232
|
+
*/
|
|
233
|
+
export class PostCompactMutationQueue {
|
|
234
|
+
/**
|
|
235
|
+
* @param {Array<object>} [initialItems=[]]
|
|
236
|
+
*/
|
|
237
|
+
constructor(initialItems = []) {
|
|
238
|
+
this.items = Array.isArray(initialItems) ? [...initialItems] : [];
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Enqueues or updates a deferred mutation keyed by `(type, key)`.
|
|
243
|
+
* @param {object} mutation
|
|
244
|
+
* @param {'effort'|'thinking'|'speed'|'system_prompt'|'mcp_tools'|'model'} mutation.type
|
|
245
|
+
* @param {string} [mutation.key]
|
|
246
|
+
* @param {any} mutation.value
|
|
247
|
+
* @param {string} [mutation.reason]
|
|
248
|
+
* @param {number} [mutation.avoidedRewritePenaltyUSD]
|
|
249
|
+
* @param {number} [mutation.cachedTokens]
|
|
250
|
+
* @param {number} [mutation.savedTokens]
|
|
251
|
+
* @returns {object} Enqueued entry
|
|
252
|
+
*/
|
|
253
|
+
enqueue(mutation = {}) {
|
|
254
|
+
const type = String(mutation.type || 'effort');
|
|
255
|
+
const key = String(mutation.key || type);
|
|
256
|
+
const entry = {
|
|
257
|
+
type,
|
|
258
|
+
key,
|
|
259
|
+
value: mutation.value,
|
|
260
|
+
reason: mutation.reason || 'Deferred to PostCompact to preserve warm Anthropic prompt cache prefix',
|
|
261
|
+
avoidedRewritePenaltyUSD: Number(mutation.avoidedRewritePenaltyUSD || 0),
|
|
262
|
+
cachedTokens: Math.max(0, Number(mutation.cachedTokens || 0)),
|
|
263
|
+
savedTokens: Math.max(0, Number(mutation.savedTokens || 0)),
|
|
264
|
+
enqueuedAt: mutation.enqueuedAt || Date.now()
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const existingIdx = this.items.findIndex((item) => item.type === type && item.key === key);
|
|
268
|
+
if (existingIdx >= 0) {
|
|
269
|
+
this.items[existingIdx] = entry;
|
|
270
|
+
} else {
|
|
271
|
+
this.items.push(entry);
|
|
272
|
+
}
|
|
273
|
+
return entry;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Returns a shallow copy of all pending mutations without removing them.
|
|
278
|
+
* @returns {Array<object>}
|
|
279
|
+
*/
|
|
280
|
+
peekAll() {
|
|
281
|
+
return [...this.items];
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Returns the number of queued mutations.
|
|
286
|
+
* @returns {number}
|
|
287
|
+
*/
|
|
288
|
+
size() {
|
|
289
|
+
return this.items.length;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Checks whether any mutations are waiting for compaction.
|
|
294
|
+
* @returns {boolean}
|
|
295
|
+
*/
|
|
296
|
+
hasPending() {
|
|
297
|
+
return this.items.length > 0;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Flushes and returns all queued mutations on `PostCompact` so they apply at zero extra rewrite cost.
|
|
302
|
+
* @param {object} [context={}]
|
|
303
|
+
* @returns {{ flushedCount: number, appliedMutations: Array<object>, totalAvoidedPenaltyUSD: number, flushedAt: number }}
|
|
304
|
+
*/
|
|
305
|
+
flush(context = {}) {
|
|
306
|
+
const appliedMutations = [...this.items];
|
|
307
|
+
this.items = [];
|
|
308
|
+
const totalAvoidedPenaltyUSD = Number(
|
|
309
|
+
appliedMutations
|
|
310
|
+
.reduce((acc, item) => acc + Number(item.avoidedRewritePenaltyUSD || 0), 0)
|
|
311
|
+
.toFixed(6)
|
|
312
|
+
);
|
|
313
|
+
return {
|
|
314
|
+
flushedCount: appliedMutations.length,
|
|
315
|
+
appliedMutations,
|
|
316
|
+
totalAvoidedPenaltyUSD,
|
|
317
|
+
flushedAt: context.nowMs || Date.now()
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Clears the queue.
|
|
323
|
+
*/
|
|
324
|
+
clear() {
|
|
325
|
+
this.items = [];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Serializes queue for `$.store` or `StateBaton`.
|
|
330
|
+
* @returns {Array<object>}
|
|
331
|
+
*/
|
|
332
|
+
toJSON() {
|
|
333
|
+
return [...this.items];
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Restores a `PostCompactMutationQueue` from serialized array.
|
|
338
|
+
* @param {Array<object>} data
|
|
339
|
+
* @returns {PostCompactMutationQueue}
|
|
340
|
+
*/
|
|
341
|
+
static fromJSON(data) {
|
|
342
|
+
return new PostCompactMutationQueue(Array.isArray(data) ? data : []);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Hysteresis Lock ensuring loop-triggered escalations (`DET-04` consecutive failures or `DET-05`
|
|
348
|
+
* edit thrashing) stay pinned until active task completion or rewind/branch reset.
|
|
349
|
+
*/
|
|
350
|
+
export class HysteresisLock {
|
|
351
|
+
constructor(initialState = {}) {
|
|
352
|
+
this.locked = Boolean(initialState.locked);
|
|
353
|
+
this.pinnedModel = initialState.pinnedModel || null;
|
|
354
|
+
this.pinnedEffort = initialState.pinnedEffort || null;
|
|
355
|
+
this.reason = initialState.reason || null;
|
|
356
|
+
this.lockedAtTurn = initialState.lockedAtTurn ?? null;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Pins model/effort due to a loop or thrashing escalation.
|
|
361
|
+
* @param {object} params
|
|
362
|
+
*/
|
|
363
|
+
engage({ model, effort = 'high', reason = 'Loop escalation lock', turn = 0 } = {}) {
|
|
364
|
+
this.locked = true;
|
|
365
|
+
this.pinnedModel = model ? normalizeModelId(model) : this.pinnedModel;
|
|
366
|
+
this.pinnedEffort = effort;
|
|
367
|
+
this.reason = reason;
|
|
368
|
+
this.lockedAtTurn = turn;
|
|
369
|
+
return this.getStatus();
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Releases the lock when the active task completes cleanly.
|
|
374
|
+
*/
|
|
375
|
+
completeActiveTask() {
|
|
376
|
+
this.locked = false;
|
|
377
|
+
this.pinnedModel = null;
|
|
378
|
+
this.pinnedEffort = null;
|
|
379
|
+
this.reason = null;
|
|
380
|
+
this.lockedAtTurn = null;
|
|
381
|
+
return this.getStatus();
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Releases the lock on conversation rewind or git branch reset.
|
|
386
|
+
*/
|
|
387
|
+
resetOnRewindOrBranch() {
|
|
388
|
+
return this.completeActiveTask();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Returns current lock status.
|
|
393
|
+
*/
|
|
394
|
+
getStatus() {
|
|
395
|
+
return {
|
|
396
|
+
locked: this.locked,
|
|
397
|
+
pinnedModel: this.pinnedModel,
|
|
398
|
+
pinnedEffort: this.pinnedEffort,
|
|
399
|
+
reason: this.reason,
|
|
400
|
+
lockedAtTurn: this.lockedAtTurn
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Anthropic Cache GravityScorer & Flight Computer Router.
|
|
407
|
+
* Supports `OFF | COACH | AUTO_PILOT` modes, 3-turn advisory cooldown,
|
|
408
|
+
* `PreModelSwitch` (`DET-08`) break-even protection, `PostCompactMutationQueue` (`DET-09`),
|
|
409
|
+
* and `Explore`/`Task` Haiku 5.5 subagent leaf delegation.
|
|
410
|
+
*/
|
|
411
|
+
export class CacheGravityRouter {
|
|
412
|
+
/**
|
|
413
|
+
* @param {object} [options={}]
|
|
414
|
+
*/
|
|
415
|
+
constructor(options = {}) {
|
|
416
|
+
this.options = options;
|
|
417
|
+
this.mode = normalizeFlightMode(options.mode || FLIGHT_MODES.COACH);
|
|
418
|
+
this.cooldownTurns = Number(options.cooldownTurns ?? DEFAULT_ADVISORY_COOLDOWN_TURNS);
|
|
419
|
+
this.lastAdvisoryTurn = null;
|
|
420
|
+
this.mutationQueue =
|
|
421
|
+
options.mutationQueue instanceof PostCompactMutationQueue
|
|
422
|
+
? options.mutationQueue
|
|
423
|
+
: new PostCompactMutationQueue(options.queuedMutations || []);
|
|
424
|
+
this.hysteresisLock =
|
|
425
|
+
options.hysteresisLock instanceof HysteresisLock
|
|
426
|
+
? options.hysteresisLock
|
|
427
|
+
: new HysteresisLock(options.hysteresisState || {});
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Updates the Flight Computer operating mode (`OFF | COACH | AUTO_PILOT`).
|
|
432
|
+
* @param {string} mode
|
|
433
|
+
* @returns {'OFF'|'COACH'|'AUTO_PILOT'}
|
|
434
|
+
*/
|
|
435
|
+
setMode(mode) {
|
|
436
|
+
this.mode = normalizeFlightMode(mode);
|
|
437
|
+
return this.mode;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Checks whether a non-crisis advisory nudge is currently in its 3-turn cooldown window.
|
|
442
|
+
* Unconditional prefix-loss blocks and Haiku 100k cliff crises are exempt from cooldown.
|
|
443
|
+
*
|
|
444
|
+
* @param {number} currentTurn
|
|
445
|
+
* @param {boolean} [isUnconditionalCrisis=false]
|
|
446
|
+
* @returns {boolean}
|
|
447
|
+
*/
|
|
448
|
+
isCooldownActive(currentTurn = 0, isUnconditionalCrisis = false) {
|
|
449
|
+
if (isUnconditionalCrisis) return false;
|
|
450
|
+
if (this.lastAdvisoryTurn === null) return false;
|
|
451
|
+
return currentTurn - this.lastAdvisoryTurn < this.cooldownTurns;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Evaluates a proposed cross-model switch (`PreModelSwitch` / `DET-08`).
|
|
456
|
+
* When `prompt_cache.warm === true` and `cachedTokens > C*`, blocks main-thread downgrades
|
|
457
|
+
* and recommends offloading routine exploration to an isolated `claude-haiku-5-5` subagent.
|
|
458
|
+
*
|
|
459
|
+
* @param {object} [request={}]
|
|
460
|
+
* @param {string} [request.currentModel='claude-opus-5-5']
|
|
461
|
+
* @param {string} [request.targetModel='claude-sonnet-5-5']
|
|
462
|
+
* @param {number} [request.cachedTokens=0]
|
|
463
|
+
* @param {number} [request.uncachedDeltaTokens=0]
|
|
464
|
+
* @param {number} [request.expectedOutputTokens=1500]
|
|
465
|
+
* @param {boolean} [request.cacheWarm=true]
|
|
466
|
+
* @param {'5m'|'1h'} [request.cacheTtlTier='5m']
|
|
467
|
+
* @param {number} [request.currentTurn=0]
|
|
468
|
+
*/
|
|
469
|
+
evaluateModelSwitch(request = {}) {
|
|
470
|
+
const breakEven = computeBreakEvenCachedTokens(request, this.options);
|
|
471
|
+
const currentTurn = Number(request.currentTurn ?? 0);
|
|
472
|
+
|
|
473
|
+
// Check HysteresisLock first
|
|
474
|
+
if (
|
|
475
|
+
this.hysteresisLock.locked &&
|
|
476
|
+
this.hysteresisLock.pinnedModel &&
|
|
477
|
+
breakEven.targetModel !== this.hysteresisLock.pinnedModel
|
|
478
|
+
) {
|
|
479
|
+
const suppressed = isSilentOrOffMode(this.mode);
|
|
480
|
+
return {
|
|
481
|
+
detectorId: 'DET-08',
|
|
482
|
+
mode: this.mode,
|
|
483
|
+
decision: suppressed ? 'allow' : 'deny',
|
|
484
|
+
blocked: !suppressed,
|
|
485
|
+
hysteresisLocked: true,
|
|
486
|
+
breakEven,
|
|
487
|
+
recommendedModel: this.hysteresisLock.pinnedModel,
|
|
488
|
+
subagentDelegation: null,
|
|
489
|
+
reason: `HysteresisLock active (${this.hysteresisLock.reason}): model pinned to ${this.hysteresisLock.pinnedModel} until active task completes.`
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (isSilentOrOffMode(this.mode)) {
|
|
494
|
+
return {
|
|
495
|
+
detectorId: 'DET-08',
|
|
496
|
+
mode: this.mode,
|
|
497
|
+
decision: 'allow',
|
|
498
|
+
blocked: false,
|
|
499
|
+
hysteresisLocked: false,
|
|
500
|
+
breakEven,
|
|
501
|
+
recommendedModel: breakEven.targetModel,
|
|
502
|
+
subagentDelegation: null,
|
|
503
|
+
reason: null
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if (breakEven.shouldHoldModel) {
|
|
508
|
+
// Unconditional prefix-loss protection: exempt from 3-turn advisory cooldown
|
|
509
|
+
const writeMultLabel = breakEven.cacheTtlTier === '1h' ? '2.0x' : '1.25x';
|
|
510
|
+
const subagentDelegation = {
|
|
511
|
+
agentType: 'Explore',
|
|
512
|
+
model: 'claude-haiku-5-5',
|
|
513
|
+
maxContextTokens: 2000,
|
|
514
|
+
turnCap: 12,
|
|
515
|
+
tokenCap: 40000,
|
|
516
|
+
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
|
+
};
|
|
518
|
+
|
|
519
|
+
const reasonText =
|
|
520
|
+
`[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.`;
|
|
525
|
+
|
|
526
|
+
// In COACH mode (default), remain 100% advisory and non-blocking unless strictBlock is explicitly set
|
|
527
|
+
if (this.mode === FLIGHT_MODES.COACH && !request.strictBlock && !this.options.strictBlock) {
|
|
528
|
+
return {
|
|
529
|
+
detectorId: 'DET-08',
|
|
530
|
+
mode: this.mode,
|
|
531
|
+
decision: 'allow',
|
|
532
|
+
blocked: false,
|
|
533
|
+
advisory: true,
|
|
534
|
+
hysteresisLocked: false,
|
|
535
|
+
breakEven,
|
|
536
|
+
recommendedModel: breakEven.currentModel,
|
|
537
|
+
subagentDelegation,
|
|
538
|
+
reason: reasonText
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// In AUTO_PILOT mode, actively gate the destructive model switch ('ask' or 'deny')
|
|
543
|
+
const autoDecision =
|
|
544
|
+
request.autoPilotDecision || this.options.autoPilotDecision || 'deny';
|
|
545
|
+
|
|
546
|
+
return {
|
|
547
|
+
detectorId: 'DET-08',
|
|
548
|
+
mode: this.mode,
|
|
549
|
+
decision: autoDecision,
|
|
550
|
+
blocked: true,
|
|
551
|
+
advisory: false,
|
|
552
|
+
hysteresisLocked: false,
|
|
553
|
+
breakEven,
|
|
554
|
+
recommendedModel: breakEven.currentModel,
|
|
555
|
+
subagentDelegation,
|
|
556
|
+
reason: reasonText
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// Advisory evaluation when cache is cold, below C*, or a capability upshift
|
|
561
|
+
const cooldownSuppressed = this.isCooldownActive(currentTurn, false);
|
|
562
|
+
if (!cooldownSuppressed && this.mode === FLIGHT_MODES.COACH) {
|
|
563
|
+
this.lastAdvisoryTurn = currentTurn;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const allowReason =
|
|
567
|
+
breakEven.isCapabilityUpshift && breakEven.currentModel !== breakEven.targetModel
|
|
568
|
+
? `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()}).`;
|
|
570
|
+
|
|
571
|
+
return {
|
|
572
|
+
detectorId: 'DET-08',
|
|
573
|
+
mode: this.mode,
|
|
574
|
+
decision: 'allow',
|
|
575
|
+
blocked: false,
|
|
576
|
+
advisory: false,
|
|
577
|
+
cooldownSuppressed,
|
|
578
|
+
hysteresisLocked: false,
|
|
579
|
+
breakEven,
|
|
580
|
+
recommendedModel: breakEven.targetModel,
|
|
581
|
+
subagentDelegation: null,
|
|
582
|
+
reason: allowReason
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* 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.
|
|
590
|
+
*
|
|
591
|
+
* @param {object} [mutationRequest={}]
|
|
592
|
+
* @param {'effort'|'thinking'|'speed'|'system_prompt'|'mcp_tools'} [mutationRequest.type='effort']
|
|
593
|
+
* @param {string} [mutationRequest.key]
|
|
594
|
+
* @param {any} mutationRequest.value
|
|
595
|
+
* @param {string} [mutationRequest.currentModel='claude-opus-5-5']
|
|
596
|
+
* @param {number} [mutationRequest.cachedTokens=0]
|
|
597
|
+
* @param {boolean} [mutationRequest.cacheWarm=true]
|
|
598
|
+
* @param {'5m'|'1h'} [mutationRequest.cacheTtlTier='5m']
|
|
599
|
+
*/
|
|
600
|
+
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
|
+
|
|
616
|
+
const targetFilePath = String(
|
|
617
|
+
mutationRequest.filePath || mutationRequest.file_path || mutationRequest.path || ''
|
|
618
|
+
).trim();
|
|
619
|
+
|
|
620
|
+
if (
|
|
621
|
+
targetFilePath &&
|
|
622
|
+
(!mutationRequest.type || mutationRequest.type === 'file_edit') &&
|
|
623
|
+
!isPrefixInstructionFile(targetFilePath)
|
|
624
|
+
) {
|
|
625
|
+
return {
|
|
626
|
+
detectorId: 'DET-09',
|
|
627
|
+
triggered: false,
|
|
628
|
+
queued: false,
|
|
629
|
+
decision: 'allow',
|
|
630
|
+
avoidedRewritePenaltyUSD: 0,
|
|
631
|
+
queueSize: this.mutationQueue.size(),
|
|
632
|
+
reason: null
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const ttlTier = mutationRequest.cacheTtlTier === '1h' ? '1h' : '5m';
|
|
637
|
+
const totalPromptTokens = Math.max(cachedTokens, computeTotalPromptTokens(mutationRequest));
|
|
638
|
+
const rates = resolveEffectiveRates(rawModel, totalPromptTokens, this.options);
|
|
639
|
+
const writeRate = ttlTier === '1h' ? rates.write1hPer1M : rates.write5mPer1M;
|
|
640
|
+
|
|
641
|
+
if (isSilentOrOffMode(this.mode) || !cacheWarm || cachedTokens === 0) {
|
|
642
|
+
return {
|
|
643
|
+
detectorId: 'DET-09',
|
|
644
|
+
triggered: false,
|
|
645
|
+
queued: false,
|
|
646
|
+
decision: 'allow',
|
|
647
|
+
avoidedRewritePenaltyUSD: 0,
|
|
648
|
+
queueSize: this.mutationQueue.size(),
|
|
649
|
+
reason: 'Cache is cold or router is OFF/SILENT; top-level mutation may apply immediately.'
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
const avoidedRewritePenaltyUSD = Number(
|
|
654
|
+
((cachedTokens / 1_000_000) * (writeRate - rates.readPer1M)).toFixed(6)
|
|
655
|
+
);
|
|
656
|
+
|
|
657
|
+
const mutationType =
|
|
658
|
+
mutationRequest.type || (targetFilePath ? 'system_prompt' : 'effort');
|
|
659
|
+
const entry = this.mutationQueue.enqueue({
|
|
660
|
+
type: mutationType,
|
|
661
|
+
key: mutationRequest.key || targetFilePath || mutationType,
|
|
662
|
+
value: mutationRequest.value,
|
|
663
|
+
cachedTokens,
|
|
664
|
+
avoidedRewritePenaltyUSD,
|
|
665
|
+
reason:
|
|
666
|
+
`[DET-09 Top-Level Mutation Deferred] Mutating top-level ${mutationType} ` +
|
|
667
|
+
`while ${cachedTokens.toLocaleString()} tokens are warm on ${modelId} would invalidate the ` +
|
|
668
|
+
`Anthropic prompt cache prefix (+$${avoidedRewritePenaltyUSD.toFixed(4)} rewrite spike). ` +
|
|
669
|
+
`Queued in PostCompactMutationQueue to apply after next compaction.`
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
return {
|
|
673
|
+
detectorId: 'DET-09',
|
|
674
|
+
triggered: true,
|
|
675
|
+
queued: true,
|
|
676
|
+
decision: 'defer',
|
|
677
|
+
entry,
|
|
678
|
+
avoidedRewritePenaltyUSD,
|
|
679
|
+
queueSize: this.mutationQueue.size(),
|
|
680
|
+
reason: entry.reason
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Convenience functional wrapper for `DET-09` Warm-Prefix Mutation Fence (`PostCompactMutationQueue`).
|
|
687
|
+
*
|
|
688
|
+
* @param {object} [mutationRequest={}]
|
|
689
|
+
* @param {object} [options={}]
|
|
690
|
+
*/
|
|
691
|
+
export function evaluateDet09PrefixMutationFence(mutationRequest = {}, options = {}) {
|
|
692
|
+
const router = new CacheGravityRouter(options);
|
|
693
|
+
return router.interceptTopLevelMutation(mutationRequest);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* Convenience functional wrapper for `DET-08` `PreModelSwitch` evaluation.
|
|
698
|
+
* @param {object} [request={}]
|
|
699
|
+
* @param {object} [options={}]
|
|
700
|
+
*/
|
|
701
|
+
export function evaluatePreModelSwitch(request = {}, options = {}) {
|
|
702
|
+
const router = new CacheGravityRouter(options);
|
|
703
|
+
return router.evaluateModelSwitch(request);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
export default {
|
|
707
|
+
FLIGHT_MODES,
|
|
708
|
+
DEFAULT_EXPECTED_OUTPUT_TOKENS,
|
|
709
|
+
DEFAULT_ADVISORY_COOLDOWN_TURNS,
|
|
710
|
+
normalizeFlightMode,
|
|
711
|
+
isSilentOrOffMode,
|
|
712
|
+
isPrefixInstructionFile,
|
|
713
|
+
resolveNaturalDownshiftPeer,
|
|
714
|
+
computeBreakEvenCachedTokens,
|
|
715
|
+
evaluatePreModelSwitch,
|
|
716
|
+
evaluateDet09PrefixMutationFence,
|
|
717
|
+
PostCompactMutationQueue,
|
|
718
|
+
HysteresisLock,
|
|
719
|
+
CacheGravityRouter
|
|
720
|
+
};
|