ctxtop 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  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 +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -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 +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,661 @@
1
+ /**
2
+ * Synthetic demo and test fixtures covering all 8 canonical session and router scenarios.
3
+ * Mathematically self-consistent:
4
+ * - sum(cells[i].totalTokens) === totalActiveTokens
5
+ * - ANCHOR + INJECTED_MEMORY + ACTIVE_WORKING_SET + DUPLICATE_READ + STALE_TURN + DEAD_ERROR === totalActiveTokens
6
+ * - topRiskyCells, chronicReads, and subagents strictly scoped to active session depth
7
+ */
8
+ import { resolvePricePerM, resolveModelCeiling } from '../core/constants.mjs';
9
+
10
+ export const SCENARIO_1_COLD_VAGUE = {
11
+ conversationId: 'fixture_scenario_1_cold',
12
+ prompt: 'Update the whole caching system and refactor everything',
13
+ modelName: 'gemini-3.8-flash',
14
+ effort: 'low',
15
+ sidecar: {
16
+ conversationId: 'fixture_scenario_1_cold',
17
+ sessionMeta: { turnCount: 1, activeModel: 'gemini-3.8-flash', activeEffort: 'low', inPlanMode: false },
18
+ telemetry: { totalInputTokens: 3500, signalPurityPct: 100.0, quota: { remaining_fraction: 0.95 } },
19
+ fileState: { activeSetPaths: ['src/cache.mjs'] }
20
+ }
21
+ };
22
+
23
+ export const SCENARIO_2_WARM_ACTIVE_SET = {
24
+ conversationId: 'fixture_scenario_2_warm',
25
+ prompt: 'In router.mjs add error handling to the dispatch function',
26
+ modelName: 'gemini-3.8-flash',
27
+ effort: 'medium',
28
+ sidecar: {
29
+ conversationId: 'fixture_scenario_2_warm',
30
+ sessionMeta: { turnCount: 18, activeModel: 'gemini-3.8-flash', activeEffort: 'medium' },
31
+ telemetry: { totalInputTokens: 62000, signalPurityPct: 82.0, quota: { remaining_fraction: 0.85 } },
32
+ fileState: { activeSetPaths: ['c:/projects/attention-horizon-antigravity/src/core/router.mjs'] }
33
+ }
34
+ };
35
+
36
+ export const SCENARIO_3_HOT_CONCURRENCY = {
37
+ conversationId: 'fixture_scenario_3_hot',
38
+ prompt: 'Investigate the async concurrency deadlock in worker queue',
39
+ modelName: 'gemini-3.8-flash',
40
+ effort: 'medium',
41
+ sidecar: {
42
+ conversationId: 'fixture_scenario_3_hot',
43
+ sessionMeta: { turnCount: 45, activeModel: 'gemini-3.8-flash', activeEffort: 'medium' },
44
+ telemetry: { totalInputTokens: 85000, signalPurityPct: 79.0, quota: { remaining_fraction: 0.70 } },
45
+ fileState: { activeSetPaths: ['src/queue.mjs'] }
46
+ }
47
+ };
48
+
49
+ export const SCENARIO_4_POLLUTED_REFACTOR = {
50
+ conversationId: 'fixture_scenario_4_polluted',
51
+ prompt: 'Refactor database connection pool',
52
+ modelName: 'gemini-3.1-pro',
53
+ effort: 'high',
54
+ sidecar: {
55
+ conversationId: 'fixture_scenario_4_polluted',
56
+ sessionMeta: { turnCount: 22, activeModel: 'gemini-3.1-pro', activeEffort: 'high' },
57
+ telemetry: { totalInputTokens: 95000, signalPurityPct: 39.0, sludgeTaxUsdPerTurn: 0.07, quota: { remaining_fraction: 0.60 } },
58
+ fileState: { activeSetPaths: [] }
59
+ }
60
+ };
61
+
62
+ export const SCENARIO_5_AMPUTATION_CRISIS = {
63
+ conversationId: 'fixture_scenario_5_amputation',
64
+ prompt: 'Add billing summary endpoint',
65
+ modelName: 'gemini-3.1-pro',
66
+ effort: 'high',
67
+ sidecar: {
68
+ conversationId: 'fixture_scenario_5_amputation',
69
+ sessionMeta: { turnCount: 50, activeModel: 'gemini-3.1-pro', activeEffort: 'high' },
70
+ telemetry: { totalInputTokens: 145000, amputationRisk: true, signalPurityPct: 35.0, quota: { remaining_fraction: 0.50 } },
71
+ fileState: { activeSetPaths: [] }
72
+ }
73
+ };
74
+
75
+ export const SCENARIO_6_PARALLEL_DRIFT = {
76
+ conversationId: 'fixture_scenario_6_drift',
77
+ prompt: 'Update server routes',
78
+ modelName: 'gemini-3.8-flash',
79
+ effort: 'high',
80
+ sidecar: {
81
+ conversationId: 'fixture_scenario_6_drift',
82
+ sessionMeta: { turnCount: 12, activeModel: 'gemini-3.8-flash', activeEffort: 'high' },
83
+ telemetry: { totalInputTokens: 30000, signalPurityPct: 80.0, quota: { remaining_fraction: 0.80 } },
84
+ fileState: {
85
+ activeSetPaths: ['src/server.mjs'],
86
+ dirtySnapshotPaths: ['src/routes.mjs'],
87
+ unseenCallers: ['src/app.mjs'],
88
+ legacyPoisonPaths: [],
89
+ streamCutoffRiskFiles: []
90
+ }
91
+ }
92
+ };
93
+
94
+ export const SCENARIO_7_QUOTA_SHIELD = {
95
+ conversationId: 'fixture_scenario_7_quota',
96
+ prompt: 'Generate detailed architecture plan',
97
+ modelName: 'gemini-3.1-pro',
98
+ effort: 'max',
99
+ sidecar: {
100
+ conversationId: 'fixture_scenario_7_quota',
101
+ sessionMeta: { turnCount: 8, activeModel: 'gemini-3.1-pro', activeEffort: 'max' },
102
+ telemetry: { totalInputTokens: 40000, signalPurityPct: 85.0, quota: { remaining_fraction: 0.08 } },
103
+ sensors: { quotaFloorBreached: true },
104
+ fileState: { activeSetPaths: [] }
105
+ }
106
+ };
107
+
108
+ export const SCENARIO_8_EXPLICIT_CHECK = {
109
+ conversationId: 'fixture_scenario_8_check',
110
+ prompt: '#check Break down large 9950 line legacy parser into modules',
111
+ modelName: 'gemini-3.8-flash',
112
+ effort: 'medium',
113
+ sidecar: {
114
+ conversationId: 'fixture_scenario_8_check',
115
+ sessionMeta: { turnCount: 6, activeModel: 'gemini-3.8-flash', activeEffort: 'medium' },
116
+ telemetry: { totalInputTokens: 25000, signalPurityPct: 75.0, quota: { remaining_fraction: 0.85 } },
117
+ fileState: { activeSetPaths: ['src/parser.mjs'] }
118
+ }
119
+ };
120
+
121
+ export const DEMO_SCENARIOS = [
122
+ {
123
+ id: 1,
124
+ slug: 'cold-vague',
125
+ title: 'Scenario 1: Cold Vague Prompt (Turn 1 Rewrite)',
126
+ complaint: 'I typed a quick refactor prompt and burned 20k tokens because the agent guessed the wrong files.',
127
+ fixture: SCENARIO_1_COLD_VAGUE,
128
+ routerState: 'HALT_REWRITE_SCORECARD',
129
+ score: 42,
130
+ sludgeTaxUsd: 0.00,
131
+ reclaimTokens: 0,
132
+ recommendedAction: '/model gemini-3.8-flash • /effort medium',
133
+ rewrite: 'In @src/cache.mjs refactor cache eviction policy and update unit tests'
134
+ },
135
+ {
136
+ id: 2,
137
+ slug: 'warm-active',
138
+ title: 'Scenario 2: Healthy Warm Session (82% Purity)',
139
+ complaint: 'Baseline healthy coding session with clean active working set.',
140
+ fixture: SCENARIO_2_WARM_ACTIVE_SET,
141
+ routerState: 'ALLOW_ACTIVE_SET',
142
+ score: 88,
143
+ sludgeTaxUsd: 0.01,
144
+ reclaimTokens: 11000,
145
+ recommendedAction: '/model gemini-3.8-flash • /effort medium (Optimal)',
146
+ rewrite: 'In @src/core/router.mjs add error handling to the dispatch function'
147
+ },
148
+ {
149
+ id: 3,
150
+ slug: 'subagent-steer',
151
+ title: 'Scenario 3: Hot Cache Subagent Steer (85k Tokens)',
152
+ complaint: 'Deep debugging polluted my main thread and ruined my warm 85k KV cache.',
153
+ fixture: SCENARIO_3_HOT_CONCURRENCY,
154
+ routerState: 'STEER_SUBAGENT',
155
+ score: 79,
156
+ sludgeTaxUsd: 0.02,
157
+ reclaimTokens: 18000,
158
+ recommendedAction: 'Delegate via invoke_subagent to preserve warm 85k parent KV cache',
159
+ rewrite: 'Use invoke_subagent (research) to isolate async concurrency deadlock in @src/queue.mjs'
160
+ },
161
+ {
162
+ id: 4,
163
+ slug: 'polluted-sludge',
164
+ title: 'Scenario 4: Polluted Context & Duplicate File Sludge ($0.07/turn)',
165
+ complaint: 'The agent read the same 600-line file 7 times and kept 5 old stack traces in memory!',
166
+ fixture: SCENARIO_4_POLLUTED_REFACTOR,
167
+ routerState: 'HALT_HYGIENE_OR_SAFETY',
168
+ score: 39,
169
+ sludgeTaxUsd: 0.07,
170
+ reclaimTokens: 58000,
171
+ recommendedAction: 'Run /compact or One-Click Surgical Pruner before High-effort refactor',
172
+ rewrite: 'After /compact: In @src/db/pool.mjs refactor connection retry backoff'
173
+ },
174
+ {
175
+ id: 5,
176
+ slug: 'amputation-crisis',
177
+ title: 'Scenario 5: Turn 50 Prefix Amputation Crisis (145k Tokens)',
178
+ complaint: 'Why did the agent suddenly ignore my AGENTS.md rules at turn 35 and break my architecture?!',
179
+ fixture: SCENARIO_5_AMPUTATION_CRISIS,
180
+ routerState: 'HALT_HYGIENE_OR_SAFETY',
181
+ score: 31,
182
+ sludgeTaxUsd: 0.09,
183
+ reclaimTokens: 84000,
184
+ recommendedAction: 'CRITICAL: Cells 1-8 (AGENTS.md) in Amputation Zone! Type /compact now',
185
+ rewrite: 'HALT: Reclaim 84k sludge tokens via /compact before adding billing endpoint'
186
+ },
187
+ {
188
+ id: 6,
189
+ slug: 'dirty-snap-drift',
190
+ title: 'Scenario 6: External Editor Dirty Snapshot & Unseen Callers',
191
+ complaint: 'I edited routes.mjs in VS Code and the agent blindly overwrote my fix with a stale snapshot!',
192
+ fixture: SCENARIO_6_PARALLEL_DRIFT,
193
+ routerState: 'INJECT_CONTEXT_GUARD',
194
+ score: 64,
195
+ sludgeTaxUsd: 0.02,
196
+ reclaimTokens: 6000,
197
+ recommendedAction: 'Re-read dirty @src/routes.mjs (modified on disk) & check unseen caller @src/app.mjs',
198
+ rewrite: 'Re-read @src/routes.mjs and inspect caller @src/app.mjs before updating server routes'
199
+ },
200
+ {
201
+ id: 7,
202
+ slug: 'quota-shield',
203
+ title: 'Scenario 7: 5-Hour Quota Floor Shield (8% Remaining)',
204
+ complaint: 'My 5-hour Pro/Opus quota evaporated in 40 minutes without warning!',
205
+ fixture: SCENARIO_7_QUOTA_SHIELD,
206
+ routerState: 'HALT_EFFORT_OR_QUOTA',
207
+ score: 52,
208
+ sludgeTaxUsd: 0.03,
209
+ reclaimTokens: 12000,
210
+ recommendedAction: 'QUOTA SHIELD (<10% left): Switch /model gemini-3.8-flash • /effort low',
211
+ rewrite: 'Switch to Flash/Low or wait for 5h bucket reset before generating architecture plan'
212
+ },
213
+ {
214
+ id: 8,
215
+ slug: 'stream-cutoff-check',
216
+ title: 'Scenario 8: #check 600-Line Stream Cutoff & Legacy Poison Guard',
217
+ complaint: 'It tried rewriting a 9,950-line legacy file in one shot and cut off mid-stream!',
218
+ fixture: SCENARIO_8_EXPLICIT_CHECK,
219
+ routerState: 'HALT_REWRITE_SCORECARD',
220
+ score: 85,
221
+ sludgeTaxUsd: 0.01,
222
+ reclaimTokens: 6000,
223
+ recommendedAction: '/model gemini-3.8-flash • Split 9,950-line @src/parser.mjs via chunked edits',
224
+ rewrite: 'In @src/parser.mjs extract tokenizer (lines 1-350) into @src/lexer.mjs using edit_file'
225
+ }
226
+ ];
227
+
228
+ /**
229
+ * Builds a complete, mathematically self-consistent 40-cell Horizon + Webview + HUD payload
230
+ * for any of the 8 demo scenarios.
231
+ */
232
+ export function buildDemoHorizonState(scenarioNumber = 5) {
233
+ const meta = DEMO_SCENARIOS.find(s => s.id === Number(scenarioNumber)) || DEMO_SCENARIOS[4];
234
+ const sc = meta.fixture.sidecar;
235
+ const totalActiveTokens = sc.telemetry.totalInputTokens || 145000;
236
+ const maxTokens = 200000;
237
+ const cellSize = 5000;
238
+ const activeCells = Math.min(40, Math.max(1, Math.ceil(totalActiveTokens / cellSize)));
239
+ const isCrisis = Boolean(sc.telemetry.amputationRisk || totalActiveTokens >= 140000);
240
+ const purity = sc.telemetry.signalPurityPct ?? 35.0;
241
+
242
+ const sludgeTokens = meta.reclaimTokens > 0
243
+ ? meta.reclaimTokens
244
+ : (purity >= 100 ? 0 : Math.round(totalActiveTokens * ((100 - purity) / 100)));
245
+
246
+ // Compute exact non-overlapping breakdown components summing to totalActiveTokens
247
+ const dupReadTokens = Math.round(sludgeTokens * 0.65);
248
+ const staleTurnTokens = Math.round(sludgeTokens * 0.15);
249
+ const deadErrorTokens = Math.max(0, sludgeTokens - dupReadTokens - staleTurnTokens);
250
+ const usefulTotalTokens = Math.max(0, totalActiveTokens - sludgeTokens);
251
+
252
+ const anchorTokens = totalActiveTokens <= 5000
253
+ ? Math.min(2000, usefulTotalTokens)
254
+ : Math.min(15000, Math.round(usefulTotalTokens * 0.30));
255
+ const injectedMemoryTokens = totalActiveTokens <= 5000
256
+ ? Math.min(500, Math.max(0, usefulTotalTokens - anchorTokens))
257
+ : Math.min(5000, Math.max(0, usefulTotalTokens - anchorTokens));
258
+ const activeWorkingSetTokens = Math.max(0, usefulTotalTokens - anchorTokens - injectedMemoryTokens);
259
+
260
+ const sludgeCellCount = sludgeTokens > 0 ? Math.max(1, Math.round(sludgeTokens / cellSize)) : 0;
261
+ const anchorCellCount = Math.max(1, Math.min(activeCells, Math.round((anchorTokens + injectedMemoryTokens) / cellSize) || 1));
262
+
263
+ const primaryActiveFile = (sc.fileState?.activeSetPaths && sc.fileState.activeSetPaths[0])
264
+ ? sc.fileState.activeSetPaths[0].replace(/^c:\/projects\/attention-horizon-antigravity\//i, '')
265
+ : (meta.id === 6 ? 'src/routes.mjs' : (meta.id === 8 ? 'src/parser.mjs' : 'src/core/router.mjs'));
266
+
267
+ const cells = [];
268
+ let remainingTokensToAssign = totalActiveTokens;
269
+ let assignedSludgeCells = 0;
270
+
271
+ for (let i = 0; i < 40; i++) {
272
+ let dominantCategory = 'FREE_HEADROOM';
273
+ let isCrisisCell = false;
274
+ const filled = i < activeCells ? Math.min(cellSize, Math.max(0, remainingTokensToAssign)) : 0;
275
+ remainingTokensToAssign = Math.max(0, remainingTokensToAssign - filled);
276
+
277
+ if (filled > 0) {
278
+ if (i < anchorCellCount - (injectedMemoryTokens >= 2500 ? 1 : 0)) {
279
+ dominantCategory = 'ANCHOR';
280
+ isCrisisCell = isCrisis;
281
+ } else if (i === anchorCellCount - 1 && injectedMemoryTokens >= 2500) {
282
+ dominantCategory = 'INJECTED_MEMORY';
283
+ isCrisisCell = isCrisis;
284
+ } else if (sludgeCellCount > 0 && assignedSludgeCells < sludgeCellCount && i >= anchorCellCount && i < activeCells - 1) {
285
+ assignedSludgeCells++;
286
+ if (meta.id === 6 && assignedSludgeCells === 1) {
287
+ dominantCategory = 'STALE_TURN';
288
+ } else if (deadErrorTokens >= 2000 && assignedSludgeCells % 3 === 0) {
289
+ dominantCategory = 'DEAD_ERROR';
290
+ } else {
291
+ dominantCategory = 'DUPLICATE_READ';
292
+ }
293
+ isCrisisCell = isCrisis && i < 8;
294
+ } else {
295
+ dominantCategory = 'ACTIVE_WORKING_SET';
296
+ isCrisisCell = isCrisis && i < 8;
297
+ }
298
+ }
299
+
300
+ const targetPath =
301
+ filled === 0 ? 'Free Token Headroom' :
302
+ i === 0 ? 'SYSTEM_PROMPT + AGENTS.md' :
303
+ i === 1 ? 'implementation_plan.md + task.md' :
304
+ i === 2 && dominantCategory === 'ANCHOR' ? 'MCP Tool Schemas (Turn 0)' :
305
+ i === 8 && dominantCategory !== 'DUPLICATE_READ' ? 'task.md' :
306
+ dominantCategory === 'DEAD_ERROR' ? 'src/cli/doctor.mjs (failed run_command trace)' :
307
+ dominantCategory === 'DUPLICATE_READ' ? primaryActiveFile :
308
+ dominantCategory === 'STALE_TURN' ? 'src/routes.mjs (stale snapshot before external edit)' :
309
+ primaryActiveFile;
310
+
311
+ const inTrough = activeCells >= 7 && i >= 6 && i <= 15 && i < activeCells;
312
+ cells.push({
313
+ index: i,
314
+ startToken: i * cellSize,
315
+ endToken: i * cellSize + filled,
316
+ totalTokens: filled,
317
+ dominantCategory,
318
+ topTarget: targetPath,
319
+ inAttentionTrough: inTrough,
320
+ attentionWeight: inTrough ? 0.42 : 0.92,
321
+ hudCategory:
322
+ dominantCategory === 'ANCHOR' ? (i === 2 ? 'ANCHOR_SCHEMA' : 'ANCHOR_CORE') :
323
+ dominantCategory === 'INJECTED_MEMORY' ? (meta.id === 5 ? 'MEMORY_BLEED' : 'MEMORY_KI') :
324
+ dominantCategory === 'DUPLICATE_READ' ? (meta.id === 6 ? 'DIRTY_SNAP' : 'STALE_DUP') :
325
+ dominantCategory === 'DEAD_ERROR' ? 'DEAD_ERROR' :
326
+ dominantCategory === 'ACTIVE_WORKING_SET' ? 'ACTIVE_SET' : 'FREE_HEADROOM',
327
+ isAmputationZone: i < 8,
328
+ isCrisisCell,
329
+ turnRange: filled > 0 ? [Math.max(0, i * 2 - 1), i * 2] : [-1, -1],
330
+ breakdown: { [dominantCategory]: filled },
331
+ topContributors: filled > 0 ? [{
332
+ category: dominantCategory,
333
+ tokens: filled,
334
+ target: targetPath,
335
+ stepIndex: i * 2,
336
+ foreignBleed: meta.id === 5 && i === 3
337
+ }] : []
338
+ });
339
+ }
340
+
341
+ const quotaRem = Math.round((sc.telemetry.quota?.remaining_fraction ?? 0.5) * 100);
342
+ const workloadMode =
343
+ meta.id === 3 ? { modeId: 'SUBAGENT_SWARM', tag: '[Mode: Subagent Swarm]' } :
344
+ (meta.id === 4 || meta.id === 8) ? { modeId: 'MULTI_FILE_REFACTOR', tag: '[Mode: Multi-File Refactor]' } :
345
+ { modeId: 'READ_HEAVY_AUDIT', tag: '[Mode: Read-Heavy Audit]' };
346
+
347
+ // Strictly scope topRiskyCells to filled cells in the attention trough (indices 6..15, i < activeCells)
348
+ const candidateRiskyCells = [
349
+ {
350
+ cellIndex: 6,
351
+ cellNumber: 7,
352
+ filePath: primaryActiveFile,
353
+ tokenWeight: 5000,
354
+ wasteTokens: sludgeTokens > 0 ? Math.min(5000, dupReadTokens) : 0,
355
+ attentionRecallPct: 44,
356
+ inTrough: true,
357
+ riskReason: sludgeTokens > 0 ? 'HIGH_SLUDGE_DENSITY' : 'TROUGH_STRANDED_SPEC',
358
+ actionType: sludgeTokens > 0 ? 'PRUNE' : 'REANCHOR',
359
+ actionLabel: '[Re-Anchor / Prune]',
360
+ specificActionLabel: sludgeTokens > 0 ? '[Prune Stale Tool Outputs]' : '[Re-Anchor Cell to Handoff]'
361
+ },
362
+ {
363
+ cellIndex: 8,
364
+ cellNumber: 9,
365
+ filePath: 'task.md',
366
+ tokenWeight: 5000,
367
+ wasteTokens: 0,
368
+ attentionRecallPct: 42,
369
+ inTrough: true,
370
+ riskReason: 'TROUGH_STRANDED_SPEC',
371
+ actionType: 'REANCHOR',
372
+ actionLabel: '[Re-Anchor / Prune]',
373
+ specificActionLabel: '[Re-Anchor Cell to Handoff]'
374
+ },
375
+ {
376
+ cellIndex: 11,
377
+ cellNumber: 12,
378
+ filePath: 'src/core/router.mjs',
379
+ tokenWeight: 5000,
380
+ wasteTokens: 5000,
381
+ attentionRecallPct: 40,
382
+ inTrough: true,
383
+ riskReason: 'HIGH_SLUDGE_DENSITY',
384
+ actionType: 'PRUNE',
385
+ actionLabel: '[Re-Anchor / Prune]',
386
+ specificActionLabel: '[Prune Stale Tool Outputs]'
387
+ }
388
+ ];
389
+ const topRiskyCells = candidateRiskyCells.filter(c => c.cellIndex < activeCells && cells[c.cellIndex]?.totalTokens > 0);
390
+
391
+ // Scope chronicReads and subagents to session maturity
392
+ const chronicReads = (meta.id === 1 || sludgeTokens === 0) ? [] : [
393
+ {
394
+ path: primaryActiveFile,
395
+ sessions: meta.id >= 4 && meta.id <= 5 ? 4 : 3,
396
+ windowSessions: 5,
397
+ wastedTokens: Math.min(35000, Math.max(6000, dupReadTokens)),
398
+ bannerText: `Across last 5 sessions, ${primaryActiveFile} caused ${Math.round(Math.min(35000, Math.max(6000, dupReadTokens)) / 1000)}k repeated re-reads`
399
+ }
400
+ ];
401
+
402
+ const hasSubagents = meta.id === 3 || meta.id === 5;
403
+ const subagents = hasSubagents ? {
404
+ count: 2,
405
+ totalChildTokens: 64000,
406
+ totalParentSummaryTokens: 1800,
407
+ overallCompressionRatio: 35.6,
408
+ tokensSaved: 62200,
409
+ invocations: [
410
+ {
411
+ stepIndex: 8,
412
+ role: 'Codebase Researcher',
413
+ typeName: 'research',
414
+ workspace: 'inherit',
415
+ workspaceMode: 'inherit',
416
+ childTokens: 38000,
417
+ summaryTokens: 950,
418
+ tokensSaved: 37050,
419
+ compressionRatio: 40.0,
420
+ badgeLabel: '[Subagent: research | 38.0k isolated -> 1.0k handoff (40x)]'
421
+ }
422
+ ]
423
+ } : {
424
+ count: 0,
425
+ totalChildTokens: 0,
426
+ totalParentSummaryTokens: 0,
427
+ overallCompressionRatio: 1.0,
428
+ tokensSaved: 0,
429
+ invocations: []
430
+ };
431
+
432
+ return {
433
+ schemaVersion: '1.1.0',
434
+ sessionId: meta.fixture.conversationId,
435
+ sessionTitle: meta.title,
436
+ demoMeta: meta,
437
+ routerState: meta.routerState,
438
+ recommendedAction: meta.recommendedAction,
439
+ rewrite: meta.rewrite,
440
+ storeSource: 'demo-synthetic',
441
+ logTierUsed: 1,
442
+ logFilePath: 'src/demo/synthetic_states.mjs',
443
+ workspace: {
444
+ canonicalPath: 'c:/projects/attention-horizon-antigravity',
445
+ projectId: 'attention-horizon-demo'
446
+ },
447
+ model: {
448
+ id: meta.fixture.modelName,
449
+ inputPricePerMillionUsd: resolvePricePerM(meta.fixture.modelName),
450
+ nativeCeilingTokens: resolveModelCeiling(meta.fixture.modelName, null, { useLegacyDefault: false })
451
+ },
452
+ window: {
453
+ maxTokens,
454
+ cellSizeTokens: cellSize,
455
+ totalCells: 40,
456
+ totalActiveTokens,
457
+ usedPercentage: parseFloat(((totalActiveTokens / maxTokens) * 100).toFixed(1)),
458
+ exceeds200kTokens: false,
459
+ turnCount: sc.sessionMeta.turnCount || 32,
460
+ safeLimit: 140000,
461
+ reminderAt: 119000
462
+ },
463
+ breakdown: {
464
+ ANCHOR: anchorTokens,
465
+ INJECTED_MEMORY: injectedMemoryTokens,
466
+ STALE_DUPLICATE: dupReadTokens + staleTurnTokens,
467
+ DUPLICATE_READ: dupReadTokens,
468
+ STALE_TURN: staleTurnTokens,
469
+ DEAD_ERROR: deadErrorTokens,
470
+ ACTIVE_WORKING_SET: activeWorkingSetTokens,
471
+ FREE_HEADROOM: Math.max(0, maxTokens - totalActiveTokens)
472
+ },
473
+ metrics: {
474
+ signalPurityPct: purity,
475
+ sludgeTokens,
476
+ sludgeTaxPerTurnUsd: meta.sludgeTaxUsd,
477
+ totalTurnCostUsd: parseFloat((meta.sludgeTaxUsd + 0.02).toFixed(4)),
478
+ healthBand: isCrisis ? 'CRISIS' : (purity < 60 ? 'DEGRADED' : 'OPTIMAL')
479
+ },
480
+ amputation: {
481
+ inAmputationZone: isCrisis,
482
+ bracketCells: [0, 7],
483
+ truncationRiskTokens: isCrisis ? 40000 : 0,
484
+ amputationCrisis: isCrisis,
485
+ anchorsAtRisk: isCrisis ? ['SYSTEM_PROMPT', 'AGENTS.md', 'implementation_plan.md', 'task.md'] : [],
486
+ activeDaemonsAtRisk: []
487
+ },
488
+ cells,
489
+ workloadMode,
490
+ topRiskyCells,
491
+ chronicReads,
492
+ offenders: sludgeTokens === 0 ? [
493
+ {
494
+ category: 'ANCHOR',
495
+ target: 'Turn-0 System & Workspace Rules (AGENTS.md)',
496
+ wastedTokens: 0,
497
+ occurrences: 1,
498
+ stepIndices: [0],
499
+ remediation: `Baseline clean (${(totalActiveTokens / 1000).toFixed(1)}k tokens); ${meta.rewrite}`
500
+ }
501
+ ] : [
502
+ {
503
+ category: 'DUPLICATE_READ',
504
+ target: primaryActiveFile,
505
+ wastedTokens: dupReadTokens,
506
+ occurrences: Math.max(2, Math.min(6, Math.floor((sc.sessionMeta.turnCount || 18) / 3))),
507
+ stepIndices: [3, 7, 14, 19, 26, 31].filter(s => s <= (sc.sessionMeta.turnCount || 32)),
508
+ remediation: `Fold superseded reads of ${primaryActiveFile} via Surgical Pruner or use read_file { Path: "${primaryActiveFile}", StartLine: 1, EndLine: 200 }`
509
+ },
510
+ {
511
+ category: 'DEAD_ERROR',
512
+ target: 'npm test (Resolved TypeError stack trace)',
513
+ wastedTokens: deadErrorTokens,
514
+ occurrences: Math.max(1, Math.min(3, Math.floor((sc.sessionMeta.turnCount || 18) / 6))),
515
+ stepIndices: [11, 12, 13].filter(s => s <= (sc.sessionMeta.turnCount || 32)),
516
+ remediation: 'Collapse resolved error traces into 1-line tombstones via Surgical Pruner or /compact'
517
+ },
518
+ {
519
+ category: 'STALE_TURN',
520
+ target: 'Older chat history (>25 turns ago)',
521
+ wastedTokens: staleTurnTokens,
522
+ occurrences: Math.max(1, Math.floor((sc.sessionMeta.turnCount || 18) / 6)),
523
+ stepIndices: [1, 2],
524
+ remediation: 'Summarize older turns when cache is cold via /compact'
525
+ }
526
+ ],
527
+ brainSignals: {
528
+ activeSignal: {
529
+ liveSessionTokens: usefulTotalTokens,
530
+ taskMdSaved: !isCrisis,
531
+ taskMdTurnsBehind: isCrisis ? 9 : (sludgeTokens === 0 ? 0 : 1),
532
+ semanticallyPinnedTurns: sludgeTokens === 0 ? 0 : 3
533
+ },
534
+ duplicateReads: sludgeTokens === 0 ? {
535
+ fileCount: 0,
536
+ reclaimableTokens: 0,
537
+ topFiles: []
538
+ } : {
539
+ fileCount: 2,
540
+ reclaimableTokens: dupReadTokens,
541
+ topFiles: [
542
+ { path: primaryActiveFile, occurrences: Math.max(2, Math.min(6, Math.floor((sc.sessionMeta.turnCount || 18) / 3))), wastedTokens: Math.round(dupReadTokens * 0.65) },
543
+ { path: 'src/webview/horizon_panel.html', occurrences: Math.max(2, Math.min(4, Math.floor((sc.sessionMeta.turnCount || 18) / 4))), wastedTokens: Math.max(0, dupReadTokens - Math.round(dupReadTokens * 0.65)) }
544
+ ]
545
+ },
546
+ oldHistory: {
547
+ turnCount: sludgeTokens === 0 ? 0 : Math.max(1, (sc.sessionMeta.turnCount || 20) - 5),
548
+ reclaimableTokens: staleTurnTokens
549
+ },
550
+ deadErrors: sludgeTokens === 0 ? {
551
+ errorCount: 0,
552
+ reclaimableTokens: 0,
553
+ isErrorLoop: false,
554
+ topErrors: []
555
+ } : {
556
+ errorCount: 3,
557
+ reclaimableTokens: deadErrorTokens,
558
+ isErrorLoop: meta.id === 5,
559
+ topErrors: [
560
+ { target: 'node --test (exit 1)', occurrences: 3, wastedTokens: deadErrorTokens }
561
+ ]
562
+ },
563
+ blowupSteps: sludgeTokens === 0 ? [] : [
564
+ {
565
+ stepIndex: Math.min(14, Math.max(1, (sc.sessionMeta.turnCount || 18) - 2)),
566
+ tokens: Math.min(18400, Math.round(totalActiveTokens * 0.25)),
567
+ category: 'DUPLICATE_READ',
568
+ target: primaryActiveFile,
569
+ payload: { kind: 'file', tool: 'read_file', detail: `${primaryActiveFile} (unclipped read)`, path: primaryActiveFile }
570
+ }
571
+ ],
572
+ userCorrections: isCrisis ? 4 : 0,
573
+ mcpAudit: {
574
+ unusedEagerServers: meta.id === 1 ? [] : [
575
+ { name: 'postgres-analytics', schemaTokens: 6800, configSource: '.agents/mcp_config.json' }
576
+ ]
577
+ },
578
+ activeDaemons: []
579
+ },
580
+ quota: {
581
+ sprint5h: {
582
+ remainingPct: quotaRem,
583
+ usedPct: 100 - quotaRem,
584
+ poolUnits: 5000000,
585
+ resetInMinutes: 142,
586
+ resetLabel: '2h 22m'
587
+ },
588
+ weekly7d: {
589
+ remainingPct: Math.min(100, quotaRem + 15),
590
+ usedPct: Math.max(0, 100 - Math.min(100, quotaRem + 15)),
591
+ sprintToWeeklyMultiplier: 2.8,
592
+ resetLabel: '4d 12h'
593
+ },
594
+ cache: {
595
+ hitRatePct: (meta.id === 2 || meta.id === 3 || meta.id === 6 || meta.id === 8)
596
+ ? (purity > 70 ? 86.4 : 62.0)
597
+ : 0,
598
+ cacheReadTokens: (meta.id === 2 || meta.id === 3 || meta.id === 6 || meta.id === 8) ? Math.round(totalActiveTokens * 0.62) : 0,
599
+ ttlRemainingSec: (meta.id === 2 || meta.id === 3 || meta.id === 6 || meta.id === 8) ? 215 : 0,
600
+ isCacheCold: !(meta.id === 2 || meta.id === 3 || meta.id === 6 || meta.id === 8),
601
+ nextTurnLikelyWarm: (meta.id === 2 || meta.id === 3 || meta.id === 6 || meta.id === 8),
602
+ cachedTokens: (meta.id === 2 || meta.id === 3 || meta.id === 6 || meta.id === 8) ? Math.round(totalActiveTokens * 0.62) : 0,
603
+ freshTokens: (meta.id === 2 || meta.id === 3 || meta.id === 6 || meta.id === 8) ? Math.round(totalActiveTokens * 0.38) : totalActiveTokens,
604
+ dualTtl: {
605
+ mainRemainingSec: (meta.id === 2 || meta.id === 3 || meta.id === 6 || meta.id === 8) ? 215 : 0,
606
+ mainWindowLabel: (meta.id === 2 || meta.id === 3) ? '1h' : '5m',
607
+ subagentRemainingSec: meta.id === 3 ? 180 : null,
608
+ subagentWindowLabel: '5m',
609
+ overageTtlCliffDetected: meta.id === 5 || meta.id === 7,
610
+ cliffWarning: (meta.id === 5 || meta.id === 7)
611
+ ? '1h -> 5m TTL Cliff Detected: Overage/fallback tier active; cache now expires 12x faster (300s).'
612
+ : ''
613
+ }
614
+ },
615
+ forecast: {
616
+ nextTurnHighSprintPct: 6.4,
617
+ turnsUntilExhaustion: Math.max(1, Math.floor(quotaRem / 6.4))
618
+ }
619
+ },
620
+ subagents,
621
+ coachState: {
622
+ routerState: meta.routerState,
623
+ recommendedAction: meta.recommendedAction,
624
+ rewrite: meta.rewrite,
625
+ taskQuotaRouter: {
626
+ activeModel: meta.fixture.modelName,
627
+ activeEffort: meta.fixture.effort,
628
+ recommendDownshift: meta.id === 7,
629
+ recommendedModelLabel: 'Gemini 3.8 Flash (Low)',
630
+ coachPillText: meta.routerState !== 'ALLOW_ACTIVE_SET' ? meta.recommendedAction : ''
631
+ }
632
+ },
633
+ diagnostics: {
634
+ status: isCrisis ? 'AMPUTATION_CRISIS' : (purity < 60 ? 'SLUDGE_HEAVY' : (meta.routerState !== 'ALLOW_ACTIVE_SET' ? meta.routerState : 'HEALTHY')),
635
+ headline: meta.title,
636
+ summary: `Complaint: "${meta.complaint}" — ${meta.recommendedAction}`,
637
+ recommendedCommand: isCrisis || purity < 55 ? '/compact' : meta.recommendedAction,
638
+ reclaimableTokens: sludgeTokens,
639
+ foreignBleedDetected: meta.id === 5,
640
+ dirtySnapshotPaths: sc.fileState?.dirtySnapshotPaths || (meta.id === 6 ? ['src/routes.mjs'] : []),
641
+ unseenCallers: sc.fileState?.unseenCallers || (meta.id === 6 ? ['src/app.mjs'] : [])
642
+ },
643
+ effortGovernor: {
644
+ activeProfile: {
645
+ id: meta.fixture.effort,
646
+ label: meta.fixture.effort.toUpperCase(),
647
+ safeLimit: 140000,
648
+ thinkingReserve: meta.fixture.effort === 'high' ? 25000 : 10000
649
+ },
650
+ recommendedEffort: isCrisis || meta.id === 7 ? 'low' : 'medium',
651
+ reason: meta.recommendedAction
652
+ },
653
+ hostHealth: {
654
+ rssGb: 0.84,
655
+ status: 'HEALTHY',
656
+ orphanCount: 0,
657
+ orphanRamMb: 0,
658
+ orphans: []
659
+ }
660
+ };
661
+ }