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,264 @@
1
+ /**
2
+ * Deterministic Zero-Prose ACTION QUEUE Control Surface
3
+ * Evaluates active telemetry state across 5 hazard conditions and emits structured,
4
+ * prioritized action items following the [Action] Target -> Quantified Payoff syntax.
5
+ */
6
+
7
+ export const ACTION_QUEUE_CONFIG = Object.freeze({
8
+ MAX_DISPLAYED_ITEMS: 4,
9
+ STALE_TOOL_TOKEN_THRESHOLD: 3000,
10
+ IDLE_MCP_TOKEN_THRESHOLD: 1000,
11
+ IDLE_MCP_MIN_TURNS: 5,
12
+ COLD_CACHE_TTL_THRESHOLD_SEC: 120,
13
+ COLD_CACHE_MIN_WARM_TOKENS: 50000
14
+ });
15
+
16
+ export const BANNED_FILLER_WORDS = Object.freeze([
17
+ 'click to',
18
+ 'consider',
19
+ 'when ready',
20
+ 'all good',
21
+ 'nothing to do',
22
+ 'you might want',
23
+ 'please'
24
+ ]);
25
+
26
+ /**
27
+ * Builds a deterministically sorted array of actionable surgery items.
28
+ * Returns [] when the state is completely nominal.
29
+ *
30
+ * @param {object} state - HorizonStatePayload or CLI telemetry object
31
+ * @returns {Array<{
32
+ * id: string,
33
+ * kind: 'ORPHAN_PID' | 'IDLE_MCP' | 'STALE_TOOLS' | 'TROUGH_SPEC' | 'COLD_CACHE_CLIFF',
34
+ * priorityScore: number,
35
+ * pinnedSlot1: boolean,
36
+ * actionLabel: string,
37
+ * cliFlag: string,
38
+ * target: string,
39
+ * payoff: string,
40
+ * reclaimTokens: number,
41
+ * reclaimRamGb: number,
42
+ * commandToCopy: string,
43
+ * apiAction: string
44
+ * }>}
45
+ */
46
+ export function buildActionQueue(state = {}) {
47
+ if (!state || typeof state !== 'object') return [];
48
+
49
+ const items = [];
50
+ const metrics = state.metrics || {};
51
+ const brainSignals = state.brainSignals || {};
52
+ const quota = state.quota || {};
53
+ const cache = quota.cache || {};
54
+ const hostHealth = state.hostHealth || {};
55
+ const baseline = state.baseline || {};
56
+ const turns = Number(state.metrics?.totalTurns || state.turns || state.steps?.length || 0);
57
+
58
+ // 1. Orphan / Host Watchdog Breach (Pin to slot 1 if unmanaged orphans or RAM breach)
59
+ const orphanCount = Number(hostHealth.orphanCount || 0);
60
+ const hostRssGb = Number(hostHealth.rssGb || 0);
61
+ const orphans = Array.isArray(hostHealth.orphans) ? hostHealth.orphans : [];
62
+ const hasOrphanIssue = orphanCount > 0 || hostRssGb >= 4.0 || hostHealth.status === 'ZOMBIE_LEAK';
63
+
64
+ if (hasOrphanIssue) {
65
+ const firstOrphan = orphans[0] || {};
66
+ const isScheduled = firstOrphan.reason === 'active_scheduled_task';
67
+ const procSummary = orphans.length === 1
68
+ ? `${firstOrphan.name || 'process'} (PID ${firstOrphan.pid || '?'})${firstOrphan.scheduleDetails ? ' ' + firstOrphan.scheduleDetails : ''}`
69
+ : `${orphanCount} process PIDs (${orphans.map(o => o.pid).filter(Boolean).slice(0, 3).join(', ')}${orphans.length > 3 ? '…' : ''})`;
70
+
71
+ const reclaimRamGb = hostRssGb > 0
72
+ ? hostRssGb
73
+ : parseFloat(((orphans.reduce((sum, o) => sum + (o.rssMb || 0), 0)) / 1024).toFixed(2));
74
+
75
+ const ramStr = reclaimRamGb > 0 ? `${reclaimRamGb} GB RAM` : (firstOrphan.rssMb ? `${firstOrphan.rssMb} MB RAM` : 'host RAM');
76
+ const isDetachedDead = Boolean(firstOrphan.parentAlive === false || firstOrphan.reason === 'detached_parent_pid' || firstOrphan.reason === 'multicall_schedule_leak');
77
+
78
+ items.push({
79
+ id: 'aq-orphan-reap',
80
+ kind: 'ORPHAN_PID',
81
+ priorityScore: 1000000 + Math.round(reclaimRamGb * 10000),
82
+ pinnedSlot1: isDetachedDead || hostHealth.status === 'ZOMBIE_LEAK',
83
+ actionLabel: isScheduled ? `[Stop ${orphanCount} Cron PID${orphanCount === 1 ? '' : 's'}]` : `[Reap ${orphanCount} Orphan PID${orphanCount === 1 ? '' : 's'}]`,
84
+ cliFlag: 'doctor --reap-orphans',
85
+ target: procSummary,
86
+ payoff: `reclaims ${ramStr}`,
87
+ reclaimTokens: 0,
88
+ reclaimRamGb,
89
+ commandToCopy: 'npx ctxtop doctor --reap-orphans',
90
+ apiAction: 'reap-orphans'
91
+ });
92
+ }
93
+
94
+ // 2. Idle Eager MCP Schema Tax
95
+ const mcpAudit = state.baseline?.mcpAudit || brainSignals.mcpAudit || {};
96
+ const unusedEager = Array.isArray(mcpAudit.unusedEagerServers)
97
+ ? mcpAudit.unusedEagerServers
98
+ : [];
99
+
100
+ const eligibleEager = unusedEager.filter(s =>
101
+ (s.schemaTokens || 0) >= ACTION_QUEUE_CONFIG.IDLE_MCP_TOKEN_THRESHOLD &&
102
+ (s.sessionCallCount || 0) === 0
103
+ );
104
+
105
+ if (eligibleEager.length > 0 && turns >= ACTION_QUEUE_CONFIG.IDLE_MCP_MIN_TURNS) {
106
+ const totalSchemaTok = eligibleEager.reduce((s, r) => s + Math.max(0, (r.schemaTokens || 0) - (r.listingTokens || 0)), 0);
107
+ const serverNames = eligibleEager.map(s => s.name).join(', ');
108
+ const tokK = (totalSchemaTok / 1000).toFixed(1);
109
+
110
+ items.push({
111
+ id: 'aq-idle-mcp',
112
+ kind: 'IDLE_MCP',
113
+ priorityScore: 250000 + totalSchemaTok * 10,
114
+ pinnedSlot1: false,
115
+ actionLabel: `[Defer ${eligibleEager.length} Idle MCP${eligibleEager.length === 1 ? '' : 's'}]`,
116
+ cliFlag: 'doctor --audit-mcp',
117
+ target: serverNames,
118
+ payoff: `saves ${tokK}k tok/turn (0 calls in ${turns}t)`,
119
+ reclaimTokens: totalSchemaTok,
120
+ reclaimRamGb: 0,
121
+ commandToCopy: `Please update ~/.gemini/config/mcp_config.json (or .agents/mcp_config.json) to set "${serverNames}" to "loading": "lazy" so unused schemas do not bloat Turn-0 prefix tokens.`,
122
+ apiAction: 'mcp-switch-lazy'
123
+ });
124
+ }
125
+
126
+ // 3. Stale Tool Outputs / Deduplication (Tool Surgeon)
127
+ const dupTokens = Number(brainSignals.duplicateReads?.reclaimableTokens || 0);
128
+ const deadErrorTokens = Number(brainSignals.deadErrors?.reclaimableTokens || 0);
129
+ const oldHistTokens = Number(brainSignals.oldHistory?.reclaimableTokens || 0);
130
+ const reclaimableToolTokens = dupTokens + deadErrorTokens + oldHistTokens;
131
+ const staleTurnCount = Number(brainSignals.oldHistory?.turnCount || 0) +
132
+ Number(brainSignals.deadErrors?.errorCount || 0) +
133
+ Number(brainSignals.duplicateReads?.fileCount || 0);
134
+
135
+ if (reclaimableToolTokens >= ACTION_QUEUE_CONFIG.STALE_TOOL_TOKEN_THRESHOLD) {
136
+ const tokK = (reclaimableToolTokens / 1000).toFixed(1);
137
+ const countLabel = staleTurnCount > 0 ? `${staleTurnCount} Stale Turn${staleTurnCount === 1 ? '' : 's'}` : 'Stale Tool Outputs';
138
+
139
+ items.push({
140
+ id: 'aq-tool-prune',
141
+ kind: 'STALE_TOOLS',
142
+ priorityScore: 300000 + reclaimableToolTokens * 10,
143
+ pinnedSlot1: false,
144
+ actionLabel: `[Prune ${countLabel}]`,
145
+ cliFlag: 'doctor --prune-tools',
146
+ target: 'Tool Surgeon (--prune-tools)',
147
+ payoff: `reclaims ~${tokK}k tok (zero LLM loss)`,
148
+ reclaimTokens: reclaimableToolTokens,
149
+ reclaimRamGb: 0,
150
+ commandToCopy: 'npx ctxtop prune',
151
+ apiAction: 'condense-ast'
152
+ });
153
+ }
154
+
155
+ // 4. Trough Spec Drift (Parabolic Attention Trough)
156
+ const topRisky = Array.isArray(state.topRiskyCells) ? state.topRiskyCells : [];
157
+ const troughSpecCell = topRisky.find(c =>
158
+ (c.riskReason === 'TROUGH_STRANDED_SPEC' || c.inTrough) &&
159
+ /task\.md|implementation_plan\.md|agents\.md|claude\.md/i.test(String(c.filePath || ''))
160
+ );
161
+
162
+ if (troughSpecCell) {
163
+ const cellNum = troughSpecCell.cellNumber || ((troughSpecCell.cellIndex ?? 0) + 1);
164
+ const baseFile = String(troughSpecCell.filePath || 'task.md').split(/[/\\]/).pop();
165
+ const recallGain = Math.max(10, 100 - (troughSpecCell.attentionRecallPct || 40));
166
+
167
+ items.push({
168
+ id: 'aq-trough-spec',
169
+ kind: 'TROUGH_SPEC',
170
+ priorityScore: 200000 + (troughSpecCell.tokenWeight || 6400) * 10,
171
+ pinnedSlot1: false,
172
+ actionLabel: '[Re-Anchor Spec Cell]',
173
+ cliFlag: 'checkpoint --reanchor',
174
+ target: `Cell #${cellNum} (${baseFile})`,
175
+ payoff: `restores recall weight (+${recallGain}% attention)`,
176
+ reclaimTokens: 0,
177
+ reclaimRamGb: 0,
178
+ commandToCopy: `Re-anchor ${baseFile} checklist to active turn`,
179
+ apiAction: 'reanchor-spec'
180
+ });
181
+ }
182
+
183
+ // 5. Cold Cache Cliff Warning (TTL expiring on warm cache)
184
+ const ttlSec = Number(cache.ttlRemainingSec ?? cache.cacheTtlRemainingSec ?? -1);
185
+ const warmTokens = Number(state.window?.totalActiveTokens || metrics.totalInputTokens || 0);
186
+ const isCacheWarm = Number(cache.hitPercent || 0) > 0 || Number(cache.cacheReadTokens || 0) > 0;
187
+
188
+ if (
189
+ ttlSec > 0 &&
190
+ ttlSec <= ACTION_QUEUE_CONFIG.COLD_CACHE_TTL_THRESHOLD_SEC &&
191
+ warmTokens >= ACTION_QUEUE_CONFIG.COLD_CACHE_MIN_WARM_TOKENS &&
192
+ isCacheWarm
193
+ ) {
194
+ items.push({
195
+ id: 'aq-cold-cliff',
196
+ kind: 'COLD_CACHE_CLIFF',
197
+ priorityScore: 150000 + (120 - ttlSec) * 1000,
198
+ pinnedSlot1: false,
199
+ actionLabel: '[Distill Handoff Now]',
200
+ cliFlag: 'handoff --distill',
201
+ target: `TTL expires in ${ttlSec}s`,
202
+ payoff: 'avoids 12.5x cold cache rewrite',
203
+ reclaimTokens: 0,
204
+ reclaimRamGb: 0,
205
+ commandToCopy: 'npx ctxtop doctor --handoff',
206
+ apiAction: 'generate-handoff'
207
+ });
208
+ }
209
+
210
+ // Deterministic Sorting:
211
+ // - Any item with pinnedSlot1 = true is sorted to position 0
212
+ // - Otherwise, sorted descending by priorityScore
213
+ items.sort((a, b) => {
214
+ if (a.pinnedSlot1 && !b.pinnedSlot1) return -1;
215
+ if (!a.pinnedSlot1 && b.pinnedSlot1) return 1;
216
+ return b.priorityScore - a.priorityScore;
217
+ });
218
+
219
+ return items.slice(0, ACTION_QUEUE_CONFIG.MAX_DISPLAYED_ITEMS);
220
+ }
221
+
222
+ /**
223
+ * Formats the Action Queue into high-contrast ANSI tree output for the CLI HUD.
224
+ * Returns "" (empty string) when items is empty (Zero-Height Collapse).
225
+ *
226
+ * @param {object|Array} stateOrQueue
227
+ * @returns {string}
228
+ */
229
+ export function formatActionQueueAnsi(stateOrQueue = {}) {
230
+ const queue = Array.isArray(stateOrQueue)
231
+ ? stateOrQueue
232
+ : buildActionQueue(stateOrQueue);
233
+
234
+ if (!queue || queue.length === 0) return '';
235
+
236
+ const totalTok = queue.reduce((s, item) => s + (item.reclaimTokens || 0), 0);
237
+ const totalRamGb = queue.reduce((s, item) => s + (item.reclaimRamGb || 0), 0);
238
+
239
+ const parts = [];
240
+ if (totalTok > 0) parts.push(`${(totalTok / 1000).toFixed(1)}k tok`);
241
+ if (totalRamGb > 0) parts.push(`${totalRamGb.toFixed(2)} GB RAM`);
242
+ const summaryStr = parts.length > 0 ? ` — ${parts.join(' + ')} reclaimable` : '';
243
+
244
+ const header = `\x1b[1;37mACTION QUEUE (${queue.length})${summaryStr}\x1b[0m`;
245
+ const lines = [header];
246
+
247
+ for (let i = 0; i < queue.length; i++) {
248
+ const item = queue[i];
249
+ const isLast = i === queue.length - 1;
250
+ const branch = isLast ? '└─' : '├─';
251
+
252
+ // 3-Column Aligned Syntax:
253
+ // Col 1: Action (pad to 24 chars)
254
+ // Col 2: Target (pad to 32 chars)
255
+ // Col 3: Payoff
256
+ const col1 = item.actionLabel.padEnd(24, ' ');
257
+ const col2 = item.target.padEnd(32, ' ');
258
+ const col3 = `-> ${item.payoff}`;
259
+
260
+ lines.push(`\x1b[36m${branch}\x1b[0m \x1b[1;33m${col1}\x1b[0m \x1b[37m${col2}\x1b[0m \x1b[32m${col3}\x1b[0m`);
261
+ }
262
+
263
+ return lines.join('\n');
264
+ }
@@ -0,0 +1,346 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { getHomeDir } from './paths.mjs';
5
+ import { atomicWriteFileSync } from './atomic_io.mjs';
6
+
7
+ /**
8
+ * Phase 0: Native Command & Prompt Dispatch Bridge (`AgBridgeService`)
9
+ *
10
+ * Provides a multi-tier command & session dispatch bridge for Google Antigravity:
11
+ * 1. Tier 1 (`rpc`): Local `language_server` RPC transport (`GetCascadeTrajectoryGeneratorMetadata` / command dispatch)
12
+ * 2. Tier 2 (`cdp`): Chrome DevTools Protocol (CDP) OOPIF target observer & input dispatcher
13
+ * 3. Tier 3 (`clipboard`): Automatic fallback to clipboard ONLY if both RPC and CDP targets are unreachable
14
+ */
15
+
16
+ /**
17
+ * Pure parser that extracts local RPC port and CSRF/cert metadata from OS process records
18
+ * matching Antigravity's `language_server` binary.
19
+ */
20
+ export function discoverLanguageServerProcess(processRecords = []) {
21
+ const list = Array.isArray(processRecords) ? processRecords : [];
22
+ for (const proc of list) {
23
+ const name = String(proc?.name || '').toLowerCase();
24
+ const cmd = String(proc?.commandLine || '');
25
+ if (!name.includes('language_server') && !cmd.toLowerCase().includes('language_server')) {
26
+ continue;
27
+ }
28
+
29
+ const portMatch =
30
+ cmd.match(/--(?:https?_port|extension_server_port|rpc_port|port)[=\s]+(\d+)/i) ||
31
+ cmd.match(/127\.0\.0\.1:(\d+)/);
32
+ const csrfMatch =
33
+ cmd.match(/--(?:csrf_token|token|auth_token)[=\s]+([A-Za-z0-9._-]+)/i);
34
+ const certMatch =
35
+ cmd.match(/--(?:cert_path|tls_cert)[=\s]+([^\s"']+)/i);
36
+
37
+ return {
38
+ discovered: true,
39
+ pid: Number(proc.pid || 0),
40
+ port: portMatch ? Number(portMatch[1]) : null,
41
+ csrfToken: csrfMatch ? csrfMatch[1] : null,
42
+ certPath: certMatch ? certMatch[1] : null,
43
+ endpoint: portMatch ? `https://127.0.0.1:${portMatch[1]}` : null
44
+ };
45
+ }
46
+
47
+ return {
48
+ discovered: false,
49
+ pid: null,
50
+ port: null,
51
+ csrfToken: null,
52
+ certPath: null,
53
+ endpoint: null
54
+ };
55
+ }
56
+
57
+ export class AgBridgeService {
58
+ constructor(options = {}) {
59
+ this.homeDir = options.homeDir || getHomeDir();
60
+ this.rpcTransport = options.rpcTransport || null;
61
+ this.cdpTransport = options.cdpTransport || null;
62
+ this.vscodeCommands = options.vscodeCommands || null;
63
+ this.enableExperimentalCdpActuation = options.enableExperimentalCdpActuation !== undefined
64
+ ? Boolean(options.enableExperimentalCdpActuation)
65
+ : (options.settings?.['attentionHorizon.enableExperimentalCdpActuation'] !== undefined
66
+ ? Boolean(options.settings['attentionHorizon.enableExperimentalCdpActuation'])
67
+ : null);
68
+ this.chatInputFocused = Boolean(options.chatInputFocused || false);
69
+ this.clipboardWriter = typeof options.clipboardWriter === 'function'
70
+ ? options.clipboardWriter
71
+ : (text) => { this.lastClipboardText = String(text || ''); return true; };
72
+ this.lastClipboardText = '';
73
+ this.dispatchLog = [];
74
+ }
75
+
76
+ setTransports({ rpcTransport, cdpTransport, vscodeCommands, clipboardWriter } = {}) {
77
+ if (rpcTransport !== undefined) this.rpcTransport = rpcTransport;
78
+ if (cdpTransport !== undefined) this.cdpTransport = cdpTransport;
79
+ if (vscodeCommands !== undefined) this.vscodeCommands = vscodeCommands;
80
+ if (typeof clipboardWriter === 'function') this.clipboardWriter = clipboardWriter;
81
+ }
82
+
83
+ setChatInputFocus(isFocused = false) {
84
+ this.chatInputFocused = Boolean(isFocused);
85
+ return this.chatInputFocused;
86
+ }
87
+
88
+ setExperimentalCdpActuation(enabled = false) {
89
+ this.enableExperimentalCdpActuation = Boolean(enabled);
90
+ return this.enableExperimentalCdpActuation;
91
+ }
92
+
93
+ isCdpActuationAllowed(payload = {}, options = {}) {
94
+ const inputFocused = options.chatInputFocused !== undefined
95
+ ? Boolean(options.chatInputFocused)
96
+ : this.chatInputFocused;
97
+
98
+ if (inputFocused) {
99
+ return {
100
+ allowed: false,
101
+ reason: 'CHAT_INPUT_FOCUSED'
102
+ };
103
+ }
104
+
105
+ const isModelActuation = typeof payload === 'object' && payload !== null &&
106
+ payload.type === 'SET_MODEL_AND_EFFORT';
107
+
108
+ const explicitSetting = options.enableExperimentalCdpActuation !== undefined
109
+ ? Boolean(options.enableExperimentalCdpActuation)
110
+ : (options.settings?.['attentionHorizon.enableExperimentalCdpActuation'] !== undefined
111
+ ? Boolean(options.settings['attentionHorizon.enableExperimentalCdpActuation'])
112
+ : this.enableExperimentalCdpActuation);
113
+
114
+ // By default, model/effort actuation is restricted to VS Code commands / RPC notifications
115
+ // unless `attentionHorizon.enableExperimentalCdpActuation` is explicitly enabled.
116
+ if (isModelActuation && explicitSetting !== true) {
117
+ return {
118
+ allowed: false,
119
+ reason: 'EXPERIMENTAL_CDP_DISABLED'
120
+ };
121
+ }
122
+
123
+ if (explicitSetting === false) {
124
+ return {
125
+ allowed: false,
126
+ reason: 'EXPERIMENTAL_CDP_DISABLED'
127
+ };
128
+ }
129
+
130
+ return {
131
+ allowed: true,
132
+ reason: null
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Dispatches a chat command or prompt to the active Antigravity session.
138
+ * Tries registered VS Code commands / RPC first, then CDP OOPIF bridge (when allowed
139
+ * and chat input does not have focus), and falls back to clipboard ONLY when unreachable.
140
+ */
141
+ async sendChatCommand(sessionId, payload, options = {}) {
142
+ const promptText = typeof payload === 'string'
143
+ ? payload
144
+ : String(payload?.prompt || payload?.command || payload?.text || '');
145
+ const normalizedPayload = typeof payload === 'object' && payload !== null
146
+ ? { ...payload, prompt: promptText }
147
+ : { prompt: promptText };
148
+
149
+ // 0. Attempt registered VS Code command transport if configured
150
+ if (this.vscodeCommands && typeof this.vscodeCommands.executeCommand === 'function') {
151
+ try {
152
+ const vsRes = await this.vscodeCommands.executeCommand('antigravity.horizon.dispatch', sessionId, normalizedPayload, options);
153
+ if (vsRes && vsRes.ok !== false) {
154
+ const entry = {
155
+ ok: true,
156
+ sessionId,
157
+ transportUsed: 'vscode_command',
158
+ fallbackUsed: false,
159
+ payload: normalizedPayload,
160
+ response: vsRes
161
+ };
162
+ this.dispatchLog.push(entry);
163
+ return entry;
164
+ }
165
+ } catch {}
166
+ }
167
+
168
+ // 1. Attempt RPC transport
169
+ if (this.rpcTransport && typeof this.rpcTransport.sendChatCommand === 'function') {
170
+ try {
171
+ const rpcRes = await this.rpcTransport.sendChatCommand(sessionId, normalizedPayload, options);
172
+ if (rpcRes && rpcRes.ok !== false) {
173
+ const entry = {
174
+ ok: true,
175
+ sessionId,
176
+ transportUsed: 'rpc',
177
+ fallbackUsed: false,
178
+ payload: normalizedPayload,
179
+ response: rpcRes
180
+ };
181
+ this.dispatchLog.push(entry);
182
+ return entry;
183
+ }
184
+ } catch {}
185
+ }
186
+
187
+ // 2. Attempt CDP OOPIF bridge transport (gated by experimental setting & unfocused chat input guard)
188
+ const cdpGate = this.isCdpActuationAllowed(normalizedPayload, options);
189
+ if (cdpGate.allowed && this.cdpTransport && typeof this.cdpTransport.sendChatCommand === 'function') {
190
+ try {
191
+ const cdpRes = await this.cdpTransport.sendChatCommand(sessionId, normalizedPayload, options);
192
+ if (cdpRes && cdpRes.ok !== false) {
193
+ const entry = {
194
+ ok: true,
195
+ sessionId,
196
+ transportUsed: 'cdp',
197
+ fallbackUsed: false,
198
+ payload: normalizedPayload,
199
+ response: cdpRes
200
+ };
201
+ this.dispatchLog.push(entry);
202
+ return entry;
203
+ }
204
+ } catch {}
205
+ } else if (!cdpGate.allowed && normalizedPayload.type === 'SET_MODEL_AND_EFFORT') {
206
+ const blockedEntry = {
207
+ ok: false,
208
+ sessionId,
209
+ transportUsed: 'blocked_cdp',
210
+ cdpBlockedReason: cdpGate.reason,
211
+ fallbackUsed: false,
212
+ payload: normalizedPayload
213
+ };
214
+ this.dispatchLog.push(blockedEntry);
215
+ return blockedEntry;
216
+ }
217
+
218
+ // 3. Fallback to clipboard ONLY if both RPC and CDP are unreachable
219
+ this.clipboardWriter(promptText);
220
+ const fallbackEntry = {
221
+ ok: true,
222
+ sessionId,
223
+ transportUsed: 'clipboard',
224
+ cdpBlockedReason: cdpGate.allowed ? null : cdpGate.reason,
225
+ fallbackUsed: true,
226
+ clipboardText: promptText,
227
+ payload: normalizedPayload
228
+ };
229
+ this.dispatchLog.push(fallbackEntry);
230
+ return fallbackEntry;
231
+ }
232
+
233
+ /**
234
+ * Pauses or halts active LLM generation (e.g., when a DET-01..16 circuit breaker trips).
235
+ */
236
+ async pauseActiveGeneration(sessionId, options = {}) {
237
+ const reason = String(options.reason || 'CIRCUIT_BREAKER_HALT');
238
+
239
+ if (this.rpcTransport && typeof this.rpcTransport.pauseActiveGeneration === 'function') {
240
+ try {
241
+ const rpcRes = await this.rpcTransport.pauseActiveGeneration(sessionId, { reason, ...options });
242
+ if (rpcRes && rpcRes.ok !== false) {
243
+ return {
244
+ ok: true,
245
+ sessionId,
246
+ transportUsed: 'rpc',
247
+ fallbackUsed: false,
248
+ reason,
249
+ response: rpcRes
250
+ };
251
+ }
252
+ } catch {}
253
+ }
254
+
255
+ if (this.cdpTransport && typeof this.cdpTransport.pauseActiveGeneration === 'function') {
256
+ try {
257
+ const cdpRes = await this.cdpTransport.pauseActiveGeneration(sessionId, { reason, ...options });
258
+ if (cdpRes && cdpRes.ok !== false) {
259
+ return {
260
+ ok: true,
261
+ sessionId,
262
+ transportUsed: 'cdp',
263
+ fallbackUsed: false,
264
+ reason,
265
+ response: cdpRes
266
+ };
267
+ }
268
+ } catch {}
269
+ }
270
+
271
+ return {
272
+ ok: true,
273
+ sessionId,
274
+ transportUsed: 'sidecar_signal',
275
+ fallbackUsed: true,
276
+ reason
277
+ };
278
+ }
279
+
280
+ /**
281
+ * Spawns a clean Antigravity session and pre-seeds `~/.gemini/antigravity/brain/<NEW_GUID>/`
282
+ * with `implementation_plan.md` and `task.md` so the new agent starts with zero amnesia.
283
+ */
284
+ async spawnCleanSession(initialBrainState = {}, options = {}) {
285
+ const newSessionId = String(initialBrainState.sessionId || options.sessionId || crypto.randomUUID());
286
+ const surface = String(initialBrainState.surface || options.surface || 'antigravity');
287
+ const brainDir = options.brainDir || path.join(this.homeDir, '.gemini', surface, 'brain', newSessionId);
288
+
289
+ fs.mkdirSync(path.join(brainDir, '.system_generated', 'logs'), { recursive: true });
290
+
291
+ const taskMdPath = path.join(brainDir, 'task.md');
292
+ const planMdPath = path.join(brainDir, 'implementation_plan.md');
293
+
294
+ const taskContent = String(
295
+ initialBrainState.taskMd ||
296
+ initialBrainState.taskContent ||
297
+ `# Task Checkpoint (Seeded via Baton Pass)\n\n- [/] Resume from Baton Pass handoff\n`
298
+ );
299
+ const planContent = String(
300
+ initialBrainState.implementationPlanMd ||
301
+ initialBrainState.planContent ||
302
+ `# Implementation Plan (Seeded via Baton Pass)\n\nSeeded from prior session handoff.\n`
303
+ );
304
+
305
+ atomicWriteFileSync(taskMdPath, taskContent, { encoding: 'utf8' });
306
+ atomicWriteFileSync(planMdPath, planContent, { encoding: 'utf8' });
307
+
308
+ if (initialBrainState.handoffMd) {
309
+ atomicWriteFileSync(path.join(brainDir, 'HANDOFF.md'), String(initialBrainState.handoffMd), { encoding: 'utf8' });
310
+ }
311
+
312
+ let transportUsed = 'filesystem_seed';
313
+ let fallbackUsed = false;
314
+
315
+ if (this.rpcTransport && typeof this.rpcTransport.spawnCleanSession === 'function') {
316
+ try {
317
+ const res = await this.rpcTransport.spawnCleanSession(newSessionId, { brainDir, ...initialBrainState });
318
+ if (res && res.ok !== false) {
319
+ transportUsed = 'rpc';
320
+ }
321
+ } catch {}
322
+ } else if (this.cdpTransport && typeof this.cdpTransport.spawnCleanSession === 'function') {
323
+ try {
324
+ const res = await this.cdpTransport.spawnCleanSession(newSessionId, { brainDir, ...initialBrainState });
325
+ if (res && res.ok !== false) {
326
+ transportUsed = 'cdp';
327
+ }
328
+ } catch {}
329
+ } else if (initialBrainState.bootstrapPrompt) {
330
+ this.clipboardWriter(initialBrainState.bootstrapPrompt);
331
+ fallbackUsed = true;
332
+ }
333
+
334
+ return {
335
+ ok: true,
336
+ sessionId: newSessionId,
337
+ brainDir,
338
+ taskMdPath,
339
+ planMdPath,
340
+ transportUsed,
341
+ fallbackUsed
342
+ };
343
+ }
344
+ }
345
+
346
+ export default AgBridgeService;