ctxtop 0.0.0-stage → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,888 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { canonicalizePath } from '../core/path_canonicalizer.mjs';
6
+ import {
7
+ readSidecarSync,
8
+ writeSidecarAtomicSync,
9
+ writeJsonAtomicSync,
10
+ readToolUsageSync,
11
+ createDefaultSidecar
12
+ } from '../core/sidecar_store.mjs';
13
+ import { resolveAndReadTranscriptIncremental } from '../core/log_resolver.mjs';
14
+ import { classifyHorizonWindow, CATEGORIES } from '../core/horizon_classifier.mjs';
15
+ import { runAllBlindspotSensors } from '../core/blindspot_sensors.mjs';
16
+ import { CATEGORIES as H_CATEGORIES, CATEGORY_METADATA, scaleEffortProfileForCeiling, resolveModelCeiling } from '../core/constants.mjs';
17
+ import { findSessionDirectory, parseTranscriptIncremental, reconcileWorkspaceAndKIs, resolveSessionModel } from '../core/parser.mjs';
18
+ import { classifyHorizon } from '../core/classifier.mjs';
19
+ import { getHomeDir, ensureSupportedNodeVersion } from '../core/paths.mjs';
20
+ import { recordAndDelta } from '../core/history.mjs';
21
+ import { loadSettings, resolveWindow } from '../core/settings.mjs';
22
+ import { measureBaseline } from '../core/baseline.mjs';
23
+ import { updateChronicReads } from '../core/offenders.mjs';
24
+ import { computePlanChurn, gradeProofQuality, detectContextRot } from '../core/session_forensics.mjs';
25
+ import { auditHandoff } from '../core/handoff_audit.mjs';
26
+ import { inspectHostProcesses } from '../core/host_watchdog.mjs';
27
+ import { loadFlightcheckConfig } from '../core/config.mjs';
28
+ import { buildDemoHorizonState, DEMO_SCENARIOS } from '../demo/synthetic_states.mjs';
29
+ import { buildActionQueue, formatActionQueueAnsi } from '../core/action_queue.mjs';
30
+ import { renderHorizonPanelHtml } from '../core-isomorphic/ui/horizonPanelHtml.mjs';
31
+
32
+ export { buildActionQueue, formatActionQueueAnsi, renderHorizonPanelHtml };
33
+
34
+ const ANSI_ESCAPE_RE = /\x1b\[[0-9;]*m/g;
35
+
36
+ export function stripAnsi(str = '') {
37
+ return String(str).replace(ANSI_ESCAPE_RE, '');
38
+ }
39
+
40
+ export function visibleWidth(str = '') {
41
+ return Array.from(stripAnsi(str)).length;
42
+ }
43
+
44
+ export function clampAnsiLine(line = '', maxCols = 80) {
45
+ const limit = Math.max(10, Number(maxCols) || 80);
46
+ const raw = String(line || '');
47
+ if (visibleWidth(raw) <= limit) return raw;
48
+ let vis = 0;
49
+ let out = '';
50
+ let i = 0;
51
+ let hadAnsi = false;
52
+ const target = Math.max(1, limit - 1);
53
+ while (i < raw.length && vis < target) {
54
+ if (raw[i] === '\x1b') {
55
+ const m = raw.slice(i).match(/^\x1b\[[0-9;]*m/);
56
+ if (m) {
57
+ out += m[0];
58
+ i += m[0].length;
59
+ hadAnsi = true;
60
+ continue;
61
+ }
62
+ }
63
+ const cp = raw.codePointAt(i);
64
+ const ch = String.fromCodePoint(cp);
65
+ out += ch;
66
+ i += ch.length;
67
+ vis += 1;
68
+ }
69
+ return `${out}…${hadAnsi ? '\x1b[0m' : ''}`;
70
+ }
71
+
72
+ export function clampAnsiText(text = '', maxCols = 80) {
73
+ return String(text || '')
74
+ .split('\n')
75
+ .map(l => clampAnsiLine(l, maxCols))
76
+ .join('\n');
77
+ }
78
+
79
+ const FALLBACK_BAR = '\x1b[38;5;244m[░░░░░░░░░░░░░░░░░░░░] Purity: 100% | Noise: 0k | Quota: 100% | Effort: OK\x1b[0m';
80
+
81
+ function safeExitFallback() {
82
+ try { console.log(FALLBACK_BAR); } catch {}
83
+ process.exit(0);
84
+ }
85
+
86
+ const ANSI_COLORS = {
87
+ [CATEGORIES.ANCHOR_CORE]: '\x1b[38;5;51m█\x1b[0m',
88
+ [CATEGORIES.ANCHOR_SCHEMA]: '\x1b[38;5;30m▒\x1b[0m',
89
+ [CATEGORIES.MEMORY_KI]: '\x1b[38;5;141m▓\x1b[0m',
90
+ [CATEGORIES.MEMORY_BLEED]: '\x1b[38;5;205m▓\x1b[0m',
91
+ [CATEGORIES.ACTIVE_SET]: '\x1b[38;5;82m█\x1b[0m',
92
+ [CATEGORIES.STALE_DUP]: '\x1b[38;5;214m▒\x1b[0m',
93
+ [CATEGORIES.DIRTY_SNAP]: '\x1b[38;5;214m▒\x1b[0m',
94
+ [CATEGORIES.LEGACY_POISON]: '\x1b[38;5;208m▒\x1b[0m',
95
+ [CATEGORIES.DEAD_ERROR]: '\x1b[38;5;196m▓\x1b[0m',
96
+ [CATEGORIES.FREE_HEADROOM]: '\x1b[38;5;240m░\x1b[0m'
97
+ };
98
+
99
+ async function readStdinSafe(timeoutMs = 150) {
100
+ if (process.stdin.isTTY) return {};
101
+ return new Promise((resolve) => {
102
+ let raw = '';
103
+ const timer = setTimeout(() => {
104
+ resolve(parseJsonSafe(raw));
105
+ }, timeoutMs);
106
+
107
+ process.stdin.setEncoding('utf8');
108
+ process.stdin.on('data', chunk => { raw += chunk; });
109
+ process.stdin.on('end', () => {
110
+ clearTimeout(timer);
111
+ resolve(parseJsonSafe(raw));
112
+ });
113
+ process.stdin.on('error', () => {
114
+ clearTimeout(timer);
115
+ resolve({});
116
+ });
117
+ });
118
+ }
119
+
120
+ function parseJsonSafe(str) {
121
+ try {
122
+ const trimmed = str ? str.trim() : '';
123
+ return trimmed ? JSON.parse(trimmed) : {};
124
+ } catch {
125
+ return {};
126
+ }
127
+ }
128
+
129
+ function scanKnowledgeItems() {
130
+ const home = process.env.USERPROFILE || process.env.HOME || os.homedir();
131
+ const kiRoot = path.join(home, '.gemini', 'antigravity', 'knowledge');
132
+ const items = [];
133
+ if (!fs.existsSync(kiRoot)) return items;
134
+
135
+ try {
136
+ const dirs = fs.readdirSync(kiRoot, { withFileTypes: true });
137
+ for (const d of dirs) {
138
+ if (d.isDirectory()) {
139
+ const metaPath = path.join(kiRoot, d.name, 'metadata.json');
140
+ if (fs.existsSync(metaPath)) {
141
+ try {
142
+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
143
+ items.push(meta);
144
+ } catch {}
145
+ }
146
+ }
147
+ }
148
+ } catch {}
149
+ return items;
150
+ }
151
+
152
+ export async function runHud(options = {}) {
153
+ try {
154
+ const stdinData = options.stdinData !== undefined ? options.stdinData : await readStdinSafe(150);
155
+ const columns = options.columns || process.stdout.columns || 120;
156
+ const conversationId = stdinData.conversation_id || stdinData.session_id || 'default_session';
157
+ const workspacePath = canonicalizePath(stdinData.workspacePath || process.cwd());
158
+ const config = options.configOverride || loadFlightcheckConfig();
159
+
160
+ let sidecar = readSidecarSync(conversationId);
161
+ if (!sidecar.conversationId) {
162
+ sidecar = createDefaultSidecar(conversationId, workspacePath);
163
+ }
164
+
165
+ // Extract native statusLine telemetry
166
+ const ctxWindow = stdinData.context_window || {};
167
+ const totalInputTokens = ctxWindow.total_input_tokens || sidecar.telemetry.totalInputTokens || 0;
168
+ const usedPercentage = ctxWindow.used_percentage || sidecar.telemetry.usedPercentage || 0;
169
+ const exceeds200k = Boolean(ctxWindow.exceeds_200k_tokens);
170
+ const modelName = stdinData.modelName || stdinData.model?.id || sidecar.sessionMeta.activeModel || 'gemini-3.8-flash';
171
+ const mode = stdinData.mode || sidecar.telemetry.mode || 'auto';
172
+ const agentState = stdinData.agent_state || sidecar.telemetry.agentState || 'idle';
173
+
174
+ // Extract minimum quota fraction
175
+ let minQuotaFraction = 1.0;
176
+ if (stdinData.quota) {
177
+ if (typeof stdinData.quota.remaining_fraction === 'number') {
178
+ minQuotaFraction = stdinData.quota.remaining_fraction;
179
+ } else if (stdinData.quota.buckets) {
180
+ for (const b of Object.values(stdinData.quota.buckets)) {
181
+ if (typeof b.remaining_fraction === 'number') {
182
+ minQuotaFraction = Math.min(minQuotaFraction, b.remaining_fraction);
183
+ }
184
+ }
185
+ }
186
+ }
187
+
188
+ // Incremental log resolution
189
+ const logCursor = sidecar.cursor || {};
190
+ const logState = resolveAndReadTranscriptIncremental(conversationId, logCursor);
191
+
192
+ // Knowledge Items & Sensors
193
+ const kis = scanKnowledgeItems();
194
+ const toolLedger = readToolUsageSync();
195
+ const sensorResults = runAllBlindspotSensors({
196
+ stepEvents: logState.parsedEvents,
197
+ sidecarState: sidecar,
198
+ workspacePath,
199
+ targetFiles: sidecar.fileState.activeSetPaths,
200
+ activeSetPaths: sidecar.fileState.activeSetPaths,
201
+ toolUsageLedger: toolLedger,
202
+ promptText: '',
203
+ config
204
+ });
205
+
206
+ // 40-Cell Classifier
207
+ const classification = classifyHorizonWindow(
208
+ logState.parsedEvents,
209
+ { total_input_tokens: totalInputTokens, modelName },
210
+ workspacePath,
211
+ kis,
212
+ config,
213
+ sensorResults
214
+ );
215
+
216
+ // Update sidecar atomically
217
+ sidecar.updatedAtMs = Date.now();
218
+ sidecar.cursor = { filePath: logState.filePath, byteOffset: logState.byteOffset, tier: logState.tier };
219
+ sidecar.sessionMeta.activeModel = modelName;
220
+ sidecar.sessionMeta.inPlanMode = mode === 'plan';
221
+ sidecar.telemetry = {
222
+ totalInputTokens: classification.totalInputTokens,
223
+ usedPercentage,
224
+ exceeds200kTokens: exceeds200k,
225
+ signalPurityPct: classification.metrics.signalPurityPct,
226
+ sludgeTaxUsdPerTurn: classification.metrics.sludgeTaxUsdPerTurn,
227
+ amputationRisk: classification.flags.amputationRisk,
228
+ confidence: classification.confidence || 'HIGH',
229
+ parseHealth: classification.parseHealth || null,
230
+ ceilingSource: classification.model?.ceilingSource || 'fallback',
231
+ agentState,
232
+ mode,
233
+ quota: {
234
+ remaining_fraction: minQuotaFraction,
235
+ remaining_amount: stdinData.quota?.remaining_amount ?? null,
236
+ reset_in_seconds: stdinData.quota?.reset_in_seconds ?? 0,
237
+ buckets: stdinData.quota?.buckets || {}
238
+ },
239
+ history: (sidecar.telemetry.history || []).slice(-19).concat([{
240
+ turn: sidecar.sessionMeta.turnCount,
241
+ purity: classification.metrics.signalPurityPct,
242
+ sludge: classification.metrics.sludgeTaxUsdPerTurn
243
+ }])
244
+ };
245
+ sidecar.cells = classification.cells;
246
+ sidecar.fileState = {
247
+ ...sidecar.fileState,
248
+ activeSetPaths: classification.fileState.activeSetPaths,
249
+ staleDupPaths: classification.fileState.staleDupPaths,
250
+ dirtySnapshotPaths: sensorResults.dirtySnapshotPaths,
251
+ legacyPoisonPaths: classification.fileState.legacyPoisonPaths,
252
+ unseenCallers: sensorResults.unseenCallers,
253
+ streamCutoffRiskFiles: sensorResults.streamCutoffRiskFiles,
254
+ foreignBleedKiIds: classification.fileState.foreignBleedKiIds
255
+ };
256
+ const planChurn = computePlanChurn(logState.parsedEvents, config);
257
+ const proofQuality = gradeProofQuality(logState.parsedEvents);
258
+ const contextRot = detectContextRot(logState.parsedEvents, {
259
+ totalActiveTokens: totalInputTokens,
260
+ correctionCount: 0,
261
+ lateStageTaskChurn: planChurn.lateStageTaskChurn,
262
+ signalPurityPct: classification.metrics.signalPurityPct
263
+ }, config);
264
+ const handoff = auditHandoff(workspacePath, {
265
+ planChurn,
266
+ errorLoop: { loop: sensorResults.threeStrikeLoop, fingerprint: sensorResults.loopFingerprint },
267
+ deadErrors: { isErrorLoop: sensorResults.threeStrikeLoop },
268
+ activeSignal: { taskMdTurnsBehind: 0 }
269
+ });
270
+
271
+ sidecar.sensors = {
272
+ schemaTaxPct: sensorResults.schemaTaxPct,
273
+ unusedMcpServers: sensorResults.unusedMcpServers,
274
+ oversizedPayloadDetected: sensorResults.oversizedPayloadDetected,
275
+ quotaFloorBreached: sensorResults.quotaFloorBreached,
276
+ planToFlashHandoffNeeded: sensorResults.planToFlashHandoffNeeded,
277
+ threeStrikeLoop: sensorResults.threeStrikeLoop,
278
+ loopFingerprint: sensorResults.loopFingerprint || null,
279
+ uncheckpointedGitDrift: sensorResults.uncheckpointedGitDrift,
280
+ dirtyGitFileCount: sensorResults.dirtyGitFileCount,
281
+ planRevisions: planChurn.planRevisions,
282
+ planRevisionWarn: planChurn.warn,
283
+ proofQuality: proofQuality.grade,
284
+ proofQualityReason: proofQuality.reason,
285
+ splitRecommended: contextRot.splitRecommended,
286
+ splitReason: contextRot.reason
287
+ };
288
+
289
+ sidecar.handoff = {
290
+ result: handoff.result,
291
+ targetFile: handoff.targetFile,
292
+ failingChecks: handoff.checks.filter(c => !c.pass).map(c => c.name),
293
+ fixes: handoff.fixes
294
+ };
295
+
296
+ writeSidecarAtomicSync(conversationId, sidecar);
297
+
298
+ // Format ANSI status line
299
+ const isAmputation = classification.flags.amputationRisk;
300
+ const isFullMode = columns >= 120;
301
+ const cellCount = isFullMode ? 40 : 20;
302
+ const downsampleRatio = 40 / cellCount;
303
+
304
+ let glyphStrip = '';
305
+ for (let i = 0; i < cellCount; i++) {
306
+ const origIdx = Math.floor(i * downsampleRatio);
307
+ const cell = classification.cells[origIdx] || { dominantCategory: CATEGORIES.FREE_HEADROOM };
308
+ const glyph = ANSI_COLORS[cell.dominantCategory] || ANSI_COLORS[CATEGORIES.FREE_HEADROOM];
309
+
310
+ if (isAmputation && origIdx === 0) {
311
+ glyphStrip += '\x1b[38;5;196m![\x1b[0m';
312
+ }
313
+ glyphStrip += glyph;
314
+ if (isAmputation && origIdx === 7 && (isFullMode ? i === 7 : i === 3)) {
315
+ glyphStrip += '\x1b[38;5;196m]!\x1b[0m';
316
+ }
317
+ }
318
+
319
+ const quotaPct = Math.round(minQuotaFraction * 100);
320
+ const purity = classification.metrics.signalPurityPct;
321
+ const noiseK = Math.round((classification.metrics.sludgeTokens || 0) / 1000);
322
+ const activeK = Math.round((classification.totalInputTokens || 0) / 1000);
323
+ const resolvedMaxTokens = classification.model?.maxTokens ||
324
+ resolveModelCeiling(modelName, stdinData.context_window, { useLegacyDefault: false, config });
325
+ const maxK = Math.round(resolvedMaxTokens / 1000);
326
+ const usedPct = maxK > 0 ? Math.round((activeK / maxK) * 100) : 0;
327
+ const modeTag = classification.workloadMode?.tag || '[Mode: Read-Heavy Audit]';
328
+ let outputLine = '';
329
+
330
+ if (isFullMode) {
331
+ const effortStatus = sensorResults.threeStrikeLoop ? 'LOOP_HALT' : (sensorResults.quotaFloorBreached ? 'QUOTA_LOW' : 'OK');
332
+ const cacheHitPct = Math.max(0, Number(classification.metrics?.cacheHitPct ?? 0) || 0);
333
+ const ttlSec = Math.max(0, Math.round(Number(classification.metrics?.ttlRemainingSec ?? 0) || 0));
334
+ let extraHints = '';
335
+ if (planChurn.warn) extraHints += ` | Plan: ${planChurn.planRevisions} revs ⚠`;
336
+ if (handoff.result === 'NEEDS_FIXES') extraHints += ' | Handoff: Needs fixes';
337
+ outputLine = `[${glyphStrip}] ${activeK}k / ${maxK}k · ${usedPct}% | Cache Hit: ${cacheHitPct}% | Waste: ${noiseK}k tok | TTL: ${ttlSec}s | Purity: ${purity}% | Noise: ${noiseK}k tok | Quota: ${quotaPct}% | ${modeTag} | Effort: ${effortStatus}${extraHints}`;
338
+ } else {
339
+ outputLine = `[${glyphStrip}] ${activeK}k/${maxK}k·${usedPct}% | P:${purity}% | N:${noiseK}k | Q:${quotaPct}%`;
340
+ }
341
+
342
+ if (columns <= 80) {
343
+ outputLine = clampAnsiText(outputLine, Math.min(columns, 80));
344
+ }
345
+
346
+ if (!options.silent) {
347
+ console.log(outputLine);
348
+ }
349
+ return { output: outputLine, sidecar };
350
+ } catch {
351
+ safeExitFallback();
352
+ }
353
+ }
354
+
355
+ export function formatDemoScenarioAnsi(scenarioId = 5, options = {}) {
356
+ const maxCols = options.columns && options.columns <= 80
357
+ ? Math.min(Number(options.columns) || 80, 80)
358
+ : 80;
359
+ const state = buildDemoHorizonState(scenarioId);
360
+ const meta = state.demoMeta || DEMO_SCENARIOS[4];
361
+ const isAmputation = state.amputation.inAmputationZone;
362
+
363
+ let glyphStrip = '';
364
+ for (let i = 0; i < 40; i++) {
365
+ const cell = state.cells[i];
366
+ const cat = cell?.hudCategory || CATEGORIES.FREE_HEADROOM;
367
+ const glyph = ANSI_COLORS[cat] || ANSI_COLORS[CATEGORIES.FREE_HEADROOM];
368
+ if (isAmputation && i === 0) glyphStrip += '\x1b[38;5;196m![\x1b[0m';
369
+ glyphStrip += glyph;
370
+ if (isAmputation && i === 7) glyphStrip += '\x1b[38;5;196m]!\x1b[0m';
371
+ }
372
+
373
+ const activeK = Math.round(state.window.totalActiveTokens / 1000);
374
+ const maxK = Math.round(state.window.maxTokens / 1000);
375
+ const usedPct = maxK > 0 ? Math.round((activeK / maxK) * 100) : 0;
376
+ const purity = state.metrics.signalPurityPct;
377
+ const noiseK = Math.round(state.metrics.sludgeTokens / 1000);
378
+ const quotaPct = state.quota.sprint5h.remainingPct;
379
+ const cacheHitPct = Math.max(0, Number(state.quota?.cache?.hitRatePct ?? 0) || 0);
380
+ const ttlSec = Math.max(0, Math.round(Number(state.quota?.cache?.ttlRemainingSec ?? 0) || 0));
381
+ const modeTag = state.workloadMode?.tag || '[Mode: Read-Heavy Audit]';
382
+ const statusColor = isAmputation ? '\x1b[38;5;196m' : (purity < 60 ? '\x1b[38;5;214m' : '\x1b[38;5;82m');
383
+
384
+ const aqAnsi = formatActionQueueAnsi(state);
385
+ const aqLines = aqAnsi ? aqAnsi.split('\n').filter(Boolean) : [];
386
+ const boxWidth = Math.max(40, Math.min(78, maxCols));
387
+ const headerLabel = `╭── Flight Check v3.3 (${meta.routerState}) `;
388
+ const headerDashCount = Math.max(1, boxWidth - visibleWidth(headerLabel) - 1);
389
+ const footerLine = `╰${'─'.repeat(Math.max(1, boxWidth - 2))}╯`;
390
+
391
+ const rawLines = [
392
+ `\x1b[1m\x1b[38;5;51m${meta.title}\x1b[0m`,
393
+ `\x1b[38;5;245m${modeTag} · "${meta.complaint}"\x1b[0m`,
394
+ `[${glyphStrip}] ${statusColor}${activeK}k / ${maxK}k · ${usedPct}%\x1b[0m | Purity: ${statusColor}${purity}%\x1b[0m`,
395
+ `Cache Hit: ${cacheHitPct}% | Waste: ${noiseK}k tok | TTL: ${ttlSec}s | Quota: ${quotaPct}%`,
396
+ ...aqLines,
397
+ `\x1b[38;5;244m${headerLabel}${'─'.repeat(headerDashCount)}╮\x1b[0m`,
398
+ `\x1b[38;5;244m│\x1b[0m 1. PROMPT : "${meta.fixture.prompt.slice(0, 56)}"`,
399
+ `\x1b[38;5;244m│\x1b[0m 2. HORIZON: [${activeK}k/${maxK}k·${usedPct}% | Cache:${cacheHitPct}% | Waste:${noiseK}k | TTL:${ttlSec}s | Q:${quotaPct}%]`,
400
+ `\x1b[38;5;244m│\x1b[0m 3. ACTION : \x1b[38;5;82m${meta.recommendedAction}\x1b[0m`,
401
+ `\x1b[38;5;244m│\x1b[0m 4. REWRITE: \x1b[38;5;51m"${meta.rewrite}"\x1b[0m`,
402
+ `\x1b[38;5;244m${footerLine}\x1b[0m`
403
+ ];
404
+ const lines = rawLines.map(l => clampAnsiLine(l, maxCols));
405
+ return { text: lines.join('\n'), state };
406
+ }
407
+
408
+ export async function runDemoShowcase({ scenarioId = null, animate = false, columns = process.stdout.columns || 80 } = {}) {
409
+ const maxCols = columns <= 80 ? Math.min(columns, 80) : 80;
410
+ console.log('\n' + clampAnsiLine('\x1b[1m\x1b[38;5;51m⚡ HIGHBEAM (ctxtop v3.4.0) — 40-Cell Context Telemetry & Flight Check\x1b[0m', maxCols));
411
+ console.log(clampAnsiLine('\x1b[38;5;244mLegend: \x1b[38;5;51m█ Anchor\x1b[0m \x1b[38;5;141m▓ Memory\x1b[0m \x1b[38;5;205m▓ Bleed\x1b[0m \x1b[38;5;214m▒ Stale\x1b[0m \x1b[38;5;196m▓ Error\x1b[0m \x1b[38;5;82m█ Active\x1b[0m \x1b[38;5;196m![..]! (>140k)\x1b[0m', maxCols) + '\n');
412
+
413
+ const ids = scenarioId ? [Number(scenarioId)] : (animate ? [2, 4, 5, 6, 7] : [5]);
414
+ for (let idx = 0; idx < ids.length; idx++) {
415
+ const { text } = formatDemoScenarioAnsi(ids[idx], { columns: maxCols });
416
+ console.log(text);
417
+ if (idx < ids.length - 1) {
418
+ console.log('');
419
+ if (animate) await new Promise(r => setTimeout(r, 450));
420
+ }
421
+ }
422
+ console.log('\n' + clampAnsiLine('\x1b[38;5;245mTry: npx attention-horizon-antigravity --demo-animate | Web UI: npx attention-horizon-antigravity ui\x1b[0m', maxCols) + '\n');
423
+ }
424
+
425
+ export function isHudMain(argv1 = process.argv[1], metaUrl = import.meta.url) {
426
+ if (!argv1) return false;
427
+ try {
428
+ return fs.realpathSync(argv1) === fs.realpathSync(fileURLToPath(metaUrl));
429
+ } catch {
430
+ return path.resolve(argv1) === path.resolve(fileURLToPath(metaUrl));
431
+ }
432
+ }
433
+
434
+ // Auto-run if executed as main CLI script
435
+ const isMain = isHudMain();
436
+ if (isMain) {
437
+ process.on('uncaughtException', () => safeExitFallback());
438
+ process.on('unhandledRejection', () => safeExitFallback());
439
+ const args = process.argv.slice(2);
440
+ if (args.includes('--emit-widget')) {
441
+ const emitIdx = args.indexOf('--emit-widget');
442
+ const outIdx = args.indexOf('--out');
443
+ let targetPath = null;
444
+ if (outIdx !== -1 && args[outIdx + 1]) {
445
+ targetPath = args[outIdx + 1];
446
+ } else if (emitIdx !== -1 && args[emitIdx + 1] && !args[emitIdx + 1].startsWith('-')) {
447
+ targetPath = args[emitIdx + 1];
448
+ } else {
449
+ targetPath = path.resolve('horizon_widget.html');
450
+ }
451
+
452
+ emitHorizonWidget({ out: targetPath, silent: false })
453
+ .then(() => process.exit(0))
454
+ .catch(() => safeExitFallback());
455
+ } else if (args.includes('--demo') || args.includes('--demo-animate')) {
456
+ const scenIdx = args.indexOf('--scenario');
457
+ const scenarioId = scenIdx !== -1 ? Number(args[scenIdx + 1]) : null;
458
+ runDemoShowcase({ scenarioId, animate: args.includes('--demo-animate') })
459
+ .then(() => process.exit(0))
460
+ .catch(() => safeExitFallback());
461
+ } else if (process.stdin.isTTY || args.includes('--live')) {
462
+ runCLI().then(() => process.exit(0)).catch(() => safeExitFallback());
463
+ } else {
464
+ readStdinSafe(150).then((stdinData) => {
465
+ if (stdinData && Object.keys(stdinData).length > 0) {
466
+ return runHud({ stdinData });
467
+ }
468
+ // If non-TTY stdin had malformed content vs empty stdin:
469
+ // runHud handles fallback bar for statusLine contracts when --hud-legacy or piped
470
+ return runHud({ stdinData });
471
+ }).then(() => process.exit(0)).catch(() => safeExitFallback());
472
+ }
473
+ }
474
+
475
+ /**
476
+ * Adapts an Antigravity `classifyHorizon` state object into the Claude Code
477
+ * static HUD contract consumed by `renderHorizonPanelHtml`. Passes native
478
+ * Claude Code states through unchanged.
479
+ */
480
+ export function adaptClassifierStateForStaticHud(state = {}, options = {}) {
481
+ const isAntigravityState = Boolean(
482
+ state &&
483
+ typeof state === 'object' &&
484
+ state.window &&
485
+ typeof state.window.totalActiveTokens === 'number' &&
486
+ !state.contextWindow &&
487
+ typeof state.totalInputTokens !== 'number'
488
+ );
489
+ if (!isAntigravityState) {
490
+ return { state, options };
491
+ }
492
+
493
+ const totalInputTokens = Math.max(0, Number(state.window.totalActiveTokens || 0));
494
+ const contextCeiling = Math.max(0, Number(state.window.maxTokens || 0));
495
+ const breakdown = state.breakdown || {};
496
+ const systemTokens = Math.max(0, Number(breakdown.ANCHOR ?? state.baseline?.totalEst ?? 0));
497
+ const dupTok = Math.max(0, Number(breakdown.STALE_DUPLICATE ?? breakdown.DUPLICATE_READ ?? 0));
498
+ const oldHistTok = Math.max(0, Number(breakdown.STALE_TURN ?? 0));
499
+ const deadErrTok = Math.max(0, Number(breakdown.DEAD_ERROR ?? 0));
500
+ const bleedTok = Math.max(0, Number(breakdown.FOREIGN_BLEED ?? 0));
501
+ const distractorTokens = dupTok + oldHistTok + deadErrTok + bleedTok;
502
+
503
+ const cacheObj = state.quota?.cache || {};
504
+ const ttlSec = Math.max(0, Math.round(Number(cacheObj.ttlRemainingSec || 0) || 0));
505
+ const hitPct = Math.max(0, Math.min(100, Math.round(Number(cacheObj.hitRatePct || 0) || 0)));
506
+ const cacheReadTokens = Math.max(0, Number(cacheObj.cacheReadTokens || 0));
507
+ const isWarm = Boolean(
508
+ !cacheObj.isCacheCold &&
509
+ !cacheObj.prefixBustDetected &&
510
+ ttlSec > 0 &&
511
+ (cacheReadTokens > 0 || hitPct > 0)
512
+ );
513
+ const nonAnchorOrDistractor = Math.max(0, totalInputTokens - systemTokens - distractorTokens);
514
+
515
+ const adaptedState = {
516
+ sessionId: state.sessionId || 'horizon-hud',
517
+ model: state.model?.id || 'claude-sonnet-5-5',
518
+ modelLabel: state.model?.displayName || state.model?.rawLabel || state.model?.id || 'claude-sonnet-5-5',
519
+ totalInputTokens,
520
+ contextCeiling: contextCeiling > 0 ? contextCeiling : undefined,
521
+ systemTokens,
522
+ distractorTokens,
523
+ cachedTokens: isWarm ? nonAnchorOrDistractor : 0,
524
+ cacheReadTokens,
525
+ uncachedInputTokens: isWarm ? 0 : nonAnchorOrDistractor,
526
+ promptCache: {
527
+ warm: isWarm,
528
+ ttlRemainingSec: isWarm ? ttlSec : 0,
529
+ ttlTier: '5m'
530
+ },
531
+ cacheRoi: {
532
+ cacheHitRatio: hitPct / 100
533
+ },
534
+ amnesiaRisk: Boolean(
535
+ state.amputation?.amputationCrisis ||
536
+ state.amputation?.inAmputationZone ||
537
+ state.telemetry?.amputationRisk
538
+ ),
539
+ sessionTimeline: state.sessionTimeline || null,
540
+ autoFixLog: state.autoFixLog || null,
541
+ compactCommand: typeof state.compaction?.parameterizedCommand === 'string' &&
542
+ state.compaction.parameterizedCommand.startsWith('/compact ')
543
+ ? state.compaction.parameterizedCommand
544
+ : '/compact'
545
+ };
546
+
547
+ const mergedOptions = { ...options };
548
+ if (!Array.isArray(mergedOptions.offenders)) {
549
+ const derivedOffenders = [];
550
+ const seen = new Set();
551
+ const bs = state.brainSignals || {};
552
+ const topFiles = Array.isArray(bs.duplicateReads?.topFiles) ? bs.duplicateReads.topFiles : [];
553
+ for (const f of topFiles) {
554
+ const target = f?.path || f?.file;
555
+ const wastedTokens = Number(f?.wastedTokens ?? f?.tokens ?? 0);
556
+ if (!target || wastedTokens <= 0) continue;
557
+ seen.add(String(target).toLowerCase());
558
+ derivedOffenders.push({
559
+ target,
560
+ occurrences: Number(f.occurrences || f.reads || 1),
561
+ wastedTokens,
562
+ category: '[D]'
563
+ });
564
+ }
565
+ for (const o of (Array.isArray(state.offenders) ? state.offenders : [])) {
566
+ const rawTarget = String(o?.target || '');
567
+ const wastedTokens = Number(o?.wastedTokens || 0);
568
+ if (!rawTarget || wastedTokens <= 0) continue;
569
+ if (rawTarget === 'Foreign Bleed Knowledge') continue;
570
+ const key = rawTarget.toLowerCase();
571
+ if (seen.has(key)) continue;
572
+ seen.add(key);
573
+ derivedOffenders.push({
574
+ target: rawTarget,
575
+ occurrences: Number(o.occurrences || 1),
576
+ wastedTokens,
577
+ category: '[D]'
578
+ });
579
+ }
580
+ if (bleedTok > 0) {
581
+ derivedOffenders.push({
582
+ target: 'Cross-project memory bleed (foreign KIs)',
583
+ occurrences: 1,
584
+ wastedTokens: bleedTok,
585
+ category: '[D]'
586
+ });
587
+ }
588
+ for (const b of (Array.isArray(bs.blowupSteps) ? bs.blowupSteps : [])) {
589
+ const wastedTokens = Number(b?.tokens || 0);
590
+ if (wastedTokens <= 0) continue;
591
+ const isFile = b.payload?.kind === 'file' && Boolean(b.payload?.path);
592
+ const target = isFile ? b.payload.path : (b.payload?.detail || b.target || 'Output spike');
593
+ const key = String(target).toLowerCase();
594
+ if (seen.has(key)) continue;
595
+ seen.add(key);
596
+ derivedOffenders.push({
597
+ target,
598
+ occurrences: 1,
599
+ wastedTokens,
600
+ category: isFile ? '[D]' : '[W]'
601
+ });
602
+ }
603
+ for (const srv of (Array.isArray(bs.mcpAudit?.unusedEagerServers) ? bs.mcpAudit.unusedEagerServers : [])) {
604
+ const schemaTokens = Number(srv?.schemaTokens || 0);
605
+ if (!srv?.name || schemaTokens <= 0) continue;
606
+ derivedOffenders.push({
607
+ target: srv.name,
608
+ occurrences: 1,
609
+ wastedTokens: schemaTokens,
610
+ category: '[S]'
611
+ });
612
+ }
613
+ derivedOffenders.sort((a, b) => (b.wastedTokens || 0) - (a.wastedTokens || 0));
614
+ mergedOptions.offenders = derivedOffenders;
615
+ }
616
+
617
+ if (!mergedOptions.breakerVerdict) {
618
+ const tripped = state.coachState?.detectors?.tripped;
619
+ const isErrLoop = Boolean(state.brainSignals?.deadErrors?.isErrorLoop);
620
+ const errCount = Number(state.brainSignals?.deadErrors?.errorCount || 0);
621
+ if (state.amputation?.amputationCrisis) {
622
+ mergedOptions.breakerVerdict = {
623
+ triggered: true,
624
+ detectorId: tripped?.detectorId || 'CRISIS',
625
+ reason: tripped?.reason || `Context truncation crisis (${Math.round(totalInputTokens / 1000)}k used — oldest rules at risk).`
626
+ };
627
+ } else if (tripped && tripped.detectorId) {
628
+ mergedOptions.breakerVerdict = {
629
+ triggered: true,
630
+ detectorId: tripped.detectorId,
631
+ reason: tripped.reason || `${tripped.detectorId} guard triggered.`
632
+ };
633
+ } else if (isErrLoop) {
634
+ mergedOptions.breakerVerdict = {
635
+ triggered: true,
636
+ detectorId: 'ERR-LOOP',
637
+ reason: `Stuck error loop (${errCount}x failing attempts). Pause retries and isolate a minimal repro.`
638
+ };
639
+ }
640
+ }
641
+
642
+ if (state.savings && mergedOptions.sessionSavedTokens === undefined) {
643
+ const sessTok = Math.max(0, Number(state.savings?.session?.totalPhysicalTokens ?? state.savings?.session?.totalTokens ?? 0));
644
+ const sessUsd = Math.max(0, Number(state.savings?.session?.estimatedInputValueUsd ?? state.savings?.session?.estimatedUsd ?? Number(((sessTok / 1_000_000) * 2).toFixed(2))));
645
+ const wsTok = Math.max(sessTok, Number(state.savings?.workspace30d?.totalPhysicalTokens ?? state.savings?.workspace30d?.totalTokens ?? 0));
646
+ const wsUsd = Math.max(sessUsd, Number(state.savings?.workspace30d?.estimatedInputValueUsd ?? state.savings?.workspace30d?.estimatedUsd ?? Number(((wsTok / 1_000_000) * 2).toFixed(2))));
647
+ mergedOptions.sessionSavedTokens = sessTok;
648
+ mergedOptions.sessionSavedUSD = sessUsd;
649
+ mergedOptions.workspace30dSavedTokens = wsTok;
650
+ mergedOptions.workspace30dSavedUSD = wsUsd;
651
+ if (mergedOptions.includeDiskLedger === undefined) {
652
+ mergedOptions.includeDiskLedger = false;
653
+ }
654
+ }
655
+
656
+ return { state: adaptedState, options: mergedOptions };
657
+ }
658
+
659
+ /**
660
+ * Renders the static HTML HUD from either an Antigravity `classifyHorizon`
661
+ * state or a native Claude Code state.
662
+ */
663
+ export function renderClassifierHudHtml(state = {}, options = {}) {
664
+ const { state: adaptedState, options: mergedOptions } = adaptClassifierStateForStaticHud(state, options);
665
+ return renderHorizonPanelHtml(adaptedState, mergedOptions);
666
+ }
667
+
668
+ /**
669
+ * Formats the single-line ANSI CLI status bar for a `classifyHorizon` state
670
+ * clamped cleanly to `columns` when <= 80.
671
+ */
672
+ export function formatCliStatusLine(state = {}, { columns = 120 } = {}) {
673
+ let cellCount = 40;
674
+ if (columns < 80) cellCount = 10;
675
+ else if (columns < 120) cellCount = 20;
676
+
677
+ const downsampleRatio = 40 / cellCount;
678
+ const isAmputation = Boolean(state.amputation?.inAmputationZone);
679
+ const isCrisis = Boolean(state.amputation?.amputationCrisis);
680
+
681
+ let bar = isCrisis ? '\x1b[48;5;196m\x1b[38;5;255m![ 🚨 \x1b[0m ' : (isAmputation ? '\x1b[38;5;196m![\x1b[0m' : '[');
682
+ for (let i = 0; i < cellCount; i++) {
683
+ const origStart = Math.floor(i * downsampleRatio);
684
+ const origEnd = Math.floor((i + 1) * downsampleRatio);
685
+ const slice = (state.cells || []).slice(origStart, origEnd);
686
+ const dominant = slice[0]?.dominantCategory || H_CATEGORIES.FREE_HEADROOM;
687
+ const meta = CATEGORY_METADATA[dominant] || CATEGORY_METADATA.FREE_HEADROOM;
688
+ if (slice.some(c => c.isCrisisCell)) {
689
+ bar += `\x1b[48;5;196m\x1b[38;5;255m${meta.symbol}\x1b[0m`;
690
+ } else {
691
+ bar += `${meta.ansiCode}${meta.symbol}\x1b[0m`;
692
+ }
693
+ }
694
+ bar += isCrisis ? ' \x1b[48;5;196m\x1b[38;5;255m]!\x1b[0m' : (isAmputation ? '\x1b[38;5;196m]!\x1b[0m' : ']');
695
+
696
+ const activeK = Math.round((state.window?.totalActiveTokens || 0) / 1000);
697
+ const maxK = Math.round((state.window?.maxTokens || 0) / 1000);
698
+ const usedPct = maxK > 0 ? Math.round((activeK / maxK) * 100) : 0;
699
+ const purity = state.metrics?.signalPurityPct ?? 100;
700
+ const noiseK = Math.round((state.metrics?.sludgeTokens || 0) / 1000);
701
+ const rawRecCmd = state.diagnostics?.recommendedCommand || 'Ready';
702
+ const recCmd = rawRecCmd === '/fast' ? 'Ready' : rawRecCmd;
703
+ const isCacheCold = state.quota?.cache ? Boolean(state.quota.cache.isCacheCold) : false;
704
+ const ttlSec = Math.max(0, Math.round(Number(state.quota?.cache?.ttlRemainingSec || 0) || 0));
705
+ const cacheHitPct = Math.max(0, Number(state.quota?.cache?.hitRatePct || 0) || 0);
706
+ const cacheLabel = (!isCacheCold && ttlSec > 0 && cacheHitPct > 0) ? `Warm(${ttlSec}s)` : 'Cold';
707
+ const modeTag = state.workloadMode?.tag || '[Mode: Read-Heavy Audit]';
708
+ const strandedCnt = Number(state.attentionHeatmap?.strandedSignalCount || 0);
709
+ const strandedSuffix = strandedCnt > 0 ? ` | \u26A0 ${strandedCnt}/40 mid-window blocks` : '';
710
+
711
+ let line1 = '';
712
+ if (cellCount === 40) {
713
+ line1 = `${bar} [ ${activeK}k / ${maxK}k · ${usedPct}% ] \x1b[1mPurity:\x1b[0m ${purity}% | \x1b[1mCache Hit:\x1b[0m ${cacheHitPct}% | \x1b[1mWaste:\x1b[0m ${noiseK}k tok | \x1b[1mCache:\x1b[0m ${cacheLabel} | ${modeTag}${strandedSuffix} \x1b[38;5;51m-> ${recCmd}\x1b[0m`;
714
+ } else if (cellCount === 20) {
715
+ line1 = `${bar} [${activeK}k/${maxK}k·${usedPct}%] P:${purity}% Waste:${noiseK}k -> ${recCmd}`;
716
+ } else {
717
+ line1 = `${bar} ${activeK}k P:${purity}% ${recCmd}`;
718
+ }
719
+ if (columns <= 80) {
720
+ line1 = clampAnsiText(line1, Math.min(columns, 80));
721
+ }
722
+ return line1;
723
+ }
724
+
725
+ /**
726
+ * Renders the ANSI statusLine bar and full 256K-aware HorizonStatePayload for Antigravity CLI / Sidecar Daemon
727
+ */
728
+ export async function runCLI(options = {}) {
729
+ const {
730
+ stdinData = null,
731
+ columns = process.stdout.columns || 120,
732
+ sessionDirOverride = null,
733
+ cacheDirOverride = null,
734
+ useNativeCeiling = true,
735
+ demoScenario = null
736
+ } = options;
737
+
738
+ if (demoScenario || process.env.HORIZON_DEMO === '1') {
739
+ const { text, state } = formatDemoScenarioAnsi(
740
+ Number(demoScenario || process.env.HORIZON_DEMO_SCENARIO || 5),
741
+ { columns }
742
+ );
743
+ if (options.emitWidget || (Array.isArray(process.argv) && process.argv.includes('--emit-widget'))) {
744
+ const target = path.resolve(options.out || 'horizon_widget.html');
745
+ const { html } = renderClassifierHudHtml(state, { viewMode: 'simple' });
746
+ fs.mkdirSync(path.dirname(target), { recursive: true });
747
+ fs.writeFileSync(target, html, 'utf8');
748
+ const fileUri = `file:///${target.replace(/\\/g, '/').replace(/^\/+/, '')}`;
749
+ const embedTag = `<agent-embed src="${fileUri}"></agent-embed>`;
750
+ if (!options.silent) console.log(embedTag);
751
+ return { output: text, state, html, path: target, fileUri, embedTag };
752
+ }
753
+ if (!options.silent) console.log(text);
754
+ return { output: text, state };
755
+ }
756
+
757
+ let sessionInfo = null;
758
+ if (sessionDirOverride) {
759
+ const lowerOverride = String(sessionDirOverride).toLowerCase();
760
+ const inferredStore = lowerOverride.endsWith('.vscdb') || fs.existsSync(path.join(sessionDirOverride, 'state.vscdb'))
761
+ ? 'cursor'
762
+ : (lowerOverride.endsWith('.jsonl') ? 'claude-code' : 'antigravity');
763
+ sessionInfo = {
764
+ storeName: inferredStore,
765
+ sessionDir: sessionDirOverride,
766
+ sessionId: path.basename(sessionDirOverride).replace(/\.(jsonl|vscdb)$/i, '')
767
+ };
768
+ } else {
769
+ const passedSessionId = stdinData?.session_id || stdinData?.conversation_id;
770
+ sessionInfo = findSessionDirectory(passedSessionId);
771
+ }
772
+
773
+ if (!sessionInfo || !fs.existsSync(sessionInfo.sessionDir)) {
774
+ const fallbackText = '\x1b[38;5;244m[ - ] No Antigravity session active\x1b[0m';
775
+ if (!options.silent) console.log(fallbackText);
776
+ return { output: fallbackText, state: null };
777
+ }
778
+
779
+ const parsed = parseTranscriptIncremental(sessionInfo.sessionDir, cacheDirOverride);
780
+ if (!parsed.steps || parsed.steps.length === 0) {
781
+ const initText = '\x1b[38;5;244m[ ... ] Initialize session to build attention horizon\x1b[0m';
782
+ if (!options.silent) console.log(initText);
783
+ return { output: initText, state: null };
784
+ }
785
+
786
+ const reconciliation = await reconcileWorkspaceAndKIs(sessionInfo.sessionId, getHomeDir());
787
+ const defaultCacheDir = path.join(getHomeDir(), '.gemini', 'antigravity', 'cache', 'agy-horizon');
788
+ const cacheDir = cacheDirOverride || defaultCacheDir;
789
+ // Model precedence: stdin > gen_metadata.model > last USER_INPUT Model Selection > fallback.
790
+ const activeGenMetadata = reconciliation.sessionGenMetadata || parsed.genMetadata || null;
791
+ const resolvedModel = resolveSessionModel({
792
+ stdinData,
793
+ genMetadata: activeGenMetadata,
794
+ steps: parsed.steps
795
+ });
796
+ const modelId = resolvedModel.id;
797
+ const loadedSettings = loadSettings(cacheDir);
798
+ const win = resolveWindow(loadedSettings, modelId);
799
+ const hasCustomLimit = Boolean(
800
+ (modelId && loadedSettings.modelOverrides?.[modelId]) ||
801
+ (loadedSettings.safeLimitTokens && loadedSettings.safeLimitTokens !== 140000)
802
+ );
803
+ const nativeMax = resolveModelCeiling(modelId, stdinData?.context_window, { useLegacyDefault: !useNativeCeiling });
804
+ const scaledEffort = scaleEffortProfileForCeiling(parsed.activeEffortProfile, nativeMax);
805
+ const effectiveSafeLimit = hasCustomLimit
806
+ ? win.safeLimit
807
+ : (scaledEffort?.safeLimit || win.safeLimit);
808
+
809
+ const state = classifyHorizon(parsed.steps, {
810
+ sessionId: sessionInfo.sessionId,
811
+ storeSource: sessionInfo.storeName,
812
+ logTierUsed: parsed.tier,
813
+ logFilePath: parsed.filePath,
814
+ canonicalWorkspace: reconciliation.primaryWorkspace || parsed.workspacePath || '',
815
+ projectId: reconciliation.projectId,
816
+ kiBleedMap: reconciliation.kiBleedMap,
817
+ modelId,
818
+ stdinContextWindow: stdinData?.context_window,
819
+ stdinQuota: stdinData?.quota,
820
+ genMetadata: activeGenMetadata,
821
+ modelSource: resolvedModel.source,
822
+ useNativeCeiling,
823
+ cacheDir,
824
+ safeLimitTokens: effectiveSafeLimit,
825
+ reminderAtPct: win.reminderAtPct,
826
+ activeEffortProfile: scaledEffort,
827
+ effortTransitions: parsed.effortTransitions
828
+ });
829
+ state.sessionTitle = reconciliation.sessionTitle || parsed.sessionTitle || '';
830
+ if (state.model && typeof state.model === 'object') {
831
+ state.model.source = resolvedModel.source;
832
+ state.model.rawLabel = resolvedModel.raw;
833
+ }
834
+ state.recentSessions = reconciliation.recentSessions || [];
835
+ state.rewindDetected = Boolean(parsed.rewindDetected);
836
+ try { state.baseline = measureBaseline(reconciliation.primaryWorkspace || ''); } catch { state.baseline = null; }
837
+ state.chronicReads = updateChronicReads(
838
+ cacheDir,
839
+ sessionInfo.sessionId,
840
+ state.brainSignals?.duplicateReads?.topFiles || [],
841
+ 10,
842
+ reconciliation.primaryWorkspace || state.workspace?.canonicalPath || ''
843
+ );
844
+
845
+ state.delta = recordAndDelta(cacheDir, sessionInfo.sessionId, state, parsed.steps).delta;
846
+ try {
847
+ state.hostHealth = await inspectHostProcesses({ force: false });
848
+ } catch {
849
+ state.hostHealth = { rssGb: 0, languageServerCount: 0, orphanCount: 0, orphans: [], status: 'HEALTHY', alertBanner: null, checkedAt: new Date().toISOString() };
850
+ }
851
+ try {
852
+ writeJsonAtomicSync(path.join(cacheDir, 'latest.state.json'), state);
853
+ } catch {}
854
+
855
+ const line1 = formatCliStatusLine(state, { columns });
856
+
857
+ if (options.emitWidget || (Array.isArray(process.argv) && process.argv.includes('--emit-widget'))) {
858
+ const target = path.resolve(options.out || 'horizon_widget.html');
859
+ const { html } = renderClassifierHudHtml(state, { viewMode: 'simple' });
860
+ fs.mkdirSync(path.dirname(target), { recursive: true });
861
+ fs.writeFileSync(target, html, 'utf8');
862
+ const fileUri = `file:///${target.replace(/\\/g, '/').replace(/^\/+/, '')}`;
863
+ const embedTag = `<agent-embed src="${fileUri}"></agent-embed>`;
864
+ if (!options.silent) console.log(embedTag);
865
+ return { output: line1, state, html, path: target, fileUri, embedTag };
866
+ }
867
+
868
+ if (!options.silent) console.log(line1);
869
+ return { output: line1, state };
870
+ }
871
+
872
+ /**
873
+ * Generates self-contained HTML widget and prints/returns `<agent-embed src="file:///<path>"></agent-embed>`
874
+ */
875
+ export async function emitHorizonWidget(options = {}) {
876
+ const targetPath = path.resolve(options.out || 'horizon_widget.html');
877
+ const cliRes = await runCLI({ ...options, silent: true, useNativeCeiling: true });
878
+ const state = cliRes?.state || {};
879
+ const { html } = renderClassifierHudHtml(state, { viewMode: 'simple' });
880
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
881
+ fs.writeFileSync(targetPath, html, 'utf8');
882
+ const fileUri = `file:///${targetPath.replace(/\\/g, '/').replace(/^\/+/, '')}`;
883
+ const embedTag = `<agent-embed src="${fileUri}"></agent-embed>`;
884
+ if (!options.silent) {
885
+ process.stdout.write(`${embedTag}\n`);
886
+ }
887
+ return { ok: true, path: targetPath, fileUri, embedTag, html, state };
888
+ }