ctxtop 0.0.0-stage → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
package/bin/ctxtop.mjs ADDED
@@ -0,0 +1,1799 @@
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 { inspectClaudeBinaryCapabilities } from '../src/diagnostics/claudeHookCapabilities.mjs';
98
+ import { installPlugin, runLiveOrDemoCli } from '../src/cli/init.mjs';
99
+ import { executeStatusLineBridge, runStatusLineCli } from './ah-statusline.mjs';
100
+ import { runSessionAudit, formatSessionAuditReport } from '../src/core/session_auditor.mjs';
101
+ import { configureShield, getShieldStatus } from '../src/core/shield_manager.mjs';
102
+ import { buildContrastiveDigest, sanitizeRslSessionId } from '../src/core/rsl_triage.mjs';
103
+ import { distillContrastiveDigest } from '../src/core/rsl_distiller.mjs';
104
+ import {
105
+ getRslLedgerPath,
106
+ getRslSummary,
107
+ ingestDistilledHeuristics,
108
+ promoteHeuristic,
109
+ pruneHeuristic,
110
+ auditWorkspaceRuleClashes,
111
+ buildConsolidatedSpecMarkdown
112
+ } from '../src/core/rsl_ledger.mjs';
113
+
114
+ export { inspectHookDiagnostics, runDoctorDiagnostics };
115
+
116
+ export const PKG_ROOT = path
117
+ .resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
118
+ .replace(/\\/g, '/');
119
+
120
+ export const PRE_TOOL_USE_MATCHER =
121
+ 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Read|Grep|Glob|Task|Agent|WebFetch|mcp__.*';
122
+ export const POST_TOOL_USE_MATCHER =
123
+ 'Bash|PowerShell|Grep|Glob|Task|Agent|WebFetch|mcp__.*';
124
+ export const LEAN_PRE_TOOL_USE_MATCHER =
125
+ 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Task|Agent|WebFetch|mcp__.*';
126
+ export const LEAN_POST_TOOL_USE_MATCHER =
127
+ 'Bash|PowerShell|Task|Agent|WebFetch|mcp__.*';
128
+
129
+ const AH_HANDLER_REGEX =
130
+ /hooks[\\/]handlers[\\/](pre-tool-use|post-tool-use|pre-model-switch|post-model-switch|compact-lifecycle|stop-gate|user-prompt-submit|config-change)\.mjs/i;
131
+ const AH_STATUSLINE_REGEX = /ah-statusline\.mjs/i;
132
+ const AH_MOD_REGISTER_REGEX = /(?:^|[\\/])hooks[\\/]register\.js$|^\.\/register\.js$/i;
133
+
134
+ /**
135
+ * Extracts the Highbeam command string from either a nested (`{ hooks: [{ command }] }`)
136
+ * or legacy flat (`{ command }`) hook entry.
137
+ *
138
+ * @param {object} entry
139
+ * @returns {string}
140
+ */
141
+ export function extractAhCommandFromEntry(entry) {
142
+ if (!entry || typeof entry !== 'object') return '';
143
+ if (typeof entry.command === 'string' && AH_HANDLER_REGEX.test(entry.command)) {
144
+ return entry.command;
145
+ }
146
+ if (Array.isArray(entry.hooks)) {
147
+ const found = entry.hooks.find((inner) =>
148
+ AH_HANDLER_REGEX.test(String(inner?.command || ''))
149
+ );
150
+ if (found) return String(found.command || '');
151
+ }
152
+ return '';
153
+ }
154
+
155
+ /**
156
+ * Builds canonical nested Claude Code hook entries using either `${CLAUDE_PLUGIN_ROOT}`
157
+ * (when `usePluginRootVar: true`) or double-quoted absolute `${pkgRoot}` paths.
158
+ *
159
+ * @param {object} [options={}]
160
+ * @returns {Record<string, Array<object>>}
161
+ */
162
+ export function buildCanonicalAhHooks(options = {}) {
163
+ const rootPrefix = options.usePluginRootVar
164
+ ? '${CLAUDE_PLUGIN_ROOT}'
165
+ : options.pkgRoot
166
+ ? String(options.pkgRoot).replace(/\\/g, '/').replace(/\/+$/, '')
167
+ : PKG_ROOT;
168
+
169
+ const handlerPrefix = `${rootPrefix}/hooks/handlers`;
170
+ const preMatcher = options.leanHooks ? LEAN_PRE_TOOL_USE_MATCHER : PRE_TOOL_USE_MATCHER;
171
+ const postMatcher = options.leanHooks ? LEAN_POST_TOOL_USE_MATCHER : POST_TOOL_USE_MATCHER;
172
+ const includePostModelSwitch = options.includePostModelSwitch !== false;
173
+
174
+ return {
175
+ PreToolUse: [
176
+ {
177
+ matcher: preMatcher,
178
+ hooks: [
179
+ {
180
+ type: 'command',
181
+ command: `node "${handlerPrefix}/pre-tool-use.mjs"`
182
+ }
183
+ ]
184
+ }
185
+ ],
186
+ PostToolUse: [
187
+ {
188
+ matcher: postMatcher,
189
+ hooks: [
190
+ {
191
+ type: 'command',
192
+ command: `node "${handlerPrefix}/post-tool-use.mjs"`
193
+ }
194
+ ]
195
+ }
196
+ ],
197
+ PreModelSwitch: [
198
+ {
199
+ hooks: [
200
+ {
201
+ type: 'command',
202
+ command: `node "${handlerPrefix}/pre-model-switch.mjs"`
203
+ }
204
+ ]
205
+ }
206
+ ],
207
+ ...(includePostModelSwitch
208
+ ? {
209
+ PostModelSwitch: [
210
+ {
211
+ hooks: [
212
+ {
213
+ type: 'command',
214
+ command: `node "${handlerPrefix}/post-model-switch.mjs"`
215
+ }
216
+ ]
217
+ }
218
+ ]
219
+ }
220
+ : {}),
221
+ PreCompact: [
222
+ {
223
+ hooks: [
224
+ {
225
+ type: 'command',
226
+ command: `node "${handlerPrefix}/compact-lifecycle.mjs" --phase=pre`
227
+ }
228
+ ]
229
+ }
230
+ ],
231
+ PostCompact: [
232
+ {
233
+ hooks: [
234
+ {
235
+ type: 'command',
236
+ command: `node "${handlerPrefix}/compact-lifecycle.mjs" --phase=post`
237
+ }
238
+ ]
239
+ }
240
+ ],
241
+ SessionStart: [
242
+ {
243
+ matcher: 'startup|resume|clear|compact|fork',
244
+ hooks: [
245
+ {
246
+ type: 'command',
247
+ command: `node "${handlerPrefix}/compact-lifecycle.mjs" --phase=start`
248
+ }
249
+ ]
250
+ }
251
+ ],
252
+ Stop: [
253
+ {
254
+ hooks: [
255
+ {
256
+ type: 'command',
257
+ command: `node "${handlerPrefix}/stop-gate.mjs"`
258
+ }
259
+ ]
260
+ }
261
+ ],
262
+ UserPromptSubmit: [
263
+ {
264
+ hooks: [
265
+ {
266
+ type: 'command',
267
+ command: `node "${handlerPrefix}/user-prompt-submit.mjs"`
268
+ }
269
+ ]
270
+ }
271
+ ],
272
+ ConfigChange: [
273
+ {
274
+ hooks: [
275
+ {
276
+ type: 'command',
277
+ command: `node "${handlerPrefix}/config-change.mjs"`
278
+ }
279
+ ]
280
+ }
281
+ ],
282
+ InstructionsLoaded: [
283
+ {
284
+ hooks: [
285
+ {
286
+ type: 'command',
287
+ command: `node "${handlerPrefix}/compact-lifecycle.mjs" --phase=instructions`
288
+ }
289
+ ]
290
+ }
291
+ ],
292
+ SessionEnd: [
293
+ {
294
+ hooks: [
295
+ {
296
+ type: 'command',
297
+ command: `node "${handlerPrefix}/stop-gate.mjs" --phase=end`
298
+ }
299
+ ]
300
+ }
301
+ ]
302
+ };
303
+ }
304
+
305
+ export const CANONICAL_AH_HOOKS = Object.freeze(buildCanonicalAhHooks({ usePluginRootVar: false }));
306
+
307
+ export function isAttentionHorizonHookEntry(entry) {
308
+ return Boolean(extractAhCommandFromEntry(entry));
309
+ }
310
+
311
+ export function resolveSettingsPath(options = {}) {
312
+ if (typeof options.settingsPath === 'string' && options.settingsPath.trim()) {
313
+ return options.settingsPath.trim();
314
+ }
315
+ const scope = options.scope === 'global' || options.global ? 'global' : 'project';
316
+ if (scope === 'global') {
317
+ const home = options.homeDir || os.homedir() || '.';
318
+ return path.join(home, '.claude', 'settings.json');
319
+ }
320
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
321
+ return path.join(cwd, '.claude', 'settings.json');
322
+ }
323
+
324
+ export function ensureGitExcludeEntries(cwd) {
325
+ const gitDir = path.join(cwd, '.git');
326
+ if (!fs.existsSync(gitDir)) {
327
+ return { updated: false, excludePath: null };
328
+ }
329
+
330
+ try {
331
+ const infoDir = path.join(gitDir, 'info');
332
+ if (!fs.existsSync(infoDir)) {
333
+ fs.mkdirSync(infoDir, { recursive: true });
334
+ }
335
+ const excludePath = path.join(infoDir, 'exclude');
336
+ const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf8') : '';
337
+ const lines = existing.split(/\r?\n/);
338
+ const required = ['.claude/cache/', '.claude/locks/'];
339
+ let appended = false;
340
+ let nextContent = existing;
341
+
342
+ for (const req of required) {
343
+ if (!lines.some((line) => line.trim() === req)) {
344
+ if (nextContent.length > 0 && !nextContent.endsWith('\n')) {
345
+ nextContent += '\n';
346
+ }
347
+ nextContent += `${req}\n`;
348
+ appended = true;
349
+ }
350
+ }
351
+
352
+ if (appended) {
353
+ writeTextAtomic(excludePath, nextContent);
354
+ }
355
+ return { updated: appended, excludePath };
356
+ } catch (_err) {
357
+ return { updated: false, excludePath: null };
358
+ }
359
+ }
360
+
361
+ export function installAttentionHorizon(options = {}) {
362
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
363
+ const pkgRoot = options.pkgRoot
364
+ ? String(options.pkgRoot).replace(/\\/g, '/').replace(/\/+$/, '')
365
+ : PKG_ROOT;
366
+ const settingsPath = resolveSettingsPath(options);
367
+ const ts = options.timestamp || Date.now();
368
+ const dryRun = Boolean(options.dryRun);
369
+
370
+ let backupPath = null;
371
+ let currentSettings = {};
372
+
373
+ if (fs.existsSync(settingsPath)) {
374
+ backupPath = `${settingsPath}.ah-backup.${ts}`;
375
+ if (!dryRun) {
376
+ fs.copyFileSync(settingsPath, backupPath);
377
+ }
378
+ const parsed = readJsonSafe(settingsPath, {});
379
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
380
+ currentSettings = JSON.parse(JSON.stringify(parsed));
381
+ }
382
+ }
383
+
384
+ if (!currentSettings.hooks || typeof currentSettings.hooks !== 'object') {
385
+ currentSettings.hooks = {};
386
+ }
387
+
388
+ const canonicalRegisterPath = `${pkgRoot}/hooks/register.js`;
389
+ const existingModules = Array.isArray(currentSettings.hooks.modules)
390
+ ? [...currentSettings.hooks.modules]
391
+ : [];
392
+ const modIdx = existingModules.findIndex((m) => AH_MOD_REGISTER_REGEX.test(String(m)));
393
+ if (modIdx >= 0) {
394
+ existingModules[modIdx] = canonicalRegisterPath;
395
+ } else {
396
+ existingModules.push(canonicalRegisterPath);
397
+ }
398
+ currentSettings.hooks.modules = existingModules;
399
+
400
+ const useLeanHooks =
401
+ options.leanHooks !== undefined ? Boolean(options.leanHooks) : !Boolean(options.fullHooks);
402
+ let includePostModelSwitch =
403
+ options.includePostModelSwitch !== undefined ? Boolean(options.includePostModelSwitch) : true;
404
+ const omittedUnsupportedHooks = [];
405
+ if (
406
+ options.includePostModelSwitch === undefined &&
407
+ options.checkBinaryCapabilities !== false
408
+ ) {
409
+ const caps = inspectClaudeBinaryCapabilities({
410
+ ...options,
411
+ cwd,
412
+ probeVersion: false,
413
+ recordDiagnostic: false,
414
+ writeCache: false
415
+ });
416
+ if (caps.found === true && caps.postModelSwitchSupported === false) {
417
+ includePostModelSwitch = false;
418
+ omittedUnsupportedHooks.push('PostModelSwitch');
419
+ }
420
+ }
421
+ const canonicalHooks = buildCanonicalAhHooks({
422
+ usePluginRootVar: false,
423
+ pkgRoot,
424
+ leanHooks: useLeanHooks,
425
+ includePostModelSwitch
426
+ });
427
+ for (const [eventName, ahEntries] of Object.entries(canonicalHooks)) {
428
+ const existingList = Array.isArray(currentSettings.hooks[eventName])
429
+ ? [...currentSettings.hooks[eventName]]
430
+ : [];
431
+
432
+ for (const ahEntry of ahEntries) {
433
+ const targetCmd = ahEntry.hooks[0].command;
434
+ const targetHandlerMatch = targetCmd.match(AH_HANDLER_REGEX);
435
+ const targetHandlerName = targetHandlerMatch ? targetHandlerMatch[1].toLowerCase() : '';
436
+ const targetPhaseMatch = targetCmd.match(/--phase=([a-z]+)/i);
437
+ const targetPhase = targetPhaseMatch ? targetPhaseMatch[1].toLowerCase() : '';
438
+
439
+ const idx = existingList.findIndex((item) => {
440
+ const existingCmd = extractAhCommandFromEntry(item);
441
+ if (!existingCmd) return false;
442
+ const m = existingCmd.match(AH_HANDLER_REGEX);
443
+ const name = m ? m[1].toLowerCase() : '';
444
+ const pm = existingCmd.match(/--phase=([a-z]+)/i);
445
+ const phase = pm ? pm[1].toLowerCase() : '';
446
+ return name === targetHandlerName && phase === targetPhase;
447
+ });
448
+
449
+ const clonedEntry = JSON.parse(JSON.stringify(ahEntry));
450
+ if (idx >= 0) {
451
+ existingList[idx] = clonedEntry;
452
+ } else {
453
+ existingList.push(clonedEntry);
454
+ }
455
+ }
456
+
457
+ currentSettings.hooks[eventName] = existingList;
458
+ }
459
+
460
+ const ahStatusLine = {
461
+ type: 'command',
462
+ command: `node "${pkgRoot}/bin/ah-statusline.mjs"`
463
+ };
464
+ if (!currentSettings.statusLine) {
465
+ currentSettings.statusLine = ahStatusLine;
466
+ } else if (
467
+ typeof currentSettings.statusLine === 'object' &&
468
+ !AH_STATUSLINE_REGEX.test(String(currentSettings.statusLine.command || ''))
469
+ ) {
470
+ currentSettings.ahPreviousStatusLine = currentSettings.statusLine;
471
+ currentSettings.statusLine = ahStatusLine;
472
+ } else {
473
+ currentSettings.statusLine = ahStatusLine;
474
+ }
475
+
476
+ let ok = true;
477
+ if (!dryRun) {
478
+ ok = writeJsonAtomic(settingsPath, currentSettings);
479
+ }
480
+ const gitExclude = dryRun ? { updated: false } : ensureGitExcludeEntries(cwd);
481
+
482
+ return {
483
+ ok,
484
+ settingsPath,
485
+ backupPath,
486
+ gitExcludeUpdated: gitExclude.updated,
487
+ omittedUnsupportedHooks,
488
+ settings: currentSettings
489
+ };
490
+ }
491
+
492
+ export function uninstallAttentionHorizon(options = {}) {
493
+ const settingsPath = resolveSettingsPath(options);
494
+ if (!fs.existsSync(settingsPath)) {
495
+ return {
496
+ ok: true,
497
+ settingsPath,
498
+ removedHooksCount: 0,
499
+ settings: {}
500
+ };
501
+ }
502
+
503
+ const currentSettings = readJsonSafe(settingsPath, {});
504
+ let removedHooksCount = 0;
505
+
506
+ if (currentSettings.hooks && typeof currentSettings.hooks === 'object') {
507
+ if (Array.isArray(currentSettings.hooks.modules)) {
508
+ const before = currentSettings.hooks.modules.length;
509
+ currentSettings.hooks.modules = currentSettings.hooks.modules.filter(
510
+ (m) => !AH_MOD_REGISTER_REGEX.test(String(m))
511
+ );
512
+ removedHooksCount += before - currentSettings.hooks.modules.length;
513
+ if (currentSettings.hooks.modules.length === 0) {
514
+ delete currentSettings.hooks.modules;
515
+ }
516
+ }
517
+
518
+ for (const eventName of Object.keys(CANONICAL_AH_HOOKS)) {
519
+ if (Array.isArray(currentSettings.hooks[eventName])) {
520
+ const before = currentSettings.hooks[eventName].length;
521
+ currentSettings.hooks[eventName] = currentSettings.hooks[eventName].filter(
522
+ (entry) => !isAttentionHorizonHookEntry(entry)
523
+ );
524
+ removedHooksCount += before - currentSettings.hooks[eventName].length;
525
+ if (currentSettings.hooks[eventName].length === 0) {
526
+ delete currentSettings.hooks[eventName];
527
+ }
528
+ }
529
+ }
530
+ }
531
+
532
+ if (
533
+ currentSettings.statusLine &&
534
+ AH_STATUSLINE_REGEX.test(String(currentSettings.statusLine.command || ''))
535
+ ) {
536
+ if (currentSettings.ahPreviousStatusLine) {
537
+ currentSettings.statusLine = currentSettings.ahPreviousStatusLine;
538
+ delete currentSettings.ahPreviousStatusLine;
539
+ } else {
540
+ delete currentSettings.statusLine;
541
+ }
542
+ }
543
+
544
+ const ok = writeJsonAtomic(settingsPath, currentSettings);
545
+ return {
546
+ ok,
547
+ settingsPath,
548
+ removedHooksCount,
549
+ settings: currentSettings
550
+ };
551
+ }
552
+
553
+ export function generateReceiptReport(options = {}) {
554
+ const sessionId = options.sessionId || 'default';
555
+ const state = options.state || readLiveStateSnapshot(sessionId, options);
556
+ const summary = getSavedQuotaReceiptSummary(options);
557
+ const renderOpts = {
558
+ ...options,
559
+ ledgerSummary: summary
560
+ };
561
+ const pane = options.advanced
562
+ ? renderAdvancedViewPane(state, renderOpts)
563
+ : options.fourRank
564
+ ? renderSimpleHudPane(state, renderOpts)
565
+ : renderSimpleViewPane(state, renderOpts);
566
+ const gitReceipt = generateGitCommitEfficiencyReceipt(options);
567
+ const corporateReceipt = generateCorporateExpenseReceipt(summary, options);
568
+
569
+ return {
570
+ summary,
571
+ pane,
572
+ gitReceipt,
573
+ corporateReceipt,
574
+ text: pane.text,
575
+ markdown: gitReceipt.markdown,
576
+ html: corporateReceipt.html,
577
+ pdfBytes: corporateReceipt.pdfBytes
578
+ };
579
+ }
580
+
581
+ export function generateRoastCard(options = {}) {
582
+ const summary = getSavedQuotaReceiptSummary(options);
583
+ const sessionId = options.sessionId || 'default';
584
+ const live = options.state || readLiveStateSnapshot(sessionId, options) || {};
585
+ const retentionPct = Number(live?.prefixRetention?.retentionIndexPct ?? (options.demo ? 74 : 92));
586
+ const retentionGrade = live?.prefixRetention?.grade || (retentionPct >= 90 ? 'A' : retentionPct >= 75 ? 'B' : 'C');
587
+ const savedTok = Math.max(Number(summary.workspace30dSavedTokens || 0), options.demo ? 142800 : 0);
588
+ const savedUsd = Math.max(Number(summary.workspace30dSavedUSD || 0), options.demo ? 4.28 : 0);
589
+ const leakedUsd = Number(live?.prefixRetention?.leakedColdPrefillUSD ?? (options.demo ? 1.85 : 0.12));
590
+
591
+ const ascii = [
592
+ '╭── 🔥 HIGHBEAM CONTEXT ROAST (Claude Code + Antigravity) ──────────╮',
593
+ `│ KV-Cache Retention : Grade ${retentionGrade} (${retentionPct}% prefix warmth retained) │`,
594
+ `│ Cold Prefill Leak : $${leakedUsd.toFixed(2)} burned on avoidable cold-cache switches/edits │`,
595
+ `│ Verified Savings : +${savedTok.toLocaleString('en-US')} tokens ($${savedUsd.toFixed(2)} USD saved in 30d) │`,
596
+ '│ Top Remediation : Fence mid-session CLAUDE.md/AGENTS.md edits (DET-09) │',
597
+ '╰────────────────────────────────────────────────────────────────────────────╯',
598
+ `Share: Shielded +${savedTok.toLocaleString('en-US')} tokens ($${savedUsd.toFixed(2)}) with npx ah-claude --roast #ClaudeCode #Antigravity`
599
+ ].join('\n');
600
+
601
+ const markdown = [
602
+ '### 🔥 Highbeam Context Roast (`npx ah-claude --roast`)',
603
+ `- **KV-Cache Retention**: Grade **${retentionGrade}** (${retentionPct}% warmth retained)`,
604
+ `- **Cold Prefill Leak**: **$${leakedUsd.toFixed(2)}** burned on avoidable cold switches`,
605
+ `- **30-Day Verified Savings**: **+${savedTok.toLocaleString('en-US')} tokens ($${savedUsd.toFixed(2)} USD)**`,
606
+ `- **Top Fix**: Fence mid-session \`CLAUDE.md\` / \`AGENTS.md\` edits via \`DET-09\` & offload >4k CLI dumps.`
607
+ ].join('\n');
608
+
609
+ return {
610
+ retentionPct,
611
+ retentionGrade,
612
+ leakedUsd,
613
+ savedTok,
614
+ savedUsd,
615
+ ascii,
616
+ markdown
617
+ };
618
+ }
619
+
620
+ export function generateHorizonPanel(options = {}) {
621
+ const sessionId = options.sessionId || 'default';
622
+ const state = options.state || readLiveStateSnapshot(sessionId, options) || {};
623
+ const ledgerSummary = options.ledgerSummary || getSavedQuotaReceiptSummary(options);
624
+ const panel = renderHorizonPanelHtml(state, {
625
+ ...options,
626
+ ledgerSummary,
627
+ initialView: options.advanced ? 'advanced' : options.initialView || 'simple'
628
+ });
629
+ const summary = {
630
+ verdict: panel.verdict.headline,
631
+ action: panel.priorityAction.title,
632
+ sessionSavedTokens: panel.metrics.sessionSavedTokens,
633
+ sessionSavedUSD: panel.metrics.sessionSavedUSD,
634
+ workspace30dSavedTokens: panel.metrics.workspace30dSavedTokens,
635
+ workspace30dSavedUSD: panel.metrics.workspace30dSavedUSD
636
+ };
637
+ return { html: panel.html, summary, state, panel };
638
+ }
639
+
640
+ export function generateCostRadar(options = {}) {
641
+ const sessionId = options.sessionId || 'default';
642
+ let state = options.state || readLiveStateSnapshot(sessionId, options) || {};
643
+ if (options.demo && (!state.prefixRetention || !state.prefixRetention.measured)) {
644
+ state = {
645
+ ...state,
646
+ prefixRetention: {
647
+ measured: true,
648
+ retentionIndexPct: 92,
649
+ grade: 'A',
650
+ retainedDiscountSavingsUSD: 1.5,
651
+ leakedColdPrefillUSD: 0.12,
652
+ measuredTurns: 5,
653
+ bustCount: 0,
654
+ timeline: []
655
+ },
656
+ thinkingDrift: {
657
+ ratio: 1.2,
658
+ loop: { triggered: false }
659
+ }
660
+ };
661
+ }
662
+ const swarm = computeSwarmSummary(state, { nowMs: options.nowMs || Date.now() });
663
+ const html = renderCostRadarHtml({
664
+ retention: state.prefixRetention || null,
665
+ drift: state.thinkingDrift || null,
666
+ topology: toCostRadarTopology(swarm),
667
+ meta: {
668
+ sessionTitle: state.sessionTitle || state.sessionId || '',
669
+ model: state.modelLabel || state.modelId || '',
670
+ edition: 'Cross-Platform',
671
+ generatedAt: options.generatedAt || new Date().toISOString()
672
+ }
673
+ });
674
+ const summary = {
675
+ retention: formatRetentionLabel(state.prefixRetention),
676
+ drift: formatDriftLabel(state.thinkingDrift),
677
+ swarm: formatSwarmCompact(swarm) || 'Solo',
678
+ loopTriggered: Boolean(state.thinkingDrift?.loop?.triggered)
679
+ };
680
+ return { html, summary, state };
681
+ }
682
+
683
+ /**
684
+ * Unified `ctxtop init` installer router.
685
+ * Supports `--antigravity`, `--claude`, `--mcp`, `--cursor`, `--all`, `--workspace`, `--project`, `--dry-run`, `--dedupe`.
686
+ */
687
+ /**
688
+ * Non-destructively writes or merges the `@ctxtop/mcp` server entry into `.cursor/mcp.json`.
689
+ *
690
+ * @param {object} [options]
691
+ * @returns {{ ok: boolean, mcpPath: string, serverKey: string, serverScript: string, dryRun: boolean }}
692
+ */
693
+ export function installMcpConfig(options = {}) {
694
+ const isDryRun = Boolean(options.dryRun);
695
+ const isGlobal = options.scope === 'global' || Boolean(options.global);
696
+ const baseDir = isGlobal
697
+ ? options.homeDir || options.home || getHomeDir()
698
+ : options.cwd || process.cwd();
699
+ const mcpPath = options.mcpConfigPath
700
+ ? path.resolve(options.mcpConfigPath)
701
+ : path.join(baseDir, '.cursor', 'mcp.json');
702
+ const existing = readJsonSafe(mcpPath, {});
703
+ const currentObj =
704
+ existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {};
705
+ const mcpServers =
706
+ currentObj.mcpServers &&
707
+ typeof currentObj.mcpServers === 'object' &&
708
+ !Array.isArray(currentObj.mcpServers)
709
+ ? { ...currentObj.mcpServers }
710
+ : {};
711
+ const serverScript = `${PKG_ROOT}/packages/mcp/src/server.mjs`;
712
+ mcpServers['attention-horizon'] = {
713
+ command: 'node',
714
+ args: [serverScript]
715
+ };
716
+ const updated = {
717
+ ...currentObj,
718
+ mcpServers
719
+ };
720
+ if (!isDryRun) {
721
+ writeJsonAtomic(mcpPath, updated);
722
+ }
723
+ return {
724
+ ok: true,
725
+ mcpPath,
726
+ serverKey: 'attention-horizon',
727
+ serverScript,
728
+ dryRun: isDryRun
729
+ };
730
+ }
731
+
732
+ export function executeInitSubcommand(args = [], options = {}) {
733
+ const isAntigravity = args.includes('--antigravity') || args.includes('-a');
734
+ const isClaude = args.includes('--claude') || args.includes('-c');
735
+ const isMcp =
736
+ args.includes('--mcp') ||
737
+ args.includes('--cursor') ||
738
+ args.includes('--windsurf') ||
739
+ Boolean(options.mcp) ||
740
+ Boolean(options.cursor);
741
+ const isAll = args.includes('--all') || (!isAntigravity && !isClaude && !isMcp);
742
+ const isDryRun = args.includes('--dry-run') || Boolean(options.dryRun);
743
+ const isWorkspace = args.includes('--workspace') || args.includes('--project') || Boolean(options.workspace);
744
+ const isGlobal = args.includes('--global') || Boolean(options.global);
745
+ const isDedupe = args.includes('--dedupe') || Boolean(options.dedupe);
746
+ const isLeanHooks = args.includes('--lean-hooks') || Boolean(options.leanHooks);
747
+ const isFullHooks = args.includes('--full-hooks') || Boolean(options.fullHooks);
748
+
749
+ const targetParts = [];
750
+ if (isAll || isAntigravity) targetParts.push('Google Antigravity');
751
+ if (isAll || isClaude) targetParts.push('Claude Code');
752
+ if (isMcp) targetParts.push('MCP (.cursor/mcp.json)');
753
+ const targetLabel =
754
+ targetParts.length === 2 && !isMcp ? targetParts.join(' & ') : targetParts.join(', ');
755
+
756
+ const lines = [
757
+ `\x1b[1m\x1b[38;5;51m⚡ Highbeam (ctxtop v4.1.0) — Zero-Config Unified Installer\x1b[0m`,
758
+ ` • Target Harnesses : ${targetLabel}`,
759
+ ` • Installation Scope: ${isWorkspace ? 'Workspace' : 'Global'}${isDryRun ? ' [DRY RUN]' : ''}`
760
+ ];
761
+
762
+ let claudeResult = null;
763
+ let antigravityResult = null;
764
+ let mcpResult = null;
765
+
766
+ if (isClaude || isAll) {
767
+ const scope = isGlobal ? 'global' : 'project';
768
+ const hasExplicitLeanArg = args.includes('--lean-hooks') || options.leanHooks !== undefined;
769
+ claudeResult = installAttentionHorizon({
770
+ ...options,
771
+ scope,
772
+ dryRun: isDryRun,
773
+ ...(hasExplicitLeanArg ? { leanHooks: isLeanHooks } : {}),
774
+ ...(isFullHooks ? { leanHooks: false, fullHooks: true } : {}),
775
+ cwd: options.cwd || process.cwd()
776
+ });
777
+ const backupNote = claudeResult.backupPath
778
+ ? ` (backup: ${path.basename(claudeResult.backupPath)})`
779
+ : '';
780
+ lines.push(
781
+ ` \x1b[38;5;82m✓\x1b[0m Claude Code : ${isDryRun ? '[DRY RUN] Would configure' : 'Configured'} ${claudeResult.settingsPath}${backupNote}`
782
+ );
783
+ }
784
+
785
+ if (isAntigravity || isAll) {
786
+ try {
787
+ const agyInstall = installPlugin({
788
+ dryRun: isDryRun,
789
+ workspace: isWorkspace,
790
+ dedupe: isDedupe,
791
+ leanHooks: isLeanHooks,
792
+ fullHooks: isFullHooks,
793
+ cwd: options.cwd || process.cwd(),
794
+ homeDir: options.homeDir || options.home
795
+ });
796
+ lines.push(
797
+ ` \x1b[38;5;82m✓\x1b[0m Antigravity : ${isDryRun ? '[DRY RUN] Would deploy plugin files & lifecycle hooks' : 'Deployed plugin files & lifecycle hooks'}`
798
+ );
799
+ antigravityResult = { ok: true, leanHooks: Boolean(agyInstall?.leanHooks) };
800
+ } catch (err) {
801
+ lines.push(` \x1b[38;5;196m✖\x1b[0m Antigravity : Failed — ${err.message}`);
802
+ antigravityResult = { ok: false, error: err.message };
803
+ }
804
+ }
805
+
806
+ if (isMcp) {
807
+ mcpResult = installMcpConfig({
808
+ ...options,
809
+ global: isGlobal,
810
+ dryRun: isDryRun,
811
+ cwd: options.cwd || process.cwd()
812
+ });
813
+ lines.push(
814
+ ` \x1b[38;5;82m✓\x1b[0m MCP Server : ${isDryRun ? '[DRY RUN] Would configure' : 'Configured'} ${mcpResult.mcpPath} (attention-horizon)`
815
+ );
816
+ }
817
+
818
+ const ok =
819
+ (claudeResult ? claudeResult.ok : true) &&
820
+ (antigravityResult ? antigravityResult.ok : true) &&
821
+ (mcpResult ? mcpResult.ok : true);
822
+ return {
823
+ ok,
824
+ exitCode: ok ? 0 : 1,
825
+ output: lines.join('\n'),
826
+ data: { claude: claudeResult, antigravity: antigravityResult, mcp: mcpResult, dryRun: isDryRun }
827
+ };
828
+ }
829
+
830
+ export function runCli(args = [], options = {}) {
831
+ const subcommand = String(args[0] || 'doctor').toLowerCase();
832
+ const isGlobal = args.includes('--global') || args.includes('-g');
833
+ const isJson = args.includes('--json') || Boolean(options.json);
834
+ const isMarkdown = args.includes('--markdown') || args.includes('--md') || args.includes('--git');
835
+ const isDiagnostic = args.includes('--diagnostic') || args.includes('--bug-report');
836
+ const scope = isGlobal ? 'global' : 'project';
837
+
838
+ if (args.includes('--version') || args.includes('-v') || subcommand === 'version') {
839
+ return { exitCode: 0, output: '4.1.0', data: { version: '4.1.0' } };
840
+ }
841
+
842
+ if (subcommand === 'inspect') {
843
+ const isLast = args.includes('--last') || args[1] === '--last' || Boolean(options.last);
844
+ let sessionId = !isLast && args[1] && !args[1].startsWith('-') ? args[1] : options.sessionId || '';
845
+ for (let i = 1; i < args.length; i++) {
846
+ if (args[i] === '--session' && args[i + 1]) {
847
+ sessionId = args[i + 1];
848
+ break;
849
+ }
850
+ }
851
+
852
+ const outIdx = args.indexOf('--out');
853
+ const outPath = outIdx !== -1 && args[outIdx + 1] ? path.resolve(args[outIdx + 1]) : options.out ? path.resolve(options.out) : null;
854
+ const homeDir = options.homeDir || getHomeDir();
855
+ const cwd = options.cwd || process.cwd();
856
+
857
+ let foundData = null;
858
+ let foundSource = null;
859
+
860
+ // 1. Check live state cache (.claude/cache/ah_live_state_<sessionId>.json)
861
+ if (sessionId && sessionId !== 'default') {
862
+ const safeId = sanitizeSessionId(sessionId);
863
+ const p1 = path.join(cwd, '.claude', 'cache', `ah_live_state_${safeId}.json`);
864
+ const p2 = path.join(homeDir, '.claude', 'cache', `ah_live_state_${safeId}.json`);
865
+ if (fs.existsSync(p1)) {
866
+ foundData = readJsonSafe(p1, null);
867
+ foundSource = p1;
868
+ } else if (fs.existsSync(p2)) {
869
+ foundData = readJsonSafe(p2, null);
870
+ foundSource = p2;
871
+ }
872
+ } else if (isLast) {
873
+ const cacheDir = path.join(cwd, '.claude', 'cache');
874
+ if (fs.existsSync(cacheDir)) {
875
+ try {
876
+ const files = fs.readdirSync(cacheDir)
877
+ .filter((f) => f.startsWith('ah_live_state_') && f.endsWith('.json'))
878
+ .map((f) => ({ name: f, full: path.join(cacheDir, f), mtime: fs.statSync(path.join(cacheDir, f)).mtimeMs }))
879
+ .sort((a, b) => b.mtime - a.mtime);
880
+ if (files.length > 0) {
881
+ foundData = readJsonSafe(files[0].full, null);
882
+ foundSource = files[0].full;
883
+ if (foundData?.sessionId) sessionId = foundData.sessionId;
884
+ }
885
+ } catch (_err) {
886
+ void _err;
887
+ }
888
+ }
889
+ }
890
+
891
+ // 2. Check USTF sessions directory (~/.ctxtop/sessions/<sessionId>.jsonl or .json)
892
+ if (!foundData && sessionId) {
893
+ const safeId = sanitizeSessionId(sessionId);
894
+ const sDir = path.join(homeDir, '.ctxtop', 'sessions');
895
+ const pJsonl = path.join(sDir, `${safeId}.jsonl`);
896
+ const pJson = path.join(sDir, `${safeId}.json`);
897
+ if (fs.existsSync(pJsonl)) {
898
+ try {
899
+ const lines = fs.readFileSync(pJsonl, 'utf8').trim().split('\n').filter(Boolean);
900
+ const events = lines.map((l) => JSON.parse(l));
901
+ foundData = { sessionId, events, harness: 'claude-code' };
902
+ foundSource = pJsonl;
903
+ } catch (_err) {
904
+ void _err;
905
+ }
906
+ } else if (fs.existsSync(pJson)) {
907
+ foundData = readJsonSafe(pJson, null);
908
+ foundSource = pJson;
909
+ }
910
+ }
911
+
912
+ // 3. Check Antigravity session directories
913
+ if (!foundData && sessionId) {
914
+ try {
915
+ const surfaces = getAntigravitySurfaces(homeDir, { includeMissing: false });
916
+ const stores = surfaces.length > 0
917
+ ? surfaces.map((s) => s.brainDir)
918
+ : getBrainStores(homeDir).map((s) => s.path);
919
+ for (const sPath of stores) {
920
+ const candidateDir = path.join(sPath, sessionId);
921
+ if (fs.existsSync(candidateDir)) {
922
+ foundData = { sessionId, path: candidateDir, isAntigravity: true };
923
+ foundSource = candidateDir;
924
+ break;
925
+ }
926
+ }
927
+ } catch (_err) {
928
+ void _err;
929
+ }
930
+ }
931
+
932
+ if (!foundData) {
933
+ return {
934
+ exitCode: 1,
935
+ output: `[Highbeam Inspect] Session "${sessionId}" not found.`,
936
+ data: { found: false, sessionId }
937
+ };
938
+ }
939
+
940
+ let trajectory = null;
941
+ if (foundData.version === '1.0.0' && foundData.sessionId && foundData.events) {
942
+ trajectory = foundData;
943
+ } else if (foundData.isAntigravity || Array.isArray(foundData.steps)) {
944
+ trajectory = normalizeAntigravitySession(foundData, { sessionId, source: foundSource });
945
+ } else if (Array.isArray(foundData.events) || Array.isArray(foundData.entries)) {
946
+ trajectory = normalizeClaudeCodeSession(foundData, { sessionId, source: foundSource });
947
+ } else {
948
+ const empty = createEmptyUstfSession(sessionId || foundData.sessionId || 'default', 'claude-code', {
949
+ modelId: foundData.modelId || foundData.rawModelId || 'claude-sonnet-5-5',
950
+ startTimeMs: foundData.sessionStartTimeMs || Date.now()
951
+ });
952
+ const uncached = Math.max(0, Number(foundData.contextWindow?.totalInputTokens || 0) - Number(foundData.contextWindow?.cachedTokens || 0));
953
+ empty.usage = {
954
+ uncached,
955
+ cacheWrite5m: Number(foundData.contextWindow?.cacheWrite5mTokens || 0),
956
+ cacheWrite1h: Number(foundData.contextWindow?.cacheWrite1hTokens || 0),
957
+ cacheRead: Number(foundData.contextWindow?.cacheReadTokens || foundData.contextWindow?.cachedTokens || 0),
958
+ output: Number(foundData.contextWindow?.outputTokens || 0),
959
+ thinking: Number(foundData.contextWindow?.thinkingTokens || 0),
960
+ costUSD: Number(foundData.savedQuota?.sessionSavedUSD || 0)
961
+ };
962
+ empty.turnsCompleted = Number(foundData.turnsCompleted || 0);
963
+ empty.flightMode = foundData.flightMode || 'COACH';
964
+ trajectory = empty;
965
+ }
966
+
967
+ if (outPath) {
968
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
969
+ writeJsonAtomic(outPath, trajectory);
970
+ }
971
+
972
+ if (isJson) {
973
+ return { exitCode: 0, output: JSON.stringify(trajectory, null, 2), data: trajectory };
974
+ }
975
+
976
+ const totalToks = (trajectory.usage?.uncached || 0) + (trajectory.usage?.cacheRead || 0);
977
+ const lines = [
978
+ `[Highbeam Inspect] Session "${sessionId || trajectory.sessionId}" (${trajectory.harness || 'claude-code'})`,
979
+ ` Model: ${trajectory.modelId || 'unknown'} | Events: ${trajectory.events?.length || 0} | Spans: ${trajectory.spans?.length || 0}`,
980
+ ` Tokens: ${totalToks.toLocaleString()} (Uncached: ${(trajectory.usage?.uncached || 0).toLocaleString()}, Cache: ${(trajectory.usage?.cacheRead || 0).toLocaleString()})`,
981
+ ` Cost: $${(trajectory.usage?.costUSD || 0).toFixed(4)}`,
982
+ outPath ? ` Artifact written: ${outPath}` : ''
983
+ ].filter(Boolean);
984
+
985
+ return { exitCode: 0, output: lines.join('\n'), data: trajectory };
986
+ }
987
+
988
+ if (subcommand === 'control') {
989
+ const action = String(args[1] || '').toLowerCase();
990
+ const validActions = ['pause', 'resume', 'step', 'abort', 'rewind', 'status'];
991
+ if (!validActions.includes(action)) {
992
+ return {
993
+ exitCode: 1,
994
+ output: `[Highbeam Control] Invalid control action "${args[1] || ''}". Valid actions: pause, resume, step, abort, rewind`,
995
+ data: { ok: false, validActions }
996
+ };
997
+ }
998
+
999
+ let sessionId = options.sessionId || 'default';
1000
+ for (let i = 2; i < args.length; i++) {
1001
+ if (args[i] === '--session' && args[i + 1]) {
1002
+ sessionId = args[i + 1];
1003
+ break;
1004
+ }
1005
+ }
1006
+
1007
+ const homeDir = options.homeDir || process.env.USERPROFILE || process.env.HOME || os.homedir();
1008
+ const runtimeDir = path.join(homeDir, '.ctxtop', 'runtime');
1009
+
1010
+ if (action === 'status') {
1011
+ const ctlPath = path.join(runtimeDir, `${sessionId}.ctl`);
1012
+ let currentState = { sessionId, state: 'RUNNING', reason: 'default' };
1013
+ if (fs.existsSync(ctlPath)) {
1014
+ try {
1015
+ currentState = parseControlFile(fs.readFileSync(ctlPath, 'utf8'), sessionId);
1016
+ } catch (_err) {
1017
+ void _err;
1018
+ }
1019
+ }
1020
+ return {
1021
+ exitCode: 0,
1022
+ output: `[Highbeam Control] Session "${sessionId}" is ${currentState.state}`,
1023
+ data: { ok: true, sessionId, state: currentState }
1024
+ };
1025
+ }
1026
+
1027
+ let rewindTarget = options.target || options.rewindTarget || null;
1028
+ const targetIdx = args.indexOf('--target') !== -1 ? args.indexOf('--target') : args.indexOf('--turn');
1029
+ if (targetIdx !== -1 && args[targetIdx + 1]) {
1030
+ rewindTarget = args[targetIdx + 1];
1031
+ } else if (args[2] && !args[2].startsWith('-')) {
1032
+ rewindTarget = args[2];
1033
+ }
1034
+
1035
+ const reason = options.reason || `CLI /control ${action}${rewindTarget ? ` (target: ${rewindTarget})` : ''}`;
1036
+
1037
+ try {
1038
+ fs.mkdirSync(runtimeDir, { recursive: true });
1039
+ const ctlPath = path.join(runtimeDir, `${sessionId}.ctl`);
1040
+ let currentState = null;
1041
+ if (fs.existsSync(ctlPath)) {
1042
+ try {
1043
+ currentState = parseControlFile(fs.readFileSync(ctlPath, 'utf8'), sessionId);
1044
+ } catch (_err) {
1045
+ void _err;
1046
+ }
1047
+ }
1048
+ const nextState = transitionControlState(currentState, action, reason, { sessionId, target: rewindTarget });
1049
+ fs.writeFileSync(ctlPath, serializeControlFile(nextState), 'utf8');
1050
+
1051
+ // Best-effort notify warm IPC daemon
1052
+ try {
1053
+ const client = new MicroIpcClient({ homeDir });
1054
+ client.call('control.transition', { sessionId, action, reason, target: rewindTarget }, { connectTimeoutMs: 15, requestTimeoutMs: 100 }).catch((_ipcErr) => {
1055
+ void _ipcErr;
1056
+ });
1057
+ } catch (_ipcErr) {
1058
+ void _ipcErr;
1059
+ }
1060
+
1061
+ return {
1062
+ exitCode: 0,
1063
+ output: `[Highbeam Control] State transitioned to ${nextState.state}`,
1064
+ data: { ok: true, action, sessionId, state: nextState }
1065
+ };
1066
+ } catch (err) {
1067
+ return {
1068
+ exitCode: 1,
1069
+ output: `[Highbeam Control] Failed to transition control state: ${err.message}`,
1070
+ data: { ok: false, error: err.message }
1071
+ };
1072
+ }
1073
+ }
1074
+
1075
+ if (subcommand === 'init') {
1076
+ return executeInitSubcommand(args.slice(1), options);
1077
+ }
1078
+
1079
+ if (subcommand === 'install') {
1080
+ const fullHooks =
1081
+ args.includes('--full-hooks') || options.leanHooks === false || Boolean(options.fullHooks);
1082
+ const leanHooks =
1083
+ args.includes('--lean-hooks') || options.leanHooks === true || !fullHooks;
1084
+ const res = installAttentionHorizon({ ...options, scope, leanHooks });
1085
+ const backupNote = res.backupPath ? `\nBackup saved: ${res.backupPath}` : '';
1086
+ const output = `[Highbeam] Installed non-destructively into ${res.settingsPath}${backupNote}`;
1087
+ return { exitCode: res.ok ? 0 : 1, output, data: res };
1088
+ }
1089
+
1090
+ if (subcommand === 'team-pack' || subcommand === 'team-finops') {
1091
+ const outIdx = args.indexOf('--out');
1092
+ const orgIdx = args.indexOf('--org');
1093
+ const outDir =
1094
+ outIdx !== -1 && args[outIdx + 1] ? path.resolve(args[outIdx + 1]) : options.outDir;
1095
+ const orgName =
1096
+ orgIdx !== -1 && args[orgIdx + 1] ? args[orgIdx + 1] : options.orgName || 'Engineering Team';
1097
+ const preview = args.includes('--preview') || Boolean(options.preview);
1098
+ const packRes = generateTeamFinopsPack({ ...options, outDir, orgName, preview });
1099
+ if (!packRes.ok) {
1100
+ return {
1101
+ exitCode: 2,
1102
+ output: `[Highbeam Team] ${packRes.entitlement.upgradeHint}`,
1103
+ data: packRes
1104
+ };
1105
+ }
1106
+ if (isJson) {
1107
+ return { exitCode: 0, output: JSON.stringify(packRes, null, 2), data: packRes };
1108
+ }
1109
+ return {
1110
+ exitCode: 0,
1111
+ output: `[Highbeam Team] Generated BYO-Grafana & Datadog Team FinOps Pack in: ${packRes.outDir}\n Files written: ${packRes.filesWritten.length}`,
1112
+ data: packRes
1113
+ };
1114
+ }
1115
+
1116
+ if (subcommand === 'verify' || subcommand === 'verify-checksums') {
1117
+ const rootDir = options.rootDir || PKG_ROOT;
1118
+ const manifestPath = path.join(rootDir, 'CHECKSUMS.sha256');
1119
+ if (!fs.existsSync(manifestPath)) {
1120
+ const missingRes = {
1121
+ valid: false,
1122
+ verifiedCount: 0,
1123
+ mismatches: ['Missing CHECKSUMS.sha256 manifest']
1124
+ };
1125
+ return {
1126
+ exitCode: 1,
1127
+ output: isJson
1128
+ ? JSON.stringify(missingRes, null, 2)
1129
+ : '[Highbeam Verify] FAILED: Missing CHECKSUMS.sha256 manifest',
1130
+ data: missingRes
1131
+ };
1132
+ }
1133
+ const lines = fs.readFileSync(manifestPath, 'utf8').split(/\r?\n/).filter(Boolean);
1134
+ const mismatches = [];
1135
+ let verifiedCount = 0;
1136
+ for (const line of lines) {
1137
+ const match = line.match(/^([a-f0-9]{64})\s\s(.+)$/);
1138
+ if (!match) continue;
1139
+ const [, expectedHash, relPath] = match;
1140
+ const absPath = path.join(rootDir, relPath);
1141
+ if (!fs.existsSync(absPath)) {
1142
+ mismatches.push(`Missing file: ${relPath}`);
1143
+ continue;
1144
+ }
1145
+ const normalized = fs.readFileSync(absPath, 'utf8').replace(/\r\n/g, '\n');
1146
+ const actualHash = sha256HexPure(normalized);
1147
+ if (actualHash !== expectedHash) {
1148
+ mismatches.push(`Checksum mismatch: ${relPath}`);
1149
+ } else {
1150
+ verifiedCount++;
1151
+ }
1152
+ }
1153
+ const verifyRes = {
1154
+ valid: mismatches.length === 0 && verifiedCount > 0,
1155
+ verifiedCount,
1156
+ mismatches
1157
+ };
1158
+ if (isJson) {
1159
+ return {
1160
+ exitCode: verifyRes.valid ? 0 : 1,
1161
+ output: JSON.stringify(verifyRes, null, 2),
1162
+ data: verifyRes
1163
+ };
1164
+ }
1165
+ return {
1166
+ exitCode: verifyRes.valid ? 0 : 1,
1167
+ output: verifyRes.valid
1168
+ ? `[Highbeam Verify] PASS — ${verifiedCount} release files verified against CHECKSUMS.sha256 (0 mismatches)`
1169
+ : `[Highbeam Verify] FAIL — ${mismatches.length} mismatch(es): ${mismatches.slice(0, 5).join('; ')}`,
1170
+ data: verifyRes
1171
+ };
1172
+ }
1173
+
1174
+ if (subcommand === 'tiers') {
1175
+ if (isJson) {
1176
+ return { exitCode: 0, output: JSON.stringify(PLG_TIER_MATRIX, null, 2), data: PLG_TIER_MATRIX };
1177
+ }
1178
+ const lines = [
1179
+ 'Highbeam — 3-Tier Self-Expensing PLG Funnel:',
1180
+ ` • Free ($0/mo): ${PLG_TIER_MATRIX.free.features.join(', ')}`,
1181
+ ` • Pro ($${PLG_TIER_MATRIX.pro.priceMonthlyUSD}/mo [$12-$19/mo]): ${PLG_TIER_MATRIX.pro.features.join(', ')}`,
1182
+ ` • Team ($${PLG_TIER_MATRIX.team.pricePerSeatMonthlyUSD}/seat/mo): ${PLG_TIER_MATRIX.team.features.join(', ')}`
1183
+ ];
1184
+ return { exitCode: 0, output: lines.join('\n'), data: PLG_TIER_MATRIX };
1185
+ }
1186
+
1187
+ if (subcommand === 'license' || subcommand === 'pro') {
1188
+ const action = String(args[1] || 'status').toLowerCase();
1189
+ if (action === 'tiers') {
1190
+ if (isJson) {
1191
+ return { exitCode: 0, output: JSON.stringify(PLG_TIER_MATRIX, null, 2), data: PLG_TIER_MATRIX };
1192
+ }
1193
+ const lines = [
1194
+ 'Highbeam — 3-Tier Self-Expensing PLG Funnel:',
1195
+ ` • Free ($0/mo): ${PLG_TIER_MATRIX.free.features.join(', ')}`,
1196
+ ` • Pro ($${PLG_TIER_MATRIX.pro.priceMonthlyUSD}/mo [$12-$19/mo]): ${PLG_TIER_MATRIX.pro.features.join(', ')}`,
1197
+ ` • Team ($${PLG_TIER_MATRIX.team.pricePerSeatMonthlyUSD}/seat/mo): ${PLG_TIER_MATRIX.team.features.join(', ')}`
1198
+ ];
1199
+ return { exitCode: 0, output: lines.join('\n'), data: PLG_TIER_MATRIX };
1200
+ }
1201
+ if (action === 'activate' && args[2]) {
1202
+ const actRes = activateProLicense(args[2], options);
1203
+ if (isJson) {
1204
+ return { exitCode: actRes.ok ? 0 : 1, output: JSON.stringify(actRes, null, 2), data: actRes };
1205
+ }
1206
+ return {
1207
+ exitCode: actRes.ok ? 0 : 1,
1208
+ output: actRes.ok
1209
+ ? `[Highbeam Pro] Activated ${actRes.tier.toUpperCase()} license (${actRes.payload.email}) -> ${actRes.licensePath}`
1210
+ : `[Highbeam Pro] License activation failed: ${actRes.reason}`,
1211
+ data: actRes
1212
+ };
1213
+ }
1214
+ if (action === 'trial') {
1215
+ const trRes = activateLocalTrial(options);
1216
+ return {
1217
+ exitCode: 0,
1218
+ output: `[Highbeam Pro] Activated 14-day local trial (expires ${trRes.expiresAt}) -> ${trRes.licensePath}`,
1219
+ data: trRes
1220
+ };
1221
+ }
1222
+ if (action === 'deactivate') {
1223
+ const deactRes = deactivateProLicense(options);
1224
+ return {
1225
+ exitCode: 0,
1226
+ output: `[Highbeam Pro] Deactivated license (${deactRes.licensePath})`,
1227
+ data: deactRes
1228
+ };
1229
+ }
1230
+ const status = getProEntitlementStatus(options);
1231
+ if (isJson) {
1232
+ return { exitCode: 0, output: JSON.stringify(status, null, 2), data: status };
1233
+ }
1234
+ return {
1235
+ exitCode: 0,
1236
+ output: `[Highbeam Pro] Tier=${status.tier} | Entitled=${status.entitled} | Source=${status.source}`,
1237
+ data: status
1238
+ };
1239
+ }
1240
+
1241
+ if (subcommand === 'roast' || (args.includes('--roast') && subcommand !== 'postmortem')) {
1242
+ const isDemo = args.includes('--demo') || Boolean(options.demo);
1243
+ const roast = generateRoastCard({ ...options, demo: isDemo });
1244
+ if (isJson) {
1245
+ return { exitCode: 0, output: JSON.stringify(roast, null, 2), data: roast };
1246
+ }
1247
+ if (isMarkdown) {
1248
+ return { exitCode: 0, output: roast.markdown, data: roast };
1249
+ }
1250
+ return { exitCode: 0, output: roast.ascii, data: roast };
1251
+ }
1252
+
1253
+ if (subcommand === 'uninstall') {
1254
+ const res = uninstallAttentionHorizon({ ...options, scope });
1255
+ const output = `[Highbeam] Uninstalled ${res.removedHooksCount} hook entries from ${res.settingsPath}`;
1256
+ return { exitCode: res.ok ? 0 : 1, output, data: res };
1257
+ }
1258
+
1259
+ if (subcommand === 'config') {
1260
+ const action = String(args[1] || 'list').toLowerCase();
1261
+ if (action === 'set') {
1262
+ const detId = args[2];
1263
+ const mode = args[3] || 'default';
1264
+ const res = setDetectorOverride(detId, mode, { ...options, scope });
1265
+ if (!res.ok) {
1266
+ return {
1267
+ exitCode: 1,
1268
+ output: `[Highbeam Config] Invalid detector ID "${detId}". Expected DET-01..DET-20.`,
1269
+ data: res
1270
+ };
1271
+ }
1272
+ return {
1273
+ exitCode: 0,
1274
+ output: `[Highbeam Config] Set ${res.detectorId}=${res.mode} in ${res.configPath}`,
1275
+ data: res
1276
+ };
1277
+ }
1278
+ if (action === 'reset') {
1279
+ const res = resetHorizonConfig({ ...options, scope });
1280
+ return {
1281
+ exitCode: res.ok ? 0 : 1,
1282
+ output: `[Highbeam Config] Reset detector overrides at ${res.configPath}`,
1283
+ data: res
1284
+ };
1285
+ }
1286
+ const cfg = loadHorizonConfig({ ...options, scope });
1287
+ if (isJson) {
1288
+ return { exitCode: 0, output: JSON.stringify(cfg, null, 2), data: cfg };
1289
+ }
1290
+ const lines = [
1291
+ `[Highbeam Config] FlightMode=${cfg.flightMode} (projectLoaded=${cfg.sources.projectLoaded})`,
1292
+ ...Object.entries(cfg.detectors).map(([id, m]) => ` ${id}: ${m}`)
1293
+ ];
1294
+ return { exitCode: 0, output: lines.join('\n'), data: cfg };
1295
+ }
1296
+
1297
+ if (subcommand === 'cost-radar' || subcommand === 'radar') {
1298
+ const isDemo = args.includes('--demo') || Boolean(options.demo);
1299
+ const isShare = args.includes('--share') || Boolean(options.share);
1300
+ const outIdx = args.indexOf('--out');
1301
+ const target = path.resolve(
1302
+ outIdx !== -1 && args[outIdx + 1]
1303
+ ? args[outIdx + 1]
1304
+ : path.join(os.homedir(), '.claude', 'attention-horizon', 'cost_radar.html')
1305
+ );
1306
+ const res = generateCostRadar({ ...options, demo: isDemo });
1307
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1308
+ const ok = writeTextAtomic(target, res.html) !== false;
1309
+ const shareSnippet = `⚡ Cost Radar: ${res.summary.retention} · ${res.summary.drift} · ${res.summary.swarm} (via npx ah-claude cost-radar)`;
1310
+ const data = { ok, path: target, ...res.summary, shareSnippet };
1311
+ if (isJson) {
1312
+ return { exitCode: ok ? 0 : 1, output: JSON.stringify(data, null, 2), data };
1313
+ }
1314
+ return {
1315
+ exitCode: ok ? 0 : 1,
1316
+ output: `[Highbeam] Cost Radar written: ${target}\n ${res.summary.retention}\n ${res.summary.drift}\n ${res.summary.swarm}${isShare ? `\n Share: ${shareSnippet}` : ''}`,
1317
+ data
1318
+ };
1319
+ }
1320
+
1321
+ if (subcommand === 'postmortem' || args.includes('--postmortem')) {
1322
+ const lastIdx = args.indexOf('--last');
1323
+ const last = lastIdx !== -1 && args[lastIdx + 1] ? Number(args[lastIdx + 1]) : (options.last || 15);
1324
+ const isRoast = args.includes('--roast') || Boolean(options.roast);
1325
+ const isDemo = args.includes('--demo') || Boolean(options.demo);
1326
+ return runPostmortem({
1327
+ ...options,
1328
+ last,
1329
+ json: false,
1330
+ demo: isDemo,
1331
+ roast: isRoast,
1332
+ writeFiles: options.writeFiles !== false
1333
+ }).then((res) => {
1334
+ if (isJson) {
1335
+ return { exitCode: 0, output: JSON.stringify(res, null, 2), data: res };
1336
+ }
1337
+ const estM = typeof res.estTokensM === 'number' ? `${res.estTokensM.toFixed(2)}M` : String(res.estTokensM || '0M');
1338
+ const summaryText = [
1339
+ `[Highbeam Postmortem] Analyzed ${res.sessionCount} sessions (${estM} active tokens)`,
1340
+ ` Clean Sessions: ${res.cleanSessionCount || 0} | Churn: ${res.churnSessionCount || 0} | Rot: ${res.rotSessionCount || 0}`,
1341
+ res.reportPath ? ` Report: ${res.reportPath}` : ''
1342
+ ].filter(Boolean).join('\n');
1343
+ return { exitCode: 0, output: summaryText, data: res };
1344
+ });
1345
+ }
1346
+
1347
+ if (subcommand === 'panel') {
1348
+ const outIdx = args.indexOf('--out');
1349
+ const isAdvanced = args.includes('--advanced') || args.includes('advanced');
1350
+ const target = path.resolve(
1351
+ outIdx !== -1 && args[outIdx + 1]
1352
+ ? args[outIdx + 1]
1353
+ : path.join(os.homedir(), '.claude', 'attention-horizon', 'horizon_panel.html')
1354
+ );
1355
+ const res = generateHorizonPanel({ ...options, advanced: isAdvanced });
1356
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1357
+ const ok = writeTextAtomic(target, res.html) !== false;
1358
+ const data = { ok, path: target, ...res.summary };
1359
+ if (isJson) {
1360
+ return { exitCode: ok ? 0 : 1, output: JSON.stringify(data, null, 2), data };
1361
+ }
1362
+ return {
1363
+ exitCode: ok ? 0 : 1,
1364
+ 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`,
1365
+ data
1366
+ };
1367
+ }
1368
+
1369
+ if (subcommand === 'receipt') {
1370
+ const isAdvanced = args.includes('--advanced') || args.includes('advanced');
1371
+ const isFourRank = args.includes('--4-rank') || args.includes('--simple');
1372
+ const isPdf = args.includes('--pdf') || Boolean(options.pdf);
1373
+ const isHtml = args.includes('--html') || Boolean(options.html);
1374
+ const outIdx = args.indexOf('--out');
1375
+ const outPath = outIdx !== -1 && args[outIdx + 1]
1376
+ ? path.resolve(args[outIdx + 1])
1377
+ : options.out
1378
+ ? path.resolve(options.out)
1379
+ : null;
1380
+ const res = generateReceiptReport({
1381
+ ...options,
1382
+ advanced: isAdvanced,
1383
+ fourRank: isFourRank
1384
+ });
1385
+ if (isPdf) {
1386
+ const proCheck = requireProFeature('corporate_expense_receipts', options);
1387
+ if (!proCheck.allowed) {
1388
+ const savedUsd = res.corporateReceipt.workspace30dSavedUSD.toFixed(2);
1389
+ return {
1390
+ exitCode: 2,
1391
+ output: `[Highbeam Pro] Pro would expense +$${savedUsd} USD saved over 30d. ${proCheck.upgradeHint}`,
1392
+ data: { ok: false, requiresPro: true, entitlement: proCheck, shadowSavedUSD: Number(savedUsd) }
1393
+ };
1394
+ }
1395
+ const targetPdf = outPath || path.resolve(options.cwd || process.cwd(), 'attention-horizon-expense-receipt.pdf');
1396
+ fs.mkdirSync(path.dirname(targetPdf), { recursive: true });
1397
+ fs.writeFileSync(targetPdf, Buffer.from(res.pdfBytes));
1398
+ const pdfData = {
1399
+ ok: true,
1400
+ path: targetPdf,
1401
+ receiptId: res.corporateReceipt.receiptId,
1402
+ sha256: res.corporateReceipt.sha256,
1403
+ workspace30dSavedUSD: res.corporateReceipt.workspace30dSavedUSD,
1404
+ netRoiMultiplier: res.corporateReceipt.netRoiMultiplier
1405
+ };
1406
+ if (isJson) {
1407
+ return { exitCode: 0, output: JSON.stringify(pdfData, null, 2), data: pdfData };
1408
+ }
1409
+ return {
1410
+ exitCode: 0,
1411
+ 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}`,
1412
+ data: pdfData
1413
+ };
1414
+ }
1415
+ if (isHtml) {
1416
+ if (outPath) {
1417
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
1418
+ writeTextAtomic(outPath, res.html);
1419
+ }
1420
+ return { exitCode: 0, output: res.html, data: res };
1421
+ }
1422
+ if (isJson) {
1423
+ return { exitCode: 0, output: JSON.stringify(res.gitReceipt, null, 2), data: res };
1424
+ }
1425
+ if (isMarkdown) {
1426
+ if (outPath) {
1427
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
1428
+ writeTextAtomic(outPath, res.markdown);
1429
+ }
1430
+ return { exitCode: 0, output: res.markdown, data: res };
1431
+ }
1432
+ return { exitCode: 0, output: res.text, data: res };
1433
+ }
1434
+
1435
+ if (subcommand === 'doctor') {
1436
+ if (args.includes('--prune-tools') || args.includes('--gc-cursor') || args.includes('--recover-brain') || args.includes('--reap-orphans') || args.includes('--handoff')) {
1437
+ return runDoctor({ ...options, ...parseDoctorArgs(args) }).then((docRes) => ({
1438
+ exitCode: docRes.ok ? 0 : 1,
1439
+ output: JSON.stringify(docRes, null, 2),
1440
+ data: docRes
1441
+ }));
1442
+ }
1443
+ const res = runDoctorDiagnostics(options);
1444
+ if (isDiagnostic) {
1445
+ const bundle = generateZeroPiiDiagnosticBundle(res, options);
1446
+ return {
1447
+ exitCode: res.ok ? 0 : 1,
1448
+ output: isJson ? JSON.stringify(bundle, null, 2) : bundle.markdown,
1449
+ data: bundle
1450
+ };
1451
+ }
1452
+ if (isJson) {
1453
+ return { exitCode: res.ok ? 0 : 1, output: JSON.stringify(res, null, 2), data: res };
1454
+ }
1455
+ const hookDiag = res.hookDiagnostics || { recentErrorCount: 0, recentErrors: [] };
1456
+ const ccCap = res.claudeCapabilities;
1457
+ const lines = [
1458
+ `[Highbeam Doctor] Status: ${res.ok ? 'HEALTHY' : 'ISSUES DETECTED'}`,
1459
+ ...res.checks.map((c) => {
1460
+ const badge = c.status || (c.ok ? 'PASS' : 'FAIL');
1461
+ return ` [${badge}] ${c.id}: ${c.detail}`;
1462
+ }),
1463
+ ...(ccCap?.found
1464
+ ? [
1465
+ ` [${ccCap.contractValid ? 'PASS' : 'WARN'}] claude_pre_model_switch: Claude Code ${ccCap.claudeVersion || 'unknown'} | PreModelSwitch=${ccCap.preModelSwitchSupported} | ask=${ccCap.supportsAskDecision} | PreEffortChange=${ccCap.preEffortChangeSupported}`
1466
+ ]
1467
+ : []),
1468
+ ` [${hookDiag.recentErrorCount > 0 ? 'WARN' : 'PASS'}] hook_diagnostics: ${hookDiag.recentErrorCount} recent non-fatal error(s)`
1469
+ ];
1470
+ for (const errEntry of hookDiag.recentErrors) {
1471
+ lines.push(
1472
+ ` - [${errEntry.timestamp}] ${errEntry.source}#${errEntry.operation} (${errEntry.name}): ${errEntry.message}`
1473
+ );
1474
+ }
1475
+ return { exitCode: res.ok ? 0 : 1, output: lines.join('\n'), data: res };
1476
+ }
1477
+
1478
+ if (subcommand === 'statusline') {
1479
+ return runStatusLineCli(args.slice(1));
1480
+ }
1481
+
1482
+ if (subcommand === 'audit') {
1483
+ const platIdx = args.indexOf('--platform');
1484
+ const platform =
1485
+ platIdx !== -1 && args[platIdx + 1]
1486
+ ? String(args[platIdx + 1]).toLowerCase()
1487
+ : (options.platform || 'all');
1488
+ const daysIdx = args.indexOf('--days');
1489
+ const days =
1490
+ daysIdx !== -1 && args[daysIdx + 1]
1491
+ ? Number(args[daysIdx + 1])
1492
+ : (options.days || 7);
1493
+ const limitIdx = args.indexOf('--limit');
1494
+ const limit =
1495
+ limitIdx !== -1 && args[limitIdx + 1]
1496
+ ? Number(args[limitIdx + 1])
1497
+ : (options.limit || 10);
1498
+
1499
+ const auditRes = runSessionAudit({
1500
+ ...options,
1501
+ platform,
1502
+ days,
1503
+ limit
1504
+ });
1505
+ if (isJson) {
1506
+ return { exitCode: 0, output: JSON.stringify(auditRes, null, 2), data: auditRes };
1507
+ }
1508
+ return { exitCode: 0, output: formatSessionAuditReport(auditRes), data: auditRes };
1509
+ }
1510
+
1511
+ if (subcommand === 'rsl') {
1512
+ const action = String(args[1] || 'status').toLowerCase();
1513
+ const readFlag = (flag, fallback) => {
1514
+ const idx = args.indexOf(flag);
1515
+ return idx !== -1 && args[idx + 1] ? String(args[idx + 1]) : fallback;
1516
+ };
1517
+ const wsRoot = path.resolve(readFlag('--cwd', options.cwd || process.cwd()));
1518
+ const platform = readFlag('--platform', options.platform || 'all').toLowerCase();
1519
+
1520
+ if (action === 'status') {
1521
+ const summary = { ok: true, platform, ...getRslSummary(wsRoot, options) };
1522
+ if (isJson) {
1523
+ return { exitCode: 0, output: JSON.stringify(summary, null, 2), data: summary };
1524
+ }
1525
+ const memNote = summary.claudeMemoryAudit?.triggered
1526
+ ? `WARN (${summary.claudeMemoryAudit.maxLines}L / ${Math.round(summary.claudeMemoryAudit.maxBytes / 1024)}KB)`
1527
+ : 'OK';
1528
+ const lines = [
1529
+ `[Highbeam RSL] Dual-Platform Self-Learning Status (platform=${platform})`,
1530
+ ` Active Carriers : ${summary.activeRules} rules · ${summary.activeSkills} skills · ${summary.promotedHooks} promoted hooks`,
1531
+ ` Rule Budget : ${summary.ruleBudgetTokens}/${summary.ruleBudgetMaxTokens} tokens (${summary.ruleBudgetPct}%)`,
1532
+ ` Rule Clashes : ${summary.clashCount || 0} conflict(s)${summary.quarantinedCount ? ` (${summary.quarantinedCount} quarantined)` : ''}`,
1533
+ ` Lifecycle Stats : ${summary.prunedCount} pruned · ${summary.taintedSessions} tainted sessions`,
1534
+ ` Claude Memory : ${memNote}`,
1535
+ ...((summary.activeClashes || []).map((c) => ` [RULE_CONFLICT] ${c.reason}`))
1536
+ ];
1537
+ return { exitCode: 0, output: lines.join('\n'), data: summary };
1538
+ }
1539
+
1540
+ if (action === 'list') {
1541
+ const includeAll = args.includes('--all') || Boolean(options.all);
1542
+ const summary = getRslSummary(wsRoot, { ...options, includeAll });
1543
+ const payload = { ok: true, includeAll, count: summary.items.length, items: summary.items };
1544
+ if (isJson) {
1545
+ return { exitCode: 0, output: JSON.stringify(payload, null, 2), data: payload };
1546
+ }
1547
+ const lines = [`[Highbeam RSL] Heuristics (${payload.count} item(s), all=${includeAll}):`];
1548
+ for (const it of summary.items) {
1549
+ lines.push(` - ${it.slug} [${it.carrier}] importance=${it.importance} status=${it.status} hook=${Boolean(it.promotedHook)}`);
1550
+ }
1551
+ return { exitCode: 0, output: lines.join('\n'), data: payload };
1552
+ }
1553
+
1554
+ if (action === 'run') {
1555
+ const mode = readFlag('--mode', options.mode || 'local').toLowerCase();
1556
+ let sessionId = readFlag('--session', options.sessionId || '');
1557
+ if (!sessionId) {
1558
+ const telemetryDir = path.join(wsRoot, '.agents', 'telemetry');
1559
+ if (fs.existsSync(telemetryDir)) {
1560
+ const candidates = fs.readdirSync(telemetryDir)
1561
+ .filter((f) => f.endsWith('.rsl_steps.jsonl'))
1562
+ .map((f) => ({ name: f.replace(/\.rsl_steps\.jsonl$/, ''), mtime: fs.statSync(path.join(telemetryDir, f)).mtimeMs }))
1563
+ .sort((a, b) => b.mtime - a.mtime);
1564
+ if (candidates[0]) sessionId = candidates[0].name;
1565
+ }
1566
+ }
1567
+ sessionId = sanitizeRslSessionId(sessionId || 'default');
1568
+ const resolvedPlatform = platform === 'auto' || platform === 'all'
1569
+ ? (options.transcriptPath && String(options.transcriptPath).includes('.claude') ? 'claude' : 'antigravity')
1570
+ : platform;
1571
+ const digest = buildContrastiveDigest(
1572
+ {
1573
+ conversationId: sessionId,
1574
+ session_id: sessionId,
1575
+ cwd: wsRoot,
1576
+ workspacePaths: [wsRoot],
1577
+ transcriptPath: readFlag('--transcript', options.transcriptPath || ''),
1578
+ artifactDirectoryPath: readFlag('--artifacts', options.artifactDirectoryPath || '')
1579
+ },
1580
+ { ...options, cwd: wsRoot, platform: resolvedPlatform }
1581
+ );
1582
+ const distillation = digest.triggered
1583
+ ? distillContrastiveDigest(digest, { mode, sdkRunner: options.sdkRunner })
1584
+ : { is_valid_learning: false, mode, heuristics: [] };
1585
+ const ledgerResult = (digest.tainted || digest.triggered || fs.existsSync(getRslLedgerPath(wsRoot)))
1586
+ ? ingestDistilledHeuristics(wsRoot, distillation, digest, options)
1587
+ : null;
1588
+ const summary = getRslSummary(wsRoot, options);
1589
+ const res = {
1590
+ ok: !digest.tainted,
1591
+ sessionId,
1592
+ platform: resolvedPlatform,
1593
+ mode: distillation.mode || mode,
1594
+ digest,
1595
+ distillation,
1596
+ ledgerResult,
1597
+ summary
1598
+ };
1599
+ if (isJson) {
1600
+ return { exitCode: res.ok ? 0 : 1, output: JSON.stringify(res, null, 2), data: res };
1601
+ }
1602
+ const msg = digest.tainted
1603
+ ? `[Highbeam RSL] Session ${sessionId} flagged ${digest.status} (${digest.taintDetails.join('; ')}) — extraction aborted.`
1604
+ : `[Highbeam RSL] Session ${sessionId} distilled (${res.mode}): +${ledgerResult?.added?.length || 0} added, ${ledgerResult?.upvoted?.length || 0} upvoted, ${ledgerResult?.pruned?.length || 0} pruned.`;
1605
+ return { exitCode: res.ok ? 0 : 1, output: msg, data: res };
1606
+ }
1607
+
1608
+ if (action === 'promote' || action === 'prune') {
1609
+ const slug = args[2] && !args[2].startsWith('-') ? args[2] : (options.slug || '');
1610
+ if (!slug) {
1611
+ const errRes = { ok: false, error: `Missing <slug> for rsl ${action}` };
1612
+ return {
1613
+ exitCode: 1,
1614
+ output: isJson ? JSON.stringify(errRes, null, 2) : `[Highbeam RSL] ERROR: ${errRes.error}`,
1615
+ data: errRes
1616
+ };
1617
+ }
1618
+ const res = action === 'promote'
1619
+ ? promoteHeuristic(wsRoot, slug, options)
1620
+ : pruneHeuristic(wsRoot, slug, options);
1621
+ if (isJson) {
1622
+ return { exitCode: res.ok ? 0 : 1, output: JSON.stringify(res, null, 2), data: res };
1623
+ }
1624
+ return {
1625
+ exitCode: res.ok ? 0 : 1,
1626
+ output: res.ok
1627
+ ? `[Highbeam RSL] ${action === 'promote' ? 'Promoted' : 'Pruned'} heuristic "${res.slug}" across .agents/ and .claude/`
1628
+ : `[Highbeam RSL] ERROR: ${res.error}`,
1629
+ data: res
1630
+ };
1631
+ }
1632
+
1633
+ const helpRsl = 'Usage: ctxtop rsl <status|list|run|promote <slug>|prune <slug>> [--platform all|antigravity|claude] [--mode local|sdk] [--json]';
1634
+ return {
1635
+ exitCode: 1,
1636
+ output: isJson ? JSON.stringify({ ok: false, error: `Unknown rsl action: ${action}` }, null, 2) : helpRsl,
1637
+ data: { ok: false }
1638
+ };
1639
+ }
1640
+
1641
+ if (subcommand === 'shield' || subcommand === 'status') {
1642
+ const platIdx = args.indexOf('--platform');
1643
+ const platform =
1644
+ platIdx !== -1 && args[platIdx + 1]
1645
+ ? String(args[platIdx + 1]).toLowerCase()
1646
+ : (options.platform || 'all');
1647
+ const linesIdx = args.indexOf('--max-lines');
1648
+ const maxUnslicedLines =
1649
+ linesIdx !== -1 && args[linesIdx + 1] ? Number(args[linesIdx + 1]) : options.maxUnslicedLines;
1650
+
1651
+ let action = 'status';
1652
+ if (subcommand === 'shield') {
1653
+ if (args.includes('--enable') || args[1] === 'enable') action = 'enable';
1654
+ else if (args.includes('--disable') || args[1] === 'disable') action = 'disable';
1655
+ else action = 'status';
1656
+ }
1657
+
1658
+ const res =
1659
+ subcommand === 'status'
1660
+ ? { ok: true, action: 'status', platform, ...getShieldStatus({ ...options }) }
1661
+ : configureShield({
1662
+ ...options,
1663
+ action,
1664
+ platform,
1665
+ ...(maxUnslicedLines ? { maxUnslicedLines } : {})
1666
+ });
1667
+
1668
+ if (isJson) {
1669
+ return { exitCode: res.ok === false ? 1 : 0, output: JSON.stringify(res, null, 2), data: res };
1670
+ }
1671
+ const lines = [
1672
+ `[Highbeam Shield] Status: ${res.enabled ? 'ACTIVE' : 'PASSIVE'} (action=${res.action}, platform=${platform})`,
1673
+ ` Targets : Antigravity=${res.platforms.antigravity ? 'ON' : 'OFF'} (hooks=${res.hooksConfigured.antigravity}) | Claude=${res.platforms.claude ? 'ON' : 'OFF'} (hooks=${res.hooksConfigured.claude})`,
1674
+ ` Read Threshold: >${res.maxUnslicedLines} lines default | >${res.cliffMaxUnslicedLines} lines near pricing cliff`,
1675
+ ` Session ROI : +${res.roi.tokensSaved.toLocaleString('en-US')} tok saved ($${res.roi.dollarsSaved.toFixed(2)} USD) | ${res.roi.readsBlocked} oversized reads indexed`,
1676
+ ...(res.selfTest ? [` Self-Test : ${res.selfTest.detail}`] : [])
1677
+ ];
1678
+ return { exitCode: res.ok === false ? 1 : 0, output: lines.join('\n'), data: res };
1679
+ }
1680
+
1681
+ if (subcommand === 'handoff') {
1682
+ const readFlag = (flag, fallback) => {
1683
+ const idx = args.indexOf(flag);
1684
+ return idx !== -1 && args[idx + 1] ? String(args[idx + 1]) : fallback;
1685
+ };
1686
+ const wsRoot = path.resolve(readFlag('--cwd', options.cwd || process.cwd()));
1687
+ const sessionId = readFlag('--session', options.sessionId || '');
1688
+ const result = buildConsolidatedSpecMarkdown(wsRoot, { sessionId });
1689
+ let outputPath = null;
1690
+ if (args.includes('--write') || Boolean(options.write)) {
1691
+ outputPath = path.join(wsRoot, '.agents', 'telemetry', 'CONSOLIDATED_SPEC.md');
1692
+ writeTextAtomic(outputPath, `${result.consolidatedMarkdown}\n`);
1693
+ }
1694
+ const payload = { ...result, ...(outputPath ? { outputPath } : {}) };
1695
+ return {
1696
+ exitCode: 0,
1697
+ output: isJson ? JSON.stringify(payload, null, 2) : payload.consolidatedMarkdown,
1698
+ data: payload
1699
+ };
1700
+ }
1701
+
1702
+ if (args.includes('--demo') || args.includes('--demo-animate') || args.includes('--roast') || args.includes('--serve')) {
1703
+ return runLiveOrDemoCli(options);
1704
+ }
1705
+
1706
+ const knownSubcommands = new Set([
1707
+ 'init', 'install', 'uninstall', 'config', 'cost-radar', 'radar', 'panel',
1708
+ 'receipt', 'doctor', 'statusline', 'inspect', 'control', 'postmortem',
1709
+ 'audit', 'shield', 'status', 'rsl', 'handoff',
1710
+ 'license', 'pro', 'roast',
1711
+ '--help', '-h', 'help', '--version', '-v', 'version'
1712
+ ]);
1713
+ const hasHelp = args.length === 0 || args.includes('--help') || args.includes('-h') || subcommand === 'help';
1714
+ const isUnknown = !hasHelp && args.length > 0 && !knownSubcommands.has(subcommand);
1715
+
1716
+ const helpText = [
1717
+ 'Usage: ctxtop <command> [options]',
1718
+ 'Commands:',
1719
+ ' init [--antigravity | --claude | --all | --workspace | --dry-run] Zero-config dual-host installer',
1720
+ ' audit [--platform all|antigravity|claude] [--days 7] [--json] Zero-write historical Sludge Tax & ROI audit',
1721
+ ' shield <--enable | --disable | --status> [--platform all|...] Toggle Active Context Shield & read-index guard',
1722
+ ' rsl <status|list|run|promote|prune> [--platform ...] [--json] Dual-platform RSL post-mortem & rule ledger',
1723
+ ' handoff [--consolidate] [--session <id>] [--write] [--json] Consolidate sharded spec constraints & diff',
1724
+ ' status [--platform all|antigravity|claude] [--json] Show Shield & Session ROI status',
1725
+ ' install [--global | --project] Merge Claude Code hooks & statusLine',
1726
+ ' uninstall [--global | --project] Remove Highbeam hooks',
1727
+ ' doctor [--diagnostic | --json] Verify contracts or emit zero-PII report',
1728
+ ' postmortem [--last N] [--json] [--demo] Analyze transcript forensics & rot',
1729
+ ' receipt [--advanced | --markdown | --json] Print Simple View or Git-Commit Receipt',
1730
+ ' panel [--advanced] [--out <file.html>] Write zero-socket Claude Code HTML HUD',
1731
+ ' radar [--out <file.html>] [--json] [--demo] Write SVG KV-cache retention radar timeline',
1732
+ ' cost-radar [--out <file.html>] [--json] (Alias for radar)',
1733
+ ' statusline [--demo] [--columns N] Responsive single-line statusline bridge',
1734
+ ' config [list | set <DET-ID> <mode> | reset] Configure per-detector overrides',
1735
+ ' inspect [<session-id> | --last] [--out <file.json>] Inspect session trajectory',
1736
+ ' control <pause|resume|step|abort|rewind|status> Execution control plane command'
1737
+ ].join('\n');
1738
+ return { exitCode: isUnknown ? 1 : 0, output: helpText, data: { help: true, isUnknown } };
1739
+ }
1740
+
1741
+ export function isCliMain(
1742
+ argv1 = globalThis.process?.argv?.[1],
1743
+ metaUrl = import.meta.url,
1744
+ fsImpl = fs
1745
+ ) {
1746
+ if (!argv1 || !metaUrl) return false;
1747
+ try {
1748
+ return fsImpl.realpathSync(argv1) === fsImpl.realpathSync(url.fileURLToPath(metaUrl));
1749
+ } catch {
1750
+ try {
1751
+ return path.resolve(String(argv1)) === path.resolve(url.fileURLToPath(metaUrl));
1752
+ } catch {
1753
+ return false;
1754
+ }
1755
+ }
1756
+ }
1757
+
1758
+ export function main(args = globalThis.process?.argv?.slice(2) || []) {
1759
+ const result = runCli(args);
1760
+ if (result && typeof result.then === 'function') {
1761
+ return result.then((res) => {
1762
+ if (res?.output) globalThis.process?.stdout?.write?.(`${res.output}\n`);
1763
+ if (res?.exitCode !== undefined && res?.exitCode !== 0 && globalThis.process?.exit) {
1764
+ globalThis.process.exit(res.exitCode);
1765
+ }
1766
+ return res;
1767
+ });
1768
+ }
1769
+ if (result?.output) globalThis.process?.stdout?.write?.(`${result.output}\n`);
1770
+ if (result?.exitCode !== undefined && result?.exitCode !== 0 && globalThis.process?.exit) {
1771
+ globalThis.process.exit(result.exitCode);
1772
+ }
1773
+ return result;
1774
+ }
1775
+
1776
+ if (isCliMain()) {
1777
+ main();
1778
+ }
1779
+
1780
+ export default {
1781
+ PKG_ROOT,
1782
+ CANONICAL_AH_HOOKS,
1783
+ PRE_TOOL_USE_MATCHER,
1784
+ POST_TOOL_USE_MATCHER,
1785
+ isAttentionHorizonHookEntry,
1786
+ resolveSettingsPath,
1787
+ ensureGitExcludeEntries,
1788
+ installAttentionHorizon,
1789
+ uninstallAttentionHorizon,
1790
+ inspectHookDiagnostics,
1791
+ runDoctorDiagnostics,
1792
+ generateReceiptReport,
1793
+ generateHorizonPanel,
1794
+ generateCostRadar,
1795
+ executeInitSubcommand,
1796
+ runCli,
1797
+ isCliMain,
1798
+ main
1799
+ };