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,955 @@
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
+ MODEL_CATALOG,
7
+ WARM_CACHE_GRAVITY_THRESHOLD_TOKENS,
8
+ FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD,
9
+ DEFAULT_EXPECTED_OUTPUT_TOKENS,
10
+ EXPECTED_OUTPUT_TOKENS_BY_EFFORT,
11
+ normalizeModelId,
12
+ getModelFamily,
13
+ isSameModelFamily,
14
+ formatModelDisplayLabel,
15
+ extractActiveTaskStep,
16
+ inferLifecycleMode,
17
+ classifyTaskComplexity,
18
+ resolveReadDiscountFactor,
19
+ computeClosedFormBreakEven,
20
+ TaskMdDirectiveWatcher,
21
+ ModelSelectorActuator,
22
+ evaluateTaskAndQuotaRoute
23
+ } from '../task_quota_router.mjs';
24
+
25
+ /**
26
+ * Phase 2: Pre-Invocation Quota Router, Cache Gravity & Turn-Boundary Queue
27
+ * (`src/core/coach/task_quota_router.mjs`)
28
+ *
29
+ * Enforces:
30
+ * - Invariant 2 (Hard Turn-Boundary Actuation): Queue `AUTO_PILOT` actuations in
31
+ * `TurnBoundaryActuationQueue` and dispatch ONLY when Language Server state is
32
+ * `IDLE`, `WAITING_FOR_USER`, or `WAITING_FOR_APPROVAL`.
33
+ * - Invariant 3 (Sticky Escalation / Hysteresis Lock): Lock elevated model/effort
34
+ * triggered by `DET-01` or `DET-02` until the active `task.md` step transitions
35
+ * from `[/]` to `[x]` OR `TRAJECTORY_REWIND` fires.
36
+ * - Invariant 4 (Zero-Token Determinism): <2ms local execution.
37
+ */
38
+
39
+ export const COACH_MODES = Object.freeze({
40
+ OFF: 'OFF',
41
+ COACH: 'COACH',
42
+ AUTO_PILOT: 'AUTO_PILOT'
43
+ });
44
+
45
+ export const SAFE_TURN_BOUNDARY_STATES = Object.freeze(new Set([
46
+ 'IDLE',
47
+ 'WAITING_FOR_USER',
48
+ 'WAITING_FOR_APPROVAL'
49
+ ]));
50
+
51
+ export const COST_MULTIPLIER_MATRIX = Object.freeze({
52
+ 'gemini-3.8-flash': Object.freeze({ low: 1.0, med: 1.5, medium: 1.5, high: 2.2 }),
53
+ 'gemini-4-argon': Object.freeze({ low: 3.0, med: 5.5, medium: 5.5, high: 9.25 }),
54
+ 'gemini-4-carbon': Object.freeze({ low: 3.2, med: 6.0, medium: 6.0, high: 10.0 }),
55
+ 'gemini-4-carbon-cyber-permissive': Object.freeze({ low: 3.2, med: 6.0, medium: 6.0, high: 10.0 }),
56
+ 'claude-haiku-5-5': Object.freeze({ low: 0.5, med: 0.8, medium: 0.8, high: 1.2 }),
57
+ 'claude-haiku-5.5': Object.freeze({ low: 0.5, med: 0.8, medium: 0.8, high: 1.2 }),
58
+ 'claude-sonnet-5-5': Object.freeze({ low: 3.0, med: 4.5, medium: 4.5, high: 7.0 }),
59
+ 'claude-sonnet-5.5': Object.freeze({ low: 3.0, med: 4.5, medium: 4.5, high: 7.0 }),
60
+ 'claude-opus-5-5': Object.freeze({ low: 6.0, med: 9.0, medium: 9.0, high: 14.0 }),
61
+ 'claude-opus-5.5': Object.freeze({ low: 6.0, med: 9.0, medium: 9.0, high: 14.0 }),
62
+ 'claude-fable-5-2': Object.freeze({ low: 10.0, med: 15.0, medium: 15.0, high: 22.0 }),
63
+ 'claude-fable-5.2': Object.freeze({ low: 10.0, med: 15.0, medium: 15.0, high: 22.0 }),
64
+ 'claude-fable-5-1': Object.freeze({ low: 12.0, med: 18.0, medium: 18.0, high: 26.0 }),
65
+ 'claude-fable-5.1': Object.freeze({ low: 12.0, med: 18.0, medium: 18.0, high: 26.0 }),
66
+ 'claude-sonnet-4-6': Object.freeze({ low: 3.5, med: 5.0, medium: 5.0, high: 7.5 }),
67
+ 'claude-sonnet-4.6': Object.freeze({ low: 3.5, med: 5.0, medium: 5.0, high: 7.5 }),
68
+ 'claude-sonnet-4-5': Object.freeze({ low: 3.5, med: 5.0, medium: 5.0, high: 7.5 }),
69
+ 'claude-sonnet-4.5': Object.freeze({ low: 3.5, med: 5.0, medium: 5.0, high: 7.5 }),
70
+ 'claude-opus-4-6': Object.freeze({ low: 5.0, med: 8.5, medium: 8.5, high: 12.0 }),
71
+ 'claude-opus-4.6': Object.freeze({ low: 5.0, med: 8.5, medium: 8.5, high: 12.0 }),
72
+ 'claude-opus-4-5': Object.freeze({ low: 5.0, med: 8.5, medium: 8.5, high: 12.0 }),
73
+ 'claude-opus-4.5': Object.freeze({ low: 5.0, med: 8.5, medium: 8.5, high: 12.0 }),
74
+ 'claude-haiku-4-5': Object.freeze({ low: 1.2, med: 1.8, medium: 1.8, high: 2.5 }),
75
+ 'claude-haiku-4.5': Object.freeze({ low: 1.2, med: 1.8, medium: 1.8, high: 2.5 }),
76
+ 'gpt-oss-120b': Object.freeze({ low: 1.5, med: 2.5, medium: 2.5, high: 3.5 }),
77
+ 'local-gemma4-26b': Object.freeze({ low: 0.0, med: 0.0, medium: 0.0, high: 0.0 })
78
+ });
79
+
80
+ export function normalizeCoachMode(rawMode = 'COACH') {
81
+ const upper = String(rawMode || 'COACH').toUpperCase().trim().replace(/[-\s]+/g, '_');
82
+ if (upper === 'OFF' || upper === 'DISABLED') return COACH_MODES.OFF;
83
+ if (upper === 'AUTO_PILOT' || upper === 'AUTOPILOT' || upper === 'AUTO') return COACH_MODES.AUTO_PILOT;
84
+ return COACH_MODES.COACH;
85
+ }
86
+
87
+ export function normalizeEffortKey(rawEffort = 'high') {
88
+ const lower = String(rawEffort || 'high').toLowerCase().trim();
89
+ if (lower === 'low' || lower === 'min') return 'low';
90
+ if (lower === 'med' || lower === 'medium') return 'med';
91
+ return 'high';
92
+ }
93
+
94
+ export function getCostMultiplier(modelId = 'gemini-4-argon', effort = 'high') {
95
+ const normModel = normalizeModelId(modelId);
96
+ const effortKey = normalizeEffortKey(effort);
97
+ const row = COST_MULTIPLIER_MATRIX[normModel] || COST_MULTIPLIER_MATRIX['gemini-4-argon'];
98
+ return row[effortKey] ?? row.high;
99
+ }
100
+
101
+ export function getModelBaseWeight(modelId = 'gemini-4-argon') {
102
+ const normModel = normalizeModelId(modelId);
103
+ const row = COST_MULTIPLIER_MATRIX[normModel] || COST_MULTIPLIER_MATRIX['gemini-4-argon'];
104
+ return row.low;
105
+ }
106
+
107
+ export function formatShortFamilyLabel(modelId = 'gemini-4-argon') {
108
+ const family = getModelFamily(modelId);
109
+ if (family === 'flash') return 'Flash';
110
+ if (family === 'argon') return 'Argon';
111
+ if (family === 'sonnet') return 'Sonnet';
112
+ return family.charAt(0).toUpperCase() + family.slice(1);
113
+ }
114
+
115
+ export function formatTtlMinutesSeconds(ttlSeconds = 0) {
116
+ const sec = Math.max(0, Math.floor(Number(ttlSeconds) || 0));
117
+ const m = Math.floor(sec / 60);
118
+ const s = sec % 60;
119
+ return `${m}m ${s}s`;
120
+ }
121
+
122
+ /**
123
+ * Phase 2.2: `CacheGravityScorer`
124
+ *
125
+ * Computes the exact break-even token delta between keeping the current model family warm
126
+ * at `low` effort versus switching to a different model family and paying a 100% cold prefill:
127
+ *
128
+ * \Delta_{cost} = (T_{cached} * 0.05 * W_{M_{curr}} + T_{out} * E_{low})
129
+ * - (T_{cached} * 1.00 * W_{M_{target}} + T_{out} * E_{target})
130
+ *
131
+ * Enforces the Cache-Gravity Invariant when `cachedTokens >= 60000` and `ttlRemainingSeconds > 0`.
132
+ */
133
+ export class CacheGravityScorer {
134
+ constructor(options = {}) {
135
+ this.explicitWarmCacheThreshold =
136
+ options.warmCacheThresholdTokens !== undefined && options.warmCacheThresholdTokens !== null
137
+ ? Number(options.warmCacheThresholdTokens)
138
+ : null;
139
+ this.warmCacheThresholdTokens = Number(
140
+ this.explicitWarmCacheThreshold ?? WARM_CACHE_GRAVITY_THRESHOLD_TOKENS
141
+ );
142
+ }
143
+
144
+ computeBreakEven(params = {}) {
145
+ return this.computeBreakEvenDelta(params);
146
+ }
147
+
148
+ /**
149
+ * Computes exact closed-form break-even ($C^*$), break-even delta (\Delta_{cost}), and UI tooltip payload.
150
+ */
151
+ computeBreakEvenDelta({
152
+ currentModel = 'gemini-4-argon',
153
+ targetModel = 'gemini-3.8-flash',
154
+ targetEffort = 'low',
155
+ cachedTokens = 0,
156
+ ttlRemainingSeconds = 0,
157
+ cacheTtlSeconds = undefined,
158
+ expectedOutputTokens = DEFAULT_EXPECTED_OUTPUT_TOKENS,
159
+ uncachedDeltaTokens = 0,
160
+ cacheTtlTier = '5m',
161
+ readDiscountFactor = undefined,
162
+ discountPct = undefined,
163
+ cacheDiscount = undefined,
164
+ pricingMode = 'auto',
165
+ eventTimestampUtc = null
166
+ } = {}) {
167
+ const normCurrent = normalizeModelId(currentModel);
168
+ const normTarget = normalizeModelId(targetModel);
169
+ const normTargetEffort = normalizeEffortKey(targetEffort);
170
+ const tCached = Math.max(0, Number(cachedTokens || 0));
171
+ const ttlSec = Math.max(0, Number(ttlRemainingSeconds ?? cacheTtlSeconds ?? 0));
172
+ const tOut = expectedOutputTokens !== null && expectedOutputTokens !== undefined
173
+ ? Math.max(0, Number(expectedOutputTokens))
174
+ : DEFAULT_EXPECTED_OUTPUT_TOKENS;
175
+
176
+ const closedForm = computeClosedFormBreakEven({
177
+ currentModel: normCurrent,
178
+ targetModel: normTarget,
179
+ targetEffort: normTargetEffort,
180
+ cachedTokens: tCached,
181
+ ttlRemainingSeconds: ttlSec,
182
+ expectedOutputTokens: tOut,
183
+ uncachedDeltaTokens,
184
+ cacheTtlTier,
185
+ readDiscountFactor,
186
+ discountPct,
187
+ cacheDiscount,
188
+ pricingMode,
189
+ eventTimestampUtc
190
+ });
191
+
192
+ const wCurr = getModelBaseWeight(normCurrent);
193
+ const eLow = getCostMultiplier(normCurrent, 'low');
194
+ const wTarget = getModelBaseWeight(normTarget);
195
+ const eTarget = getCostMultiplier(normTarget, normTargetEffort);
196
+ const readFactor = closedForm.readDiscountFactor;
197
+
198
+ const warmCurrentLowCost = Number(((tCached * readFactor * wCurr) + (tOut * eLow)).toFixed(2));
199
+ const coldTargetSwitchCost = Number(((tCached * 1.00 * wTarget) + (tOut * eTarget)).toFixed(2));
200
+
201
+ // \Delta_{cost} = Warm(curr, low) - Cold(target, targetEffort)
202
+ // Negative \Delta_{cost} means staying warm on currentModel-Low is cheaper than cold-switching to targetModel.
203
+ const deltaCost = Number((warmCurrentLowCost - coldTargetSwitchCost).toFixed(2));
204
+ const coldSwitchPenaltyTokens = Number((coldTargetSwitchCost - warmCurrentLowCost).toFixed(2));
205
+
206
+ const hasWarmCacheGravity =
207
+ ttlSec > 0 &&
208
+ (this.explicitWarmCacheThreshold !== null
209
+ ? tCached >= this.explicitWarmCacheThreshold
210
+ : (closedForm.canHoldWarmPrefix && tCached > closedForm.breakEvenTokens));
211
+ const crossFamily = !isSameModelFamily(normCurrent, normTarget);
212
+ const blockCrossModelSwitch = hasWarmCacheGravity && crossFamily;
213
+
214
+ const cachedK = (tCached / 1000).toFixed(1);
215
+ const penaltyK = Math.round(Math.abs(coldSwitchPenaltyTokens) / 1000);
216
+ const penaltySign = coldSwitchPenaltyTokens >= 0 ? '+' : '-';
217
+ const targetShort = formatShortFamilyLabel(normTarget);
218
+ const currShort = formatShortFamilyLabel(normCurrent);
219
+
220
+ const tooltip = `Warm Cache: ${cachedK}k tokens (TTL ${formatTtlMinutesSeconds(ttlSec)}) • Cold ${targetShort} switch costs ${penaltySign}${penaltyK}k equiv burn vs ${currShort}-Low`;
221
+
222
+ return {
223
+ mode: closedForm.mode,
224
+ currentModel: normCurrent,
225
+ targetModel: normTarget,
226
+ targetEffort: normTargetEffort,
227
+ cachedTokens: tCached,
228
+ ttlRemainingSeconds: ttlSec,
229
+ expectedOutputTokens: tOut,
230
+ readDiscountFactor: readFactor,
231
+ breakEvenTokens: closedForm.breakEvenTokens,
232
+ canHoldWarmPrefix: closedForm.canHoldWarmPrefix,
233
+ denominator: closedForm.denominator,
234
+ wCurr,
235
+ eLow,
236
+ wTarget,
237
+ eTarget,
238
+ warmCurrentLowCost,
239
+ coldTargetSwitchCost,
240
+ deltaCost,
241
+ coldSwitchPenaltyTokens,
242
+ hasWarmCacheGravity,
243
+ blockCrossModelSwitch,
244
+ recommendedAction: blockCrossModelSwitch
245
+ ? 'DOWNSHIFT_EFFORT_SAME_MODEL_OR_SPAWN_FLASH_SUBAGENT'
246
+ : (crossFamily ? 'SWITCH_MODEL_FAMILY' : 'MODULATE_EFFORT_SAME_MODEL'),
247
+ recommendedModel: blockCrossModelSwitch ? normCurrent : normTarget,
248
+ recommendedEffort: blockCrossModelSwitch ? 'low' : normTargetEffort,
249
+ tooltip
250
+ };
251
+ }
252
+
253
+ /**
254
+ * Backward-compatible effective cost method used by existing Phase 5 callers.
255
+ */
256
+ computeEffectiveCost({
257
+ candidateModel,
258
+ candidateEffort,
259
+ activeModel = 'gemini-4-argon',
260
+ cachedTokens = 0,
261
+ cacheTtlSeconds = 0,
262
+ ttlRemainingSeconds = undefined,
263
+ uncachedDeltaTokens = 2000,
264
+ expectedOutputTokens = null
265
+ } = {}) {
266
+ const normCandidateModel = normalizeModelId(candidateModel);
267
+ const normActiveModel = normalizeModelId(activeModel);
268
+ const rawEffort = String(candidateEffort || 'high').toLowerCase();
269
+ const effortKey = rawEffort === 'medium' ? 'medium' : normalizeEffortKey(rawEffort);
270
+ const ttlSec = Math.max(0, Number(ttlRemainingSeconds ?? cacheTtlSeconds ?? 0));
271
+
272
+ const multiplier = MODEL_CATALOG[normCandidateModel]?.multipliers?.[effortKey === 'med' ? 'medium' : effortKey]
273
+ ?? getCostMultiplier(normCandidateModel, effortKey);
274
+ const isCacheWarm = ttlSec > 0 && Number(cachedTokens) > 0;
275
+ const sameModelIndicator = isCacheWarm && isSameModelFamily(normCandidateModel, normActiveModel) ? 1 : 0;
276
+
277
+ const tCached = Math.max(0, Number(cachedTokens || 0));
278
+ const tUncachedDelta = Math.max(0, Number(uncachedDeltaTokens || 0));
279
+ const eOutput = expectedOutputTokens !== null && expectedOutputTokens !== undefined
280
+ ? Number(expectedOutputTokens)
281
+ : (EXPECTED_OUTPUT_TOKENS_BY_EFFORT[effortKey === 'med' ? 'medium' : effortKey] || DEFAULT_EXPECTED_OUTPUT_TOKENS);
282
+
283
+ const readFactor = resolveReadDiscountFactor(normActiveModel, { totalPromptTokens: tCached });
284
+ const cachedTerm = sameModelIndicator * (readFactor * tCached);
285
+ const coldPrefillTerm = (1 - sameModelIndicator) * tCached;
286
+ const effectiveTokens = cachedTerm + coldPrefillTerm + tUncachedDelta + eOutput;
287
+ const effectiveQuotaCost = Number((multiplier * effectiveTokens).toFixed(2));
288
+
289
+ return {
290
+ model: normCandidateModel,
291
+ effort: effortKey === 'med' ? 'medium' : effortKey,
292
+ multiplier,
293
+ sameModelIndicator,
294
+ isCacheWarm,
295
+ cachedTokens: tCached,
296
+ uncachedDeltaTokens: tUncachedDelta,
297
+ expectedOutputTokens: eOutput,
298
+ readDiscountFactor: readFactor,
299
+ cachedTerm: Number(cachedTerm.toFixed(2)),
300
+ coldPrefillTerm: Number(coldPrefillTerm.toFixed(2)),
301
+ effectiveTokens: Number(effectiveTokens.toFixed(2)),
302
+ effectiveQuotaCost
303
+ };
304
+ }
305
+
306
+ /**
307
+ * Evaluates candidate routes and enforces dynamic Closed-Form Cache-Gravity Invariant.
308
+ */
309
+ evaluateCandidates(context = {}) {
310
+ const activeModel = normalizeModelId(context.activeModel || 'gemini-4-argon');
311
+ const activeEffort = String(context.activeEffort || 'high').toLowerCase();
312
+ const cachedTokens = Math.max(0, Number(context.cachedTokens || 0));
313
+ const ttlSec = Math.max(0, Number(context.ttlRemainingSeconds ?? context.cacheTtlSeconds ?? 0));
314
+ const uncachedDeltaTokens = Math.max(0, Number(context.uncachedDeltaTokens ?? 2000));
315
+ const complexityTier = String(context.complexityTier || 'LOW').toUpperCase();
316
+ const confidence = Number(context.confidence ?? 0.90);
317
+
318
+ const defaultDownshiftPeer = activeModel === 'claude-opus-5-5'
319
+ ? 'claude-sonnet-5-5'
320
+ : (activeModel === 'claude-opus-4-6'
321
+ ? 'claude-sonnet-4-6'
322
+ : (activeModel === 'claude-opus-4-5'
323
+ ? 'claude-sonnet-4-5'
324
+ : (activeModel.startsWith('claude-fable') ? 'claude-opus-5-5' : 'gemini-3.8-flash')));
325
+
326
+ const breakEven = this.computeBreakEvenDelta({
327
+ currentModel: activeModel,
328
+ targetModel: context.targetModel || defaultDownshiftPeer,
329
+ targetEffort: 'low',
330
+ cachedTokens,
331
+ ttlRemainingSeconds: ttlSec,
332
+ expectedOutputTokens: context.expectedOutputTokens ?? DEFAULT_EXPECTED_OUTPUT_TOKENS
333
+ });
334
+
335
+ const hasWarmCacheGravity = breakEven.hasWarmCacheGravity;
336
+
337
+ const baselineCost = this.computeEffectiveCost({
338
+ candidateModel: activeModel,
339
+ candidateEffort: activeEffort,
340
+ activeModel,
341
+ cachedTokens,
342
+ cacheTtlSeconds: ttlSec,
343
+ uncachedDeltaTokens
344
+ });
345
+
346
+ const sameModelLowCost = this.computeEffectiveCost({
347
+ candidateModel: activeModel,
348
+ candidateEffort: 'low',
349
+ activeModel,
350
+ cachedTokens,
351
+ cacheTtlSeconds: ttlSec,
352
+ uncachedDeltaTokens
353
+ });
354
+
355
+ const coldSwitchToFlashCost = this.computeEffectiveCost({
356
+ candidateModel: 'gemini-3.8-flash',
357
+ candidateEffort: 'low',
358
+ activeModel,
359
+ cachedTokens,
360
+ cacheTtlSeconds: ttlSec,
361
+ uncachedDeltaTokens
362
+ });
363
+
364
+ let primaryRecommendation = null;
365
+ let subagentOffloadOption = null;
366
+ let localOffloadOption = null;
367
+ let policyApplied = 'COLD_OR_LOW_CACHE_OPTIMAL';
368
+
369
+ if (hasWarmCacheGravity && activeModel !== 'gemini-3.8-flash') {
370
+ const targetSameModelEffort = complexityTier === 'HIGH' ? 'high' : 'low';
371
+ const targetCostObj = targetSameModelEffort === 'low' ? sameModelLowCost : baselineCost;
372
+ const multiplierSavingsPct = baselineCost.multiplier > 0
373
+ ? Math.max(0, Math.round(((baselineCost.multiplier - targetCostObj.multiplier) / baselineCost.multiplier) * 100))
374
+ : 0;
375
+ const effectiveSavingsPct = baselineCost.effectiveQuotaCost > 0
376
+ ? Math.max(0, Math.round(((baselineCost.effectiveQuotaCost - targetCostObj.effectiveQuotaCost) / baselineCost.effectiveQuotaCost) * 100))
377
+ : 0;
378
+
379
+ primaryRecommendation = {
380
+ action: 'MODULATE_EFFORT_SAME_MODEL',
381
+ model: activeModel,
382
+ effort: targetSameModelEffort,
383
+ multiplier: targetCostObj.multiplier,
384
+ effectiveQuotaCost: targetCostObj.effectiveQuotaCost,
385
+ preservesWarmCache: true,
386
+ coldPrefillPenaltyAvoidedTokens: cachedTokens,
387
+ multiplierSavingsPct,
388
+ effectiveSavingsPct,
389
+ tooltip: breakEven.tooltip,
390
+ label: `Drop to ${formatModelDisplayLabel(activeModel)} • ${targetSameModelEffort.toUpperCase()} (Keep ${(cachedTokens / 1000).toFixed(1)}k Cache, Save ${Math.max(multiplierSavingsPct, effectiveSavingsPct)}%)`
391
+ };
392
+ policyApplied = 'RULE_A_MODULATE_SAME_MODEL_EFFORT';
393
+
394
+ if (complexityTier === 'LOW' && confidence >= FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD) {
395
+ subagentOffloadOption = {
396
+ action: 'SPAWN_FLASH_SUBAGENT',
397
+ model: 'gemini-3.8-flash',
398
+ effort: 'low',
399
+ multiplier: 1.0,
400
+ contextBudgetTokens: 2000,
401
+ preservesMainSessionCache: true,
402
+ label: '⚡ Offload to Flash-Low Subagent (<2k ctx)'
403
+ };
404
+ localOffloadOption = {
405
+ action: 'OFFLOAD_LOCAL_LITERT',
406
+ model: 'local-gemma4-26b',
407
+ effort: 'low',
408
+ multiplier: 0.0,
409
+ effectiveQuotaCost: 0,
410
+ preservesMainSessionCache: true,
411
+ label: '⚡ Offload to Local LiteRT Gemma 4 26B (0.0x quota)'
412
+ };
413
+ policyApplied = 'RULE_A_AND_B_WARM_CACHE_WITH_SUBAGENT_OFFLOAD';
414
+ }
415
+ } else {
416
+ const frontierDefault = activeModel.includes('carbon') ? activeModel : 'gemini-4-argon';
417
+ let targetModel = activeModel;
418
+ let targetEffort = activeEffort;
419
+ if (complexityTier === 'LOW' && confidence >= FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD) {
420
+ targetModel = 'gemini-3.8-flash';
421
+ targetEffort = 'low';
422
+ } else if (complexityTier === 'MEDIUM') {
423
+ targetModel = ttlSec === 0 && cachedTokens >= this.warmCacheThresholdTokens
424
+ ? 'gemini-3.8-flash'
425
+ : frontierDefault;
426
+ targetEffort = 'medium';
427
+ } else {
428
+ targetModel = frontierDefault;
429
+ targetEffort = 'high';
430
+ }
431
+
432
+ const targetCostObj = this.computeEffectiveCost({
433
+ candidateModel: targetModel,
434
+ candidateEffort: targetEffort,
435
+ activeModel,
436
+ cachedTokens,
437
+ cacheTtlSeconds: ttlSec,
438
+ uncachedDeltaTokens
439
+ });
440
+
441
+ primaryRecommendation = {
442
+ action: targetModel !== activeModel ? 'SWITCH_MODEL_FAMILY' : 'MODULATE_EFFORT_SAME_MODEL',
443
+ model: targetModel,
444
+ effort: targetEffort,
445
+ multiplier: targetCostObj.multiplier,
446
+ effectiveQuotaCost: targetCostObj.effectiveQuotaCost,
447
+ preservesWarmCache: isSameModelFamily(targetModel, activeModel) && ttlSec > 0,
448
+ coldPrefillPenaltyAvoidedTokens: 0,
449
+ tooltip: breakEven.tooltip,
450
+ label: `Switch to ${formatModelDisplayLabel(targetModel)} • ${targetEffort.toUpperCase()} (${targetCostObj.multiplier}x)`
451
+ };
452
+ }
453
+
454
+ return {
455
+ hasWarmCacheGravity,
456
+ policyApplied,
457
+ breakEven,
458
+ tooltip: breakEven.tooltip,
459
+ baseline: baselineCost,
460
+ sameModelLowCost,
461
+ coldSwitchToFlashCost,
462
+ primaryRecommendation,
463
+ subagentOffloadOption,
464
+ localOffloadOption
465
+ };
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Phase 2.3a: `HysteresisLock` (Invariant 3 — Sticky Escalation)
471
+ *
472
+ * When `DET-01` or `DET-02` triggers a tier escalation, locks the elevated model/effort
473
+ * for `activeTaskMdStepId`. Rejects downshift recommendations until:
474
+ * 1. `TaskMdDirectiveWatcher` observes that step marked `[x]`, OR
475
+ * 2. `TrajectoryWatcher` emits a `TRAJECTORY_REWIND` event.
476
+ */
477
+ export class HysteresisLock {
478
+ constructor() {
479
+ this.locked = false;
480
+ this.activeTaskMdStepId = null;
481
+ this.lockedModel = null;
482
+ this.lockedEffort = null;
483
+ this.triggerDetectorId = null;
484
+ this.reason = null;
485
+ this.engagedAtTurn = null;
486
+ this.cleanTurnsSinceEngaged = 0;
487
+ this.lastUnlockReason = null;
488
+ }
489
+
490
+ engage({
491
+ stepId = 'active-step',
492
+ model = 'gemini-4-argon',
493
+ effort = 'high',
494
+ detectorId = 'DET-01',
495
+ reason = 'Circuit breaker tier escalation',
496
+ turnIndex = 0
497
+ } = {}) {
498
+ this.locked = true;
499
+ this.activeTaskMdStepId = String(stepId || 'active-step');
500
+ this.lockedModel = normalizeModelId(model);
501
+ this.lockedEffort = normalizeEffortKey(effort);
502
+ this.triggerDetectorId = String(detectorId || 'DET-01');
503
+ this.reason = String(reason || '');
504
+ this.engagedAtTurn = Number(turnIndex || 0);
505
+ this.cleanTurnsSinceEngaged = 0;
506
+ this.lastUnlockReason = null;
507
+ return this.getStatus();
508
+ }
509
+
510
+ /**
511
+ * Auto-decays the hysteresis lock after `maxLockedTurns` clean turns so users
512
+ * who do not maintain `task.md` checkboxes are never permanently trapped on a high tier.
513
+ */
514
+ onTurnCompleted({ currentTurnIndex = null, hadBreakerError = false, maxLockedTurns = 3 } = {}) {
515
+ if (!this.locked) {
516
+ return { unlocked: false, locked: false, reason: null };
517
+ }
518
+ if (hadBreakerError) {
519
+ this.cleanTurnsSinceEngaged = 0;
520
+ if (Number.isFinite(currentTurnIndex)) {
521
+ this.engagedAtTurn = Number(currentTurnIndex);
522
+ }
523
+ return { unlocked: false, locked: true, reason: null };
524
+ }
525
+ this.cleanTurnsSinceEngaged += 1;
526
+ const turnDelta =
527
+ Number.isFinite(currentTurnIndex) && Number.isFinite(this.engagedAtTurn)
528
+ ? Number(currentTurnIndex) - Number(this.engagedAtTurn)
529
+ : this.cleanTurnsSinceEngaged;
530
+ if (this.cleanTurnsSinceEngaged >= maxLockedTurns || turnDelta >= maxLockedTurns) {
531
+ return this.unlock('AUTO_DECAY_CLEAN_TURNS', {
532
+ cleanTurns: this.cleanTurnsSinceEngaged,
533
+ turnDelta
534
+ });
535
+ }
536
+ return { unlocked: false, locked: true, cleanTurns: this.cleanTurnsSinceEngaged };
537
+ }
538
+
539
+ isLocked() {
540
+ return Boolean(this.locked);
541
+ }
542
+
543
+ /**
544
+ * Returns true if a proposed candidate (model, effort) is a downshift below the locked tier.
545
+ */
546
+ shouldBlockDownshift({ candidateModel, candidateEffort } = {}) {
547
+ if (!this.locked) return false;
548
+ const lockedMult = getCostMultiplier(this.lockedModel, this.lockedEffort);
549
+ const candidateMult = getCostMultiplier(candidateModel || this.lockedModel, candidateEffort || 'low');
550
+ return candidateMult < lockedMult;
551
+ }
552
+
553
+ /**
554
+ * Evaluates `task.md` content or parsed directives and unlocks ONLY when `activeTaskMdStepId`
555
+ * transitions from `[/]` to `[x]`.
556
+ */
557
+ onTaskMdUpdate(taskMdInput = '') {
558
+ if (!this.locked) {
559
+ return { unlocked: false, locked: false, reason: null };
560
+ }
561
+
562
+ if (typeof taskMdInput === 'string') {
563
+ const lines = taskMdInput.split(/\r?\n/);
564
+ for (let i = 0; i < lines.length; i++) {
565
+ const line = lines[i];
566
+ const completedMatch = line.match(/^\s*-\s*\[[xX]\]\s*(.+)$/);
567
+ if (completedMatch) {
568
+ const text = completedMatch[1].trim();
569
+ const lineId = `line-${i + 1}`;
570
+ if (
571
+ this.activeTaskMdStepId === lineId ||
572
+ text.includes(this.activeTaskMdStepId) ||
573
+ this.activeTaskMdStepId.includes(text)
574
+ ) {
575
+ return this.unlock('TASK_MD_STEP_COMPLETED');
576
+ }
577
+ }
578
+ }
579
+ } else if (taskMdInput && typeof taskMdInput === 'object') {
580
+ if (taskMdInput.completedStepId && taskMdInput.completedStepId === this.activeTaskMdStepId) {
581
+ return this.unlock('TASK_MD_STEP_COMPLETED');
582
+ }
583
+ if (Array.isArray(taskMdInput.allDirectives)) {
584
+ const match = taskMdInput.allDirectives.find((item) =>
585
+ item.status === 'COMPLETED' &&
586
+ (`line-${item.lineNumber}` === this.activeTaskMdStepId ||
587
+ item.text.includes(this.activeTaskMdStepId) ||
588
+ this.activeTaskMdStepId.includes(item.text))
589
+ );
590
+ if (match) {
591
+ return this.unlock('TASK_MD_STEP_COMPLETED');
592
+ }
593
+ }
594
+ }
595
+
596
+ return { unlocked: false, locked: true, reason: null };
597
+ }
598
+
599
+ /**
600
+ * Unlocks immediately when `TrajectoryWatcher` emits `TRAJECTORY_REWIND`.
601
+ */
602
+ onTrajectoryRewind(rewindPayload = {}) {
603
+ if (!this.locked) {
604
+ return { unlocked: false, locked: false, reason: 'ALREADY_UNLOCKED' };
605
+ }
606
+ return this.unlock('TRAJECTORY_REWIND', rewindPayload);
607
+ }
608
+
609
+ unlock(reason = 'MANUAL_RESET', metadata = null) {
610
+ this.locked = false;
611
+ this.lastUnlockReason = String(reason);
612
+ const prevStep = this.activeTaskMdStepId;
613
+ this.activeTaskMdStepId = null;
614
+ return {
615
+ unlocked: true,
616
+ locked: false,
617
+ previousStepId: prevStep,
618
+ reason: this.lastUnlockReason,
619
+ metadata
620
+ };
621
+ }
622
+
623
+ getStatus() {
624
+ return {
625
+ locked: this.locked,
626
+ activeTaskMdStepId: this.activeTaskMdStepId,
627
+ lockedModel: this.lockedModel,
628
+ lockedEffort: this.lockedEffort,
629
+ triggerDetectorId: this.triggerDetectorId,
630
+ reason: this.reason,
631
+ lastUnlockReason: this.lastUnlockReason
632
+ };
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Phase 2.3b: `TurnBoundaryActuationQueue` (Invariant 2 — Hard Turn-Boundary Actuation)
638
+ *
639
+ * Never fires `SET_MODEL_AND_EFFORT` RPC/commands mid-stream while tools are executing.
640
+ * Queues actuations while Language Server state is `STREAMING`, `EXECUTING_TOOLS`, or `BUSY`
641
+ * and dispatches ONLY when state is `IDLE`, `WAITING_FOR_USER`, or `WAITING_FOR_APPROVAL`.
642
+ */
643
+ export class TurnBoundaryActuationQueue {
644
+ constructor(options = {}) {
645
+ this.languageServerState = String(options.languageServerState || 'IDLE').toUpperCase();
646
+ this.queue = [];
647
+ this.dispatchedHistory = [];
648
+ this.dispatcher = typeof options.dispatcher === 'function' ? options.dispatcher : null;
649
+ }
650
+
651
+ isTurnBoundarySafe(state = this.languageServerState) {
652
+ return SAFE_TURN_BOUNDARY_STATES.has(String(state || '').toUpperCase());
653
+ }
654
+
655
+ /**
656
+ * Enqueues an actuation request or dispatches it immediately if the Language Server
657
+ * is currently at a safe turn boundary (`IDLE`, `WAITING_FOR_USER`, `WAITING_FOR_APPROVAL`).
658
+ */
659
+ async enqueueOrDispatch(actuationPayload, customDispatcher = null) {
660
+ const dispatchFn = customDispatcher || this.dispatcher;
661
+ const item = {
662
+ id: `act-${Date.now()}-${this.queue.length + 1}`,
663
+ payload: actuationPayload,
664
+ enqueuedAtState: this.languageServerState,
665
+ dispatchFn
666
+ };
667
+
668
+ if (!this.isTurnBoundarySafe(this.languageServerState)) {
669
+ this.queue.push(item);
670
+ return {
671
+ queued: true,
672
+ actuated: false,
673
+ languageServerState: this.languageServerState,
674
+ queueLength: this.queue.length,
675
+ payload: actuationPayload
676
+ };
677
+ }
678
+
679
+ let dispatchResult = null;
680
+ if (typeof dispatchFn === 'function') {
681
+ dispatchResult = await dispatchFn(actuationPayload);
682
+ }
683
+
684
+ const isBlocked = Boolean(
685
+ dispatchResult &&
686
+ (dispatchResult.ok === false || dispatchResult.allowed === false || dispatchResult.transportUsed === 'blocked_cdp')
687
+ );
688
+ const record = {
689
+ queued: false,
690
+ actuated: !isBlocked,
691
+ method: isBlocked ? 'blocked_cdp' : (dispatchResult?.transportUsed || 'rpc'),
692
+ ...(isBlocked
693
+ ? { reason: dispatchResult.cdpBlockedReason || dispatchResult.reason || 'EXPERIMENTAL_CDP_DISABLED' }
694
+ : {}),
695
+ languageServerState: this.languageServerState,
696
+ payload: actuationPayload,
697
+ dispatchResult
698
+ };
699
+ this.dispatchedHistory.push(record);
700
+ return record;
701
+ }
702
+
703
+ /**
704
+ * Transitions the Language Server state and automatically flushes queued actuations
705
+ * when entering `IDLE`, `WAITING_FOR_USER`, or `WAITING_FOR_APPROVAL`.
706
+ */
707
+ async setLanguageServerState(newState) {
708
+ this.languageServerState = String(newState || 'IDLE').toUpperCase();
709
+ if (this.isTurnBoundarySafe(this.languageServerState) && this.queue.length > 0) {
710
+ return this.flush();
711
+ }
712
+ return {
713
+ flushed: false,
714
+ flushedCount: 0,
715
+ languageServerState: this.languageServerState,
716
+ remainingQueueLength: this.queue.length,
717
+ results: []
718
+ };
719
+ }
720
+
721
+ async flush() {
722
+ if (!this.isTurnBoundarySafe(this.languageServerState)) {
723
+ return {
724
+ flushed: false,
725
+ flushedCount: 0,
726
+ languageServerState: this.languageServerState,
727
+ remainingQueueLength: this.queue.length,
728
+ results: []
729
+ };
730
+ }
731
+
732
+ const pending = this.queue.splice(0, this.queue.length);
733
+ const results = [];
734
+ for (const item of pending) {
735
+ let dispatchResult = null;
736
+ if (typeof item.dispatchFn === 'function') {
737
+ dispatchResult = await item.dispatchFn(item.payload);
738
+ }
739
+ const isBlocked = Boolean(
740
+ dispatchResult &&
741
+ (dispatchResult.ok === false || dispatchResult.allowed === false || dispatchResult.transportUsed === 'blocked_cdp')
742
+ );
743
+ const record = {
744
+ queued: false,
745
+ actuated: !isBlocked,
746
+ method: isBlocked ? 'blocked_cdp' : (dispatchResult?.transportUsed || 'rpc'),
747
+ ...(isBlocked
748
+ ? { reason: dispatchResult.cdpBlockedReason || dispatchResult.reason || 'EXPERIMENTAL_CDP_DISABLED' }
749
+ : {}),
750
+ languageServerState: this.languageServerState,
751
+ payload: item.payload,
752
+ dispatchResult
753
+ };
754
+ this.dispatchedHistory.push(record);
755
+ results.push(record);
756
+ }
757
+
758
+ return {
759
+ flushed: results.length > 0,
760
+ flushedCount: results.length,
761
+ languageServerState: this.languageServerState,
762
+ remainingQueueLength: this.queue.length,
763
+ results
764
+ };
765
+ }
766
+
767
+ clear() {
768
+ this.queue = [];
769
+ }
770
+ }
771
+
772
+ /**
773
+ * Phase 2 Unified Flight Computer & Coach Router (`TaskQuotaRouter`)
774
+ */
775
+ export class TaskQuotaRouter {
776
+ constructor(options = {}) {
777
+ this.mode = normalizeCoachMode(options.mode || COACH_MODES.COACH);
778
+ this.activeModel = normalizeModelId(options.activeModel || 'gemini-4-argon');
779
+ this.activeEffort = normalizeEffortKey(options.activeEffort || 'high');
780
+ this.cacheGravityScorer = options.cacheGravityScorer || new CacheGravityScorer(options);
781
+ this.hysteresisLock = options.hysteresisLock || new HysteresisLock();
782
+ this.agBridge = options.agBridge || new AgBridgeService(options);
783
+ this.turnBoundaryQueue = options.turnBoundaryQueue || new TurnBoundaryActuationQueue({
784
+ languageServerState: options.languageServerState || 'IDLE',
785
+ dispatcher: async (payload) => {
786
+ const res = await this.agBridge.sendChatCommand(payload.sessionId || 'default', payload, options);
787
+ if (res && res.ok !== false) {
788
+ this.activeModel = payload.model;
789
+ this.activeEffort = payload.effort;
790
+ }
791
+ return res;
792
+ }
793
+ });
794
+ }
795
+
796
+ setMode(mode) {
797
+ this.mode = normalizeCoachMode(mode);
798
+ return this.mode;
799
+ }
800
+
801
+ async evaluateTurn({
802
+ sessionId = 'default',
803
+ currentModel = this.activeModel,
804
+ currentEffort = this.activeEffort,
805
+ targetModel = 'gemini-3.8-flash',
806
+ targetEffort = 'low',
807
+ cachedTokens = 0,
808
+ ttlRemainingSeconds = 0,
809
+ expectedOutputTokens = DEFAULT_EXPECTED_OUTPUT_TOKENS,
810
+ activeTaskMdStepId = 'step-1',
811
+ det01Triggered = false,
812
+ det02Triggered = false,
813
+ languageServerState = null
814
+ } = {}) {
815
+ if (languageServerState) {
816
+ await this.turnBoundaryQueue.setLanguageServerState(languageServerState);
817
+ }
818
+
819
+ // 1. Check DET-01 / DET-02 tier escalation -> engage HysteresisLock
820
+ if (det01Triggered || det02Triggered) {
821
+ const detectorId = det01Triggered ? 'DET-01' : 'DET-02';
822
+ const normCurr = normalizeModelId(currentModel);
823
+ const escalatedModel = normCurr.includes('carbon') ? normCurr : 'gemini-4-argon';
824
+ this.hysteresisLock.engage({
825
+ stepId: activeTaskMdStepId,
826
+ model: escalatedModel,
827
+ effort: 'high',
828
+ detectorId,
829
+ reason: `${detectorId} loop escalation`
830
+ });
831
+ }
832
+
833
+ // 2. If HysteresisLock is engaged, block any downshift below locked tier
834
+ if (
835
+ this.hysteresisLock.isLocked() &&
836
+ this.hysteresisLock.shouldBlockDownshift({ candidateModel: targetModel, candidateEffort: targetEffort })
837
+ ) {
838
+ return {
839
+ mode: this.mode,
840
+ blockedByHysteresis: true,
841
+ hysteresisStatus: this.hysteresisLock.getStatus(),
842
+ recommendedModel: this.hysteresisLock.lockedModel,
843
+ recommendedEffort: this.hysteresisLock.lockedEffort,
844
+ actuated: false,
845
+ queued: false
846
+ };
847
+ }
848
+
849
+ // 3. Evaluate CacheGravityScorer break-even math & 60k warm cache lock
850
+ const breakEven = this.cacheGravityScorer.computeBreakEvenDelta({
851
+ currentModel,
852
+ targetModel,
853
+ targetEffort,
854
+ cachedTokens,
855
+ ttlRemainingSeconds,
856
+ expectedOutputTokens
857
+ });
858
+
859
+ const safeModel = breakEven.recommendedModel;
860
+ const safeEffort = breakEven.recommendedEffort;
861
+
862
+ if (this.mode === COACH_MODES.OFF) {
863
+ return {
864
+ mode: this.mode,
865
+ blockedByHysteresis: false,
866
+ breakEven,
867
+ recommendedModel: safeModel,
868
+ recommendedEffort: safeEffort,
869
+ actuated: false,
870
+ queued: false
871
+ };
872
+ }
873
+
874
+ if (this.mode === COACH_MODES.COACH) {
875
+ return {
876
+ mode: this.mode,
877
+ blockedByHysteresis: false,
878
+ breakEven,
879
+ recommendedModel: safeModel,
880
+ recommendedEffort: safeEffort,
881
+ tooltip: breakEven.tooltip,
882
+ actuated: false,
883
+ queued: false
884
+ };
885
+ }
886
+
887
+ // 4. AUTO_PILOT mode: route through TurnBoundaryActuationQueue (Invariant 2)
888
+ const commandPayload = {
889
+ type: 'SET_MODEL_AND_EFFORT',
890
+ sessionId,
891
+ model: safeModel,
892
+ effort: safeEffort,
893
+ preserveWarmCache: breakEven.blockCrossModelSwitch
894
+ };
895
+
896
+ const queueRes = await this.turnBoundaryQueue.enqueueOrDispatch(commandPayload);
897
+
898
+ return {
899
+ mode: this.mode,
900
+ blockedByHysteresis: false,
901
+ breakEven,
902
+ recommendedModel: safeModel,
903
+ recommendedEffort: safeEffort,
904
+ tooltip: breakEven.tooltip,
905
+ actuated: queueRes.actuated,
906
+ method: queueRes.method || (queueRes.queued ? 'queued_turn_boundary' : 'rpc'),
907
+ ...(queueRes.reason ? { reason: queueRes.reason } : {}),
908
+ queued: queueRes.queued,
909
+ languageServerState: queueRes.languageServerState,
910
+ queueResult: queueRes
911
+ };
912
+ }
913
+ }
914
+
915
+ export function evaluateCacheGravity(params = {}) {
916
+ const scorer = new CacheGravityScorer(params);
917
+ return scorer.computeBreakEvenDelta(params);
918
+ }
919
+
920
+ export {
921
+ MODEL_CATALOG,
922
+ WARM_CACHE_GRAVITY_THRESHOLD_TOKENS,
923
+ FLOOR_GUARANTEE_CONFIDENCE_THRESHOLD,
924
+ DEFAULT_EXPECTED_OUTPUT_TOKENS,
925
+ EXPECTED_OUTPUT_TOKENS_BY_EFFORT,
926
+ normalizeModelId,
927
+ getModelFamily,
928
+ isSameModelFamily,
929
+ formatModelDisplayLabel,
930
+ extractActiveTaskStep,
931
+ inferLifecycleMode,
932
+ classifyTaskComplexity,
933
+ computeClosedFormBreakEven,
934
+ TaskMdDirectiveWatcher,
935
+ ModelSelectorActuator,
936
+ evaluateTaskAndQuotaRoute
937
+ };
938
+
939
+ export default {
940
+ COACH_MODES,
941
+ COST_MULTIPLIER_MATRIX,
942
+ SAFE_TURN_BOUNDARY_STATES,
943
+ CacheGravityScorer,
944
+ HysteresisLock,
945
+ TurnBoundaryActuationQueue,
946
+ TaskQuotaRouter,
947
+ TaskMdDirectiveWatcher,
948
+ ModelSelectorActuator,
949
+ evaluateTaskAndQuotaRoute,
950
+ evaluateCacheGravity,
951
+ computeClosedFormBreakEven,
952
+ getCostMultiplier,
953
+ getModelBaseWeight,
954
+ classifyTaskComplexity
955
+ };