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,1504 @@
1
+ /**
2
+ * @file src/ui/modViews.mjs
3
+ * Multi-Surface UI Renderers for Claude Code Highbeam:
4
+ * 1. `AbovePrompt` Band: 1-line 40-Cell Horizon Bar + active Coach Pill (`OFF | COACH | AUTO_PILOT`)
5
+ * 2. Docked `Pane` (`/horizon`): Strict 5-Box Simple View vertical hierarchy (zero promotional text)
6
+ * 3. `Spinner` Suffix: Compact live status (`· Cache 95% (4m12s) · Saved $1.84`)
7
+ * 4. Terminal `statusLine`: Responsive ANSI single-line bar adapting to 80 / 110 / 144 columns
8
+ */
9
+
10
+ import {
11
+ computeHorizonGrid,
12
+ extractHorizonTokens,
13
+ isNoColorEnabled
14
+ } from './horizonGrid.mjs';
15
+ import { resolveEffectiveRates } from '../config/catalogLoader.mjs';
16
+ import {
17
+ computeBreakEvenCachedTokens,
18
+ resolveNaturalDownshiftPeer
19
+ } from '../coach/cacheGravityRouter.mjs';
20
+ import { formatRemainingTtl } from '../coach/ttlWatchdog.mjs';
21
+ import { SAVINGS_BUCKETS, getSavedQuotaReceiptSummary } from '../coach/savedQuotaLedger.mjs';
22
+ import {
23
+ formatRetentionCompact,
24
+ formatRetentionLabel,
25
+ formatDriftCompact,
26
+ formatDriftLabel
27
+ } from '../telemetry/sprintMetrics.mjs';
28
+ import { computeSwarmSummary, formatSwarmCompact } from '../telemetry/swarmTopology.mjs';
29
+
30
+ const ANSI_ESCAPE_REGEX = /\x1B\[[0-?]*[ -/]*[@-~]/g;
31
+
32
+ /**
33
+ * Formats seconds into `MM:SS` digital clock notation (e.g. `04:12`, `00:38`).
34
+ * @param {number} seconds
35
+ * @returns {string}
36
+ */
37
+ export function formatTtlClock(seconds = 0) {
38
+ const s = Math.max(0, Math.floor(Number(seconds || 0)));
39
+ const mins = Math.floor(s / 60);
40
+ const rem = s % 60;
41
+ return `${String(mins).padStart(2, '0')}:${String(rem).padStart(2, '0')}`;
42
+ }
43
+
44
+ /**
45
+ * Strips ANSI escape sequences to measure exact visible terminal column width.
46
+ * @param {string} text
47
+ * @returns {string}
48
+ */
49
+ export function stripAnsi(text = '') {
50
+ return String(text || '').replace(ANSI_ESCAPE_REGEX, '');
51
+ }
52
+
53
+ /**
54
+ * Truncates an ANSI-styled string to at most `maxCols` visible columns while stepping over
55
+ * `\x1b\[[0-9;]*m` (and CSI) sequences without counting them toward visible width (`ISS-050`).
56
+ * Appends `\x1b[0m` when truncation cuts off while color styling is active.
57
+ *
58
+ * @param {string} ansiStr
59
+ * @param {number} [maxCols=80]
60
+ * @returns {string}
61
+ */
62
+ export function truncateAnsiVisible(ansiStr = '', maxCols = 80) {
63
+ const str = String(ansiStr || '');
64
+ const limit = Math.max(0, Math.floor(Number(maxCols ?? 80)));
65
+ if (limit === 0) return '';
66
+ if (stripAnsi(str).length <= limit) return str;
67
+
68
+ const csiHeadRegex = /^\x1b\[[0-?]*[ -/]*[@-~]/;
69
+ let out = '';
70
+ let visible = 0;
71
+ let idx = 0;
72
+ let colorActive = false;
73
+
74
+ while (idx < str.length && visible < limit) {
75
+ if (str.charCodeAt(idx) === 0x1b) {
76
+ const match = csiHeadRegex.exec(str.slice(idx));
77
+ if (match) {
78
+ const seq = match[0];
79
+ out += seq;
80
+ if (seq === '\x1b[0m' || seq === '\x1b[m') {
81
+ colorActive = false;
82
+ } else if (seq.endsWith('m')) {
83
+ colorActive = true;
84
+ }
85
+ idx += seq.length;
86
+ continue;
87
+ }
88
+ }
89
+ const cp = str.codePointAt(idx);
90
+ const step = cp > 0xffff ? 2 : 1;
91
+ out += str.slice(idx, idx + step);
92
+ visible += 1;
93
+ idx += step;
94
+ }
95
+
96
+ if (colorActive && !out.endsWith('\x1b[0m')) {
97
+ out += '\x1b[0m';
98
+ }
99
+ return out;
100
+ }
101
+
102
+ /**
103
+ * Clamps a plain-text line to at most `maxCols` visible columns.
104
+ * @param {string} text
105
+ * @param {number} maxCols
106
+ * @returns {string}
107
+ */
108
+ function clampPlainLine(text = '', maxCols = 80) {
109
+ const str = String(text || '');
110
+ if (str.length <= maxCols) return str;
111
+ if (maxCols <= 1) return str.slice(0, maxCols);
112
+ return `${str.slice(0, maxCols - 1)}…`;
113
+ }
114
+
115
+ /**
116
+ * Formats a scale tick label (`0k`, `50k`, `100k`, `200k`, `500k`, `1M`).
117
+ * @param {number} tokens
118
+ * @returns {string}
119
+ */
120
+ function formatScaleTickLabel(tokens = 0) {
121
+ const n = Math.max(0, Math.round(Number(tokens || 0)));
122
+ if (n === 0) return '0k';
123
+ if (n >= 1_000_000) {
124
+ const m = n / 1_000_000;
125
+ return Number.isInteger(m) ? `${m}M` : `${Number(m.toFixed(2))}M`;
126
+ }
127
+ if (n >= 1_000) {
128
+ const k = n / 1_000;
129
+ return Number.isInteger(k) ? `${k}k` : `${Number(k.toFixed(1))}k`;
130
+ }
131
+ return String(n);
132
+ }
133
+
134
+ /**
135
+ * Builds a Tufte scale-tick ruler row (`0k ··· midpoint ··· ceiling`) aligned to `barSpan` columns (`ISS-050`).
136
+ * @param {number} ceilingTokens
137
+ * @param {number} [barSpan=42]
138
+ * @returns {string}
139
+ */
140
+ export function buildScaleTickRuler(ceilingTokens = 200000, barSpan = 42) {
141
+ const left = '0k';
142
+ const mid = formatScaleTickLabel(Math.round(ceilingTokens / 2));
143
+ const right = formatScaleTickLabel(ceilingTokens);
144
+ const minPlain = `${left} · ${mid} · ${right}`;
145
+ if (barSpan <= minPlain.length) {
146
+ return minPlain;
147
+ }
148
+ const totalDots = Math.max(2, barSpan - left.length - mid.length - right.length - 4);
149
+ const leftDots = Math.max(1, Math.floor(totalDots / 2));
150
+ const rightDots = Math.max(1, totalDots - leftDots);
151
+ return `${left} ${'·'.repeat(leftDots)} ${mid} ${'·'.repeat(rightDots)} ${right}`;
152
+ }
153
+
154
+ /**
155
+ * Formats token counts compactly (e.g. `0`, `950`, `45.0k`, `90.0k`, `210.0k`, `1.0M`).
156
+ * @param {number} tokens
157
+ * @returns {string}
158
+ */
159
+ export function formatTokensCompact(tokens = 0) {
160
+ const n = Math.max(0, Number(tokens || 0));
161
+ if (n >= 1000000) {
162
+ return `${(n / 1000000).toFixed(2).replace(/\.00$/, '')}M`;
163
+ }
164
+ if (n >= 1000) {
165
+ const k = n / 1000;
166
+ return `${k >= 100 ? Math.round(k) : Number(k.toFixed(1))}k`;
167
+ }
168
+ return String(Math.round(n));
169
+ }
170
+
171
+ /**
172
+ * Formats seconds into compact `XmYs` (e.g. `4m12s`, `38s`, `0s`).
173
+ * @param {number} seconds
174
+ * @returns {string}
175
+ */
176
+ export function formatDurationCompact(seconds = 0) {
177
+ const s = Math.max(0, Math.floor(Number(seconds || 0)));
178
+ const mins = Math.floor(s / 60);
179
+ const rem = s % 60;
180
+ if (mins > 0) {
181
+ return `${mins}m${String(rem).padStart(2, '0')}s`;
182
+ }
183
+ return `${rem}s`;
184
+ }
185
+
186
+ /**
187
+ * Formats USD amount (`$0.00`, `$1.84`).
188
+ * @param {number} usd
189
+ * @returns {string}
190
+ */
191
+ export function formatUsd(usd = 0) {
192
+ const val = Math.max(0, Number(usd || 0));
193
+ return `$${val.toFixed(2)}`;
194
+ }
195
+
196
+ /**
197
+ * Computes live cache hit percentage, remaining TTL seconds, and total saved USD/tokens
198
+ * from telemetry state, optional TTL tick, and optional ledger summary.
199
+ *
200
+ * @param {object} [state={}]
201
+ * @param {object} [options={}]
202
+ */
203
+ export function deriveSurfaceMetrics(state = {}, options = {}) {
204
+ const nowMs = options.nowMs || Date.now();
205
+ const cw = state.contextWindow || {};
206
+ const pc = state.promptCache || {};
207
+ const roi = state.cacheRoi || {};
208
+ const cumulative = state.cumulative || {};
209
+ const extracted = extractHorizonTokens(state);
210
+
211
+ const totalInputTokens = Math.max(
212
+ 0,
213
+ Number(
214
+ cw.totalInputTokens ??
215
+ state.totalInputTokens ??
216
+ state.totalTokens ??
217
+ extracted.totalInputTokens ??
218
+ 0
219
+ )
220
+ );
221
+ const warmPrefixTokens = Math.max(
222
+ 0,
223
+ Number(
224
+ cw.warmPrefixTokens ??
225
+ cw.cachedTokens ??
226
+ state.cachedTokens ??
227
+ state.cacheReadTokens ??
228
+ extracted.cachedHistoryTokens ??
229
+ 0
230
+ )
231
+ );
232
+ const cacheWriteTokens = Math.max(
233
+ 0,
234
+ Number(
235
+ cw.cacheWriteTokens ??
236
+ cw.lastWriteTokens ??
237
+ state.cacheWriteTokens ??
238
+ state.lastWriteTokens ??
239
+ 0
240
+ )
241
+ );
242
+ const hasExplicitCacheRead =
243
+ cw.cacheReadTokens !== undefined || state.cacheReadTokens !== undefined;
244
+ const cacheReadTokens = hasExplicitCacheRead
245
+ ? Math.max(0, Number(cw.cacheReadTokens ?? state.cacheReadTokens ?? 0))
246
+ : Math.max(0, warmPrefixTokens - cacheWriteTokens);
247
+
248
+ const cachedTokens = warmPrefixTokens;
249
+
250
+ // ISS-006: Check typeof roi.cacheHitRatio === 'number' (including 0, NEVER > 0!) when ROI was evaluated,
251
+ // and fall back to cacheReadTokens / totalInputTokens so Turn-1 cold writes render Cache 0%
252
+ const hasEvaluatedRoi =
253
+ typeof roi.cacheHitRatio === 'number' &&
254
+ (state.lastSource !== 'init' || roi.cacheHitRatio > 0 || Number(roi.actualCacheSpendUSD || 0) > 0);
255
+ const hitRatio = hasEvaluatedRoi
256
+ ? roi.cacheHitRatio
257
+ : totalInputTokens > 0
258
+ ? cacheReadTokens / totalInputTokens
259
+ : 0;
260
+ const cacheHitPct = Math.max(0, Math.min(100, Math.round(hitRatio * 100)));
261
+
262
+ let parsedExpiresAtMs = null;
263
+ if (typeof pc.expiresAt === 'number' && Number.isFinite(pc.expiresAt)) {
264
+ parsedExpiresAtMs = pc.expiresAt < 1e11 ? pc.expiresAt * 1000 : pc.expiresAt;
265
+ } else if (typeof pc.expiresAt === 'string' && pc.expiresAt.trim()) {
266
+ const parsed = Date.parse(pc.expiresAt);
267
+ if (!Number.isNaN(parsed)) parsedExpiresAtMs = parsed;
268
+ }
269
+
270
+ const explicitTtlOpt =
271
+ options.ttlRemainingSeconds ??
272
+ options.ttlRemainingSec ??
273
+ state.ttlRemainingSeconds ??
274
+ state.ttlRemainingSec ??
275
+ pc.ttlRemainingSec;
276
+
277
+ const hasExplicitTtlField =
278
+ typeof explicitTtlOpt === 'number' ||
279
+ (options.ttlTick && typeof options.ttlTick.remainingSeconds === 'number') ||
280
+ parsedExpiresAtMs !== null ||
281
+ typeof pc.ttlSeconds === 'number' ||
282
+ typeof state.ttlSeconds === 'number';
283
+
284
+ const hasExplicitWarm = typeof pc.warm === 'boolean' || typeof state.cacheWarm === 'boolean';
285
+ const explicitWarmVal = typeof pc.warm === 'boolean' ? pc.warm : Boolean(state.cacheWarm);
286
+
287
+ let remainingSeconds = 0;
288
+ if (typeof explicitTtlOpt === 'number') {
289
+ remainingSeconds = Math.max(0, Math.floor(explicitTtlOpt));
290
+ } else if (options.ttlTick && typeof options.ttlTick.remainingSeconds === 'number') {
291
+ remainingSeconds = Math.max(0, Math.floor(options.ttlTick.remainingSeconds));
292
+ } else if (parsedExpiresAtMs !== null) {
293
+ remainingSeconds = Math.max(0, Math.floor((parsedExpiresAtMs - nowMs) / 1000));
294
+ } else if (typeof pc.ttlSeconds === 'number') {
295
+ remainingSeconds = Math.max(0, Math.floor(pc.ttlSeconds));
296
+ } else if (typeof state.ttlSeconds === 'number') {
297
+ remainingSeconds = Math.max(0, Math.floor(state.ttlSeconds));
298
+ } else if (!hasExplicitTtlField && hasExplicitWarm && explicitWarmVal) {
299
+ remainingSeconds = pc.ttlTier === '1h' ? 3600 : 300;
300
+ }
301
+
302
+ // ISS-027: Never allow cacheWarm = true when remainingSeconds <= 0!
303
+ const cacheWarm = hasExplicitWarm
304
+ ? Boolean(explicitWarmVal && remainingSeconds > 0)
305
+ : Boolean(warmPrefixTokens > 0 && remainingSeconds > 0);
306
+ if (!cacheWarm) {
307
+ remainingSeconds = 0;
308
+ }
309
+
310
+ const amberAlert = Boolean(
311
+ cacheWarm &&
312
+ (options.ttlTick?.amberAlertActive ||
313
+ (remainingSeconds > 0 && remainingSeconds <= 45 && cachedTokens >= 25000))
314
+ );
315
+
316
+ const ledgerSummary =
317
+ options.ledgerSummary ||
318
+ (options.includeDiskLedger !== false
319
+ ? getSavedQuotaReceiptSummary({
320
+ ...options,
321
+ activeSessionId: state.sessionId || options.sessionId || 'default'
322
+ })
323
+ : null);
324
+
325
+ const ledgerTokens = Math.max(0, Number(ledgerSummary?.totalSavedTokens || 0));
326
+ const ledgerUSD = Math.max(0, Number(ledgerSummary?.totalSavedUSD || 0));
327
+ const sessionNetSavingsUSD = Math.max(
328
+ 0,
329
+ Number(cumulative.netCacheSavingsUSD ?? roi.netCacheSavingsUSD ?? 0)
330
+ );
331
+ const liveSessionCacheReadTokens = Math.max(
332
+ 0,
333
+ Math.round(Number(cumulative.cacheReadTokens ?? state.savedTokensTotal ?? 0))
334
+ );
335
+
336
+ // Subagent isolated tokens from Task/Agent workers in state.subagents
337
+ let liveSubagentIsolatedTokens = 0;
338
+ if (state.subagents && typeof state.subagents === 'object') {
339
+ for (const worker of Object.values(state.subagents)) {
340
+ liveSubagentIsolatedTokens += Math.max(0, Math.round(Number(worker?.totalTokens || 0)));
341
+ }
342
+ }
343
+ const activeRatesForSub = resolveEffectiveRates(
344
+ state.rawModelId || state.modelId || state.model || 'claude-sonnet-5-5',
345
+ totalInputTokens,
346
+ options
347
+ );
348
+ const liveSubagentIsolatedUSD =
349
+ activeRatesForSub && !activeRatesForSub.unknownModel && Number.isFinite(activeRatesForSub.inputPer1M)
350
+ ? Number(((liveSubagentIsolatedTokens / 1_000_000) * activeRatesForSub.inputPer1M).toFixed(6))
351
+ : 0;
352
+
353
+ // Use explicit options.savedUSD / options.savedTokens if passed, else max of ledger + session
354
+ const savedUSD =
355
+ typeof options.savedUSD === 'number'
356
+ ? Math.max(0, options.savedUSD)
357
+ : Number(Math.max(ledgerUSD, sessionNetSavingsUSD).toFixed(2));
358
+ const savedTokens =
359
+ typeof options.savedTokens === 'number'
360
+ ? Math.max(0, Math.round(options.savedTokens))
361
+ : Math.max(ledgerTokens, liveSessionCacheReadTokens);
362
+
363
+ const rawSessionTokens = Math.max(
364
+ Number(ledgerSummary?.sessionSavedTokens || 0),
365
+ liveSessionCacheReadTokens + liveSubagentIsolatedTokens,
366
+ typeof options.savedTokens === 'number' ? Math.max(0, Math.round(options.savedTokens)) : 0
367
+ );
368
+ const rawSessionUSD = Math.max(
369
+ Number(ledgerSummary?.sessionSavedUSD || 0),
370
+ sessionNetSavingsUSD + liveSubagentIsolatedUSD,
371
+ typeof options.savedUSD === 'number' ? Math.max(0, options.savedUSD) : 0
372
+ );
373
+ const sessionSavedTokens = Math.max(0, Math.round(options.sessionSavedTokens ?? rawSessionTokens));
374
+ const sessionSavedUSD = Number(
375
+ Math.max(0, Number(options.sessionSavedUSD ?? rawSessionUSD)).toFixed(2)
376
+ );
377
+ const workspace30dSavedTokens = Math.max(
378
+ sessionSavedTokens,
379
+ savedTokens,
380
+ Math.round(Number(options.workspace30dSavedTokens ?? ledgerSummary?.workspace30dSavedTokens ?? 0))
381
+ );
382
+ const workspace30dSavedUSD = Number(
383
+ Math.max(
384
+ sessionSavedUSD,
385
+ savedUSD,
386
+ Number(options.workspace30dSavedUSD ?? ledgerSummary?.workspace30dSavedUSD ?? 0)
387
+ ).toFixed(2)
388
+ );
389
+
390
+ // Build 5-category savings breakdown combining ledger + live session telemetry
391
+ const baseCats = ledgerSummary?.categories || {};
392
+ const savingsCategories = {
393
+ cacheReadDiscount: {
394
+ id: 'cacheReadDiscount',
395
+ label: SAVINGS_BUCKETS.cacheReadDiscount.label,
396
+ shortLabel: SAVINGS_BUCKETS.cacheReadDiscount.shortLabel,
397
+ savedTokens: Math.max(
398
+ Number(baseCats.cacheReadDiscount?.savedTokens || 0),
399
+ liveSessionCacheReadTokens
400
+ ),
401
+ savedUSD: Number(
402
+ Math.max(
403
+ Number(baseCats.cacheReadDiscount?.savedUSD || 0),
404
+ sessionNetSavingsUSD
405
+ ).toFixed(4)
406
+ ),
407
+ count: Math.max(
408
+ Number(baseCats.cacheReadDiscount?.count || 0),
409
+ liveSessionCacheReadTokens > 0 ? Math.max(1, Number(state.turnsCompleted || 1)) : 0
410
+ )
411
+ },
412
+ prefixBustAvoided: {
413
+ id: 'prefixBustAvoided',
414
+ label: SAVINGS_BUCKETS.prefixBustAvoided.label,
415
+ shortLabel: SAVINGS_BUCKETS.prefixBustAvoided.shortLabel,
416
+ savedTokens: Math.max(0, Number(baseCats.prefixBustAvoided?.savedTokens || 0)),
417
+ savedUSD: Number(Math.max(0, Number(baseCats.prefixBustAvoided?.savedUSD || 0)).toFixed(4)),
418
+ count: Math.max(0, Number(baseCats.prefixBustAvoided?.count || 0))
419
+ },
420
+ toolOutputCompressed: {
421
+ id: 'toolOutputCompressed',
422
+ label: SAVINGS_BUCKETS.toolOutputCompressed.label,
423
+ shortLabel: SAVINGS_BUCKETS.toolOutputCompressed.shortLabel,
424
+ savedTokens: Math.max(0, Number(baseCats.toolOutputCompressed?.savedTokens || 0)),
425
+ savedUSD: Number(Math.max(0, Number(baseCats.toolOutputCompressed?.savedUSD || 0)).toFixed(4)),
426
+ count: Math.max(0, Number(baseCats.toolOutputCompressed?.count || 0))
427
+ },
428
+ loopAndReadGuarded: {
429
+ id: 'loopAndReadGuarded',
430
+ label: SAVINGS_BUCKETS.loopAndReadGuarded.label,
431
+ shortLabel: SAVINGS_BUCKETS.loopAndReadGuarded.shortLabel,
432
+ savedTokens: Math.max(0, Number(baseCats.loopAndReadGuarded?.savedTokens || 0)),
433
+ savedUSD: Number(Math.max(0, Number(baseCats.loopAndReadGuarded?.savedUSD || 0)).toFixed(4)),
434
+ count: Math.max(0, Number(baseCats.loopAndReadGuarded?.count || 0))
435
+ },
436
+ subagentIsolated: {
437
+ id: 'subagentIsolated',
438
+ label: SAVINGS_BUCKETS.subagentIsolated.label,
439
+ shortLabel: SAVINGS_BUCKETS.subagentIsolated.shortLabel,
440
+ savedTokens: Math.max(
441
+ Number(baseCats.subagentIsolated?.savedTokens || 0),
442
+ liveSubagentIsolatedTokens
443
+ ),
444
+ savedUSD: Number(
445
+ Math.max(
446
+ Number(baseCats.subagentIsolated?.savedUSD || 0),
447
+ liveSubagentIsolatedUSD
448
+ ).toFixed(4)
449
+ ),
450
+ count: Math.max(
451
+ Number(baseCats.subagentIsolated?.count || 0),
452
+ liveSubagentIsolatedTokens > 0 ? Object.keys(state.subagents || {}).length : 0
453
+ )
454
+ }
455
+ };
456
+
457
+ let topSavingsDriver = savingsCategories.cacheReadDiscount;
458
+ for (const bucket of Object.values(savingsCategories)) {
459
+ if (
460
+ bucket.savedTokens > topSavingsDriver.savedTokens ||
461
+ (bucket.savedTokens === topSavingsDriver.savedTokens &&
462
+ bucket.savedUSD > topSavingsDriver.savedUSD)
463
+ ) {
464
+ topSavingsDriver = bucket;
465
+ }
466
+ }
467
+
468
+ const flightMode = String(
469
+ options.flightMode || state.flightMode || 'COACH'
470
+ ).toUpperCase();
471
+
472
+ const ttlTier = pc.ttlTier === '1h' ? '1h' : '5m';
473
+ let breakEvenReadsPerWrite = 0.263;
474
+ if (typeof roi.breakEvenReadsPerWrite === 'number' && roi.breakEvenReadsPerWrite > 0 && state.lastSource !== 'init') {
475
+ breakEvenReadsPerWrite = roi.breakEvenReadsPerWrite;
476
+ } else {
477
+ const activeRates = resolveEffectiveRates(
478
+ state.rawModelId || state.modelId || state.model || 'claude-sonnet-5-5',
479
+ totalInputTokens,
480
+ options
481
+ );
482
+ if (activeRates && !activeRates.unknownModel && activeRates.multipliers) {
483
+ const mWrite =
484
+ ttlTier === '1h' ? activeRates.multipliers.write1h : activeRates.multipliers.write5m;
485
+ const mRead = activeRates.multipliers.read;
486
+ breakEvenReadsPerWrite = Number(((mWrite - 1) / (1 - mRead)).toFixed(3));
487
+ } else {
488
+ breakEvenReadsPerWrite = null;
489
+ }
490
+ }
491
+ const sessionFiveMinRoiTarget = Number(roi.sessionFiveMinRoiTarget || 1.39);
492
+
493
+ const hasEvaluatedRwRatio =
494
+ typeof roi.readsPerWriteRatio === 'number' &&
495
+ (state.lastSource !== 'init' || roi.readsPerWriteRatio > 0 || Number(roi.actualCacheSpendUSD || 0) > 0);
496
+ const derivedRwRatio = hasEvaluatedRwRatio
497
+ ? roi.readsPerWriteRatio
498
+ : cacheWriteTokens > 0
499
+ ? cacheReadTokens / cacheWriteTokens
500
+ : cacheReadTokens > 0
501
+ ? Infinity
502
+ : 0;
503
+ const readsPerWriteRatio = Math.max(0, Number(derivedRwRatio || 0));
504
+ const negativeCacheRoi =
505
+ typeof roi.negativeCacheRoi === 'boolean' && state.lastSource !== 'init'
506
+ ? roi.negativeCacheRoi
507
+ : cacheWriteTokens > 0 && readsPerWriteRatio < breakEvenReadsPerWrite;
508
+
509
+ return {
510
+ totalInputTokens,
511
+ cachedTokens,
512
+ cacheReadTokens,
513
+ cacheWriteTokens,
514
+ warmPrefixTokens,
515
+ cacheHitPct,
516
+ cacheWarm,
517
+ remainingSeconds,
518
+ ttlCompact: cacheWarm ? formatDurationCompact(remainingSeconds) : 'COLD',
519
+ ttlClock: cacheWarm ? formatTtlClock(remainingSeconds) : '00:00',
520
+ ttlTier,
521
+ amberAlert,
522
+ savedUSD,
523
+ savedTokens,
524
+ sessionSavedTokens,
525
+ sessionSavedUSD,
526
+ workspace30dSavedTokens,
527
+ workspace30dSavedUSD,
528
+ savingsCategories,
529
+ topSavingsDriver,
530
+ flightMode: ['OFF', 'COACH', 'AUTO_PILOT'].includes(flightMode) ? flightMode : 'COACH',
531
+ negativeCacheRoi,
532
+ readsPerWriteRatio,
533
+ breakEvenReadsPerWrite,
534
+ sessionFiveMinRoiTarget
535
+ };
536
+ }
537
+
538
+ /**
539
+ * Checks whether a path is a lockfile, log, build artifact, or scratch file eligible
540
+ * for a `.claudeignore` recommendation (never active source code files).
541
+ *
542
+ * @param {string} [filePath='']
543
+ * @returns {boolean}
544
+ */
545
+ export function isIgnorableClaudePath(filePath = '') {
546
+ const s = String(filePath || '').trim();
547
+ if (!s) return false;
548
+ return /(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|go\.sum|\.(?:log|tmp|bak|min\.js|min\.css|map|bundle\.js)$|(?:^|[\\/])(?:dist|build|coverage|\.next|out|node_modules|\.claude[\\/]cache)[\\/])/i.test(
549
+ s
550
+ );
551
+ }
552
+
553
+ /**
554
+ * Derives plain-English Claude Code status verdict and prioritized action cards
555
+ * for Simple View (Rank 1 & Rank 3) and Advanced View.
556
+ *
557
+ * @param {object} [state={}]
558
+ * @param {object} grid
559
+ * @param {object} metrics
560
+ * @param {object} [options={}]
561
+ */
562
+ export function deriveClaudeCodeVerdictAndActions(state = {}, grid, metrics, options = {}) {
563
+ const actions = [];
564
+ let verdict = {
565
+ severity: 'healthy',
566
+ badge: 'HEALTHY',
567
+ headline: metrics.cacheWarm
568
+ ? `Healthy — Prompt Cache Warm (${metrics.ttlCompact})`
569
+ : 'Ready — Cold Prompt Prefix',
570
+ detail: metrics.cacheWarm
571
+ ? `${metrics.cacheHitPct}% of prompt reading at 0.10x cached rates (${metrics.ttlTier} TTL)`
572
+ : 'Next turn establishes the 5m warm prompt cache prefix'
573
+ };
574
+
575
+ const reclaimEstimate = Math.max(
576
+ grid.tokens.D,
577
+ Math.round(grid.totalInputTokens * 0.35)
578
+ );
579
+
580
+ if (options.breakerVerdict?.triggered) {
581
+ const breakerId =
582
+ options.breakerVerdict.detectorId || options.breakerVerdict.ruleId || 'BREAKER';
583
+ const reasonText =
584
+ options.breakerVerdict.reason || 'Circuit breaker triggered on active tool or model call';
585
+ verdict = {
586
+ severity: 'critical',
587
+ badge: 'CRITICAL',
588
+ headline: `${breakerId} Active — Guard Intervention`,
589
+ detail: reasonText
590
+ };
591
+ actions.push({
592
+ id: breakerId.toLowerCase(),
593
+ severity: 'critical',
594
+ title: `Resolve ${breakerId} guard before continuing`,
595
+ instruction: reasonText,
596
+ commandHint: `npx ah-claude config set ${breakerId} warn`,
597
+ reclaimTokens: 0
598
+ });
599
+ }
600
+
601
+ if (state.thinkingDrift?.loop?.triggered) {
602
+ const ratio = state.thinkingDrift.lastDriftRatio ?? 'high';
603
+ if (verdict.severity !== 'critical') {
604
+ verdict = {
605
+ severity: 'critical',
606
+ badge: 'CRITICAL',
607
+ headline: `Critical — Scratchpad Loop Detected (${ratio}x)`,
608
+ detail:
609
+ state.thinkingDrift.loop.message ||
610
+ `DET-21: Thinking tokens exceeded ${ratio}x output tokens with zero file edits`
611
+ };
612
+ }
613
+ actions.push({
614
+ id: 'det-21-loop',
615
+ severity: 'critical',
616
+ title: `Break ${ratio}x thinking loop`,
617
+ instruction:
618
+ 'Add a concrete target file path and test constraint to your next prompt, or lower /effort.',
619
+ commandHint: '/effort medium',
620
+ reclaimTokens: Math.max(0, Number(state.contextWindow?.lastThinkingTokens || 4000))
621
+ });
622
+ }
623
+
624
+ if (state.cliffTriggered) {
625
+ if (verdict.severity !== 'critical') {
626
+ verdict = {
627
+ severity: 'critical',
628
+ badge: 'CRITICAL',
629
+ headline: 'Critical — Haiku 5.5 100k 5x Pricing Cliff Exceeded',
630
+ detail: 'Total prompt exceeded 100,000 tokens ($0.10 -> $0.50/1M input step-up)'
631
+ };
632
+ }
633
+ actions.push({
634
+ id: 'det-12-cliff',
635
+ severity: 'critical',
636
+ title: 'Exit Haiku 100k 5x pricing cliff now',
637
+ instruction: `Type /compact in the chat box and press Enter to drop below 100k tokens (reclaims ~${formatTokensCompact(reclaimEstimate)}).`,
638
+ commandHint: 'Type /compact in the chat box and press Enter',
639
+ reclaimTokens: reclaimEstimate
640
+ });
641
+ } else if (state.preCliffWarningTriggered) {
642
+ if (verdict.severity === 'healthy') {
643
+ verdict = {
644
+ severity: 'warn',
645
+ badge: 'ACTION NEEDED',
646
+ headline: 'Approaching Haiku 100k 5x Pricing Cliff (>= 90k)',
647
+ detail: 'Compact before 100,000 tokens to avoid the 5x Haiku rate step-up'
648
+ };
649
+ }
650
+ actions.push({
651
+ id: 'det-12-precliff',
652
+ severity: 'warn',
653
+ title: 'Compact before crossing 100k Haiku cliff',
654
+ instruction: `Type /compact in the chat box and press Enter to reclaim ~${formatTokensCompact(reclaimEstimate)} before 100k.`,
655
+ commandHint: 'Type /compact in the chat box and press Enter',
656
+ reclaimTokens: reclaimEstimate
657
+ });
658
+ }
659
+
660
+ if (metrics.amberAlert) {
661
+ if (verdict.severity === 'healthy') {
662
+ verdict = {
663
+ severity: 'warn',
664
+ badge: 'CACHE EXPIRING',
665
+ headline: `5m Prompt Cache Expiring in ${metrics.ttlCompact}`,
666
+ detail: `${formatTokensCompact(metrics.cachedTokens)} warm prefix will go cold in ${metrics.ttlClock}`
667
+ };
668
+ }
669
+ actions.push({
670
+ id: 'det-10-ttl',
671
+ severity: 'warn',
672
+ title: `Send next prompt within ${metrics.ttlCompact} or hold prefix edits`,
673
+ instruction:
674
+ 'Keep coding to refresh the 5m TTL at 0.10x read cost, and hold CLAUDE.md or .mcp.json edits until PostCompact.',
675
+ commandHint: '/handoff',
676
+ reclaimTokens: metrics.cachedTokens
677
+ });
678
+ }
679
+
680
+ if (grid.tokens.D >= 25000 || grid.utilizationPct >= 75) {
681
+ if (verdict.severity === 'healthy') {
682
+ verdict = {
683
+ severity: 'warn',
684
+ badge: 'ACTION NEEDED',
685
+ headline:
686
+ metrics.cacheWarm && metrics.remainingSeconds > 60
687
+ ? `Stale Tool Debt High (${formatTokensCompact(grid.tokens.D)}) — Compact After Cache Window`
688
+ : `Context ${grid.utilizationPct}% Full — Compact Recommended`,
689
+ detail: `${formatTokensCompact(grid.tokens.D)} in middle-window distractors [D]`
690
+ };
691
+ }
692
+ if (metrics.cacheWarm && metrics.remainingSeconds > 60) {
693
+ actions.push({
694
+ id: 'compact-cache-gated',
695
+ severity: 'warn',
696
+ title: `Wait ${metrics.ttlCompact} for warm cache, then compact (~${formatTokensCompact(reclaimEstimate)} reclaimable)`,
697
+ instruction: `Finish your current step while ${formatTokensCompact(metrics.cachedTokens)} is warm (${metrics.ttlCompact} left), then: Type /compact in the chat box and press Enter`,
698
+ commandHint: 'Type /compact in the chat box and press Enter',
699
+ reclaimTokens: reclaimEstimate
700
+ });
701
+ } else {
702
+ actions.push({
703
+ id: 'compact-now',
704
+ severity: 'warn',
705
+ title: `Compact context now (~${formatTokensCompact(reclaimEstimate)} reclaimable)`,
706
+ instruction: 'Type /compact in the chat box and press Enter',
707
+ commandHint: 'Type /compact in the chat box and press Enter',
708
+ reclaimTokens: reclaimEstimate
709
+ });
710
+ }
711
+ }
712
+
713
+ if (metrics.negativeCacheRoi) {
714
+ if (verdict.severity === 'healthy') {
715
+ verdict = {
716
+ severity: 'warn',
717
+ badge: 'CACHE ROI WARN',
718
+ headline: 'Cache Write Surcharge Exceeds Read Discount',
719
+ detail: `Reads/Write ${metrics.readsPerWriteRatio.toFixed(2)} < ${metrics.breakEvenReadsPerWrite} break-even`
720
+ };
721
+ }
722
+ actions.push({
723
+ id: 'negative-roi',
724
+ severity: 'warn',
725
+ title: 'Hold CLAUDE.md, .claude/rules/, and .mcp.json mutations',
726
+ instruction: `Keep prefix static for at least 2 turns so 0.10x cache reads amortize the 1.25x write surcharge.`,
727
+ commandHint: 'Hold prefix edits until /compact',
728
+ reclaimTokens: metrics.cacheWriteTokens
729
+ });
730
+ }
731
+
732
+ if (actions.length === 0) {
733
+ actions.push({
734
+ id: 'keep-coding',
735
+ severity: 'healthy',
736
+ title: metrics.cacheWarm
737
+ ? `Keep coding — warm prefix active (${metrics.ttlCompact} remaining)`
738
+ : 'Keep coding — context headroom is clean',
739
+ instruction: metrics.cacheWarm
740
+ ? `Hold model switches and CLAUDE.md edits while ${formatTokensCompact(metrics.cachedTokens)} is reading at 0.10x.`
741
+ : 'No compaction or intervention needed right now.',
742
+ commandHint: '',
743
+ reclaimTokens: 0
744
+ });
745
+ }
746
+
747
+ const priorityAction = actions[0];
748
+ const secondaryActions = actions.slice(1);
749
+
750
+ return {
751
+ verdict,
752
+ priorityAction,
753
+ secondaryActions,
754
+ overflowActionCount: secondaryActions.length
755
+ };
756
+ }
757
+
758
+ /**
759
+ * 1. Renders the `AbovePrompt` 1-line Band with the 40-Cell Horizon Bar and active Coach Pill.
760
+ *
761
+ * @param {object} [state={}]
762
+ * @param {object} [options={}]
763
+ * @returns {{
764
+ * line: string,
765
+ * plainLine: string,
766
+ * grid: object,
767
+ * metrics: object,
768
+ * coachPill: string
769
+ * }}
770
+ */
771
+ export function renderAbovePromptBand(state = {}, options = {}) {
772
+ const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
773
+ const useAnsi = Boolean(options.ansi) && !isNoColorEnabled(options);
774
+ const grid = computeHorizonGrid(state, options);
775
+ const metrics = deriveSurfaceMetrics(state, options);
776
+
777
+ let coachAction = 'HOLD WARM PREFIX';
778
+ if (options.breakerVerdict?.triggered) {
779
+ const breakerId =
780
+ options.breakerVerdict.detectorId || options.breakerVerdict.ruleId || 'BREAKER';
781
+ coachAction = `${breakerId} ACTIVE`;
782
+ } else if (state.thinkingDrift?.loop?.triggered) {
783
+ coachAction = `THINK LOOP ${state.thinkingDrift.lastDriftRatio ?? ''}x`;
784
+ } else if (state.cliffTriggered) {
785
+ coachAction = 'HAIKU 100K CLIFF (5X)';
786
+ } else if (state.preCliffWarningTriggered) {
787
+ coachAction = 'HAIKU 90K PRE-CLIFF';
788
+ } else if (metrics.amberAlert) {
789
+ coachAction = `TTL EXPIRING ${metrics.ttlCompact}`;
790
+ } else if (!metrics.cacheWarm) {
791
+ coachAction = 'COLD PREFIX';
792
+ }
793
+
794
+ const coachPill = `[${metrics.flightMode} · ${coachAction}]`;
795
+ const tokenBadge = `${formatTokensCompact(grid.totalInputTokens)}/${grid.zoomTier.id}`;
796
+ const ttlBadge = metrics.cacheWarm ? `TTL ${metrics.ttlCompact}` : 'TTL COLD';
797
+
798
+ const suffixWithPct = ` ${tokenBadge} (${grid.utilizationPct}%) · ${ttlBadge} · ${coachPill}`;
799
+ const suffixCompact = ` ${tokenBadge} · ${ttlBadge} · ${coachPill}`;
800
+
801
+ let plainCandidate = `AH ${grid.bracketedBar}${suffixWithPct}`;
802
+ let ansiCandidate = `AH ${grid.ansiCodeBar}${suffixWithPct}`;
803
+
804
+ if (plainCandidate.length > maxCols) {
805
+ const availWithPct = maxCols - 3 - suffixWithPct.length - 2;
806
+ const availCompact = maxCols - 3 - suffixCompact.length - 2;
807
+ if (availWithPct >= 12) {
808
+ const dynCells = Math.min(40, availWithPct);
809
+ const barGrid = computeHorizonGrid(state, { ...options, cellCount: dynCells });
810
+ plainCandidate = `AH ${barGrid.bracketedBar}${suffixWithPct}`;
811
+ ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixWithPct}`;
812
+ } else if (availCompact >= 8) {
813
+ const dynCells = Math.min(40, availCompact);
814
+ const barGrid = computeHorizonGrid(state, { ...options, cellCount: dynCells });
815
+ plainCandidate = `AH ${barGrid.bracketedBar}${suffixCompact}`;
816
+ ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixCompact}`;
817
+ } else {
818
+ const barGrid = computeHorizonGrid(state, { ...options, cellCount: 8 });
819
+ plainCandidate = `AH ${barGrid.bracketedBar}${suffixCompact}`;
820
+ ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixCompact}`;
821
+ }
822
+ }
823
+
824
+ if (plainCandidate.length > maxCols) {
825
+ plainCandidate = plainCandidate.slice(0, maxCols);
826
+ ansiCandidate = truncateAnsiVisible(ansiCandidate, maxCols);
827
+ }
828
+
829
+ const plainLine = plainCandidate;
830
+ const line = useAnsi ? ansiCandidate : plainLine;
831
+
832
+ return {
833
+ line,
834
+ plainLine,
835
+ grid,
836
+ metrics,
837
+ coachPill
838
+ };
839
+ }
840
+
841
+ /**
842
+ * 2. Renders the `Spinner` suffix appended during active turns (`· Cache 95% (4m12s) · Saved $1.84`).
843
+ *
844
+ * @param {object} [state={}]
845
+ * @param {object} [options={}]
846
+ * @returns {{
847
+ * suffix: string,
848
+ * cacheHitPct: number,
849
+ * ttlText: string,
850
+ * savedUSDText: string
851
+ * }}
852
+ */
853
+ export function renderSpinnerSuffix(state = {}, options = {}) {
854
+ const metrics = deriveSurfaceMetrics(state, options);
855
+ const ttlText = metrics.cacheWarm ? metrics.ttlCompact : 'cold';
856
+ const savedUSDText = formatUsd(metrics.savedUSD);
857
+ let suffix = `· Cache ${metrics.cacheHitPct}% (${ttlText}) · Saved ${savedUSDText}`;
858
+ if (state.prefixRetention?.measured) suffix += ` · ${formatRetentionCompact(state.prefixRetention)}`;
859
+ if (state.thinkingDrift?.loop?.triggered) suffix += ` · ${formatDriftCompact(state.thinkingDrift)}`;
860
+
861
+ return {
862
+ suffix,
863
+ cacheHitPct: metrics.cacheHitPct,
864
+ ttlText,
865
+ savedUSDText
866
+ };
867
+ }
868
+
869
+ /**
870
+ * Builds the ranked list of Top Context Offenders for Box 4 of the Simple View Pane.
871
+ *
872
+ * @param {object} state
873
+ * @param {object} grid
874
+ * @param {object} [options={}]
875
+ * @returns {Array<{ name: string, tokens: number, category: string, pct: number }>}
876
+ */
877
+ function buildTopContextOffenders(state = {}, grid, options = {}) {
878
+ if (Array.isArray(options.offenders) && options.offenders.length > 0) {
879
+ return options.offenders.slice(0, 4).map((item) => {
880
+ const name = String(item.name || 'Context Item');
881
+ return {
882
+ name,
883
+ tokens: Math.max(0, Number(item.tokens || 0)),
884
+ category: String(item.category || 'C'),
885
+ ignorable: isIgnorableClaudePath(name),
886
+ pct:
887
+ grid.totalInputTokens > 0
888
+ ? Number(((Number(item.tokens || 0) / grid.totalInputTokens) * 100).toFixed(1))
889
+ : 0
890
+ };
891
+ });
892
+ }
893
+
894
+ const entries = [
895
+ {
896
+ name: 'Middle-Window Distractor / Stale Tool Output',
897
+ tokens: grid.tokens.D,
898
+ category: '[D]',
899
+ ignorable: false
900
+ },
901
+ {
902
+ name: 'System Prompt & MCP Tool Schemas',
903
+ tokens: grid.tokens.S,
904
+ category: '[S]',
905
+ ignorable: false
906
+ },
907
+ {
908
+ name: 'Fresh 1.25x Cache Write Delta',
909
+ tokens: grid.tokens.W,
910
+ category: '[W]',
911
+ ignorable: false
912
+ },
913
+ {
914
+ name: 'Warm Cached Conversation Prefix',
915
+ tokens: grid.tokens.C,
916
+ category: '[C]',
917
+ ignorable: false
918
+ }
919
+ ].filter((e) => e.tokens > 0);
920
+
921
+ entries.sort((a, b) => b.tokens - a.tokens);
922
+
923
+ if (entries.length === 0) {
924
+ return [
925
+ {
926
+ name: 'No active context offenders recorded',
927
+ tokens: 0,
928
+ category: '[.]',
929
+ ignorable: false,
930
+ pct: 0
931
+ }
932
+ ];
933
+ }
934
+
935
+ return entries.slice(0, 4).map((e) => ({
936
+ ...e,
937
+ pct:
938
+ grid.totalInputTokens > 0
939
+ ? Number(((e.tokens / grid.totalInputTokens) * 100).toFixed(1))
940
+ : 0
941
+ }));
942
+ }
943
+
944
+ /**
945
+ * 3. Renders the Docked `Pane` (`id: 'attention-horizon'`) with both the 4-Rank Glanceable Simple View
946
+ * (`ranks` / `simpleText`) and the 5-Box vertical hierarchy (`boxes`, zero promotional banner text):
947
+ * - Rank 1: Status Verdict & Flight Header (`Healthy` / `Action Needed` / `Critical`)
948
+ * - Rank 2: 40-Cell Horizon Bar, 3-Stat Row & 5m/1h Prompt Cache Shield
949
+ * - Rank 3: Single Priority Next Action (+ overflow count for `/horizon advanced`)
950
+ * - Rank 4: Elevated "Tokens & USD Saved" Card (`This Session` + `30d Workspace` + Top Driver)
951
+ *
952
+ * @param {object} [state={}]
953
+ * @param {object} [options={}]
954
+ */
955
+ export function renderSimpleViewPane(state = {}, options = {}) {
956
+ const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
957
+ const grid = computeHorizonGrid(state, options);
958
+ const paneCellCount = maxCols >= 49 ? 40 : Math.max(8, maxCols - 9);
959
+ const paneGrid =
960
+ paneCellCount === 40 ? grid : computeHorizonGrid(state, { ...options, cellCount: paneCellCount });
961
+ const scaleRuler = buildScaleTickRuler(
962
+ grid.zoomTier.ceilingTokens,
963
+ paneGrid.bracketedBar.length
964
+ );
965
+ const metrics = deriveSurfaceMetrics(state, options);
966
+ const peerModel = resolveNaturalDownshiftPeer(grid.modelId);
967
+ const breakEven = computeBreakEvenCachedTokens(
968
+ {
969
+ currentModel: grid.modelId,
970
+ targetModel: peerModel,
971
+ expectedOutputTokens: 1500,
972
+ cacheTtlTier: metrics.ttlTier
973
+ },
974
+ options
975
+ );
976
+ const { verdict, priorityAction, secondaryActions, overflowActionCount } =
977
+ deriveClaudeCodeVerdictAndActions(state, grid, metrics, options);
978
+
979
+ const headroomTokens = Math.max(0, grid.zoomTier.ceilingTokens - grid.totalInputTokens);
980
+
981
+ // 4-Rank Glanceable Simple View (`ranks`)
982
+ const rank1Lines = [
983
+ `[Rank 1] ${verdict.badge}: ${verdict.headline}`,
984
+ `Model: ${state.modelLabel || grid.modelId} · Mode: ${metrics.flightMode} · ${verdict.detail}`
985
+ ];
986
+ const rank2Lines = [
987
+ `[Rank 2] Context Capacity & Prompt Cache Shield (${grid.zoomTier.label})`,
988
+ `Grid : ${paneGrid.bracketedBar}`,
989
+ `Scale: ${scaleRuler}`,
990
+ `Stats: Used ${formatTokensCompact(grid.totalInputTokens)}/${grid.zoomTier.id} (${grid.utilizationPct}%) | Stale Debt [D] ${formatTokensCompact(grid.tokens.D)} | Free ${formatTokensCompact(headroomTokens)}`,
991
+ `Cache: ${metrics.cacheWarm ? 'WARM' : 'COLD'} (${metrics.ttlTier}) · TTL ${metrics.ttlClock} (${metrics.ttlCompact}) · Hit ${metrics.cacheHitPct}%`
992
+ ];
993
+ const overflowNote =
994
+ overflowActionCount > 0 ? ` (+${overflowActionCount} more in /horizon advanced)` : '';
995
+ const rank3Lines = [
996
+ `[Rank 3] Next Action${overflowNote}`,
997
+ `Action: ${priorityAction.title}`,
998
+ `Guide : ${priorityAction.instruction}`
999
+ ];
1000
+ const rank4Lines = [
1001
+ `[Rank 4] Verified Tokens & USD Saved`,
1002
+ `Saved : +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) this session · +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)}) 30d`,
1003
+ `Driver: ${metrics.topSavingsDriver.shortLabel} (+${formatTokensCompact(metrics.topSavingsDriver.savedTokens)})`
1004
+ ];
1005
+
1006
+ const rawRanks = [
1007
+ {
1008
+ rankNumber: 1,
1009
+ id: 'status-verdict-header',
1010
+ title: 'Status Verdict & Flight Header',
1011
+ lines: rank1Lines
1012
+ },
1013
+ {
1014
+ rankNumber: 2,
1015
+ id: 'capacity-cache-shield',
1016
+ title: 'Context Capacity & Prompt Cache Shield',
1017
+ lines: rank2Lines
1018
+ },
1019
+ {
1020
+ rankNumber: 3,
1021
+ id: 'priority-next-action',
1022
+ title: 'Priority Next Action',
1023
+ lines: rank3Lines
1024
+ },
1025
+ {
1026
+ rankNumber: 4,
1027
+ id: 'tokens-usd-saved',
1028
+ title: 'Verified Tokens & USD Saved',
1029
+ lines: rank4Lines
1030
+ }
1031
+ ];
1032
+
1033
+ const ranks = rawRanks.map((r) => {
1034
+ const clampedLines = r.lines.map((l) => clampPlainLine(l, maxCols));
1035
+ return {
1036
+ ...r,
1037
+ lines: clampedLines,
1038
+ text: clampedLines.join('\n')
1039
+ };
1040
+ });
1041
+
1042
+ // Box 1: Capacity & Horizon Bar + Tufte Scale-Tick Ruler
1043
+ const box1Lines = [
1044
+ `[Box 1] Capacity & Horizon Bar · ${grid.zoomTier.label}`,
1045
+ `Model: ${state.modelLabel || grid.modelId} | Tokens: ${formatTokensCompact(grid.totalInputTokens)} / ${grid.zoomTier.id} (${grid.utilizationPct}%)`,
1046
+ `Grid : ${paneGrid.bracketedBar}`,
1047
+ `Scale: ${scaleRuler}`,
1048
+ `Cells: [S] ${grid.cellCounts.S} (${formatTokensCompact(grid.tokens.S)}) | [C] ${grid.cellCounts.C} (${formatTokensCompact(grid.tokens.C)}) | [D] ${grid.cellCounts.D} (${formatTokensCompact(grid.tokens.D)}) | [W] ${grid.cellCounts.W} (${formatTokensCompact(grid.tokens.W)})`
1049
+ ];
1050
+
1051
+ // Box 2: Cache Hold & 5m TTL Countdown
1052
+ const roiLabel = metrics.negativeCacheRoi
1053
+ ? `NEGATIVE ROI (Reads/Write ${metrics.readsPerWriteRatio.toFixed(2)} < ${metrics.breakEvenReadsPerWrite})`
1054
+ : `POSITIVE ROI (Hit ${metrics.cacheHitPct}% | R/W ${metrics.readsPerWriteRatio.toFixed(2)} >= ${metrics.breakEvenReadsPerWrite})`;
1055
+ const ttlAlertText = metrics.amberAlert ? ' [AMBER TTL ALERT <= 45s]' : '';
1056
+ const box2Lines = [
1057
+ `[Box 2] Cache Hold & 5m TTL Countdown`,
1058
+ `State: ${metrics.cacheWarm ? 'WARM' : 'COLD'} (${metrics.ttlTier} tier) | Countdown: ${metrics.ttlClock} (${metrics.ttlCompact})${ttlAlertText}`,
1059
+ `Break-Even Gravity C*: ${breakEven.breakEvenTokens.toLocaleString('en-US')} cached tokens`,
1060
+ `Cache ROI: ${roiLabel}`,
1061
+ `Prefix Retention: ${formatRetentionLabel(state.prefixRetention)}`,
1062
+ `Thinking Drift: ${formatDriftLabel(state.thinkingDrift)}`
1063
+ ];
1064
+
1065
+ // Sprint 2.1: Swarm & Worktrees block (progressive disclosure: only when subagents seen)
1066
+ const swarmSummary = computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() });
1067
+ if (swarmSummary.active) {
1068
+ box2Lines.push(`Swarm & Worktrees: ${swarmSummary.label}`);
1069
+ for (const w of swarmSummary.workers.slice(0, 4)) {
1070
+ const loc = w.branch || w.worktree ? ` @${w.branch || w.worktree}` : '';
1071
+ box2Lines.push(` · ${w.agentId} ${w.state}${w.state === 'waiting' ? ' ($0)' : ''} · ${formatTokensCompact(w.totalTokens)} · ${w.turns}t${loc}`);
1072
+ }
1073
+ if (swarmSummary.workers.length > 4) box2Lines.push(` · +${swarmSummary.workers.length - 4} more`);
1074
+ }
1075
+
1076
+ // Box 3: Active Coach / Circuit Breaker Slot
1077
+ const activeBreakerId =
1078
+ options.breakerVerdict?.detectorId || options.breakerVerdict?.ruleId || 'BREAKER';
1079
+ const activeBreaker = options.breakerVerdict?.triggered
1080
+ ? options.breakerVerdict.reason
1081
+ ? `${activeBreakerId} ACTIVE — ${options.breakerVerdict.reason}`
1082
+ : `${activeBreakerId} ACTIVE`
1083
+ : state.thinkingDrift?.loop?.triggered
1084
+ ? state.thinkingDrift.loop.message
1085
+ : state.cliffTriggered
1086
+ ? 'DET-12: Haiku 5.5 100k 5x pricing cliff exceeded'
1087
+ : state.preCliffWarningTriggered
1088
+ ? 'DET-12: Haiku 5.5 90k pre-cliff compaction recommended'
1089
+ : metrics.amberAlert
1090
+ ? 'DET-10: 5m KV-cache TTL <= 45s; hold mutations or flush State Baton'
1091
+ : 'All DET-01..32 circuit breakers nominal';
1092
+ const singleBox3Status = `Flight Mode: ${metrics.flightMode} | Status: ${activeBreaker}`;
1093
+ const box3Lines =
1094
+ singleBox3Status.length <= maxCols
1095
+ ? [
1096
+ `[Box 3] Active Coach / Circuit Breaker Slot`,
1097
+ singleBox3Status,
1098
+ `Action: ${priorityAction.title}`
1099
+ ]
1100
+ : [
1101
+ `[Box 3] Active Coach / Circuit Breaker Slot`,
1102
+ `Flight Mode: ${metrics.flightMode}`,
1103
+ `Status: ${activeBreaker}`,
1104
+ `Action: ${priorityAction.title}`
1105
+ ];
1106
+
1107
+ // Box 4: Top Context Offenders
1108
+ const offenders = buildTopContextOffenders(state, grid, options);
1109
+ const offenderLines = offenders.map((o, idx) => {
1110
+ const prefix = ` ${idx + 1}. ${o.category} `;
1111
+ const suffix = `: ${formatTokensCompact(o.tokens)} (${o.pct}%)`;
1112
+ const maxNameLen = Math.max(6, maxCols - prefix.length - suffix.length);
1113
+ const safeName =
1114
+ o.name.length > maxNameLen ? `${o.name.slice(0, maxNameLen - 1)}…` : o.name;
1115
+ return `${prefix}${safeName}${suffix}`;
1116
+ });
1117
+ const box4Lines = [`[Box 4] Top Context Offenders`, ...offenderLines];
1118
+
1119
+ // Box 5: Deterministic Saved-Quota Receipt in USD & Tokens
1120
+ const box5Lines = [
1121
+ `[Box 5] Deterministic Saved-Quota Receipt`,
1122
+ `Verified Savings: ${formatUsd(metrics.savedUSD)} USD | ${metrics.savedTokens.toLocaleString('en-US')} tokens preserved`,
1123
+ `Session: +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) | 30d: +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)})`
1124
+ ];
1125
+
1126
+ const rawBoxes = [
1127
+ {
1128
+ boxNumber: 1,
1129
+ id: 'capacity-horizon-bar',
1130
+ title: 'Capacity & Horizon Bar',
1131
+ lines: box1Lines
1132
+ },
1133
+ {
1134
+ boxNumber: 2,
1135
+ id: 'cache-hold-ttl-countdown',
1136
+ title: 'Cache Hold & 5m TTL Countdown',
1137
+ lines: box2Lines
1138
+ },
1139
+ {
1140
+ boxNumber: 3,
1141
+ id: 'active-coach-circuit-breaker',
1142
+ title: 'Active Coach / Circuit Breaker Slot',
1143
+ lines: box3Lines
1144
+ },
1145
+ {
1146
+ boxNumber: 4,
1147
+ id: 'top-context-offenders',
1148
+ title: 'Top Context Offenders',
1149
+ lines: box4Lines
1150
+ },
1151
+ {
1152
+ boxNumber: 5,
1153
+ id: 'saved-quota-receipt',
1154
+ title: 'Deterministic Saved-Quota Receipt',
1155
+ lines: box5Lines
1156
+ }
1157
+ ];
1158
+
1159
+ const boxes = rawBoxes.map((b) => {
1160
+ const clampedLines = b.lines.map((l) => clampPlainLine(l, maxCols));
1161
+ return {
1162
+ ...b,
1163
+ lines: clampedLines,
1164
+ text: clampedLines.join('\n')
1165
+ };
1166
+ });
1167
+
1168
+ const divider = '─'.repeat(Math.min(76, maxCols));
1169
+ const simpleText = ranks.map((r) => r.text).join(`\n${divider}\n`);
1170
+ const boxText = boxes.map((b) => b.text).join(`\n${divider}\n`);
1171
+ const useRankMode = options.viewMode === 'SIMPLE_4_RANK' || options.layout === '4-rank';
1172
+
1173
+ return {
1174
+ paneId: 'attention-horizon',
1175
+ title: 'Highbeam',
1176
+ viewMode: useRankMode ? 'SIMPLE_4_RANK' : 'SIMPLE_5_BOX',
1177
+ ranks,
1178
+ simpleText,
1179
+ boxes,
1180
+ text: useRankMode ? simpleText : boxText,
1181
+ verdict,
1182
+ priorityAction,
1183
+ secondaryActions,
1184
+ overflowActionCount,
1185
+ grid,
1186
+ metrics
1187
+ };
1188
+ }
1189
+
1190
+ /**
1191
+ * Renders the pure 4-Rank Glanceable Simple View HUD (`viewMode: 'SIMPLE_4_RANK'`).
1192
+ *
1193
+ * @param {object} [state={}]
1194
+ * @param {object} [options={}]
1195
+ */
1196
+ export function renderSimpleHudPane(state = {}, options = {}) {
1197
+ return renderSimpleViewPane(state, { ...options, viewMode: 'SIMPLE_4_RANK' });
1198
+ }
1199
+
1200
+ /**
1201
+ * Renders the 5-Section Advanced View Workbench for Claude Code (`/horizon advanced` / `npx ah-claude receipt --advanced`):
1202
+ * Section 1: Verified 5-Category Savings & Anthropic Cache ROI (`C*` & `0.263`/`1.053` R/W)
1203
+ * Section 2: 40-Cell `[S]/[C]/[D]/[W]` Context Anatomy & Top Context Offenders
1204
+ * Section 3: Circuit Breakers (`DET-01..21`), Thinking Drift & Prefix Retention
1205
+ * Section 4: Subagent Swarm (`Task`/`Agent`), Worktrees & `DET-20` Scope Locks
1206
+ * Section 5: `PreCompact` State Baton (`HANDOFF_LATEST.md`) & Session Forensics
1207
+ *
1208
+ * @param {object} [state={}]
1209
+ * @param {object} [options={}]
1210
+ */
1211
+ export function renderAdvancedViewPane(state = {}, options = {}) {
1212
+ const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
1213
+ const simple = renderSimpleViewPane(state, options);
1214
+ const { grid, metrics } = simple;
1215
+ const peerModel = resolveNaturalDownshiftPeer(grid.modelId);
1216
+ const breakEven = computeBreakEvenCachedTokens(
1217
+ {
1218
+ currentModel: grid.modelId,
1219
+ targetModel: peerModel,
1220
+ expectedOutputTokens: 1500,
1221
+ cacheTtlTier: metrics.ttlTier
1222
+ },
1223
+ options
1224
+ );
1225
+ const offenders = buildTopContextOffenders(state, grid, options);
1226
+ const swarmSummary = computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() });
1227
+
1228
+ // Section 1: 5-Category Savings Breakdown & Anthropic Cache ROI
1229
+ const catOrder = [
1230
+ metrics.savingsCategories.cacheReadDiscount,
1231
+ metrics.savingsCategories.prefixBustAvoided,
1232
+ metrics.savingsCategories.toolOutputCompressed,
1233
+ metrics.savingsCategories.loopAndReadGuarded,
1234
+ metrics.savingsCategories.subagentIsolated
1235
+ ];
1236
+ const sec1Lines = [
1237
+ `[Section 1] Verified 5-Category Savings & Anthropic Cache ROI`,
1238
+ `Headline: +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) session · +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)}) 30d`,
1239
+ ...catOrder.map(
1240
+ (c, idx) =>
1241
+ ` ${idx + 1}. ${c.shortLabel}: +${formatTokensCompact(c.savedTokens)} (${formatUsd(c.savedUSD)}) [${c.count}x]`
1242
+ ),
1243
+ `Break-Even Gravity C*: ${breakEven.breakEvenTokens.toLocaleString('en-US')} cached tok (${grid.modelId} -> ${peerModel})`,
1244
+ `Reads/Write Ratio: ${metrics.readsPerWriteRatio.toFixed(2)} (target >= ${metrics.breakEvenReadsPerWrite} for ${metrics.ttlTier} TTL)`
1245
+ ];
1246
+
1247
+ // Section 2: 40-Cell [S]/[C]/[D]/[W] Anatomy & Top Context Offenders
1248
+ const sec2Lines = [
1249
+ `[Section 2] 40-Cell Context Anatomy & Top Context Offenders`,
1250
+ `[S] System & MCP Schemas : ${grid.cellCounts.S} cells (${formatTokensCompact(grid.tokens.S)})`,
1251
+ `[C] Warm Cached Prefix : ${grid.cellCounts.C} cells (${formatTokensCompact(grid.tokens.C)})`,
1252
+ `[D] Stale Tool Debt : ${grid.cellCounts.D} cells (${formatTokensCompact(grid.tokens.D)})`,
1253
+ `[W] Fresh 1.25x Write : ${grid.cellCounts.W} cells (${formatTokensCompact(grid.tokens.W)})`,
1254
+ ...offenders.map(
1255
+ (o, idx) =>
1256
+ ` Offender ${idx + 1}: ${o.category} ${o.name} — ${formatTokensCompact(o.tokens)} (${o.pct}%)${o.ignorable ? ' [.claudeignore candidate]' : ''}`
1257
+ )
1258
+ ];
1259
+
1260
+ // Section 3: Circuit Breakers (DET-01..32), Thinking Drift & Prefix Retention
1261
+ const activeBreakerId =
1262
+ options.breakerVerdict?.detectorId || options.breakerVerdict?.ruleId || null;
1263
+ const sec3Lines = [
1264
+ `[Section 3] Circuit Breakers (DET-01..32), Thinking Drift & Retention`,
1265
+ `Flight Mode: ${metrics.flightMode} | Active Trigger: ${activeBreakerId ? `${activeBreakerId} (${options.breakerVerdict?.reason || 'active'})` : 'None (32 guards nominal)'}`,
1266
+ `Prefix Retention: ${formatRetentionLabel(state.prefixRetention)}`,
1267
+ `Thinking Drift (DET-30): ${formatDriftLabel(state.thinkingDrift)}`,
1268
+ `Haiku 100k 5x Cliff (DET-12): ${state.cliffTriggered ? 'EXCEEDED (5x step-up)' : state.preCliffWarningTriggered ? 'PRE-CLIFF WARNING (>= 90k)' : 'Nominal'}`
1269
+ ];
1270
+
1271
+ // Section 4: Subagent Swarm (Task/Agent), Worktrees & DET-20 Scope Locks
1272
+ const sec4Lines = [
1273
+ `[Section 4] Subagent Swarm (Task/Agent), Worktrees & Scope Locks`,
1274
+ `Topology: ${swarmSummary.active ? swarmSummary.label : 'Solo main agent (0 active Task/Agent subagents)'}`
1275
+ ];
1276
+ if (swarmSummary.active) {
1277
+ for (const w of swarmSummary.workers.slice(0, 6)) {
1278
+ const loc = w.branch || w.worktree ? ` @${w.branch || w.worktree}` : '';
1279
+ sec4Lines.push(
1280
+ ` · ${w.agentId} [${w.state}${w.state === 'waiting' ? ' $0' : ''}] ${formatTokensCompact(w.totalTokens)} (${w.turns}t)${loc}`
1281
+ );
1282
+ }
1283
+ }
1284
+
1285
+ // Section 5: PreCompact State Baton & Session Forensics
1286
+ const sec5Lines = [
1287
+ `[Section 5] PreCompact State Baton & Claude Code Forensics`,
1288
+ `Session ID: ${state.sessionId || 'default'} | Completed Turns: ${Number(state.turnsCompleted || 0)}`,
1289
+ `Zoom Tier : ${grid.zoomTier.label} (${grid.zoomTier.tokensPerCell.toLocaleString('en-US')} tok/cell)`,
1290
+ `State Baton: Auto-flushed on PreCompact to .claude/cache/HANDOFF_LATEST.md`,
1291
+ `CLI Tools : npx ctxtop statusline | npx ctxtop radar | npx ctxtop inspect | npx ctxtop doctor`
1292
+ ];
1293
+
1294
+ const rawSections = [
1295
+ {
1296
+ sectionNumber: 1,
1297
+ id: 'savings-and-cache-roi',
1298
+ title: 'Verified 5-Category Savings & Anthropic Cache ROI',
1299
+ lines: sec1Lines
1300
+ },
1301
+ {
1302
+ sectionNumber: 2,
1303
+ id: 'context-anatomy-offenders',
1304
+ title: '40-Cell Context Anatomy & Top Context Offenders',
1305
+ lines: sec2Lines
1306
+ },
1307
+ {
1308
+ sectionNumber: 3,
1309
+ id: 'circuit-breakers-drift',
1310
+ title: 'Circuit Breakers (DET-01..21), Thinking Drift & Retention',
1311
+ lines: sec3Lines
1312
+ },
1313
+ {
1314
+ sectionNumber: 4,
1315
+ id: 'subagent-swarm-worktrees',
1316
+ title: 'Subagent Swarm (Task/Agent), Worktrees & Scope Locks',
1317
+ lines: sec4Lines
1318
+ },
1319
+ {
1320
+ sectionNumber: 5,
1321
+ id: 'state-baton-forensics',
1322
+ title: 'PreCompact State Baton & Claude Code Forensics',
1323
+ lines: sec5Lines
1324
+ }
1325
+ ];
1326
+
1327
+ const sections = rawSections.map((s) => {
1328
+ const clampedLines = s.lines.map((l) => clampPlainLine(l, maxCols));
1329
+ return {
1330
+ ...s,
1331
+ lines: clampedLines,
1332
+ text: clampedLines.join('\n')
1333
+ };
1334
+ });
1335
+
1336
+ const divider = '─'.repeat(Math.min(76, maxCols));
1337
+ const text = sections.map((s) => s.text).join(`\n${divider}\n`);
1338
+
1339
+ return {
1340
+ paneId: 'attention-horizon',
1341
+ title: 'Highbeam (Advanced View)',
1342
+ viewMode: 'ADVANCED_5_SECTION',
1343
+ sections,
1344
+ boxes: simple.boxes,
1345
+ ranks: simple.ranks,
1346
+ text,
1347
+ verdict: simple.verdict,
1348
+ priorityAction: simple.priorityAction,
1349
+ grid,
1350
+ metrics
1351
+ };
1352
+ }
1353
+
1354
+ /**
1355
+ * Pure zero-Node formatter for the Claude Code `statusLine` RSL budget segment.
1356
+ *
1357
+ * @param {object} rsl
1358
+ * @returns {string}
1359
+ */
1360
+ export function formatRslStatusSegment(rsl) {
1361
+ if (!rsl || typeof rsl !== 'object') return '';
1362
+ const rules = Math.max(0, Number(rsl.activeRules ?? 0));
1363
+ const tokens = Math.max(0, Number(rsl.ruleBudgetTokens ?? 0));
1364
+ const clashes = Math.max(0, Number(rsl.clashCount ?? 0));
1365
+ const budgetStr =
1366
+ tokens >= 1000 ? `${(tokens / 1000).toFixed(1).replace(/\.0$/, '')}k` : String(tokens);
1367
+ const base = `RSL: ${rules} rules | Budget: ${budgetStr}/20k`;
1368
+ return clashes > 0 ? `${base} | ${clashes} clash!` : base;
1369
+ }
1370
+
1371
+ /**
1372
+ * 4. Renders a single-line terminal `statusLine` adapting cleanly to terminal column width
1373
+ * (`80`, `110`, `144`, or arbitrary column count).
1374
+ *
1375
+ * Guaranteed invariant: `stripAnsi(result.line).length <= columns`.
1376
+ *
1377
+ * @param {object} [state={}]
1378
+ * @param {object} [options={}]
1379
+ * @param {number} [options.columns=110]
1380
+ * @param {boolean} [options.ansi=true]
1381
+ * @returns {{
1382
+ * line: string,
1383
+ * plainLine: string,
1384
+ * visibleLength: number,
1385
+ * columns: number,
1386
+ * layoutTier: 'compact-80'|'standard-110'|'wide-144',
1387
+ * grid: object,
1388
+ * metrics: object
1389
+ * }}
1390
+ */
1391
+ export function renderStatusLine(state = {}, options = {}) {
1392
+ const columns = Math.max(
1393
+ 40,
1394
+ Number(options.columns || options.maxCols || globalThis.process?.stdout?.columns || 110)
1395
+ );
1396
+ const useAnsi = options.ansi !== false && !isNoColorEnabled(options);
1397
+ const metrics = deriveSurfaceMetrics(state, options);
1398
+
1399
+ let layoutTier = 'standard-110';
1400
+ let candidateBarWidths = [24, 20, 16, 12];
1401
+ if (columns < 96) {
1402
+ layoutTier = 'compact-80';
1403
+ candidateBarWidths = [20, 16, 14, 12];
1404
+ } else if (columns >= 132) {
1405
+ layoutTier = 'wide-144';
1406
+ candidateBarWidths = [40, 24, 20, 16, 12];
1407
+ }
1408
+
1409
+ const breakerId =
1410
+ options.breakerVerdict?.detectorId || options.breakerVerdict?.ruleId || '';
1411
+ const shortMode =
1412
+ metrics.flightMode === 'AUTO_PILOT' ? 'AUTO' : metrics.flightMode;
1413
+ const fullCoachPill =
1414
+ options.breakerVerdict?.triggered && breakerId
1415
+ ? `[${shortMode}·${breakerId}]`
1416
+ : layoutTier === 'wide-144'
1417
+ ? `[${metrics.flightMode}]`
1418
+ : metrics.flightMode;
1419
+ const compactCoachPill =
1420
+ options.breakerVerdict?.triggered && breakerId ? breakerId : shortMode;
1421
+
1422
+ const pillVariants =
1423
+ fullCoachPill === compactCoachPill ? [fullCoachPill] : [fullCoachPill, compactCoachPill];
1424
+
1425
+ let chosenGrid = null;
1426
+ let plainCandidate = '';
1427
+ let ansiCandidate = '';
1428
+ let matchedFit = false;
1429
+
1430
+ for (const pill of pillVariants) {
1431
+ for (const barWidth of candidateBarWidths) {
1432
+ const g = computeHorizonGrid(state, { ...options, cellCount: barWidth });
1433
+ const tokStr = `${formatTokensCompact(g.totalInputTokens)}/${g.zoomTier.id}`;
1434
+ const ttlStr = metrics.cacheWarm ? metrics.ttlCompact : 'COLD';
1435
+ const savedStr = formatUsd(metrics.savedUSD);
1436
+ const loopStr = state.thinkingDrift?.loop?.triggered ? ` ${formatDriftCompact(state.thinkingDrift)}` : '';
1437
+ const retStr = state.prefixRetention?.measured ? ` · ${formatRetentionCompact(state.prefixRetention)}` : '';
1438
+ const swarmTok = layoutTier === 'wide-144' ? formatSwarmCompact(computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() })) : '';
1439
+ const swarmStr = swarmTok ? ` · ${swarmTok}` : '';
1440
+ const rslData = options.rsl || state.rsl || null;
1441
+ const rslTok = layoutTier !== 'compact-80' && rslData ? formatRslStatusSegment(rslData) : '';
1442
+ const rslStr = rslTok ? ` · ${rslTok}` : '';
1443
+
1444
+ let p = '';
1445
+ let a = '';
1446
+ if (layoutTier === 'compact-80') {
1447
+ p = `AH ${g.bracketedBar} ${tokStr} C:${metrics.cacheHitPct}% ${ttlStr} ${pill}${loopStr} ${savedStr}`;
1448
+ a = `AH ${g.ansiCodeBar} ${tokStr} C:${metrics.cacheHitPct}% ${ttlStr} ${pill}${loopStr} ${savedStr}`;
1449
+ } else {
1450
+ const shortModel = g.modelId.replace(/^claude-/, '');
1451
+ p = `AH ${g.bracketedBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}${rslStr}`;
1452
+ a = `AH ${g.ansiCodeBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}${rslStr}`;
1453
+ }
1454
+
1455
+ chosenGrid = g;
1456
+ plainCandidate = p;
1457
+ ansiCandidate = a;
1458
+
1459
+ if (p.length <= columns) {
1460
+ matchedFit = true;
1461
+ break;
1462
+ }
1463
+ }
1464
+ if (matchedFit) break;
1465
+ }
1466
+
1467
+ // Enforce strict column ceiling via ANSI-preserving truncation (never stripping ANSI colors!)
1468
+ if (plainCandidate.length > columns) {
1469
+ plainCandidate = plainCandidate.slice(0, columns);
1470
+ ansiCandidate = truncateAnsiVisible(ansiCandidate, columns);
1471
+ }
1472
+
1473
+ const finalLine = useAnsi ? ansiCandidate : plainCandidate;
1474
+ const visibleLength = stripAnsi(finalLine).length;
1475
+
1476
+ return {
1477
+ line: finalLine,
1478
+ plainLine: stripAnsi(finalLine),
1479
+ visibleLength,
1480
+ columns,
1481
+ layoutTier,
1482
+ grid: chosenGrid,
1483
+ metrics
1484
+ };
1485
+ }
1486
+
1487
+ export default {
1488
+ stripAnsi,
1489
+ truncateAnsiVisible,
1490
+ buildScaleTickRuler,
1491
+ formatTokensCompact,
1492
+ formatDurationCompact,
1493
+ formatUsd,
1494
+ isIgnorableClaudePath,
1495
+ deriveClaudeCodeVerdictAndActions,
1496
+ deriveSurfaceMetrics,
1497
+ renderAbovePromptBand,
1498
+ renderSpinnerSuffix,
1499
+ renderSimpleViewPane,
1500
+ renderSimpleHudPane,
1501
+ renderAdvancedViewPane,
1502
+ formatRslStatusSegment,
1503
+ renderStatusLine
1504
+ };