ctxtop 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,686 @@
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
+ * Renders the ANSI statusLine bar and full 256K-aware HorizonStatePayload for Antigravity CLI / Sidecar Daemon
477
+ */
478
+ export async function runCLI(options = {}) {
479
+ const {
480
+ stdinData = null,
481
+ columns = process.stdout.columns || 120,
482
+ sessionDirOverride = null,
483
+ cacheDirOverride = null,
484
+ useNativeCeiling = true,
485
+ demoScenario = null
486
+ } = options;
487
+
488
+ if (demoScenario || process.env.HORIZON_DEMO === '1') {
489
+ const { text, state } = formatDemoScenarioAnsi(
490
+ Number(demoScenario || process.env.HORIZON_DEMO_SCENARIO || 5),
491
+ { columns }
492
+ );
493
+ if (options.emitWidget || (Array.isArray(process.argv) && process.argv.includes('--emit-widget'))) {
494
+ const target = path.resolve(options.out || 'horizon_widget.html');
495
+ const { html } = renderHorizonPanelHtml(state, { viewMode: 'simple' });
496
+ fs.mkdirSync(path.dirname(target), { recursive: true });
497
+ fs.writeFileSync(target, html, 'utf8');
498
+ const fileUri = `file:///${target.replace(/\\/g, '/').replace(/^\/+/, '')}`;
499
+ const embedTag = `<agent-embed src="${fileUri}"></agent-embed>`;
500
+ if (!options.silent) console.log(embedTag);
501
+ return { output: text, state, html, path: target, fileUri, embedTag };
502
+ }
503
+ if (!options.silent) console.log(text);
504
+ return { output: text, state };
505
+ }
506
+
507
+ let sessionInfo = null;
508
+ if (sessionDirOverride) {
509
+ const lowerOverride = String(sessionDirOverride).toLowerCase();
510
+ const inferredStore = lowerOverride.endsWith('.vscdb') || fs.existsSync(path.join(sessionDirOverride, 'state.vscdb'))
511
+ ? 'cursor'
512
+ : (lowerOverride.endsWith('.jsonl') ? 'claude-code' : 'antigravity');
513
+ sessionInfo = {
514
+ storeName: inferredStore,
515
+ sessionDir: sessionDirOverride,
516
+ sessionId: path.basename(sessionDirOverride).replace(/\.(jsonl|vscdb)$/i, '')
517
+ };
518
+ } else {
519
+ const passedSessionId = stdinData?.session_id || stdinData?.conversation_id;
520
+ sessionInfo = findSessionDirectory(passedSessionId);
521
+ }
522
+
523
+ if (!sessionInfo || !fs.existsSync(sessionInfo.sessionDir)) {
524
+ const fallbackText = '\x1b[38;5;244m[ - ] No Antigravity session active\x1b[0m';
525
+ if (!options.silent) console.log(fallbackText);
526
+ return { output: fallbackText, state: null };
527
+ }
528
+
529
+ const parsed = parseTranscriptIncremental(sessionInfo.sessionDir, cacheDirOverride);
530
+ if (!parsed.steps || parsed.steps.length === 0) {
531
+ const initText = '\x1b[38;5;244m[ ... ] Initialize session to build attention horizon\x1b[0m';
532
+ if (!options.silent) console.log(initText);
533
+ return { output: initText, state: null };
534
+ }
535
+
536
+ const reconciliation = await reconcileWorkspaceAndKIs(sessionInfo.sessionId, getHomeDir());
537
+ const defaultCacheDir = path.join(getHomeDir(), '.gemini', 'antigravity', 'cache', 'agy-horizon');
538
+ const cacheDir = cacheDirOverride || defaultCacheDir;
539
+ // Model precedence: stdin > gen_metadata.model > last USER_INPUT Model Selection > fallback.
540
+ const activeGenMetadata = reconciliation.sessionGenMetadata || parsed.genMetadata || null;
541
+ const resolvedModel = resolveSessionModel({
542
+ stdinData,
543
+ genMetadata: activeGenMetadata,
544
+ steps: parsed.steps
545
+ });
546
+ const modelId = resolvedModel.id;
547
+ const loadedSettings = loadSettings(cacheDir);
548
+ const win = resolveWindow(loadedSettings, modelId);
549
+ const hasCustomLimit = Boolean(
550
+ (modelId && loadedSettings.modelOverrides?.[modelId]) ||
551
+ (loadedSettings.safeLimitTokens && loadedSettings.safeLimitTokens !== 140000)
552
+ );
553
+ const nativeMax = resolveModelCeiling(modelId, stdinData?.context_window, { useLegacyDefault: !useNativeCeiling });
554
+ const scaledEffort = scaleEffortProfileForCeiling(parsed.activeEffortProfile, nativeMax);
555
+ const effectiveSafeLimit = hasCustomLimit
556
+ ? win.safeLimit
557
+ : (scaledEffort?.safeLimit || win.safeLimit);
558
+
559
+ const state = classifyHorizon(parsed.steps, {
560
+ sessionId: sessionInfo.sessionId,
561
+ storeSource: sessionInfo.storeName,
562
+ logTierUsed: parsed.tier,
563
+ logFilePath: parsed.filePath,
564
+ canonicalWorkspace: reconciliation.primaryWorkspace || parsed.workspacePath || '',
565
+ projectId: reconciliation.projectId,
566
+ kiBleedMap: reconciliation.kiBleedMap,
567
+ modelId,
568
+ stdinContextWindow: stdinData?.context_window,
569
+ stdinQuota: stdinData?.quota,
570
+ genMetadata: activeGenMetadata,
571
+ modelSource: resolvedModel.source,
572
+ useNativeCeiling,
573
+ cacheDir,
574
+ safeLimitTokens: effectiveSafeLimit,
575
+ reminderAtPct: win.reminderAtPct,
576
+ activeEffortProfile: scaledEffort,
577
+ effortTransitions: parsed.effortTransitions
578
+ });
579
+ state.sessionTitle = reconciliation.sessionTitle || parsed.sessionTitle || '';
580
+ if (state.model && typeof state.model === 'object') {
581
+ state.model.source = resolvedModel.source;
582
+ state.model.rawLabel = resolvedModel.raw;
583
+ }
584
+ state.recentSessions = reconciliation.recentSessions || [];
585
+ state.rewindDetected = Boolean(parsed.rewindDetected);
586
+ try { state.baseline = measureBaseline(reconciliation.primaryWorkspace || ''); } catch { state.baseline = null; }
587
+ state.chronicReads = updateChronicReads(
588
+ cacheDir,
589
+ sessionInfo.sessionId,
590
+ state.brainSignals?.duplicateReads?.topFiles || [],
591
+ 10,
592
+ reconciliation.primaryWorkspace || state.workspace?.canonicalPath || ''
593
+ );
594
+
595
+ state.delta = recordAndDelta(cacheDir, sessionInfo.sessionId, state, parsed.steps).delta;
596
+ try {
597
+ state.hostHealth = await inspectHostProcesses({ force: false });
598
+ } catch {
599
+ state.hostHealth = { rssGb: 0, languageServerCount: 0, orphanCount: 0, orphans: [], status: 'HEALTHY', alertBanner: null, checkedAt: new Date().toISOString() };
600
+ }
601
+ try {
602
+ writeJsonAtomicSync(path.join(cacheDir, 'latest.state.json'), state);
603
+ } catch {}
604
+
605
+ let cellCount = 40;
606
+ if (columns < 80) cellCount = 10;
607
+ else if (columns < 120) cellCount = 20;
608
+
609
+ const downsampleRatio = 40 / cellCount;
610
+ const isAmputation = state.amputation.inAmputationZone;
611
+ const isCrisis = state.amputation.amputationCrisis;
612
+
613
+ let bar = isCrisis ? '\x1b[48;5;196m\x1b[38;5;255m![ 🚨 \x1b[0m ' : (isAmputation ? '\x1b[38;5;196m![\x1b[0m' : '[');
614
+ for (let i = 0; i < cellCount; i++) {
615
+ const origStart = Math.floor(i * downsampleRatio);
616
+ const origEnd = Math.floor((i + 1) * downsampleRatio);
617
+ const slice = state.cells.slice(origStart, origEnd);
618
+ const dominant = slice[0]?.dominantCategory || H_CATEGORIES.FREE_HEADROOM;
619
+ const meta = CATEGORY_METADATA[dominant] || CATEGORY_METADATA.FREE_HEADROOM;
620
+ if (slice.some(c => c.isCrisisCell)) {
621
+ bar += `\x1b[48;5;196m\x1b[38;5;255m${meta.symbol}\x1b[0m`;
622
+ } else {
623
+ bar += `${meta.ansiCode}${meta.symbol}\x1b[0m`;
624
+ }
625
+ }
626
+ bar += isCrisis ? ' \x1b[48;5;196m\x1b[38;5;255m]!\x1b[0m' : (isAmputation ? '\x1b[38;5;196m]!\x1b[0m' : ']');
627
+
628
+ const activeK = Math.round(state.window.totalActiveTokens / 1000);
629
+ const maxK = Math.round(state.window.maxTokens / 1000);
630
+ const usedPct = maxK > 0 ? Math.round((activeK / maxK) * 100) : 0;
631
+ const purity = state.metrics.signalPurityPct;
632
+ const noiseK = Math.round((state.metrics.sludgeTokens || 0) / 1000);
633
+ const rawRecCmd = state.diagnostics.recommendedCommand || 'Ready';
634
+ const recCmd = rawRecCmd === '/fast' ? 'Ready' : rawRecCmd;
635
+ const isCacheCold = state.quota?.cache ? Boolean(state.quota.cache.isCacheCold) : false;
636
+ const ttlSec = Math.max(0, Math.round(Number(state.quota?.cache?.ttlRemainingSec || 0) || 0));
637
+ const cacheHitPct = Math.max(0, Number(state.quota?.cache?.hitRatePct || 0) || 0);
638
+ const cacheLabel = (!isCacheCold && ttlSec > 0 && cacheHitPct > 0) ? `Warm(${ttlSec}s)` : 'Cold';
639
+ const modeTag = state.workloadMode?.tag || '[Mode: Read-Heavy Audit]';
640
+ const strandedCnt = Number(state.attentionHeatmap?.strandedSignalCount || 0);
641
+ const strandedSuffix = strandedCnt > 0 ? ` | \u26A0 ${strandedCnt}/40 mid-window blocks` : '';
642
+
643
+ let line1 = '';
644
+ if (cellCount === 40) {
645
+ 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`;
646
+ } else if (cellCount === 20) {
647
+ line1 = `${bar} [${activeK}k/${maxK}k·${usedPct}%] P:${purity}% Waste:${noiseK}k -> ${recCmd}`;
648
+ } else {
649
+ line1 = `${bar} ${activeK}k P:${purity}% ${recCmd}`;
650
+ }
651
+ if (columns <= 80) {
652
+ line1 = clampAnsiText(line1, Math.min(columns, 80));
653
+ }
654
+
655
+ if (options.emitWidget || (Array.isArray(process.argv) && process.argv.includes('--emit-widget'))) {
656
+ const target = path.resolve(options.out || 'horizon_widget.html');
657
+ const { html } = renderHorizonPanelHtml(state, { viewMode: 'simple' });
658
+ fs.mkdirSync(path.dirname(target), { recursive: true });
659
+ fs.writeFileSync(target, html, 'utf8');
660
+ const fileUri = `file:///${target.replace(/\\/g, '/').replace(/^\/+/, '')}`;
661
+ const embedTag = `<agent-embed src="${fileUri}"></agent-embed>`;
662
+ if (!options.silent) console.log(embedTag);
663
+ return { output: line1, state, html, path: target, fileUri, embedTag };
664
+ }
665
+
666
+ if (!options.silent) console.log(line1);
667
+ return { output: line1, state };
668
+ }
669
+
670
+ /**
671
+ * Generates self-contained HTML widget and prints/returns `<agent-embed src="file:///<path>"></agent-embed>`
672
+ */
673
+ export async function emitHorizonWidget(options = {}) {
674
+ const targetPath = path.resolve(options.out || 'horizon_widget.html');
675
+ const cliRes = await runCLI({ ...options, silent: true, useNativeCeiling: true });
676
+ const state = cliRes?.state || {};
677
+ const { html } = renderHorizonPanelHtml(state, { viewMode: 'simple' });
678
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
679
+ fs.writeFileSync(targetPath, html, 'utf8');
680
+ const fileUri = `file:///${targetPath.replace(/\\/g, '/').replace(/^\/+/, '')}`;
681
+ const embedTag = `<agent-embed src="${fileUri}"></agent-embed>`;
682
+ if (!options.silent) {
683
+ process.stdout.write(`${embedTag}\n`);
684
+ }
685
+ return { ok: true, path: targetPath, fileUri, embedTag, html, state };
686
+ }