ctxtop 0.0.0-stage → 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 (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,1656 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { AgBridgeService } from './ag_bridge.mjs';
5
+ import {
6
+ ANTIGRAVITY_ENUM_ALIASES,
7
+ LEGACY_MODEL_SUNSET_UTC,
8
+ SHARED_1M_CONTEXT_POOL_TOKENS,
9
+ resolveModelDescriptor,
10
+ resolveModelRates,
11
+ isModelDeprecated,
12
+ getDeprecatedModelMigrationNotice,
13
+ isPlanTierEligible
14
+ } from './constants.mjs';
15
+
16
+ /**
17
+ * Upgraded Phase 5: Task Model & Multi-Tier Quota Router
18
+ * ("Floor is the Guarantee" + CacheGravityScorer + TaskMdDirectiveWatcher + ModelSelectorActuator)
19
+ *
20
+ * Zero-trust local execution (<5ms classification, <2ms task.md directive parse,
21
+ * zero external API or network calls).
22
+ */
23
+
24
+ export const WARM_CACHE_GRAVITY_THRESHOLD_TOKENS = 60000;
25
+ export const FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD = 0.85;
26
+ export const DEFAULT_EXPECTED_OUTPUT_TOKENS = 1500;
27
+
28
+ export const MODEL_CATALOG = {
29
+ 'gemini-3.8-flash': {
30
+ id: 'gemini-3.8-flash',
31
+ family: 'flash',
32
+ label: 'Gemini 3.8 Flash',
33
+ supported_efforts: ['low', 'medium', 'high'],
34
+ caching_mode: 'implicit_only',
35
+ supports_explicit_cache: false,
36
+ antigravity_min_tier: 'free',
37
+ shared_pool_ceiling: 256000,
38
+ deprecated_after: null,
39
+ multipliers: { low: 1.0, med: 1.5, medium: 1.5, high: 2.2 }
40
+ },
41
+ 'gemini-3.8-pro': {
42
+ id: 'gemini-3.8-pro',
43
+ family: 'pro',
44
+ label: 'Gemini 3.8 Pro',
45
+ supported_efforts: ['low', 'medium', 'high'],
46
+ caching_mode: 'implicit_only',
47
+ supports_explicit_cache: false,
48
+ antigravity_min_tier: 'pro',
49
+ deprecated_after: null,
50
+ multipliers: { low: 2.0, med: 3.5, medium: 3.5, high: 5.0 }
51
+ },
52
+ 'gemini-4-argon': {
53
+ id: 'gemini-4-argon',
54
+ aliases: ['gemini-4-argon-high', 'gemini-4-argon-medium', 'gemini-4-argon-med', 'gemini-4-argon-low'],
55
+ family: 'argon',
56
+ label: 'Gemini 4 Argon',
57
+ supported_efforts: ['low', 'medium', 'high'],
58
+ caching_mode: 'implicit_only',
59
+ supports_explicit_cache: false,
60
+ antigravity_min_tier: 'pro',
61
+ shared_pool_ceiling: SHARED_1M_CONTEXT_POOL_TOKENS,
62
+ deprecated_after: null,
63
+ multipliers: { low: 3.0, med: 5.5, medium: 5.5, high: 9.25 }
64
+ },
65
+ 'gemini-4-carbon': {
66
+ id: 'gemini-4-carbon',
67
+ aliases: ['gemini-4-carbon-high', 'gemini-4-carbon-medium', 'gemini-4-carbon-med', 'gemini-4-carbon-low', 'M427', 'M437', 'M438'],
68
+ family: 'carbon',
69
+ label: 'Gemini 4 Carbon',
70
+ supported_efforts: ['low', 'medium', 'high'],
71
+ caching_mode: 'implicit_only',
72
+ supports_explicit_cache: false,
73
+ antigravity_min_tier: 'ultra',
74
+ shared_pool_ceiling: SHARED_1M_CONTEXT_POOL_TOKENS,
75
+ deprecated_after: null,
76
+ multipliers: { low: 3.2, med: 6.0, medium: 6.0, high: 10.0 }
77
+ },
78
+ 'gemini-4-carbon-cyber-permissive': {
79
+ id: 'gemini-4-carbon-cyber-permissive',
80
+ aliases: ['M670'],
81
+ family: 'carbon',
82
+ label: 'Gemini 4 Carbon (Cyber Permissive)',
83
+ supported_efforts: ['low', 'medium', 'high'],
84
+ caching_mode: 'implicit_only',
85
+ supports_explicit_cache: false,
86
+ antigravity_min_tier: 'ultra',
87
+ shared_pool_ceiling: SHARED_1M_CONTEXT_POOL_TOKENS,
88
+ deprecated_after: null,
89
+ multipliers: { low: 3.2, med: 6.0, medium: 6.0, high: 10.0 }
90
+ },
91
+ 'claude-haiku-5-5': {
92
+ id: 'claude-haiku-5-5',
93
+ aliases: ['claude-haiku-5.5', 'haiku-5-5', 'haiku-5.5'],
94
+ family: 'haiku',
95
+ label: 'Claude Haiku 5.5',
96
+ supported_efforts: ['low', 'medium', 'high'],
97
+ caching_mode: 'explicit_and_implicit',
98
+ supports_explicit_cache: true,
99
+ antigravity_min_tier: 'pro',
100
+ shared_pool_ceiling: 1000000,
101
+ deprecated_after: null,
102
+ multipliers: { low: 0.5, med: 0.8, medium: 0.8, high: 1.2 }
103
+ },
104
+ 'claude-sonnet-5-5': {
105
+ id: 'claude-sonnet-5-5',
106
+ aliases: ['claude-sonnet-5.5', 'sonnet-5-5', 'sonnet-5.5'],
107
+ family: 'sonnet',
108
+ label: 'Claude Sonnet 5.5',
109
+ supported_efforts: ['low', 'medium', 'high'],
110
+ caching_mode: 'explicit_and_implicit',
111
+ supports_explicit_cache: true,
112
+ antigravity_min_tier: 'pro',
113
+ shared_pool_ceiling: 1000000,
114
+ deprecated_after: null,
115
+ multipliers: { low: 3.0, med: 4.5, medium: 4.5, high: 7.0 }
116
+ },
117
+ 'claude-opus-5-5': {
118
+ id: 'claude-opus-5-5',
119
+ aliases: ['claude-opus-5.5', 'opus-5-5', 'opus-5.5'],
120
+ family: 'opus',
121
+ label: 'Claude Opus 5.5',
122
+ supported_efforts: ['low', 'medium', 'high'],
123
+ caching_mode: 'explicit_and_implicit',
124
+ supports_explicit_cache: true,
125
+ antigravity_min_tier: 'pro',
126
+ shared_pool_ceiling: 1000000,
127
+ deprecated_after: null,
128
+ multipliers: { low: 6.0, med: 9.0, medium: 9.0, high: 14.0 }
129
+ },
130
+ 'claude-fable-5-2': {
131
+ id: 'claude-fable-5-2',
132
+ aliases: ['claude-fable-5.2', 'fable-5-2', 'fable-5.2'],
133
+ family: 'fable',
134
+ label: 'Claude Fable 5.2',
135
+ supported_efforts: ['low', 'medium', 'high'],
136
+ caching_mode: 'explicit_and_implicit',
137
+ supports_explicit_cache: true,
138
+ antigravity_min_tier: 'ultra',
139
+ shared_pool_ceiling: 1000000,
140
+ deprecated_after: null,
141
+ multipliers: { low: 10.0, med: 15.0, medium: 15.0, high: 22.0 }
142
+ },
143
+ 'claude-fable-5-1': {
144
+ id: 'claude-fable-5-1',
145
+ aliases: ['claude-fable-5.1', 'fable-5-1', 'fable-5.1'],
146
+ family: 'fable',
147
+ label: 'Claude Fable 5.1',
148
+ supported_efforts: ['low', 'medium', 'high'],
149
+ caching_mode: 'explicit_and_implicit',
150
+ supports_explicit_cache: true,
151
+ antigravity_min_tier: 'ultra',
152
+ shared_pool_ceiling: 1000000,
153
+ deprecated_after: null,
154
+ multipliers: { low: 12.0, med: 18.0, medium: 18.0, high: 26.0 }
155
+ },
156
+ 'claude-sonnet-4-6': {
157
+ id: 'claude-sonnet-4-6',
158
+ family: 'sonnet',
159
+ label: 'Claude Sonnet 4.6',
160
+ supported_efforts: ['low', 'medium', 'high'],
161
+ caching_mode: 'explicit_and_implicit',
162
+ supports_explicit_cache: true,
163
+ antigravity_min_tier: 'pro',
164
+ shared_pool_ceiling: 200000,
165
+ deprecated_after: LEGACY_MODEL_SUNSET_UTC,
166
+ multipliers: { low: 3.5, med: 5.0, medium: 5.0, high: 7.5 }
167
+ },
168
+ 'claude-sonnet-4.6': {
169
+ id: 'claude-sonnet-4.6',
170
+ family: 'sonnet',
171
+ label: 'Claude Sonnet 4.6',
172
+ supported_efforts: ['low', 'medium', 'high'],
173
+ caching_mode: 'explicit_and_implicit',
174
+ supports_explicit_cache: true,
175
+ antigravity_min_tier: 'pro',
176
+ shared_pool_ceiling: 200000,
177
+ deprecated_after: LEGACY_MODEL_SUNSET_UTC,
178
+ multipliers: { low: 3.5, med: 5.0, medium: 5.0, high: 7.5 }
179
+ },
180
+ 'claude-sonnet-4-5': {
181
+ id: 'claude-sonnet-4-5',
182
+ aliases: ['claude-sonnet-4.5'],
183
+ family: 'sonnet',
184
+ label: 'Claude Sonnet 4.5',
185
+ supported_efforts: ['low', 'medium', 'high'],
186
+ caching_mode: 'explicit_and_implicit',
187
+ supports_explicit_cache: true,
188
+ antigravity_min_tier: 'pro',
189
+ shared_pool_ceiling: 200000,
190
+ deprecated_after: null,
191
+ multipliers: { low: 3.5, med: 5.0, medium: 5.0, high: 7.5 }
192
+ },
193
+ 'claude-opus-4-6': {
194
+ id: 'claude-opus-4-6',
195
+ aliases: ['claude-opus-4.6'],
196
+ family: 'opus',
197
+ label: 'Claude Opus 4.6',
198
+ supported_efforts: ['low', 'medium', 'high'],
199
+ caching_mode: 'explicit_and_implicit',
200
+ supports_explicit_cache: true,
201
+ antigravity_min_tier: 'pro',
202
+ shared_pool_ceiling: 200000,
203
+ deprecated_after: LEGACY_MODEL_SUNSET_UTC,
204
+ multipliers: { low: 5.0, med: 8.5, medium: 8.5, high: 12.0 }
205
+ },
206
+ 'claude-opus-4-5': {
207
+ id: 'claude-opus-4-5',
208
+ aliases: ['claude-opus-4.5'],
209
+ family: 'opus',
210
+ label: 'Claude Opus 4.5',
211
+ supported_efforts: ['low', 'medium', 'high'],
212
+ caching_mode: 'explicit_and_implicit',
213
+ supports_explicit_cache: true,
214
+ antigravity_min_tier: 'pro',
215
+ shared_pool_ceiling: 200000,
216
+ deprecated_after: null,
217
+ multipliers: { low: 5.0, med: 8.5, medium: 8.5, high: 12.0 }
218
+ },
219
+ 'claude-haiku-4-5': {
220
+ id: 'claude-haiku-4-5',
221
+ aliases: ['claude-haiku-4.5'],
222
+ family: 'haiku',
223
+ label: 'Claude Haiku 4.5',
224
+ supported_efforts: ['low', 'medium', 'high'],
225
+ caching_mode: 'explicit_and_implicit',
226
+ supports_explicit_cache: true,
227
+ antigravity_min_tier: 'pro',
228
+ shared_pool_ceiling: 200000,
229
+ deprecated_after: null,
230
+ multipliers: { low: 1.2, med: 1.8, medium: 1.8, high: 2.5 }
231
+ },
232
+ 'gpt-oss-120b': {
233
+ id: 'gpt-oss-120b',
234
+ family: 'gpt-oss',
235
+ label: 'GPT-OSS 120B',
236
+ supported_efforts: ['low', 'medium', 'high'],
237
+ caching_mode: 'implicit_only',
238
+ supports_explicit_cache: false,
239
+ antigravity_min_tier: 'pro',
240
+ deprecated_after: LEGACY_MODEL_SUNSET_UTC,
241
+ multipliers: { low: 1.5, med: 2.5, medium: 2.5, high: 3.5 }
242
+ },
243
+ 'local-gemma4-26b': {
244
+ id: 'local-gemma4-26b',
245
+ family: 'local',
246
+ label: 'Local LiteRT Gemma 4 26B',
247
+ supported_efforts: ['low', 'medium', 'high'],
248
+ caching_mode: 'implicit_only',
249
+ supports_explicit_cache: false,
250
+ antigravity_min_tier: 'free',
251
+ deprecated_after: null,
252
+ multipliers: { low: 0.0, med: 0.0, medium: 0.0, high: 0.0 }
253
+ }
254
+ };
255
+
256
+ export const EXPECTED_OUTPUT_TOKENS_BY_EFFORT = Object.freeze({
257
+ low: 800,
258
+ med: 1500,
259
+ medium: 1500,
260
+ high: 3500,
261
+ max: 6000
262
+ });
263
+
264
+ const LOW_COMPLEXITY_PATTERNS = [
265
+ /\bfix\s+typo\b/i,
266
+ /\btypo\b/i,
267
+ /\brename\b/i,
268
+ /\bformat\b/i,
269
+ /\badd\s+docstring\b/i,
270
+ /\bdocstring\b/i,
271
+ /\bwrite\s+fixture\b/i,
272
+ /\btest\s+fixture\b/i,
273
+ /\bupdate\s+readme\b/i,
274
+ /\bupdate\s+comment\b/i,
275
+ /\bbump\s+version\b/i,
276
+ /\bfix\s+lint\b/i,
277
+ /\bsort\s+imports\b/i,
278
+ /\bexport\s+constant\b/i
279
+ ];
280
+
281
+ const HIGH_COMPLEXITY_PATTERNS = [
282
+ /\barchitect\b/i,
283
+ /\barchitecture\b/i,
284
+ /\brefactor\s+across\b/i,
285
+ /\bmulti[-\s]?file\b/i,
286
+ /\bdebug\s+race\s+condition\b/i,
287
+ /\brace\s+condition\b/i,
288
+ /\bstate\s+machine\b/i,
289
+ /\bdeadlock\b/i,
290
+ /\bconcurrency\b/i,
291
+ /\bsecurity\s+audit\b/i,
292
+ /\bschema\s+migration\b/i,
293
+ /\bcross[-\s]?module\b/i,
294
+ /\bdistributed\b/i,
295
+ /\bconsensus\b/i,
296
+ /\bredesign\b/i
297
+ ];
298
+
299
+ const MEDIUM_COMPLEXITY_PATTERNS = [
300
+ /\bimplement\b/i,
301
+ /\badd\s+unit\s+test\b/i,
302
+ /\bunit\s+test\b/i,
303
+ /\bvalidation\b/i,
304
+ /\bhandler\b/i,
305
+ /\bendpoint\b/i,
306
+ /\bcomponent\b/i,
307
+ /\bparser\b/i,
308
+ /\boptimize\b/i,
309
+ /\bfix\s+bug\b/i
310
+ ];
311
+
312
+ const AMBIGUOUS_PATTERNS = [
313
+ /\bsomething\s+is\s+wrong\b/i,
314
+ /\bnot\s+working\b/i,
315
+ /\bweird\s+bug\b/i,
316
+ /\bintermittent\b/i,
317
+ /\bflaky\b/i,
318
+ /\binvestigate\b/i,
319
+ /\bwhy\s+does\b/i
320
+ ];
321
+
322
+ export function normalizeModelId(rawModel = '') {
323
+ const lower = String(rawModel || '').toLowerCase().trim();
324
+ if (!lower) return 'gemini-4-argon';
325
+ if (Object.prototype.hasOwnProperty.call(ANTIGRAVITY_ENUM_ALIASES, lower)) {
326
+ return ANTIGRAVITY_ENUM_ALIASES[lower];
327
+ }
328
+ if (lower.includes('carbon-cyber-permissive')) return 'gemini-4-carbon-cyber-permissive';
329
+ if (lower.includes('carbon')) return 'gemini-4-carbon';
330
+ if (lower.includes('flash')) return 'gemini-3.8-flash';
331
+ if (lower.includes('argon')) return 'gemini-4-argon';
332
+ if (lower.includes('fable-5-2') || lower.includes('fable-5.2')) return 'claude-fable-5-2';
333
+ if (lower.includes('fable-5-1') || lower.includes('fable-5.1')) return 'claude-fable-5-1';
334
+ if (lower.includes('fable')) return 'claude-fable-5-2';
335
+ if (lower.includes('haiku-5-5') || lower.includes('haiku-5.5')) return 'claude-haiku-5-5';
336
+ if (lower.includes('haiku-4-5') || lower.includes('haiku-4.5')) return 'claude-haiku-4-5';
337
+ if (lower.includes('haiku')) return 'claude-haiku-5-5';
338
+ if (lower.includes('opus-5-5') || lower.includes('opus-5.5')) return 'claude-opus-5-5';
339
+ if (lower.includes('opus-4-6') || lower.includes('opus-4.6')) return 'claude-opus-4-6';
340
+ if (lower.includes('opus-4-5') || lower.includes('opus-4.5')) return 'claude-opus-4-5';
341
+ if (lower.includes('opus')) return 'claude-opus-5-5';
342
+ if (lower.includes('sonnet-5-5') || lower.includes('sonnet-5.5')) return 'claude-sonnet-5-5';
343
+ if (lower.includes('sonnet-4-6') || lower.includes('sonnet-4.6')) return 'claude-sonnet-4-6';
344
+ if (lower.includes('sonnet-4-5') || lower.includes('sonnet-4.5')) return 'claude-sonnet-4-5';
345
+ if (lower.includes('sonnet') || lower.includes('claude')) return 'claude-sonnet-5-5';
346
+ if (lower.includes('gpt-oss')) return 'gpt-oss-120b';
347
+ if (lower.includes('gemma') || lower.includes('local') || lower.includes('ollama')) return 'local-gemma4-26b';
348
+ if (lower.includes('pro')) return 'gemini-3.8-pro';
349
+ return MODEL_CATALOG[lower] ? lower : 'gemini-4-argon';
350
+ }
351
+
352
+ /**
353
+ * Filters MODEL_CATALOG to models that are not deprecated at `eventTimestampUtc`
354
+ * and satisfy the user's `userTier` (`antigravity_min_tier`).
355
+ */
356
+ export function getEligibleModelsForRouting({
357
+ eventTimestampUtc = null,
358
+ userTier = 'pro',
359
+ includeLocal = false
360
+ } = {}) {
361
+ const eligible = [];
362
+ for (const entry of Object.values(MODEL_CATALOG)) {
363
+ if (!includeLocal && entry.family === 'local') continue;
364
+ if (isModelDeprecated(entry.id, eventTimestampUtc)) continue;
365
+ if (!isPlanTierEligible(userTier, entry.antigravity_min_tier || 'free')) continue;
366
+ eligible.push(entry.id);
367
+ }
368
+ return [...new Set(eligible)];
369
+ }
370
+
371
+ export function normalizeEffortTier(rawEffort = '') {
372
+ const lower = String(rawEffort || '').toLowerCase().trim();
373
+ if (lower === 'low' || lower === 'min') return 'low';
374
+ if (lower === 'medium' || lower === 'med') return 'medium';
375
+ if (lower === 'high' || lower === 'max') return 'high';
376
+ return 'high';
377
+ }
378
+
379
+ export function getModelFamily(modelId = '') {
380
+ const norm = normalizeModelId(modelId);
381
+ return MODEL_CATALOG[norm]?.family || norm;
382
+ }
383
+
384
+ export function isSameModelFamily(modelA, modelB) {
385
+ return normalizeModelId(modelA) === normalizeModelId(modelB);
386
+ }
387
+
388
+ export function getQuotaMultiplier(modelId = 'gemini-4-argon', effort = 'high') {
389
+ const normModel = normalizeModelId(modelId);
390
+ const normEffort = normalizeEffortTier(effort);
391
+ const entry = MODEL_CATALOG[normModel] || MODEL_CATALOG['gemini-4-argon'];
392
+ return entry.multipliers[normEffort] ?? entry.multipliers.high;
393
+ }
394
+
395
+ export function formatModelDisplayLabel(modelId = 'gemini-4-argon') {
396
+ const normModel = normalizeModelId(modelId);
397
+ return MODEL_CATALOG[normModel]?.label || normModel;
398
+ }
399
+
400
+ /**
401
+ * Extracts active `[/]` checklist item and its depth/tags from `task.md` content.
402
+ */
403
+ export function extractActiveTaskStep(taskMdContent = '') {
404
+ const lines = String(taskMdContent || '').split(/\r?\n/);
405
+ for (let i = 0; i < lines.length; i++) {
406
+ const line = lines[i];
407
+ const match = line.match(/^(\s*)-\s*\[\/\]\s*(.+)$/);
408
+ if (match) {
409
+ const indentSpaces = match[1].length;
410
+ const rawText = match[2].trim();
411
+ const tagMatch = rawText.match(/\[([a-z0-9_.-]+):([a-z0-9_.-]+)\]/i);
412
+ let subItemCount = 0;
413
+ for (let j = i + 1; j < lines.length; j++) {
414
+ const nextLine = lines[j];
415
+ const nextIndent = (nextLine.match(/^(\s*)/) || ['', ''])[1].length;
416
+ if (nextLine.trim().startsWith('-') && nextIndent > indentSpaces) {
417
+ subItemCount++;
418
+ } else if (nextLine.trim().startsWith('-') && nextIndent <= indentSpaces) {
419
+ break;
420
+ } else if (nextLine.trim().startsWith('#')) {
421
+ break;
422
+ }
423
+ }
424
+ return {
425
+ found: true,
426
+ lineNumber: i + 1,
427
+ indentDepth: Math.floor(indentSpaces / 2),
428
+ subItemCount,
429
+ rawText,
430
+ directiveTag: tagMatch
431
+ ? {
432
+ raw: tagMatch[0],
433
+ modelTag: tagMatch[1].toLowerCase(),
434
+ effortTag: tagMatch[2].toLowerCase()
435
+ }
436
+ : null
437
+ };
438
+ }
439
+ }
440
+ return {
441
+ found: false,
442
+ lineNumber: null,
443
+ indentDepth: 0,
444
+ subItemCount: 0,
445
+ rawText: '',
446
+ directiveTag: null
447
+ };
448
+ }
449
+
450
+ /**
451
+ * Infers Agent Lifecycle Mode (`PLANNING` | `EXECUTION` | `VERIFICATION`)
452
+ */
453
+ export function inferLifecycleMode(options = {}) {
454
+ if (options.lifecycleMode) {
455
+ const upper = String(options.lifecycleMode).toUpperCase();
456
+ if (upper === 'PLANNING' || upper === 'EXECUTION' || upper === 'VERIFICATION') {
457
+ return upper;
458
+ }
459
+ }
460
+ const prompt = String(options.prompt || '');
461
+ if (/^\/plan\b/i.test(prompt) || /\bimplementation_plan\.md\b/i.test(prompt) || /\bdesign\s+architecture\b/i.test(prompt)) {
462
+ return 'PLANNING';
463
+ }
464
+ if (/\bwalkthrough\.md\b/i.test(prompt) || /\bverify_gate\b/i.test(prompt) || /\brun\s+(?:all\s+)?tests\b/i.test(prompt)) {
465
+ return 'VERIFICATION';
466
+ }
467
+ return 'EXECUTION';
468
+ }
469
+
470
+ /**
471
+ * Component 1 & 2: Zero-API-Call Pre-Invocation Task & Brain Classifier (<5ms)
472
+ * + "Floor is the Guarantee" Asymmetric Safety Rule & Loop Escalation
473
+ */
474
+ export function classifyTaskComplexity(promptOrOptions = {}, maybeOptions = {}) {
475
+ const startMs = performance.now();
476
+ const options = typeof promptOrOptions === 'string'
477
+ ? { ...(maybeOptions || {}), prompt: promptOrOptions }
478
+ : (promptOrOptions || {});
479
+ const prompt = String(options.prompt || '').trim();
480
+ const taskMdContent = String(options.taskMdContent || '');
481
+ const lifecycleMode = inferLifecycleMode(options);
482
+
483
+ const activeStep = extractActiveTaskStep(taskMdContent);
484
+ const combinedText = `${prompt} ${activeStep.rawText}`.trim();
485
+
486
+ // Count @file mentions
487
+ const fileMentions = prompt.match(/@[\w./\\-]+/g) || [];
488
+ const fileMentionCount = Math.max(fileMentions.length, Number(options.fileMentionCount || 0));
489
+ const astFileCount = Number(options.astFileCount ?? fileMentionCount);
490
+ const multiFileMutation = Boolean(options.multiFileMutation || astFileCount > 1 || fileMentionCount > 1);
491
+ const cyclomaticComplexity = Number(options.cyclomaticComplexity || 1);
492
+
493
+ // Live Retry / Oscillation Telemetry from Phase 1 (DET-01 / DET-02)
494
+ const det01Count = Number(options.det01Count ?? options.retryChurnCount ?? 0);
495
+ const det02Count = Number(options.det02Count ?? options.oscillationCount ?? 0);
496
+
497
+ const activeModel = normalizeModelId(options.activeModel || options.currentModel || options.modelId || 'gemini-4-argon');
498
+ const activeEffort = normalizeEffortTier(options.activeEffort || 'high');
499
+
500
+ const matchesLow = LOW_COMPLEXITY_PATTERNS.some((rx) => rx.test(combinedText));
501
+ const matchesHigh = HIGH_COMPLEXITY_PATTERNS.some((rx) => rx.test(combinedText));
502
+ const matchesMedium = MEDIUM_COMPLEXITY_PATTERNS.some((rx) => rx.test(combinedText));
503
+ const matchesAmbiguous = AMBIGUOUS_PATTERNS.some((rx) => rx.test(combinedText));
504
+
505
+ let complexityTier = 'MEDIUM';
506
+ let confidence = 0.80;
507
+
508
+ if (lifecycleMode === 'PLANNING' || matchesHigh || multiFileMutation || cyclomaticComplexity >= 15 || activeStep.subItemCount >= 4) {
509
+ complexityTier = 'HIGH';
510
+ confidence = matchesHigh || multiFileMutation || lifecycleMode === 'PLANNING' ? 0.92 : 0.86;
511
+ } else if (matchesLow && !matchesHigh && !matchesMedium && !matchesAmbiguous && !multiFileMutation && cyclomaticComplexity < 8) {
512
+ complexityTier = 'LOW';
513
+ confidence = prompt.length > 0 && prompt.length <= 160 && astFileCount <= 1 ? 0.91 : 0.86;
514
+ } else if (matchesAmbiguous) {
515
+ complexityTier = 'MEDIUM';
516
+ confidence = 0.68; // Ambiguous bug reports have <0.85 confidence -> Floor Guarantee promotes upward
517
+ } else {
518
+ complexityTier = 'MEDIUM';
519
+ confidence = matchesMedium ? 0.88 : 0.78;
520
+ }
521
+
522
+ // Allow explicit confidence override for deterministic boundary tests if provided
523
+ if (typeof options.confidenceOverride === 'number') {
524
+ confidence = options.confidenceOverride;
525
+ }
526
+
527
+ // "Floor is the Guarantee" Asymmetric Safety Rule:
528
+ // Recommend budget tier (Gemini 3.8 Flash — Low/Medium effort, 1.0x burn) ONLY when
529
+ // complexityTier === 'LOW' && confidence >= 0.85 && !multiFileMutation.
530
+ const explicitUserTier = options.userTier || options.planTier || options.antigravityTier || null;
531
+ const userTier = String(explicitUserTier || (activeModel.includes('carbon') ? 'ultra' : 'pro')).toLowerCase().trim();
532
+ const eventTimestampUtc = options.eventTimestampUtc ?? options.timestamp ?? null;
533
+ const canUseCarbon = isPlanTierEligible(userTier, 'ultra');
534
+ const isActiveCarbon = activeModel.includes('carbon') && canUseCarbon;
535
+ const frontierModel = ((options.preferCarbon || isActiveCarbon) && canUseCarbon)
536
+ ? (isActiveCarbon ? activeModel : 'gemini-4-carbon')
537
+ : 'gemini-4-argon';
538
+
539
+ let recommendedModel = frontierModel;
540
+ let recommendedEffort = 'medium';
541
+ let floorGuaranteeApplied = false;
542
+
543
+ if (complexityTier === 'LOW' && confidence >= FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD && !multiFileMutation) {
544
+ recommendedModel = 'gemini-3.8-flash';
545
+ recommendedEffort = 'low';
546
+ } else if (complexityTier === 'HIGH' || multiFileMutation) {
547
+ recommendedModel = frontierModel;
548
+ recommendedEffort = 'high';
549
+ if (complexityTier !== 'HIGH') {
550
+ floorGuaranteeApplied = true;
551
+ }
552
+ } else {
553
+ // Either MEDIUM complexity or LOW complexity with confidence < 0.85
554
+ if (complexityTier === 'LOW' && confidence < FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD) {
555
+ floorGuaranteeApplied = true;
556
+ }
557
+ recommendedModel = confidence < FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD ? frontierModel : frontierModel;
558
+ recommendedEffort = confidence < FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD ? 'high' : 'medium';
559
+ }
560
+
561
+ // Enforce tier eligibility & sunset filtering on recommendedModel
562
+ const recCatalogEntry = MODEL_CATALOG[recommendedModel];
563
+ if (recCatalogEntry && !isPlanTierEligible(userTier, recCatalogEntry.antigravity_min_tier || 'free')) {
564
+ recommendedModel = isPlanTierEligible(userTier, 'pro') ? 'gemini-4-argon' : 'gemini-3.8-flash';
565
+ }
566
+ if (isModelDeprecated(recommendedModel, eventTimestampUtc)) {
567
+ recommendedModel = canUseCarbon ? 'gemini-4-carbon' : 'gemini-4-argon';
568
+ }
569
+
570
+ const migrationNotice = getDeprecatedModelMigrationNotice(activeModel, eventTimestampUtc, userTier);
571
+
572
+ // Auto-Escalation on Loop Detection (DET-01 >= 2 consecutive failures or DET-02 oscillation >= 1)
573
+ let loopEscalated = false;
574
+ let escalationReason = null;
575
+ const hasLoopSignal = det01Count >= 2 || det02Count >= 1;
576
+
577
+ if (hasLoopSignal) {
578
+ const isFlashLow = activeModel === 'gemini-3.8-flash' && activeEffort === 'low';
579
+ const isArgonLow = activeModel === 'gemini-4-argon' && activeEffort === 'low';
580
+ const isCarbonLow = activeModel.includes('carbon') && activeEffort === 'low';
581
+ if (isFlashLow || isArgonLow || isCarbonLow || recommendedModel === 'gemini-3.8-flash') {
582
+ loopEscalated = true;
583
+ escalationReason = det01Count >= 2
584
+ ? `DET-01 retry churn (${det01Count} consecutive failures)`
585
+ : `DET-02 file-hash edit oscillation (${det02Count} flips)`;
586
+ recommendedModel = isActiveCarbon ? activeModel : 'gemini-4-argon';
587
+ recommendedEffort = (isArgonLow || isCarbonLow) && det01Count >= 3 ? 'high' : 'medium';
588
+ if (complexityTier === 'LOW') {
589
+ complexityTier = 'MEDIUM';
590
+ }
591
+ }
592
+ }
593
+
594
+ const estimatedBurnMultiplier = getQuotaMultiplier(recommendedModel, recommendedEffort);
595
+ const elapsedMs = Number((performance.now() - startMs).toFixed(3));
596
+
597
+ return {
598
+ complexityTier,
599
+ confidence: Number(confidence.toFixed(2)),
600
+ recommendedModel,
601
+ recommendedEffort,
602
+ estimatedBurnMultiplier,
603
+ lifecycleMode,
604
+ loopEscalated,
605
+ escalationReason,
606
+ floorGuaranteeApplied,
607
+ userTier,
608
+ migrationNotice,
609
+ signals: {
610
+ fileMentionCount,
611
+ astFileCount,
612
+ multiFileMutation,
613
+ cyclomaticComplexity,
614
+ det01Count,
615
+ det02Count,
616
+ activeStepFound: activeStep.found,
617
+ activeStepSubItems: activeStep.subItemCount,
618
+ activeStepDirective: activeStep.directiveTag
619
+ },
620
+ elapsedMs
621
+ };
622
+ }
623
+
624
+ /**
625
+ * Component 3: `CacheGravityScorer` & Cache-Adjusted Quota Cost Equation
626
+ *
627
+ * C_effective(m, e) = M(m, e) * [
628
+ * I_same_model(m) * (0.05 * T_cached) +
629
+ * (1 - I_same_model(m)) * T_cached +
630
+ * T_uncached_delta +
631
+ * E_output(e)
632
+ * ]
633
+ */
634
+ export function resolveReadDiscountFactor(modelId = 'gemini-4-argon', options = {}) {
635
+ if (typeof options.readDiscountFactor === 'number' && Number.isFinite(options.readDiscountFactor) && options.readDiscountFactor >= 0) {
636
+ return options.readDiscountFactor;
637
+ }
638
+ if (typeof options.discountPct === 'number' && Number.isFinite(options.discountPct)) {
639
+ return Math.max(0, (100 - options.discountPct) / 100);
640
+ }
641
+ if (typeof options.cacheDiscount === 'number' && Number.isFinite(options.cacheDiscount)) {
642
+ return options.cacheDiscount <= 1 ? Math.max(0, 1 - options.cacheDiscount) : Math.max(0, (100 - options.cacheDiscount) / 100);
643
+ }
644
+ const rates = resolveModelRates(modelId, options.eventTimestampUtc ?? null, 'standard', options);
645
+ if (rates && rates.input > 0 && rates.cachedRead >= 0) {
646
+ return Number((rates.cachedRead / rates.input).toFixed(6));
647
+ }
648
+ return 0.05;
649
+ }
650
+
651
+ /**
652
+ * Closed-form prefix break-even calculator ($C^*$) for both quota-weight parity pairs
653
+ * (`Argon -> Flash` = 3,529 @ 95%, 4,286 @ 90%; `Carbon -> Flash` = 3,529 @ 95%, 4,286 @ 90%)
654
+ * and Anthropic explicit-cache USD pairs (computed dynamically from catalog pricing rates).
655
+ */
656
+ export function computeClosedFormBreakEven({
657
+ currentModel = 'gemini-4-argon',
658
+ targetModel = 'gemini-3.8-flash',
659
+ targetEffort = 'low',
660
+ cachedTokens = 0,
661
+ ttlRemainingSeconds = 0,
662
+ cacheTtlSeconds = undefined,
663
+ expectedOutputTokens = DEFAULT_EXPECTED_OUTPUT_TOKENS,
664
+ uncachedDeltaTokens = 0,
665
+ cacheTtlTier = '5m',
666
+ readDiscountFactor = undefined,
667
+ discountPct = undefined,
668
+ cacheDiscount = undefined,
669
+ pricingMode = 'auto',
670
+ eventTimestampUtc = null
671
+ } = {}) {
672
+ const normCurrent = normalizeModelId(currentModel);
673
+ const normTarget = normalizeModelId(targetModel);
674
+ const normTargetEffort = normalizeEffortTier(targetEffort);
675
+ const tCached = Math.max(0, Number(cachedTokens || 0));
676
+ const ttlSec = Math.max(0, Number(ttlRemainingSeconds ?? cacheTtlSeconds ?? 0));
677
+ const tOut = expectedOutputTokens !== null && expectedOutputTokens !== undefined
678
+ ? Math.max(0, Number(expectedOutputTokens))
679
+ : DEFAULT_EXPECTED_OUTPUT_TOKENS;
680
+ const tUncachedDelta = Math.max(0, Number(uncachedDeltaTokens || 0));
681
+
682
+ const descCurr = resolveModelDescriptor(normCurrent);
683
+ const descTarget = resolveModelDescriptor(normTarget);
684
+ const useUsdExplicitMode =
685
+ pricingMode === 'usd' ||
686
+ (pricingMode !== 'quota' && Boolean(descCurr?.supports_explicit_cache && descTarget?.supports_explicit_cache));
687
+
688
+ const readFactor = resolveReadDiscountFactor(normCurrent, {
689
+ readDiscountFactor,
690
+ discountPct,
691
+ cacheDiscount,
692
+ eventTimestampUtc,
693
+ totalPromptTokens: tCached
694
+ });
695
+
696
+ if (useUsdExplicitMode) {
697
+ const ratesCurr = resolveModelRates(normCurrent, eventTimestampUtc, 'standard', { totalPromptTokens: tCached });
698
+ const ratesTarget = resolveModelRates(normTarget, eventTimestampUtc, 'standard', { totalPromptTokens: tCached });
699
+ const is1h = String(cacheTtlTier || '5m').toLowerCase() === '1h';
700
+ const pWriteCurr = is1h ? ratesCurr.write1h : ratesCurr.write5m;
701
+ const pWriteTarget = is1h ? ratesTarget.write1h : ratesTarget.write5m;
702
+ const pReadCurr = ratesCurr.cachedRead;
703
+ const pOutCurr = ratesCurr.output;
704
+ const pOutTarget = ratesTarget.output;
705
+
706
+ const denom = pWriteTarget - pReadCurr;
707
+ const num = (tOut * (pOutCurr - pOutTarget)) + (tUncachedDelta * (pWriteCurr - pWriteTarget));
708
+ const canHoldWarmPrefix = denom > 0 && pOutCurr > pOutTarget && num > 0;
709
+ const breakEvenTokens = canHoldWarmPrefix ? Math.round(num / denom) : Infinity;
710
+
711
+ const warmCostUsd = ((tCached * pReadCurr) + (tUncachedDelta * pWriteCurr) + (tOut * pOutCurr)) / 1_000_000;
712
+ const coldSwitchCostUsd = (((tCached + tUncachedDelta) * pWriteTarget) + (tOut * pOutTarget)) / 1_000_000;
713
+
714
+ return {
715
+ mode: 'usd',
716
+ currentModel: normCurrent,
717
+ targetModel: normTarget,
718
+ targetEffort: normTargetEffort,
719
+ cachedTokens: tCached,
720
+ ttlRemainingSeconds: ttlSec,
721
+ expectedOutputTokens: tOut,
722
+ uncachedDeltaTokens: tUncachedDelta,
723
+ cacheTtlTier: is1h ? '1h' : '5m',
724
+ readDiscountFactor: readFactor,
725
+ pWriteCurr,
726
+ pWriteTarget,
727
+ pReadCurr,
728
+ pOutCurr,
729
+ pOutTarget,
730
+ denominator: Number(denom.toFixed(6)),
731
+ canHoldWarmPrefix,
732
+ breakEvenTokens,
733
+ warmCostUsd: Number(warmCostUsd.toFixed(6)),
734
+ coldSwitchCostUsd: Number(coldSwitchCostUsd.toFixed(6)),
735
+ deltaCostUsd: Number((warmCostUsd - coldSwitchCostUsd).toFixed(6)),
736
+ shouldHoldWarmCache: Boolean(canHoldWarmPrefix && tCached > breakEvenTokens && ttlSec > 0 && !isSameModelFamily(normCurrent, normTarget))
737
+ };
738
+ }
739
+
740
+ const wCurr = getQuotaMultiplier(normCurrent, 'low');
741
+ const eLow = getQuotaMultiplier(normCurrent, 'low');
742
+ const wTarget = getQuotaMultiplier(normTarget, 'low');
743
+ const eTarget = getQuotaMultiplier(normTarget, normTargetEffort);
744
+
745
+ const denom = wTarget - (readFactor * wCurr);
746
+ const num = (tOut * (eLow - eTarget)) + (tUncachedDelta * (wCurr - wTarget));
747
+ const canHoldWarmPrefix = denom > 0 && eLow > eTarget && num > 0;
748
+ const breakEvenTokens = canHoldWarmPrefix ? Math.round(num / denom) : Infinity;
749
+
750
+ return {
751
+ mode: 'quota',
752
+ currentModel: normCurrent,
753
+ targetModel: normTarget,
754
+ targetEffort: normTargetEffort,
755
+ cachedTokens: tCached,
756
+ ttlRemainingSeconds: ttlSec,
757
+ expectedOutputTokens: tOut,
758
+ uncachedDeltaTokens: tUncachedDelta,
759
+ readDiscountFactor: readFactor,
760
+ wCurr,
761
+ eLow,
762
+ wTarget,
763
+ eTarget,
764
+ denominator: Number(denom.toFixed(6)),
765
+ canHoldWarmPrefix,
766
+ breakEvenTokens,
767
+ shouldHoldWarmCache: Boolean(canHoldWarmPrefix && tCached > breakEvenTokens && ttlSec > 0 && !isSameModelFamily(normCurrent, normTarget))
768
+ };
769
+ }
770
+
771
+ export function evaluateCacheGravity(params = {}) {
772
+ const scorer = new CacheGravityScorer(params);
773
+ return scorer.computeBreakEven(params);
774
+ }
775
+
776
+ export class CacheGravityScorer {
777
+ constructor(options = {}) {
778
+ this.explicitWarmCacheThreshold =
779
+ options.warmCacheThresholdTokens !== undefined && options.warmCacheThresholdTokens !== null
780
+ ? Number(options.warmCacheThresholdTokens)
781
+ : null;
782
+ this.warmCacheThresholdTokens = Number(
783
+ this.explicitWarmCacheThreshold ?? WARM_CACHE_GRAVITY_THRESHOLD_TOKENS
784
+ );
785
+ }
786
+
787
+ computeBreakEven(params = {}) {
788
+ return computeClosedFormBreakEven(params);
789
+ }
790
+
791
+ /**
792
+ * Computes exact Cache-Adjusted Effective Quota Cost for a single candidate (model, effort).
793
+ */
794
+ computeEffectiveCost({
795
+ candidateModel,
796
+ candidateEffort,
797
+ activeModel = 'gemini-4-argon',
798
+ cachedTokens = 0,
799
+ cacheTtlSeconds = 0,
800
+ uncachedDeltaTokens = 2000,
801
+ expectedOutputTokens = null
802
+ } = {}) {
803
+ const normCandidateModel = normalizeModelId(candidateModel);
804
+ const normCandidateEffort = normalizeEffortTier(candidateEffort);
805
+ const normActiveModel = normalizeModelId(activeModel);
806
+
807
+ const multiplier = getQuotaMultiplier(normCandidateModel, normCandidateEffort);
808
+ const isCacheWarm = Number(cacheTtlSeconds) > 0 && Number(cachedTokens) > 0;
809
+ const sameModelIndicator = isCacheWarm && isSameModelFamily(normCandidateModel, normActiveModel) ? 1 : 0;
810
+
811
+ const tCached = Math.max(0, Number(cachedTokens || 0));
812
+ const tUncachedDelta = Math.max(0, Number(uncachedDeltaTokens || 0));
813
+ const eOutput = expectedOutputTokens !== null && expectedOutputTokens !== undefined
814
+ ? Number(expectedOutputTokens)
815
+ : (EXPECTED_OUTPUT_TOKENS_BY_EFFORT[normCandidateEffort] || DEFAULT_EXPECTED_OUTPUT_TOKENS);
816
+
817
+ const readFactor = resolveReadDiscountFactor(normActiveModel, { totalPromptTokens: tCached });
818
+ const cachedTerm = sameModelIndicator * (readFactor * tCached);
819
+ const coldPrefillTerm = (1 - sameModelIndicator) * tCached;
820
+ const effectiveTokens = cachedTerm + coldPrefillTerm + tUncachedDelta + eOutput;
821
+ const effectiveQuotaCost = Number((multiplier * effectiveTokens).toFixed(2));
822
+
823
+ return {
824
+ model: normCandidateModel,
825
+ effort: normCandidateEffort,
826
+ multiplier,
827
+ sameModelIndicator,
828
+ isCacheWarm,
829
+ cachedTokens: tCached,
830
+ uncachedDeltaTokens: tUncachedDelta,
831
+ expectedOutputTokens: eOutput,
832
+ readDiscountFactor: readFactor,
833
+ cachedTerm: Number(cachedTerm.toFixed(2)),
834
+ coldPrefillTerm: Number(coldPrefillTerm.toFixed(2)),
835
+ effectiveTokens: Number(effectiveTokens.toFixed(2)),
836
+ effectiveQuotaCost
837
+ };
838
+ }
839
+
840
+ /**
841
+ * Evaluates candidate (model, effort) pairs and applies Rule A (Modulate Effort Within Same Model)
842
+ * and Rule B (Subagent / Local Offload for Routine Subtasks) when Cached History > breakEvenTokens and TTL > 0s.
843
+ */
844
+ evaluateCandidates(context = {}) {
845
+ const activeModel = normalizeModelId(context.activeModel || 'gemini-4-argon');
846
+ const activeEffort = normalizeEffortTier(context.activeEffort || 'high');
847
+ const cachedTokens = Math.max(0, Number(context.cachedTokens || 0));
848
+ const cacheTtlSeconds = Math.max(0, Number(context.cacheTtlSeconds ?? context.ttlRemainingSeconds ?? 0));
849
+ const uncachedDeltaTokens = Math.max(0, Number(context.uncachedDeltaTokens ?? 2000));
850
+ const complexityTier = String(context.complexityTier || 'LOW').toUpperCase();
851
+ const confidence = Number(context.confidence ?? 0.90);
852
+ const explicitUserTier = context.userTier || context.planTier || null;
853
+ const userTier = String(explicitUserTier || (activeModel.includes('carbon') ? 'ultra' : 'pro')).toLowerCase().trim();
854
+ const eventTimestampUtc = context.eventTimestampUtc ?? context.timestamp ?? null;
855
+ const activeModelDeprecated = isModelDeprecated(activeModel, eventTimestampUtc);
856
+ const migrationNotice = getDeprecatedModelMigrationNotice(activeModel, eventTimestampUtc, userTier);
857
+
858
+ const defaultDownshiftPeer = activeModel === 'claude-opus-5-5'
859
+ ? 'claude-sonnet-5-5'
860
+ : (activeModel === 'claude-opus-4-6'
861
+ ? 'claude-sonnet-4-6'
862
+ : (activeModel === 'claude-opus-4-5'
863
+ ? 'claude-sonnet-4-5'
864
+ : (activeModel.startsWith('claude-fable') ? 'claude-opus-5-5' : 'gemini-3.8-flash')));
865
+
866
+ const breakEven = this.computeBreakEven({
867
+ currentModel: activeModel,
868
+ targetModel: context.targetModel || defaultDownshiftPeer,
869
+ targetEffort: 'low',
870
+ cachedTokens,
871
+ ttlRemainingSeconds: cacheTtlSeconds,
872
+ expectedOutputTokens: context.expectedOutputTokens ?? DEFAULT_EXPECTED_OUTPUT_TOKENS,
873
+ eventTimestampUtc
874
+ });
875
+
876
+ const hasWarmCacheGravity =
877
+ !activeModelDeprecated &&
878
+ cacheTtlSeconds > 0 &&
879
+ (this.explicitWarmCacheThreshold !== null
880
+ ? cachedTokens >= this.explicitWarmCacheThreshold
881
+ : (breakEven.canHoldWarmPrefix && cachedTokens > breakEven.breakEvenTokens));
882
+
883
+ const candidatePairs = [
884
+ { model: activeModel, effort: 'low' },
885
+ { model: activeModel, effort: 'medium' },
886
+ { model: activeModel, effort: 'high' },
887
+ { model: 'gemini-3.8-flash', effort: 'low' },
888
+ { model: 'gemini-3.8-flash', effort: 'medium' },
889
+ { model: 'gemini-4-argon', effort: 'low' },
890
+ { model: 'gemini-4-argon', effort: 'medium' },
891
+ { model: 'gemini-4-argon', effort: 'high' },
892
+ { model: 'gemini-4-carbon', effort: 'low' },
893
+ { model: 'gemini-4-carbon', effort: 'medium' },
894
+ { model: 'gemini-4-carbon', effort: 'high' }
895
+ ];
896
+
897
+ const seen = new Set();
898
+ const scoredCandidates = [];
899
+ for (const pair of candidatePairs) {
900
+ const key = `${pair.model}:${pair.effort}`;
901
+ if (seen.has(key)) continue;
902
+ seen.add(key);
903
+ if (isModelDeprecated(pair.model, eventTimestampUtc)) continue;
904
+ const catEntry = MODEL_CATALOG[pair.model];
905
+ if (catEntry && !isPlanTierEligible(userTier, catEntry.antigravity_min_tier || 'free')) continue;
906
+ scoredCandidates.push(
907
+ this.computeEffectiveCost({
908
+ candidateModel: pair.model,
909
+ candidateEffort: pair.effort,
910
+ activeModel,
911
+ cachedTokens,
912
+ cacheTtlSeconds,
913
+ uncachedDeltaTokens
914
+ })
915
+ );
916
+ }
917
+
918
+ scoredCandidates.sort((a, b) => a.effectiveQuotaCost - b.effectiveQuotaCost);
919
+
920
+ const baselineCost = this.computeEffectiveCost({
921
+ candidateModel: activeModel,
922
+ candidateEffort: activeEffort,
923
+ activeModel,
924
+ cachedTokens,
925
+ cacheTtlSeconds,
926
+ uncachedDeltaTokens
927
+ });
928
+
929
+ const coldSwitchToFlashCost = this.computeEffectiveCost({
930
+ candidateModel: 'gemini-3.8-flash',
931
+ candidateEffort: 'low',
932
+ activeModel,
933
+ cachedTokens,
934
+ cacheTtlSeconds,
935
+ uncachedDeltaTokens
936
+ });
937
+
938
+ const sameModelLowCost = this.computeEffectiveCost({
939
+ candidateModel: activeModel,
940
+ candidateEffort: 'low',
941
+ activeModel,
942
+ cachedTokens,
943
+ cacheTtlSeconds,
944
+ uncachedDeltaTokens
945
+ });
946
+
947
+ const sameModelMediumCost = this.computeEffectiveCost({
948
+ candidateModel: activeModel,
949
+ candidateEffort: 'medium',
950
+ activeModel,
951
+ cachedTokens,
952
+ cacheTtlSeconds,
953
+ uncachedDeltaTokens
954
+ });
955
+
956
+ let primaryRecommendation = null;
957
+ let subagentOffloadOption = null;
958
+ let localOffloadOption = null;
959
+ let policyApplied = 'COLD_OR_LOW_CACHE_OPTIMAL';
960
+
961
+ if (hasWarmCacheGravity && activeModel !== 'gemini-3.8-flash') {
962
+ // Rule A: Modulate Effort Within the Same Model First to preserve 95% KV cache discount
963
+ const targetSameModelEffort = complexityTier === 'HIGH' ? 'high' : 'low';
964
+ const targetCostObj = targetSameModelEffort === 'low' ? sameModelLowCost : (
965
+ targetSameModelEffort === 'medium' ? sameModelMediumCost : baselineCost
966
+ );
967
+ const multiplierSavingsPct = baselineCost.multiplier > 0
968
+ ? Math.round(((baselineCost.multiplier - targetCostObj.multiplier) / baselineCost.multiplier) * 100)
969
+ : 0;
970
+ const effectiveSavingsPct = baselineCost.effectiveQuotaCost > 0
971
+ ? Math.round(((baselineCost.effectiveQuotaCost - targetCostObj.effectiveQuotaCost) / baselineCost.effectiveQuotaCost) * 100)
972
+ : 0;
973
+
974
+ primaryRecommendation = {
975
+ action: 'MODULATE_EFFORT_SAME_MODEL',
976
+ model: activeModel,
977
+ effort: targetSameModelEffort,
978
+ multiplier: targetCostObj.multiplier,
979
+ effectiveQuotaCost: targetCostObj.effectiveQuotaCost,
980
+ preservesWarmCache: true,
981
+ coldPrefillPenaltyAvoidedTokens: cachedTokens,
982
+ multiplierSavingsPct: Math.max(0, multiplierSavingsPct),
983
+ effectiveSavingsPct: Math.max(0, effectiveSavingsPct),
984
+ label: `Drop to ${formatModelDisplayLabel(activeModel)} • ${targetSameModelEffort.toUpperCase()} (Keep ${(cachedTokens / 1000).toFixed(1)}k Cache, Save ${Math.max(multiplierSavingsPct, effectiveSavingsPct)}%)`
985
+ };
986
+ policyApplied = 'RULE_A_MODULATE_SAME_MODEL_EFFORT';
987
+
988
+ // Rule B: Subagent / Local Offload for Routine Subtasks when LOW complexity & confidence >= 0.85
989
+ if (complexityTier === 'LOW' && confidence >= FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD) {
990
+ const subagentCleanCost = this.computeEffectiveCost({
991
+ candidateModel: 'gemini-3.8-flash',
992
+ candidateEffort: 'low',
993
+ activeModel: 'gemini-3.8-flash',
994
+ cachedTokens: 0,
995
+ cacheTtlSeconds: 0,
996
+ uncachedDeltaTokens: Math.min(uncachedDeltaTokens, 1800)
997
+ });
998
+ subagentOffloadOption = {
999
+ action: 'SPAWN_FLASH_SUBAGENT',
1000
+ model: 'gemini-3.8-flash',
1001
+ effort: 'low',
1002
+ multiplier: 1.0,
1003
+ contextBudgetTokens: 2000,
1004
+ effectiveQuotaCost: subagentCleanCost.effectiveQuotaCost,
1005
+ preservesMainSessionCache: true,
1006
+ label: '⚡ Offload to Flash-Low Subagent (<2k ctx)'
1007
+ };
1008
+ localOffloadOption = {
1009
+ action: 'OFFLOAD_LOCAL_LITERT',
1010
+ model: 'local-gemma4-26b',
1011
+ effort: 'low',
1012
+ multiplier: 0.0,
1013
+ effectiveQuotaCost: 0,
1014
+ preservesMainSessionCache: true,
1015
+ label: '⚡ Offload to Local LiteRT Gemma 4 26B (0.0x quota)'
1016
+ };
1017
+ policyApplied = 'RULE_A_AND_B_WARM_CACHE_WITH_SUBAGENT_OFFLOAD';
1018
+ }
1019
+ } else {
1020
+ // Cache is cold (TTL == 0) or below break-even: safe to switch model family directly if complexity allows
1021
+ const canUseCarbon = isPlanTierEligible(userTier, 'ultra');
1022
+ const isActiveCarbon = activeModel.includes('carbon') && canUseCarbon;
1023
+ const frontierTarget = ((context.preferCarbon || isActiveCarbon) && canUseCarbon)
1024
+ ? (isActiveCarbon ? activeModel : 'gemini-4-carbon')
1025
+ : (isPlanTierEligible(userTier, 'pro') ? 'gemini-4-argon' : 'gemini-3.8-flash');
1026
+ let targetModel = activeModel;
1027
+ let targetEffort = activeEffort;
1028
+
1029
+ if (complexityTier === 'LOW' && confidence >= FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD) {
1030
+ targetModel = 'gemini-3.8-flash';
1031
+ targetEffort = 'low';
1032
+ } else if (complexityTier === 'MEDIUM') {
1033
+ targetModel = cacheTtlSeconds === 0 && cachedTokens >= this.warmCacheThresholdTokens
1034
+ ? 'gemini-3.8-flash'
1035
+ : frontierTarget;
1036
+ targetEffort = 'medium';
1037
+ } else {
1038
+ targetModel = frontierTarget;
1039
+ targetEffort = 'high';
1040
+ }
1041
+
1042
+ if (isModelDeprecated(targetModel, eventTimestampUtc) || !isPlanTierEligible(userTier, MODEL_CATALOG[targetModel]?.antigravity_min_tier || 'free')) {
1043
+ targetModel = frontierTarget;
1044
+ }
1045
+
1046
+ const targetCostObj = this.computeEffectiveCost({
1047
+ candidateModel: targetModel,
1048
+ candidateEffort: targetEffort,
1049
+ activeModel,
1050
+ cachedTokens,
1051
+ cacheTtlSeconds,
1052
+ uncachedDeltaTokens
1053
+ });
1054
+
1055
+ primaryRecommendation = {
1056
+ action: targetModel !== activeModel ? 'SWITCH_MODEL_FAMILY' : 'MODULATE_EFFORT_SAME_MODEL',
1057
+ model: targetModel,
1058
+ effort: targetEffort,
1059
+ multiplier: targetCostObj.multiplier,
1060
+ effectiveQuotaCost: targetCostObj.effectiveQuotaCost,
1061
+ preservesWarmCache: isSameModelFamily(targetModel, activeModel) && cacheTtlSeconds > 0,
1062
+ coldPrefillPenaltyAvoidedTokens: 0,
1063
+ multiplierSavingsPct: baselineCost.multiplier > 0
1064
+ ? Math.max(0, Math.round(((baselineCost.multiplier - targetCostObj.multiplier) / baselineCost.multiplier) * 100))
1065
+ : 0,
1066
+ effectiveSavingsPct: baselineCost.effectiveQuotaCost > 0
1067
+ ? Math.max(0, Math.round(((baselineCost.effectiveQuotaCost - targetCostObj.effectiveQuotaCost) / baselineCost.effectiveQuotaCost) * 100))
1068
+ : 0,
1069
+ label: `Switch to ${formatModelDisplayLabel(targetModel)} • ${targetEffort.toUpperCase()} (${targetCostObj.multiplier}x)`
1070
+ };
1071
+ }
1072
+
1073
+ return {
1074
+ hasWarmCacheGravity,
1075
+ breakEvenTokens: breakEven.breakEvenTokens,
1076
+ breakEven,
1077
+ policyApplied,
1078
+ baseline: baselineCost,
1079
+ sameModelLowCost,
1080
+ coldSwitchToFlashCost,
1081
+ primaryRecommendation,
1082
+ subagentOffloadOption,
1083
+ localOffloadOption,
1084
+ scoredCandidates,
1085
+ migrationNotice
1086
+ };
1087
+ }
1088
+ }
1089
+
1090
+ /**
1091
+ * Component 4: `TaskMdDirectiveWatcher` — Brain-Driven Inline Routing Tags
1092
+ *
1093
+ * Parses and watches `~/.gemini/antigravity/brain/<GUID>/task.md` for inline `[model:effort]`
1094
+ * tags (`[argon:high]`, `[argon:medium]`, `[flash:low]`, `[local:gemma4]`) on checklist milestones.
1095
+ */
1096
+ export class TaskMdDirectiveWatcher {
1097
+ constructor(options = {}) {
1098
+ this.cacheGravityScorer = options.cacheGravityScorer || new CacheGravityScorer(options);
1099
+ this.actuator = options.actuator || null;
1100
+ this.watchers = new Map();
1101
+ this.lastParsedDirective = null;
1102
+ }
1103
+
1104
+ /**
1105
+ * Resolves a shorthand tag (`[argon:high]`, `[flash:low]`, `[local:gemma4]`) to canonical model & effort.
1106
+ */
1107
+ resolveTagToModelEffort(modelTag = '', effortTag = '') {
1108
+ const m = String(modelTag || '').toLowerCase();
1109
+ const e = String(effortTag || '').toLowerCase();
1110
+
1111
+ let model = 'gemini-4-argon';
1112
+ let effort = 'high';
1113
+
1114
+ if (m === 'local' || e.includes('gemma') || m.includes('gemma')) {
1115
+ model = 'local-gemma4-26b';
1116
+ effort = 'low';
1117
+ } else {
1118
+ model = normalizeModelId(m);
1119
+ effort = normalizeEffortTier(e);
1120
+ }
1121
+
1122
+ return {
1123
+ model,
1124
+ effort,
1125
+ multiplier: getQuotaMultiplier(model, effort),
1126
+ rawTag: `[${modelTag}:${effortTag}]`
1127
+ };
1128
+ }
1129
+
1130
+ /**
1131
+ * Parses `task.md` content in <2ms, extracts the active `[/]` step's `[model:effort]` directive,
1132
+ * and evaluates `CacheGravityScorer` to verify cache safety.
1133
+ */
1134
+ parseTaskMdDirectives(taskMdContent = '', sessionContext = {}) {
1135
+ const startMs = performance.now();
1136
+ const lines = String(taskMdContent || '').split(/\r?\n/);
1137
+ const allDirectives = [];
1138
+ let activeStep = null;
1139
+
1140
+ for (let i = 0; i < lines.length; i++) {
1141
+ const line = lines[i];
1142
+ const match = line.match(/^\s*-\s*\[([ xX/])\]\s*(.+)$/);
1143
+ if (!match) continue;
1144
+
1145
+ const statusChar = match[1];
1146
+ const text = match[2].trim();
1147
+ const tagMatch = text.match(/\[([a-z0-9_.-]+):([a-z0-9_.-]+)\]/i);
1148
+
1149
+ const resolved = tagMatch
1150
+ ? this.resolveTagToModelEffort(tagMatch[1], tagMatch[2])
1151
+ : null;
1152
+
1153
+ const item = {
1154
+ lineNumber: i + 1,
1155
+ status: statusChar === '/' ? 'IN_PROGRESS' : (statusChar.toLowerCase() === 'x' ? 'COMPLETED' : 'PENDING'),
1156
+ text,
1157
+ directive: resolved
1158
+ };
1159
+
1160
+ allDirectives.push(item);
1161
+ if (statusChar === '/' && !activeStep) {
1162
+ activeStep = item;
1163
+ }
1164
+ }
1165
+
1166
+ let gravityEvaluation = null;
1167
+ if (activeStep && activeStep.directive) {
1168
+ const target = activeStep.directive;
1169
+ const isLowRoutine = target.model === 'gemini-3.8-flash' || target.model === 'local-gemma4-26b';
1170
+ gravityEvaluation = this.cacheGravityScorer.evaluateCandidates({
1171
+ activeModel: sessionContext.activeModel || 'gemini-4-argon',
1172
+ activeEffort: sessionContext.activeEffort || 'high',
1173
+ cachedTokens: sessionContext.cachedTokens ?? 0,
1174
+ cacheTtlSeconds: sessionContext.cacheTtlSeconds ?? 0,
1175
+ uncachedDeltaTokens: sessionContext.uncachedDeltaTokens ?? 2000,
1176
+ complexityTier: isLowRoutine ? 'LOW' : (target.effort === 'high' ? 'HIGH' : 'MEDIUM'),
1177
+ confidence: 0.95
1178
+ });
1179
+ }
1180
+
1181
+ const elapsedMs = Number((performance.now() - startMs).toFixed(3));
1182
+ const result = {
1183
+ foundActiveStep: Boolean(activeStep),
1184
+ activeStep,
1185
+ allDirectives,
1186
+ gravityEvaluation,
1187
+ elapsedMs
1188
+ };
1189
+ this.lastParsedDirective = result;
1190
+ return result;
1191
+ }
1192
+
1193
+ /**
1194
+ * Annotates un-tagged checklist items in `task.md` during `PLANNING` mode with `[model:effort]` badges.
1195
+ */
1196
+ annotateTaskMdPlan(taskMdContent = '') {
1197
+ const lines = String(taskMdContent || '').split(/\r?\n/);
1198
+ const updated = lines.map((line) => {
1199
+ const match = line.match(/^(\s*-\s*\[[ xX/]\]\s*)(.+)$/);
1200
+ if (!match) return line;
1201
+ const prefix = match[1];
1202
+ const body = match[2];
1203
+ if (/\[[a-z0-9_.-]+:[a-z0-9_.-]+\]/i.test(body)) {
1204
+ return line; // Already tagged
1205
+ }
1206
+ const classification = classifyTaskComplexity({ prompt: body, lifecycleMode: 'EXECUTION' });
1207
+ let badge = '[argon:medium]';
1208
+ if (classification.complexityTier === 'HIGH') {
1209
+ badge = '[argon:high]';
1210
+ } else if (classification.complexityTier === 'LOW' && classification.confidence >= FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD) {
1211
+ badge = '[flash:low]';
1212
+ }
1213
+ return `${prefix}${badge} ${body}`;
1214
+ });
1215
+ return updated.join('\n');
1216
+ }
1217
+
1218
+ /**
1219
+ * Attaches a fast file watcher to `taskMdPath` and invokes `onTransition` whenever the active `[/]` step changes.
1220
+ */
1221
+ watchTaskMdFile(taskMdPath, sessionContextProvider = () => ({}), onTransition = null) {
1222
+ const resolvedPath = path.resolve(taskMdPath);
1223
+ this.unwatchTaskMdFile(resolvedPath);
1224
+
1225
+ const evaluateNow = () => {
1226
+ if (!fs.existsSync(resolvedPath)) return null;
1227
+ const content = fs.readFileSync(resolvedPath, 'utf8');
1228
+ const ctx = typeof sessionContextProvider === 'function' ? sessionContextProvider() : sessionContextProvider;
1229
+ const parsed = this.parseTaskMdDirectives(content, ctx);
1230
+ if (this.actuator && parsed.activeStep?.directive) {
1231
+ this.actuator.handleDirectiveTransition(parsed, ctx);
1232
+ }
1233
+ if (typeof onTransition === 'function') {
1234
+ onTransition(parsed);
1235
+ }
1236
+ return parsed;
1237
+ };
1238
+
1239
+ if (fs.existsSync(resolvedPath)) {
1240
+ const watcher = fs.watch(resolvedPath, { persistent: false }, () => {
1241
+ try { evaluateNow(); } catch {}
1242
+ });
1243
+ this.watchers.set(resolvedPath, watcher);
1244
+ }
1245
+
1246
+ return {
1247
+ path: resolvedPath,
1248
+ evaluateNow,
1249
+ close: () => this.unwatchTaskMdFile(resolvedPath)
1250
+ };
1251
+ }
1252
+
1253
+ unwatchTaskMdFile(taskMdPath) {
1254
+ const resolvedPath = path.resolve(taskMdPath);
1255
+ const existing = this.watchers.get(resolvedPath);
1256
+ if (existing) {
1257
+ try { existing.close(); } catch {}
1258
+ this.watchers.delete(resolvedPath);
1259
+ }
1260
+ }
1261
+ }
1262
+
1263
+ /**
1264
+ * Component 5: `ModelSelectorActuator` — Live CDP OOPIF & RPC Model/Effort Control
1265
+ *
1266
+ * Supports 3-way router mode toggle (`off` | `coach` | `autopilot`) and uses `AgBridgeService`
1267
+ * to read and actuate the active model/effort dropdown state in the Antigravity chat panel.
1268
+ */
1269
+ export class ModelSelectorActuator {
1270
+ constructor(options = {}) {
1271
+ this.agBridge = options.agBridge || new AgBridgeService(options);
1272
+ this.cacheGravityScorer = options.cacheGravityScorer || new CacheGravityScorer(options);
1273
+ this.mode = this.normalizeMode(options.mode || 'coach');
1274
+ this.activeModel = normalizeModelId(options.activeModel || 'gemini-4-argon');
1275
+ this.activeEffort = normalizeEffortTier(options.activeEffort || 'high');
1276
+ this.syncStatus = options.syncStatus || 'live synced';
1277
+ this.actuationHistory = [];
1278
+ }
1279
+
1280
+ normalizeMode(mode = 'coach') {
1281
+ const lower = String(mode || '').toLowerCase().trim();
1282
+ if (lower === 'off' || lower === 'disabled') return 'off';
1283
+ if (lower === 'autopilot' || lower === 'auto-pilot' || lower === 'auto') return 'autopilot';
1284
+ return 'coach';
1285
+ }
1286
+
1287
+ setMode(mode) {
1288
+ this.mode = this.normalizeMode(mode);
1289
+ return {
1290
+ ok: true,
1291
+ mode: this.mode
1292
+ };
1293
+ }
1294
+
1295
+ /**
1296
+ * Reads live model & effort state via RPC or CDP OOPIF bridge, upgrading status from
1297
+ * `(model inferred)` to `(live synced)`.
1298
+ */
1299
+ async readLiveModelState(sessionId = 'default_session') {
1300
+ if (this.agBridge?.rpcTransport && typeof this.agBridge.rpcTransport.getModelState === 'function') {
1301
+ try {
1302
+ const res = await this.agBridge.rpcTransport.getModelState(sessionId);
1303
+ if (res && res.model) {
1304
+ this.activeModel = normalizeModelId(res.model);
1305
+ this.activeEffort = normalizeEffortTier(res.effort || this.activeEffort);
1306
+ this.syncStatus = 'live synced';
1307
+ return {
1308
+ ok: true,
1309
+ model: this.activeModel,
1310
+ effort: this.activeEffort,
1311
+ multiplier: getQuotaMultiplier(this.activeModel, this.activeEffort),
1312
+ syncStatus: 'live synced',
1313
+ transportUsed: 'rpc'
1314
+ };
1315
+ }
1316
+ } catch {}
1317
+ }
1318
+
1319
+ if (this.agBridge?.cdpTransport && typeof this.agBridge.cdpTransport.getModelState === 'function') {
1320
+ try {
1321
+ const res = await this.agBridge.cdpTransport.getModelState(sessionId);
1322
+ if (res && res.model) {
1323
+ this.activeModel = normalizeModelId(res.model);
1324
+ this.activeEffort = normalizeEffortTier(res.effort || this.activeEffort);
1325
+ this.syncStatus = 'live synced';
1326
+ return {
1327
+ ok: true,
1328
+ model: this.activeModel,
1329
+ effort: this.activeEffort,
1330
+ multiplier: getQuotaMultiplier(this.activeModel, this.activeEffort),
1331
+ syncStatus: 'live synced',
1332
+ transportUsed: 'cdp'
1333
+ };
1334
+ }
1335
+ } catch {}
1336
+ }
1337
+
1338
+ return {
1339
+ ok: true,
1340
+ model: this.activeModel,
1341
+ effort: this.activeEffort,
1342
+ multiplier: getQuotaMultiplier(this.activeModel, this.activeEffort),
1343
+ syncStatus: this.syncStatus,
1344
+ transportUsed: 'cached_state'
1345
+ };
1346
+ }
1347
+
1348
+ /**
1349
+ * Evaluates and either recommends (Coach Mode) or actuates (Auto-Pilot Mode) model/effort changes
1350
+ * while enforcing CacheGravityScorer's warm-cache protection rule.
1351
+ */
1352
+ async evaluateAndActuate(request = {}) {
1353
+ const sessionId = String(request.sessionId || 'default_session');
1354
+ const currentModel = normalizeModelId(request.activeModel || this.activeModel);
1355
+ const currentEffort = normalizeEffortTier(request.activeEffort || this.activeEffort);
1356
+ const desiredModel = normalizeModelId(request.targetModel || currentModel);
1357
+ const desiredEffort = normalizeEffortTier(request.targetEffort || currentEffort);
1358
+ const cachedTokens = Math.max(0, Number(request.cachedTokens ?? 0));
1359
+ const cacheTtlSeconds = Math.max(0, Number(request.cacheTtlSeconds ?? 0));
1360
+ const isCleanBoundary = Boolean(request.isCleanBoundary || request.onHandoff);
1361
+ const directiveBadge = request.directiveBadge || `[${getModelFamily(desiredModel)}:${desiredEffort}]`;
1362
+
1363
+ const gravity = this.cacheGravityScorer.evaluateCandidates({
1364
+ activeModel: currentModel,
1365
+ activeEffort: currentEffort,
1366
+ cachedTokens,
1367
+ cacheTtlSeconds,
1368
+ uncachedDeltaTokens: request.uncachedDeltaTokens ?? 2000,
1369
+ complexityTier: desiredModel === 'gemini-3.8-flash' ? 'LOW' : (desiredEffort === 'high' ? 'HIGH' : 'MEDIUM'),
1370
+ confidence: 0.95
1371
+ });
1372
+
1373
+ // Determine cache-safe target for the main thread:
1374
+ // Never switch model family mid-session when Cached History >= 60k and TTL > 0s unless at a clean boundary.
1375
+ let safeMainThreadModel = desiredModel;
1376
+ let safeMainThreadEffort = desiredEffort;
1377
+ let preventedColdPrefill = false;
1378
+
1379
+ if (
1380
+ gravity.hasWarmCacheGravity &&
1381
+ !isCleanBoundary &&
1382
+ !isSameModelFamily(desiredModel, currentModel)
1383
+ ) {
1384
+ safeMainThreadModel = currentModel;
1385
+ safeMainThreadEffort = desiredEffort; // Modulate effort within same model family (e.g. Argon-High -> Argon-Low)
1386
+ preventedColdPrefill = true;
1387
+ }
1388
+
1389
+ const savingsPct = gravity.primaryRecommendation?.multiplierSavingsPct || 67;
1390
+ const coachPillText = preventedColdPrefill
1391
+ ? `💡 task.md step is ${directiveBadge} → [Switch to ${formatModelDisplayLabel(safeMainThreadModel)}-${safeMainThreadEffort.charAt(0).toUpperCase() + safeMainThreadEffort.slice(1)} (Save ${savingsPct}%)] or [Spawn Flash Subagent (1.0x)]`
1392
+ : `💡 task.md step is ${directiveBadge} → [Switch to ${formatModelDisplayLabel(safeMainThreadModel)} • ${safeMainThreadEffort.toUpperCase()} (${getQuotaMultiplier(safeMainThreadModel, safeMainThreadEffort)}x)]`;
1393
+
1394
+ if (this.mode === 'off') {
1395
+ return {
1396
+ ok: true,
1397
+ mode: 'off',
1398
+ actuated: false,
1399
+ preventedColdPrefill,
1400
+ activeModel: currentModel,
1401
+ activeEffort: currentEffort,
1402
+ recommendedModel: safeMainThreadModel,
1403
+ recommendedEffort: safeMainThreadEffort,
1404
+ coachPillText: null,
1405
+ gravity
1406
+ };
1407
+ }
1408
+
1409
+ if (this.mode === 'coach' && !request.forceActuate) {
1410
+ return {
1411
+ ok: true,
1412
+ mode: 'coach',
1413
+ actuated: false,
1414
+ preventedColdPrefill,
1415
+ activeModel: currentModel,
1416
+ activeEffort: currentEffort,
1417
+ recommendedModel: safeMainThreadModel,
1418
+ recommendedEffort: safeMainThreadEffort,
1419
+ subagentOffloadOption: gravity.subagentOffloadOption,
1420
+ coachPillText,
1421
+ gravity
1422
+ };
1423
+ }
1424
+
1425
+ // Auto-Pilot Mode (or explicit 1-click forceActuate in Coach Mode)
1426
+ let transportUsed = 'state_sync';
1427
+ const commandPayload = {
1428
+ type: 'SET_MODEL_AND_EFFORT',
1429
+ model: safeMainThreadModel,
1430
+ effort: safeMainThreadEffort,
1431
+ preserveWarmCache: preventedColdPrefill
1432
+ };
1433
+
1434
+ if (this.agBridge) {
1435
+ const dispatchRes = await this.agBridge.sendChatCommand(sessionId, commandPayload, request);
1436
+ transportUsed = dispatchRes?.transportUsed || 'rpc';
1437
+ if (
1438
+ dispatchRes &&
1439
+ (dispatchRes.ok === false || dispatchRes.allowed === false || dispatchRes.transportUsed === 'blocked_cdp')
1440
+ ) {
1441
+ const blockedReason = dispatchRes.cdpBlockedReason || dispatchRes.reason || 'EXPERIMENTAL_CDP_DISABLED';
1442
+ this.syncStatus = 'blocked_cdp';
1443
+ const blockedRecord = {
1444
+ ok: false,
1445
+ mode: this.mode,
1446
+ actuated: false,
1447
+ method: 'blocked_cdp',
1448
+ transportUsed: 'blocked_cdp',
1449
+ reason: blockedReason,
1450
+ cdpBlockedReason: blockedReason,
1451
+ preventedColdPrefill,
1452
+ previousModel: currentModel,
1453
+ previousEffort: currentEffort,
1454
+ activeModel: currentModel,
1455
+ activeEffort: currentEffort,
1456
+ recommendedModel: safeMainThreadModel,
1457
+ recommendedEffort: safeMainThreadEffort,
1458
+ activeMultiplier: getQuotaMultiplier(currentModel, currentEffort),
1459
+ syncStatus: this.syncStatus,
1460
+ coachPillText,
1461
+ gravity
1462
+ };
1463
+ this.actuationHistory.push(blockedRecord);
1464
+ return blockedRecord;
1465
+ }
1466
+ }
1467
+
1468
+ this.activeModel = safeMainThreadModel;
1469
+ this.activeEffort = safeMainThreadEffort;
1470
+ this.syncStatus = 'live synced';
1471
+
1472
+ const record = {
1473
+ ok: true,
1474
+ mode: this.mode,
1475
+ actuated: true,
1476
+ method: transportUsed,
1477
+ preventedColdPrefill,
1478
+ previousModel: currentModel,
1479
+ previousEffort: currentEffort,
1480
+ activeModel: this.activeModel,
1481
+ activeEffort: this.activeEffort,
1482
+ activeMultiplier: getQuotaMultiplier(this.activeModel, this.activeEffort),
1483
+ syncStatus: this.syncStatus,
1484
+ transportUsed,
1485
+ coachPillText,
1486
+ gravity
1487
+ };
1488
+
1489
+ this.actuationHistory.push(record);
1490
+ return record;
1491
+ }
1492
+
1493
+ /**
1494
+ * Invoked by TaskMdDirectiveWatcher when an active `[/]` step with `[model:effort]` is parsed.
1495
+ */
1496
+ async handleDirectiveTransition(parsedDirectiveResult, sessionContext = {}) {
1497
+ const directive = parsedDirectiveResult?.activeStep?.directive;
1498
+ if (!directive) return null;
1499
+ return this.evaluateAndActuate({
1500
+ sessionId: sessionContext.sessionId || 'default_session',
1501
+ activeModel: sessionContext.activeModel || this.activeModel,
1502
+ activeEffort: sessionContext.activeEffort || this.activeEffort,
1503
+ targetModel: directive.model,
1504
+ targetEffort: directive.effort,
1505
+ directiveBadge: directive.rawTag,
1506
+ cachedTokens: sessionContext.cachedTokens ?? 0,
1507
+ cacheTtlSeconds: sessionContext.cacheTtlSeconds ?? 0,
1508
+ isCleanBoundary: sessionContext.isCleanBoundary ?? false
1509
+ });
1510
+ }
1511
+
1512
+ /**
1513
+ * Spawns a clean `<2k` context Flash-Low subagent session for Rule B offload via `AgBridgeService`.
1514
+ */
1515
+ async spawnFlashSubagentOffload(subtaskState = {}) {
1516
+ return this.agBridge.spawnCleanSession({
1517
+ ...subtaskState,
1518
+ recommendedModel: 'gemini-3.8-flash',
1519
+ recommendedEffort: 'low',
1520
+ contextBudgetTokens: 2000
1521
+ });
1522
+ }
1523
+ }
1524
+
1525
+ /**
1526
+ * Unified Phase 5 Facade combining Task Classifier, CacheGravityScorer,
1527
+ * TaskMdDirectiveWatcher, and ModelSelectorActuator for PreInvocation & UI HUD.
1528
+ */
1529
+ export function evaluateTaskAndQuotaRoute(options = {}) {
1530
+ const scorer = options.cacheGravityScorer || new CacheGravityScorer(options);
1531
+ const actuator = options.actuator || new ModelSelectorActuator({
1532
+ agBridge: options.agBridge,
1533
+ cacheGravityScorer: scorer,
1534
+ mode: options.routerMode || 'coach',
1535
+ activeModel: options.activeModel || 'gemini-4-argon',
1536
+ activeEffort: options.activeEffort || 'high'
1537
+ });
1538
+ const watcher = options.directiveWatcher || new TaskMdDirectiveWatcher({
1539
+ cacheGravityScorer: scorer,
1540
+ actuator
1541
+ });
1542
+
1543
+ const classification = classifyTaskComplexity(options);
1544
+ const directiveState = options.taskMdContent
1545
+ ? watcher.parseTaskMdDirectives(options.taskMdContent, options)
1546
+ : { foundActiveStep: false, activeStep: null, allDirectives: [], elapsedMs: 0 };
1547
+
1548
+ // If task.md has an explicit [model:effort] directive on the active [/] item and no loop escalation occurred,
1549
+ // merge its target into the gravity evaluation.
1550
+ const targetModel = (!classification.loopEscalated && directiveState.activeStep?.directive?.model)
1551
+ ? directiveState.activeStep.directive.model
1552
+ : classification.recommendedModel;
1553
+ const targetEffort = (!classification.loopEscalated && directiveState.activeStep?.directive?.effort)
1554
+ ? directiveState.activeStep.directive.effort
1555
+ : classification.recommendedEffort;
1556
+
1557
+ const gravity = scorer.evaluateCandidates({
1558
+ activeModel: options.activeModel || 'gemini-4-argon',
1559
+ activeEffort: options.activeEffort || 'high',
1560
+ cachedTokens: options.cachedTokens ?? 0,
1561
+ cacheTtlSeconds: options.cacheTtlSeconds ?? 0,
1562
+ uncachedDeltaTokens: options.uncachedDeltaTokens ?? 2000,
1563
+ complexityTier: classification.complexityTier,
1564
+ confidence: classification.confidence
1565
+ });
1566
+
1567
+ const activeModelNorm = normalizeModelId(options.activeModel || 'gemini-4-argon');
1568
+ const activeEffortNorm = normalizeEffortTier(options.activeEffort || 'high');
1569
+ const activeBurnMultiplier = getQuotaMultiplier(activeModelNorm, activeEffortNorm);
1570
+
1571
+ const directiveBadge = directiveState.activeStep?.directive?.rawTag ||
1572
+ `[${getModelFamily(targetModel)}:${targetEffort}]`;
1573
+
1574
+ const coachPillText = gravity.hasWarmCacheGravity && !isSameModelFamily(targetModel, activeModelNorm)
1575
+ ? `💡 Next task.md step is ${directiveBadge} → [Drop to ${formatModelDisplayLabel(activeModelNorm)}-${gravity.primaryRecommendation.effort.charAt(0).toUpperCase() + gravity.primaryRecommendation.effort.slice(1)} (Keep ${(Number(options.cachedTokens || 0) / 1000).toFixed(1)}k Cache)] | [Run in Flash Subagent]`
1576
+ : `💡 Recommended: ${formatModelDisplayLabel(gravity.primaryRecommendation.model)} • ${gravity.primaryRecommendation.effort.toUpperCase()} (${gravity.primaryRecommendation.multiplier}x burn)`;
1577
+
1578
+ return {
1579
+ activeModel: activeModelNorm,
1580
+ activeModelLabel: formatModelDisplayLabel(activeModelNorm),
1581
+ activeEffort: activeEffortNorm,
1582
+ activeBurnMultiplier,
1583
+ syncStatus: actuator.syncStatus || 'live synced',
1584
+ routerMode: actuator.mode,
1585
+ classification,
1586
+ directiveState,
1587
+ gravity,
1588
+ coachPillText
1589
+ };
1590
+ }
1591
+
1592
+ /**
1593
+ * Actuates a routing recommendation when `flightMode === 'AUTO_PILOT'` (or `forceActuate === true`),
1594
+ * respecting `AgBridgeService` CDP safety gates (`EXPERIMENTAL_CDP_DISABLED` -> `actuated: false`).
1595
+ */
1596
+ export async function actuateRoutingRecommendation(routeOrInput = {}, options = {}) {
1597
+ const actuator = options.actuator || new ModelSelectorActuator({
1598
+ agBridge: options.agBridge,
1599
+ cacheGravityScorer: options.cacheGravityScorer,
1600
+ mode: options.mode || (String(options.flightMode || '').toUpperCase() === 'AUTO_PILOT' ? 'autopilot' : 'coach'),
1601
+ activeModel: routeOrInput.activeModel || options.activeModel || 'gemini-4-argon',
1602
+ activeEffort: routeOrInput.activeEffort || options.activeEffort || 'high'
1603
+ });
1604
+
1605
+ const targetModel = routeOrInput.targetModel ||
1606
+ routeOrInput.gravity?.primaryRecommendation?.model ||
1607
+ routeOrInput.classification?.recommendedModel ||
1608
+ actuator.activeModel;
1609
+ const targetEffort = routeOrInput.targetEffort ||
1610
+ routeOrInput.gravity?.primaryRecommendation?.effort ||
1611
+ routeOrInput.classification?.recommendedEffort ||
1612
+ actuator.activeEffort;
1613
+
1614
+ // No-op when already on the exact recommended model + effort
1615
+ if (
1616
+ normalizeModelId(targetModel) === normalizeModelId(routeOrInput.activeModel || actuator.activeModel) &&
1617
+ normalizeEffortTier(targetEffort) === normalizeEffortTier(routeOrInput.activeEffort || actuator.activeEffort) &&
1618
+ !options.forceActuate
1619
+ ) {
1620
+ return {
1621
+ ok: true,
1622
+ mode: actuator.mode,
1623
+ actuated: false,
1624
+ method: 'noop_already_synced',
1625
+ reason: 'ALREADY_ON_RECOMMENDED_MODEL_EFFORT',
1626
+ activeModel: actuator.activeModel,
1627
+ activeEffort: actuator.activeEffort
1628
+ };
1629
+ }
1630
+
1631
+ return actuator.evaluateAndActuate({
1632
+ sessionId: options.sessionId || routeOrInput.sessionId || 'default_session',
1633
+ activeModel: routeOrInput.activeModel || actuator.activeModel,
1634
+ activeEffort: routeOrInput.activeEffort || actuator.activeEffort,
1635
+ targetModel,
1636
+ targetEffort,
1637
+ cachedTokens: routeOrInput.cachedTokens ?? options.cachedTokens ?? 0,
1638
+ cacheTtlSeconds: routeOrInput.cacheTtlSeconds ?? options.cacheTtlSeconds ?? 0,
1639
+ isCleanBoundary: options.isCleanBoundary ?? true,
1640
+ forceActuate: Boolean(options.forceActuate),
1641
+ enableExperimentalCdpActuation: options.enableExperimentalCdpActuation,
1642
+ settings: options.settings
1643
+ });
1644
+ }
1645
+
1646
+ export default {
1647
+ MODEL_CATALOG,
1648
+ WARM_CACHE_GRAVITY_THRESHOLD_TOKENS,
1649
+ FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD,
1650
+ classifyTaskComplexity,
1651
+ CacheGravityScorer,
1652
+ TaskMdDirectiveWatcher,
1653
+ ModelSelectorActuator,
1654
+ evaluateTaskAndQuotaRoute,
1655
+ actuateRoutingRecommendation
1656
+ };