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
package/bin/ctxtop.mjs ADDED
@@ -0,0 +1,1474 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file bin/ctxtop.mjs
4
+ * Highbeam v4.0 Unified Cross-Platform CLI (`ctxtop`).
5
+ *
6
+ * Commands:
7
+ * - `ctxtop init [--antigravity | --claude | --all | --workspace | --project | --dry-run | --dedupe]`
8
+ * - `ctxtop install [--global | --project]`
9
+ * - `ctxtop uninstall [--global | --project]`
10
+ * - `ctxtop doctor [--diagnostic | --json]`
11
+ * - `ctxtop receipt [--advanced | --markdown | --json]`
12
+ * - `ctxtop config [list | set <DET-ID> <mode> | reset]`
13
+ * - `ctxtop cost-radar [--out <file.html>] [--json]`
14
+ * - `ctxtop panel [--advanced] [--out <file.html>]`
15
+ * - `ctxtop statusline [--demo]`
16
+ * - `ctxtop postmortem [--last N]`
17
+ */
18
+
19
+ import {
20
+ fs,
21
+ path,
22
+ os,
23
+ url,
24
+ fileURLToPath,
25
+ readJsonSafe,
26
+ writeTextAtomic,
27
+ writeJsonAtomic
28
+ } from '../src/utils/nodeIo.mjs';
29
+ import {
30
+ loadHorizonConfig,
31
+ setDetectorOverride,
32
+ resetHorizonConfig
33
+ } from '../src/core-isomorphic/config/horizonConfig.mjs';
34
+ import {
35
+ readLiveStateSnapshot,
36
+ sanitizeSessionId,
37
+ getLiveStateBridgePath
38
+ } from '../src/core-isomorphic/telemetry/telemetryBridge.mjs';
39
+ import {
40
+ normalizeSessionTrajectory,
41
+ normalizeAntigravitySession,
42
+ normalizeClaudeCodeSession,
43
+ createEmptyUstfSession
44
+ } from '../src/core-isomorphic/ustf/index.mjs';
45
+ import {
46
+ getHomeDir,
47
+ getBrainStores,
48
+ getAntigravitySurfaces
49
+ } from '../src/core/paths.mjs';
50
+ import { runPostmortem, printPostmortemSummary } from '../src/cli/postmortem.mjs';
51
+ import { runDoctor, parseDoctorArgs } from '../src/cli/doctor.mjs';
52
+ import { getSavedQuotaReceiptSummary } from '../src/core-isomorphic/coach/savedQuotaLedger.mjs';
53
+ import {
54
+ renderSimpleViewPane,
55
+ renderSimpleHudPane,
56
+ renderAdvancedViewPane
57
+ } from '../src/core-isomorphic/ui/modViews.mjs';
58
+ import { renderHorizonPanelHtml } from '../src/core-isomorphic/ui/horizonPanelHtml.mjs';
59
+ import { renderCostRadarHtml } from '../src/core-isomorphic/ui/costRadarSvg.mjs';
60
+ import {
61
+ generateCorporateExpenseReceipt,
62
+ sha256HexPure
63
+ } from '../src/core-isomorphic/ui/pdfReceiptGenerator.mjs';
64
+ import {
65
+ activateProLicense,
66
+ activateLocalTrial,
67
+ deactivateProLicense,
68
+ getProEntitlementStatus,
69
+ requireProFeature,
70
+ verifyProLicenseKey,
71
+ PLG_TIER_MATRIX
72
+ } from '../src/core/pro_license.mjs';
73
+ import { generateTeamFinopsPack } from '../packages/pro/src/team_finops_pack.mjs';
74
+ import {
75
+ computeSwarmSummary,
76
+ toCostRadarTopology,
77
+ formatSwarmCompact
78
+ } from '../src/core-isomorphic/telemetry/swarmTopology.mjs';
79
+ import {
80
+ formatRetentionLabel,
81
+ formatDriftLabel
82
+ } from '../src/core-isomorphic/telemetry/sprintMetrics.mjs';
83
+ import {
84
+ transitionControlState,
85
+ serializeControlFile,
86
+ parseControlFile
87
+ } from '../src/core-isomorphic/control/index.mjs';
88
+ import { MicroIpcClient } from '../src/engine-node/ipc/client.mjs';
89
+ import {
90
+ generateZeroPiiDiagnosticBundle,
91
+ generateGitCommitEfficiencyReceipt
92
+ } from '../src/diagnostics/bugReportGenerator.mjs';
93
+ import {
94
+ inspectHookDiagnostics,
95
+ runDoctorDiagnostics
96
+ } from '../src/diagnostics/doctorEngine.mjs';
97
+ import { installPlugin, runLiveOrDemoCli } from '../src/cli/init.mjs';
98
+ import { executeStatusLineBridge, runStatusLineCli } from './ah-statusline.mjs';
99
+
100
+ export { inspectHookDiagnostics, runDoctorDiagnostics };
101
+
102
+ export const PKG_ROOT = path
103
+ .resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
104
+ .replace(/\\/g, '/');
105
+
106
+ export const PRE_TOOL_USE_MATCHER =
107
+ 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Read|Grep|Glob|Task|Agent|WebFetch|mcp__.*';
108
+ export const POST_TOOL_USE_MATCHER =
109
+ 'Bash|PowerShell|Grep|Glob|Task|Agent|WebFetch|mcp__.*';
110
+ export const LEAN_PRE_TOOL_USE_MATCHER =
111
+ 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Task|Agent|WebFetch|mcp__.*';
112
+ export const LEAN_POST_TOOL_USE_MATCHER =
113
+ 'Bash|PowerShell|Task|Agent|WebFetch|mcp__.*';
114
+
115
+ const AH_HANDLER_REGEX =
116
+ /hooks[\\/]handlers[\\/](pre-tool-use|post-tool-use|pre-model-switch|compact-lifecycle|stop-gate)\.mjs/i;
117
+ const AH_STATUSLINE_REGEX = /ah-statusline\.mjs/i;
118
+ const AH_MOD_REGISTER_REGEX = /(?:^|[\\/])hooks[\\/]register\.js$|^\.\/register\.js$/i;
119
+
120
+ /**
121
+ * Extracts the Highbeam command string from either a nested (`{ hooks: [{ command }] }`)
122
+ * or legacy flat (`{ command }`) hook entry.
123
+ *
124
+ * @param {object} entry
125
+ * @returns {string}
126
+ */
127
+ export function extractAhCommandFromEntry(entry) {
128
+ if (!entry || typeof entry !== 'object') return '';
129
+ if (typeof entry.command === 'string' && AH_HANDLER_REGEX.test(entry.command)) {
130
+ return entry.command;
131
+ }
132
+ if (Array.isArray(entry.hooks)) {
133
+ const found = entry.hooks.find((inner) =>
134
+ AH_HANDLER_REGEX.test(String(inner?.command || ''))
135
+ );
136
+ if (found) return String(found.command || '');
137
+ }
138
+ return '';
139
+ }
140
+
141
+ /**
142
+ * Builds canonical nested Claude Code hook entries using either `${CLAUDE_PLUGIN_ROOT}`
143
+ * (when `usePluginRootVar: true`) or double-quoted absolute `${pkgRoot}` paths.
144
+ *
145
+ * @param {object} [options={}]
146
+ * @returns {Record<string, Array<object>>}
147
+ */
148
+ export function buildCanonicalAhHooks(options = {}) {
149
+ const rootPrefix = options.usePluginRootVar
150
+ ? '${CLAUDE_PLUGIN_ROOT}'
151
+ : options.pkgRoot
152
+ ? String(options.pkgRoot).replace(/\\/g, '/').replace(/\/+$/, '')
153
+ : PKG_ROOT;
154
+
155
+ const handlerPrefix = `${rootPrefix}/hooks/handlers`;
156
+ const preMatcher = options.leanHooks ? LEAN_PRE_TOOL_USE_MATCHER : PRE_TOOL_USE_MATCHER;
157
+ const postMatcher = options.leanHooks ? LEAN_POST_TOOL_USE_MATCHER : POST_TOOL_USE_MATCHER;
158
+
159
+ return {
160
+ PreToolUse: [
161
+ {
162
+ matcher: preMatcher,
163
+ hooks: [
164
+ {
165
+ type: 'command',
166
+ command: `node "${handlerPrefix}/pre-tool-use.mjs"`
167
+ }
168
+ ]
169
+ }
170
+ ],
171
+ PostToolUse: [
172
+ {
173
+ matcher: postMatcher,
174
+ hooks: [
175
+ {
176
+ type: 'command',
177
+ command: `node "${handlerPrefix}/post-tool-use.mjs"`
178
+ }
179
+ ]
180
+ }
181
+ ],
182
+ PreModelSwitch: [
183
+ {
184
+ hooks: [
185
+ {
186
+ type: 'command',
187
+ command: `node "${handlerPrefix}/pre-model-switch.mjs"`
188
+ }
189
+ ]
190
+ }
191
+ ],
192
+ PreCompact: [
193
+ {
194
+ hooks: [
195
+ {
196
+ type: 'command',
197
+ command: `node "${handlerPrefix}/compact-lifecycle.mjs" --phase=pre`
198
+ }
199
+ ]
200
+ }
201
+ ],
202
+ PostCompact: [
203
+ {
204
+ hooks: [
205
+ {
206
+ type: 'command',
207
+ command: `node "${handlerPrefix}/compact-lifecycle.mjs" --phase=post`
208
+ }
209
+ ]
210
+ }
211
+ ],
212
+ SessionStart: [
213
+ {
214
+ matcher: 'startup|resume|clear|compact|fork',
215
+ hooks: [
216
+ {
217
+ type: 'command',
218
+ command: `node "${handlerPrefix}/compact-lifecycle.mjs" --phase=start`
219
+ }
220
+ ]
221
+ }
222
+ ],
223
+ Stop: [
224
+ {
225
+ hooks: [
226
+ {
227
+ type: 'command',
228
+ command: `node "${handlerPrefix}/stop-gate.mjs"`
229
+ }
230
+ ]
231
+ }
232
+ ]
233
+ };
234
+ }
235
+
236
+ export const CANONICAL_AH_HOOKS = Object.freeze(buildCanonicalAhHooks({ usePluginRootVar: false }));
237
+
238
+ export function isAttentionHorizonHookEntry(entry) {
239
+ return Boolean(extractAhCommandFromEntry(entry));
240
+ }
241
+
242
+ export function resolveSettingsPath(options = {}) {
243
+ if (typeof options.settingsPath === 'string' && options.settingsPath.trim()) {
244
+ return options.settingsPath.trim();
245
+ }
246
+ const scope = options.scope === 'global' || options.global ? 'global' : 'project';
247
+ if (scope === 'global') {
248
+ const home = options.homeDir || os.homedir() || '.';
249
+ return path.join(home, '.claude', 'settings.json');
250
+ }
251
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
252
+ return path.join(cwd, '.claude', 'settings.json');
253
+ }
254
+
255
+ export function ensureGitExcludeEntries(cwd) {
256
+ const gitDir = path.join(cwd, '.git');
257
+ if (!fs.existsSync(gitDir)) {
258
+ return { updated: false, excludePath: null };
259
+ }
260
+
261
+ try {
262
+ const infoDir = path.join(gitDir, 'info');
263
+ if (!fs.existsSync(infoDir)) {
264
+ fs.mkdirSync(infoDir, { recursive: true });
265
+ }
266
+ const excludePath = path.join(infoDir, 'exclude');
267
+ const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf8') : '';
268
+ const lines = existing.split(/\r?\n/);
269
+ const required = ['.claude/cache/', '.claude/locks/'];
270
+ let appended = false;
271
+ let nextContent = existing;
272
+
273
+ for (const req of required) {
274
+ if (!lines.some((line) => line.trim() === req)) {
275
+ if (nextContent.length > 0 && !nextContent.endsWith('\n')) {
276
+ nextContent += '\n';
277
+ }
278
+ nextContent += `${req}\n`;
279
+ appended = true;
280
+ }
281
+ }
282
+
283
+ if (appended) {
284
+ writeTextAtomic(excludePath, nextContent);
285
+ }
286
+ return { updated: appended, excludePath };
287
+ } catch (_err) {
288
+ return { updated: false, excludePath: null };
289
+ }
290
+ }
291
+
292
+ export function installAttentionHorizon(options = {}) {
293
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
294
+ const pkgRoot = options.pkgRoot
295
+ ? String(options.pkgRoot).replace(/\\/g, '/').replace(/\/+$/, '')
296
+ : PKG_ROOT;
297
+ const settingsPath = resolveSettingsPath(options);
298
+ const ts = options.timestamp || Date.now();
299
+ const dryRun = Boolean(options.dryRun);
300
+
301
+ let backupPath = null;
302
+ let currentSettings = {};
303
+
304
+ if (fs.existsSync(settingsPath)) {
305
+ backupPath = `${settingsPath}.ah-backup.${ts}`;
306
+ if (!dryRun) {
307
+ fs.copyFileSync(settingsPath, backupPath);
308
+ }
309
+ const parsed = readJsonSafe(settingsPath, {});
310
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
311
+ currentSettings = JSON.parse(JSON.stringify(parsed));
312
+ }
313
+ }
314
+
315
+ if (!currentSettings.hooks || typeof currentSettings.hooks !== 'object') {
316
+ currentSettings.hooks = {};
317
+ }
318
+
319
+ const canonicalRegisterPath = `${pkgRoot}/hooks/register.js`;
320
+ const existingModules = Array.isArray(currentSettings.hooks.modules)
321
+ ? [...currentSettings.hooks.modules]
322
+ : [];
323
+ const modIdx = existingModules.findIndex((m) => AH_MOD_REGISTER_REGEX.test(String(m)));
324
+ if (modIdx >= 0) {
325
+ existingModules[modIdx] = canonicalRegisterPath;
326
+ } else {
327
+ existingModules.push(canonicalRegisterPath);
328
+ }
329
+ currentSettings.hooks.modules = existingModules;
330
+
331
+ const useLeanHooks =
332
+ options.leanHooks !== undefined ? Boolean(options.leanHooks) : !Boolean(options.fullHooks);
333
+ const canonicalHooks = buildCanonicalAhHooks({
334
+ usePluginRootVar: false,
335
+ pkgRoot,
336
+ leanHooks: useLeanHooks
337
+ });
338
+ for (const [eventName, ahEntries] of Object.entries(canonicalHooks)) {
339
+ const existingList = Array.isArray(currentSettings.hooks[eventName])
340
+ ? [...currentSettings.hooks[eventName]]
341
+ : [];
342
+
343
+ for (const ahEntry of ahEntries) {
344
+ const targetCmd = ahEntry.hooks[0].command;
345
+ const targetHandlerMatch = targetCmd.match(AH_HANDLER_REGEX);
346
+ const targetHandlerName = targetHandlerMatch ? targetHandlerMatch[1].toLowerCase() : '';
347
+ const targetPhaseMatch = targetCmd.match(/--phase=([a-z]+)/i);
348
+ const targetPhase = targetPhaseMatch ? targetPhaseMatch[1].toLowerCase() : '';
349
+
350
+ const idx = existingList.findIndex((item) => {
351
+ const existingCmd = extractAhCommandFromEntry(item);
352
+ if (!existingCmd) return false;
353
+ const m = existingCmd.match(AH_HANDLER_REGEX);
354
+ const name = m ? m[1].toLowerCase() : '';
355
+ const pm = existingCmd.match(/--phase=([a-z]+)/i);
356
+ const phase = pm ? pm[1].toLowerCase() : '';
357
+ return name === targetHandlerName && phase === targetPhase;
358
+ });
359
+
360
+ const clonedEntry = JSON.parse(JSON.stringify(ahEntry));
361
+ if (idx >= 0) {
362
+ existingList[idx] = clonedEntry;
363
+ } else {
364
+ existingList.push(clonedEntry);
365
+ }
366
+ }
367
+
368
+ currentSettings.hooks[eventName] = existingList;
369
+ }
370
+
371
+ const ahStatusLine = {
372
+ type: 'command',
373
+ command: `node "${pkgRoot}/bin/ah-statusline.mjs"`
374
+ };
375
+ if (!currentSettings.statusLine) {
376
+ currentSettings.statusLine = ahStatusLine;
377
+ } else if (
378
+ typeof currentSettings.statusLine === 'object' &&
379
+ !AH_STATUSLINE_REGEX.test(String(currentSettings.statusLine.command || ''))
380
+ ) {
381
+ currentSettings.ahPreviousStatusLine = currentSettings.statusLine;
382
+ currentSettings.statusLine = ahStatusLine;
383
+ } else {
384
+ currentSettings.statusLine = ahStatusLine;
385
+ }
386
+
387
+ let ok = true;
388
+ if (!dryRun) {
389
+ ok = writeJsonAtomic(settingsPath, currentSettings);
390
+ }
391
+ const gitExclude = dryRun ? { updated: false } : ensureGitExcludeEntries(cwd);
392
+
393
+ return {
394
+ ok,
395
+ settingsPath,
396
+ backupPath,
397
+ gitExcludeUpdated: gitExclude.updated,
398
+ settings: currentSettings
399
+ };
400
+ }
401
+
402
+ export function uninstallAttentionHorizon(options = {}) {
403
+ const settingsPath = resolveSettingsPath(options);
404
+ if (!fs.existsSync(settingsPath)) {
405
+ return {
406
+ ok: true,
407
+ settingsPath,
408
+ removedHooksCount: 0,
409
+ settings: {}
410
+ };
411
+ }
412
+
413
+ const currentSettings = readJsonSafe(settingsPath, {});
414
+ let removedHooksCount = 0;
415
+
416
+ if (currentSettings.hooks && typeof currentSettings.hooks === 'object') {
417
+ if (Array.isArray(currentSettings.hooks.modules)) {
418
+ const before = currentSettings.hooks.modules.length;
419
+ currentSettings.hooks.modules = currentSettings.hooks.modules.filter(
420
+ (m) => !AH_MOD_REGISTER_REGEX.test(String(m))
421
+ );
422
+ removedHooksCount += before - currentSettings.hooks.modules.length;
423
+ if (currentSettings.hooks.modules.length === 0) {
424
+ delete currentSettings.hooks.modules;
425
+ }
426
+ }
427
+
428
+ for (const eventName of Object.keys(CANONICAL_AH_HOOKS)) {
429
+ if (Array.isArray(currentSettings.hooks[eventName])) {
430
+ const before = currentSettings.hooks[eventName].length;
431
+ currentSettings.hooks[eventName] = currentSettings.hooks[eventName].filter(
432
+ (entry) => !isAttentionHorizonHookEntry(entry)
433
+ );
434
+ removedHooksCount += before - currentSettings.hooks[eventName].length;
435
+ if (currentSettings.hooks[eventName].length === 0) {
436
+ delete currentSettings.hooks[eventName];
437
+ }
438
+ }
439
+ }
440
+ }
441
+
442
+ if (
443
+ currentSettings.statusLine &&
444
+ AH_STATUSLINE_REGEX.test(String(currentSettings.statusLine.command || ''))
445
+ ) {
446
+ if (currentSettings.ahPreviousStatusLine) {
447
+ currentSettings.statusLine = currentSettings.ahPreviousStatusLine;
448
+ delete currentSettings.ahPreviousStatusLine;
449
+ } else {
450
+ delete currentSettings.statusLine;
451
+ }
452
+ }
453
+
454
+ const ok = writeJsonAtomic(settingsPath, currentSettings);
455
+ return {
456
+ ok,
457
+ settingsPath,
458
+ removedHooksCount,
459
+ settings: currentSettings
460
+ };
461
+ }
462
+
463
+ export function generateReceiptReport(options = {}) {
464
+ const sessionId = options.sessionId || 'default';
465
+ const state = options.state || readLiveStateSnapshot(sessionId, options);
466
+ const summary = getSavedQuotaReceiptSummary(options);
467
+ const renderOpts = {
468
+ ...options,
469
+ ledgerSummary: summary
470
+ };
471
+ const pane = options.advanced
472
+ ? renderAdvancedViewPane(state, renderOpts)
473
+ : options.fourRank
474
+ ? renderSimpleHudPane(state, renderOpts)
475
+ : renderSimpleViewPane(state, renderOpts);
476
+ const gitReceipt = generateGitCommitEfficiencyReceipt(options);
477
+ const corporateReceipt = generateCorporateExpenseReceipt(summary, options);
478
+
479
+ return {
480
+ summary,
481
+ pane,
482
+ gitReceipt,
483
+ corporateReceipt,
484
+ text: pane.text,
485
+ markdown: gitReceipt.markdown,
486
+ html: corporateReceipt.html,
487
+ pdfBytes: corporateReceipt.pdfBytes
488
+ };
489
+ }
490
+
491
+ export function generateRoastCard(options = {}) {
492
+ const summary = getSavedQuotaReceiptSummary(options);
493
+ const sessionId = options.sessionId || 'default';
494
+ const live = options.state || readLiveStateSnapshot(sessionId, options) || {};
495
+ const retentionPct = Number(live?.prefixRetention?.retentionIndexPct ?? (options.demo ? 74 : 92));
496
+ const retentionGrade = live?.prefixRetention?.grade || (retentionPct >= 90 ? 'A' : retentionPct >= 75 ? 'B' : 'C');
497
+ const savedTok = Math.max(Number(summary.workspace30dSavedTokens || 0), options.demo ? 142800 : 0);
498
+ const savedUsd = Math.max(Number(summary.workspace30dSavedUSD || 0), options.demo ? 4.28 : 0);
499
+ const leakedUsd = Number(live?.prefixRetention?.leakedColdPrefillUSD ?? (options.demo ? 1.85 : 0.12));
500
+
501
+ const ascii = [
502
+ '╭── 🔥 HIGHBEAM CONTEXT ROAST (Claude Code + Antigravity) ──────────╮',
503
+ `│ KV-Cache Retention : Grade ${retentionGrade} (${retentionPct}% prefix warmth retained) │`,
504
+ `│ Cold Prefill Leak : $${leakedUsd.toFixed(2)} burned on avoidable cold-cache switches/edits │`,
505
+ `│ Verified Savings : +${savedTok.toLocaleString('en-US')} tokens ($${savedUsd.toFixed(2)} USD saved in 30d) │`,
506
+ '│ Top Remediation : Fence mid-session CLAUDE.md/AGENTS.md edits (DET-09) │',
507
+ '╰────────────────────────────────────────────────────────────────────────────╯',
508
+ `Share: Shielded +${savedTok.toLocaleString('en-US')} tokens ($${savedUsd.toFixed(2)}) with npx ah-claude --roast #ClaudeCode #Antigravity`
509
+ ].join('\n');
510
+
511
+ const markdown = [
512
+ '### 🔥 Highbeam Context Roast (`npx ah-claude --roast`)',
513
+ `- **KV-Cache Retention**: Grade **${retentionGrade}** (${retentionPct}% warmth retained)`,
514
+ `- **Cold Prefill Leak**: **$${leakedUsd.toFixed(2)}** burned on avoidable cold switches`,
515
+ `- **30-Day Verified Savings**: **+${savedTok.toLocaleString('en-US')} tokens ($${savedUsd.toFixed(2)} USD)**`,
516
+ `- **Top Fix**: Fence mid-session \`CLAUDE.md\` / \`AGENTS.md\` edits via \`DET-09\` & offload >4k CLI dumps.`
517
+ ].join('\n');
518
+
519
+ return {
520
+ retentionPct,
521
+ retentionGrade,
522
+ leakedUsd,
523
+ savedTok,
524
+ savedUsd,
525
+ ascii,
526
+ markdown
527
+ };
528
+ }
529
+
530
+ export function generateHorizonPanel(options = {}) {
531
+ const sessionId = options.sessionId || 'default';
532
+ const state = options.state || readLiveStateSnapshot(sessionId, options) || {};
533
+ const ledgerSummary = options.ledgerSummary || getSavedQuotaReceiptSummary(options);
534
+ const panel = renderHorizonPanelHtml(state, {
535
+ ...options,
536
+ ledgerSummary,
537
+ initialView: options.advanced ? 'advanced' : options.initialView || 'simple'
538
+ });
539
+ const summary = {
540
+ verdict: panel.verdict.headline,
541
+ action: panel.priorityAction.title,
542
+ sessionSavedTokens: panel.metrics.sessionSavedTokens,
543
+ sessionSavedUSD: panel.metrics.sessionSavedUSD,
544
+ workspace30dSavedTokens: panel.metrics.workspace30dSavedTokens,
545
+ workspace30dSavedUSD: panel.metrics.workspace30dSavedUSD
546
+ };
547
+ return { html: panel.html, summary, state, panel };
548
+ }
549
+
550
+ export function generateCostRadar(options = {}) {
551
+ const sessionId = options.sessionId || 'default';
552
+ let state = options.state || readLiveStateSnapshot(sessionId, options) || {};
553
+ if (options.demo && (!state.prefixRetention || !state.prefixRetention.measured)) {
554
+ state = {
555
+ ...state,
556
+ prefixRetention: {
557
+ measured: true,
558
+ retentionIndexPct: 92,
559
+ grade: 'A',
560
+ retainedDiscountSavingsUSD: 1.5,
561
+ leakedColdPrefillUSD: 0.12,
562
+ measuredTurns: 5,
563
+ bustCount: 0,
564
+ timeline: []
565
+ },
566
+ thinkingDrift: {
567
+ ratio: 1.2,
568
+ loop: { triggered: false }
569
+ }
570
+ };
571
+ }
572
+ const swarm = computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() });
573
+ const html = renderCostRadarHtml({
574
+ retention: state.prefixRetention || null,
575
+ drift: state.thinkingDrift || null,
576
+ topology: toCostRadarTopology(swarm),
577
+ meta: {
578
+ sessionTitle: state.sessionTitle || state.sessionId || '',
579
+ model: state.modelLabel || state.modelId || '',
580
+ edition: 'Cross-Platform',
581
+ generatedAt: options.generatedAt || new Date().toISOString()
582
+ }
583
+ });
584
+ const summary = {
585
+ retention: formatRetentionLabel(state.prefixRetention),
586
+ drift: formatDriftLabel(state.thinkingDrift),
587
+ swarm: formatSwarmCompact(swarm) || 'Solo',
588
+ loopTriggered: Boolean(state.thinkingDrift?.loop?.triggered)
589
+ };
590
+ return { html, summary, state };
591
+ }
592
+
593
+ /**
594
+ * Unified `ctxtop init` installer router.
595
+ * Supports `--antigravity`, `--claude`, `--mcp`, `--cursor`, `--all`, `--workspace`, `--project`, `--dry-run`, `--dedupe`.
596
+ */
597
+ /**
598
+ * Non-destructively writes or merges the `@ctxtop/mcp` server entry into `.cursor/mcp.json`.
599
+ *
600
+ * @param {object} [options]
601
+ * @returns {{ ok: boolean, mcpPath: string, serverKey: string, serverScript: string, dryRun: boolean }}
602
+ */
603
+ export function installMcpConfig(options = {}) {
604
+ const isDryRun = Boolean(options.dryRun);
605
+ const isGlobal = options.scope === 'global' || Boolean(options.global);
606
+ const baseDir = isGlobal
607
+ ? options.homeDir || options.home || getHomeDir()
608
+ : options.cwd || process.cwd();
609
+ const mcpPath = options.mcpConfigPath
610
+ ? path.resolve(options.mcpConfigPath)
611
+ : path.join(baseDir, '.cursor', 'mcp.json');
612
+ const existing = readJsonSafe(mcpPath, {});
613
+ const currentObj =
614
+ existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {};
615
+ const mcpServers =
616
+ currentObj.mcpServers &&
617
+ typeof currentObj.mcpServers === 'object' &&
618
+ !Array.isArray(currentObj.mcpServers)
619
+ ? { ...currentObj.mcpServers }
620
+ : {};
621
+ const serverScript = `${PKG_ROOT}/packages/mcp/src/server.mjs`;
622
+ mcpServers['attention-horizon'] = {
623
+ command: 'node',
624
+ args: [serverScript]
625
+ };
626
+ const updated = {
627
+ ...currentObj,
628
+ mcpServers
629
+ };
630
+ if (!isDryRun) {
631
+ writeJsonAtomic(mcpPath, updated);
632
+ }
633
+ return {
634
+ ok: true,
635
+ mcpPath,
636
+ serverKey: 'attention-horizon',
637
+ serverScript,
638
+ dryRun: isDryRun
639
+ };
640
+ }
641
+
642
+ export function executeInitSubcommand(args = [], options = {}) {
643
+ const isAntigravity = args.includes('--antigravity') || args.includes('-a');
644
+ const isClaude = args.includes('--claude') || args.includes('-c');
645
+ const isMcp =
646
+ args.includes('--mcp') ||
647
+ args.includes('--cursor') ||
648
+ args.includes('--windsurf') ||
649
+ Boolean(options.mcp) ||
650
+ Boolean(options.cursor);
651
+ const isAll = args.includes('--all') || (!isAntigravity && !isClaude && !isMcp);
652
+ const isDryRun = args.includes('--dry-run') || Boolean(options.dryRun);
653
+ const isWorkspace = args.includes('--workspace') || args.includes('--project') || Boolean(options.workspace);
654
+ const isGlobal = args.includes('--global') || Boolean(options.global);
655
+ const isDedupe = args.includes('--dedupe') || Boolean(options.dedupe);
656
+ const isLeanHooks = args.includes('--lean-hooks') || Boolean(options.leanHooks);
657
+ const isFullHooks = args.includes('--full-hooks') || Boolean(options.fullHooks);
658
+
659
+ const targetParts = [];
660
+ if (isAll || isAntigravity) targetParts.push('Google Antigravity');
661
+ if (isAll || isClaude) targetParts.push('Claude Code');
662
+ if (isMcp) targetParts.push('MCP (.cursor/mcp.json)');
663
+ const targetLabel =
664
+ targetParts.length === 2 && !isMcp ? targetParts.join(' & ') : targetParts.join(', ');
665
+
666
+ const lines = [
667
+ `\x1b[1m\x1b[38;5;51m⚡ Highbeam (ctxtop v4.0.0) — Zero-Config Unified Installer\x1b[0m`,
668
+ ` • Target Harnesses : ${targetLabel}`,
669
+ ` • Installation Scope: ${isWorkspace ? 'Workspace' : 'Global'}${isDryRun ? ' [DRY RUN]' : ''}`
670
+ ];
671
+
672
+ let claudeResult = null;
673
+ let antigravityResult = null;
674
+ let mcpResult = null;
675
+
676
+ if (isClaude || isAll) {
677
+ const scope = isGlobal ? 'global' : 'project';
678
+ const hasExplicitLeanArg = args.includes('--lean-hooks') || options.leanHooks !== undefined;
679
+ claudeResult = installAttentionHorizon({
680
+ ...options,
681
+ scope,
682
+ dryRun: isDryRun,
683
+ ...(hasExplicitLeanArg ? { leanHooks: isLeanHooks } : {}),
684
+ ...(isFullHooks ? { leanHooks: false, fullHooks: true } : {}),
685
+ cwd: options.cwd || process.cwd()
686
+ });
687
+ const backupNote = claudeResult.backupPath
688
+ ? ` (backup: ${path.basename(claudeResult.backupPath)})`
689
+ : '';
690
+ lines.push(
691
+ ` \x1b[38;5;82m✓\x1b[0m Claude Code : ${isDryRun ? '[DRY RUN] Would configure' : 'Configured'} ${claudeResult.settingsPath}${backupNote}`
692
+ );
693
+ }
694
+
695
+ if (isAntigravity || isAll) {
696
+ try {
697
+ const agyInstall = installPlugin({
698
+ dryRun: isDryRun,
699
+ workspace: isWorkspace,
700
+ dedupe: isDedupe,
701
+ leanHooks: isLeanHooks,
702
+ fullHooks: isFullHooks,
703
+ cwd: options.cwd || process.cwd(),
704
+ homeDir: options.homeDir || options.home
705
+ });
706
+ lines.push(
707
+ ` \x1b[38;5;82m✓\x1b[0m Antigravity : ${isDryRun ? '[DRY RUN] Would deploy plugin files & lifecycle hooks' : 'Deployed plugin files & lifecycle hooks'}`
708
+ );
709
+ antigravityResult = { ok: true, leanHooks: Boolean(agyInstall?.leanHooks) };
710
+ } catch (err) {
711
+ lines.push(` \x1b[38;5;196m✖\x1b[0m Antigravity : Failed — ${err.message}`);
712
+ antigravityResult = { ok: false, error: err.message };
713
+ }
714
+ }
715
+
716
+ if (isMcp) {
717
+ mcpResult = installMcpConfig({
718
+ ...options,
719
+ global: isGlobal,
720
+ dryRun: isDryRun,
721
+ cwd: options.cwd || process.cwd()
722
+ });
723
+ lines.push(
724
+ ` \x1b[38;5;82m✓\x1b[0m MCP Server : ${isDryRun ? '[DRY RUN] Would configure' : 'Configured'} ${mcpResult.mcpPath} (attention-horizon)`
725
+ );
726
+ }
727
+
728
+ const ok =
729
+ (claudeResult ? claudeResult.ok : true) &&
730
+ (antigravityResult ? antigravityResult.ok : true) &&
731
+ (mcpResult ? mcpResult.ok : true);
732
+ return {
733
+ ok,
734
+ exitCode: ok ? 0 : 1,
735
+ output: lines.join('\n'),
736
+ data: { claude: claudeResult, antigravity: antigravityResult, mcp: mcpResult, dryRun: isDryRun }
737
+ };
738
+ }
739
+
740
+ export function runCli(args = [], options = {}) {
741
+ const subcommand = String(args[0] || 'doctor').toLowerCase();
742
+ const isGlobal = args.includes('--global') || args.includes('-g');
743
+ const isJson = args.includes('--json') || Boolean(options.json);
744
+ const isMarkdown = args.includes('--markdown') || args.includes('--md') || args.includes('--git');
745
+ const isDiagnostic = args.includes('--diagnostic') || args.includes('--bug-report');
746
+ const scope = isGlobal ? 'global' : 'project';
747
+
748
+ if (args.includes('--version') || args.includes('-v') || subcommand === 'version') {
749
+ return { exitCode: 0, output: '4.0.0', data: { version: '4.0.0' } };
750
+ }
751
+
752
+ if (subcommand === 'inspect') {
753
+ const isLast = args.includes('--last') || args[1] === '--last' || Boolean(options.last);
754
+ let sessionId = !isLast && args[1] && !args[1].startsWith('-') ? args[1] : options.sessionId || '';
755
+ for (let i = 1; i < args.length; i++) {
756
+ if (args[i] === '--session' && args[i + 1]) {
757
+ sessionId = args[i + 1];
758
+ break;
759
+ }
760
+ }
761
+
762
+ const outIdx = args.indexOf('--out');
763
+ const outPath = outIdx !== -1 && args[outIdx + 1] ? path.resolve(args[outIdx + 1]) : options.out ? path.resolve(options.out) : null;
764
+ const homeDir = options.homeDir || getHomeDir();
765
+ const cwd = options.cwd || process.cwd();
766
+
767
+ let foundData = null;
768
+ let foundSource = null;
769
+
770
+ // 1. Check live state cache (.claude/cache/ah_live_state_<sessionId>.json)
771
+ if (sessionId && sessionId !== 'default') {
772
+ const safeId = sanitizeSessionId(sessionId);
773
+ const p1 = path.join(cwd, '.claude', 'cache', `ah_live_state_${safeId}.json`);
774
+ const p2 = path.join(homeDir, '.claude', 'cache', `ah_live_state_${safeId}.json`);
775
+ if (fs.existsSync(p1)) {
776
+ foundData = readJsonSafe(p1, null);
777
+ foundSource = p1;
778
+ } else if (fs.existsSync(p2)) {
779
+ foundData = readJsonSafe(p2, null);
780
+ foundSource = p2;
781
+ }
782
+ } else if (isLast) {
783
+ const cacheDir = path.join(cwd, '.claude', 'cache');
784
+ if (fs.existsSync(cacheDir)) {
785
+ try {
786
+ const files = fs.readdirSync(cacheDir)
787
+ .filter((f) => f.startsWith('ah_live_state_') && f.endsWith('.json'))
788
+ .map((f) => ({ name: f, full: path.join(cacheDir, f), mtime: fs.statSync(path.join(cacheDir, f)).mtimeMs }))
789
+ .sort((a, b) => b.mtime - a.mtime);
790
+ if (files.length > 0) {
791
+ foundData = readJsonSafe(files[0].full, null);
792
+ foundSource = files[0].full;
793
+ if (foundData?.sessionId) sessionId = foundData.sessionId;
794
+ }
795
+ } catch (_err) {
796
+ void _err;
797
+ }
798
+ }
799
+ }
800
+
801
+ // 2. Check USTF sessions directory (~/.ctxtop/sessions/<sessionId>.jsonl or .json)
802
+ if (!foundData && sessionId) {
803
+ const safeId = sanitizeSessionId(sessionId);
804
+ const sDir = path.join(homeDir, '.ctxtop', 'sessions');
805
+ const pJsonl = path.join(sDir, `${safeId}.jsonl`);
806
+ const pJson = path.join(sDir, `${safeId}.json`);
807
+ if (fs.existsSync(pJsonl)) {
808
+ try {
809
+ const lines = fs.readFileSync(pJsonl, 'utf8').trim().split('\n').filter(Boolean);
810
+ const events = lines.map((l) => JSON.parse(l));
811
+ foundData = { sessionId, events, harness: 'claude-code' };
812
+ foundSource = pJsonl;
813
+ } catch (_err) {
814
+ void _err;
815
+ }
816
+ } else if (fs.existsSync(pJson)) {
817
+ foundData = readJsonSafe(pJson, null);
818
+ foundSource = pJson;
819
+ }
820
+ }
821
+
822
+ // 3. Check Antigravity session directories
823
+ if (!foundData && sessionId) {
824
+ try {
825
+ const surfaces = getAntigravitySurfaces(homeDir, { includeMissing: false });
826
+ const stores = surfaces.length > 0
827
+ ? surfaces.map((s) => s.brainDir)
828
+ : getBrainStores(homeDir).map((s) => s.path);
829
+ for (const sPath of stores) {
830
+ const candidateDir = path.join(sPath, sessionId);
831
+ if (fs.existsSync(candidateDir)) {
832
+ foundData = { sessionId, path: candidateDir, isAntigravity: true };
833
+ foundSource = candidateDir;
834
+ break;
835
+ }
836
+ }
837
+ } catch (_err) {
838
+ void _err;
839
+ }
840
+ }
841
+
842
+ if (!foundData) {
843
+ return {
844
+ exitCode: 1,
845
+ output: `[Highbeam Inspect] Session "${sessionId}" not found.`,
846
+ data: { found: false, sessionId }
847
+ };
848
+ }
849
+
850
+ let trajectory = null;
851
+ if (foundData.version === '1.0.0' && foundData.sessionId && foundData.events) {
852
+ trajectory = foundData;
853
+ } else if (foundData.isAntigravity || Array.isArray(foundData.steps)) {
854
+ trajectory = normalizeAntigravitySession(foundData, { sessionId, source: foundSource });
855
+ } else if (Array.isArray(foundData.events) || Array.isArray(foundData.entries)) {
856
+ trajectory = normalizeClaudeCodeSession(foundData, { sessionId, source: foundSource });
857
+ } else {
858
+ const empty = createEmptyUstfSession(sessionId || foundData.sessionId || 'default', 'claude-code', {
859
+ modelId: foundData.modelId || foundData.rawModelId || 'claude-sonnet-5-5',
860
+ startTimeMs: foundData.sessionStartTimeMs || Date.now()
861
+ });
862
+ const uncached = Math.max(0, Number(foundData.contextWindow?.totalInputTokens || 0) - Number(foundData.contextWindow?.cachedTokens || 0));
863
+ empty.usage = {
864
+ uncached,
865
+ cacheWrite5m: Number(foundData.contextWindow?.cacheWrite5mTokens || 0),
866
+ cacheWrite1h: Number(foundData.contextWindow?.cacheWrite1hTokens || 0),
867
+ cacheRead: Number(foundData.contextWindow?.cacheReadTokens || foundData.contextWindow?.cachedTokens || 0),
868
+ output: Number(foundData.contextWindow?.outputTokens || 0),
869
+ thinking: Number(foundData.contextWindow?.thinkingTokens || 0),
870
+ costUSD: Number(foundData.savedQuota?.sessionSavedUSD || 0)
871
+ };
872
+ empty.turnsCompleted = Number(foundData.turnsCompleted || 0);
873
+ empty.flightMode = foundData.flightMode || 'COACH';
874
+ trajectory = empty;
875
+ }
876
+
877
+ if (outPath) {
878
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
879
+ writeJsonAtomic(outPath, trajectory);
880
+ }
881
+
882
+ if (isJson) {
883
+ return { exitCode: 0, output: JSON.stringify(trajectory, null, 2), data: trajectory };
884
+ }
885
+
886
+ const totalToks = (trajectory.usage?.uncached || 0) + (trajectory.usage?.cacheRead || 0);
887
+ const lines = [
888
+ `[Highbeam Inspect] Session "${sessionId || trajectory.sessionId}" (${trajectory.harness || 'claude-code'})`,
889
+ ` Model: ${trajectory.modelId || 'unknown'} | Events: ${trajectory.events?.length || 0} | Spans: ${trajectory.spans?.length || 0}`,
890
+ ` Tokens: ${totalToks.toLocaleString()} (Uncached: ${(trajectory.usage?.uncached || 0).toLocaleString()}, Cache: ${(trajectory.usage?.cacheRead || 0).toLocaleString()})`,
891
+ ` Cost: $${(trajectory.usage?.costUSD || 0).toFixed(4)}`,
892
+ outPath ? ` Artifact written: ${outPath}` : ''
893
+ ].filter(Boolean);
894
+
895
+ return { exitCode: 0, output: lines.join('\n'), data: trajectory };
896
+ }
897
+
898
+ if (subcommand === 'control') {
899
+ const action = String(args[1] || '').toLowerCase();
900
+ const validActions = ['pause', 'resume', 'step', 'abort', 'rewind', 'status'];
901
+ if (!validActions.includes(action)) {
902
+ return {
903
+ exitCode: 1,
904
+ output: `[Highbeam Control] Invalid control action "${args[1] || ''}". Valid actions: pause, resume, step, abort, rewind`,
905
+ data: { ok: false, validActions }
906
+ };
907
+ }
908
+
909
+ let sessionId = options.sessionId || 'default';
910
+ for (let i = 2; i < args.length; i++) {
911
+ if (args[i] === '--session' && args[i + 1]) {
912
+ sessionId = args[i + 1];
913
+ break;
914
+ }
915
+ }
916
+
917
+ const homeDir = options.homeDir || process.env.USERPROFILE || process.env.HOME || os.homedir();
918
+ const runtimeDir = path.join(homeDir, '.ctxtop', 'runtime');
919
+
920
+ if (action === 'status') {
921
+ const ctlPath = path.join(runtimeDir, `${sessionId}.ctl`);
922
+ let currentState = { sessionId, state: 'RUNNING', reason: 'default' };
923
+ if (fs.existsSync(ctlPath)) {
924
+ try {
925
+ currentState = parseControlFile(fs.readFileSync(ctlPath, 'utf8'), sessionId);
926
+ } catch (_err) {
927
+ void _err;
928
+ }
929
+ }
930
+ return {
931
+ exitCode: 0,
932
+ output: `[Highbeam Control] Session "${sessionId}" is ${currentState.state}`,
933
+ data: { ok: true, sessionId, state: currentState }
934
+ };
935
+ }
936
+
937
+ let rewindTarget = options.target || options.rewindTarget || null;
938
+ const targetIdx = args.indexOf('--target') !== -1 ? args.indexOf('--target') : args.indexOf('--turn');
939
+ if (targetIdx !== -1 && args[targetIdx + 1]) {
940
+ rewindTarget = args[targetIdx + 1];
941
+ } else if (args[2] && !args[2].startsWith('-')) {
942
+ rewindTarget = args[2];
943
+ }
944
+
945
+ const reason = options.reason || `CLI /control ${action}${rewindTarget ? ` (target: ${rewindTarget})` : ''}`;
946
+
947
+ try {
948
+ fs.mkdirSync(runtimeDir, { recursive: true });
949
+ const ctlPath = path.join(runtimeDir, `${sessionId}.ctl`);
950
+ let currentState = null;
951
+ if (fs.existsSync(ctlPath)) {
952
+ try {
953
+ currentState = parseControlFile(fs.readFileSync(ctlPath, 'utf8'), sessionId);
954
+ } catch (_err) {
955
+ void _err;
956
+ }
957
+ }
958
+ const nextState = transitionControlState(currentState, action, reason, { sessionId, target: rewindTarget });
959
+ fs.writeFileSync(ctlPath, serializeControlFile(nextState), 'utf8');
960
+
961
+ // Best-effort notify warm IPC daemon
962
+ try {
963
+ const client = new MicroIpcClient({ homeDir });
964
+ client.call('control.transition', { sessionId, action, reason, target: rewindTarget }, { connectTimeoutMs: 15, requestTimeoutMs: 100 }).catch((_ipcErr) => {
965
+ void _ipcErr;
966
+ });
967
+ } catch (_ipcErr) {
968
+ void _ipcErr;
969
+ }
970
+
971
+ return {
972
+ exitCode: 0,
973
+ output: `[Highbeam Control] State transitioned to ${nextState.state}`,
974
+ data: { ok: true, action, sessionId, state: nextState }
975
+ };
976
+ } catch (err) {
977
+ return {
978
+ exitCode: 1,
979
+ output: `[Highbeam Control] Failed to transition control state: ${err.message}`,
980
+ data: { ok: false, error: err.message }
981
+ };
982
+ }
983
+ }
984
+
985
+ if (subcommand === 'init') {
986
+ return executeInitSubcommand(args.slice(1), options);
987
+ }
988
+
989
+ if (subcommand === 'install') {
990
+ const fullHooks =
991
+ args.includes('--full-hooks') || options.leanHooks === false || Boolean(options.fullHooks);
992
+ const leanHooks =
993
+ args.includes('--lean-hooks') || options.leanHooks === true || !fullHooks;
994
+ const res = installAttentionHorizon({ ...options, scope, leanHooks });
995
+ const backupNote = res.backupPath ? `\nBackup saved: ${res.backupPath}` : '';
996
+ const output = `[Highbeam] Installed non-destructively into ${res.settingsPath}${backupNote}`;
997
+ return { exitCode: res.ok ? 0 : 1, output, data: res };
998
+ }
999
+
1000
+ if (subcommand === 'team-pack' || subcommand === 'team-finops') {
1001
+ const outIdx = args.indexOf('--out');
1002
+ const orgIdx = args.indexOf('--org');
1003
+ const outDir =
1004
+ outIdx !== -1 && args[outIdx + 1] ? path.resolve(args[outIdx + 1]) : options.outDir;
1005
+ const orgName =
1006
+ orgIdx !== -1 && args[orgIdx + 1] ? args[orgIdx + 1] : options.orgName || 'Engineering Team';
1007
+ const preview = args.includes('--preview') || Boolean(options.preview);
1008
+ const packRes = generateTeamFinopsPack({ ...options, outDir, orgName, preview });
1009
+ if (!packRes.ok) {
1010
+ return {
1011
+ exitCode: 2,
1012
+ output: `[Highbeam Team] ${packRes.entitlement.upgradeHint}`,
1013
+ data: packRes
1014
+ };
1015
+ }
1016
+ if (isJson) {
1017
+ return { exitCode: 0, output: JSON.stringify(packRes, null, 2), data: packRes };
1018
+ }
1019
+ return {
1020
+ exitCode: 0,
1021
+ output: `[Highbeam Team] Generated BYO-Grafana & Datadog Team FinOps Pack in: ${packRes.outDir}\n Files written: ${packRes.filesWritten.length}`,
1022
+ data: packRes
1023
+ };
1024
+ }
1025
+
1026
+ if (subcommand === 'verify' || subcommand === 'verify-checksums') {
1027
+ const rootDir = options.rootDir || PKG_ROOT;
1028
+ const manifestPath = path.join(rootDir, 'CHECKSUMS.sha256');
1029
+ if (!fs.existsSync(manifestPath)) {
1030
+ const missingRes = {
1031
+ valid: false,
1032
+ verifiedCount: 0,
1033
+ mismatches: ['Missing CHECKSUMS.sha256 manifest']
1034
+ };
1035
+ return {
1036
+ exitCode: 1,
1037
+ output: isJson
1038
+ ? JSON.stringify(missingRes, null, 2)
1039
+ : '[Highbeam Verify] FAILED: Missing CHECKSUMS.sha256 manifest',
1040
+ data: missingRes
1041
+ };
1042
+ }
1043
+ const lines = fs.readFileSync(manifestPath, 'utf8').split(/\r?\n/).filter(Boolean);
1044
+ const mismatches = [];
1045
+ let verifiedCount = 0;
1046
+ for (const line of lines) {
1047
+ const match = line.match(/^([a-f0-9]{64})\s\s(.+)$/);
1048
+ if (!match) continue;
1049
+ const [, expectedHash, relPath] = match;
1050
+ const absPath = path.join(rootDir, relPath);
1051
+ if (!fs.existsSync(absPath)) {
1052
+ mismatches.push(`Missing file: ${relPath}`);
1053
+ continue;
1054
+ }
1055
+ const normalized = fs.readFileSync(absPath, 'utf8').replace(/\r\n/g, '\n');
1056
+ const actualHash = sha256HexPure(normalized);
1057
+ if (actualHash !== expectedHash) {
1058
+ mismatches.push(`Checksum mismatch: ${relPath}`);
1059
+ } else {
1060
+ verifiedCount++;
1061
+ }
1062
+ }
1063
+ const verifyRes = {
1064
+ valid: mismatches.length === 0 && verifiedCount > 0,
1065
+ verifiedCount,
1066
+ mismatches
1067
+ };
1068
+ if (isJson) {
1069
+ return {
1070
+ exitCode: verifyRes.valid ? 0 : 1,
1071
+ output: JSON.stringify(verifyRes, null, 2),
1072
+ data: verifyRes
1073
+ };
1074
+ }
1075
+ return {
1076
+ exitCode: verifyRes.valid ? 0 : 1,
1077
+ output: verifyRes.valid
1078
+ ? `[Highbeam Verify] PASS — ${verifiedCount} release files verified against CHECKSUMS.sha256 (0 mismatches)`
1079
+ : `[Highbeam Verify] FAIL — ${mismatches.length} mismatch(es): ${mismatches.slice(0, 5).join('; ')}`,
1080
+ data: verifyRes
1081
+ };
1082
+ }
1083
+
1084
+ if (subcommand === 'tiers') {
1085
+ if (isJson) {
1086
+ return { exitCode: 0, output: JSON.stringify(PLG_TIER_MATRIX, null, 2), data: PLG_TIER_MATRIX };
1087
+ }
1088
+ const lines = [
1089
+ 'Highbeam — 3-Tier Self-Expensing PLG Funnel:',
1090
+ ` • Free ($0/mo): ${PLG_TIER_MATRIX.free.features.join(', ')}`,
1091
+ ` • Pro ($${PLG_TIER_MATRIX.pro.priceMonthlyUSD}/mo [$12-$19/mo]): ${PLG_TIER_MATRIX.pro.features.join(', ')}`,
1092
+ ` • Team ($${PLG_TIER_MATRIX.team.pricePerSeatMonthlyUSD}/seat/mo): ${PLG_TIER_MATRIX.team.features.join(', ')}`
1093
+ ];
1094
+ return { exitCode: 0, output: lines.join('\n'), data: PLG_TIER_MATRIX };
1095
+ }
1096
+
1097
+ if (subcommand === 'license' || subcommand === 'pro') {
1098
+ const action = String(args[1] || 'status').toLowerCase();
1099
+ if (action === 'tiers') {
1100
+ if (isJson) {
1101
+ return { exitCode: 0, output: JSON.stringify(PLG_TIER_MATRIX, null, 2), data: PLG_TIER_MATRIX };
1102
+ }
1103
+ const lines = [
1104
+ 'Highbeam — 3-Tier Self-Expensing PLG Funnel:',
1105
+ ` • Free ($0/mo): ${PLG_TIER_MATRIX.free.features.join(', ')}`,
1106
+ ` • Pro ($${PLG_TIER_MATRIX.pro.priceMonthlyUSD}/mo [$12-$19/mo]): ${PLG_TIER_MATRIX.pro.features.join(', ')}`,
1107
+ ` • Team ($${PLG_TIER_MATRIX.team.pricePerSeatMonthlyUSD}/seat/mo): ${PLG_TIER_MATRIX.team.features.join(', ')}`
1108
+ ];
1109
+ return { exitCode: 0, output: lines.join('\n'), data: PLG_TIER_MATRIX };
1110
+ }
1111
+ if (action === 'activate' && args[2]) {
1112
+ const actRes = activateProLicense(args[2], options);
1113
+ if (isJson) {
1114
+ return { exitCode: actRes.ok ? 0 : 1, output: JSON.stringify(actRes, null, 2), data: actRes };
1115
+ }
1116
+ return {
1117
+ exitCode: actRes.ok ? 0 : 1,
1118
+ output: actRes.ok
1119
+ ? `[Highbeam Pro] Activated ${actRes.tier.toUpperCase()} license (${actRes.payload.email}) -> ${actRes.licensePath}`
1120
+ : `[Highbeam Pro] License activation failed: ${actRes.reason}`,
1121
+ data: actRes
1122
+ };
1123
+ }
1124
+ if (action === 'trial') {
1125
+ const trRes = activateLocalTrial(options);
1126
+ return {
1127
+ exitCode: 0,
1128
+ output: `[Highbeam Pro] Activated 14-day local trial (expires ${trRes.expiresAt}) -> ${trRes.licensePath}`,
1129
+ data: trRes
1130
+ };
1131
+ }
1132
+ if (action === 'deactivate') {
1133
+ const deactRes = deactivateProLicense(options);
1134
+ return {
1135
+ exitCode: 0,
1136
+ output: `[Highbeam Pro] Deactivated license (${deactRes.licensePath})`,
1137
+ data: deactRes
1138
+ };
1139
+ }
1140
+ const status = getProEntitlementStatus(options);
1141
+ if (isJson) {
1142
+ return { exitCode: 0, output: JSON.stringify(status, null, 2), data: status };
1143
+ }
1144
+ return {
1145
+ exitCode: 0,
1146
+ output: `[Highbeam Pro] Tier=${status.tier} | Entitled=${status.entitled} | Source=${status.source}`,
1147
+ data: status
1148
+ };
1149
+ }
1150
+
1151
+ if (subcommand === 'roast' || (args.includes('--roast') && subcommand !== 'postmortem')) {
1152
+ const isDemo = args.includes('--demo') || Boolean(options.demo);
1153
+ const roast = generateRoastCard({ ...options, demo: isDemo });
1154
+ if (isJson) {
1155
+ return { exitCode: 0, output: JSON.stringify(roast, null, 2), data: roast };
1156
+ }
1157
+ if (isMarkdown) {
1158
+ return { exitCode: 0, output: roast.markdown, data: roast };
1159
+ }
1160
+ return { exitCode: 0, output: roast.ascii, data: roast };
1161
+ }
1162
+
1163
+ if (subcommand === 'uninstall') {
1164
+ const res = uninstallAttentionHorizon({ ...options, scope });
1165
+ const output = `[Highbeam] Uninstalled ${res.removedHooksCount} hook entries from ${res.settingsPath}`;
1166
+ return { exitCode: res.ok ? 0 : 1, output, data: res };
1167
+ }
1168
+
1169
+ if (subcommand === 'config') {
1170
+ const action = String(args[1] || 'list').toLowerCase();
1171
+ if (action === 'set') {
1172
+ const detId = args[2];
1173
+ const mode = args[3] || 'default';
1174
+ const res = setDetectorOverride(detId, mode, { ...options, scope });
1175
+ if (!res.ok) {
1176
+ return {
1177
+ exitCode: 1,
1178
+ output: `[Highbeam Config] Invalid detector ID "${detId}". Expected DET-01..DET-20.`,
1179
+ data: res
1180
+ };
1181
+ }
1182
+ return {
1183
+ exitCode: 0,
1184
+ output: `[Highbeam Config] Set ${res.detectorId}=${res.mode} in ${res.configPath}`,
1185
+ data: res
1186
+ };
1187
+ }
1188
+ if (action === 'reset') {
1189
+ const res = resetHorizonConfig({ ...options, scope });
1190
+ return {
1191
+ exitCode: res.ok ? 0 : 1,
1192
+ output: `[Highbeam Config] Reset detector overrides at ${res.configPath}`,
1193
+ data: res
1194
+ };
1195
+ }
1196
+ const cfg = loadHorizonConfig({ ...options, scope });
1197
+ if (isJson) {
1198
+ return { exitCode: 0, output: JSON.stringify(cfg, null, 2), data: cfg };
1199
+ }
1200
+ const lines = [
1201
+ `[Highbeam Config] FlightMode=${cfg.flightMode} (projectLoaded=${cfg.sources.projectLoaded})`,
1202
+ ...Object.entries(cfg.detectors).map(([id, m]) => ` ${id}: ${m}`)
1203
+ ];
1204
+ return { exitCode: 0, output: lines.join('\n'), data: cfg };
1205
+ }
1206
+
1207
+ if (subcommand === 'cost-radar' || subcommand === 'radar') {
1208
+ const isDemo = args.includes('--demo') || Boolean(options.demo);
1209
+ const isShare = args.includes('--share') || Boolean(options.share);
1210
+ const outIdx = args.indexOf('--out');
1211
+ const target = path.resolve(
1212
+ outIdx !== -1 && args[outIdx + 1]
1213
+ ? args[outIdx + 1]
1214
+ : path.join(os.homedir(), '.claude', 'attention-horizon', 'cost_radar.html')
1215
+ );
1216
+ const res = generateCostRadar({ ...options, demo: isDemo });
1217
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1218
+ const ok = writeTextAtomic(target, res.html) !== false;
1219
+ const shareSnippet = `⚡ Cost Radar: ${res.summary.retention} · ${res.summary.drift} · ${res.summary.swarm} (via npx ah-claude cost-radar)`;
1220
+ const data = { ok, path: target, ...res.summary, shareSnippet };
1221
+ if (isJson) {
1222
+ return { exitCode: ok ? 0 : 1, output: JSON.stringify(data, null, 2), data };
1223
+ }
1224
+ return {
1225
+ exitCode: ok ? 0 : 1,
1226
+ output: `[Highbeam] Cost Radar written: ${target}\n ${res.summary.retention}\n ${res.summary.drift}\n ${res.summary.swarm}${isShare ? `\n Share: ${shareSnippet}` : ''}`,
1227
+ data
1228
+ };
1229
+ }
1230
+
1231
+ if (subcommand === 'postmortem' || args.includes('--postmortem')) {
1232
+ const lastIdx = args.indexOf('--last');
1233
+ const last = lastIdx !== -1 && args[lastIdx + 1] ? Number(args[lastIdx + 1]) : (options.last || 15);
1234
+ const isRoast = args.includes('--roast') || Boolean(options.roast);
1235
+ const isDemo = args.includes('--demo') || Boolean(options.demo);
1236
+ return runPostmortem({
1237
+ ...options,
1238
+ last,
1239
+ json: false,
1240
+ demo: isDemo,
1241
+ roast: isRoast,
1242
+ writeFiles: options.writeFiles !== false
1243
+ }).then((res) => {
1244
+ if (isJson) {
1245
+ return { exitCode: 0, output: JSON.stringify(res, null, 2), data: res };
1246
+ }
1247
+ const estM = typeof res.estTokensM === 'number' ? `${res.estTokensM.toFixed(2)}M` : String(res.estTokensM || '0M');
1248
+ const summaryText = [
1249
+ `[Highbeam Postmortem] Analyzed ${res.sessionCount} sessions (${estM} active tokens)`,
1250
+ ` Clean Sessions: ${res.cleanSessionCount || 0} | Churn: ${res.churnSessionCount || 0} | Rot: ${res.rotSessionCount || 0}`,
1251
+ res.reportPath ? ` Report: ${res.reportPath}` : ''
1252
+ ].filter(Boolean).join('\n');
1253
+ return { exitCode: 0, output: summaryText, data: res };
1254
+ });
1255
+ }
1256
+
1257
+ if (subcommand === 'panel') {
1258
+ const outIdx = args.indexOf('--out');
1259
+ const isAdvanced = args.includes('--advanced') || args.includes('advanced');
1260
+ const target = path.resolve(
1261
+ outIdx !== -1 && args[outIdx + 1]
1262
+ ? args[outIdx + 1]
1263
+ : path.join(os.homedir(), '.claude', 'attention-horizon', 'horizon_panel.html')
1264
+ );
1265
+ const res = generateHorizonPanel({ ...options, advanced: isAdvanced });
1266
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1267
+ const ok = writeTextAtomic(target, res.html) !== false;
1268
+ const data = { ok, path: target, ...res.summary };
1269
+ if (isJson) {
1270
+ return { exitCode: ok ? 0 : 1, output: JSON.stringify(data, null, 2), data };
1271
+ }
1272
+ return {
1273
+ exitCode: ok ? 0 : 1,
1274
+ output: `[Highbeam] Claude Code HUD written: ${target}\n Verdict: ${res.summary.verdict}\n Next Action: ${res.summary.action}\n Saved: +${res.summary.sessionSavedTokens.toLocaleString('en-US')} tokens ($${res.summary.sessionSavedUSD.toFixed(2)}) this session`,
1275
+ data
1276
+ };
1277
+ }
1278
+
1279
+ if (subcommand === 'receipt') {
1280
+ const isAdvanced = args.includes('--advanced') || args.includes('advanced');
1281
+ const isFourRank = args.includes('--4-rank') || args.includes('--simple');
1282
+ const isPdf = args.includes('--pdf') || Boolean(options.pdf);
1283
+ const isHtml = args.includes('--html') || Boolean(options.html);
1284
+ const outIdx = args.indexOf('--out');
1285
+ const outPath = outIdx !== -1 && args[outIdx + 1]
1286
+ ? path.resolve(args[outIdx + 1])
1287
+ : options.out
1288
+ ? path.resolve(options.out)
1289
+ : null;
1290
+ const res = generateReceiptReport({
1291
+ ...options,
1292
+ advanced: isAdvanced,
1293
+ fourRank: isFourRank
1294
+ });
1295
+ if (isPdf) {
1296
+ const proCheck = requireProFeature('corporate_expense_receipts', options);
1297
+ if (!proCheck.allowed) {
1298
+ const savedUsd = res.corporateReceipt.workspace30dSavedUSD.toFixed(2);
1299
+ return {
1300
+ exitCode: 2,
1301
+ output: `[Highbeam Pro] Pro would expense +$${savedUsd} USD saved over 30d. ${proCheck.upgradeHint}`,
1302
+ data: { ok: false, requiresPro: true, entitlement: proCheck, shadowSavedUSD: Number(savedUsd) }
1303
+ };
1304
+ }
1305
+ const targetPdf = outPath || path.resolve(options.cwd || process.cwd(), 'attention-horizon-expense-receipt.pdf');
1306
+ fs.mkdirSync(path.dirname(targetPdf), { recursive: true });
1307
+ fs.writeFileSync(targetPdf, Buffer.from(res.pdfBytes));
1308
+ const pdfData = {
1309
+ ok: true,
1310
+ path: targetPdf,
1311
+ receiptId: res.corporateReceipt.receiptId,
1312
+ sha256: res.corporateReceipt.sha256,
1313
+ workspace30dSavedUSD: res.corporateReceipt.workspace30dSavedUSD,
1314
+ netRoiMultiplier: res.corporateReceipt.netRoiMultiplier
1315
+ };
1316
+ if (isJson) {
1317
+ return { exitCode: 0, output: JSON.stringify(pdfData, null, 2), data: pdfData };
1318
+ }
1319
+ return {
1320
+ exitCode: 0,
1321
+ output: `[Highbeam Pro] Corporate Expense Receipt (PDF 1.4) written: ${targetPdf}\n Receipt ID : ${pdfData.receiptId}\n 30d Saved : +$${pdfData.workspace30dSavedUSD.toFixed(2)} USD (${pdfData.netRoiMultiplier}x ROI)\n SHA-256 : ${pdfData.sha256}`,
1322
+ data: pdfData
1323
+ };
1324
+ }
1325
+ if (isHtml) {
1326
+ if (outPath) {
1327
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
1328
+ writeTextAtomic(outPath, res.html);
1329
+ }
1330
+ return { exitCode: 0, output: res.html, data: res };
1331
+ }
1332
+ if (isJson) {
1333
+ return { exitCode: 0, output: JSON.stringify(res.gitReceipt, null, 2), data: res };
1334
+ }
1335
+ if (isMarkdown) {
1336
+ if (outPath) {
1337
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
1338
+ writeTextAtomic(outPath, res.markdown);
1339
+ }
1340
+ return { exitCode: 0, output: res.markdown, data: res };
1341
+ }
1342
+ return { exitCode: 0, output: res.text, data: res };
1343
+ }
1344
+
1345
+ if (subcommand === 'doctor') {
1346
+ if (args.includes('--prune-tools') || args.includes('--gc-cursor') || args.includes('--recover-brain') || args.includes('--reap-orphans') || args.includes('--handoff')) {
1347
+ return runDoctor({ ...options, ...parseDoctorArgs(args) }).then((docRes) => ({
1348
+ exitCode: docRes.ok ? 0 : 1,
1349
+ output: JSON.stringify(docRes, null, 2),
1350
+ data: docRes
1351
+ }));
1352
+ }
1353
+ const res = runDoctorDiagnostics(options);
1354
+ if (isDiagnostic) {
1355
+ const bundle = generateZeroPiiDiagnosticBundle(res, options);
1356
+ return {
1357
+ exitCode: res.ok ? 0 : 1,
1358
+ output: isJson ? JSON.stringify(bundle, null, 2) : bundle.markdown,
1359
+ data: bundle
1360
+ };
1361
+ }
1362
+ if (isJson) {
1363
+ return { exitCode: res.ok ? 0 : 1, output: JSON.stringify(res, null, 2), data: res };
1364
+ }
1365
+ const hookDiag = res.hookDiagnostics || { recentErrorCount: 0, recentErrors: [] };
1366
+ const lines = [
1367
+ `[Highbeam Doctor] Status: ${res.ok ? 'HEALTHY' : 'ISSUES DETECTED'}`,
1368
+ ...res.checks.map((c) => ` [${c.ok ? 'PASS' : 'FAIL'}] ${c.id}: ${c.detail}`),
1369
+ ` [${hookDiag.recentErrorCount > 0 ? 'WARN' : 'PASS'}] hook_diagnostics: ${hookDiag.recentErrorCount} recent non-fatal error(s)`
1370
+ ];
1371
+ for (const errEntry of hookDiag.recentErrors) {
1372
+ lines.push(
1373
+ ` - [${errEntry.timestamp}] ${errEntry.source}#${errEntry.operation} (${errEntry.name}): ${errEntry.message}`
1374
+ );
1375
+ }
1376
+ return { exitCode: res.ok ? 0 : 1, output: lines.join('\n'), data: res };
1377
+ }
1378
+
1379
+ if (subcommand === 'statusline') {
1380
+ return runStatusLineCli(args.slice(1));
1381
+ }
1382
+
1383
+ if (args.includes('--demo') || args.includes('--demo-animate') || args.includes('--roast') || args.includes('--serve')) {
1384
+ return runLiveOrDemoCli(options);
1385
+ }
1386
+
1387
+ const knownSubcommands = new Set([
1388
+ 'init', 'install', 'uninstall', 'config', 'cost-radar', 'radar', 'panel',
1389
+ 'receipt', 'doctor', 'statusline', 'inspect', 'control', 'postmortem',
1390
+ 'license', 'pro', 'roast',
1391
+ '--help', '-h', 'help', '--version', '-v', 'version'
1392
+ ]);
1393
+ const hasHelp = args.length === 0 || args.includes('--help') || args.includes('-h') || subcommand === 'help';
1394
+ const isUnknown = !hasHelp && args.length > 0 && !knownSubcommands.has(subcommand);
1395
+
1396
+ const helpText = [
1397
+ 'Usage: ctxtop <command> [options]',
1398
+ 'Commands:',
1399
+ ' init [--antigravity | --claude | --all | --workspace | --dry-run] Zero-config dual-host installer',
1400
+ ' install [--global | --project] Merge Claude Code hooks & statusLine',
1401
+ ' uninstall [--global | --project] Remove Highbeam hooks',
1402
+ ' doctor [--diagnostic | --json] Verify contracts or emit zero-PII report',
1403
+ ' postmortem [--last N] [--json] [--demo] Analyze transcript forensics & rot',
1404
+ ' receipt [--advanced | --markdown | --json] Print Simple View or Git-Commit Receipt',
1405
+ ' panel [--advanced] [--out <file.html>] Write zero-socket Claude Code HTML HUD',
1406
+ ' radar [--out <file.html>] [--json] [--demo] Write SVG KV-cache retention radar timeline',
1407
+ ' cost-radar [--out <file.html>] [--json] (Alias for radar)',
1408
+ ' statusline [--demo] [--columns N] Responsive single-line statusline bridge',
1409
+ ' config [list | set <DET-ID> <mode> | reset] Configure per-detector overrides',
1410
+ ' inspect [<session-id> | --last] [--out <file.json>] Inspect session trajectory',
1411
+ ' control <pause|resume|step|abort|rewind|status> Execution control plane command'
1412
+ ].join('\n');
1413
+ return { exitCode: isUnknown ? 1 : 0, output: helpText, data: { help: true, isUnknown } };
1414
+ }
1415
+
1416
+ export function isCliMain(
1417
+ argv1 = globalThis.process?.argv?.[1],
1418
+ metaUrl = import.meta.url,
1419
+ fsImpl = fs
1420
+ ) {
1421
+ if (!argv1 || !metaUrl) return false;
1422
+ try {
1423
+ return fsImpl.realpathSync(argv1) === fsImpl.realpathSync(url.fileURLToPath(metaUrl));
1424
+ } catch {
1425
+ try {
1426
+ return path.resolve(String(argv1)) === path.resolve(url.fileURLToPath(metaUrl));
1427
+ } catch {
1428
+ return false;
1429
+ }
1430
+ }
1431
+ }
1432
+
1433
+ export function main(args = globalThis.process?.argv?.slice(2) || []) {
1434
+ const result = runCli(args);
1435
+ if (result && typeof result.then === 'function') {
1436
+ return result.then((res) => {
1437
+ if (res?.output) globalThis.process?.stdout?.write?.(`${res.output}\n`);
1438
+ if (res?.exitCode !== undefined && res?.exitCode !== 0 && globalThis.process?.exit) {
1439
+ globalThis.process.exit(res.exitCode);
1440
+ }
1441
+ return res;
1442
+ });
1443
+ }
1444
+ if (result?.output) globalThis.process?.stdout?.write?.(`${result.output}\n`);
1445
+ if (result?.exitCode !== undefined && result?.exitCode !== 0 && globalThis.process?.exit) {
1446
+ globalThis.process.exit(result.exitCode);
1447
+ }
1448
+ return result;
1449
+ }
1450
+
1451
+ if (isCliMain()) {
1452
+ main();
1453
+ }
1454
+
1455
+ export default {
1456
+ PKG_ROOT,
1457
+ CANONICAL_AH_HOOKS,
1458
+ PRE_TOOL_USE_MATCHER,
1459
+ POST_TOOL_USE_MATCHER,
1460
+ isAttentionHorizonHookEntry,
1461
+ resolveSettingsPath,
1462
+ ensureGitExcludeEntries,
1463
+ installAttentionHorizon,
1464
+ uninstallAttentionHorizon,
1465
+ inspectHookDiagnostics,
1466
+ runDoctorDiagnostics,
1467
+ generateReceiptReport,
1468
+ generateHorizonPanel,
1469
+ generateCostRadar,
1470
+ executeInitSubcommand,
1471
+ runCli,
1472
+ isCliMain,
1473
+ main
1474
+ };