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,2002 @@
1
+ import http from 'node:http';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { getHomeDir, getDaemonPortFile, ensureSupportedNodeVersion } from '../../src/core/paths.mjs';
8
+ import { resolveSurfaceTag, resolveModelCeiling } from '../../src/core/constants.mjs';
9
+ import { runCLI } from '../../src/cli/horizon_hud.mjs';
10
+ import { buildCostRadarFromState } from '../../src/cli/cost_radar.mjs';
11
+ import { findSessionDirectory } from '../../src/core/parser.mjs';
12
+ import { loadSettings, saveSettings, SETTINGS_LIMITS } from '../../src/core/settings.mjs';
13
+ import { pruneSessionTranscript } from '../../src/core/pruner.mjs';
14
+ import { inspectHostProcesses, reapOrphanProcesses } from '../../src/core/host_watchdog.mjs';
15
+ import { generateHandoffMarkdown } from '../../src/core/handoff_audit.mjs';
16
+ import { registerCliDampeningHook, promoteRuleWithAttentionZone } from '../../src/core/layer5_hygiene.mjs';
17
+ import { exportSanitizedSnapshot } from '../../src/core/sanitizer.mjs';
18
+ import { executeToolOutputSurgery } from '../../src/core/tool_surgeon.mjs';
19
+ import { buildGitCommitTokenLedger } from '../../src/core/git_ledger.mjs';
20
+ import { synthesizeResumeHerePack } from '../../src/core/episodic_memory.mjs';
21
+ import { getFlightcheckDir } from '../../src/core/sidecar_store.mjs';
22
+ import { PrefixCacheShield } from '../../src/core/prefix_cache_shield.mjs';
23
+ import { CompactionCoach, assessCompactionState, trimUncachedTail } from '../../src/core/compaction_coach.mjs';
24
+ import { RsiInstinctEngine } from '../../src/core/rsi_instinct_engine.mjs';
25
+ import { UShapedAttentionOptimizer } from '../../src/core/u_shaped_optimizer.mjs';
26
+ import {
27
+ evaluateTaskAndQuotaRoute,
28
+ actuateRoutingRecommendation,
29
+ CacheGravityScorer,
30
+ TaskMdDirectiveWatcher,
31
+ ModelSelectorActuator
32
+ } from '../../src/core/task_quota_router.mjs';
33
+ import { loadHorizonConfig } from '../../src/core/horizon_config.mjs';
34
+ import { TrajectoryWatcher } from '../../src/core/telemetry/trajectory_watcher.mjs';
35
+ import { detectShadowedFileBloat } from '../../src/core/telemetry/shadow_file_detector.mjs';
36
+ import { CacheTtlWatchdog } from '../../src/core/telemetry/cache_ttl_watchdog.mjs';
37
+ import {
38
+ loadRegistry as loadScopeLockRegistry,
39
+ detectScopeCollision,
40
+ deriveSessionClaimedPaths
41
+ } from '../../src/core/telemetry/scope_lock_registry.mjs';
42
+ import { HysteresisLock, TurnBoundaryActuationQueue } from '../../src/core/coach/task_quota_router.mjs';
43
+ import { CircuitBreakers } from '../../src/core/coach/circuit_breakers.mjs';
44
+ import { SubagentPhantomAuditor } from '../../src/core/coach/subagent_phantom_auditor.mjs';
45
+ import { TurnZeroGate } from '../../src/core/coach/turn_zero_gate.mjs';
46
+ import { HandoffHydrationLauncher } from '../../src/core/coach/handoff_hydrator.mjs';
47
+ import {
48
+ SavedQuotaReceiptLedger,
49
+ SAVINGS_EVENT_TYPES,
50
+ computeUnifiedSavings
51
+ } from '../../src/core/coach/saved_quota_ledger.mjs';
52
+ import { applyAutoFixToTimeline } from '../../src/core/session_timeline.mjs';
53
+ import {
54
+ getProEntitlementStatus,
55
+ requireProFeature,
56
+ activateProLicense,
57
+ activateLocalTrial
58
+ } from '../../src/core/pro_license.mjs';
59
+ import { generateCorporateExpenseReceipt } from '../../src/core-isomorphic/ui/pdfReceiptGenerator.mjs';
60
+ import { ProgressiveCheckpointer } from '../../src/core/coach/progressive_checkpointer.mjs';
61
+ import { atomicWriteFileSync } from '../../src/core/atomic_io.mjs';
62
+ import { MicroIpcServer } from '../../src/engine-node/ipc/server.mjs';
63
+
64
+ export const HORIZON_CSRF_TOKEN = crypto.randomBytes(32).toString('hex');
65
+ export const MAX_REQUEST_BODY_BYTES = 1_048_576; // 1 MB
66
+ export const MAX_SSE_CLIENTS = 16;
67
+ export const MAX_DAEMON_DIAGNOSTICS = 50;
68
+
69
+ const daemonDiagnostics = [];
70
+ let daemonDiagnosticTotalCount = 0;
71
+
72
+ export function recordDaemonDiagnostic(operation, err) {
73
+ const entry = {
74
+ timestamp: new Date().toISOString(),
75
+ operation: String(operation || 'unknown').slice(0, 96),
76
+ name: err && typeof err === 'object' && err.name ? String(err.name).slice(0, 48) : 'Error',
77
+ code: err && typeof err === 'object' && err.code ? String(err.code) : null,
78
+ message: String(err instanceof Error ? err.message : (err ?? 'Unknown error')).slice(0, 240)
79
+ };
80
+ daemonDiagnosticTotalCount += 1;
81
+ daemonDiagnostics.push(entry);
82
+ while (daemonDiagnostics.length > MAX_DAEMON_DIAGNOSTICS) {
83
+ daemonDiagnostics.shift();
84
+ }
85
+ return entry;
86
+ }
87
+
88
+ export function getDaemonDiagnostics() {
89
+ return {
90
+ count: daemonDiagnostics.length,
91
+ totalRecorded: daemonDiagnosticTotalCount,
92
+ recent: [...daemonDiagnostics]
93
+ };
94
+ }
95
+
96
+ export function clearDaemonDiagnostics() {
97
+ daemonDiagnostics.length = 0;
98
+ daemonDiagnosticTotalCount = 0;
99
+ }
100
+
101
+ export function isValidCsrfToken(candidate) {
102
+ if (typeof candidate !== 'string' || candidate.length !== HORIZON_CSRF_TOKEN.length) {
103
+ return false;
104
+ }
105
+ const a = Buffer.from(candidate, 'utf8');
106
+ const b = Buffer.from(HORIZON_CSRF_TOKEN, 'utf8');
107
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
108
+ }
109
+ import { ContradictionAuditor } from '../../src/core/coach/contradiction_auditor.mjs';
110
+ import { ReflectorQueue } from '../../src/core/coach/reflector_queue.mjs';
111
+ import { PromptDecomposerCoach } from '../../src/core/coach/prompt_decomposer_coach.mjs';
112
+ import { getFts5CompressionStats } from '../../src/core/fts5_output_compressor.mjs';
113
+
114
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
115
+ if (process.argv.includes('--demo')) {
116
+ process.env.HORIZON_DEMO = '1';
117
+ }
118
+ const isDemoMode = process.env.HORIZON_DEMO === '1' || process.argv.includes('--demo');
119
+
120
+ const EXPLICIT_PORT = parseInt(
121
+ process.env.ANTIGRAVITY_SIDECAR_WEB_PORT ||
122
+ process.env.PORT ||
123
+ '0',
124
+ 10
125
+ );
126
+ const DEFAULT_PORT_START = 62935;
127
+ const DEFAULT_PORT_MAX = 62945;
128
+ const BIND_HOST = '127.0.0.1';
129
+ const clients = new Set();
130
+
131
+ const defaultCacheDir = path.join(getHomeDir(), '.gemini', 'antigravity', 'cache', 'agy-horizon');
132
+ const runtimeDir = path.join(getHomeDir(), '.gemini', 'runtime');
133
+ const stateFile = path.join(defaultCacheDir, 'latest.state.json');
134
+
135
+ const sidePaneHtml = path.resolve(__dirname, '../../src/ui/sidepane.html');
136
+ const horizonPanelHtml = path.resolve(__dirname, '../../src/webview/horizon_panel.html');
137
+
138
+ function getHtmlMtimeMs() {
139
+ const target = fs.existsSync(horizonPanelHtml) ? horizonPanelHtml : (fs.existsSync(sidePaneHtml) ? sidePaneHtml : null);
140
+ if (target) {
141
+ try {
142
+ return fs.statSync(target).mtimeMs;
143
+ } catch (err) {
144
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('getHtmlMtimeMs', err);
145
+ }
146
+ }
147
+ return 0;
148
+ }
149
+
150
+ let lastEvalMs = 0;
151
+ let cachedLiveState = null;
152
+ let pinnedConversationId = null;
153
+ let activeLockfiles = [];
154
+
155
+ const prefixCacheShield = new PrefixCacheShield();
156
+ const compactionCoach = new CompactionCoach({ prefixCacheShield, prefixShield: prefixCacheShield });
157
+ let rsiEngine = null;
158
+ try {
159
+ rsiEngine = new RsiInstinctEngine({ prefixCacheShield, prefixShield: prefixCacheShield });
160
+ } catch (err) {
161
+ recordDaemonDiagnostic('init:RsiInstinctEngine', err);
162
+ rsiEngine = null;
163
+ }
164
+ const uShapedOptimizer = new UShapedAttentionOptimizer({ prefixCacheShield, prefixShield: prefixCacheShield });
165
+ const cacheGravityScorer = new CacheGravityScorer();
166
+ const modelSelectorActuator = new ModelSelectorActuator({ cacheGravityScorer });
167
+ const taskMdWatcher = new TaskMdDirectiveWatcher({ cacheGravityScorer, actuator: modelSelectorActuator });
168
+ const hysteresisLock = new HysteresisLock();
169
+ const turnBoundaryQueue = new TurnBoundaryActuationQueue();
170
+ const circuitBreakers = new CircuitBreakers({ hysteresisLock });
171
+ const trajectoryWatcher = new TrajectoryWatcher({ hysteresisLock, circuitBreaker: circuitBreakers });
172
+ const handoffHydrator = new HandoffHydrationLauncher();
173
+ const cacheTtlWatchdog = new CacheTtlWatchdog({
174
+ onPreSnapshot: () => {
175
+ try {
176
+ const wsDir = cachedLiveState?.workspace?.canonicalPath || process.cwd();
177
+ handoffHydrator.preStageOnTtlSnapshot({
178
+ workspaceDir: wsDir,
179
+ sessionId: cachedLiveState?.sessionId || pinnedConversationId || 'default-session',
180
+ writeToDisk: true,
181
+ writeDocsHandoff: false
182
+ });
183
+ } catch (err) {
184
+ recordDaemonDiagnostic('cacheTtlWatchdog:onPreSnapshot', err);
185
+ }
186
+ }
187
+ });
188
+ const subagentPhantomAuditor = new SubagentPhantomAuditor();
189
+ const turnZeroGate = new TurnZeroGate();
190
+ const progressiveCheckpointer = new ProgressiveCheckpointer({
191
+ checkpointDir: path.join(getFlightcheckDir(), 'checkpoints'),
192
+ captureGitStat: false
193
+ });
194
+ const contradictionAuditor = new ContradictionAuditor();
195
+ const reflectorQueue = new ReflectorQueue({ prefixCacheShield });
196
+ prefixCacheShield.attachReflectorQueue(reflectorQueue);
197
+ const promptDecomposerCoach = new PromptDecomposerCoach();
198
+ let savedQuotaLedger = null;
199
+ try {
200
+ savedQuotaLedger = new SavedQuotaReceiptLedger();
201
+ } catch (err) {
202
+ recordDaemonDiagnostic('init:SavedQuotaReceiptLedger', err);
203
+ savedQuotaLedger = null;
204
+ }
205
+
206
+ let cachedTaskMdMeta = { path: '', mtimeMs: -1, content: '' };
207
+ function getCachedTaskMdContent(wsDir) {
208
+ if (!wsDir) return '';
209
+ const candidate = path.join(wsDir, 'task.md');
210
+ try {
211
+ if (!fs.existsSync(candidate)) return '';
212
+ const st = fs.statSync(candidate);
213
+ if (cachedTaskMdMeta.path === candidate && cachedTaskMdMeta.mtimeMs === st.mtimeMs) {
214
+ return cachedTaskMdMeta.content;
215
+ }
216
+ const content = fs.readFileSync(candidate, 'utf8');
217
+ cachedTaskMdMeta = { path: candidate, mtimeMs: st.mtimeMs, content };
218
+ return content;
219
+ } catch (err) {
220
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('getCachedTaskMdContent', err);
221
+ return '';
222
+ }
223
+ }
224
+
225
+ let lastBreakerSessionKey = null;
226
+ let lastBreakerStepCount = 0;
227
+
228
+ function syncLiveCircuitBreakers(state, sessionKey) {
229
+ const steps = Array.isArray(state?.steps) ? state.steps : [];
230
+ if (sessionKey !== lastBreakerSessionKey) {
231
+ circuitBreakers.purgeRewoundTurns(0);
232
+ lastBreakerSessionKey = sessionKey;
233
+ lastBreakerStepCount = 0;
234
+ } else if (steps.length < lastBreakerStepCount) {
235
+ circuitBreakers.purgeRewoundTurns(steps.length);
236
+ lastBreakerStepCount = steps.length;
237
+ }
238
+
239
+ for (let idx = lastBreakerStepCount; idx < steps.length; idx++) {
240
+ const st = steps[idx] || {};
241
+ const calls = Array.isArray(st.toolCalls) ? st.toolCalls : [];
242
+ if (calls.length === 0) continue;
243
+
244
+ const nextSt = steps[idx + 1] || null;
245
+ const nextHasOwnCalls = Array.isArray(nextSt?.toolCalls) && nextSt.toolCalls.length > 0;
246
+ const isPairedNext = Boolean(
247
+ nextSt &&
248
+ !nextHasOwnCalls &&
249
+ nextSt.type !== 'USER_INPUT' &&
250
+ nextSt.source !== 'USER_EXPLICIT'
251
+ );
252
+
253
+ const exitCode = isPairedNext && typeof nextSt.exitCode === 'number'
254
+ ? nextSt.exitCode
255
+ : (typeof st.exitCode === 'number'
256
+ ? st.exitCode
257
+ : ((st.status === 'ERROR' || (isPairedNext && nextSt.status === 'ERROR')) ? 1 : 0));
258
+ const failed = Boolean(st.status === 'ERROR' || (isPairedNext && nextSt.status === 'ERROR') || exitCode !== 0);
259
+
260
+ for (const c of calls) {
261
+ const toolName = String(c?.name || c?.tool || '').toLowerCase();
262
+ const args = c?.args || {};
263
+ const filePath = args.Path || args.path || args.TargetFile || args.AbsolutePath || '';
264
+ const chunks = Array.isArray(args.ReplacementChunks) ? args.ReplacementChunks : null;
265
+ const chunksOld = chunks
266
+ ? chunks.map((ch) => String(ch?.TargetContent ?? ch?.Target ?? '')).filter(Boolean).join('\n')
267
+ : undefined;
268
+ const chunksNew = chunks
269
+ ? chunks.map((ch) => String(ch?.ReplacementContent ?? ch?.Replacement ?? '')).filter(Boolean).join('\n')
270
+ : undefined;
271
+ const previousContent = args.Target !== undefined
272
+ ? args.Target
273
+ : (args.TargetContent !== undefined ? args.TargetContent : chunksOld);
274
+ const newContent = args.Content !== undefined
275
+ ? args.Content
276
+ : (args.CodeContent !== undefined
277
+ ? args.CodeContent
278
+ : (args.Replacement !== undefined
279
+ ? args.Replacement
280
+ : (args.ReplacementContent !== undefined ? args.ReplacementContent : chunksNew)));
281
+ circuitBreakers.recordTurn({
282
+ turnIndex: Number.isFinite(st.stepIndex) ? st.stepIndex : idx,
283
+ toolName,
284
+ args,
285
+ exitCode,
286
+ failed,
287
+ filePath,
288
+ previousContent,
289
+ newContent
290
+ });
291
+ }
292
+ }
293
+ lastBreakerStepCount = steps.length;
294
+ }
295
+
296
+ function buildCoachState(state, targetConvId) {
297
+ try {
298
+ const sessionKey = targetConvId || state?.sessionId || 'default';
299
+ const wsDir = state?.workspace?.canonicalPath || process.cwd();
300
+ const taskMdContent = state?.taskMdContent || getCachedTaskMdContent(wsDir);
301
+ const livePrompt = String(state?.lastUserPrompt || '');
302
+
303
+ const ttlSec = Math.max(0, Number(state?.quota?.cache?.ttlRemainingSec ?? state?.cache?.ttlRemainingSec ?? 0) || 0);
304
+ // Single source of truth for cache warmth: classifier `sessionRisk.isCacheTrulyWarm`
305
+ // (requires real cache-read evidence). A cold/busted cache contributes 0 warm tokens,
306
+ // so Coach never defends a prefix that is not actually resident.
307
+ const cacheBlock = state?.quota?.cache || state?.cache || {};
308
+ const totalActive = Number(state?.window?.totalActiveTokens || state?.tokens?.total || 0);
309
+ const trulyWarm = typeof state?.sessionRisk?.isCacheTrulyWarm === 'boolean'
310
+ ? state.sessionRisk.isCacheTrulyWarm
311
+ : (ttlSec > 0 && Number(cacheBlock.cacheReadTokens || 0) > 0 && !cacheBlock.prefixBustDetected);
312
+ const cachedTokens = trulyWarm
313
+ ? Math.max(Number(cacheBlock.lastTurnCacheReadTokens || 0), totalActive)
314
+ : 0;
315
+ const session = {
316
+ cachedTokens,
317
+ cacheTtlSeconds: ttlSec,
318
+ ttlRemainingSeconds: ttlSec,
319
+ turnCount: Number(state?.window?.turnCount ?? state?.turnCount ?? 0)
320
+ };
321
+
322
+ syncLiveCircuitBreakers(state, sessionKey);
323
+
324
+ let scopeCollisionAlert = null;
325
+ try {
326
+ const registry = loadScopeLockRegistry(wsDir);
327
+ if (Array.isArray(registry.leases) && registry.leases.length > 0) {
328
+ const stepEditedPaths = [];
329
+ for (const st of (Array.isArray(state?.steps) ? state.steps : [])) {
330
+ for (const c of (Array.isArray(st?.toolCalls) ? st.toolCalls : [])) {
331
+ if (/write|edit|replace|create|patch/i.test(String(c?.name || ''))) {
332
+ const p = c?.args?.Path || c?.args?.path || c?.args?.TargetFile || c?.args?.AbsolutePath;
333
+ if (p) stepEditedPaths.push(path.isAbsolute(p) ? path.relative(wsDir, p) : String(p));
334
+ }
335
+ }
336
+ }
337
+ const claimed = Array.from(new Set([
338
+ ...deriveSessionClaimedPaths({ workspaceDir: wsDir, taskMdContent }),
339
+ ...stepEditedPaths
340
+ ]));
341
+ const collision = detectScopeCollision(sessionKey, claimed, registry.leases);
342
+ if (collision) {
343
+ const shortId = String(sessionKey).slice(0, 8);
344
+ const worktreeCommand = `git worktree add ../${path.basename(wsDir)}-worktree-${shortId} -b feature-parallel-${shortId}`;
345
+ scopeCollisionAlert = {
346
+ detectorId: 'DET-20',
347
+ name: 'Scope Lock Collision',
348
+ severity: 'WARN',
349
+ conflictingTrajectoryId: collision.trajectoryId,
350
+ conflictingPid: collision.pid,
351
+ overlappingPaths: collision.overlappingPaths,
352
+ worktreeCommand,
353
+ message: `🚨 DET-20 Scope Collision: [${collision.overlappingPaths.join(', ')}] leased by "${collision.trajectoryId}" (PID ${collision.pid}). Isolate via git worktree.`
354
+ };
355
+ }
356
+ }
357
+ } catch (err) {
358
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('buildCoachState:scopeCollision', err);
359
+ }
360
+
361
+ const shieldStatus = prefixCacheShield.getStatus(session);
362
+ const compactionEval = assessCompactionState({
363
+ totalTokens: cachedTokens,
364
+ cachedTokens,
365
+ cacheTtlSeconds: ttlSec,
366
+ turnCount: session.turnCount,
367
+ reclaimableWasteTokens: Number(state?.metrics?.sludgeTokens || 0)
368
+ });
369
+
370
+ const clusters = rsiEngine?.getDomainClusters ? rsiEngine.getDomainClusters() : [];
371
+ const horizonCfg = loadHorizonConfig({ cwd: wsDir });
372
+ const configuredFlightMode = String(horizonCfg.flightMode || 'COACH').toUpperCase();
373
+ const effectiveRouterMode = modelSelectorActuator.mode === 'autopilot' || configuredFlightMode === 'AUTO_PILOT'
374
+ ? 'autopilot'
375
+ : (configuredFlightMode === 'OFF' ? 'off' : modelSelectorActuator.mode);
376
+ const effectiveFlightMode = effectiveRouterMode === 'autopilot'
377
+ ? 'AUTO_PILOT'
378
+ : configuredFlightMode;
379
+
380
+ const resolvedEffort = String(
381
+ state?.activeEffort ||
382
+ state?.activeEffortProfile?.shortLabel ||
383
+ state?.activeEffortProfile?.tier ||
384
+ 'auto'
385
+ ).toLowerCase();
386
+ const taskRoute = evaluateTaskAndQuotaRoute({
387
+ prompt: livePrompt,
388
+ taskMdContent,
389
+ activeModel: state?.model?.id || state?.model?.rawLabel || state?.activeModel || 'gemini-4-argon',
390
+ activeEffort: resolvedEffort === 'standard' ? 'auto' : resolvedEffort,
391
+ cachedTokens,
392
+ cacheTtlSeconds: ttlSec,
393
+ routerMode: effectiveRouterMode
394
+ });
395
+
396
+ const det17ShadowBloat = detectShadowedFileBloat(state?.steps || []);
397
+ const elapsedIdleSec = Math.max(0, 300 - ttlSec);
398
+ const ttlWatchdogState = cacheTtlWatchdog.evaluateElapsed(elapsedIdleSec, {
399
+ sessionId: sessionKey,
400
+ cachedTokens,
401
+ flightMode: effectiveFlightMode
402
+ });
403
+ const subagentAudit = subagentPhantomAuditor.auditTrajectories(state?.subagents?.invocations || []);
404
+ const fts5SavedTokens = getFts5CompressionStats().savedTokens;
405
+ const liveCacheReadTok = Math.max(0, Number(state?.quota?.cache?.cacheReadTokens || 0));
406
+ const liveStepKey = Number(state?.window?.stepCount || state?.window?.turnCount || 0);
407
+ if (savedQuotaLedger && liveCacheReadTok > 0 && !Boolean(state?.demoMeta || process.env.HORIZON_DEMO === '1')) {
408
+ try {
409
+ savedQuotaLedger.recordSaving({
410
+ sessionId: sessionKey,
411
+ eventType: SAVINGS_EVENT_TYPES.CACHE_HIT_PRESERVED,
412
+ tokensSaved: Math.round(liveCacheReadTok * 0.95),
413
+ dedupeKey: `cachehit:${sessionKey}:step:${liveStepKey}`,
414
+ detail: `95% KV cache hit on ${Math.round(liveCacheReadTok / 1000)}k tokens (step ${liveStepKey})`
415
+ });
416
+ } catch (err) {
417
+ recordDaemonDiagnostic('buildCoachState:cacheHitLedger', err);
418
+ }
419
+ }
420
+ const ledgerSummary = savedQuotaLedger
421
+ ? savedQuotaLedger.getSummary(sessionKey)
422
+ : {
423
+ totalArgonEquivTokensSaved: 0,
424
+ formattedSavedK: '0.0k',
425
+ statusBarText: '$(shield) Horizon: +0.0k Argon-equiv tokens saved (0 Cold Prefills • 0 Downshifts • 0 CLI Compress)',
426
+ footerText: '🛡️ Horizon: +0.0k Argon-equiv tokens saved (0 Cold Prefills • 0 Downshifts • 0 CLI Compress)',
427
+ displayFooterText: '🛡️ Tokens Saved: +0.0k (0 Cold Prefills · 0 Downshifts · 0 CLI Compress)'
428
+ };
429
+ const unifiedSavings = computeUnifiedSavings(state, {
430
+ ledger: savedQuotaLedger,
431
+ sessionId: sessionKey,
432
+ fts5SavedTokens
433
+ });
434
+ if (state && typeof state === 'object') {
435
+ state.savings = unifiedSavings;
436
+ try {
437
+ const keepDemoLog = Boolean(state.demoMeta && state.autoFixLog);
438
+ if (!keepDemoLog) {
439
+ state.autoFixLog = savedQuotaLedger
440
+ ? savedQuotaLedger.listRecentEvents(sessionKey, 20)
441
+ : { total: 0, items: [] };
442
+ }
443
+ if (state.sessionTimeline) {
444
+ applyAutoFixToTimeline(state.sessionTimeline, state.autoFixLog.items);
445
+ }
446
+ } catch (err) {
447
+ recordDaemonDiagnostic('buildCoachState:autoFixLog', err);
448
+ }
449
+ }
450
+
451
+ const ckptEval = progressiveCheckpointer.evaluateAndSnapshot({
452
+ sessionId: sessionKey,
453
+ totalTokens: cachedTokens,
454
+ maxTokens: Number(state?.window?.maxTokens) || resolveModelCeiling(
455
+ state?.model?.id || state?.model?.rawLabel || state?.activeModel || 'gemini-4-argon',
456
+ null,
457
+ { useLegacyDefault: false }
458
+ ),
459
+ taskMdContent,
460
+ agentsMdContent: state?.agentsMdContent || '',
461
+ userConstraints: state?.userConstraints || [],
462
+ writeToDisk: !Boolean(state?.demoMeta || process.env.HORIZON_DEMO === '1')
463
+ });
464
+ const latestCkpt = progressiveCheckpointer.getLatestCheckpoint(sessionKey);
465
+ const evaporationCheck = latestCkpt && state?.contextSummary
466
+ ? progressiveCheckpointer.detectConstraintEvaporation(state.contextSummary, sessionKey, latestCkpt)
467
+ : null;
468
+
469
+ reflectorQueue.setWorkspaceDir(wsDir);
470
+ const stagedLearnings = reflectorQueue.listItems();
471
+ const promptAdvisory = promptDecomposerCoach.evaluate(livePrompt);
472
+
473
+ const combinedAlerts = [...circuitBreakers.activeAlerts];
474
+ if (scopeCollisionAlert) combinedAlerts.push(scopeCollisionAlert);
475
+ const thinkingDrift = state?.quota?.thinkingDrift || null;
476
+ const det30Mode = String(horizonCfg?.detectors?.['DET-30'] || 'default').toLowerCase();
477
+ if (thinkingDrift?.loop?.triggered && det30Mode !== 'off') {
478
+ combinedAlerts.push({
479
+ detectorId: 'DET-30',
480
+ name: 'thinking-drift-loop',
481
+ severity: thinkingDrift.loop.severity === 'critical' ? 'CRITICAL' : 'WARN',
482
+ message: thinkingDrift.loop.message
483
+ });
484
+ }
485
+ const primaryTripped = combinedAlerts.length > 0 ? combinedAlerts[combinedAlerts.length - 1] : null;
486
+
487
+ return {
488
+ prefixCacheShield: shieldStatus,
489
+ detectors: {
490
+ active: true,
491
+ totalCount: 30,
492
+ tripped: primaryTripped
493
+ ? {
494
+ detectorId: primaryTripped.detectorId,
495
+ reason: primaryTripped.message || primaryTripped.name,
496
+ severity: primaryTripped.severity || 'WARN',
497
+ revertAction: primaryTripped.revertAction || null,
498
+ worktreeCommand: primaryTripped.worktreeCommand || null
499
+ }
500
+ : null,
501
+ summary: combinedAlerts.length > 0
502
+ ? `${combinedAlerts.length} breaker${combinedAlerts.length === 1 ? '' : 's'} tripped (${combinedAlerts.map(a => a.detectorId).join(', ')})`
503
+ : '30 guards quiet (DET-01..30 Active)'
504
+ },
505
+ scopeCollision: scopeCollisionAlert,
506
+ thinkingDrift,
507
+ prefixRetention: state?.quota?.cache?.prefixRetention || null,
508
+ det17ShadowBloat,
509
+ ttlWatchdog: ttlWatchdogState,
510
+ hysteresisLock: hysteresisLock.getStatus(),
511
+ turnBoundaryQueue: {
512
+ languageServerState: turnBoundaryQueue.languageServerState,
513
+ queuedCount: turnBoundaryQueue.queue.length
514
+ },
515
+ circuitBreakerAlerts: combinedAlerts,
516
+ subagentAudit,
517
+ turnZeroGate: {
518
+ lockedByInvariant1: turnZeroGate.isWarmPrefixLocked(session),
519
+ queuedCount: turnZeroGate.queuedMutations.length,
520
+ activeMcpProfile: turnZeroGate.activeMcpProfile
521
+ },
522
+ checkpoints: {
523
+ latest: latestCkpt,
524
+ evaporationCheck,
525
+ allBands: progressiveCheckpointer.listCheckpoints(targetConvId || state?.sessionId || 'default')
526
+ },
527
+ reflectorQueue: {
528
+ projectHash: reflectorQueue.projectHash,
529
+ items: stagedLearnings,
530
+ stagedCount: stagedLearnings.filter((it) => it.status === 'staged').length,
531
+ approvedCount: stagedLearnings.filter((it) => it.status === 'approved').length
532
+ },
533
+ promptAdvisory,
534
+ savedQuotaLedger: ledgerSummary,
535
+ savings: unifiedSavings,
536
+ proEntitlement: getProEntitlementStatus(),
537
+ fts5Compressor: {
538
+ active: true,
539
+ savedTokens: fts5SavedTokens
540
+ },
541
+ compactionCoach: compactionEval,
542
+ rsiEngine: {
543
+ clusters,
544
+ readyToEvolveCount: clusters.length,
545
+ globalCandidates: rsiEngine?.getGlobalPromotionCandidates ? rsiEngine.getGlobalPromotionCandidates() : []
546
+ },
547
+ uShapedAttention: (() => {
548
+ try {
549
+ const ruleScan = uShapedOptimizer.scanWorkspaceAndGlobalRules();
550
+ return {
551
+ healthScore: ruleScan?.avgPrimacyPct || 94,
552
+ middleTroughRiskCount: ruleScan?.totalMiddleTroughRisk || 0,
553
+ recencyMirrorActive: Boolean(fs.existsSync(path.join(wsDir || '.', 'task.md')) && fs.readFileSync(path.join(wsDir || '.', 'task.md'), 'utf8').includes('## Active Guardrail Pin'))
554
+ };
555
+ } catch (err) {
556
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('buildCoachState:uShapedAttention', err);
557
+ return {
558
+ healthScore: 94,
559
+ middleTroughRiskCount: 0,
560
+ recencyMirrorActive: false
561
+ };
562
+ }
563
+ })(),
564
+ taskQuotaRouter: taskRoute
565
+ };
566
+ } catch (err) {
567
+ recordDaemonDiagnostic('buildCoachState', err);
568
+ return null;
569
+ }
570
+ }
571
+
572
+ function getWorkspaceHash(wsPath = process.cwd()) {
573
+ return crypto.createHash('sha1').update(String(wsPath).toLowerCase()).digest('hex').slice(0, 10);
574
+ }
575
+
576
+ function writeRuntimeLockfile(boundPort, workspacePath = process.cwd()) {
577
+ try {
578
+ const homeDir = getHomeDir();
579
+ fs.mkdirSync(runtimeDir, { recursive: true });
580
+ const ctxtopPortFile = getDaemonPortFile(homeDir);
581
+ const ctxtopDir = path.dirname(ctxtopPortFile);
582
+ const ctxtopJsonFile = path.join(ctxtopDir, 'daemon.json');
583
+ fs.mkdirSync(ctxtopDir, { recursive: true });
584
+
585
+ const wsHash = getWorkspaceHash(workspacePath);
586
+ const payload = JSON.stringify({
587
+ pid: process.pid,
588
+ port: boundPort,
589
+ host: BIND_HOST,
590
+ workspace: workspacePath,
591
+ workspaceHash: wsHash,
592
+ startedAt: new Date().toISOString()
593
+ }, null, 2);
594
+
595
+ const wsPortFile = path.join(runtimeDir, `horizon-${wsHash}.port`);
596
+ const wsJsonFile = path.join(runtimeDir, `horizon-${wsHash}.json`);
597
+ const latestJsonFile = path.join(runtimeDir, 'horizon-latest.json');
598
+
599
+ atomicWriteFileSync(wsPortFile, String(boundPort), { encoding: 'utf8' });
600
+ atomicWriteFileSync(wsJsonFile, payload, { encoding: 'utf8' });
601
+ atomicWriteFileSync(latestJsonFile, payload, { encoding: 'utf8' });
602
+ atomicWriteFileSync(ctxtopPortFile, String(boundPort), { encoding: 'utf8' });
603
+ atomicWriteFileSync(ctxtopJsonFile, payload, { encoding: 'utf8' });
604
+ activeLockfiles = [wsPortFile, wsJsonFile, ctxtopPortFile, ctxtopJsonFile];
605
+ } catch (err) {
606
+ recordDaemonDiagnostic('writeRuntimeLockfile', err);
607
+ }
608
+ }
609
+
610
+ function cleanupRuntimeLockfiles() {
611
+ for (const f of activeLockfiles) {
612
+ try {
613
+ if (fs.existsSync(f)) fs.unlinkSync(f);
614
+ } catch (err) {
615
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('cleanupRuntimeLockfiles', err);
616
+ }
617
+ }
618
+ }
619
+
620
+ process.on('exit', cleanupRuntimeLockfiles);
621
+ process.on('SIGINT', () => { cleanupRuntimeLockfiles(); process.exit(0); });
622
+ process.on('SIGTERM', () => { cleanupRuntimeLockfiles(); process.exit(0); });
623
+
624
+ async function refreshLiveState(force = false, explicitConvId = null) {
625
+ const now = Date.now();
626
+ const htmlMtimeMs = getHtmlMtimeMs();
627
+ const targetConvId = explicitConvId || pinnedConversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || null;
628
+ if (!force && !explicitConvId && cachedLiveState && (now - lastEvalMs) < 1000) {
629
+ if (cachedLiveState) {
630
+ cachedLiveState.uiMtimeMs = htmlMtimeMs;
631
+ try {
632
+ cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
633
+ } catch (err) {
634
+ recordDaemonDiagnostic('refreshLiveState:cachedCoachState', err);
635
+ }
636
+ }
637
+ return cachedLiveState;
638
+ }
639
+ try {
640
+ const [resLive, hostHealth] = await Promise.all([
641
+ runCLI({
642
+ silent: true,
643
+ useNativeCeiling: true,
644
+ stdinData: targetConvId ? { conversation_id: targetConvId } : null
645
+ }),
646
+ inspectHostProcesses({ force: false }).catch((err) => {
647
+ recordDaemonDiagnostic('refreshLiveState:inspectHostProcesses', err);
648
+ return null;
649
+ })
650
+ ]);
651
+ if (resLive && resLive.state) {
652
+ resLive.state.pinnedConversationId = pinnedConversationId;
653
+ resLive.state.hostHealth = hostHealth;
654
+ resLive.state.uiMtimeMs = htmlMtimeMs;
655
+ try {
656
+ const wsPath = resLive.state.workspace?.canonicalPath || process.cwd();
657
+ resLive.state.gitLedger = buildGitCommitTokenLedger(wsPath, []);
658
+ } catch (err) {
659
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('refreshLiveState:gitLedger', err);
660
+ }
661
+ cachedLiveState = resLive.state;
662
+ lastEvalMs = now;
663
+ try {
664
+ cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
665
+ } catch (err) {
666
+ recordDaemonDiagnostic('refreshLiveState:liveCoachState', err);
667
+ }
668
+ if (
669
+ cachedLiveState?.coachState?.taskQuotaRouter &&
670
+ (modelSelectorActuator.mode === 'autopilot' || cachedLiveState.coachState.taskQuotaRouter.routerMode === 'autopilot')
671
+ ) {
672
+ try {
673
+ cachedLiveState.coachState.autoPilotActuation = await actuateRoutingRecommendation(
674
+ cachedLiveState.coachState.taskQuotaRouter,
675
+ {
676
+ actuator: modelSelectorActuator,
677
+ flightMode: 'AUTO_PILOT',
678
+ sessionId: targetConvId || cachedLiveState.sessionId || 'default_session',
679
+ cachedTokens: Number(cachedLiveState?.window?.totalActiveTokens || 0),
680
+ cacheTtlSeconds: Number(cachedLiveState?.quota?.cache?.ttlRemainingSec || 0)
681
+ }
682
+ );
683
+ } catch (err) {
684
+ recordDaemonDiagnostic('refreshLiveState:autoPilotActuation', err);
685
+ }
686
+ }
687
+ return cachedLiveState;
688
+ }
689
+ } catch (err) {
690
+ recordDaemonDiagnostic('refreshLiveState:runCLI', err);
691
+ }
692
+
693
+ if (fs.existsSync(stateFile)) {
694
+ try {
695
+ cachedLiveState = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
696
+ cachedLiveState.uiMtimeMs = htmlMtimeMs;
697
+ if (!cachedLiveState.hostHealth) {
698
+ cachedLiveState.hostHealth = await inspectHostProcesses({ force: false }).catch((err) => {
699
+ recordDaemonDiagnostic('refreshLiveState:stateFileHostProcesses', err);
700
+ return null;
701
+ });
702
+ }
703
+ try {
704
+ cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
705
+ } catch (err) {
706
+ recordDaemonDiagnostic('refreshLiveState:stateFileCoachState', err);
707
+ }
708
+ return cachedLiveState;
709
+ } catch (err) {
710
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('refreshLiveState:readStateFile', err);
711
+ }
712
+ }
713
+
714
+ // Fallback to FlightCheck session sidecar if present (strictly real UUID sessions, never synthetic test fixtures)
715
+ const fcSessionsDir = path.join(getHomeDir(), '.gemini', 'flightcheck', 'sessions');
716
+ if (fs.existsSync(fcSessionsDir)) {
717
+ try {
718
+ const uuidSidecarRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.sidecar\.json$/i;
719
+ const files = fs.readdirSync(fcSessionsDir)
720
+ .filter(f => uuidSidecarRe.test(f))
721
+ .map(f => ({ name: f, time: fs.statSync(path.join(fcSessionsDir, f)).mtimeMs }))
722
+ .sort((a, b) => b.time - a.time);
723
+ if (files.length > 0) {
724
+ cachedLiveState = JSON.parse(fs.readFileSync(path.join(fcSessionsDir, files[0].name), 'utf8'));
725
+ cachedLiveState.uiMtimeMs = htmlMtimeMs;
726
+ try {
727
+ cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
728
+ } catch (err) {
729
+ recordDaemonDiagnostic('refreshLiveState:sidecarCoachState', err);
730
+ }
731
+ return cachedLiveState;
732
+ }
733
+ } catch (err) {
734
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('refreshLiveState:readSidecarFallback', err);
735
+ }
736
+ }
737
+
738
+ if (!cachedLiveState && isDemoMode) {
739
+ try {
740
+ const demoRes = await runCLI({ silent: true, demo: true, useNativeCeiling: true });
741
+ if (demoRes && demoRes.state) {
742
+ cachedLiveState = demoRes.state;
743
+ }
744
+ } catch (err) {
745
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('refreshLiveState:demoFallback', err);
746
+ }
747
+ }
748
+
749
+ if (cachedLiveState) {
750
+ cachedLiveState.uiMtimeMs = htmlMtimeMs;
751
+ try {
752
+ cachedLiveState.coachState = buildCoachState(cachedLiveState, targetConvId);
753
+ } catch (err) {
754
+ recordDaemonDiagnostic('refreshLiveState:finalCoachState', err);
755
+ }
756
+ }
757
+ return cachedLiveState;
758
+ }
759
+
760
+ const LOCAL_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '[::1]']);
761
+
762
+ const LOOPBACK_ORIGIN_RE = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i;
763
+ const IDE_WEBVIEW_ORIGIN_RE = /^(vscode-webview|antigravity):\/\//i;
764
+
765
+ export function isAllowedOriginHeader(origin) {
766
+ if (origin === undefined || origin === '') return true;
767
+ if (origin === 'null') return false;
768
+ const s = String(origin);
769
+ return LOOPBACK_ORIGIN_RE.test(s) || IDE_WEBVIEW_ORIGIN_RE.test(s);
770
+ }
771
+
772
+ /**
773
+ * Allows only requests addressed to this loopback daemon (Host check blocks DNS rebinding)
774
+ * and, when a browser sends an Origin header, only strict local loopback pages or IDE webviews
775
+ * (explicitly rejecting `Origin: null` sandboxed iframes).
776
+ */
777
+ export function isAllowedLocalRequest(req) {
778
+ const hostHeader = String(req.headers.host || '').toLowerCase();
779
+ const hostMatch = hostHeader.match(/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/);
780
+ if (!hostMatch || !LOCAL_HOSTNAMES.has(hostMatch[1])) return false;
781
+
782
+ const sidecarToken = process.env.ANTIGRAVITY_SIDECAR_UI_TOKEN;
783
+ if (sidecarToken && req.headers['x-sidecar-token'] === sidecarToken) {
784
+ return true;
785
+ }
786
+
787
+ return isAllowedOriginHeader(req.headers.origin);
788
+ }
789
+
790
+ /**
791
+ * Reads an HTTP request body up to `maxBytes` (default 1 MB).
792
+ * Responds with `413 Payload Too Large` and destroys the socket on oversized payloads.
793
+ */
794
+ function readRequestBody(req, res, maxBytes = MAX_REQUEST_BODY_BYTES) {
795
+ return new Promise((resolve) => {
796
+ const declaredLen = Number(req.headers['content-length']);
797
+ if (Number.isFinite(declaredLen) && declaredLen > maxBytes) {
798
+ res.writeHead(413, { 'Content-Type': 'application/json', 'Connection': 'close' });
799
+ res.end(
800
+ JSON.stringify({ success: false, error: `Payload Too Large (max ${maxBytes} bytes)` }),
801
+ () => {
802
+ try {
803
+ req.destroy();
804
+ } catch (err) {
805
+ if (err?.code !== 'ERR_STREAM_DESTROYED') recordDaemonDiagnostic('readRequestBody:destroy413Header', err);
806
+ }
807
+ }
808
+ );
809
+ resolve(null);
810
+ return;
811
+ }
812
+
813
+ const chunks = [];
814
+ let totalBytes = 0;
815
+ let aborted = false;
816
+
817
+ req.on('data', (chunk) => {
818
+ if (aborted) return;
819
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
820
+ totalBytes += buf.length;
821
+ if (totalBytes > maxBytes) {
822
+ aborted = true;
823
+ try {
824
+ req.pause();
825
+ } catch (err) {
826
+ recordDaemonDiagnostic('readRequestBody:pause', err);
827
+ }
828
+ res.writeHead(413, { 'Content-Type': 'application/json', 'Connection': 'close' });
829
+ res.end(
830
+ JSON.stringify({ success: false, error: `Payload Too Large (max ${maxBytes} bytes)` }),
831
+ () => {
832
+ try {
833
+ req.destroy();
834
+ } catch (err) {
835
+ if (err?.code !== 'ERR_STREAM_DESTROYED') recordDaemonDiagnostic('readRequestBody:destroy413Stream', err);
836
+ }
837
+ }
838
+ );
839
+ resolve(null);
840
+ return;
841
+ }
842
+ chunks.push(buf);
843
+ });
844
+
845
+ req.on('end', () => {
846
+ if (aborted) return;
847
+ resolve(Buffer.concat(chunks).toString('utf8'));
848
+ });
849
+
850
+ req.on('error', () => {
851
+ if (aborted) return;
852
+ aborted = true;
853
+ resolve(null);
854
+ });
855
+ });
856
+ }
857
+
858
+ const RULE_FILE_RE = /(^|[\\/])(AGENTS\.md|GEMINI\.md)$|[\\/]\.agents[\\/]rules[\\/][^\\/]+\.md$/i;
859
+
860
+ function parseJsonBodyOrSend400(bodyStr, res, routeName) {
861
+ const trimmed = String(bodyStr ?? '').trim();
862
+ if (!trimmed) return {};
863
+ try {
864
+ const parsed = JSON.parse(trimmed);
865
+ return parsed && typeof parsed === 'object' ? parsed : {};
866
+ } catch (err) {
867
+ recordDaemonDiagnostic(`${routeName}:parseBody`, err);
868
+ if (!res.headersSent) {
869
+ res.writeHead(400, { 'Content-Type': 'application/json' });
870
+ res.end(JSON.stringify({ ok: false, success: false, error: err?.message || 'Invalid JSON' }));
871
+ }
872
+ return null;
873
+ }
874
+ }
875
+
876
+ function sendRouteError500(res, routeName, err) {
877
+ recordDaemonDiagnostic(routeName, err);
878
+ if (!res.headersSent) {
879
+ res.writeHead(500, { 'Content-Type': 'application/json' });
880
+ res.end(JSON.stringify({ ok: false, success: false, error: String(err?.message || err) }));
881
+ }
882
+ }
883
+
884
+ const server = http.createServer(async (req, res) => {
885
+ try {
886
+ const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`);
887
+
888
+ const isStaticUiAsset = req.method === 'GET' && (
889
+ url.pathname === '/' ||
890
+ url.pathname === '/index.html' ||
891
+ url.pathname === '/widget' ||
892
+ url.pathname === '/widget.html' ||
893
+ url.pathname === '/simple' ||
894
+ url.pathname === '/simple.html' ||
895
+ url.pathname === '/advanced' ||
896
+ url.pathname === '/advanced.html' ||
897
+ url.pathname === '/preload.js' ||
898
+ url.pathname === '/favicon.ico'
899
+ );
900
+
901
+ // Host header is always verified (blocks DNS rebinding).
902
+ // Origin is strictly enforced for API / mutation endpoints.
903
+ const hostHeader = String(req.headers.host || '').toLowerCase();
904
+ const hostMatch = hostHeader.match(/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/);
905
+ const isHostValid = hostMatch && LOCAL_HOSTNAMES.has(hostMatch[1]);
906
+ const sidecarToken = process.env.ANTIGRAVITY_SIDECAR_UI_TOKEN;
907
+ const hasValidTokenQuery = Boolean(sidecarToken && url.searchParams.get('token') === sidecarToken);
908
+
909
+ if (!isHostValid || (!isStaticUiAsset && !hasValidTokenQuery && !isAllowedLocalRequest(req))) {
910
+ res.writeHead(403, { 'Content-Type': 'application/json' });
911
+ res.end(JSON.stringify({ success: false, error: 'Forbidden: cross-origin or non-local request' }));
912
+ return;
913
+ }
914
+
915
+ // Emit CORS headers ONLY echoing the specific validated origin (never wildcard '*')
916
+ const origin = req.headers.origin;
917
+ if (origin && isAllowedOriginHeader(origin)) {
918
+ res.setHeader('Access-Control-Allow-Origin', origin);
919
+ res.setHeader('Vary', 'Origin');
920
+ }
921
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
922
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Sidecar-Token, X-Horizon-CSRF');
923
+
924
+ if (req.method === 'OPTIONS') {
925
+ res.writeHead(204);
926
+ res.end();
927
+ return;
928
+ }
929
+
930
+ if (url.pathname === '/api/csrf-token' && req.method === 'GET') {
931
+ res.writeHead(200, {
932
+ 'Content-Type': 'application/json; charset=utf-8',
933
+ 'Cache-Control': 'no-store'
934
+ });
935
+ res.end(JSON.stringify({ ok: true, csrfToken: HORIZON_CSRF_TOKEN }));
936
+ return;
937
+ }
938
+
939
+ // Enforce per-boot random CSRF token on browser-originated mutating POST requests
940
+ if (req.method === 'POST') {
941
+ const providedCsrf = req.headers['x-horizon-csrf'];
942
+ const isBrowserOriginated = Boolean(req.headers.origin);
943
+ const hasValidSidecarHeader = Boolean(sidecarToken && req.headers['x-sidecar-token'] === sidecarToken);
944
+ if (isBrowserOriginated && !hasValidSidecarHeader && !isValidCsrfToken(providedCsrf)) {
945
+ res.writeHead(403, { 'Content-Type': 'application/json' });
946
+ res.end(JSON.stringify({ success: false, error: 'Forbidden: missing or invalid X-Horizon-CSRF token' }));
947
+ return;
948
+ }
949
+ if (!isBrowserOriginated && providedCsrf !== undefined && !isValidCsrfToken(providedCsrf)) {
950
+ res.writeHead(403, { 'Content-Type': 'application/json' });
951
+ res.end(JSON.stringify({ success: false, error: 'Forbidden: invalid X-Horizon-CSRF token' }));
952
+ return;
953
+ }
954
+ }
955
+
956
+ if (url.pathname === '/favicon.ico') {
957
+ res.writeHead(204, { 'Cache-Control': 'public, max-age=86400' });
958
+ res.end();
959
+ return;
960
+ }
961
+
962
+ if (url.pathname === '/api/health') {
963
+ const addr = server.address();
964
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
965
+ res.end(JSON.stringify({
966
+ ok: true,
967
+ pid: process.pid,
968
+ port: addr ? addr.port : 0,
969
+ workspace: cachedLiveState?.workspace?.canonicalPath || process.cwd(),
970
+ pinnedConversationId,
971
+ diagnostics: getDaemonDiagnostics()
972
+ }));
973
+ return;
974
+ }
975
+
976
+ if (url.pathname === '/preload.js') {
977
+ const candidates = [
978
+ path.join(getHomeDir(), '.gemini', 'antigravity', 'lib', 'node_modules', 'sidecar_sdk', 'preload.js'),
979
+ path.join(getHomeDir(), '.gemini', 'config', 'node_modules', 'sidecar_sdk', 'preload.js')
980
+ ];
981
+ const target = candidates.find(p => fs.existsSync(p));
982
+ res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8' });
983
+ res.end(target ? fs.readFileSync(target) : '// no preload');
984
+ return;
985
+ }
986
+
987
+ if (url.pathname === '/simple' || url.pathname === '/simple.html') {
988
+ const qConv = url.searchParams.get('conversationId');
989
+ if (qConv && qConv !== 'auto') {
990
+ pinnedConversationId = qConv;
991
+ }
992
+ const initState = await refreshLiveState(false, pinnedConversationId);
993
+ res.writeHead(200, {
994
+ 'Content-Type': 'text/html; charset=utf-8',
995
+ 'Cache-Control': 'no-store, no-cache, must-revalidate'
996
+ });
997
+ const simpleViewHtml = path.resolve(__dirname, '../../src/webview/simple_view.html');
998
+ if (fs.existsSync(simpleViewHtml)) {
999
+ let html = fs.readFileSync(simpleViewHtml, 'utf8');
1000
+ const mtimeMs = fs.statSync(simpleViewHtml).mtimeMs;
1001
+ const mtimeScript = `<script id="liveInitialMtime">window.__INITIAL_UI_MTIME__ = ${mtimeMs}; window.__HORIZON_CSRF_TOKEN__ = ${JSON.stringify(HORIZON_CSRF_TOKEN)};</script>`;
1002
+ if (initState) {
1003
+ initState.uiMtimeMs = mtimeMs;
1004
+ const safeJson = JSON.stringify(initState)
1005
+ .replace(/</g, '\\u003c')
1006
+ .replace(/\u2028/g, '\\u2028')
1007
+ .replace(/\u2029/g, '\\u2029');
1008
+ const stateScript = `<script id="liveInitialState">window.__LIVE_INITIAL_STATE__ = ${safeJson};</script>`;
1009
+ html = html.replace(
1010
+ '<script id="precomputedCatalogScript">',
1011
+ () => `${mtimeScript}\n${stateScript}\n<script id="precomputedCatalogScript">`
1012
+ );
1013
+ } else {
1014
+ html = html.replace(
1015
+ '<script id="precomputedCatalogScript">',
1016
+ () => `${mtimeScript}\n<script id="precomputedCatalogScript">`
1017
+ );
1018
+ }
1019
+ res.end(html);
1020
+ } else {
1021
+ res.end('<h1>Highbeam Simple View</h1>');
1022
+ }
1023
+ return;
1024
+ }
1025
+
1026
+ if (url.pathname === '/advanced' || url.pathname === '/advanced.html') {
1027
+ const qConv = url.searchParams.get('conversationId');
1028
+ if (qConv && qConv !== 'auto') {
1029
+ pinnedConversationId = qConv;
1030
+ }
1031
+ const initState = await refreshLiveState(false, pinnedConversationId);
1032
+ res.writeHead(200, {
1033
+ 'Content-Type': 'text/html; charset=utf-8',
1034
+ 'Cache-Control': 'no-store, no-cache, must-revalidate'
1035
+ });
1036
+ const advancedViewHtml = path.resolve(__dirname, '../../src/webview/advanced_view.html');
1037
+ if (fs.existsSync(advancedViewHtml)) {
1038
+ let html = fs.readFileSync(advancedViewHtml, 'utf8');
1039
+ const mtimeMs = fs.statSync(advancedViewHtml).mtimeMs;
1040
+ const mtimeScript = `<script id="liveInitialMtime">window.__INITIAL_UI_MTIME__ = ${mtimeMs}; window.__HORIZON_CSRF_TOKEN__ = ${JSON.stringify(HORIZON_CSRF_TOKEN)};</script>`;
1041
+ if (initState) {
1042
+ initState.uiMtimeMs = mtimeMs;
1043
+ const safeJson = JSON.stringify(initState)
1044
+ .replace(/</g, '\\u003c')
1045
+ .replace(/\u2028/g, '\\u2028')
1046
+ .replace(/\u2029/g, '\\u2029');
1047
+ const stateScript = `<script id="liveInitialState">window.__LIVE_INITIAL_STATE__ = ${safeJson};</script>`;
1048
+ html = html.replace(
1049
+ '<script id="precomputedCatalogScript">',
1050
+ () => `${mtimeScript}\n${stateScript}\n<script id="precomputedCatalogScript">`
1051
+ );
1052
+ } else {
1053
+ html = html.replace(
1054
+ '<script id="precomputedCatalogScript">',
1055
+ () => `${mtimeScript}\n<script id="precomputedCatalogScript">`
1056
+ );
1057
+ }
1058
+ res.end(html);
1059
+ } else {
1060
+ res.end('<h1>Highbeam Advanced View</h1>');
1061
+ }
1062
+ return;
1063
+ }
1064
+
1065
+ if (url.pathname === '/' || url.pathname === '/index.html' || url.pathname === '/widget' || url.pathname === '/widget.html') {
1066
+ const qConv = url.searchParams.get('conversationId');
1067
+ if (qConv && qConv !== 'auto') {
1068
+ pinnedConversationId = qConv;
1069
+ }
1070
+ const initState = await refreshLiveState(false, pinnedConversationId);
1071
+ res.writeHead(200, {
1072
+ 'Content-Type': 'text/html; charset=utf-8',
1073
+ 'Cache-Control': 'no-store, no-cache, must-revalidate'
1074
+ });
1075
+ const rawHtmlPath = fs.existsSync(horizonPanelHtml)
1076
+ ? horizonPanelHtml
1077
+ : (fs.existsSync(sidePaneHtml) ? sidePaneHtml : null);
1078
+ if (rawHtmlPath) {
1079
+ let html = fs.readFileSync(rawHtmlPath, 'utf8');
1080
+ const mtimeMs = getHtmlMtimeMs();
1081
+ const mtimeScript = `<script id="liveInitialMtime">window.__INITIAL_UI_MTIME__ = ${mtimeMs}; window.__HORIZON_CSRF_TOKEN__ = ${JSON.stringify(HORIZON_CSRF_TOKEN)};</script>`;
1082
+ if (initState) {
1083
+ initState.uiMtimeMs = mtimeMs;
1084
+ const safeJson = JSON.stringify(initState)
1085
+ .replace(/</g, '\\u003c')
1086
+ .replace(/\u2028/g, '\\u2028')
1087
+ .replace(/\u2029/g, '\\u2029');
1088
+ const stateScript = `<script id="liveInitialState">window.__LIVE_INITIAL_STATE__ = ${safeJson};</script>`;
1089
+ html = html.replace(
1090
+ '<script id="precomputedCatalogScript">',
1091
+ () => `${mtimeScript}\n${stateScript}\n<script id="precomputedCatalogScript">`
1092
+ );
1093
+ } else {
1094
+ html = html.replace(
1095
+ '<script id="precomputedCatalogScript">',
1096
+ () => `${mtimeScript}\n<script id="precomputedCatalogScript">`
1097
+ );
1098
+ }
1099
+ res.end(html);
1100
+ } else {
1101
+ res.end('<h1>Highbeam Side-Pane</h1>');
1102
+ }
1103
+ return;
1104
+ }
1105
+
1106
+ if (url.pathname === '/api/state') {
1107
+ const qConv = url.searchParams.get('conversationId');
1108
+ const qScenario = url.searchParams.get('scenario');
1109
+ if (qScenario) {
1110
+ process.env.HORIZON_DEMO = '1';
1111
+ process.env.HORIZON_DEMO_SCENARIO = qScenario;
1112
+ }
1113
+ if (qConv) {
1114
+ pinnedConversationId = qConv === 'auto' ? null : qConv;
1115
+ }
1116
+ const forceEval = Boolean(qConv || qScenario || url.searchParams.get('force') === '1');
1117
+ const state = await refreshLiveState(forceEval, pinnedConversationId);
1118
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
1119
+ res.end(JSON.stringify(state || {}));
1120
+ return;
1121
+ }
1122
+
1123
+ // Route: GET /api/cost-radar (Sprint 2.2 HTML/SVG timeline artifact, loopback only)
1124
+ if (url.pathname === '/api/cost-radar' && req.method === 'GET') {
1125
+ try {
1126
+ const state = await refreshLiveState(false, pinnedConversationId);
1127
+ const { html, summary } = buildCostRadarFromState(state || {});
1128
+ if (url.searchParams.get('format') === 'json') {
1129
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
1130
+ res.end(JSON.stringify({ ok: true, ...summary }));
1131
+ } else {
1132
+ res.writeHead(200, {
1133
+ 'Content-Type': 'text/html; charset=utf-8',
1134
+ 'Cache-Control': 'no-store',
1135
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:"
1136
+ });
1137
+ res.end(html);
1138
+ }
1139
+ } catch (err) {
1140
+ sendRouteError500(res, 'GET /api/cost-radar', err);
1141
+ }
1142
+ return;
1143
+ }
1144
+
1145
+ if (url.pathname === '/api/stream') {
1146
+ if (clients.size >= MAX_SSE_CLIENTS) {
1147
+ res.writeHead(429, { 'Content-Type': 'application/json' });
1148
+ res.end(JSON.stringify({ success: false, error: `SSE client cap reached (max ${MAX_SSE_CLIENTS})` }));
1149
+ return;
1150
+ }
1151
+
1152
+ res.writeHead(200, {
1153
+ 'Content-Type': 'text/event-stream',
1154
+ 'Cache-Control': 'no-cache',
1155
+ 'Connection': 'keep-alive'
1156
+ });
1157
+
1158
+ clients.add(res);
1159
+ const current = await refreshLiveState(true);
1160
+ if (current) {
1161
+ res.write(`data: ${JSON.stringify(current)}\n\n`);
1162
+ }
1163
+
1164
+ req.on('close', () => {
1165
+ clients.delete(res);
1166
+ });
1167
+ return;
1168
+ }
1169
+
1170
+ if (url.pathname === '/api/settings') {
1171
+ if (req.method === 'GET') {
1172
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
1173
+ res.end(JSON.stringify({ settings: loadSettings(defaultCacheDir), limits: SETTINGS_LIMITS }));
1174
+ return;
1175
+ }
1176
+ if (req.method === 'POST') {
1177
+ const bodyStr = await readRequestBody(req, res);
1178
+ if (bodyStr === null) return;
1179
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/settings');
1180
+ if (body === null) return;
1181
+ const patch = {};
1182
+ for (const k of ['safeLimitTokens', 'reminderAtPct', 'modelOverrides']) {
1183
+ if (body && body[k] !== undefined) patch[k] = body[k];
1184
+ }
1185
+ try {
1186
+ const settings = saveSettings(defaultCacheDir, patch);
1187
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1188
+ broadcastState(nextState);
1189
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1190
+ res.end(JSON.stringify({ success: true, settings, state: nextState }));
1191
+ } catch (e) {
1192
+ sendRouteError500(res, 'POST /api/settings', e);
1193
+ }
1194
+ return;
1195
+ }
1196
+ res.writeHead(405);
1197
+ res.end('Method Not Allowed');
1198
+ return;
1199
+ }
1200
+
1201
+ // Route: POST /api/prune (Prefix-Safe Surgical Context Pruner & AST Folder)
1202
+ if (url.pathname === '/api/prune' && req.method === 'POST') {
1203
+ const bodyStr = await readRequestBody(req, res);
1204
+ if (bodyStr === null) return;
1205
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/prune');
1206
+ if (body === null) return;
1207
+ const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
1208
+ const sessionInfo = findSessionDirectory(targetConvId);
1209
+ if (!sessionInfo || !sessionInfo.sessionDir) {
1210
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1211
+ res.end(JSON.stringify({ success: false, error: 'Active session directory not found' }));
1212
+ return;
1213
+ }
1214
+ const pruneResult = pruneSessionTranscript(sessionInfo.sessionDir, {
1215
+ dryRun: Boolean(body.dryRun),
1216
+ forceHotCache: Boolean(body.forceHotCache),
1217
+ cacheDir: defaultCacheDir
1218
+ });
1219
+ const nextState = await refreshLiveState(true, targetConvId);
1220
+ broadcastState(nextState);
1221
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1222
+ res.end(JSON.stringify({ ...pruneResult, state: nextState }));
1223
+ return;
1224
+ }
1225
+
1226
+ // Route: POST /api/host/reap (Host Process & Zombie Subagent/MCP Watchdog)
1227
+ if (url.pathname === '/api/host/reap' && req.method === 'POST') {
1228
+ const bodyStr = await readRequestBody(req, res);
1229
+ if (bodyStr === null) return;
1230
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/host/reap');
1231
+ if (body === null) return;
1232
+ const reapResult = await reapOrphanProcesses(body.pids || null);
1233
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1234
+ broadcastState(nextState);
1235
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1236
+ res.end(JSON.stringify({ ...reapResult, state: nextState }));
1237
+ return;
1238
+ }
1239
+
1240
+ // Route: POST /api/open-brain (Dual-Target Session Jump: Alt+Click opens ~/.gemini/<surface>/brain/<uuid>/)
1241
+ if (url.pathname === '/api/open-brain' && req.method === 'POST') {
1242
+ const bodyStr = await readRequestBody(req, res);
1243
+ if (bodyStr === null) return;
1244
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/open-brain');
1245
+ if (body === null) return;
1246
+ const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
1247
+ const requestedSurface = ['antigravity', 'antigravity-ide', 'antigravity-cli'].includes(body.surface)
1248
+ ? body.surface
1249
+ : null;
1250
+ const sessionInfo = findSessionDirectory(targetConvId);
1251
+ const safeId = String(targetConvId || sessionInfo?.sessionId || '').replace(/[^a-zA-Z0-9_-]/g, '');
1252
+ const matchedInfo = (sessionInfo && sessionInfo.sessionId === safeId) ? sessionInfo : null;
1253
+ const surfaceName = requestedSurface || matchedInfo?.storeName || sessionInfo?.storeName || cachedLiveState?.storeSource || 'antigravity';
1254
+
1255
+ let resolvedBrainDir = null;
1256
+ if (matchedInfo && matchedInfo.sessionDir && fs.existsSync(matchedInfo.sessionDir)) {
1257
+ resolvedBrainDir = matchedInfo.sessionDir;
1258
+ } else if (safeId) {
1259
+ const directBrainDir = path.join(getHomeDir(), '.gemini', surfaceName, 'brain', safeId);
1260
+ if (fs.existsSync(directBrainDir)) {
1261
+ resolvedBrainDir = directBrainDir;
1262
+ }
1263
+ }
1264
+ let fallbackUsed = false;
1265
+
1266
+ if (!resolvedBrainDir || !fs.existsSync(resolvedBrainDir)) {
1267
+ const convDir = path.join(getHomeDir(), '.gemini', surfaceName, 'conversations');
1268
+ if (fs.existsSync(convDir)) {
1269
+ resolvedBrainDir = convDir;
1270
+ fallbackUsed = true;
1271
+ } else {
1272
+ const surfaceRoot = path.join(getHomeDir(), '.gemini', surfaceName);
1273
+ if (fs.existsSync(surfaceRoot)) {
1274
+ resolvedBrainDir = surfaceRoot;
1275
+ fallbackUsed = true;
1276
+ }
1277
+ }
1278
+ }
1279
+
1280
+ if (!resolvedBrainDir || !fs.existsSync(resolvedBrainDir)) {
1281
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1282
+ res.end(JSON.stringify({ success: false, error: 'Session brain directory not found' }));
1283
+ return;
1284
+ }
1285
+
1286
+ if (!body.dryRun && process.env.HORIZON_TEST_NO_SPAWN !== '1') {
1287
+ try {
1288
+ const onSpawnDone = (spawnErr) => {
1289
+ if (spawnErr) recordDaemonDiagnostic('POST /api/open-brain:execFile', spawnErr);
1290
+ };
1291
+ if (process.platform === 'win32') {
1292
+ execFile('explorer.exe', [resolvedBrainDir], onSpawnDone);
1293
+ } else if (process.platform === 'darwin') {
1294
+ execFile('open', [resolvedBrainDir], onSpawnDone);
1295
+ } else {
1296
+ execFile('xdg-open', [resolvedBrainDir], onSpawnDone);
1297
+ }
1298
+ } catch (err) {
1299
+ recordDaemonDiagnostic('POST /api/open-brain:spawn', err);
1300
+ }
1301
+ }
1302
+
1303
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1304
+ res.end(JSON.stringify({
1305
+ success: true,
1306
+ conversationId: safeId,
1307
+ surface: surfaceName,
1308
+ surfaceTag: resolveSurfaceTag(surfaceName),
1309
+ brainDir: resolvedBrainDir,
1310
+ fallbackUsed
1311
+ }));
1312
+ return;
1313
+ }
1314
+
1315
+ // Route: POST /api/handoff or /api/handoff/generate (The Baton Pass /handoff Markdown Generator)
1316
+ if ((url.pathname === '/api/handoff' || url.pathname === '/api/handoff/generate') && req.method === 'POST') {
1317
+ const bodyStr = await readRequestBody(req, res);
1318
+ if (bodyStr === null) return;
1319
+ const body = parseJsonBodyOrSend400(bodyStr, res, `POST ${url.pathname}`);
1320
+ if (body === null) return;
1321
+ const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
1322
+ const state = await refreshLiveState(false, targetConvId) || cachedLiveState || {};
1323
+ const handoffRes = generateHandoffMarkdown(state, {
1324
+ timestamp: body.timestamp || null,
1325
+ workspacePath: body.workspacePath || state?.workspace?.canonicalPath || process.cwd(),
1326
+ writeToDisk: body.writeToDisk !== false
1327
+ });
1328
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1329
+ res.end(JSON.stringify(handoffRes));
1330
+ return;
1331
+ }
1332
+
1333
+ // Route: POST /api/hooks/dampen (Fail-Open CLI Command Dampening Hook in .agents/hooks.json)
1334
+ if (url.pathname === '/api/hooks/dampen' && req.method === 'POST') {
1335
+ const bodyStr = await readRequestBody(req, res);
1336
+ if (bodyStr === null) return;
1337
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/hooks/dampen');
1338
+ if (body === null) return;
1339
+ const wsPath = body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
1340
+ const hookRes = registerCliDampeningHook(wsPath, {
1341
+ command: body.command || '',
1342
+ maxLines: body.maxLines || 100,
1343
+ logFile: body.logFile || '.agents/tmp/cli_stdout.log',
1344
+ writeToDisk: body.writeToDisk !== false
1345
+ });
1346
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1347
+ res.end(JSON.stringify(hookRes));
1348
+ return;
1349
+ }
1350
+
1351
+ // Route: POST /api/rules/promote (Attention-Aware Rule Promotion in Primacy/Recency zones)
1352
+ if (url.pathname === '/api/rules/promote' && req.method === 'POST') {
1353
+ const bodyStr = await readRequestBody(req, res);
1354
+ if (bodyStr === null) return;
1355
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/rules/promote');
1356
+ if (body === null) return;
1357
+ const wsPath = body.targetPath || body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
1358
+ // Only rule files may be written: a directory target, or an explicit AGENTS.md / GEMINI.md / .agents/rules/*.md file.
1359
+ let isDirTarget = false;
1360
+ try {
1361
+ isDirTarget = fs.existsSync(wsPath) && fs.statSync(wsPath).isDirectory();
1362
+ } catch (err) {
1363
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('POST /api/rules/promote:statTarget', err);
1364
+ }
1365
+ const badTarget = !isDirTarget && !RULE_FILE_RE.test(String(wsPath));
1366
+ const badFileName = body.targetFileName != null && !/^[\w.-]+\.md$/i.test(String(body.targetFileName));
1367
+ if (badTarget || badFileName) {
1368
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1369
+ res.end(JSON.stringify({ success: false, error: 'Rule promotion target must be a rule file (AGENTS.md, GEMINI.md, .agents/rules/*.md)' }));
1370
+ return;
1371
+ }
1372
+ const fallbackRule = cachedLiveState?.brainSignals?.userCorrectionTexts?.[0] ||
1373
+ 'Follow all in-chat user corrections and architectural constraints.';
1374
+ const resolvedRuleText = body.ruleText || fallbackRule;
1375
+
1376
+ const liveCachedTokens = Number(
1377
+ body.cachedTokens ??
1378
+ cachedLiveState?.window?.totalActiveTokens ??
1379
+ cachedLiveState?.tokens?.total ??
1380
+ 0
1381
+ );
1382
+ const liveTtlSec = Math.max(0, Number(
1383
+ body.cacheTtlSeconds ??
1384
+ cachedLiveState?.quota?.cache?.ttlRemainingSec ??
1385
+ cachedLiveState?.cache?.ttlRemainingSec ??
1386
+ 0
1387
+ ) || 0);
1388
+ const liveTurnCount = Number(
1389
+ body.turnCount ??
1390
+ cachedLiveState?.window?.turnCount ??
1391
+ cachedLiveState?.turnCount ??
1392
+ 1
1393
+ );
1394
+ const shieldStatus = prefixCacheShield.getStatus({
1395
+ cachedTokens: liveCachedTokens,
1396
+ cacheTtlSeconds: liveTtlSec,
1397
+ turnCount: liveTurnCount
1398
+ });
1399
+
1400
+ if (shieldStatus.locked && body.writeToDisk !== false && !body.forceHotCache) {
1401
+ try {
1402
+ const targetWsDir = isDirTarget ? wsPath : path.dirname(wsPath);
1403
+ reflectorQueue.setWorkspaceDir(targetWsDir);
1404
+ reflectorQueue.enqueue({
1405
+ directive_action: resolvedRuleText,
1406
+ domain: 'rules',
1407
+ sessionId: cachedLiveState?.sessionId || pinnedConversationId || 'default-session'
1408
+ });
1409
+ } catch (err) {
1410
+ recordDaemonDiagnostic('POST /api/rules/promote:enqueueStaged', err);
1411
+ }
1412
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1413
+ res.end(JSON.stringify({
1414
+ success: false,
1415
+ staged: true,
1416
+ requiresConfirmation: true,
1417
+ ttlRemainingSec: liveTtlSec,
1418
+ cachedTokens: liveCachedTokens,
1419
+ reason: `Warm prompt cache active (${liveTtlSec}s TTL). Rule promotion staged until cache expires to protect your 95% KV discount.`
1420
+ }));
1421
+ return;
1422
+ }
1423
+
1424
+ const promoRes = promoteRuleWithAttentionZone(wsPath, resolvedRuleText, {
1425
+ zone: body.zone || 'primacy',
1426
+ targetFileName: body.targetFileName || null,
1427
+ maxLines: body.maxLines || 200,
1428
+ writeToDisk: body.writeToDisk !== false
1429
+ });
1430
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1431
+ res.end(JSON.stringify(promoRes));
1432
+ return;
1433
+ }
1434
+
1435
+ // Route: POST /api/export/sanitized (Zero-PII Sanitized Snapshot Exporter)
1436
+ if (url.pathname === '/api/export/sanitized' && req.method === 'POST') {
1437
+ const bodyStr = await readRequestBody(req, res);
1438
+ if (bodyStr === null) return;
1439
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/export/sanitized');
1440
+ if (body === null) return;
1441
+ const targetState = body.state || cachedLiveState || (await refreshLiveState(true, pinnedConversationId)) || {};
1442
+ const outPath = path.join(defaultCacheDir, `sanitized_snapshot_${Date.now()}.json`);
1443
+ const expRes = exportSanitizedSnapshot(targetState, {
1444
+ format: body.format || 'json',
1445
+ outputPath: outPath
1446
+ });
1447
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1448
+ res.end(JSON.stringify(expRes));
1449
+ return;
1450
+ }
1451
+
1452
+ // Route: POST /api/surgeon (Offline Tool-Output Surgeon)
1453
+ if (url.pathname === '/api/surgeon' && req.method === 'POST') {
1454
+ const bodyStr = await readRequestBody(req, res);
1455
+ if (bodyStr === null) return;
1456
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/surgeon');
1457
+ if (body === null) return;
1458
+ const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
1459
+ const sessionInfo = findSessionDirectory(targetConvId);
1460
+ const transcriptFile = body.transcriptPath ||
1461
+ (sessionInfo?.sessionDir ? path.join(sessionInfo.sessionDir, '.system_generated', 'logs', 'transcript_full.jsonl') : null);
1462
+ const surgRes = executeToolOutputSurgery(transcriptFile, { dryRun: Boolean(body.dryRun) });
1463
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1464
+ res.end(JSON.stringify(surgRes));
1465
+ return;
1466
+ }
1467
+
1468
+ // Route: GET /api/memory/resume (SQLite FTS5 Episodic Memory Resume Pack)
1469
+ if (url.pathname === '/api/memory/resume' && req.method === 'GET') {
1470
+ const query = url.searchParams.get('q') || '';
1471
+ const wsPath = url.searchParams.get('workspace') || cachedLiveState?.workspace?.canonicalPath || process.cwd();
1472
+ const epDbPath = path.join(getFlightcheckDir(), 'episodic_memory.db');
1473
+ const pack = await synthesizeResumeHerePack(epDbPath, { workspacePath: wsPath, query });
1474
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
1475
+ res.end(JSON.stringify(pack));
1476
+ return;
1477
+ }
1478
+
1479
+ // Helper: Resolve live or caller-supplied warm-cache state for ISS-041 PrefixCacheShield fencing
1480
+ const resolveRouteCacheContext = (body = {}) => {
1481
+ const cachedTokens = body.cachedTokens !== undefined
1482
+ ? Number(body.cachedTokens || 0)
1483
+ : Number(cachedLiveState?.window?.totalActiveTokens ?? cachedLiveState?.tokens?.total ?? 0);
1484
+ const cacheTtlSeconds = body.cacheTtlSeconds !== undefined
1485
+ ? Number(body.cacheTtlSeconds || 0)
1486
+ : Number(cachedLiveState?.quota?.cache?.ttlRemainingSec ?? cachedLiveState?.cache?.ttlRemainingSec ?? 0);
1487
+ const cacheState = body.cacheState || body.options?.cacheState || null;
1488
+ const cacheWarm = body.cacheWarm === true || body.options?.cacheWarm === true;
1489
+ return {
1490
+ cachedTokens,
1491
+ cacheTtlSeconds,
1492
+ ttlRemainingSeconds: cacheTtlSeconds,
1493
+ ...(cacheState ? { cacheState } : {}),
1494
+ ...(cacheWarm ? { cacheWarm: true } : {})
1495
+ };
1496
+ };
1497
+
1498
+ // Route: POST /api/shield/flush (Flush PrefixCacheShield staged deltas — fenced when cache is warm unless force=true)
1499
+ if (url.pathname === '/api/shield/flush' && req.method === 'POST') {
1500
+ const bodyStr = await readRequestBody(req, res);
1501
+ if (bodyStr === null) return;
1502
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/shield/flush');
1503
+ if (body === null) return;
1504
+ const sessCtx = resolveRouteCacheContext(body);
1505
+ const forceFlush = body.force === true || body.forceColdBust === true;
1506
+ if (!forceFlush && prefixCacheShield.isPrefixLocked(sessCtx)) {
1507
+ const shieldState = prefixCacheShield.getStatus(sessCtx);
1508
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1509
+ res.end(JSON.stringify({
1510
+ success: true,
1511
+ flushed: false,
1512
+ deferred: true,
1513
+ reason: 'CACHE_WARM_FENCE',
1514
+ queuedCount: shieldState.queuedCount,
1515
+ ttlRemainingSec: sessCtx.cacheTtlSeconds,
1516
+ cachedTokens: sessCtx.cachedTokens
1517
+ }));
1518
+ return;
1519
+ }
1520
+ const resPayload = prefixCacheShield._flushAllNow('MANUAL_FLUSH');
1521
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1522
+ broadcastState(nextState);
1523
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1524
+ res.end(JSON.stringify({ success: true, deferred: false, ...resPayload, state: nextState }));
1525
+ return;
1526
+ }
1527
+
1528
+ // Route: POST /api/tail/trim (Read-Only Host Transcript Analysis -> Staged Plugin Output)
1529
+ if (url.pathname === '/api/tail/trim' && req.method === 'POST') {
1530
+ const bodyStr = await readRequestBody(req, res);
1531
+ if (bodyStr === null) return;
1532
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/tail/trim');
1533
+ if (body === null) return;
1534
+ const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || null;
1535
+ const sessionInfo = findSessionDirectory(targetConvId);
1536
+ const transcriptFile = body.transcriptPath || (sessionInfo?.sessionDir
1537
+ ? path.join(sessionInfo.sessionDir, '.system_generated', 'logs', 'transcript_full.jsonl')
1538
+ : null);
1539
+ let trimRes = {
1540
+ trimmed: false,
1541
+ message: 'No transcript found',
1542
+ hostTranscriptMutated: false,
1543
+ persistBlockedReason: body.persist ? 'HOST_TRANSCRIPT_READONLY_GUARD' : null
1544
+ };
1545
+ if (transcriptFile && fs.existsSync(transcriptFile)) {
1546
+ try {
1547
+ // Strictly read-only ('r') on host Antigravity transcript logs (AGENTS.md Invariant 4 & ISS-040)
1548
+ const fd = fs.openSync(transcriptFile, 'r');
1549
+ let rawTranscript = '';
1550
+ try {
1551
+ rawTranscript = fs.readFileSync(fd, 'utf8');
1552
+ } finally {
1553
+ fs.closeSync(fd);
1554
+ }
1555
+ const lines = rawTranscript.trim().split('\n').filter(Boolean);
1556
+ const steps = lines.map(l => JSON.parse(l));
1557
+ const offloadDir = body.cwd
1558
+ ? path.join(body.cwd, '.agents', 'tmp')
1559
+ : path.join(defaultCacheDir, 'staged_trims', 'offloads');
1560
+ trimRes = trimUncachedTail(steps, {
1561
+ cachedTokens: cachedLiveState?.window?.totalActiveTokens || 50000,
1562
+ ...(body.cwd ? { cwd: body.cwd } : { offloadDir })
1563
+ });
1564
+ if (trimRes && typeof trimRes === 'object') {
1565
+ trimRes.hostTranscriptMutated = false;
1566
+ trimRes.persistBlockedReason = body.persist ? 'HOST_TRANSCRIPT_READONLY_GUARD' : null;
1567
+ }
1568
+ if (trimRes && trimRes.modifiedCount > 0 && trimRes.headBytesPreserved) {
1569
+ const safeSessionSlug = String(sessionInfo?.sessionId || targetConvId || 'session').replace(/[^a-zA-Z0-9_-]/g, '_');
1570
+ const stagedDir = path.join(defaultCacheDir, 'staged_trims');
1571
+ const stagedFullPath = path.join(stagedDir, `${safeSessionSlug}.transcript_full.staged.jsonl`);
1572
+ const serialized = trimRes.prunedSteps.map(s => JSON.stringify(s)).join('\n') + '\n';
1573
+ atomicWriteFileSync(stagedFullPath, serialized, { encoding: 'utf8' });
1574
+ trimRes.trimmed = true;
1575
+ trimRes.stagedOnly = true;
1576
+ trimRes.hostTranscriptMutated = false;
1577
+ trimRes.stagedPath = stagedFullPath;
1578
+ if (savedQuotaLedger && Number(trimRes.tokensSaved) > 0) {
1579
+ try {
1580
+ savedQuotaLedger.recordSaving({
1581
+ sessionId: String(sessionInfo?.sessionId || targetConvId || 'default-session'),
1582
+ eventType: SAVINGS_EVENT_TYPES.COMPACTION_RECLAIMED,
1583
+ tokensSaved: Math.round(Number(trimRes.tokensSaved)),
1584
+ dedupeKey: `tailtrim:${safeSessionSlug}:${trimRes.modifiedCount}`,
1585
+ detail: `Trimmed ${trimRes.modifiedCount} uncached tail step(s)`
1586
+ });
1587
+ } catch (err) {
1588
+ recordDaemonDiagnostic('POST /api/tail/trim:ledger', err);
1589
+ }
1590
+ }
1591
+
1592
+ // Also stage companion transcript.jsonl preview without mutating host logs
1593
+ const compactFile = path.join(path.dirname(transcriptFile), 'transcript.jsonl');
1594
+ if (fs.existsSync(compactFile)) {
1595
+ try {
1596
+ const cFd = fs.openSync(compactFile, 'r');
1597
+ let rawCompact = '';
1598
+ try {
1599
+ rawCompact = fs.readFileSync(cFd, 'utf8');
1600
+ } finally {
1601
+ fs.closeSync(cFd);
1602
+ }
1603
+ const cLines = rawCompact.trim().split('\n').filter(Boolean);
1604
+ const cSteps = cLines.map(l => JSON.parse(l));
1605
+ const cRes = trimUncachedTail(cSteps, {
1606
+ cachedTokens: cachedLiveState?.window?.totalActiveTokens || 50000,
1607
+ ...(body.cwd ? { cwd: body.cwd } : { offloadDir })
1608
+ });
1609
+ if (cRes && cRes.modifiedCount > 0 && cRes.headBytesPreserved) {
1610
+ const stagedCompactPath = path.join(stagedDir, `${safeSessionSlug}.transcript.staged.jsonl`);
1611
+ atomicWriteFileSync(
1612
+ stagedCompactPath,
1613
+ cRes.prunedSteps.map(s => JSON.stringify(s)).join('\n') + '\n',
1614
+ { encoding: 'utf8' }
1615
+ );
1616
+ trimRes.stagedCompactPath = stagedCompactPath;
1617
+ }
1618
+ } catch (err) {
1619
+ recordDaemonDiagnostic('POST /api/tail/trim:stageCompact', err);
1620
+ }
1621
+ }
1622
+ }
1623
+ } catch (e) {
1624
+ recordDaemonDiagnostic('POST /api/tail/trim:readOrStage', e);
1625
+ trimRes = { trimmed: false, hostTranscriptMutated: false, error: String(e?.message || e) };
1626
+ }
1627
+ }
1628
+ const nextState = await refreshLiveState(true, targetConvId);
1629
+ broadcastState(nextState);
1630
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1631
+ res.end(JSON.stringify({ success: true, ...trimRes, state: nextState }));
1632
+ return;
1633
+ }
1634
+
1635
+ // Route: POST /api/rsi/evolve & POST /api/instincts/promote (Synthesize / Promote Instincts via PrefixCacheShield fence)
1636
+ if ((url.pathname === '/api/rsi/evolve' || url.pathname === '/api/instincts/promote') && req.method === 'POST') {
1637
+ const bodyStr = await readRequestBody(req, res);
1638
+ if (bodyStr === null) return;
1639
+ const body = parseJsonBodyOrSend400(bodyStr, res, `POST ${url.pathname}`);
1640
+ if (body === null) return;
1641
+ const sessCtx = resolveRouteCacheContext(body);
1642
+ const forceColdBust = Boolean(body.force || body.forceColdBust || body.options?.forceColdBust);
1643
+ let evolveRes = null;
1644
+ try {
1645
+ if (body.ruleText && url.pathname === '/api/instincts/promote') {
1646
+ const wsPath = body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
1647
+ evolveRes = promoteRuleWithAttentionZone(wsPath, body.ruleText, {
1648
+ ...sessCtx,
1649
+ ...(body.options || {}),
1650
+ zone: body.zone || 'primacy',
1651
+ targetFileName: body.targetFileName || 'AGENTS.md',
1652
+ prefixCacheShield,
1653
+ forceColdBust
1654
+ });
1655
+ } else {
1656
+ const domain = body.domain || 'general';
1657
+ evolveRes = rsiEngine?.evolveDomainToSkill
1658
+ ? rsiEngine.evolveDomainToSkill(domain, {
1659
+ ...sessCtx,
1660
+ ...(body.options || {}),
1661
+ prefixCacheShield,
1662
+ forceColdBust
1663
+ })
1664
+ : { error: 'RSI engine not initialized' };
1665
+ }
1666
+ } catch (err) {
1667
+ recordDaemonDiagnostic(`POST ${url.pathname}`, err);
1668
+ evolveRes = { success: false, error: String(err?.message || err) };
1669
+ }
1670
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1671
+ broadcastState(nextState);
1672
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1673
+ res.end(JSON.stringify({ success: !evolveRes?.error, ...evolveRes, state: nextState }));
1674
+ return;
1675
+ }
1676
+
1677
+ // Route: POST /api/rules/u-curve-optimize & POST /api/ushape/reorder (Reorder Rules via PrefixCacheShield fence)
1678
+ if ((url.pathname === '/api/rules/u-curve-optimize' || url.pathname === '/api/ushape/reorder') && req.method === 'POST') {
1679
+ const bodyStr = await readRequestBody(req, res);
1680
+ if (bodyStr === null) return;
1681
+ const body = parseJsonBodyOrSend400(bodyStr, res, `POST ${url.pathname}`);
1682
+ if (body === null) return;
1683
+ const wsPath = body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
1684
+ const targetRule = body.filePath || path.join(wsPath, 'AGENTS.md');
1685
+ const sessCtx = resolveRouteCacheContext(body);
1686
+ const forceColdBust = Boolean(body.force || body.forceColdBust || body.options?.forceColdBust);
1687
+ let optRes = null;
1688
+ try {
1689
+ optRes = uShapedOptimizer.optimizeRuleFile(targetRule, {
1690
+ ...sessCtx,
1691
+ ...(body.options || {}),
1692
+ prefixCacheShield,
1693
+ forceColdBust
1694
+ });
1695
+ } catch (err) {
1696
+ recordDaemonDiagnostic(`POST ${url.pathname}`, err);
1697
+ optRes = { success: false, error: String(err?.message || err) };
1698
+ }
1699
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1700
+ broadcastState(nextState);
1701
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1702
+ res.end(JSON.stringify({ success: !optRes?.error, ...optRes, state: nextState }));
1703
+ return;
1704
+ }
1705
+
1706
+ // Route: POST /api/rsi/queue-action (Approve or dismiss staged learning in ReflectorQueue)
1707
+ if (url.pathname === '/api/rsi/queue-action' && req.method === 'POST') {
1708
+ const bodyStr = await readRequestBody(req, res);
1709
+ if (bodyStr === null) return;
1710
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/rsi/queue-action');
1711
+ if (body === null) return;
1712
+ const itemId = body.id || body.itemId || null;
1713
+ const action = String(body.action || 'approve').toLowerCase();
1714
+ const activeWsDir = body.workspacePath || cachedLiveState?.workspace?.canonicalPath || process.cwd();
1715
+ reflectorQueue.setWorkspaceDir(activeWsDir);
1716
+ let actionRes = null;
1717
+ if (action === 'approve') {
1718
+ actionRes = reflectorQueue.approve(itemId);
1719
+ } else {
1720
+ actionRes = reflectorQueue.dismiss(itemId);
1721
+ }
1722
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1723
+ broadcastState(nextState);
1724
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1725
+ res.end(JSON.stringify({ success: Boolean(actionRes), ...actionRes, state: nextState }));
1726
+ return;
1727
+ }
1728
+
1729
+ // Route: POST /api/checkpoint/evaporation-check
1730
+ if (url.pathname === '/api/checkpoint/evaporation-check' && req.method === 'POST') {
1731
+ const bodyStr = await readRequestBody(req, res);
1732
+ if (bodyStr === null) return;
1733
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/checkpoint/evaporation-check');
1734
+ if (body === null) return;
1735
+ const targetConvId = body.conversationId || pinnedConversationId || cachedLiveState?.sessionId || 'default';
1736
+ const evapRes = progressiveCheckpointer.detectConstraintEvaporation(
1737
+ body.summaryText || '',
1738
+ targetConvId
1739
+ );
1740
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1741
+ res.end(JSON.stringify({ success: true, ...evapRes }));
1742
+ return;
1743
+ }
1744
+
1745
+ // Route: POST /api/router/unlock-hysteresis (1-click manual unlock for HysteresisLock)
1746
+ if (url.pathname === '/api/router/unlock-hysteresis' && req.method === 'POST') {
1747
+ const unlockRes = hysteresisLock.unlock('MANUAL_UI_UNLOCK');
1748
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1749
+ broadcastState(nextState);
1750
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1751
+ res.end(JSON.stringify({ success: true, ...unlockRes, hysteresisLock: hysteresisLock.getStatus(), state: nextState }));
1752
+ return;
1753
+ }
1754
+
1755
+ // Route: POST /api/license/activate (Offline Ed25519 Pro license or 14-day local trial activation)
1756
+ if (url.pathname === '/api/license/activate' && req.method === 'POST') {
1757
+ const bodyStr = await readRequestBody(req, res);
1758
+ if (bodyStr === null) return;
1759
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/license/activate');
1760
+ if (body === null) return;
1761
+ const actRes = body.trial
1762
+ ? activateLocalTrial()
1763
+ : activateProLicense(body.licenseKey || '');
1764
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1765
+ broadcastState(nextState);
1766
+ res.writeHead(actRes.ok ? 200 : 400, { 'Content-Type': 'application/json' });
1767
+ res.end(JSON.stringify({ success: Boolean(actRes.ok), ...actRes, state: nextState }));
1768
+ return;
1769
+ }
1770
+
1771
+ // Route: GET /api/receipt/export (1-Click Corporate Expense Receipt in PDF 1.4, HTML, or Markdown)
1772
+ if (url.pathname === '/api/receipt/export' && req.method === 'GET') {
1773
+ const fmt = String(url.searchParams.get('format') || 'pdf').toLowerCase();
1774
+ const sessionKey = pinnedConversationId || cachedLiveState?.sessionId || 'default';
1775
+ const ledgerSum = savedQuotaLedger ? savedQuotaLedger.getSummary(sessionKey) : {};
1776
+ const unified = cachedLiveState?.savings || {};
1777
+ const rcpt = generateCorporateExpenseReceipt({
1778
+ sessionSavedTokens: Number(unified.totalSavedTokens || ledgerSum.totalArgonEquivTokensSaved || 0),
1779
+ sessionSavedUSD: Number(unified.estimatedSavedUSD || (Number(ledgerSum.totalArgonEquivTokensSaved || 0) * 0.000015) || 0),
1780
+ workspace30dSavedTokens: Number(unified.totalSavedTokens || ledgerSum.totalArgonEquivTokensSaved || 0),
1781
+ workspace30dSavedUSD: Number(unified.estimatedSavedUSD || (Number(ledgerSum.totalArgonEquivTokensSaved || 0) * 0.000015) || 0)
1782
+ });
1783
+ if (fmt === 'pdf') {
1784
+ const proCheck = requireProFeature('corporate_expense_receipts', {
1785
+ strict: url.searchParams.get('strict') === '1'
1786
+ });
1787
+ if (!proCheck.allowed) {
1788
+ res.writeHead(402, { 'Content-Type': 'application/json' });
1789
+ res.end(
1790
+ JSON.stringify({
1791
+ ok: false,
1792
+ requiresPro: true,
1793
+ shadowSavedUSD: rcpt.workspace30dSavedUSD,
1794
+ upgradeHint: proCheck.upgradeHint
1795
+ })
1796
+ );
1797
+ return;
1798
+ }
1799
+ const buf = Buffer.from(rcpt.pdfBytes);
1800
+ res.writeHead(200, {
1801
+ 'Content-Type': 'application/pdf',
1802
+ 'Content-Disposition': `attachment; filename="attention-horizon-receipt-${rcpt.receiptId}.pdf"`,
1803
+ 'Content-Length': buf.length
1804
+ });
1805
+ res.end(buf);
1806
+ return;
1807
+ }
1808
+ if (fmt === 'html') {
1809
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
1810
+ res.end(rcpt.html);
1811
+ return;
1812
+ }
1813
+ res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
1814
+ res.end(rcpt.markdown);
1815
+ return;
1816
+ }
1817
+
1818
+ // Route: POST /api/router/mode (Set Coach / Auto-Pilot mode)
1819
+ if (url.pathname === '/api/router/mode' && req.method === 'POST') {
1820
+ const bodyStr = await readRequestBody(req, res);
1821
+ if (bodyStr === null) return;
1822
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/router/mode');
1823
+ if (body === null) return;
1824
+ const mode = body.mode || 'coach';
1825
+ const modeRes = modelSelectorActuator.setMode(mode);
1826
+ cacheTtlWatchdog.setFlightMode(
1827
+ modeRes.mode === 'autopilot' ? 'AUTO_PILOT' : (modeRes.mode === 'off' ? 'OFF' : 'COACH')
1828
+ );
1829
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1830
+ broadcastState(nextState);
1831
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1832
+ res.end(JSON.stringify({ success: true, ...modeRes, state: nextState }));
1833
+ return;
1834
+ }
1835
+
1836
+ // Route: POST /api/router/actuate (Actuate model/effort change)
1837
+ if (url.pathname === '/api/router/actuate' && req.method === 'POST') {
1838
+ const bodyStr = await readRequestBody(req, res);
1839
+ if (bodyStr === null) return;
1840
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/router/actuate');
1841
+ if (body === null) return;
1842
+ const actuateRes = await modelSelectorActuator.evaluateAndActuate({
1843
+ ...body,
1844
+ forceActuate: true
1845
+ });
1846
+ if (savedQuotaLedger && actuateRes && (actuateRes.actuated || actuateRes.changed)) {
1847
+ try {
1848
+ const estTok = Math.max(1500, Math.round(Number(cachedLiveState?.window?.totalActiveTokens || 20000) * 0.2));
1849
+ savedQuotaLedger.recordSaving({
1850
+ sessionId: String(pinnedConversationId || cachedLiveState?.sessionId || 'default-session'),
1851
+ eventType: SAVINGS_EVENT_TYPES.EFFORT_DOWNSHIFT,
1852
+ tokensSaved: estTok,
1853
+ detail: `Actuated model/effort shift to ${actuateRes.targetModel || body.recommendedModel || 'leaner tier'}`
1854
+ });
1855
+ } catch (err) {
1856
+ recordDaemonDiagnostic('POST /api/router/actuate:ledger', err);
1857
+ }
1858
+ }
1859
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1860
+ broadcastState(nextState);
1861
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1862
+ res.end(JSON.stringify({ success: true, ...actuateRes, state: nextState }));
1863
+ return;
1864
+ }
1865
+
1866
+ // Route: POST /api/savings/receipt (Export plain-English verified Tokens Saved receipt)
1867
+ if (url.pathname === '/api/savings/receipt' && req.method === 'POST') {
1868
+ const bodyStr = await readRequestBody(req, res);
1869
+ if (bodyStr === null) return;
1870
+ const body = bodyStr ? parseJsonBodyOrSend400(bodyStr, res, 'POST /api/savings/receipt') : {};
1871
+ if (body === null) return;
1872
+ const targetSession = body.conversationId || body.sessionId || pinnedConversationId || cachedLiveState?.sessionId || 'default';
1873
+ const liveSavings = cachedLiveState?.savings || computeUnifiedSavings(cachedLiveState || {}, {
1874
+ ledger: savedQuotaLedger,
1875
+ sessionId: targetSession,
1876
+ fts5SavedTokens: getFts5CompressionStats().savedTokens
1877
+ });
1878
+ const receipt = savedQuotaLedger
1879
+ ? savedQuotaLedger.copyPlainSavingsReceipt({ sessionId: targetSession, liveSavings })
1880
+ : { ok: false, markdown: '' };
1881
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1882
+ res.end(JSON.stringify({ success: true, ...receipt, receiptMarkdown: receipt.markdown || '', savings: liveSavings }));
1883
+ return;
1884
+ }
1885
+
1886
+ if (url.pathname === '/api/action' && req.method === 'POST') {
1887
+ const bodyStr = await readRequestBody(req, res);
1888
+ if (bodyStr === null) return;
1889
+ const body = parseJsonBodyOrSend400(bodyStr, res, 'POST /api/action');
1890
+ if (body === null) return;
1891
+ if (body.action === 'select_session') {
1892
+ pinnedConversationId = (!body.conversationId || body.conversationId === 'auto') ? null : body.conversationId;
1893
+ const nextState = await refreshLiveState(true, pinnedConversationId);
1894
+ broadcastState(nextState);
1895
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1896
+ res.end(JSON.stringify({ success: true, state: nextState }));
1897
+ return;
1898
+ }
1899
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1900
+ res.end(JSON.stringify({ success: true, action: body.action }));
1901
+ return;
1902
+ }
1903
+
1904
+ res.writeHead(404);
1905
+ res.end('Not Found');
1906
+ } catch (err) {
1907
+ sendRouteError500(res, `${req.method || 'HTTP'} ${req.url || '/'}`, err);
1908
+ }
1909
+ });
1910
+
1911
+ function broadcastState(state) {
1912
+ if (!state || clients.size === 0) return;
1913
+ const payload = `data: ${JSON.stringify(state)}\n\n`;
1914
+ for (const client of clients) {
1915
+ try {
1916
+ client.write(payload);
1917
+ } catch (err) {
1918
+ clients.delete(client);
1919
+ recordDaemonDiagnostic('broadcastState:write', err);
1920
+ }
1921
+ }
1922
+ }
1923
+
1924
+ setInterval(async () => {
1925
+ if (clients.size > 0) {
1926
+ try {
1927
+ const state = await refreshLiveState(true);
1928
+ broadcastState(state);
1929
+ } catch (err) {
1930
+ recordDaemonDiagnostic('sseBroadcastInterval', err);
1931
+ }
1932
+ }
1933
+ }, 2000).unref();
1934
+
1935
+ export function startServer(port = EXPLICIT_PORT) {
1936
+ return new Promise((resolve, reject) => {
1937
+ const candidates = port > 0
1938
+ ? [port]
1939
+ : [...Array.from({ length: DEFAULT_PORT_MAX - DEFAULT_PORT_START + 1 }, (_, i) => DEFAULT_PORT_START + i), 0];
1940
+
1941
+ let idx = 0;
1942
+ const tryListen = () => {
1943
+ const candidatePort = candidates[idx++];
1944
+ const onError = (err) => {
1945
+ server.removeListener('listening', onListening);
1946
+ if (err.code === 'EADDRINUSE' && idx < candidates.length) {
1947
+ tryListen();
1948
+ } else {
1949
+ reject(err);
1950
+ }
1951
+ };
1952
+ const onListening = () => {
1953
+ server.removeListener('error', onError);
1954
+ const boundPort = server.address().port;
1955
+ writeRuntimeLockfile(boundPort);
1956
+ cacheTtlWatchdog.startPolling(1000);
1957
+
1958
+ let ipcServer = null;
1959
+ try {
1960
+ ipcServer = new MicroIpcServer();
1961
+ ipcServer.listen().catch((ipcErr) => {
1962
+ recordDaemonDiagnostic('ipcServer:listen', ipcErr);
1963
+ });
1964
+ } catch (ipcErr) {
1965
+ recordDaemonDiagnostic('ipcServer:init', ipcErr);
1966
+ }
1967
+
1968
+ server.once('close', () => {
1969
+ cacheTtlWatchdog.stopPolling();
1970
+ if (ipcServer) {
1971
+ ipcServer.close().catch((err) => {
1972
+ recordDaemonDiagnostic('ipcServer:close', err);
1973
+ });
1974
+ }
1975
+ });
1976
+ console.log(`[Horizon Daemon] Listening on http://${BIND_HOST}:${boundPort}`);
1977
+ resolve({ server, port: boundPort, ipcServer });
1978
+ };
1979
+ server.once('error', onError);
1980
+ server.once('listening', onListening);
1981
+ server.listen(candidatePort, BIND_HOST);
1982
+ };
1983
+
1984
+ tryListen();
1985
+ });
1986
+ }
1987
+
1988
+ function isDaemonMain(argv1 = process.argv[1], metaUrl = import.meta.url) {
1989
+ if (!argv1) return false;
1990
+ try {
1991
+ return fs.realpathSync(argv1) === fs.realpathSync(fileURLToPath(metaUrl));
1992
+ } catch (err) {
1993
+ if (err?.code !== 'ENOENT') recordDaemonDiagnostic('isDaemonMain:realpath', err);
1994
+ return path.resolve(argv1) === path.resolve(fileURLToPath(metaUrl));
1995
+ }
1996
+ }
1997
+
1998
+ const isMain = isDaemonMain();
1999
+ if (isMain) {
2000
+ ensureSupportedNodeVersion();
2001
+ startServer();
2002
+ }