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,1478 @@
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 = Number(
349
+ ((liveSubagentIsolatedTokens / 1_000_000) * Number(activeRatesForSub.inputPer1M || 3)).toFixed(6)
350
+ );
351
+
352
+ // Use explicit options.savedUSD / options.savedTokens if passed, else max of ledger + session
353
+ const savedUSD =
354
+ typeof options.savedUSD === 'number'
355
+ ? Math.max(0, options.savedUSD)
356
+ : Number(Math.max(ledgerUSD, sessionNetSavingsUSD).toFixed(2));
357
+ const savedTokens =
358
+ typeof options.savedTokens === 'number'
359
+ ? Math.max(0, Math.round(options.savedTokens))
360
+ : Math.max(ledgerTokens, liveSessionCacheReadTokens);
361
+
362
+ const rawSessionTokens = Math.max(
363
+ Number(ledgerSummary?.sessionSavedTokens || 0),
364
+ liveSessionCacheReadTokens + liveSubagentIsolatedTokens,
365
+ typeof options.savedTokens === 'number' ? Math.max(0, Math.round(options.savedTokens)) : 0
366
+ );
367
+ const rawSessionUSD = Math.max(
368
+ Number(ledgerSummary?.sessionSavedUSD || 0),
369
+ sessionNetSavingsUSD + liveSubagentIsolatedUSD,
370
+ typeof options.savedUSD === 'number' ? Math.max(0, options.savedUSD) : 0
371
+ );
372
+ const sessionSavedTokens = Math.max(0, Math.round(options.sessionSavedTokens ?? rawSessionTokens));
373
+ const sessionSavedUSD = Number(
374
+ Math.max(0, Number(options.sessionSavedUSD ?? rawSessionUSD)).toFixed(2)
375
+ );
376
+ const workspace30dSavedTokens = Math.max(
377
+ sessionSavedTokens,
378
+ savedTokens,
379
+ Math.round(Number(options.workspace30dSavedTokens ?? ledgerSummary?.workspace30dSavedTokens ?? 0))
380
+ );
381
+ const workspace30dSavedUSD = Number(
382
+ Math.max(
383
+ sessionSavedUSD,
384
+ savedUSD,
385
+ Number(options.workspace30dSavedUSD ?? ledgerSummary?.workspace30dSavedUSD ?? 0)
386
+ ).toFixed(2)
387
+ );
388
+
389
+ // Build 5-category savings breakdown combining ledger + live session telemetry
390
+ const baseCats = ledgerSummary?.categories || {};
391
+ const savingsCategories = {
392
+ cacheReadDiscount: {
393
+ id: 'cacheReadDiscount',
394
+ label: SAVINGS_BUCKETS.cacheReadDiscount.label,
395
+ shortLabel: SAVINGS_BUCKETS.cacheReadDiscount.shortLabel,
396
+ savedTokens: Math.max(
397
+ Number(baseCats.cacheReadDiscount?.savedTokens || 0),
398
+ liveSessionCacheReadTokens
399
+ ),
400
+ savedUSD: Number(
401
+ Math.max(
402
+ Number(baseCats.cacheReadDiscount?.savedUSD || 0),
403
+ sessionNetSavingsUSD
404
+ ).toFixed(4)
405
+ ),
406
+ count: Math.max(
407
+ Number(baseCats.cacheReadDiscount?.count || 0),
408
+ liveSessionCacheReadTokens > 0 ? Math.max(1, Number(state.turnsCompleted || 1)) : 0
409
+ )
410
+ },
411
+ prefixBustAvoided: {
412
+ id: 'prefixBustAvoided',
413
+ label: SAVINGS_BUCKETS.prefixBustAvoided.label,
414
+ shortLabel: SAVINGS_BUCKETS.prefixBustAvoided.shortLabel,
415
+ savedTokens: Math.max(0, Number(baseCats.prefixBustAvoided?.savedTokens || 0)),
416
+ savedUSD: Number(Math.max(0, Number(baseCats.prefixBustAvoided?.savedUSD || 0)).toFixed(4)),
417
+ count: Math.max(0, Number(baseCats.prefixBustAvoided?.count || 0))
418
+ },
419
+ toolOutputCompressed: {
420
+ id: 'toolOutputCompressed',
421
+ label: SAVINGS_BUCKETS.toolOutputCompressed.label,
422
+ shortLabel: SAVINGS_BUCKETS.toolOutputCompressed.shortLabel,
423
+ savedTokens: Math.max(0, Number(baseCats.toolOutputCompressed?.savedTokens || 0)),
424
+ savedUSD: Number(Math.max(0, Number(baseCats.toolOutputCompressed?.savedUSD || 0)).toFixed(4)),
425
+ count: Math.max(0, Number(baseCats.toolOutputCompressed?.count || 0))
426
+ },
427
+ loopAndReadGuarded: {
428
+ id: 'loopAndReadGuarded',
429
+ label: SAVINGS_BUCKETS.loopAndReadGuarded.label,
430
+ shortLabel: SAVINGS_BUCKETS.loopAndReadGuarded.shortLabel,
431
+ savedTokens: Math.max(0, Number(baseCats.loopAndReadGuarded?.savedTokens || 0)),
432
+ savedUSD: Number(Math.max(0, Number(baseCats.loopAndReadGuarded?.savedUSD || 0)).toFixed(4)),
433
+ count: Math.max(0, Number(baseCats.loopAndReadGuarded?.count || 0))
434
+ },
435
+ subagentIsolated: {
436
+ id: 'subagentIsolated',
437
+ label: SAVINGS_BUCKETS.subagentIsolated.label,
438
+ shortLabel: SAVINGS_BUCKETS.subagentIsolated.shortLabel,
439
+ savedTokens: Math.max(
440
+ Number(baseCats.subagentIsolated?.savedTokens || 0),
441
+ liveSubagentIsolatedTokens
442
+ ),
443
+ savedUSD: Number(
444
+ Math.max(
445
+ Number(baseCats.subagentIsolated?.savedUSD || 0),
446
+ liveSubagentIsolatedUSD
447
+ ).toFixed(4)
448
+ ),
449
+ count: Math.max(
450
+ Number(baseCats.subagentIsolated?.count || 0),
451
+ liveSubagentIsolatedTokens > 0 ? Object.keys(state.subagents || {}).length : 0
452
+ )
453
+ }
454
+ };
455
+
456
+ let topSavingsDriver = savingsCategories.cacheReadDiscount;
457
+ for (const bucket of Object.values(savingsCategories)) {
458
+ if (
459
+ bucket.savedTokens > topSavingsDriver.savedTokens ||
460
+ (bucket.savedTokens === topSavingsDriver.savedTokens &&
461
+ bucket.savedUSD > topSavingsDriver.savedUSD)
462
+ ) {
463
+ topSavingsDriver = bucket;
464
+ }
465
+ }
466
+
467
+ const flightMode = String(
468
+ options.flightMode || state.flightMode || 'COACH'
469
+ ).toUpperCase();
470
+
471
+ const ttlTier = pc.ttlTier === '1h' ? '1h' : '5m';
472
+ let breakEvenReadsPerWrite = 0.263;
473
+ if (typeof roi.breakEvenReadsPerWrite === 'number' && roi.breakEvenReadsPerWrite > 0 && state.lastSource !== 'init') {
474
+ breakEvenReadsPerWrite = roi.breakEvenReadsPerWrite;
475
+ } else {
476
+ const activeRates = resolveEffectiveRates(
477
+ state.rawModelId || state.modelId || state.model || 'claude-sonnet-5-5',
478
+ totalInputTokens,
479
+ options
480
+ );
481
+ const mWrite =
482
+ ttlTier === '1h' ? activeRates.multipliers.write1h : activeRates.multipliers.write5m;
483
+ const mRead = activeRates.multipliers.read;
484
+ breakEvenReadsPerWrite = Number(((mWrite - 1) / (1 - mRead)).toFixed(3));
485
+ }
486
+ const sessionFiveMinRoiTarget = Number(roi.sessionFiveMinRoiTarget || 1.39);
487
+
488
+ const hasEvaluatedRwRatio =
489
+ typeof roi.readsPerWriteRatio === 'number' &&
490
+ (state.lastSource !== 'init' || roi.readsPerWriteRatio > 0 || Number(roi.actualCacheSpendUSD || 0) > 0);
491
+ const derivedRwRatio = hasEvaluatedRwRatio
492
+ ? roi.readsPerWriteRatio
493
+ : cacheWriteTokens > 0
494
+ ? cacheReadTokens / cacheWriteTokens
495
+ : cacheReadTokens > 0
496
+ ? Infinity
497
+ : 0;
498
+ const readsPerWriteRatio = Math.max(0, Number(derivedRwRatio || 0));
499
+ const negativeCacheRoi =
500
+ typeof roi.negativeCacheRoi === 'boolean' && state.lastSource !== 'init'
501
+ ? roi.negativeCacheRoi
502
+ : cacheWriteTokens > 0 && readsPerWriteRatio < breakEvenReadsPerWrite;
503
+
504
+ return {
505
+ totalInputTokens,
506
+ cachedTokens,
507
+ cacheReadTokens,
508
+ cacheWriteTokens,
509
+ warmPrefixTokens,
510
+ cacheHitPct,
511
+ cacheWarm,
512
+ remainingSeconds,
513
+ ttlCompact: cacheWarm ? formatDurationCompact(remainingSeconds) : 'COLD',
514
+ ttlClock: cacheWarm ? formatTtlClock(remainingSeconds) : '00:00',
515
+ ttlTier,
516
+ amberAlert,
517
+ savedUSD,
518
+ savedTokens,
519
+ sessionSavedTokens,
520
+ sessionSavedUSD,
521
+ workspace30dSavedTokens,
522
+ workspace30dSavedUSD,
523
+ savingsCategories,
524
+ topSavingsDriver,
525
+ flightMode: ['OFF', 'COACH', 'AUTO_PILOT'].includes(flightMode) ? flightMode : 'COACH',
526
+ negativeCacheRoi,
527
+ readsPerWriteRatio,
528
+ breakEvenReadsPerWrite,
529
+ sessionFiveMinRoiTarget
530
+ };
531
+ }
532
+
533
+ /**
534
+ * Checks whether a path is a lockfile, log, build artifact, or scratch file eligible
535
+ * for a `.claudeignore` recommendation (never active source code files).
536
+ *
537
+ * @param {string} [filePath='']
538
+ * @returns {boolean}
539
+ */
540
+ export function isIgnorableClaudePath(filePath = '') {
541
+ const s = String(filePath || '').trim();
542
+ if (!s) return false;
543
+ 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(
544
+ s
545
+ );
546
+ }
547
+
548
+ /**
549
+ * Derives plain-English Claude Code status verdict and prioritized action cards
550
+ * for Simple View (Rank 1 & Rank 3) and Advanced View.
551
+ *
552
+ * @param {object} [state={}]
553
+ * @param {object} grid
554
+ * @param {object} metrics
555
+ * @param {object} [options={}]
556
+ */
557
+ export function deriveClaudeCodeVerdictAndActions(state = {}, grid, metrics, options = {}) {
558
+ const actions = [];
559
+ let verdict = {
560
+ severity: 'healthy',
561
+ badge: 'HEALTHY',
562
+ headline: metrics.cacheWarm
563
+ ? `Healthy — Prompt Cache Warm (${metrics.ttlCompact})`
564
+ : 'Ready — Cold Prompt Prefix',
565
+ detail: metrics.cacheWarm
566
+ ? `${metrics.cacheHitPct}% of prompt reading at 0.10x cached rates (${metrics.ttlTier} TTL)`
567
+ : 'Next turn establishes the 5m warm prompt cache prefix'
568
+ };
569
+
570
+ const reclaimEstimate = Math.max(
571
+ grid.tokens.D,
572
+ Math.round(grid.totalInputTokens * 0.35)
573
+ );
574
+
575
+ if (options.breakerVerdict?.triggered) {
576
+ const breakerId =
577
+ options.breakerVerdict.detectorId || options.breakerVerdict.ruleId || 'BREAKER';
578
+ const reasonText =
579
+ options.breakerVerdict.reason || 'Circuit breaker triggered on active tool or model call';
580
+ verdict = {
581
+ severity: 'critical',
582
+ badge: 'CRITICAL',
583
+ headline: `${breakerId} Active — Guard Intervention`,
584
+ detail: reasonText
585
+ };
586
+ actions.push({
587
+ id: breakerId.toLowerCase(),
588
+ severity: 'critical',
589
+ title: `Resolve ${breakerId} guard before continuing`,
590
+ instruction: reasonText,
591
+ commandHint: `npx ah-claude config set ${breakerId} warn`,
592
+ reclaimTokens: 0
593
+ });
594
+ }
595
+
596
+ if (state.thinkingDrift?.loop?.triggered) {
597
+ const ratio = state.thinkingDrift.lastDriftRatio ?? 'high';
598
+ if (verdict.severity !== 'critical') {
599
+ verdict = {
600
+ severity: 'critical',
601
+ badge: 'CRITICAL',
602
+ headline: `Critical — Scratchpad Loop Detected (${ratio}x)`,
603
+ detail:
604
+ state.thinkingDrift.loop.message ||
605
+ `DET-21: Thinking tokens exceeded ${ratio}x output tokens with zero file edits`
606
+ };
607
+ }
608
+ actions.push({
609
+ id: 'det-21-loop',
610
+ severity: 'critical',
611
+ title: `Break ${ratio}x thinking loop`,
612
+ instruction:
613
+ 'Add a concrete target file path and test constraint to your next prompt, or lower /effort.',
614
+ commandHint: '/effort medium',
615
+ reclaimTokens: Math.max(0, Number(state.contextWindow?.lastThinkingTokens || 4000))
616
+ });
617
+ }
618
+
619
+ if (state.cliffTriggered) {
620
+ if (verdict.severity !== 'critical') {
621
+ verdict = {
622
+ severity: 'critical',
623
+ badge: 'CRITICAL',
624
+ headline: 'Critical — Haiku 5.5 100k 5x Pricing Cliff Exceeded',
625
+ detail: 'Total prompt exceeded 100,000 tokens ($0.10 -> $0.50/1M input step-up)'
626
+ };
627
+ }
628
+ actions.push({
629
+ id: 'det-12-cliff',
630
+ severity: 'critical',
631
+ title: 'Exit Haiku 100k 5x pricing cliff now',
632
+ instruction: `Type /compact in the chat box and press Enter to drop below 100k tokens (reclaims ~${formatTokensCompact(reclaimEstimate)}).`,
633
+ commandHint: 'Type /compact in the chat box and press Enter',
634
+ reclaimTokens: reclaimEstimate
635
+ });
636
+ } else if (state.preCliffWarningTriggered) {
637
+ if (verdict.severity === 'healthy') {
638
+ verdict = {
639
+ severity: 'warn',
640
+ badge: 'ACTION NEEDED',
641
+ headline: 'Approaching Haiku 100k 5x Pricing Cliff (>= 90k)',
642
+ detail: 'Compact before 100,000 tokens to avoid the 5x Haiku rate step-up'
643
+ };
644
+ }
645
+ actions.push({
646
+ id: 'det-12-precliff',
647
+ severity: 'warn',
648
+ title: 'Compact before crossing 100k Haiku cliff',
649
+ instruction: `Type /compact in the chat box and press Enter to reclaim ~${formatTokensCompact(reclaimEstimate)} before 100k.`,
650
+ commandHint: 'Type /compact in the chat box and press Enter',
651
+ reclaimTokens: reclaimEstimate
652
+ });
653
+ }
654
+
655
+ if (metrics.amberAlert) {
656
+ if (verdict.severity === 'healthy') {
657
+ verdict = {
658
+ severity: 'warn',
659
+ badge: 'CACHE EXPIRING',
660
+ headline: `5m Prompt Cache Expiring in ${metrics.ttlCompact}`,
661
+ detail: `${formatTokensCompact(metrics.cachedTokens)} warm prefix will go cold in ${metrics.ttlClock}`
662
+ };
663
+ }
664
+ actions.push({
665
+ id: 'det-10-ttl',
666
+ severity: 'warn',
667
+ title: `Send next prompt within ${metrics.ttlCompact} or hold prefix edits`,
668
+ instruction:
669
+ 'Keep coding to refresh the 5m TTL at 0.10x read cost, and hold CLAUDE.md or .mcp.json edits until PostCompact.',
670
+ commandHint: '/handoff',
671
+ reclaimTokens: metrics.cachedTokens
672
+ });
673
+ }
674
+
675
+ if (grid.tokens.D >= 25000 || grid.utilizationPct >= 75) {
676
+ if (verdict.severity === 'healthy') {
677
+ verdict = {
678
+ severity: 'warn',
679
+ badge: 'ACTION NEEDED',
680
+ headline:
681
+ metrics.cacheWarm && metrics.remainingSeconds > 60
682
+ ? `Stale Tool Debt High (${formatTokensCompact(grid.tokens.D)}) — Compact After Cache Window`
683
+ : `Context ${grid.utilizationPct}% Full — Compact Recommended`,
684
+ detail: `${formatTokensCompact(grid.tokens.D)} in middle-window distractors [D]`
685
+ };
686
+ }
687
+ if (metrics.cacheWarm && metrics.remainingSeconds > 60) {
688
+ actions.push({
689
+ id: 'compact-cache-gated',
690
+ severity: 'warn',
691
+ title: `Wait ${metrics.ttlCompact} for warm cache, then compact (~${formatTokensCompact(reclaimEstimate)} reclaimable)`,
692
+ instruction: `Finish your current step while ${formatTokensCompact(metrics.cachedTokens)} is warm (${metrics.ttlCompact} left), then: Type /compact in the chat box and press Enter`,
693
+ commandHint: 'Type /compact in the chat box and press Enter',
694
+ reclaimTokens: reclaimEstimate
695
+ });
696
+ } else {
697
+ actions.push({
698
+ id: 'compact-now',
699
+ severity: 'warn',
700
+ title: `Compact context now (~${formatTokensCompact(reclaimEstimate)} reclaimable)`,
701
+ instruction: 'Type /compact in the chat box and press Enter',
702
+ commandHint: 'Type /compact in the chat box and press Enter',
703
+ reclaimTokens: reclaimEstimate
704
+ });
705
+ }
706
+ }
707
+
708
+ if (metrics.negativeCacheRoi) {
709
+ if (verdict.severity === 'healthy') {
710
+ verdict = {
711
+ severity: 'warn',
712
+ badge: 'CACHE ROI WARN',
713
+ headline: 'Cache Write Surcharge Exceeds Read Discount',
714
+ detail: `Reads/Write ${metrics.readsPerWriteRatio.toFixed(2)} < ${metrics.breakEvenReadsPerWrite} break-even`
715
+ };
716
+ }
717
+ actions.push({
718
+ id: 'negative-roi',
719
+ severity: 'warn',
720
+ title: 'Hold CLAUDE.md, .claude/rules/, and .mcp.json mutations',
721
+ instruction: `Keep prefix static for at least 2 turns so 0.10x cache reads amortize the 1.25x write surcharge.`,
722
+ commandHint: 'Hold prefix edits until /compact',
723
+ reclaimTokens: metrics.cacheWriteTokens
724
+ });
725
+ }
726
+
727
+ if (actions.length === 0) {
728
+ actions.push({
729
+ id: 'keep-coding',
730
+ severity: 'healthy',
731
+ title: metrics.cacheWarm
732
+ ? `Keep coding — warm prefix active (${metrics.ttlCompact} remaining)`
733
+ : 'Keep coding — context headroom is clean',
734
+ instruction: metrics.cacheWarm
735
+ ? `Hold model switches and CLAUDE.md edits while ${formatTokensCompact(metrics.cachedTokens)} is reading at 0.10x.`
736
+ : 'No compaction or intervention needed right now.',
737
+ commandHint: '',
738
+ reclaimTokens: 0
739
+ });
740
+ }
741
+
742
+ const priorityAction = actions[0];
743
+ const secondaryActions = actions.slice(1);
744
+
745
+ return {
746
+ verdict,
747
+ priorityAction,
748
+ secondaryActions,
749
+ overflowActionCount: secondaryActions.length
750
+ };
751
+ }
752
+
753
+ /**
754
+ * 1. Renders the `AbovePrompt` 1-line Band with the 40-Cell Horizon Bar and active Coach Pill.
755
+ *
756
+ * @param {object} [state={}]
757
+ * @param {object} [options={}]
758
+ * @returns {{
759
+ * line: string,
760
+ * plainLine: string,
761
+ * grid: object,
762
+ * metrics: object,
763
+ * coachPill: string
764
+ * }}
765
+ */
766
+ export function renderAbovePromptBand(state = {}, options = {}) {
767
+ const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
768
+ const useAnsi = Boolean(options.ansi) && !isNoColorEnabled(options);
769
+ const grid = computeHorizonGrid(state, options);
770
+ const metrics = deriveSurfaceMetrics(state, options);
771
+
772
+ let coachAction = 'HOLD WARM PREFIX';
773
+ if (options.breakerVerdict?.triggered) {
774
+ const breakerId =
775
+ options.breakerVerdict.detectorId || options.breakerVerdict.ruleId || 'BREAKER';
776
+ coachAction = `${breakerId} ACTIVE`;
777
+ } else if (state.thinkingDrift?.loop?.triggered) {
778
+ coachAction = `THINK LOOP ${state.thinkingDrift.lastDriftRatio ?? ''}x`;
779
+ } else if (state.cliffTriggered) {
780
+ coachAction = 'HAIKU 100K CLIFF (5X)';
781
+ } else if (state.preCliffWarningTriggered) {
782
+ coachAction = 'HAIKU 90K PRE-CLIFF';
783
+ } else if (metrics.amberAlert) {
784
+ coachAction = `TTL EXPIRING ${metrics.ttlCompact}`;
785
+ } else if (!metrics.cacheWarm) {
786
+ coachAction = 'COLD PREFIX';
787
+ }
788
+
789
+ const coachPill = `[${metrics.flightMode} · ${coachAction}]`;
790
+ const tokenBadge = `${formatTokensCompact(grid.totalInputTokens)}/${grid.zoomTier.id}`;
791
+ const ttlBadge = metrics.cacheWarm ? `TTL ${metrics.ttlCompact}` : 'TTL COLD';
792
+
793
+ const suffixWithPct = ` ${tokenBadge} (${grid.utilizationPct}%) · ${ttlBadge} · ${coachPill}`;
794
+ const suffixCompact = ` ${tokenBadge} · ${ttlBadge} · ${coachPill}`;
795
+
796
+ let plainCandidate = `AH ${grid.bracketedBar}${suffixWithPct}`;
797
+ let ansiCandidate = `AH ${grid.ansiCodeBar}${suffixWithPct}`;
798
+
799
+ if (plainCandidate.length > maxCols) {
800
+ const availWithPct = maxCols - 3 - suffixWithPct.length - 2;
801
+ const availCompact = maxCols - 3 - suffixCompact.length - 2;
802
+ if (availWithPct >= 12) {
803
+ const dynCells = Math.min(40, availWithPct);
804
+ const barGrid = computeHorizonGrid(state, { ...options, cellCount: dynCells });
805
+ plainCandidate = `AH ${barGrid.bracketedBar}${suffixWithPct}`;
806
+ ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixWithPct}`;
807
+ } else if (availCompact >= 8) {
808
+ const dynCells = Math.min(40, availCompact);
809
+ const barGrid = computeHorizonGrid(state, { ...options, cellCount: dynCells });
810
+ plainCandidate = `AH ${barGrid.bracketedBar}${suffixCompact}`;
811
+ ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixCompact}`;
812
+ } else {
813
+ const barGrid = computeHorizonGrid(state, { ...options, cellCount: 8 });
814
+ plainCandidate = `AH ${barGrid.bracketedBar}${suffixCompact}`;
815
+ ansiCandidate = `AH ${barGrid.ansiCodeBar}${suffixCompact}`;
816
+ }
817
+ }
818
+
819
+ if (plainCandidate.length > maxCols) {
820
+ plainCandidate = plainCandidate.slice(0, maxCols);
821
+ ansiCandidate = truncateAnsiVisible(ansiCandidate, maxCols);
822
+ }
823
+
824
+ const plainLine = plainCandidate;
825
+ const line = useAnsi ? ansiCandidate : plainLine;
826
+
827
+ return {
828
+ line,
829
+ plainLine,
830
+ grid,
831
+ metrics,
832
+ coachPill
833
+ };
834
+ }
835
+
836
+ /**
837
+ * 2. Renders the `Spinner` suffix appended during active turns (`· Cache 95% (4m12s) · Saved $1.84`).
838
+ *
839
+ * @param {object} [state={}]
840
+ * @param {object} [options={}]
841
+ * @returns {{
842
+ * suffix: string,
843
+ * cacheHitPct: number,
844
+ * ttlText: string,
845
+ * savedUSDText: string
846
+ * }}
847
+ */
848
+ export function renderSpinnerSuffix(state = {}, options = {}) {
849
+ const metrics = deriveSurfaceMetrics(state, options);
850
+ const ttlText = metrics.cacheWarm ? metrics.ttlCompact : 'cold';
851
+ const savedUSDText = formatUsd(metrics.savedUSD);
852
+ let suffix = `· Cache ${metrics.cacheHitPct}% (${ttlText}) · Saved ${savedUSDText}`;
853
+ if (state.prefixRetention?.measured) suffix += ` · ${formatRetentionCompact(state.prefixRetention)}`;
854
+ if (state.thinkingDrift?.loop?.triggered) suffix += ` · ${formatDriftCompact(state.thinkingDrift)}`;
855
+
856
+ return {
857
+ suffix,
858
+ cacheHitPct: metrics.cacheHitPct,
859
+ ttlText,
860
+ savedUSDText
861
+ };
862
+ }
863
+
864
+ /**
865
+ * Builds the ranked list of Top Context Offenders for Box 4 of the Simple View Pane.
866
+ *
867
+ * @param {object} state
868
+ * @param {object} grid
869
+ * @param {object} [options={}]
870
+ * @returns {Array<{ name: string, tokens: number, category: string, pct: number }>}
871
+ */
872
+ function buildTopContextOffenders(state = {}, grid, options = {}) {
873
+ if (Array.isArray(options.offenders) && options.offenders.length > 0) {
874
+ return options.offenders.slice(0, 4).map((item) => {
875
+ const name = String(item.name || 'Context Item');
876
+ return {
877
+ name,
878
+ tokens: Math.max(0, Number(item.tokens || 0)),
879
+ category: String(item.category || 'C'),
880
+ ignorable: isIgnorableClaudePath(name),
881
+ pct:
882
+ grid.totalInputTokens > 0
883
+ ? Number(((Number(item.tokens || 0) / grid.totalInputTokens) * 100).toFixed(1))
884
+ : 0
885
+ };
886
+ });
887
+ }
888
+
889
+ const entries = [
890
+ {
891
+ name: 'Middle-Window Distractor / Stale Tool Output',
892
+ tokens: grid.tokens.D,
893
+ category: '[D]',
894
+ ignorable: false
895
+ },
896
+ {
897
+ name: 'System Prompt & MCP Tool Schemas',
898
+ tokens: grid.tokens.S,
899
+ category: '[S]',
900
+ ignorable: false
901
+ },
902
+ {
903
+ name: 'Fresh 1.25x Cache Write Delta',
904
+ tokens: grid.tokens.W,
905
+ category: '[W]',
906
+ ignorable: false
907
+ },
908
+ {
909
+ name: 'Warm Cached Conversation Prefix',
910
+ tokens: grid.tokens.C,
911
+ category: '[C]',
912
+ ignorable: false
913
+ }
914
+ ].filter((e) => e.tokens > 0);
915
+
916
+ entries.sort((a, b) => b.tokens - a.tokens);
917
+
918
+ if (entries.length === 0) {
919
+ return [
920
+ {
921
+ name: 'No active context offenders recorded',
922
+ tokens: 0,
923
+ category: '[.]',
924
+ ignorable: false,
925
+ pct: 0
926
+ }
927
+ ];
928
+ }
929
+
930
+ return entries.slice(0, 4).map((e) => ({
931
+ ...e,
932
+ pct:
933
+ grid.totalInputTokens > 0
934
+ ? Number(((e.tokens / grid.totalInputTokens) * 100).toFixed(1))
935
+ : 0
936
+ }));
937
+ }
938
+
939
+ /**
940
+ * 3. Renders the Docked `Pane` (`id: 'attention-horizon'`) with both the 4-Rank Glanceable Simple View
941
+ * (`ranks` / `simpleText`) and the 5-Box vertical hierarchy (`boxes`, zero promotional banner text):
942
+ * - Rank 1: Status Verdict & Flight Header (`Healthy` / `Action Needed` / `Critical`)
943
+ * - Rank 2: 40-Cell Horizon Bar, 3-Stat Row & 5m/1h Prompt Cache Shield
944
+ * - Rank 3: Single Priority Next Action (+ overflow count for `/horizon advanced`)
945
+ * - Rank 4: Elevated "Tokens & USD Saved" Card (`This Session` + `30d Workspace` + Top Driver)
946
+ *
947
+ * @param {object} [state={}]
948
+ * @param {object} [options={}]
949
+ */
950
+ export function renderSimpleViewPane(state = {}, options = {}) {
951
+ const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
952
+ const grid = computeHorizonGrid(state, options);
953
+ const paneCellCount = maxCols >= 49 ? 40 : Math.max(8, maxCols - 9);
954
+ const paneGrid =
955
+ paneCellCount === 40 ? grid : computeHorizonGrid(state, { ...options, cellCount: paneCellCount });
956
+ const scaleRuler = buildScaleTickRuler(
957
+ grid.zoomTier.ceilingTokens,
958
+ paneGrid.bracketedBar.length
959
+ );
960
+ const metrics = deriveSurfaceMetrics(state, options);
961
+ const peerModel = resolveNaturalDownshiftPeer(grid.modelId);
962
+ const breakEven = computeBreakEvenCachedTokens(
963
+ {
964
+ currentModel: grid.modelId,
965
+ targetModel: peerModel,
966
+ expectedOutputTokens: 1500,
967
+ cacheTtlTier: metrics.ttlTier
968
+ },
969
+ options
970
+ );
971
+ const { verdict, priorityAction, secondaryActions, overflowActionCount } =
972
+ deriveClaudeCodeVerdictAndActions(state, grid, metrics, options);
973
+
974
+ const headroomTokens = Math.max(0, grid.zoomTier.ceilingTokens - grid.totalInputTokens);
975
+
976
+ // 4-Rank Glanceable Simple View (`ranks`)
977
+ const rank1Lines = [
978
+ `[Rank 1] ${verdict.badge}: ${verdict.headline}`,
979
+ `Model: ${state.modelLabel || grid.modelId} · Mode: ${metrics.flightMode} · ${verdict.detail}`
980
+ ];
981
+ const rank2Lines = [
982
+ `[Rank 2] Context Capacity & Prompt Cache Shield (${grid.zoomTier.label})`,
983
+ `Grid : ${paneGrid.bracketedBar}`,
984
+ `Scale: ${scaleRuler}`,
985
+ `Stats: Used ${formatTokensCompact(grid.totalInputTokens)}/${grid.zoomTier.id} (${grid.utilizationPct}%) | Stale Debt [D] ${formatTokensCompact(grid.tokens.D)} | Free ${formatTokensCompact(headroomTokens)}`,
986
+ `Cache: ${metrics.cacheWarm ? 'WARM' : 'COLD'} (${metrics.ttlTier}) · TTL ${metrics.ttlClock} (${metrics.ttlCompact}) · Hit ${metrics.cacheHitPct}%`
987
+ ];
988
+ const overflowNote =
989
+ overflowActionCount > 0 ? ` (+${overflowActionCount} more in /horizon advanced)` : '';
990
+ const rank3Lines = [
991
+ `[Rank 3] Next Action${overflowNote}`,
992
+ `Action: ${priorityAction.title}`,
993
+ `Guide : ${priorityAction.instruction}`
994
+ ];
995
+ const rank4Lines = [
996
+ `[Rank 4] Verified Tokens & USD Saved`,
997
+ `Saved : +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) this session · +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)}) 30d`,
998
+ `Driver: ${metrics.topSavingsDriver.shortLabel} (+${formatTokensCompact(metrics.topSavingsDriver.savedTokens)})`
999
+ ];
1000
+
1001
+ const rawRanks = [
1002
+ {
1003
+ rankNumber: 1,
1004
+ id: 'status-verdict-header',
1005
+ title: 'Status Verdict & Flight Header',
1006
+ lines: rank1Lines
1007
+ },
1008
+ {
1009
+ rankNumber: 2,
1010
+ id: 'capacity-cache-shield',
1011
+ title: 'Context Capacity & Prompt Cache Shield',
1012
+ lines: rank2Lines
1013
+ },
1014
+ {
1015
+ rankNumber: 3,
1016
+ id: 'priority-next-action',
1017
+ title: 'Priority Next Action',
1018
+ lines: rank3Lines
1019
+ },
1020
+ {
1021
+ rankNumber: 4,
1022
+ id: 'tokens-usd-saved',
1023
+ title: 'Verified Tokens & USD Saved',
1024
+ lines: rank4Lines
1025
+ }
1026
+ ];
1027
+
1028
+ const ranks = rawRanks.map((r) => {
1029
+ const clampedLines = r.lines.map((l) => clampPlainLine(l, maxCols));
1030
+ return {
1031
+ ...r,
1032
+ lines: clampedLines,
1033
+ text: clampedLines.join('\n')
1034
+ };
1035
+ });
1036
+
1037
+ // Box 1: Capacity & Horizon Bar + Tufte Scale-Tick Ruler
1038
+ const box1Lines = [
1039
+ `[Box 1] Capacity & Horizon Bar · ${grid.zoomTier.label}`,
1040
+ `Model: ${state.modelLabel || grid.modelId} | Tokens: ${formatTokensCompact(grid.totalInputTokens)} / ${grid.zoomTier.id} (${grid.utilizationPct}%)`,
1041
+ `Grid : ${paneGrid.bracketedBar}`,
1042
+ `Scale: ${scaleRuler}`,
1043
+ `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)})`
1044
+ ];
1045
+
1046
+ // Box 2: Cache Hold & 5m TTL Countdown
1047
+ const roiLabel = metrics.negativeCacheRoi
1048
+ ? `NEGATIVE ROI (Reads/Write ${metrics.readsPerWriteRatio.toFixed(2)} < ${metrics.breakEvenReadsPerWrite})`
1049
+ : `POSITIVE ROI (Hit ${metrics.cacheHitPct}% | R/W ${metrics.readsPerWriteRatio.toFixed(2)} >= ${metrics.breakEvenReadsPerWrite})`;
1050
+ const ttlAlertText = metrics.amberAlert ? ' [AMBER TTL ALERT <= 45s]' : '';
1051
+ const box2Lines = [
1052
+ `[Box 2] Cache Hold & 5m TTL Countdown`,
1053
+ `State: ${metrics.cacheWarm ? 'WARM' : 'COLD'} (${metrics.ttlTier} tier) | Countdown: ${metrics.ttlClock} (${metrics.ttlCompact})${ttlAlertText}`,
1054
+ `Break-Even Gravity C*: ${breakEven.breakEvenTokens.toLocaleString('en-US')} cached tokens`,
1055
+ `Cache ROI: ${roiLabel}`,
1056
+ `Prefix Retention: ${formatRetentionLabel(state.prefixRetention)}`,
1057
+ `Thinking Drift: ${formatDriftLabel(state.thinkingDrift)}`
1058
+ ];
1059
+
1060
+ // Sprint 2.1: Swarm & Worktrees block (progressive disclosure: only when subagents seen)
1061
+ const swarmSummary = computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() });
1062
+ if (swarmSummary.active) {
1063
+ box2Lines.push(`Swarm & Worktrees: ${swarmSummary.label}`);
1064
+ for (const w of swarmSummary.workers.slice(0, 4)) {
1065
+ const loc = w.branch || w.worktree ? ` @${w.branch || w.worktree}` : '';
1066
+ box2Lines.push(` · ${w.agentId} ${w.state}${w.state === 'waiting' ? ' ($0)' : ''} · ${formatTokensCompact(w.totalTokens)} · ${w.turns}t${loc}`);
1067
+ }
1068
+ if (swarmSummary.workers.length > 4) box2Lines.push(` · +${swarmSummary.workers.length - 4} more`);
1069
+ }
1070
+
1071
+ // Box 3: Active Coach / Circuit Breaker Slot
1072
+ const activeBreakerId =
1073
+ options.breakerVerdict?.detectorId || options.breakerVerdict?.ruleId || 'BREAKER';
1074
+ const activeBreaker = options.breakerVerdict?.triggered
1075
+ ? options.breakerVerdict.reason
1076
+ ? `${activeBreakerId} ACTIVE — ${options.breakerVerdict.reason}`
1077
+ : `${activeBreakerId} ACTIVE`
1078
+ : state.thinkingDrift?.loop?.triggered
1079
+ ? state.thinkingDrift.loop.message
1080
+ : state.cliffTriggered
1081
+ ? 'DET-12: Haiku 5.5 100k 5x pricing cliff exceeded'
1082
+ : state.preCliffWarningTriggered
1083
+ ? 'DET-12: Haiku 5.5 90k pre-cliff compaction recommended'
1084
+ : metrics.amberAlert
1085
+ ? 'DET-10: 5m KV-cache TTL <= 45s; hold mutations or flush State Baton'
1086
+ : 'All DET-01..32 circuit breakers nominal';
1087
+ const singleBox3Status = `Flight Mode: ${metrics.flightMode} | Status: ${activeBreaker}`;
1088
+ const box3Lines =
1089
+ singleBox3Status.length <= maxCols
1090
+ ? [
1091
+ `[Box 3] Active Coach / Circuit Breaker Slot`,
1092
+ singleBox3Status,
1093
+ `Action: ${priorityAction.title}`
1094
+ ]
1095
+ : [
1096
+ `[Box 3] Active Coach / Circuit Breaker Slot`,
1097
+ `Flight Mode: ${metrics.flightMode}`,
1098
+ `Status: ${activeBreaker}`,
1099
+ `Action: ${priorityAction.title}`
1100
+ ];
1101
+
1102
+ // Box 4: Top Context Offenders
1103
+ const offenders = buildTopContextOffenders(state, grid, options);
1104
+ const offenderLines = offenders.map((o, idx) => {
1105
+ const prefix = ` ${idx + 1}. ${o.category} `;
1106
+ const suffix = `: ${formatTokensCompact(o.tokens)} (${o.pct}%)`;
1107
+ const maxNameLen = Math.max(6, maxCols - prefix.length - suffix.length);
1108
+ const safeName =
1109
+ o.name.length > maxNameLen ? `${o.name.slice(0, maxNameLen - 1)}…` : o.name;
1110
+ return `${prefix}${safeName}${suffix}`;
1111
+ });
1112
+ const box4Lines = [`[Box 4] Top Context Offenders`, ...offenderLines];
1113
+
1114
+ // Box 5: Deterministic Saved-Quota Receipt in USD & Tokens
1115
+ const box5Lines = [
1116
+ `[Box 5] Deterministic Saved-Quota Receipt`,
1117
+ `Verified Savings: ${formatUsd(metrics.savedUSD)} USD | ${metrics.savedTokens.toLocaleString('en-US')} tokens preserved`,
1118
+ `Session: +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) | 30d: +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)})`
1119
+ ];
1120
+
1121
+ const rawBoxes = [
1122
+ {
1123
+ boxNumber: 1,
1124
+ id: 'capacity-horizon-bar',
1125
+ title: 'Capacity & Horizon Bar',
1126
+ lines: box1Lines
1127
+ },
1128
+ {
1129
+ boxNumber: 2,
1130
+ id: 'cache-hold-ttl-countdown',
1131
+ title: 'Cache Hold & 5m TTL Countdown',
1132
+ lines: box2Lines
1133
+ },
1134
+ {
1135
+ boxNumber: 3,
1136
+ id: 'active-coach-circuit-breaker',
1137
+ title: 'Active Coach / Circuit Breaker Slot',
1138
+ lines: box3Lines
1139
+ },
1140
+ {
1141
+ boxNumber: 4,
1142
+ id: 'top-context-offenders',
1143
+ title: 'Top Context Offenders',
1144
+ lines: box4Lines
1145
+ },
1146
+ {
1147
+ boxNumber: 5,
1148
+ id: 'saved-quota-receipt',
1149
+ title: 'Deterministic Saved-Quota Receipt',
1150
+ lines: box5Lines
1151
+ }
1152
+ ];
1153
+
1154
+ const boxes = rawBoxes.map((b) => {
1155
+ const clampedLines = b.lines.map((l) => clampPlainLine(l, maxCols));
1156
+ return {
1157
+ ...b,
1158
+ lines: clampedLines,
1159
+ text: clampedLines.join('\n')
1160
+ };
1161
+ });
1162
+
1163
+ const divider = '─'.repeat(Math.min(76, maxCols));
1164
+ const simpleText = ranks.map((r) => r.text).join(`\n${divider}\n`);
1165
+ const boxText = boxes.map((b) => b.text).join(`\n${divider}\n`);
1166
+ const useRankMode = options.viewMode === 'SIMPLE_4_RANK' || options.layout === '4-rank';
1167
+
1168
+ return {
1169
+ paneId: 'attention-horizon',
1170
+ title: 'Highbeam',
1171
+ viewMode: useRankMode ? 'SIMPLE_4_RANK' : 'SIMPLE_5_BOX',
1172
+ ranks,
1173
+ simpleText,
1174
+ boxes,
1175
+ text: useRankMode ? simpleText : boxText,
1176
+ verdict,
1177
+ priorityAction,
1178
+ secondaryActions,
1179
+ overflowActionCount,
1180
+ grid,
1181
+ metrics
1182
+ };
1183
+ }
1184
+
1185
+ /**
1186
+ * Renders the pure 4-Rank Glanceable Simple View HUD (`viewMode: 'SIMPLE_4_RANK'`).
1187
+ *
1188
+ * @param {object} [state={}]
1189
+ * @param {object} [options={}]
1190
+ */
1191
+ export function renderSimpleHudPane(state = {}, options = {}) {
1192
+ return renderSimpleViewPane(state, { ...options, viewMode: 'SIMPLE_4_RANK' });
1193
+ }
1194
+
1195
+ /**
1196
+ * Renders the 5-Section Advanced View Workbench for Claude Code (`/horizon advanced` / `npx ah-claude receipt --advanced`):
1197
+ * Section 1: Verified 5-Category Savings & Anthropic Cache ROI (`C*` & `0.263`/`1.053` R/W)
1198
+ * Section 2: 40-Cell `[S]/[C]/[D]/[W]` Context Anatomy & Top Context Offenders
1199
+ * Section 3: Circuit Breakers (`DET-01..21`), Thinking Drift & Prefix Retention
1200
+ * Section 4: Subagent Swarm (`Task`/`Agent`), Worktrees & `DET-20` Scope Locks
1201
+ * Section 5: `PreCompact` State Baton (`HANDOFF_LATEST.md`) & Session Forensics
1202
+ *
1203
+ * @param {object} [state={}]
1204
+ * @param {object} [options={}]
1205
+ */
1206
+ export function renderAdvancedViewPane(state = {}, options = {}) {
1207
+ const maxCols = Math.max(40, Number(options.maxCols || globalThis.process?.stdout?.columns || 80));
1208
+ const simple = renderSimpleViewPane(state, options);
1209
+ const { grid, metrics } = simple;
1210
+ const peerModel = resolveNaturalDownshiftPeer(grid.modelId);
1211
+ const breakEven = computeBreakEvenCachedTokens(
1212
+ {
1213
+ currentModel: grid.modelId,
1214
+ targetModel: peerModel,
1215
+ expectedOutputTokens: 1500,
1216
+ cacheTtlTier: metrics.ttlTier
1217
+ },
1218
+ options
1219
+ );
1220
+ const offenders = buildTopContextOffenders(state, grid, options);
1221
+ const swarmSummary = computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() });
1222
+
1223
+ // Section 1: 5-Category Savings Breakdown & Anthropic Cache ROI
1224
+ const catOrder = [
1225
+ metrics.savingsCategories.cacheReadDiscount,
1226
+ metrics.savingsCategories.prefixBustAvoided,
1227
+ metrics.savingsCategories.toolOutputCompressed,
1228
+ metrics.savingsCategories.loopAndReadGuarded,
1229
+ metrics.savingsCategories.subagentIsolated
1230
+ ];
1231
+ const sec1Lines = [
1232
+ `[Section 1] Verified 5-Category Savings & Anthropic Cache ROI`,
1233
+ `Headline: +${formatTokensCompact(metrics.sessionSavedTokens)} (${formatUsd(metrics.sessionSavedUSD)}) session · +${formatTokensCompact(metrics.workspace30dSavedTokens)} (${formatUsd(metrics.workspace30dSavedUSD)}) 30d`,
1234
+ ...catOrder.map(
1235
+ (c, idx) =>
1236
+ ` ${idx + 1}. ${c.shortLabel}: +${formatTokensCompact(c.savedTokens)} (${formatUsd(c.savedUSD)}) [${c.count}x]`
1237
+ ),
1238
+ `Break-Even Gravity C*: ${breakEven.breakEvenTokens.toLocaleString('en-US')} cached tok (${grid.modelId} -> ${peerModel})`,
1239
+ `Reads/Write Ratio: ${metrics.readsPerWriteRatio.toFixed(2)} (target >= ${metrics.breakEvenReadsPerWrite} for ${metrics.ttlTier} TTL)`
1240
+ ];
1241
+
1242
+ // Section 2: 40-Cell [S]/[C]/[D]/[W] Anatomy & Top Context Offenders
1243
+ const sec2Lines = [
1244
+ `[Section 2] 40-Cell Context Anatomy & Top Context Offenders`,
1245
+ `[S] System & MCP Schemas : ${grid.cellCounts.S} cells (${formatTokensCompact(grid.tokens.S)})`,
1246
+ `[C] Warm Cached Prefix : ${grid.cellCounts.C} cells (${formatTokensCompact(grid.tokens.C)})`,
1247
+ `[D] Stale Tool Debt : ${grid.cellCounts.D} cells (${formatTokensCompact(grid.tokens.D)})`,
1248
+ `[W] Fresh 1.25x Write : ${grid.cellCounts.W} cells (${formatTokensCompact(grid.tokens.W)})`,
1249
+ ...offenders.map(
1250
+ (o, idx) =>
1251
+ ` Offender ${idx + 1}: ${o.category} ${o.name} — ${formatTokensCompact(o.tokens)} (${o.pct}%)${o.ignorable ? ' [.claudeignore candidate]' : ''}`
1252
+ )
1253
+ ];
1254
+
1255
+ // Section 3: Circuit Breakers (DET-01..32), Thinking Drift & Prefix Retention
1256
+ const activeBreakerId =
1257
+ options.breakerVerdict?.detectorId || options.breakerVerdict?.ruleId || null;
1258
+ const sec3Lines = [
1259
+ `[Section 3] Circuit Breakers (DET-01..32), Thinking Drift & Retention`,
1260
+ `Flight Mode: ${metrics.flightMode} | Active Trigger: ${activeBreakerId ? `${activeBreakerId} (${options.breakerVerdict?.reason || 'active'})` : 'None (32 guards nominal)'}`,
1261
+ `Prefix Retention: ${formatRetentionLabel(state.prefixRetention)}`,
1262
+ `Thinking Drift (DET-30): ${formatDriftLabel(state.thinkingDrift)}`,
1263
+ `Haiku 100k 5x Cliff (DET-12): ${state.cliffTriggered ? 'EXCEEDED (5x step-up)' : state.preCliffWarningTriggered ? 'PRE-CLIFF WARNING (>= 90k)' : 'Nominal'}`
1264
+ ];
1265
+
1266
+ // Section 4: Subagent Swarm (Task/Agent), Worktrees & DET-20 Scope Locks
1267
+ const sec4Lines = [
1268
+ `[Section 4] Subagent Swarm (Task/Agent), Worktrees & Scope Locks`,
1269
+ `Topology: ${swarmSummary.active ? swarmSummary.label : 'Solo main agent (0 active Task/Agent subagents)'}`
1270
+ ];
1271
+ if (swarmSummary.active) {
1272
+ for (const w of swarmSummary.workers.slice(0, 6)) {
1273
+ const loc = w.branch || w.worktree ? ` @${w.branch || w.worktree}` : '';
1274
+ sec4Lines.push(
1275
+ ` · ${w.agentId} [${w.state}${w.state === 'waiting' ? ' $0' : ''}] ${formatTokensCompact(w.totalTokens)} (${w.turns}t)${loc}`
1276
+ );
1277
+ }
1278
+ }
1279
+
1280
+ // Section 5: PreCompact State Baton & Session Forensics
1281
+ const sec5Lines = [
1282
+ `[Section 5] PreCompact State Baton & Claude Code Forensics`,
1283
+ `Session ID: ${state.sessionId || 'default'} | Completed Turns: ${Number(state.turnsCompleted || 0)}`,
1284
+ `Zoom Tier : ${grid.zoomTier.label} (${grid.zoomTier.tokensPerCell.toLocaleString('en-US')} tok/cell)`,
1285
+ `State Baton: Auto-flushed on PreCompact to .claude/cache/HANDOFF_LATEST.md`,
1286
+ `CLI Tools : npx ctxtop statusline | npx ctxtop radar | npx ctxtop inspect | npx ctxtop doctor`
1287
+ ];
1288
+
1289
+ const rawSections = [
1290
+ {
1291
+ sectionNumber: 1,
1292
+ id: 'savings-and-cache-roi',
1293
+ title: 'Verified 5-Category Savings & Anthropic Cache ROI',
1294
+ lines: sec1Lines
1295
+ },
1296
+ {
1297
+ sectionNumber: 2,
1298
+ id: 'context-anatomy-offenders',
1299
+ title: '40-Cell Context Anatomy & Top Context Offenders',
1300
+ lines: sec2Lines
1301
+ },
1302
+ {
1303
+ sectionNumber: 3,
1304
+ id: 'circuit-breakers-drift',
1305
+ title: 'Circuit Breakers (DET-01..21), Thinking Drift & Retention',
1306
+ lines: sec3Lines
1307
+ },
1308
+ {
1309
+ sectionNumber: 4,
1310
+ id: 'subagent-swarm-worktrees',
1311
+ title: 'Subagent Swarm (Task/Agent), Worktrees & Scope Locks',
1312
+ lines: sec4Lines
1313
+ },
1314
+ {
1315
+ sectionNumber: 5,
1316
+ id: 'state-baton-forensics',
1317
+ title: 'PreCompact State Baton & Claude Code Forensics',
1318
+ lines: sec5Lines
1319
+ }
1320
+ ];
1321
+
1322
+ const sections = rawSections.map((s) => {
1323
+ const clampedLines = s.lines.map((l) => clampPlainLine(l, maxCols));
1324
+ return {
1325
+ ...s,
1326
+ lines: clampedLines,
1327
+ text: clampedLines.join('\n')
1328
+ };
1329
+ });
1330
+
1331
+ const divider = '─'.repeat(Math.min(76, maxCols));
1332
+ const text = sections.map((s) => s.text).join(`\n${divider}\n`);
1333
+
1334
+ return {
1335
+ paneId: 'attention-horizon',
1336
+ title: 'Highbeam (Advanced View)',
1337
+ viewMode: 'ADVANCED_5_SECTION',
1338
+ sections,
1339
+ boxes: simple.boxes,
1340
+ ranks: simple.ranks,
1341
+ text,
1342
+ verdict: simple.verdict,
1343
+ priorityAction: simple.priorityAction,
1344
+ grid,
1345
+ metrics
1346
+ };
1347
+ }
1348
+
1349
+ /**
1350
+ * 4. Renders a single-line terminal `statusLine` adapting cleanly to terminal column width
1351
+ * (`80`, `110`, `144`, or arbitrary column count).
1352
+ *
1353
+ * Guaranteed invariant: `stripAnsi(result.line).length <= columns`.
1354
+ *
1355
+ * @param {object} [state={}]
1356
+ * @param {object} [options={}]
1357
+ * @param {number} [options.columns=110]
1358
+ * @param {boolean} [options.ansi=true]
1359
+ * @returns {{
1360
+ * line: string,
1361
+ * plainLine: string,
1362
+ * visibleLength: number,
1363
+ * columns: number,
1364
+ * layoutTier: 'compact-80'|'standard-110'|'wide-144',
1365
+ * grid: object,
1366
+ * metrics: object
1367
+ * }}
1368
+ */
1369
+ export function renderStatusLine(state = {}, options = {}) {
1370
+ const columns = Math.max(
1371
+ 40,
1372
+ Number(options.columns || options.maxCols || globalThis.process?.stdout?.columns || 110)
1373
+ );
1374
+ const useAnsi = options.ansi !== false && !isNoColorEnabled(options);
1375
+ const metrics = deriveSurfaceMetrics(state, options);
1376
+
1377
+ let layoutTier = 'standard-110';
1378
+ let candidateBarWidths = [24, 20, 16, 12];
1379
+ if (columns < 96) {
1380
+ layoutTier = 'compact-80';
1381
+ candidateBarWidths = [20, 16, 14, 12];
1382
+ } else if (columns >= 132) {
1383
+ layoutTier = 'wide-144';
1384
+ candidateBarWidths = [40, 24, 20, 16, 12];
1385
+ }
1386
+
1387
+ const breakerId =
1388
+ options.breakerVerdict?.detectorId || options.breakerVerdict?.ruleId || '';
1389
+ const shortMode =
1390
+ metrics.flightMode === 'AUTO_PILOT' ? 'AUTO' : metrics.flightMode;
1391
+ const fullCoachPill =
1392
+ options.breakerVerdict?.triggered && breakerId
1393
+ ? `[${shortMode}·${breakerId}]`
1394
+ : layoutTier === 'wide-144'
1395
+ ? `[${metrics.flightMode}]`
1396
+ : metrics.flightMode;
1397
+ const compactCoachPill =
1398
+ options.breakerVerdict?.triggered && breakerId ? breakerId : shortMode;
1399
+
1400
+ const pillVariants =
1401
+ fullCoachPill === compactCoachPill ? [fullCoachPill] : [fullCoachPill, compactCoachPill];
1402
+
1403
+ let chosenGrid = null;
1404
+ let plainCandidate = '';
1405
+ let ansiCandidate = '';
1406
+ let matchedFit = false;
1407
+
1408
+ for (const pill of pillVariants) {
1409
+ for (const barWidth of candidateBarWidths) {
1410
+ const g = computeHorizonGrid(state, { ...options, cellCount: barWidth });
1411
+ const tokStr = `${formatTokensCompact(g.totalInputTokens)}/${g.zoomTier.id}`;
1412
+ const ttlStr = metrics.cacheWarm ? metrics.ttlCompact : 'COLD';
1413
+ const savedStr = formatUsd(metrics.savedUSD);
1414
+ const loopStr = state.thinkingDrift?.loop?.triggered ? ` ${formatDriftCompact(state.thinkingDrift)}` : '';
1415
+ const retStr = state.prefixRetention?.measured ? ` · ${formatRetentionCompact(state.prefixRetention)}` : '';
1416
+ const swarmTok = layoutTier === 'wide-144' ? formatSwarmCompact(computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() })) : '';
1417
+ const swarmStr = swarmTok ? ` · ${swarmTok}` : '';
1418
+
1419
+ let p = '';
1420
+ let a = '';
1421
+ if (layoutTier === 'compact-80') {
1422
+ p = `AH ${g.bracketedBar} ${tokStr} C:${metrics.cacheHitPct}% ${ttlStr} ${pill}${loopStr} ${savedStr}`;
1423
+ a = `AH ${g.ansiCodeBar} ${tokStr} C:${metrics.cacheHitPct}% ${ttlStr} ${pill}${loopStr} ${savedStr}`;
1424
+ } else {
1425
+ const shortModel = g.modelId.replace(/^claude-/, '');
1426
+ p = `AH ${g.bracketedBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}`;
1427
+ a = `AH ${g.ansiCodeBar} ${shortModel} ${tokStr} (${g.utilizationPct}%) · Cache ${metrics.cacheHitPct}% (${ttlStr})${retStr} · ${pill}${loopStr} · Saved ${savedStr}${swarmStr}`;
1428
+ }
1429
+
1430
+ chosenGrid = g;
1431
+ plainCandidate = p;
1432
+ ansiCandidate = a;
1433
+
1434
+ if (p.length <= columns) {
1435
+ matchedFit = true;
1436
+ break;
1437
+ }
1438
+ }
1439
+ if (matchedFit) break;
1440
+ }
1441
+
1442
+ // Enforce strict column ceiling via ANSI-preserving truncation (never stripping ANSI colors!)
1443
+ if (plainCandidate.length > columns) {
1444
+ plainCandidate = plainCandidate.slice(0, columns);
1445
+ ansiCandidate = truncateAnsiVisible(ansiCandidate, columns);
1446
+ }
1447
+
1448
+ const finalLine = useAnsi ? ansiCandidate : plainCandidate;
1449
+ const visibleLength = stripAnsi(finalLine).length;
1450
+
1451
+ return {
1452
+ line: finalLine,
1453
+ plainLine: stripAnsi(finalLine),
1454
+ visibleLength,
1455
+ columns,
1456
+ layoutTier,
1457
+ grid: chosenGrid,
1458
+ metrics
1459
+ };
1460
+ }
1461
+
1462
+ export default {
1463
+ stripAnsi,
1464
+ truncateAnsiVisible,
1465
+ buildScaleTickRuler,
1466
+ formatTokensCompact,
1467
+ formatDurationCompact,
1468
+ formatUsd,
1469
+ isIgnorableClaudePath,
1470
+ deriveClaudeCodeVerdictAndActions,
1471
+ deriveSurfaceMetrics,
1472
+ renderAbovePromptBand,
1473
+ renderSpinnerSuffix,
1474
+ renderSimpleViewPane,
1475
+ renderSimpleHudPane,
1476
+ renderAdvancedViewPane,
1477
+ renderStatusLine
1478
+ };