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,607 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { getHomeDir } from './paths.mjs';
4
+
5
+ /**
6
+ * Per-source estimate of the "workspace baseline" that is re-sent every turn:
7
+ * rules (AGENTS.md / GEMINI.md / .agents/rules / plugin rules), the skill list
8
+ * (name + description frontmatter only) and MCP tool listings.
9
+ *
10
+ * Token counts are ceil(bytes / 4) and always flagged `exact: false`.
11
+ * MCP servers report the lazy listing cost (tool names + instructions.md) as
12
+ * `tokens`, and the full schema size as `schemaTokens` (what eager loading would cost).
13
+ * Results are memoised on a stat signature (path + mtime + size).
14
+ */
15
+
16
+ const est = bytes => Math.ceil(bytes / 4);
17
+
18
+ function statSafe(p) {
19
+ try { return fs.statSync(p); } catch { return null; }
20
+ }
21
+
22
+ function listDirs(dir) {
23
+ try { return fs.readdirSync(dir, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => path.join(dir, d.name)); } catch { return []; }
24
+ }
25
+
26
+ function listFiles(dir, ext) {
27
+ try { return fs.readdirSync(dir, { withFileTypes: true }).filter(d => d.isFile() && d.name.toLowerCase().endsWith(ext)).map(d => path.join(dir, d.name)); } catch { return []; }
28
+ }
29
+
30
+ /** Extracts the YAML frontmatter block (between the first two `---` lines). */
31
+ export function frontmatterBytes(text) {
32
+ const m = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text);
33
+ return Buffer.byteLength(m ? m[1] : '', 'utf8');
34
+ }
35
+
36
+ export function collectBaselineSources(workspaceDir, homeDir = getHomeDir()) {
37
+ const gemini = path.join(homeDir, '.gemini');
38
+ const sources = [];
39
+ const add = (kind, label, p, mode = 'full') => sources.push({ kind, label, path: p, mode });
40
+
41
+ // Rules
42
+ if (workspaceDir) {
43
+ for (const name of ['AGENTS.md', 'GEMINI.md']) add('rule', `${name} (workspace)`, path.join(workspaceDir, name));
44
+ for (const f of listFiles(path.join(workspaceDir, '.agents', 'rules'), '.md')) add('rule', `.agents/rules/${path.basename(f)}`, f);
45
+ }
46
+ add('rule', 'GEMINI.md (global)', path.join(gemini, 'GEMINI.md'));
47
+ for (const plugin of listDirs(path.join(gemini, 'config', 'plugins'))) {
48
+ for (const f of listFiles(path.join(plugin, 'rules'), '.md')) add('rule', `${path.basename(plugin)} rule: ${path.basename(f)}`, f);
49
+ }
50
+
51
+ // Skills (frontmatter only: the skill list is injected every turn, bodies only when read)
52
+ const skillRoots = [
53
+ path.join(gemini, 'config', 'skills'),
54
+ path.join(gemini, 'antigravity', 'builtin', 'skills'),
55
+ ...listDirs(path.join(gemini, 'config', 'plugins')).map(p => path.join(p, 'skills'))
56
+ ];
57
+ if (workspaceDir) skillRoots.push(path.join(workspaceDir, '.agents', 'skills'));
58
+ for (const root of skillRoots) {
59
+ for (const dir of listDirs(root)) add('skill', `skill: ${path.basename(dir)}`, path.join(dir, 'SKILL.md'), 'frontmatter');
60
+ }
61
+
62
+ // MCP servers
63
+ for (const dir of listDirs(path.join(gemini, 'antigravity', 'mcp'))) add('mcp', `MCP: ${path.basename(dir)}`, dir, 'mcp');
64
+
65
+ // Subagent definitions
66
+ const subagentRoots = [
67
+ path.join(gemini, 'config', 'agents'),
68
+ ...listDirs(path.join(gemini, 'config', 'plugins')).map(p => path.join(p, 'agents'))
69
+ ];
70
+ if (workspaceDir) subagentRoots.push(path.join(workspaceDir, '.agents', 'agents'));
71
+ for (const root of subagentRoots) {
72
+ for (const f of listFiles(root, '.md')) add('subagent', `subagent: ${path.basename(f, '.md')}`, f);
73
+ }
74
+
75
+ // Workflows
76
+ const workflowRoots = [
77
+ path.join(gemini, 'config', 'workflows'),
78
+ path.join(gemini, 'antigravity', 'global_workflows')
79
+ ];
80
+ if (workspaceDir) {
81
+ workflowRoots.push(path.join(workspaceDir, '.agents', 'workflows'));
82
+ workflowRoots.push(path.join(workspaceDir, '.agent', 'workflows'));
83
+ }
84
+ for (const root of workflowRoots) {
85
+ for (const f of listFiles(root, '.md')) add('workflow', `workflow: ${path.basename(f, '.md')}`, f);
86
+ }
87
+
88
+ return sources;
89
+ }
90
+
91
+ function measureSource(src) {
92
+ if (src.mode === 'mcp') {
93
+ const files = listFiles(src.path, '.json');
94
+ let schemaBytes = 0;
95
+ let nameBytes = 0;
96
+ for (const f of files) {
97
+ schemaBytes += statSafe(f)?.size || 0;
98
+ nameBytes += Buffer.byteLength(path.basename(f, '.json'), 'utf8') + 1;
99
+ }
100
+ const instr = statSafe(path.join(src.path, 'instructions.md'))?.size || 0;
101
+ if (!files.length && !instr) return null;
102
+ return { tokens: est(nameBytes + instr), schemaTokens: est(schemaBytes + instr), toolCount: files.length };
103
+ }
104
+ const st = statSafe(src.path);
105
+ if (!st || !st.isFile()) return null;
106
+ if (src.mode === 'frontmatter') {
107
+ try { return { tokens: est(frontmatterBytes(fs.readFileSync(src.path, 'utf8'))) }; } catch { return null; }
108
+ }
109
+ return { tokens: est(st.size) };
110
+ }
111
+
112
+ function signatureOf(sources) {
113
+ return sources.map(s => {
114
+ if (s.mode === 'mcp') {
115
+ const st = statSafe(s.path);
116
+ return `${s.path}|${st ? st.mtimeMs : 0}|${listFiles(s.path, '.json').length}`;
117
+ }
118
+ const st = statSafe(s.path);
119
+ return `${s.path}|${st ? st.mtimeMs : 0}|${st ? st.size : 0}`;
120
+ }).join('\n');
121
+ }
122
+
123
+ const memo = new Map();
124
+
125
+ export const CUSTOMIZATION_BUCKET_BUDGET = 20000;
126
+
127
+ function normalizeMcpName(name) {
128
+ return String(name || '').trim().toLowerCase().replace(/[^a-z0-9]+/g, '_');
129
+ }
130
+
131
+ /**
132
+ * Parses `~/.gemini/config/mcp_config.json` and `.agents/mcp_config.json`
133
+ * to discover configured MCP servers, their loading mode (`eager` vs `lazy`),
134
+ * and any inline tool schemas.
135
+ */
136
+ export function parseMcpConfigFiles(workspaceDir = '', homeDir = getHomeDir()) {
137
+ const candidates = [];
138
+ if (homeDir) {
139
+ candidates.push({
140
+ sourceLabel: '~/.gemini/config/mcp_config.json',
141
+ path: path.join(homeDir, '.gemini', 'config', 'mcp_config.json')
142
+ });
143
+ }
144
+ if (workspaceDir) {
145
+ candidates.push({
146
+ sourceLabel: '.agents/mcp_config.json',
147
+ path: path.join(workspaceDir, '.agents', 'mcp_config.json')
148
+ });
149
+ }
150
+
151
+ const configPaths = [];
152
+ const serverMap = new Map(); // serverName -> config descriptor
153
+
154
+ for (const c of candidates) {
155
+ const st = statSafe(c.path);
156
+ if (!st || !st.isFile()) continue;
157
+ configPaths.push(c.path);
158
+ try {
159
+ const parsed = JSON.parse(fs.readFileSync(c.path, 'utf8'));
160
+ const rawServers = (parsed && typeof parsed === 'object')
161
+ ? (parsed.mcpServers || parsed.servers || (!Array.isArray(parsed) ? parsed : {}))
162
+ : {};
163
+ for (const [serverName, rawCfg] of Object.entries(rawServers)) {
164
+ if (!rawCfg || typeof rawCfg !== 'object' || Array.isArray(rawCfg)) continue;
165
+ if (rawCfg.disabled === true || rawCfg.enabled === false) continue;
166
+
167
+ const modeRaw = String(rawCfg.loading || rawCfg.loadingMode || rawCfg.loadMode || rawCfg.mode || '').toLowerCase().trim();
168
+ const isExplicitEager = modeRaw === 'eager' || rawCfg.eager === true;
169
+ const loadingMode = isExplicitEager ? 'eager' : 'lazy';
170
+
171
+ const inlineTools = Array.isArray(rawCfg.tools)
172
+ ? rawCfg.tools
173
+ : (Array.isArray(rawCfg.schemas) ? rawCfg.schemas : null);
174
+ const inlineSchemaBytes = inlineTools
175
+ ? Buffer.byteLength(JSON.stringify(inlineTools), 'utf8')
176
+ : Buffer.byteLength(JSON.stringify(rawCfg), 'utf8');
177
+ const explicitSchemaTokens = Number(rawCfg.schemaTokens || rawCfg.staticTokens || 0);
178
+
179
+ serverMap.set(serverName, {
180
+ name: serverName,
181
+ configPath: c.path,
182
+ configSource: c.sourceLabel,
183
+ loadingMode,
184
+ explicitSchemaTokens: explicitSchemaTokens > 0 ? explicitSchemaTokens : null,
185
+ inlineSchemaTokens: est(inlineSchemaBytes),
186
+ inlineToolCount: inlineTools ? inlineTools.length : 0
187
+ });
188
+ }
189
+ } catch {}
190
+ }
191
+
192
+ return { configPaths, serverMap };
193
+ }
194
+
195
+ /**
196
+ * Counts tool invocations per MCP server across the active session steps.
197
+ */
198
+ export function countMcpServerCallsInSession(steps = [], stepEvents = []) {
199
+ const counts = new Map(); // normalized server name -> count
200
+ const bump = (srv) => {
201
+ const key = normalizeMcpName(srv);
202
+ if (!key) return;
203
+ counts.set(key, (counts.get(key) || 0) + 1);
204
+ };
205
+
206
+ for (const step of (Array.isArray(steps) ? steps : [])) {
207
+ const calls = step?.toolCalls || step?.tool_calls || [];
208
+ for (const call of calls) {
209
+ const name = String(call?.name || call?.tool || '').trim();
210
+ const args = call?.args || call?.parameters || call?.Arguments || {};
211
+ if (name === 'call_mcp_tool' || name === 'read_resource' || name === 'list_resources') {
212
+ const srv = args.ServerName || args.server_name || args.server;
213
+ if (srv) bump(srv);
214
+ } else if (/^mcp_([a-z0-9_-]+)_/i.test(name)) {
215
+ // Check against known `mcp_<server>_<tool>` convention
216
+ bump(name.replace(/^mcp_/i, ''));
217
+ } else if (name.includes(':')) {
218
+ bump(name.split(':')[0]);
219
+ }
220
+ }
221
+ }
222
+
223
+ for (const ev of (Array.isArray(stepEvents) ? stepEvents : [])) {
224
+ const name = String(ev?.toolName || '').trim();
225
+ if (ev?.serverName || ev?.ServerName) {
226
+ bump(ev.serverName || ev.ServerName);
227
+ } else if (/^mcp_([a-z0-9_-]+)_/i.test(name)) {
228
+ bump(name.replace(/^mcp_/i, ''));
229
+ } else if (name.includes(':')) {
230
+ bump(name.split(':')[0]);
231
+ }
232
+ }
233
+
234
+ return counts;
235
+ }
236
+
237
+ const mcpDirMemo = new Map();
238
+
239
+ /**
240
+ * MCP Prefix Bloat & Schema Audit.
241
+ *
242
+ * - Parses `~/.gemini/config/mcp_config.json` and `.agents/mcp_config.json`.
243
+ * - Calculates static token overhead of registered tool schemas.
244
+ * - Flags `eager`-loaded MCP servers that have had zero tool calls across the active session
245
+ * and suggests switching to `lazy` loading.
246
+ */
247
+ export function auditMcpPrefixBloat({
248
+ workspaceDir = '',
249
+ homeDir = getHomeDir(),
250
+ steps = [],
251
+ stepEvents = []
252
+ } = {}) {
253
+ const { configPaths, serverMap } = parseMcpConfigFiles(workspaceDir, homeDir);
254
+ const callCounts = countMcpServerCallsInSession(steps, stepEvents);
255
+ const mcpDirRoot = path.join(homeDir, '.gemini', 'antigravity', 'mcp');
256
+ const rootStat = statSafe(mcpDirRoot);
257
+ const rootSig = `${mcpDirRoot}|${rootStat ? rootStat.mtimeMs : -1}`;
258
+ let dirServers = mcpDirMemo.get(rootSig);
259
+
260
+ if (!dirServers) {
261
+ dirServers = new Map();
262
+ for (const dir of listDirs(mcpDirRoot)) {
263
+ const serverName = path.basename(dir);
264
+ const m = measureSource({ path: dir, mode: 'mcp' });
265
+ if (m) {
266
+ dirServers.set(serverName, {
267
+ name: serverName,
268
+ dirPath: dir,
269
+ listingTokens: m.tokens,
270
+ schemaTokens: m.schemaTokens,
271
+ toolCount: m.toolCount
272
+ });
273
+ }
274
+ }
275
+ if (mcpDirMemo.size > 16) mcpDirMemo.clear();
276
+ mcpDirMemo.set(rootSig, dirServers);
277
+ }
278
+
279
+ const allServerNames = new Set([
280
+ ...serverMap.keys(),
281
+ ...dirServers.keys()
282
+ ]);
283
+
284
+ // Deduplicate servers by normalized name (e.g. chrome-devtools and chrome_devtools)
285
+ // Prefer the entry with higher schemaTokens/toolCount or the one from an explicit config file
286
+ const deduplicatedNames = new Map();
287
+ for (const name of allServerNames) {
288
+ const norm = normalizeMcpName(name);
289
+ if (!deduplicatedNames.has(norm)) {
290
+ deduplicatedNames.set(norm, name);
291
+ } else {
292
+ const existingName = deduplicatedNames.get(norm);
293
+ const existingCfg = serverMap.get(existingName);
294
+ const existingDir = dirServers.get(existingName);
295
+ const existingTok = existingCfg?.explicitSchemaTokens || existingDir?.schemaTokens || 0;
296
+
297
+ const newCfg = serverMap.get(name);
298
+ const newDir = dirServers.get(name);
299
+ const newTok = newCfg?.explicitSchemaTokens || newDir?.schemaTokens || 0;
300
+
301
+ if ((newCfg && !existingCfg) || newTok > existingTok) {
302
+ deduplicatedNames.set(norm, name);
303
+ }
304
+ }
305
+ }
306
+
307
+ const servers = [];
308
+ for (const name of deduplicatedNames.values()) {
309
+ const cfg = serverMap.get(name) || null;
310
+ const dirInfo = dirServers.get(name) || null;
311
+ const loadingMode = cfg ? cfg.loadingMode : 'lazy';
312
+ const schemaTokens = cfg?.explicitSchemaTokens
313
+ || dirInfo?.schemaTokens
314
+ || cfg?.inlineSchemaTokens
315
+ || 0;
316
+ const listingTokens = dirInfo?.listingTokens || Math.min(schemaTokens, Math.max(25, Math.round(schemaTokens * 0.1)));
317
+ const toolCount = dirInfo?.toolCount || cfg?.inlineToolCount || 1;
318
+
319
+ const norm = normalizeMcpName(name);
320
+ let sessionCallCount = callCounts.get(norm) || 0;
321
+ if (sessionCallCount === 0) {
322
+ for (const [calledKey, cnt] of callCounts.entries()) {
323
+ if (calledKey.startsWith(norm + '_') || calledKey === norm) {
324
+ sessionCallCount += cnt;
325
+ }
326
+ }
327
+ }
328
+
329
+ const unusedEager = loadingMode === 'eager' && sessionCallCount === 0;
330
+ const configSource = cfg?.configSource || '~/.gemini/config/mcp_config.json';
331
+ const recommendation = unusedEager
332
+ ? `Switch eager MCP server "${name}" to "lazy" loading in ${configSource} (saves ~${(schemaTokens / 1000).toFixed(1)}k static schema tokens/turn; 0 tool calls in active session).`
333
+ : null;
334
+
335
+ servers.push({
336
+ name,
337
+ configSource: cfg?.configSource || 'mcp_schema_cache',
338
+ configPath: cfg?.configPath || dirInfo?.dirPath || '',
339
+ loadingMode,
340
+ schemaTokens,
341
+ listingTokens,
342
+ activeOverheadTokens: loadingMode === 'eager' ? schemaTokens : listingTokens,
343
+ toolCount,
344
+ sessionCallCount,
345
+ unusedEager,
346
+ recommendation
347
+ });
348
+ }
349
+
350
+ servers.sort((a, b) => b.schemaTokens - a.schemaTokens);
351
+
352
+ const unusedEagerServers = servers.filter(s => s.unusedEager);
353
+ const totalStaticSchemaTokens = servers.reduce((s, r) => s + r.schemaTokens, 0);
354
+ const totalEagerSchemaTokens = servers
355
+ .filter(s => s.loadingMode === 'eager')
356
+ .reduce((s, r) => s + r.schemaTokens, 0);
357
+ const reclaimableEagerSchemaTokens = unusedEagerServers.reduce((s, r) => s + Math.max(0, r.schemaTokens - r.listingTokens), 0);
358
+
359
+ return {
360
+ configPaths,
361
+ servers,
362
+ unusedEagerServers,
363
+ totalStaticSchemaTokens,
364
+ totalEagerSchemaTokens,
365
+ reclaimableEagerSchemaTokens,
366
+ recommendations: unusedEagerServers.map(s => s.recommendation).filter(Boolean)
367
+ };
368
+ }
369
+
370
+ /** Returns `{ rows, totalEst, buckets, eagerInjectionWarning, recommendations, mcpAudit, measuredAt }`, rows sorted by tokens desc. */
371
+ export function measureBaseline(workspaceDir, homeDir = getHomeDir(), options = {}) {
372
+ const sources = collectBaselineSources(workspaceDir, homeDir);
373
+ const mcpConfigFiles = [
374
+ homeDir ? path.join(homeDir, '.gemini', 'config', 'mcp_config.json') : '',
375
+ workspaceDir ? path.join(workspaceDir, '.agents', 'mcp_config.json') : ''
376
+ ].filter(Boolean);
377
+ const mcpCfgSig = mcpConfigFiles.map(p => {
378
+ const st = statSafe(p);
379
+ return `${p}|${st ? st.mtimeMs : 0}|${st ? st.size : 0}`;
380
+ }).join('|');
381
+ const hasSessionSteps = Array.isArray(options.steps) && options.steps.length > 0;
382
+ const key = `${workspaceDir}|${homeDir}`;
383
+ const sig = `${signatureOf(sources)}\n${mcpCfgSig}`;
384
+ const hit = memo.get(key);
385
+ if (hit && hit.sig === sig && !hasSessionSteps && !options.force) return hit.result;
386
+
387
+ const rows = [];
388
+ for (const src of sources) {
389
+ const m = measureSource(src);
390
+ if (!m || m.tokens <= 0) continue;
391
+ rows.push({ source: src.label, kind: src.kind, path: src.path, exact: false, ...m });
392
+ }
393
+
394
+ const mcpAudit = auditMcpPrefixBloat({
395
+ workspaceDir,
396
+ homeDir,
397
+ steps: options.steps || [],
398
+ stepEvents: options.stepEvents || []
399
+ });
400
+
401
+ // Ensure any server configured in mcp_config.json is represented in rows with accurate eager/lazy overhead
402
+ for (const srv of mcpAudit.servers) {
403
+ const existingRow = rows.find(r => r.kind === 'mcp' && r.source === `MCP: ${srv.name}`);
404
+ if (existingRow) {
405
+ existingRow.loadingMode = srv.loadingMode;
406
+ existingRow.unusedEager = srv.unusedEager;
407
+ existingRow.sessionCallCount = srv.sessionCallCount;
408
+ if (srv.loadingMode === 'eager') {
409
+ existingRow.tokens = srv.schemaTokens;
410
+ }
411
+ } else if (srv.schemaTokens > 0) {
412
+ rows.push({
413
+ source: `MCP: ${srv.name}`,
414
+ kind: 'mcp',
415
+ path: srv.configPath,
416
+ exact: false,
417
+ tokens: srv.activeOverheadTokens,
418
+ schemaTokens: srv.schemaTokens,
419
+ toolCount: srv.toolCount,
420
+ loadingMode: srv.loadingMode,
421
+ unusedEager: srv.unusedEager,
422
+ sessionCallCount: srv.sessionCallCount
423
+ });
424
+ }
425
+ }
426
+
427
+ rows.sort((a, b) => b.tokens - a.tokens);
428
+
429
+ const bucketDefs = [
430
+ { id: 'rule', label: 'Rules (AGENTS.md & Global)', budgetTokens: CUSTOMIZATION_BUCKET_BUDGET },
431
+ { id: 'skill', label: 'Skills (Frontmatter Index)', budgetTokens: CUSTOMIZATION_BUCKET_BUDGET },
432
+ { id: 'mcp', label: 'MCP Tool Listings & Instructions', budgetTokens: CUSTOMIZATION_BUCKET_BUDGET },
433
+ { id: 'subagent', label: 'Subagent Definitions', budgetTokens: CUSTOMIZATION_BUCKET_BUDGET },
434
+ { id: 'workflow', label: 'Workflows', budgetTokens: CUSTOMIZATION_BUCKET_BUDGET }
435
+ ];
436
+
437
+ const buckets = {};
438
+ for (const b of bucketDefs) {
439
+ const matching = rows.filter(r => r.kind === b.id);
440
+ const tokens = matching.reduce((s, r) => s + r.tokens, 0);
441
+ const eagerSchemaTokens = b.id === 'mcp' ? matching.reduce((s, r) => s + (r.schemaTokens || r.tokens), 0) : tokens;
442
+ const usedPct = parseFloat(Math.min(100, (tokens / b.budgetTokens) * 100).toFixed(1));
443
+ buckets[b.id] = {
444
+ id: b.id,
445
+ label: b.label,
446
+ tokens,
447
+ eagerSchemaTokens,
448
+ budgetTokens: b.budgetTokens,
449
+ usedPct,
450
+ itemCount: matching.length
451
+ };
452
+ }
453
+
454
+ const totalEst = rows.reduce((s, r) => s + r.tokens, 0);
455
+ const eagerInjectionWarning = totalEst > 30000 || Object.values(buckets).some(b => b.usedPct >= 60) || mcpAudit.unusedEagerServers.length > 0;
456
+
457
+ // Detect duplicate rule/subagent/skill definitions across sibling Horizon plugin installs (e.g., agy-horizon + agy-horizon-flightcheck)
458
+ const contentSigMap = new Map();
459
+ const duplicateSources = [];
460
+ for (const r of rows) {
461
+ if (!r.path || r.kind === 'mcp') continue;
462
+ try {
463
+ const st = statSafe(r.path);
464
+ if (!st || !st.isFile() || st.size <= 0) continue;
465
+ const keySig = `${r.kind}|${ path.basename(r.path).toLowerCase() }|${st.size}`;
466
+ const first = contentSigMap.get(keySig);
467
+ if (first && first.path !== r.path) {
468
+ const firstText = fs.readFileSync(first.path, 'utf8');
469
+ const curText = fs.readFileSync(r.path, 'utf8');
470
+ if (firstText === curText) {
471
+ duplicateSources.push({
472
+ kind: r.kind,
473
+ source: r.source,
474
+ duplicateOf: first.source,
475
+ tokens: r.tokens
476
+ });
477
+ }
478
+ } else if (!first) {
479
+ contentSigMap.set(keySig, r);
480
+ }
481
+ } catch (err) {
482
+ void err;
483
+ }
484
+ }
485
+ const duplicateOverheadTokens = duplicateSources.reduce((s, d) => s + d.tokens, 0);
486
+
487
+ const recommendations = [...mcpAudit.recommendations];
488
+ if (duplicateOverheadTokens > 0) {
489
+ recommendations.push(`Duplicate plugin files detected (${duplicateSources.length} mirrored rule/skill/agent file${duplicateSources.length === 1 ? '' : 's'}, ~${(duplicateOverheadTokens / 1000).toFixed(1)}k tok/turn). Disable one duplicate Horizon plugin in Antigravity Plugins Manager when not testing mirrors.`);
490
+ }
491
+ if (buckets.rule.tokens > 8000) {
492
+ recommendations.push(`Move domain-specific rules out of AGENTS.md (${(buckets.rule.tokens / 1000).toFixed(1)}k tok) into on-demand .agents/skills/ frontmatter.`);
493
+ }
494
+ const heavyMcp = rows.filter(r => r.kind === 'mcp' && (r.schemaTokens || 0) > 5000);
495
+ if (heavyMcp.length > 0) {
496
+ recommendations.push(`Keep ${heavyMcp[0].source} lazy-loaded (saves ${Math.round(((heavyMcp[0].schemaTokens || 0) - heavyMcp[0].tokens) / 1000)}k eager schema tokens per turn).`);
497
+ }
498
+
499
+ const result = {
500
+ rows,
501
+ totalEst,
502
+ buckets,
503
+ duplicateOverheadTokens,
504
+ duplicateSources,
505
+ eagerInjectionWarning,
506
+ recommendations,
507
+ mcpAudit,
508
+ topHeaviest: rows.slice(0, 5),
509
+ measuredAt: new Date().toISOString()
510
+ };
511
+ if (!hasSessionSteps) {
512
+ memo.set(key, { sig, result });
513
+ }
514
+ return result;
515
+ }
516
+
517
+ /**
518
+ * Computes per-MCP-server Token ROI (`calls / schemaTokens`, `tokensPerCall`, `IDLE_BLOAT_TAX`, `LOW_ROI`)
519
+ * and tracks dynamic `deferred_tools_delta` / `mcp_instructions_delta` expansion across turns.
520
+ */
521
+ export function computeMcpTokenRoiMatrix({
522
+ workspaceDir = '',
523
+ homeDir = getHomeDir(),
524
+ steps = [],
525
+ stepEvents = []
526
+ } = {}) {
527
+ const audit = auditMcpPrefixBloat({ workspaceDir, homeDir, steps, stepEvents });
528
+ let dynamicDeltaTokens = 0;
529
+
530
+ for (const s of (steps || [])) {
531
+ const mcpDelta = String(s?.mcp_instructions_delta || s?.attachment?.mcp_instructions_delta || '');
532
+ const defDelta = String(s?.deferred_tools_delta || s?.attachment?.deferred_tools_delta || '');
533
+ if (mcpDelta) dynamicDeltaTokens += Math.ceil(mcpDelta.length / 4);
534
+ if (defDelta) dynamicDeltaTokens += Math.ceil(defDelta.length / 4);
535
+ }
536
+
537
+ const matrix = audit.servers.map(srv => {
538
+ const calls = Number(srv.sessionCallCount || 0);
539
+ const schemaTok = Number(srv.schemaTokens || 0);
540
+ const tokensPerCall = calls > 0 ? Math.round(schemaTok / calls) : schemaTok;
541
+ const status = (srv.loadingMode === 'eager' && calls === 0)
542
+ ? 'IDLE_BLOAT_TAX'
543
+ : (tokensPerCall > 3500 ? 'LOW_ROI' : 'HEALTHY_ROI');
544
+ return {
545
+ name: srv.name,
546
+ loadingMode: srv.loadingMode,
547
+ schemaTokens: schemaTok,
548
+ sessionCallCount: calls,
549
+ tokensPerCall,
550
+ status,
551
+ recommendation: srv.recommendation
552
+ };
553
+ });
554
+
555
+ return {
556
+ matrix,
557
+ dynamicDeltaTokens,
558
+ idleBloatServers: matrix.filter(m => m.status === 'IDLE_BLOAT_TAX'),
559
+ totalEagerSchemaTokens: audit.totalEagerSchemaTokens,
560
+ reclaimableEagerSchemaTokens: audit.reclaimableEagerSchemaTokens
561
+ };
562
+ }
563
+
564
+ /**
565
+ * Audits workspace instruction files (`AGENTS.md`, `GEMINI.md`, `.agents/CONTEXT.md`) for static rot:
566
+ * broken `@path` references to non-existent files and oversized instruction files.
567
+ */
568
+ export function auditInstructionStaticRot(workspaceDir = '', homeDir = getHomeDir()) {
569
+ const ws = workspaceDir || process.cwd();
570
+ const candidates = [
571
+ path.join(ws, 'AGENTS.md'),
572
+ path.join(ws, 'GEMINI.md'),
573
+ path.join(ws, '.agents', 'CONTEXT.md')
574
+ ];
575
+
576
+ const brokenReferences = [];
577
+ const inspectedFiles = [];
578
+
579
+ for (const filePath of candidates) {
580
+ if (!fs.existsSync(filePath)) continue;
581
+ try {
582
+ const content = fs.readFileSync(filePath, 'utf8');
583
+ const tokens = est(Buffer.byteLength(content, 'utf8'));
584
+ inspectedFiles.push({ path: filePath, tokens });
585
+
586
+ const refs = content.match(/@([A-Za-z0-9_./\\-]+\.(?:mjs|cjs|js|ts|tsx|json|md|py|sh|ps1|html|css))/g) || [];
587
+ for (const rawRef of refs) {
588
+ const rel = rawRef.slice(1);
589
+ const resolved = path.resolve(ws, rel);
590
+ if (!fs.existsSync(resolved)) {
591
+ brokenReferences.push({
592
+ ruleFile: path.basename(filePath),
593
+ reference: rawRef,
594
+ resolvedPath: resolved
595
+ });
596
+ }
597
+ }
598
+ } catch {}
599
+ }
600
+
601
+ return {
602
+ inspectedFiles,
603
+ brokenReferences,
604
+ hasStaticRot: brokenReferences.length > 0
605
+ };
606
+ }
607
+