ctxtop 4.0.0 → 4.1.1

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 (357) hide show
  1. package/.antigravity-plugin/plugin.json +1 -1
  2. package/.claude-plugin/plugin.json +21 -18
  3. package/CHECKSUMS.sha256 +81 -57
  4. package/LICENSE +27 -27
  5. package/README.md +385 -330
  6. package/SECURITY.md +7 -1
  7. package/assets/hero-demo.svg +1 -1
  8. package/bin/ah-statusline.mjs +30 -0
  9. package/bin/ctxtop.mjs +587 -49
  10. package/config/default_flightcheck.json +19 -0
  11. package/config/modelCatalog.json +952 -213
  12. package/hooks/handlers/compact-lifecycle.mjs +323 -8
  13. package/hooks/handlers/config-change.mjs +402 -0
  14. package/hooks/handlers/hookIo.mjs +56 -0
  15. package/hooks/handlers/hookIpcClient.mjs +8 -4
  16. package/hooks/handlers/post-model-switch.mjs +148 -0
  17. package/hooks/handlers/post-tool-use-core.mjs +394 -0
  18. package/hooks/handlers/post-tool-use.mjs +54 -220
  19. package/hooks/handlers/pre-model-switch.mjs +933 -24
  20. package/hooks/handlers/pre-tool-use-core.mjs +680 -0
  21. package/hooks/handlers/pre-tool-use.mjs +61 -304
  22. package/hooks/handlers/stop-gate.mjs +310 -12
  23. package/hooks/handlers/user-prompt-submit.mjs +334 -1
  24. package/hooks/hooks.json +50 -0
  25. package/hooks/post_tool_use.mjs +24 -3
  26. package/hooks/pre_tool_use.mjs +84 -54
  27. package/hooks/register.js +48 -9
  28. package/hooks/session_start.mjs +11 -1
  29. package/hooks/stop.mjs +11 -1
  30. package/hooks.json +56 -56
  31. package/package.json +12 -4
  32. package/packages/antigravity/package.json +10 -3
  33. package/packages/antigravity/src/adapter.mjs +109 -0
  34. package/packages/antigravity/src/index.mjs +7 -1
  35. package/packages/claude-code/package.json +10 -3
  36. package/packages/claude-code/src/adapter.mjs +194 -0
  37. package/packages/claude-code/src/index.mjs +8 -2
  38. package/packages/claude-code/src/register.js +726 -0
  39. package/packages/core/package.json +6 -2
  40. package/packages/core/src/catalog/detectorCatalog.mjs +558 -0
  41. package/packages/core/src/catalog/index.mjs +1 -0
  42. package/packages/core/src/catalog/safeguardGuide.mjs +412 -0
  43. package/packages/core/src/coach/cacheGravityRouter.mjs +1547 -0
  44. package/packages/core/src/coach/effortShiftDetector.mjs +316 -0
  45. package/packages/core/src/coach/microSkills.mjs +1 -0
  46. package/packages/core/src/coach/promptHygieneGovernor.mjs +1 -0
  47. package/packages/core/src/coach/repoCalibration.mjs +254 -0
  48. package/packages/core/src/coach/resumeToolsetAuditor.mjs +321 -0
  49. package/packages/core/src/coach/savedQuotaLedger.mjs +527 -0
  50. package/packages/core/src/coach/smartCompactAdvisor.mjs +339 -0
  51. package/packages/core/src/coach/stateBatonHydrator.mjs +810 -0
  52. package/packages/core/src/coach/ttlWatchdog.mjs +464 -0
  53. package/packages/core/src/config/anthropicModelCatalog.json +607 -0
  54. package/packages/core/src/config/catalogLoader.mjs +1271 -0
  55. package/packages/core/src/config/horizonConfig.mjs +1055 -0
  56. package/packages/core/src/control/callTree.mjs +338 -0
  57. package/packages/core/src/control/coachLatches.mjs +126 -0
  58. package/packages/core/src/control/controlStateMachine.mjs +205 -0
  59. package/packages/core/src/control/index.mjs +49 -0
  60. package/packages/core/src/control/swarmWorktree.mjs +109 -0
  61. package/packages/core/src/control/toolSuspension.mjs +197 -0
  62. package/packages/core/src/diagnostics/drift_guard.mjs +382 -0
  63. package/packages/core/src/diagnostics/index.mjs +9 -0
  64. package/packages/core/src/diagnostics/micro_skills.mjs +471 -0
  65. package/packages/core/src/diagnostics/prompt_hygiene_governor.mjs +888 -0
  66. package/packages/core/src/economics/billingBlocks.mjs +251 -0
  67. package/packages/core/src/economics/cacheGravity.mjs +371 -0
  68. package/packages/core/src/economics/cliffBreaker.mjs +256 -0
  69. package/packages/core/src/economics/driftLatency.mjs +433 -0
  70. package/packages/core/src/economics/dualTtl.mjs +198 -0
  71. package/packages/core/src/economics/index.mjs +47 -0
  72. package/packages/core/src/economics/retentionRadar.mjs +348 -0
  73. package/packages/core/src/economics/shadowAutoModel.mjs +228 -0
  74. package/packages/core/src/guards/bucketBAlphaBeta.mjs +860 -0
  75. package/packages/core/src/guards/bucketBGamma.mjs +442 -0
  76. package/packages/core/src/guards/bucketBHeuristics.mjs +37 -0
  77. package/packages/core/src/guards/circuitBreakers.mjs +1202 -0
  78. package/packages/core/src/guards/det01_03_shell_secret.mjs +1184 -0
  79. package/packages/core/src/guards/det04_12_thrash_rot.mjs +572 -0
  80. package/packages/core/src/guards/det13_20_mcp_scope.mjs +913 -0
  81. package/packages/core/src/guards/docIndexCore.mjs +446 -0
  82. package/packages/core/src/guards/losslessPostSanitizer.mjs +317 -0
  83. package/packages/core/src/guards/slopsquatGate.mjs +551 -0
  84. package/packages/core/src/index.js +27 -0
  85. package/packages/core/src/index.mjs +25 -1
  86. package/packages/core/src/telemetry/otelExporter.mjs +187 -0
  87. package/packages/core/src/telemetry/scopeLockRegistry.mjs +522 -0
  88. package/packages/core/src/telemetry/sprintMetrics.mjs +327 -0
  89. package/packages/core/src/telemetry/swarmTopology.mjs +152 -0
  90. package/packages/core/src/telemetry/telemetryBridge.mjs +1232 -0
  91. package/packages/core/src/ui/brailleSparkline.mjs +142 -0
  92. package/packages/core/src/ui/costRadarSvg.mjs +276 -0
  93. package/packages/core/src/ui/horizonGrid.mjs +475 -0
  94. package/packages/core/src/ui/horizonPanelHtml.mjs +1502 -0
  95. package/packages/core/src/ui/modViews.mjs +1558 -0
  96. package/packages/core/src/ui/pdfReceiptGenerator.mjs +329 -0
  97. package/packages/core/src/ustf/index.mjs +7 -0
  98. package/packages/core/src/ustf/normalizer.mjs +512 -0
  99. package/packages/core/src/ustf/schema.mjs +186 -0
  100. package/packages/core/src/utils/runtime.mjs +962 -0
  101. package/packages/engine-node/package.json +6 -2
  102. package/packages/engine-node/src/db/index.mjs +58 -0
  103. package/packages/engine-node/src/db/jsonl_fallback.mjs +184 -0
  104. package/packages/engine-node/src/db/probe.mjs +342 -0
  105. package/packages/engine-node/src/db/sqlite_wrapper.mjs +122 -0
  106. package/packages/engine-node/src/index.mjs +11 -1
  107. package/packages/engine-node/src/ipc/client.mjs +447 -0
  108. package/packages/engine-node/src/ipc/fast_client.mjs +191 -0
  109. package/packages/engine-node/src/ipc/index.mjs +24 -0
  110. package/packages/engine-node/src/ipc/protocol.mjs +177 -0
  111. package/packages/engine-node/src/ipc/server.mjs +445 -0
  112. package/packages/engine-node/src/multi_host_mcp.mjs +168 -0
  113. package/packages/engine-node/src/offloader/index.mjs +6 -0
  114. package/packages/engine-node/src/offloader/tool_offloader.mjs +241 -0
  115. package/packages/engine-node/src/rsl/index.mjs +3 -0
  116. package/packages/engine-node/src/sensors/blindspots.mjs +376 -0
  117. package/packages/engine-node/src/sensors/git_merge_tree.mjs +223 -0
  118. package/packages/engine-node/src/sensors/index.mjs +7 -0
  119. package/packages/engine-node/src/vendor/config/default_flightcheck.json +133 -0
  120. package/packages/engine-node/src/vendor/config/modelCatalog.json +1359 -0
  121. package/packages/engine-node/src/vendor/config/platformQuirks.json +19 -0
  122. package/packages/engine-node/src/vendor/core/atomic_io.mjs +124 -0
  123. package/packages/engine-node/src/vendor/core/constants.mjs +2150 -0
  124. package/packages/engine-node/src/vendor/core/doc_indexer.mjs +338 -0
  125. package/packages/engine-node/src/vendor/core/rsl_clash_auditor.mjs +423 -0
  126. package/packages/engine-node/src/vendor/core/rsl_distiller.mjs +394 -0
  127. package/packages/engine-node/src/vendor/core/rsl_ledger.mjs +1029 -0
  128. package/packages/engine-node/src/vendor/core/rsl_triage.mjs +1051 -0
  129. package/packages/engine-node/src/vendor/core/shield_manager.mjs +1417 -0
  130. package/packages/engine-node/src/vendor/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  131. package/packages/engine-node/src/vendor/core-isomorphic/catalog/index.mjs +1 -0
  132. package/packages/engine-node/src/vendor/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
  133. package/packages/engine-node/src/vendor/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  134. package/packages/engine-node/src/vendor/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
  135. package/packages/engine-node/src/vendor/core-isomorphic/coach/microSkills.mjs +1 -0
  136. package/packages/engine-node/src/vendor/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  137. package/packages/engine-node/src/vendor/core-isomorphic/coach/repoCalibration.mjs +254 -0
  138. package/packages/engine-node/src/vendor/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  139. package/packages/engine-node/src/vendor/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  140. package/packages/engine-node/src/vendor/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
  141. package/packages/engine-node/src/vendor/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  142. package/packages/engine-node/src/vendor/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  143. package/packages/engine-node/src/vendor/core-isomorphic/config/anthropicModelCatalog.json +607 -0
  144. package/packages/engine-node/src/vendor/core-isomorphic/config/catalogLoader.mjs +1271 -0
  145. package/packages/engine-node/src/vendor/core-isomorphic/config/horizonConfig.mjs +1055 -0
  146. package/packages/engine-node/src/vendor/core-isomorphic/control/callTree.mjs +338 -0
  147. package/packages/engine-node/src/vendor/core-isomorphic/control/coachLatches.mjs +126 -0
  148. package/packages/engine-node/src/vendor/core-isomorphic/control/controlStateMachine.mjs +205 -0
  149. package/packages/engine-node/src/vendor/core-isomorphic/control/index.mjs +49 -0
  150. package/packages/engine-node/src/vendor/core-isomorphic/control/swarmWorktree.mjs +109 -0
  151. package/packages/engine-node/src/vendor/core-isomorphic/control/toolSuspension.mjs +197 -0
  152. package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  153. package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/index.mjs +9 -0
  154. package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  155. package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  156. package/packages/engine-node/src/vendor/core-isomorphic/economics/billingBlocks.mjs +251 -0
  157. package/packages/engine-node/src/vendor/core-isomorphic/economics/cacheGravity.mjs +371 -0
  158. package/packages/engine-node/src/vendor/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  159. package/packages/engine-node/src/vendor/core-isomorphic/economics/driftLatency.mjs +433 -0
  160. package/packages/engine-node/src/vendor/core-isomorphic/economics/dualTtl.mjs +198 -0
  161. package/packages/engine-node/src/vendor/core-isomorphic/economics/index.mjs +47 -0
  162. package/packages/engine-node/src/vendor/core-isomorphic/economics/retentionRadar.mjs +348 -0
  163. package/packages/engine-node/src/vendor/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
  164. package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  165. package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  166. package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  167. package/packages/engine-node/src/vendor/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  168. package/packages/engine-node/src/vendor/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  169. package/packages/engine-node/src/vendor/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  170. package/packages/engine-node/src/vendor/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  171. package/packages/engine-node/src/vendor/core-isomorphic/guards/docIndexCore.mjs +446 -0
  172. package/packages/engine-node/src/vendor/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  173. package/packages/engine-node/src/vendor/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  174. package/packages/engine-node/src/vendor/core-isomorphic/index.js +27 -0
  175. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  176. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  177. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  178. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  179. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/telemetryBridge.mjs +1232 -0
  180. package/packages/engine-node/src/vendor/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  181. package/packages/engine-node/src/vendor/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  182. package/packages/engine-node/src/vendor/core-isomorphic/ui/horizonGrid.mjs +475 -0
  183. package/packages/engine-node/src/vendor/core-isomorphic/ui/horizonPanelHtml.mjs +1502 -0
  184. package/packages/engine-node/src/vendor/core-isomorphic/ui/modViews.mjs +1558 -0
  185. package/packages/engine-node/src/vendor/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  186. package/packages/engine-node/src/vendor/core-isomorphic/ustf/index.mjs +7 -0
  187. package/packages/engine-node/src/vendor/core-isomorphic/ustf/normalizer.mjs +512 -0
  188. package/packages/engine-node/src/vendor/core-isomorphic/ustf/schema.mjs +186 -0
  189. package/packages/engine-node/src/vendor/core-isomorphic/utils/runtime.mjs +962 -0
  190. package/packages/mcp/package.json +7 -3
  191. package/packages/mcp/src/server.mjs +115 -14
  192. package/packages/mcp/src/vendor/config/default_flightcheck.json +133 -0
  193. package/packages/mcp/src/vendor/config/modelCatalog.json +1359 -0
  194. package/packages/mcp/src/vendor/config/platformQuirks.json +19 -0
  195. package/packages/mcp/src/vendor/core/atomic_io.mjs +124 -0
  196. package/packages/mcp/src/vendor/core/coach/saved_quota_ledger.mjs +615 -0
  197. package/packages/mcp/src/vendor/core/constants.mjs +2150 -0
  198. package/packages/mcp/src/vendor/core/doc_indexer.mjs +338 -0
  199. package/packages/mcp/src/vendor/core/fts5_output_compressor.mjs +596 -0
  200. package/packages/mcp/src/vendor/core/hook_diagnostics.mjs +158 -0
  201. package/packages/mcp/src/vendor/core/paths.mjs +311 -0
  202. package/packages/mcp/src/vendor/core/session_auditor.mjs +1109 -0
  203. package/packages/mcp/src/vendor/core/sqlite_client.mjs +289 -0
  204. package/packages/mcp/src/vendor/core/telemetry/scope_lock_registry.mjs +578 -0
  205. package/packages/mcp/src/vendor/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  206. package/packages/mcp/src/vendor/core-isomorphic/catalog/index.mjs +1 -0
  207. package/packages/mcp/src/vendor/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
  208. package/packages/mcp/src/vendor/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  209. package/packages/mcp/src/vendor/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
  210. package/packages/mcp/src/vendor/core-isomorphic/coach/microSkills.mjs +1 -0
  211. package/packages/mcp/src/vendor/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  212. package/packages/mcp/src/vendor/core-isomorphic/coach/repoCalibration.mjs +254 -0
  213. package/packages/mcp/src/vendor/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  214. package/packages/mcp/src/vendor/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  215. package/packages/mcp/src/vendor/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
  216. package/packages/mcp/src/vendor/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  217. package/packages/mcp/src/vendor/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  218. package/packages/mcp/src/vendor/core-isomorphic/config/anthropicModelCatalog.json +607 -0
  219. package/packages/mcp/src/vendor/core-isomorphic/config/catalogLoader.mjs +1271 -0
  220. package/packages/mcp/src/vendor/core-isomorphic/config/horizonConfig.mjs +1055 -0
  221. package/packages/mcp/src/vendor/core-isomorphic/control/callTree.mjs +338 -0
  222. package/packages/mcp/src/vendor/core-isomorphic/control/coachLatches.mjs +126 -0
  223. package/packages/mcp/src/vendor/core-isomorphic/control/controlStateMachine.mjs +205 -0
  224. package/packages/mcp/src/vendor/core-isomorphic/control/index.mjs +49 -0
  225. package/packages/mcp/src/vendor/core-isomorphic/control/swarmWorktree.mjs +109 -0
  226. package/packages/mcp/src/vendor/core-isomorphic/control/toolSuspension.mjs +197 -0
  227. package/packages/mcp/src/vendor/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  228. package/packages/mcp/src/vendor/core-isomorphic/diagnostics/index.mjs +9 -0
  229. package/packages/mcp/src/vendor/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  230. package/packages/mcp/src/vendor/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  231. package/packages/mcp/src/vendor/core-isomorphic/economics/billingBlocks.mjs +251 -0
  232. package/packages/mcp/src/vendor/core-isomorphic/economics/cacheGravity.mjs +371 -0
  233. package/packages/mcp/src/vendor/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  234. package/packages/mcp/src/vendor/core-isomorphic/economics/driftLatency.mjs +433 -0
  235. package/packages/mcp/src/vendor/core-isomorphic/economics/dualTtl.mjs +198 -0
  236. package/packages/mcp/src/vendor/core-isomorphic/economics/index.mjs +47 -0
  237. package/packages/mcp/src/vendor/core-isomorphic/economics/retentionRadar.mjs +348 -0
  238. package/packages/mcp/src/vendor/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
  239. package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  240. package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  241. package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  242. package/packages/mcp/src/vendor/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  243. package/packages/mcp/src/vendor/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  244. package/packages/mcp/src/vendor/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  245. package/packages/mcp/src/vendor/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  246. package/packages/mcp/src/vendor/core-isomorphic/guards/docIndexCore.mjs +446 -0
  247. package/packages/mcp/src/vendor/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  248. package/packages/mcp/src/vendor/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  249. package/packages/mcp/src/vendor/core-isomorphic/index.js +27 -0
  250. package/packages/mcp/src/vendor/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  251. package/packages/mcp/src/vendor/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  252. package/packages/mcp/src/vendor/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  253. package/packages/mcp/src/vendor/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  254. package/packages/mcp/src/vendor/core-isomorphic/telemetry/telemetryBridge.mjs +1232 -0
  255. package/packages/mcp/src/vendor/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  256. package/packages/mcp/src/vendor/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  257. package/packages/mcp/src/vendor/core-isomorphic/ui/horizonGrid.mjs +475 -0
  258. package/packages/mcp/src/vendor/core-isomorphic/ui/horizonPanelHtml.mjs +1502 -0
  259. package/packages/mcp/src/vendor/core-isomorphic/ui/modViews.mjs +1558 -0
  260. package/packages/mcp/src/vendor/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  261. package/packages/mcp/src/vendor/core-isomorphic/ustf/index.mjs +7 -0
  262. package/packages/mcp/src/vendor/core-isomorphic/ustf/normalizer.mjs +512 -0
  263. package/packages/mcp/src/vendor/core-isomorphic/ustf/schema.mjs +186 -0
  264. package/packages/mcp/src/vendor/core-isomorphic/utils/runtime.mjs +962 -0
  265. package/packages/mcp/src/vendor/engine-node/db/probe.mjs +342 -0
  266. package/packages/mcp/src/vendor/pro/pro_license.mjs +547 -0
  267. package/packages/pro/package.json +23 -16
  268. package/packages/pro/src/index.mjs +9 -3
  269. package/packages/pro/src/pro_license.mjs +547 -0
  270. package/packages/pro/src/team_finops_pack.mjs +241 -241
  271. package/packages/pro/workers/polar_webhook_worker.mjs +219 -215
  272. package/plugin.json +1 -1
  273. package/sidecars/horizon-daemon/server.mjs +514 -40
  274. package/skills/handoff/SKILL.md +8 -0
  275. package/src/adapters/antigravity/index.mjs +31 -1
  276. package/src/adapters/claude-code/index.mjs +40 -1
  277. package/src/cli/doctor.mjs +11 -2
  278. package/src/cli/horizon_hud.mjs +283 -65
  279. package/src/cli/init.mjs +46 -13
  280. package/src/config/modelCatalog.json +952 -213
  281. package/src/core/bucket_b_runtime.mjs +1200 -0
  282. package/src/core/classifier.mjs +25 -11
  283. package/src/core/coach/circuit_breakers.mjs +84 -6
  284. package/src/core/coach/task_quota_router.mjs +8 -0
  285. package/src/core/code_fold_lite.mjs +169 -0
  286. package/src/core/config.mjs +44 -0
  287. package/src/core/constants.mjs +365 -15
  288. package/src/core/detectors_det01_to_16.mjs +98 -8
  289. package/src/core/doc_indexer.mjs +338 -0
  290. package/src/core/fts5_output_compressor.mjs +272 -35
  291. package/src/core/horizon_config.mjs +42 -0
  292. package/src/core/layer5_hygiene.mjs +118 -0
  293. package/src/core/parser.mjs +88 -12
  294. package/src/core/paths.mjs +3 -2
  295. package/src/core/pro_license.mjs +174 -12
  296. package/src/core/pruner.mjs +7 -146
  297. package/src/core/quota.mjs +14 -2
  298. package/src/core/rsl_clash_auditor.mjs +423 -0
  299. package/src/core/rsl_distiller.mjs +394 -0
  300. package/src/core/rsl_ledger.mjs +1029 -0
  301. package/src/core/rsl_triage.mjs +1051 -0
  302. package/src/core/session_auditor.mjs +1109 -0
  303. package/src/core/shadow_auto_ledger.mjs +205 -0
  304. package/src/core/shield_manager.mjs +1417 -0
  305. package/src/core/sqlite_client.mjs +10 -4
  306. package/src/core/subagents.mjs +18 -2
  307. package/src/core/task_quota_router.mjs +62 -5
  308. package/src/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
  309. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
  310. package/src/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
  311. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  312. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
  313. package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
  314. package/src/core-isomorphic/config/anthropicModelCatalog.json +405 -1
  315. package/src/core-isomorphic/config/catalogLoader.mjs +549 -46
  316. package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
  317. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
  318. package/src/core-isomorphic/economics/cacheGravity.mjs +21 -1
  319. package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
  320. package/src/core-isomorphic/economics/driftLatency.mjs +114 -0
  321. package/src/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
  322. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  323. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  324. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  325. package/src/core-isomorphic/guards/circuitBreakers.mjs +191 -191
  326. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
  327. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
  328. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
  329. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  330. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
  331. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  332. package/src/core-isomorphic/index.js +1 -0
  333. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +113 -13
  334. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +684 -363
  335. package/src/core-isomorphic/ui/modViews.mjs +95 -15
  336. package/src/diagnostics/claudeHookCapabilities.mjs +426 -0
  337. package/src/diagnostics/doctorEngine.mjs +122 -4
  338. package/src/engine-node/db/probe.mjs +234 -2
  339. package/src/engine-node/index.mjs +3 -0
  340. package/src/engine-node/ipc/fast_client.mjs +191 -0
  341. package/src/engine-node/ipc/index.mjs +2 -0
  342. package/src/engine-node/multi_host_mcp.mjs +168 -0
  343. package/src/engine-node/sensors/blindspots.mjs +13 -6
  344. package/src/hooks/antigravity_rsl_hook.mjs +272 -0
  345. package/src/hooks/claude_rsl_hook.mjs +308 -0
  346. package/src/hooks/daemon_hook_bridge.mjs +256 -0
  347. package/src/hooks/fast_hook_ipc.mjs +295 -0
  348. package/src/hooks/post_invocation.mjs +37 -405
  349. package/src/hooks/post_invocation_core.mjs +623 -0
  350. package/src/hooks/pre_invocation.mjs +103 -958
  351. package/src/hooks/pre_invocation_core.mjs +1830 -0
  352. package/src/hooks/session_start.mjs +39 -1
  353. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  354. package/src/utils/sessionCalibration.mjs +704 -0
  355. package/src/webview/advanced_view.html +34 -18
  356. package/src/webview/horizon_panel.html +4191 -625
  357. package/src/webview/simple_view.html +1 -1
package/README.md CHANGED
@@ -1,330 +1,385 @@
1
- <div align="center">
2
-
3
- # Highbeam (ctxtop v4.0) — Active Context Surgeon, KV-Cache Shield & Token FinOps for Claude Code & Google Antigravity
4
-
5
- **Local Context Window Profiler, KV-Cache TTL Monitor & Deterministic PreInvocation / PreToolUse Surgeon (`~0.18ms` Tier-1 In-Process / `~25–90ms` Tier-2 CLI Hook) for Claude Code & Google Antigravity**
6
-
7
- [![Zero Runtime Dependencies](https://img.shields.io/badge/dependencies-0_runtime-brightgreen.svg)](#systems-architecture--zero-trust-security)
8
- [![Hook Latency](https://img.shields.io/badge/Tier--1_in--process-~0.18ms_p95_%7C_Tier--2_CLI_hook-~25--90ms-00e5ff.svg)](#deterministic-preinvocation-router--6-local-sensors)
9
- [![Node.js >= 20](https://img.shields.io/badge/node-%3E%3D20_zero_deps-339933.svg)](#quick-start)
10
- [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
11
- [![Claude Code & Antigravity](https://img.shields.io/badge/Hosts-Claude_Code_%2B_Google_Antigravity-blueviolet.svg)](#-installation--quick-start)
12
-
13
- [**Live Interactive Demo**](https://gizzant.github.io/attention-horizon-antigravity/) • [**Quick Start**](#-installation--quick-start) • [**Cookbook & Recipes**](docs/COOKBOOK.md) • [**Systems Architecture**](#systems-architecture--zero-trust-security)
14
-
15
- <br/>
16
-
17
- <img src="assets/hero-demo.svg" alt="Highbeam 40-Cell ANSI HUD & PreInvocation Router" width="100%" />
18
-
19
- </div>
20
-
21
- ---
22
-
23
- ## ⚡ Installation & Quick Start
24
-
25
- | **Google Antigravity** *(1-Line Install)* | **Claude Code** *(1-Line Install)* |
26
- | :--- | :--- |
27
- | ```bash
28
- npx ctxtop init
29
- ``` | ```bash
30
- npx ctxtop install --claude
31
- ``` |
32
- | *Workspace-only*: `npx ctxtop init --workspace`<br/>*Health check*: `npx ctxtop doctor` | *StatusLine HUD*: `npx ah-statusline --demo`<br/>*In-chat pane*: `/horizon` · `/cost-radar` · `/handoff` |
33
-
34
- ### Your First 5 Minutes After Installing
35
-
36
- #### 1. Google Antigravity Workflow
37
- 1. **Install hooks & sidecar**: Run `npx ctxtop init` in your project root (or globally).
38
- 2. **Open the Highbeam Sidepane**: Launch the local telemetry WebView (`npx ctxtop --serve` or via the Antigravity sidepane) to view real-time context health:
39
- - **Simple View (Default)**: 4 glanceable zones—**Zone A** (Safe Headroom & Warm KV Cache TTL), **Zone B** (`DO / AVOID / HOLD` Model & Effort switch guidance), **Zone C** (Live automated interventions), and **Zone D** (Verified tokens/USD saved + 1-click `/compact`).
40
- - **Advanced View (1-Click Toggle)**: Expands the **40-Cell Chrono-Positional Recall Grid** (`Primacy 0–30%`, `Mid-Trough 30–70%`, `Recency 70–100%`), top token consumer file table, `Off / Coach / Auto-Pilot` mode switcher, and the full `DET-01..32` guard log.
41
- 3. **Code normally**: Highbeam runs in **`COACH` mode** by default—automatically compressing verbose CLI test dumps via SQLite FTS5 and folding repeat file reads without interrupting your prompts.
42
-
43
- #### 2. Claude Code Workflow
44
- 1. **Install plugin & hooks**: Run `npx ctxtop install --claude` to wire `.claude-plugin/plugin.json`, `hooks/hooks.json`, and the live terminal `statusLine`.
45
- 2. **Watch the Live Terminal `statusLine`**: At the bottom of your terminal, Highbeam renders an auto-adapting (`80 / 110 / 144` col) telemetry bar:
46
- ```text
47
- AH [SCCCCCCC................] sonnet-5-5 64k/200k (32%) · Cache 88% (4m12s) · COACH · Saved $1.84
48
- ```
49
- 3. **Open the In-Chat Docked HUD**: Type `/horizon` in chat (or run `npx ah-claude panel` for the standalone HTML workbench) to inspect cache gravity, active guards, and reclaimable tokens.
50
-
51
- ---
52
-
53
- ## 🧭 Built-In Slash Skills & In-Chat Commands (Both Hosts)
54
-
55
- All 6 slash skills are registered identically in both **Google Antigravity** (`plugin.json`) and **Claude Code** (`.claude-plugin/plugin.json`):
56
-
57
- | Slash Command / Skill | When to Use It | What It Outputs |
58
- | :--- | :--- | :--- |
59
- | **`/horizon`** | Anytime during a coding session | Renders the live 40-cell Context Health HUD, KV-Cache TTL countdown, active `DO / AVOID / HOLD` guidance, and reclaimable clutter breakdown. |
60
- | **`/precheck`** | Before sending a complex refactor prompt or switching models | Audits prompt specificity (6-dimension rubric), checks algebraic KV-cache gravity (`C*`), and recommends the optimal Model & Effort tier. |
61
- | **`/handoff`** | Before running `/compact` or `/clear` at `>=75%` context fill | Distills active plan checkboxes, modified files, and unresolved `stderr` into a compressed `<1,000`-token checkpoint (`task.md` / `.handoff.md`). |
62
- | **`/cost-radar`** | When reviewing session token burn or cache busts | Generates an interactive HTML/SVG timeline of prefix-cache retention, `DET-30` thinking drift loops, and subagent worktree topology. |
63
- | **`/inspect`** | When diagnosing slow tools or subagent fan-out | Visualizes session trajectory call-tree spans, per-tool latencies, and token attribution as a standalone artifact. |
64
- | **`/evolve`** | After correcting agent mistakes across a session | Audits `AGENTS.md` / `CLAUDE.md` Turn-0 prefix budget (`<=20k` tok) and synthesizes validated session instincts via 1-click diff approval. |
65
-
66
- **Quick In-Chat Prompt Prefixes:**
67
- - `! <prompt>` — Bypass `PreInvocation` checks for a single turn.
68
- - `!lock <prompt>` — Freeze current reasoning effort tier and prefix state for the remainder of the session.
69
- - `#check <prompt>` — Force an explicit pre-flight scorecard and concrete prompt rewrite suggestion.
70
-
71
- ---
72
-
73
- ## 🛡️ Verified Token Receipt: `+164.0k` Tokens Saved in One 4-Step Coding Loop
74
-
75
- Most CLI trackers passively count tokens *after* your quota is already burned. Highbeam intercepts redundant reads, compresses noisy test dumps via local SQLite FTS5, and shields warm KV prefixes **before** they hit your billing meter:
76
-
77
- <div align="center">
78
- <img src="assets/zone_c_step3_shield_full.png" alt="Highbeam Zone C Active Protection & Verified Token Receipt (+164.0k tokens saved)" width="460" />
79
- </div>
80
-
81
- | Step in Coding Loop | Developer / Agent Action | Highbeam Active Intervention (Zone C) | Verified Savings |
82
- | :--- | :--- | :--- | :---: |
83
- | **1. Warm KV Cache + Repeat Read** | Agent re-reads an unmodified 800-line source file on a `100k` warm cache | **GUARD-4** intercepts the duplicate read (`AST signature stub`) and preserves the `95%` warm KV cache discount | **`+95.0k` tok** *(KV cache)*<br/>**`+800` tok** *(deduped read)* |
84
- | **2. Failing Test Suite Dump** | `npm test` dumps `120+` lines of verbose stdout (`~11.4k` tokens) | **SQLite FTS5 BM25 Compressor** indexes raw stdout locally and injects only the 160-token failing assertion digest | **`+11.2k` tok** |
85
- | **3. Mid-Session Rule Edit** | Agent updates `AGENTS.md` / `CLAUDE.md` while `60k` prefix is warm (`2m 55s` TTL left) | **PrefixCacheShield** queues the rule delta until TTL expiry or `/compact`, preventing a cold prefix rebuild | **`+57.0k` tok** |
86
- | **Total Verified Session Receipt** | **4-Step Feature / Bugfix Loop** | **Zero context dilution · 100% critical error retention** | **`+164.0k` tok (`~$0.33`)** |
87
-
88
- ---
89
-
90
- ## 💡 Why Saved Tokens Multiply (`O(N²)` Turn Compounding, Quota Life & Model IQ)
91
-
92
- In agentic coding, every turn re-sends the entire prior conversation history. A single `15,000`-token raw test dump on Turn 5 is not billed once—it is re-sent on Turns 6 through 25, burning **`300,000` cumulative tokens** (`15,000 × 20`).
93
-
94
- 1. **For Fixed-Subscription Users (`Claude Pro / Max`, `Antigravity OAuth Seats`) — Stop 2:00 PM Quota Lockouts & Context Rot**:
95
- - Compressing noisy tool outputs and duplicate file reads on early turns prevents `O(N²)` history compounding, **stretching 5-hour sprint quotas by `30%–50%`**.
96
- - Even more importantly, keeping your session below the **70% Safe Horizon** prevents **Context Rot** (middle-window attention decay where the model starts forgetting `AGENTS.md`/`CLAUDE.md` rules, hallucinating imports, and breaking working code).
97
- 2. **For Metered API & Enterprise Teams — Self-Expensing FinOps ROI**:
98
- - Preventing just two accidental warm-cache busts per day (switching models mid-TTL or editing rule files on a `100k` warm prefix) plus FTS5 log compression saves **`$3–$12/day` (`$60–$240/month`) per active seat**.
99
- 3. **Daily Cockpit Decisions No Human Can Calculate in Their Head (Zone B)**:
100
- - *"If I downshift from Opus/Argon to Sonnet/Flash right now, will I save quota or pay a 10x cold-prefill penalty?"* — Highbeam computes the algebraic cross-model break-even threshold (`C*`) in real time and displays a 1-line verdict: **`Model: Hold (03:34) — switching busts warm cache · Effort: OK to change`**.
101
-
102
- ---
103
-
104
- ## ⚙️ What Runs Automatically (Zero-Friction `COACH` Default)
105
-
106
- Highbeam defaults to **`COACH` mode**—performing lossless token surgery silently in the background while never blocking your chat prompt unless a true 3-strike identical failure loop or destructive git command occurs:
107
-
108
- | Automated Feature | How It Works Under the Hood | Developer Experience |
109
- | :--- | :--- | :--- |
110
- | **1. SQLite FTS5 CLI & Test Output Compression** (`PostToolUse`) | Strips ANSI/progress noise, indexes full stdout in local SQLite FTS5 (`porter unicode61`), and injects only the compact failing assertion digest | **100% automatic** — saves `50%–90%` of test/build log tokens with zero lost stack traces |
111
- | **2. Post-Edit Delta Diffs & 3rd-Read AST Stubs** (`GUARD-4` in `PreToolUse`) | When the agent re-reads a file after editing 5 lines (or reads the same unclipped file `>=3` times), returns a unified line diff or function-signature AST stub | **100% automatic** — cuts repeat-read token burn by `80%+` without interrupting the agent |
112
- | **3. `PrefixCacheShield` Warm Rule Deferral** (`DET-09`) | Intercepts mid-session edits to `AGENTS.md` / `CLAUDE.md` while a `>=15k` KV cache is warm (`TTL > 0s`) and queues the delta until Turn 0, `/compact`, or manual `[Apply]` | **Automatic protection** — prevents silent `50k–150k` cold prefix rebuilds |
113
- | **4. Live Model & Effort Switch Verdict** (`Zone B`) | Evaluates remaining KV cache TTL (`5m`/`1h`) and algebraic break-even `C*` across `MODEL / HOLD / SWITCH / LOCK` states | **Instant visual guidance** — tells you when to hold vs. switch models or lower thinking effort |
114
- | **5. Pre-Compact State Baton** (`task.md` / `HANDOFF.md`) | Distills active plan checkboxes, modified file paths, and unresolved errors before `/compact` (`>=80%` saturation) | **Eliminates post-compact amnesia** — stops the agent from re-reading the same 10 files after compacting |
115
- | **6. Git Hook-Bypass & Destructive Shell Guard** (`DET-08` / `DET-19`) | Blocks `git commit --no-verify`, `-n`, `core.hooksPath` tampering, and unconfirmed `git reset --hard` | **Zero-config repo safety** — keeps frustrated agents from bypassing your pre-commit linters |
116
-
117
- ---
118
-
119
- ## 🌱 Zero-Waste AI Engineering: FinOps + GreenOps (Scope 3 Compute Efficiency)
120
-
121
- For systems engineers, re-sending a 40,000-token test log 15 times is the AI equivalent of a memory leak—it wastes datacenter GPU prefill cycles, increases time-to-first-token (TTFT) latency, and degrades reasoning quality.
122
-
123
- For **Engineering Managers and Enterprise FinOps / Sustainability teams**, every `1,000,000` redundant frontier LLM tokens prevented avoids approximately **`~0.65 kWh` (`650 Wh`) of datacenter GPU prefill energy** (`~247g CO₂e` and associated cooling water). Highbeam's local **Corporate PDF 1.4 Expense Receipt** (`npx ctxtop receipt --pdf`) automatically reports both **Verified USD Saved (FinOps)** and **Estimated GPU Compute Energy Avoided (GreenOps / Scope 3)** with a cryptographic SHA-256 audit digest—giving teams a dual cost-and-sustainability justification with zero cloud telemetry.
124
-
125
- ---
126
-
127
- ## Why Highbeam (`ctxtop`) Exists (vs. Cloud LLM Observability)
128
-
129
- Cloud trace platforms (Langfuse, Helicone, Arize) require proxying API keys over the network and only observe HTTP request/response payloads. They have **zero visibility into the local filesystem, git working tree, IDE process table, or local SQLite/JSONL session stores**.
130
-
131
- `ctxtop` is a zero-dependency local systems profiler built on Node.js built-ins (`node:sqlite`, `node:fs`, `node:http`). It correlates local session transcripts and SQLite databases with live disk state to catch concrete failure modes that cloud proxies cannot see:
132
-
133
- | Failure Mode | Root Cause in Agentic Sessions | How `ctxtop` Detects & Remediates It Locally |
134
- | :--- | :--- | :--- |
135
- | **12.5x–80x Prompt Cache Tax & Overage TTL Cliffs** | Falling from a 1-hour prompt cache tier to a 5-minute overage/fallback tier, or mutating system/MCP blocks mid-session while holding `>50k` warm tokens, triggers an uncached prefix rebuild. | Tracks Dual-TTL windows (`1h` vs `5m` main + `5m` subagent), pinpoints the exact turn/component/byte offset of prefix mutations (`computePrefixMutationDiff`), and enforces a Cold-Session Cost Gate. |
136
- | **Compaction Lobotomy & Post-Compact Re-Read Tax** | Autocompact at 80%–95% context wipes file line numbers, active `task.md` checklists, and unresolved `stderr`, forcing the agent to re-read the same unmodified files immediately after compaction. | Deterministically distills `.handoff.md` before compaction (`>=80%` saturation), tracks post-compaction re-reads of unmodified files, and synthesizes `<1,000`-token `[▶ RESUME HERE]` packs via SQLite FTS5 BM25 episodic memory. |
137
- | **30GB–100GB Local IDE Storage Bloat (`state.vscdb`)** | Orphaned Cursor `bubbleId:*`, `checkpointId:*`, `messageRequestContext:*`, and unreferenced `agentKv:blob:*` rows accumulate in SQLite `cursorDiskKV` until disk space or `VACUUM` locks fail. | Audits and reclaims orphaned rows via streaming read-only SQLite export (`--gc-cursor` / `--storage-gc`) without requiring a 2x-disk-space in-place `VACUUM` lock, and recovers orphaned Antigravity `brain/` artifacts (`--recover-brain`). |
138
- | **Stale File Overwrites (`DIRTY_SNAP`)** | Developer edits or runs `git pull` on a file the agent read 10 turns ago; the agent overwrites disk changes with its stale in-context snapshot. | Compares `fs.statSync(path).mtimeMs` on disk against the last `read_file` / `view_file` step timestamp in the JSONL transcript (`+1000ms` tolerance) and injects a pre-turn re-read guard. |
139
- | **Unseen Call-Site Breakage (`UNSEEN_CALLERS`)** | Agent modifies an exported function signature without reading downstream callers in the repo. | Runs a bounded `<8ms` regex import scan (`import ... from`, `require()`, Python `from ... import`) across workspace files (up to 250 files) and flags callers absent from the active working set. |
140
- | **Superseded Full-File Reads & Tool Sludge (`--prune-tools`)** | Agent reads the same 800-line file 6 times, runs unreferenced exploratory `grep` searches, or retains resolved test `stderr` traces, diluting middle-window recall. | Pairs `tool_use` and `tool_result` across Antigravity, Claude Code, and Cursor while pinning Turn 0 and the newest 6 turns; truncates stale tool outputs offline with an atomic `.pre_surgeon` backup. |
141
- | **Turn-0 MCP Schema Bloat (`SCHEMA_TAX`)** | Eagerly loaded MCP servers inject 15k–40k tokens of JSON tool schemas on Turn 0 even when never invoked. | Computes per-server Token ROI (`calls / schemaTokens`, `IDLE_BLOAT_TAX`) and dynamic `deferred_tools_delta` expansion, flagging 0-call eager servers to switch to `"loading": "lazy"`. |
142
-
143
- ---
144
-
145
- ## Multi-Harness v4.0 Wedge Capabilities
146
-
147
- 1. **Cross-Harness SQLite & Protobuf Trajectory Stitcher (`src/core/trajectory_stitcher.mjs`)**:
148
- - **Google Antigravity (`[App]`, `[IDE]`, `[CLI]`)**: Zero-dependency protobuf wire-walker (`decodeProtobufWire`) inspects `conversations/<uuid>.db` (`steps` table binary `step_payload` and `metadata` blobs) in strict read-only mode to extract `file:///` workspace URIs and stitch with `transcript_full.jsonl` and `annotations/<uuid>.pbtxt`.
149
- - **Claude Code**: Reconstructs the `uuid -> parentUuid` DAG up to the active `leafUuid`, isolating `/rewind` branches, `file-history-snapshot` restore points, and Turn-1 `cache_creation_input_tokens`.
150
- - **Cursor**: Correlates `composerData:<id>`, `bubbleId:<id>:<bubble>`, `messageRequestContext`, and `agentKv:blob:*` (`requestId`) with `store.db` and timestamp-less `agent-transcripts/*.jsonl`.
151
- 2. **Subagent Worktree & File Collision Detector (`src/core/subagents.mjs`)**:
152
- - Builds a parent-to-child subagent DAG, tracks independent 5-minute child cache TTLs, and flags `SUBAGENT_FILE_COLLISION` when `>= 2` concurrent subagent branches edit the same canonical file path.
153
- 3. **SQLite FTS5 Episodic Memory & Git Commit Token Ledger (`src/core/episodic_memory.mjs`, `src/core/git_ledger.mjs`)**:
154
- - Indexes historical session decisions, modified files, and resolved bug signatures into a local SQLite FTS5 (`porter unicode61`) store (`~/.ctxtop/episodic_memory.sqlite`) for `<1,000`-token BM25 retrieval.
155
- - Correlates `.git/logs/HEAD` commit timestamps against session windows to attribute input/output tokens, cache hit %, and USD cost per git commit.
156
- 4. **Zero-PII Sanitizer & Forensic Snapshot Exporter (`src/core/sanitizer.mjs`)**:
157
- - Scrubs API keys (`sk-ant-*`, `sk-proj-*`, `AIza*`), GitHub PATs (`ghp_*`, `github_pat_*`), AWS keys, Bearer tokens, `.env` values, and OS home paths (`<USER_HOME>`) before exporting shareable forensic JSON snapshots.
158
-
159
- ---
160
-
161
- ## Quick Start
162
-
163
- ### 1. Inspect Live Sessions, Prune Tool Sludge, or Run Storage GC
164
- ```bash
165
- # Audit the last 5 local sessions for duplicate file reads, dead errors & MCP schema tax
166
- node src/cli/postmortem.mjs --last 5
167
-
168
- # Run environment & transcript health diagnostics (hooks, SQLite/JSONL confidence, 3-way mirror SHA-256)
169
- node src/cli/doctor.mjs
170
-
171
- # Run offline Prefix-Safe Tool-Output Surgeon on the active session transcript (with atomic backup)
172
- node src/cli/doctor.mjs --prune-tools --dry-run
173
-
174
- # Recover orphaned Antigravity brain/ directories or compact Cursor state.vscdb without VACUUM locks
175
- node src/cli/doctor.mjs --recover-brain --gc-cursor --vscdb path/to/state.vscdb --dry-run
176
-
177
- # Print the 40-cell ANSI status bar for the active session
178
- node src/cli/horizon_hud.mjs --live
179
- ```
180
-
181
- ### 2. Launch the Local Telemetry WebView (`127.0.0.1`)
182
- ```bash
183
- # Start the loopback sidecar daemon and open the Tufte WebView
184
- node sidecars/horizon-daemon/server.mjs
185
- ```
186
-
187
- ### 3. Install Lifecycle Hooks & CLI `statusLine`
188
- ```bash
189
- # Global install (~/.gemini/config/plugins/agy-horizon-flightcheck)
190
- node src/cli/init.mjs init
191
-
192
- # Workspace-local install (.agents/plugins/agy-horizon-flightcheck)
193
- node src/cli/init.mjs init --workspace
194
- ```
195
-
196
- > [!TIP]
197
- > Looking for copy-paste recipes for Cursor 50GB storage reclamation, offline tool pruning, Antigravity brain recovery, or programmatic Node.js API snippets? See the [**`ctxtop` Cookbook & Recipes**](docs/COOKBOOK.md).
198
-
199
- ---
200
-
201
- ## Systems Architecture & Zero-Trust Security
202
-
203
- `ctxtop` is engineered for strict operational safety alongside live IDE/CLI database writers:
204
-
205
- 1. **Zero Outbound Network Connections**:
206
- - **0 runtime `npm` dependencies** (`package.json` has no `dependencies` block).
207
- - **0 external HTTP/HTTPS requests, telemetry beacons, or remote API calls**. All parsing, classification, and routing run 100% in-memory on the local machine.
208
- - The local WebView daemon (`sidecars/horizon-daemon/server.mjs`) binds strictly to `127.0.0.1` (loopback only) and rejects cross-origin `Origin` or non-local `Host` headers (`HTTP 403`) to prevent DNS rebinding and drive-by localhost CSRF.
209
- 2. **Read-Only Database & Transcript Introspection (`SQLITE_OPEN_READONLY`)**:
210
- - Every connection to Antigravity or Cursor SQLite databases (`conversations/<uuid>.db`, `conversation_summaries.db`, `state.vscdb`, `store.db`) is opened via Node's native `node:sqlite` `DatabaseSync` with `Object.freeze({ readOnly: true })` (`SQLITE_OPEN_READONLY`). `ctxtop` can never contend for write locks with an active IDE or CLI.
211
- - Live JSONL transcripts (`transcript_full.jsonl` / `transcript.jsonl`) are read via `fs.openSync(filePath, 'r')` using byte-offset slicing (`O(Δbytes)` per turn), falling back to full re-parse only when a step-index regression (Undo/Rewind) is detected.
212
- 3. **Ring 1 Security, Concurrency & Context Hygiene Boundaries**:
213
- - **`DET-19` Git Hook-Bypass Guard**: Intercepts `git` execution via `.agents/shims/` wrappers, strips `.agents/shims` from `PATH` to eliminate recursion, blocks verification evasion (`--no-verify`, standalone `-n`, `-amn`, `--no-gpg-sign`, `core.hooksPath`), and allows bypass strictly via a 60-second single-use cryptographic human nonce.
214
- - **Zero-Token Subagent IPI Sanitizer**: Deterministically strips Unicode Tag characters, zero-width spaces, bidi overrides, HTML comments, and delimiter breakouts in `<1ms`, framing external research digests safely at prompt tails under `<untrusted_subagent_data>`.
215
- - **Pre-Threshold ANSI Normalization (`DET-14b`)**: Strips ANSI escape sequences and collapses carriage returns (`\r`) before the 4,096-char threshold and SQLite FTS5 archival, featuring specialized noise profiles for `cargo test` and `npm install` with Critical Error-Line Recovery.
216
- - **Concurrent Scope Lockfile (`DET-20`)**: Manages `.agents/locks/active_scopes.json` with atomic writes, auto-evicting dead PIDs and expired leases (>300s), while alerting on multi-agent file collisions with 1-click `git worktree add` commands.
217
- 4. **Locked v4.0 Edward Tufte UI Laws**:
218
- - **Law 1 (Raw Physical Units Only)**: Displays `Tokens + %`, `Cache Hit %`, `Waste Tokens`, and `1h/5m TTL Countdown` side-by-side—never arbitrary `0–100` gamified scores.
219
- - **Law 2 (40-Cell Hero + Top 3–5 Riskiest Cells)**: Surfaces the top 3–5 highest-risk context cells directly below the 40-cell flamegraph with exact file paths, attention recall %, and 1-click `[Re-Anchor / Prune]` actions.
220
- - **Law 3 (Zero-Click Passive Workload Tag)**: Passively classifies sessions into `[Mode: Read-Heavy Audit]`, `[Mode: Multi-File Refactor]`, or `[Mode: Subagent Swarm]` from tool-call ratios.
221
- - **Law 4 (Silent-When-Nominal Watchdog)**: Host RAM and orphan process counters remain completely hidden unless an anomaly (`orphanCount > 0` or `ZOMBIE_LEAK`) occurs.
222
-
223
- ---
224
-
225
- ## 🔧 Configuration, Flight Modes & MCP Server (`@ctxtop/mcp`)
226
-
227
- ### 1. Customizing `.attention-horizon.json` (Flight Modes & Detector Overrides)
228
- Highbeam works with zero configuration out of the box (`COACH` mode). To customize behavior per-repository or globally (`~/.attention-horizon.json`), use the CLI or create `.attention-horizon.json` in your workspace root:
229
-
230
- ```bash
231
- # Set a detector to warn-only, block, or off via CLI
232
- npx ctxtop config DET-08 warn
233
- npx ctxtop config DET-19 block
234
- ```
235
-
236
- ```json
237
- {
238
- "flightMode": "COACH",
239
- "turnZeroTokenBudget": 20000,
240
- "detectors": {
241
- "DET-06": "block",
242
- "DET-07": "block",
243
- "DET-08": "warn",
244
- "DET-09": "block",
245
- "DET-19": "block",
246
- "DET-20": "warn"
247
- }
248
- }
249
- ```
250
- - **`"COACH"` *(Default)***: Compresses CLI output (`DET-07`), folds repeat file reads (`GUARD-4`), and stages warm rule edits (`DET-09`) automatically while advising on model/cache switches without blocking normal flow.
251
- - **`"AUTO_PILOT"`**: Enforces strict pre-turn & stop-gate verification locks (e.g., requiring tests to run after source edits before session completion).
252
- - **`"SILENT"` / `"OFF"`**: Passive telemetry collection only.
253
-
254
- ### 2. Using Highbeam as an MCP Server (`ctxtop-mcp`)
255
- Any MCP-compatible client (**Google Antigravity**, **Claude Code**, **Cursor**, **Windsurf**, or **Claude Desktop**) can query Highbeam's telemetry and KV-cache advisor via standard JSON-RPC stdio:
256
-
257
- ```json
258
- {
259
- "mcpServers": {
260
- "highbeam": {
261
- "command": "npx",
262
- "args": ["-y", "ctxtop-mcp"]
263
- }
264
- }
265
- }
266
- ```
267
- Exposes 4 read-only MCP tools (`<5ms` response): `get_context_telemetry`, `check_cache_gravity`, `get_savings_receipt`, and `inspect_detectors`.
268
-
269
- ---
270
-
271
- ## Deterministic `PreInvocation` Router & 6 Local Sensors
272
-
273
- When registered in `hooks.json`, `src/hooks/pre_invocation.mjs` evaluates incoming prompts across 8 deterministic router states (**Tier-1 In-Process Router Evaluation: `~0.18ms p95`** inside a warm V8 isolate; **Tier-2 Spawned CLI Hook End-to-End Wall Time: `~25–45ms` POSIX / `~40–90ms` Windows PowerShell** including Node process startup):
274
-
275
- 1. `ALLOW_SILENT`: Immediate pass-through (`{}`) on `!` bypass prefix or healthy turns.
276
- 2. `ALLOW_ACTIVE_SET`: Silent pass-through when referenced files are already warm in the last 5 turns.
277
- 3. `ALLOW_PLAN_OR_SUBAGENT`: Silent pass-through during `/plan` mode or subagent delegation.
278
- 4. `INJECT_CONTEXT_GUARD`: Appends a `systemMessage` warning when target files were modified externally on disk (`DIRTY_SNAP`), have unseen callers (`UNSEEN_CALLERS`), or touch deprecated paths (`LEGACY_POISON`).
279
- 5. `STEER_SUBAGENT`: Advises `invoke_subagent` when a broad exploratory prompt would pollute a warm `>30k`-token parent context window.
280
- 6. `HALT_HYGIENE_OR_SAFETY`: Halts execution (or warns in `advisory` mode) on context ceiling breach, 3-strike identical command error loops, or severe duplicate-read dilution.
281
- 7. `HALT_EFFORT_OR_QUOTA`: Warns when 5-hour/7-day quota falls below the configured floor (`10%`) or when `>600`-line single-shot file rewrites risk output stream truncation.
282
- 8. `HALT_REWRITE_SCORECARD`: Triggered via `#check` or vague cold-start prompts (`Turn <= 2`), outputting a 4-line prompt rewrite scorecard.
283
-
284
- ---
285
-
286
- ## CLI Commands & Forensic Postmortem
287
-
288
- | Command | Description |
289
- | :--- | :--- |
290
- | `npx ctxtop init [--workspace]` | Installs Google Antigravity plugin manifests, lifecycle hooks, and sidecar configuration. |
291
- | `npx ctxtop install --claude` | Installs Claude Code `.claude-plugin` manifest, Tier-1/Tier-2 hooks, and terminal `statusLine`. |
292
- | `npx ctxtop doctor [--diagnostic]` | Validates hook registration, config overlays, dynamic model ceilings, 3-way WebView SHA-256 parity, and SQLite/JSONL health. |
293
- | `npx ctxtop postmortem [--last N] [--json]` | Scans the last `N` local sessions, classifies root causes (`CONTEXT_ROT_DECAY`, `VERIFICATION_CHURN`, `SPEC_AMBIGUITY`, `CLEAN`), lists top duplicate-read files, and audits Turn-0 MCP schema overhead. |
294
- | `npx ctxtop receipt [--markdown \| --pdf]` | Exports a SHA-256 verified FinOps + GreenOps token/USD savings receipt for the active workspace. |
295
- | `npx ctxtop verify [--json]` | Verifies cryptographic SHA-256 integrity of all 149 release files against `CHECKSUMS.sha256`. |
296
- | `npx ctxtop --roast` | Prints a terminal forensic summary of recent sessions with top duplicate-read file offenders and copy-pasteable remediations. |
297
- | `npx ctxtop --serve` | Launches the local HTTP/SSE telemetry daemon (`127.0.0.1`) and interactive WebView (`/` Simple, `/advanced` Advanced). |
298
- | `npx ctxtop --demo-animate` | Plays the 5-stage terminal crisis simulation across synthetic fixtures. |
299
-
300
- ---
301
-
302
- ## Verification & Benchmarks
303
-
304
- Run the full zero-dependency test and verification suite (**1,050+ tests across 215+ suites**):
305
-
306
- ```bash
307
- # Full Coach, UI, & 360° Capability-Proof suite (911+ tests across 183+ suites)
308
- npm run test:coach
309
-
310
- # Claude Code dual-tier Mod, CLI hooks, statusLine, and 5-category ledger suite (168 tests)
311
- npm run test:claude
312
-
313
- # Unit & Multi-Harness Wedge suite (89 tests across 31 suites)
314
- npm run test:unit
315
-
316
- # Architectural verification suite (Gates 0-6 & Phases 1-7: SQLite read-only locks, JSDOM UI, MCP audit)
317
- npm run test:gates && npm run test:phases
318
-
319
- # End-to-end context memory & live loopback daemon integration suite (7 layers)
320
- npm run test:e2e
321
-
322
- # Latency benchmark (200 iterations/path: Tier-1 ~3.0ms avg / <15ms SLA, Tier-2 CLI Hook, <45ms HUD)
323
- npm run bench
324
- ```
325
-
326
- ---
327
-
328
- ## License
329
-
330
- MIT © [Gizzant](https://github.com/Gizzant)
1
+ <div align="center">
2
+
3
+ # Highbeam (`ctxtop` v4.1) — Active Context Surgeon, KV-Cache Shield & Token FinOps for Claude Code, Google Antigravity & MCP Hosts
4
+
5
+ **Local Context Window Profiler, KV-Cache TTL Monitor, Multi-Family FTS5 Output Compressor & Deterministic PreInvocation / PreToolUse Surgeon (`~0.1–2.9ms` avg Tier-1 In-Process · `~58ms` Warm IPC / `~105ms` Cold Windows Tier-2 Hook) across Google Antigravity, Claude Code, Codex CLI, Gemini CLI & Cursor**
6
+
7
+ [![Zero Runtime Dependencies](https://img.shields.io/badge/dependencies-0_runtime-brightgreen.svg)](#systems-architecture--zero-trust-security)
8
+ [![Hook Latency](https://img.shields.io/badge/Tier--1_in--process-~2.9ms_avg_%7C_Tier--2_hook-~58ms_IPC%2F~105ms_cold-00e5ff.svg)](#deterministic-preinvocation-router--6-local-sensors)
9
+ [![Node.js >= 20](https://img.shields.io/badge/node-%3E%3D20_zero_deps-339933.svg)](#try-in-10-seconds-zero-hooks--zero-writes)
10
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
11
+ [![Multi-Host Parity](https://img.shields.io/badge/Hosts-Antigravity_%7C_Claude_%7C_Codex_%7C_Gemini_%7C_Cursor-blueviolet.svg)](#-installation--quick-start)
12
+
13
+ [**Live Interactive Demo**](https://gizzant.github.io/attention-horizon-antigravity/) • [**10-Second 5-Host Audit**](#try-in-10-seconds-zero-hooks--zero-writes) • [**Quick Start**](#-installation--quick-start) • [**Cookbook**](docs/COOKBOOK.md) • [**Benchmarks**](docs/ANTIGRAVITY_AND_COMPRESSION_BENCHMARK.md) • [**Enterprise MDM**](docs/ENTERPRISE_MDM.md)
14
+
15
+ <br/>
16
+
17
+ <img src="assets/hero-demo.svg" alt="Highbeam 40-Cell ANSI HUD & PreInvocation Router" width="100%" />
18
+
19
+ </div>
20
+
21
+ ---
22
+
23
+ ## ⚡ Try in 10 Seconds (Zero Hooks / Zero Writes)
24
+
25
+ Before installing any hooks or modifying config files, scan your last 7 days of local **Google Antigravity**, **Claude Code**, **OpenAI Codex CLI**, **Gemini CLI**, and **Cursor** sessions strictly read-only to measure preventable token waste, cold-cache spikes, and oversized tool dumps:
26
+
27
+ ```bash
28
+ npx ctxtop audit --days 7
29
+ ```
30
+
31
+ ```text
32
+ [Highbeam Session ROI Audit] Window: 7d | Platform: all | Sessions: 12
33
+ Sludge Tax Preventable : 1,420,850 tok ($2.84 USD)
34
+ Cold-Cache Spikes (>5m): 14 | 3x Thrash Loops: 4
35
+ Un-Sliced Large Reads : 11 | Oversized Tool Dumps: 38
36
+ ```
37
+
38
+ ---
39
+
40
+ ## 🚀 Installation & Quick Start
41
+
42
+ | **Google Antigravity** *(1-Line Install)* | **Claude Code** *(1-Line Install)* | **Cursor / Windsurf / Codex / Gemini CLI** |
43
+ | :--- | :--- | :--- |
44
+ | ```bash
45
+ npx ctxtop init
46
+ ``` | ```bash
47
+ npx ctxtop install --global
48
+ ``` | ```bash
49
+ npx ctxtop init --cursor --windsurf --codex --gemini-cli
50
+ ``` |
51
+ | *Workspace-only*: `npx ctxtop init --workspace`<br/>*Health check*: `npx ctxtop doctor` | *StatusLine HUD*: `npx ctxtop statusline --demo`<br/>*In-chat pane*: `/horizon` · `/cost-radar` · `/handoff` | *Universal `.mcp.json`*: `npx ctxtop init --all-hosts`<br/>*FTS5 search*: `npx ctxtop search "<keyword>"` |
52
+
53
+ ### Your First 5 Minutes After Installing
54
+
55
+ #### 1. Google Antigravity Workflow
56
+ 1. **Install hooks & sidecar**: Run `npx ctxtop init` in your project root (or globally).
57
+ 2. **Open the Highbeam Sidepane**: Launch the local telemetry WebView (`npx ctxtop ui` or via the Antigravity sidepane) to view real-time context health:
58
+ - **Simple View (Default)**: 4 glanceable zones—**Zone A** (Safe Headroom & Warm KV Cache TTL), **Zone B** (`DO / AVOID / HOLD` Model & Effort switch guidance), **Zone C** (Live automated interventions), and **Zone D** (Verified tokens/USD saved + 1-click `/compact`).
59
+ - **Advanced View (1-Click Toggle)**: Expands the **40-Cell Chrono-Positional Recall Grid** (`Primacy 0–30%`, `Mid-Trough 30–70%`, `Recency 70–100%`), top token consumer file table, `Off / Coach / Auto` mode switcher, and the full `DET-01..32` guard log.
60
+ 3. **Code normally**: Highbeam runs in **`COACH` mode** by default—automatically compressing verbose CLI test dumps via SQLite FTS5 and folding repeat file reads without interrupting your prompts.
61
+
62
+ #### 2. Claude Code Workflow
63
+ 1. **Install plugin & hooks**: Run `npx ctxtop install --global` (or `npx ctxtop init --claude`) to wire `.claude-plugin/plugin.json`, `hooks/hooks.json`, and the live terminal `statusLine`.
64
+ 2. **Watch the Live Terminal `statusLine`**: At the bottom of your terminal, Highbeam renders an auto-adapting (`80 / 110 / 144` col) telemetry bar:
65
+ ```text
66
+ AH [SCCCCCCC................] sonnet-5-5 64k/200k (32%) · Cache 88% (4m12s) · COACH · Saved $1.84
67
+ ```
68
+ 3. **Open the In-Chat Docked HUD**: Type `/horizon` in chat (or run `npx ctxtop panel` for the standalone HTML workbench) to inspect cache gravity, active guards, and reclaimable tokens.
69
+
70
+ ---
71
+
72
+ ## 🧭 Built-In Slash Skills & In-Chat Commands (Both Hosts)
73
+
74
+ All 6 slash skills are registered identically in both **Google Antigravity** (`plugin.json`) and **Claude Code** (`.claude-plugin/plugin.json`):
75
+
76
+ | Slash Command / Skill | When to Use It | What It Outputs |
77
+ | :--- | :--- | :--- |
78
+ | **`/horizon`** | Anytime during a coding session | Renders the live 40-cell Context Health HUD, KV-Cache TTL countdown, active `DO / AVOID / HOLD` guidance, and reclaimable clutter breakdown. |
79
+ | **`/precheck`** | Before sending a complex refactor prompt or switching models | Audits prompt specificity (6-dimension rubric), checks horizon-aware KV-cache break-even (`C_max` & warm-request payback), and recommends the optimal Model & Effort tier. |
80
+ | **`/handoff`** | Before running `/compact` or `/clear` at `>=75%` context fill | Distills active plan checkboxes, modified files, and unresolved `stderr` into a compressed `<1,000`-token checkpoint (`task.md` / `.handoff.md`). |
81
+ | **`/cost-radar`** | When reviewing session token burn or cache busts | Generates an interactive HTML/SVG timeline of prefix-cache retention, `DET-30` thinking drift loops, and subagent worktree topology. |
82
+ | **`/inspect`** | When diagnosing slow tools or subagent fan-out | Visualizes session trajectory call-tree spans, per-tool latencies, and token attribution as a standalone artifact. |
83
+ | **`/evolve`** | After correcting agent mistakes across a session | Audits `AGENTS.md` / `CLAUDE.md` Turn-0 prefix budget (`<=20k` tok) and synthesizes validated session instincts via 1-click diff approval. |
84
+
85
+ **Quick In-Chat Prompt Prefixes:**
86
+ - `! <prompt>` — Bypass `PreInvocation` checks for a single turn.
87
+ - `!lock <prompt>` — Freeze current reasoning effort tier and prefix state for the remainder of the session.
88
+ - `#check <prompt>` — Force an explicit pre-flight scorecard and concrete prompt rewrite suggestion.
89
+
90
+ ---
91
+
92
+ ## 🛡️ Example Session Receipt: `+164.0k` Tokens Saved in One 4-Step Loop
93
+
94
+ Most CLI trackers passively count tokens *after* your quota is already burned. Highbeam intercepts redundant reads, compresses noisy test dumps via local SQLite FTS5, and shields warm KV prefixes **before** they hit your billing meter:
95
+
96
+ <div align="center">
97
+ <img src="assets/zone_c_step3_shield_full.png" alt="Highbeam Zone C Active Protection & Verified Token Receipt (+164.0k tokens saved)" width="460" />
98
+ </div>
99
+
100
+ | Step in Coding Loop | Developer / Agent Action | Highbeam Active Intervention (Zone C) | Verified Incident Savings |
101
+ | :--- | :--- | :--- | :---: |
102
+ | **1. Warm KV Cache + Repeat Read** | Agent re-reads an unmodified 800-line source file on a `100k` warm cache | **GUARD-4** intercepts the duplicate read (`AST signature stub`) and preserves the `95%` warm KV cache discount | **`+95.0k` tok** *(KV cache)*<br/>**`+800` tok** *(deduped read)* |
103
+ | **2. Failing Test Suite Dump** | `npm test` dumps `120+` lines of verbose stdout (`~11.4k` tokens) | **SQLite FTS5 BM25 Compressor** indexes raw stdout locally and injects only the 160-token failing assertion digest | **`+11.2k` tok** |
104
+ | **3. Mid-Session Rule Edit** | Agent updates `AGENTS.md` / `CLAUDE.md` while `60k` prefix is warm (`2m 55s` TTL left) | **PrefixCacheShield** queues the rule delta until TTL expiry or `/compact`, preventing a cold prefix rebuild | **`+57.0k` tok** |
105
+ | **Example Incident Receipt** | **4-Step Feature / Bugfix Loop** | **Zero context dilution · 100% critical error retention** | **`+164.0k` tok (`~$0.33`)** |
106
+
107
+ > **Reconciled Monthly Expectation:** Across normal coding weeks without deliberate cache-busting, our bottom-up benchmark model estimates **`~$9.42/wk` (`~$40.79/mo`, `~6%–11%` of raw API spend)** saved for a full-time agentic developer, alongside **`30%–50%` longer 5-hour subscription sprints** by cutting `O(N²)` tool-log compounding.
108
+
109
+ ---
110
+
111
+ ## 💡 Why Saved Tokens Multiply (`O(N²)` Turn Compounding, Quota Life & Model IQ)
112
+
113
+ In agentic coding, every turn re-sends the entire prior conversation history. A single `15,000`-token raw test dump on Turn 5 is not billed once—it is re-sent on Turns 6 through 25, burning **`300,000` cumulative tokens** (`15,000 × 20`).
114
+
115
+ 1. **For Fixed-Subscription Users (`Claude Pro / Max`, `Antigravity OAuth Seats`) — Stop 2:00 PM Quota Lockouts & Context Rot**:
116
+ - Compressing noisy tool outputs and duplicate file reads on early turns prevents `O(N²)` history compounding, **stretching 5-hour sprint quotas by `30%–50%`**.
117
+ - Staying below the **70% Safe Horizon** prevents **Context Rot** (middle-window attention decay where the model starts overlooking `AGENTS.md`/`CLAUDE.md` rules or hallucinating imports).
118
+ 2. **For Metered API & Enterprise Teams — Self-Expensing FinOps ROI**:
119
+ - Preventing accidental warm-cache busts plus automatic FTS5 log compression saves **`~$40.79/mo` (`$9.42/wk`)** for average full-time API devs (`~$149/mo` for heavy 100k–200k Opus swarm users).
120
+ 3. **Daily Cockpit Decisions No Human Can Calculate in Their Head (Zone B)**:
121
+ - *"If I downshift from Opus to Sonnet right now, will I save quota or pay a 10x cold-prefill penalty?"* — Highbeam computes the horizon-aware KV-cache break-even limit (`C_max`) and post-switch warm-request payback in real time and displays a 1-line verdict: **`Model: Hold (03:34) — switching busts warm cache`**.
122
+
123
+ ---
124
+
125
+ ## ⚙️ What Runs Automatically (100% Free `COACH` Default)
126
+
127
+ Highbeam defaults to **`COACH` mode**—performing lossless token surgery silently in the background while never blocking your chat prompt unless a 3-strike identical failure loop or destructive git command occurs:
128
+
129
+ | Automated Feature | How It Works Under the Hood | Developer Experience |
130
+ | :--- | :--- | :--- |
131
+ | **1. SQLite FTS5 CLI & Test Output Compression** (`PostToolUse`) | Strips ANSI/progress noise, indexes full stdout in local SQLite FTS5 (`porter unicode61`), and injects only the compact failing assertion digest | **100% automatic** — saves `50%–90%` of test/build log tokens with zero lost stack traces |
132
+ | **2. Post-Edit Delta Diffs & 3rd-Read AST Stubs** (`GUARD-4` in `PreToolUse`) | When the agent re-reads a file after editing 5 lines (or reads the same unclipped file `>=3` times), returns a unified line diff or function-signature AST stub | **100% automatic** — cuts repeat-read token burn by `80%+` without interrupting the agent |
133
+ | **3. `PrefixCacheShield` Warm Rule & Effort Deferral** (`DET-09`) | Intercepts mid-session edits to `AGENTS.md` / `CLAUDE.md` while a KV cache is warm, and checks `MODEL_EFFORT_CACHE_CAPABILITIES` on effort changes (defers on `4.6`, silent on cache-preserving `5.5` models, warns on untested models) | **Model-aware cache protection** — prevents silent cold prefix rebuilds without false-positiving on `5.5` effort |
134
+ | **4. Live Model & Effort Switch Verdict** (`Zone B`) | Evaluates remaining KV cache TTL (`5m`/`1h`) and horizon break-even (`C_max` & warm-request payback) across `MODEL / HOLD / SWITCH / LOCK` states | **Instant visual guidance** — tells you when to hold vs. switch models or lower thinking effort |
135
+ | **5. Held Downshift & Boundary Lifecycle** (`SessionStart:compact` / `Stop`) | Surfaces held `pending_downshift` after compaction via a zero-token `SessionStart:compact` `systemMessage` reminder (`/model <target>`), with optional boundary prompts disabled by default | **Post-compact downshift handoff** — reminds `/model <target>` cleanly right after compaction |
136
+ | **6. Git Hook-Bypass & Destructive Shell Guard** (`DET-18` / `DET-19`) | Blocks `git commit --no-verify`, `-n`, `core.hooksPath` tampering, and unconfirmed `git reset --hard` | **Zero-config repo safety** — keeps frustrated agents from bypassing your pre-commit linters |
137
+ | **7. `PreModelSwitch` Warm KV-Cache Guard** (`DET-08`) | Computes break-even (`C*`, `C_max`), cold-write penalties, and warm-request paybacks directly from `anthropicModelCatalog.json` using rolling session turns (`R`, `g`), returning explicit `unknownModel: true` without fallback price guesses | **Protects mid-session switches** — prevents losing money on short-horizon downgrades while allowing profitable early switches |
138
+
139
+ ---
140
+
141
+ ## 📊 Empirical Wire Highlights (Claude Code `2.1.325`)
142
+
143
+ Highbeam's cache-economics engine is backed by **45 pre-registered randomized runs (`540` live wire-reconciled turns)** and **6 live 30-turn compaction studies** against first-party Anthropic via OpenRouter:
144
+
145
+ - **Downgrading Mid-Chat Can Cost More Than Staying on Opus:** At `~58k` context, switching `Opus 4.6 -> Sonnet 4.6` at Turn 6 produced a `0.0%` cache hit (`+$0.1783` spike) and increased 12-turn session cost (`$0.8611` vs `$0.7789` Opus control).
146
+ - **Changing `--effort` Busted `4.6` Caches (`+$0.0853`), Fixed in `5.5`:** Wire diffs caught `output_config.effort` invalidating `4.6` prompt caches while `claude-sonnet-5-5` preserved warm cache hits (`n = 3`).
147
+ - **Stock `/compact` Scored `0/6` Violations Up to `28.10x` Compression:** Because default compaction preserved constraints cleanly without custom templates, Highbeam emits zero `PreCompact` bloat.
148
+ - **MCP / Tool-List Swaps on `--resume` Wipe Cache; `CLAUDE.md` Edits Do Not:** Highbeam hashes `.mcp.json` / `.claude/settings*.json` across resumes and warns before uncached rebuilds.
149
+
150
+ 👉 See full methodology, per-arm datasets, SDK `stream-json` `set_model` patterns, and explicit unverified boundaries in [**`docs/EMPIRICAL_BENCHMARKS.md`**](docs/EMPIRICAL_BENCHMARKS.md).
151
+
152
+ ---
153
+
154
+ ## 🌱 Zero-Waste AI Engineering: FinOps + GreenOps (Scope 3 Compute Efficiency)
155
+
156
+ For systems engineers, re-sending a 40,000-token test log 15 times is the AI equivalent of a memory leak—it wastes datacenter GPU prefill cycles, increases time-to-first-token (TTFT) latency, and degrades reasoning quality.
157
+
158
+ For **Engineering Managers and Enterprise FinOps / Sustainability teams**, every `1,000,000` redundant frontier LLM tokens prevented avoids approximately **`~0.65 kWh` (`650 Wh`) of datacenter GPU prefill energy** (`~247g CO₂e` and associated cooling water). Highbeam's local **Corporate PDF 1.4 Expense Receipt** (`npx ctxtop receipt --pdf`) automatically reports both **Verified USD Saved (FinOps)** and **Estimated GPU Compute Energy Avoided (GreenOps / Scope 3)** with a cryptographic SHA-256 audit digest—giving teams a dual cost-and-sustainability justification with zero cloud telemetry.
159
+
160
+ ---
161
+
162
+ ## Why Highbeam (`ctxtop`) Exists (vs. Cloud LLM Observability)
163
+
164
+ Cloud trace platforms (Langfuse, Helicone, Arize) require proxying API keys over the network and only observe HTTP request/response payloads. They have **zero visibility into the local filesystem, git working tree, IDE process table, or local SQLite/JSONL session stores**.
165
+
166
+ `ctxtop` is a zero-dependency local systems profiler built on Node.js built-ins (`node:sqlite`, `node:fs`, `node:http`). It correlates local session transcripts and SQLite databases with live disk state to catch concrete failure modes that cloud proxies cannot see:
167
+
168
+ | Failure Mode | Root Cause in Agentic Sessions | How `ctxtop` Detects & Remediates It Locally |
169
+ | :--- | :--- | :--- |
170
+ | **12.5x–80x Prompt Cache Tax & Overage TTL Cliffs** | Falling from a 1-hour prompt cache tier to a 5-minute overage/fallback tier, or mutating system/MCP blocks mid-session while holding `>50k` warm tokens, triggers an uncached prefix rebuild. | Tracks Dual-TTL windows (`1h` vs `5m` main + `5m` subagent), pinpoints the exact turn/component/byte offset of prefix mutations (`computePrefixMutationDiff`), and enforces a Cold-Session Cost Gate. |
171
+ | **Compaction Lobotomy & Post-Compact Re-Read Tax** | Autocompact at 80%–95% context wipes file line numbers, active `task.md` checklists, and unresolved `stderr`, forcing the agent to re-read the same unmodified files immediately after compaction. | Deterministically distills `.handoff.md` before compaction (`>=80%` saturation), tracks post-compaction re-reads of unmodified files, and synthesizes `<1,000`-token `[▶ RESUME HERE]` packs via SQLite FTS5 BM25 episodic memory. |
172
+ | **30GB–100GB Local IDE Storage Bloat (`state.vscdb`)** | Orphaned Cursor `bubbleId:*`, `checkpointId:*`, `messageRequestContext:*`, and unreferenced `agentKv:blob:*` rows accumulate in SQLite `cursorDiskKV` until disk space or `VACUUM` locks fail. | Audits and reclaims orphaned rows via streaming read-only SQLite export (`--gc-cursor` / `--storage-gc`) without requiring a 2x-disk-space in-place `VACUUM` lock, and recovers orphaned Antigravity `brain/` artifacts (`--recover-brain`). |
173
+ | **Stale File Overwrites (`DIRTY_SNAP`)** | Developer edits or runs `git pull` on a file the agent read 10 turns ago; the agent overwrites disk changes with its stale in-context snapshot. | Compares `fs.statSync(path).mtimeMs` on disk against the last `read_file` / `view_file` step timestamp in the JSONL transcript (`+1000ms` tolerance) and injects a pre-turn re-read guard. |
174
+ | **Unseen Call-Site Breakage (`UNSEEN_CALLERS`)** | Agent modifies an exported function signature without reading downstream callers in the repo. | Runs a bounded `<8ms` regex import scan (`import ... from`, `require()`, Python `from ... import`) across workspace files (up to 250 files) and flags callers absent from the active working set. |
175
+ | **Superseded Full-File Reads & Tool Sludge (`--prune-tools`)** | Agent reads the same 800-line file 6 times, runs unreferenced exploratory `grep` searches, or retains resolved test `stderr` traces, diluting middle-window recall. | Pairs `tool_use` and `tool_result` across Antigravity, Claude Code, and Cursor while pinning Turn 0 and the newest 6 turns; truncates stale tool outputs offline with an atomic `.pre_surgeon` backup. |
176
+ | **Turn-0 MCP Schema Bloat (`SCHEMA_TAX`)** | Eagerly loaded MCP servers inject 15k–40k tokens of JSON tool schemas on Turn 0 even when never invoked. | Computes per-server Token ROI (`calls / schemaTokens`, `IDLE_BLOAT_TAX`) and dynamic `deferred_tools_delta` expansion, flagging 0-call eager servers to switch to `"loading": "lazy"`. |
177
+
178
+ ---
179
+
180
+ ## Multi-Harness v4.0 Wedge Capabilities
181
+
182
+ 1. **Cross-Harness SQLite & Protobuf Trajectory Stitcher (`src/core/trajectory_stitcher.mjs`)**:
183
+ - **Google Antigravity (`[App]`, `[IDE]`, `[CLI]`)**: Zero-dependency protobuf wire-walker (`decodeProtobufWire`) inspects `conversations/<uuid>.db` (`steps` table binary `step_payload` and `metadata` blobs) in strict read-only mode to extract `file:///` workspace URIs and stitch with `transcript_full.jsonl` and `annotations/<uuid>.pbtxt`.
184
+ - **Claude Code**: Reconstructs the `uuid -> parentUuid` DAG up to the active `leafUuid`, isolating `/rewind` branches, `file-history-snapshot` restore points, and Turn-1 `cache_creation_input_tokens`.
185
+ - **Cursor**: Correlates `composerData:<id>`, `bubbleId:<id>:<bubble>`, `messageRequestContext`, and `agentKv:blob:*` (`requestId`) with `store.db` and timestamp-less `agent-transcripts/*.jsonl`.
186
+ 2. **Subagent Worktree & File Collision Detector (`src/core/subagents.mjs`)**:
187
+ - Builds a parent-to-child subagent DAG, tracks independent 5-minute child cache TTLs, and flags `SUBAGENT_FILE_COLLISION` when `>= 2` concurrent subagent branches edit the same canonical file path.
188
+ 3. **SQLite FTS5 Episodic Memory & Git Commit Token Ledger (`src/core/episodic_memory.mjs`, `src/core/git_ledger.mjs`)**:
189
+ - Indexes historical session decisions, modified files, and resolved bug signatures into a local SQLite FTS5 (`porter unicode61`) store (`~/.ctxtop/episodic_memory.sqlite`) for `<1,000`-token BM25 retrieval.
190
+ - Correlates `.git/logs/HEAD` commit timestamps against session windows to attribute input/output tokens, cache hit %, and USD cost per git commit.
191
+ 4. **Zero-PII Sanitizer & Forensic Snapshot Exporter (`src/core/sanitizer.mjs`)**:
192
+ - Scrubs API keys (`sk-ant-*`, `sk-proj-*`, `AIza*`), GitHub PATs (`ghp_*`, `github_pat_*`), AWS keys, Bearer tokens, `.env` values, and OS home paths (`<USER_HOME>`) before exporting shareable forensic JSON snapshots.
193
+
194
+ ---
195
+
196
+ ## Quick Start
197
+
198
+ ### 1. Inspect Live Sessions, Prune Tool Sludge, or Run Storage GC
199
+ ```bash
200
+ # Audit the last 5 local sessions for duplicate file reads, dead errors & MCP schema tax
201
+ node src/cli/postmortem.mjs --last 5
202
+
203
+ # Run environment & transcript health diagnostics (hooks, SQLite/JSONL confidence, 3-way mirror SHA-256)
204
+ node src/cli/doctor.mjs
205
+
206
+ # Run offline Prefix-Safe Tool-Output Surgeon on the active session transcript (with atomic backup)
207
+ node src/cli/doctor.mjs --prune-tools --dry-run
208
+
209
+ # Recover orphaned Antigravity brain/ directories or compact Cursor state.vscdb without VACUUM locks
210
+ node src/cli/doctor.mjs --recover-brain --gc-cursor --vscdb path/to/state.vscdb --dry-run
211
+
212
+ # Print the 40-cell ANSI status bar for the active session
213
+ node src/cli/horizon_hud.mjs --live
214
+ ```
215
+
216
+ ### 2. Launch the Local Telemetry WebView (`127.0.0.1`)
217
+ ```bash
218
+ # Start the loopback sidecar daemon and open the Tufte WebView
219
+ node sidecars/horizon-daemon/server.mjs
220
+ ```
221
+
222
+ ### 3. Install Lifecycle Hooks & CLI `statusLine`
223
+ ```bash
224
+ # Global install (~/.gemini/config/plugins/agy-horizon-flightcheck)
225
+ node src/cli/init.mjs init
226
+
227
+ # Workspace-local install (.agents/plugins/agy-horizon-flightcheck)
228
+ node src/cli/init.mjs init --workspace
229
+ ```
230
+
231
+ > [!TIP]
232
+ > Looking for copy-paste recipes for Cursor 50GB storage reclamation, offline tool pruning, Antigravity brain recovery, or programmatic Node.js API snippets? See the [**`ctxtop` Cookbook & Recipes**](docs/COOKBOOK.md).
233
+
234
+ ---
235
+
236
+ ## Systems Architecture & Zero-Trust Security
237
+
238
+ `ctxtop` is engineered for strict operational safety alongside live IDE/CLI database writers:
239
+
240
+ 1. **Zero Outbound Network Connections**:
241
+ - **0 runtime `npm` dependencies** (`package.json` has no `dependencies` block).
242
+ - **0 external HTTP/HTTPS requests, telemetry beacons, or remote API calls**. All parsing, classification, and routing run 100% in-memory on the local machine.
243
+ - The local WebView daemon (`sidecars/horizon-daemon/server.mjs`) binds strictly to `127.0.0.1` (loopback only) and rejects cross-origin `Origin` or non-local `Host` headers (`HTTP 403`) to prevent DNS rebinding and drive-by localhost CSRF.
244
+ 2. **Read-Only Database & Transcript Introspection (`SQLITE_OPEN_READONLY`)**:
245
+ - Every connection to Antigravity or Cursor SQLite databases (`conversations/<uuid>.db`, `conversation_summaries.db`, `state.vscdb`, `store.db`) is opened via Node's native `node:sqlite` `DatabaseSync` with `Object.freeze({ readOnly: true })` (`SQLITE_OPEN_READONLY`). `ctxtop` can never contend for write locks with an active IDE or CLI.
246
+ - Live JSONL transcripts (`transcript_full.jsonl` / `transcript.jsonl`) are read via `fs.openSync(filePath, 'r')` using byte-offset slicing (`O(Δbytes)` per turn), falling back to full re-parse only when a step-index regression (Undo/Rewind) is detected.
247
+ 3. **Ring 1 Security, Concurrency & Context Hygiene Boundaries**:
248
+ - **`DET-19` Git Hook-Bypass Guard**: Intercepts `git` execution via `.agents/shims/` wrappers, strips `.agents/shims` from `PATH` to eliminate recursion, blocks verification evasion (`--no-verify`, standalone `-n`, `-amn`, `--no-gpg-sign`, `core.hooksPath`), and allows bypass strictly via a 60-second single-use cryptographic human nonce.
249
+ - **Zero-Token Subagent IPI Sanitizer**: Deterministically strips Unicode Tag characters, zero-width spaces, bidi overrides, HTML comments, and delimiter breakouts in `<1ms`, framing external research digests safely at prompt tails under `<untrusted_subagent_data>`.
250
+ - **Pre-Threshold ANSI Normalization (`DET-14b`)**: Strips ANSI escape sequences and collapses carriage returns (`\r`) before the 4,096-char threshold and SQLite FTS5 archival, featuring specialized noise profiles for `cargo test` and `npm install` with Critical Error-Line Recovery.
251
+ - **Concurrent Scope Lockfile (`DET-20`)**: Manages `.agents/locks/active_scopes.json` with atomic writes, auto-evicting dead PIDs and expired leases (>300s), while alerting on multi-agent file collisions with 1-click `git worktree add` commands.
252
+ 4. **Locked v4.0 Edward Tufte UI Laws**:
253
+ - **Law 1 (Raw Physical Units Only)**: Displays `Tokens + %`, `Cache Hit %`, `Waste Tokens`, and `1h/5m TTL Countdown` side-by-side—never arbitrary `0–100` gamified scores.
254
+ - **Law 2 (40-Cell Hero + Top 3–5 Riskiest Cells)**: Surfaces the top 3–5 highest-risk context cells directly below the 40-cell flamegraph with exact file paths, attention recall %, and 1-click `[Re-Anchor / Prune]` actions.
255
+ - **Law 3 (Zero-Click Passive Workload Tag)**: Passively classifies sessions into `[Mode: Read-Heavy Audit]`, `[Mode: Multi-File Refactor]`, or `[Mode: Subagent Swarm]` from tool-call ratios.
256
+ - **Law 4 (Silent-When-Nominal Watchdog)**: Host RAM and orphan process counters remain completely hidden unless an anomaly (`orphanCount > 0` or `ZOMBIE_LEAK`) occurs.
257
+
258
+ ---
259
+
260
+ ## 🔧 Configuration, Flight Modes & MCP Server (`@ctxtop/mcp`)
261
+
262
+ ### 1. Customizing `.attention-horizon.json` (Flight Modes & Detector Overrides)
263
+ Highbeam works with zero configuration out of the box (`COACH` mode). To customize behavior per-repository or globally (`~/.attention-horizon.json`), use the CLI or create `.attention-horizon.json` in your workspace root:
264
+
265
+ ```bash
266
+ # Set a detector to warn-only, block, or off via CLI
267
+ npx ctxtop config DET-08 warn
268
+ npx ctxtop config DET-19 block
269
+ ```
270
+
271
+ ```json
272
+ {
273
+ "flightMode": "COACH",
274
+ "turnZeroTokenBudget": 20000,
275
+ "detectors": {
276
+ "DET-06": "block",
277
+ "DET-07": "block",
278
+ "DET-08": "warn",
279
+ "DET-09": "block",
280
+ "DET-19": "block",
281
+ "DET-20": "warn"
282
+ }
283
+ }
284
+ ```
285
+ - **`"COACH"` *(Default)***: Compresses CLI output (`DET-07`), folds repeat file reads (`GUARD-4`), and stages warm rule edits (`DET-09`) automatically while advising on model/cache switches without blocking normal flow.
286
+ - **`"AUTO_PILOT"`**: Enforces strict pre-turn & stop-gate verification locks (e.g., requiring tests to run after source edits before session completion).
287
+ - **`"SILENT"` / `"OFF"`**: Passive telemetry collection only.
288
+
289
+ ### 2. Using Highbeam as an MCP Server (`npx ctxtop mcp`)
290
+ Any MCP-compatible client (**Google Antigravity**, **Claude Code**, **OpenAI Codex CLI**, **Gemini CLI**, **Cursor**, **Windsurf**, or **Claude Desktop**) can auto-configure Highbeam via `npx ctxtop init --cursor --windsurf --codex --gemini-cli` or run standard JSON-RPC stdio directly:
291
+
292
+ ```json
293
+ {
294
+ "mcpServers": {
295
+ "highbeam": {
296
+ "command": "npx",
297
+ "args": ["-y", "ctxtop", "mcp"]
298
+ }
299
+ }
300
+ }
301
+ ```
302
+ Exposes **7 standalone zero-network MCP tools** (`<5ms` response): `horizon_status`, `cache_gravity_check`, `scope_lock_claim`, `export_receipt_pdf`, `horizon_compress_cli`, `horizon_search_logs`, and `horizon_audit_sessions`.
303
+
304
+ For centralized organization deployment (Jamf / Intune / GPO), `CHECKSUMS.sha256` verification, and BYO-Grafana OpenTelemetry telemetry, see [**Enterprise & MDM Deployment Guide**](docs/ENTERPRISE_MDM.md).
305
+
306
+ ---
307
+
308
+ ## 📦 Editions: Free (`MIT` Core + `COACH`) vs. Pro & Team
309
+
310
+ | Feature / Capability | Free Core (`MIT`) | Highbeam Pro (`$15/mo` · 14d Trial) | Team / FinOps (`$39/seat/mo`) |
311
+ | :--- | :---: | :---: | :---: |
312
+ | Simple & Advanced 40-Cell HUD + `5m/1h` Live TTL Timer | ✅ | ✅ | ✅ |
313
+ | Multi-Family FTS5 Compression (`test`, `lint`, `git`, `docker`/`kubectl`) & `ctxtop search` | ✅ | ✅ | ✅ |
314
+ | Automated Repeat-Read Delta Diffs & AST Stubs (`GUARD-4`) | ✅ | ✅ | ✅ |
315
+ | `COACH` Non-Blocking Advisories & 32 Auditable Guards across 5 Hosts | ✅ | ✅ | ✅ |
316
+ | `AUTO_PILOT` Hands-Free Enforcement & Horizon `C_max` Holds | Preview | ✅ | ✅ |
317
+ | 30-Day Chronic Offender Memory & Workspace Savings Ledger | — | ✅ | ✅ |
318
+ | Signed Corporate PDF 1.4 FinOps + GreenOps Receipt (`ctxtop receipt --pdf`) | — | ✅ | ✅ |
319
+ | Shared `.agents/rules/` Governance, MDM Policy & OTel / Grafana Pack | — | — | ✅ |
320
+
321
+ ---
322
+
323
+ ## Deterministic `PreInvocation` Router & 6 Local Sensors
324
+
325
+ When registered in `hooks.json`, `src/hooks/pre_invocation.mjs` evaluates incoming prompts across 8 deterministic router states (**Tier-1 In-Process `PreInvocation`: `~0.1–2.9ms` avg / `~3.4ms` p95** inside a warm V8 isolate; **Tier-2 CLI Hook End-to-End Wall Time on Windows: `~58ms` p50 warm daemon IPC / `~105ms` avg cold fallback (`~25–60ms` POSIX)** including Node process startup):
326
+
327
+ 1. `ALLOW_SILENT`: Immediate pass-through (`{}`) on `!` bypass prefix or healthy turns.
328
+ 2. `ALLOW_ACTIVE_SET`: Silent pass-through when referenced files are already warm in the last 5 turns.
329
+ 3. `ALLOW_PLAN_OR_SUBAGENT`: Silent pass-through during `/plan` mode or subagent delegation.
330
+ 4. `INJECT_CONTEXT_GUARD`: Appends a `systemMessage` warning when target files were modified externally on disk (`DIRTY_SNAP`), have unseen callers (`UNSEEN_CALLERS`), or touch deprecated paths (`LEGACY_POISON`).
331
+ 5. `STEER_SUBAGENT`: Advises `invoke_subagent` when a broad exploratory prompt would pollute a warm `>30k`-token parent context window.
332
+ 6. `HALT_HYGIENE_OR_SAFETY`: Halts execution (or warns in `advisory` mode) on context ceiling breach, 3-strike identical command error loops, or severe duplicate-read dilution.
333
+ 7. `HALT_EFFORT_OR_QUOTA`: Warns when 5-hour/7-day quota falls below the configured floor (`10%`) or when `>600`-line single-shot file rewrites risk output stream truncation.
334
+ 8. `HALT_REWRITE_SCORECARD`: Triggered via `#check` or vague cold-start prompts (`Turn <= 2`), outputting a 4-line prompt rewrite scorecard.
335
+
336
+ ---
337
+
338
+ ## CLI Commands & Forensic Postmortem
339
+
340
+ | Command | Description |
341
+ | :--- | :--- |
342
+ | `npx ctxtop audit [--platform all\|antigravity\|claude\|codex\|gemini\|cursor] [--days 7] [--json]` | Zero-write, hookless 5-host audit of Sludge Tax, cold-cache spikes, and oversized tool dumps. |
343
+ | `npx ctxtop init [--cursor \| --windsurf \| --codex \| --gemini-cli \| --all-hosts]` | Installs Google Antigravity, Claude Code, and 1-command MCP configurations across editors & CLIs. |
344
+ | `npx ctxtop search [<turn-id>] "<keyword>" [--json]` | Searches local SQLite FTS5 offloaded CLI dumps and artifacts via BM25 matching. |
345
+ | `npx ctxtop install --global` | Installs Claude Code `.claude-plugin` manifest, Tier-1/Tier-2 hooks, and terminal `statusLine`. |
346
+ | `npx ctxtop ui [--demo]` | Launches the local HTTP/SSE telemetry daemon (`127.0.0.1`) and interactive WebView (`/` Simple, `/advanced` Advanced). |
347
+ | `npx ctxtop mcp` | Starts the standalone zero-network 7-tool JSON-RPC stdio MCP server (`@ctxtop/mcp`). |
348
+ | `npx ctxtop doctor [--diagnostic]` | Validates hook registration, FTS5 offload readiness, warm-IPC path, model ceilings, 3-way SHA-256 parity, and SQLite health. |
349
+ | `npx ctxtop postmortem [--last N] [--json]` | Scans the last `N` local sessions, classifies root causes (`CONTEXT_ROT_DECAY`, `VERIFICATION_CHURN`, `SPEC_AMBIGUITY`, `CLEAN`), lists top duplicate-read files, and audits Turn-0 MCP schema overhead. |
350
+ | `npx ctxtop receipt [--markdown \| --pdf]` | Exports a SHA-256 verified FinOps + GreenOps token/USD savings receipt for the active workspace. |
351
+ | `npx ctxtop verify [--json]` | Verifies cryptographic SHA-256 integrity of all tracked release files against `CHECKSUMS.sha256`. |
352
+ | `npx ctxtop --roast` | Prints a terminal forensic summary of recent sessions with top duplicate-read file offenders and copy-pasteable remediations. |
353
+ | `npx ctxtop --demo-animate` | Plays the 5-stage terminal crisis simulation across synthetic fixtures. |
354
+
355
+ ---
356
+
357
+ ## Verification & Benchmarks
358
+
359
+ Run the full zero-dependency test and verification suites (**1,060+ tests across 215+ suites** — see [**Empirical Benchmarks**](docs/EMPIRICAL_BENCHMARKS.md) & [**Compression & Antigravity Parity Report**](docs/ANTIGRAVITY_AND_COMPRESSION_BENCHMARK.md)):
360
+
361
+ ```bash
362
+ # Full Coach, UI, & 360° Capability-Proof suite
363
+ npm run test:coach
364
+
365
+ # Claude Code dual-tier Mod, CLI hooks, statusLine, and 5-category ledger suite (195 tests)
366
+ npm run test:claude
367
+
368
+ # Unit & Multi-Harness Wedge suite (89 tests across 31 suites)
369
+ npm run test:unit
370
+
371
+ # Architectural verification suite (Gates 0-6 & Phases 1-7: SQLite read-only locks, JSDOM UI, MCP audit)
372
+ npm run test:gates && npm run test:phases
373
+
374
+ # Reproducible 10-family CLI compression + 12-session Antigravity & 5-host parity benchmark
375
+ npm run bench:parity
376
+
377
+ # Latency benchmark (200 iterations/path: Tier-1 ~2.9ms avg, Tier-2 ~58ms warm IPC / ~105ms cold Windows, ~5.4ms HUD)
378
+ npm run bench
379
+ ```
380
+
381
+ ---
382
+
383
+ ## License
384
+
385
+ MIT © [Gizzant](https://github.com/Gizzant)