ctxtop 0.0.0-stage → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,396 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file packages/mcp/src/server.mjs
4
+ * Zero-dependency MCP stdio JSON-RPC 2.0 server (`@ctxtop/mcp`) for Cursor, Windsurf,
5
+ * Claude Code, and Google Antigravity.
6
+ *
7
+ * Supports both newline-delimited JSON-RPC and `Content-Length` framed stdio transport.
8
+ * Exposes 4 local, zero-network tools:
9
+ * 1. `horizon_status`
10
+ * 2. `cache_gravity_check`
11
+ * 3. `scope_lock_claim`
12
+ * 4. `export_receipt_pdf`
13
+ */
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { readLiveStateSnapshot } from '../../../src/core-isomorphic/telemetry/telemetryBridge.mjs';
19
+ import { getSavedQuotaReceiptSummary } from '../../../src/core-isomorphic/coach/savedQuotaLedger.mjs';
20
+ import { generateCorporateExpenseReceipt } from '../../../src/core-isomorphic/ui/pdfReceiptGenerator.mjs';
21
+ import { getProEntitlementStatus } from '../../../src/core/pro_license.mjs';
22
+ import { CacheGravityScorer } from '../../../src/core/task_quota_router.mjs';
23
+ import { ScopeLockRegistry, loadRegistry } from '../../../src/core/telemetry/scope_lock_registry.mjs';
24
+
25
+ export const MCP_SERVER_INFO = Object.freeze({
26
+ name: '@ctxtop/mcp',
27
+ version: '4.1.0',
28
+ protocolVersion: '2024-11-05'
29
+ });
30
+
31
+ export const MCP_TOOLS = Object.freeze([
32
+ {
33
+ name: 'horizon_status',
34
+ description: 'Read local Highbeam live telemetry, 30-day saved quota ledger, and @ctxtop/pro license status (zero network calls).',
35
+ inputSchema: {
36
+ type: 'object',
37
+ properties: {
38
+ cwd: { type: 'string', description: 'Workspace directory path' },
39
+ sessionId: { type: 'string', description: 'Session or trajectory ID' }
40
+ }
41
+ }
42
+ },
43
+ {
44
+ name: 'cache_gravity_check',
45
+ description: 'Evaluate warm KV-cache break-even gravity before switching models or downshifting tiers.',
46
+ inputSchema: {
47
+ type: 'object',
48
+ required: ['currentModel', 'targetModel'],
49
+ properties: {
50
+ currentModel: { type: 'string', description: 'Current active model ID' },
51
+ targetModel: { type: 'string', description: 'Candidate target model ID' },
52
+ cachedTokens: { type: 'number', description: 'Current warm cached prefix tokens' },
53
+ ttlRemainingSeconds: { type: 'number', description: 'Remaining prompt-cache TTL in seconds' },
54
+ remainingExpectedTurns: { type: 'number', description: 'Remaining expected turns in this session' },
55
+ expectedOutputTokens: { type: 'number', description: 'Expected output tokens per turn' }
56
+ }
57
+ }
58
+ },
59
+ {
60
+ name: 'scope_lock_claim',
61
+ description: 'Inspect active multi-agent scope locks or acquire a DET-20 file-scope lease for a workspace path set.',
62
+ inputSchema: {
63
+ type: 'object',
64
+ properties: {
65
+ workspaceDir: { type: 'string', description: 'Workspace root directory' },
66
+ sessionId: { type: 'string', description: 'Trajectory / session ID owning the lease' },
67
+ agentId: { type: 'string', description: 'Tool/agent identifier (e.g., cursor, windsurf, claude-code)' },
68
+ paths: { type: 'array', items: { type: 'string' }, description: 'Relative paths or globs to claim; omit for read-only inspection' },
69
+ ttlSeconds: { type: 'number', description: 'Lease TTL in seconds (default 900)' }
70
+ }
71
+ }
72
+ },
73
+ {
74
+ name: 'export_receipt_pdf',
75
+ description: 'Generate a local SHA-256 verified Corporate PDF 1.4 Expense Receipt from 30-day saved-quota ledger telemetry.',
76
+ inputSchema: {
77
+ type: 'object',
78
+ properties: {
79
+ cwd: { type: 'string', description: 'Workspace root directory' },
80
+ sessionId: { type: 'string', description: 'Session ID' },
81
+ email: { type: 'string', description: 'Optional account email override' },
82
+ outPath: { type: 'string', description: 'Optional output .pdf file path' },
83
+ allowPreview: { type: 'boolean', description: 'Allow writing/previewing receipt when on Free tier (default false)' }
84
+ }
85
+ }
86
+ }
87
+ ]);
88
+
89
+ function executeHorizonStatusTool(args = {}, options = {}) {
90
+ const cwd = args.cwd || options.cwd || process.cwd();
91
+ const sessionId = args.sessionId || options.sessionId || 'default';
92
+ const homeDir = args.homeDir || options.homeDir;
93
+ const licensePath = args.licensePath || options.licensePath;
94
+ const publicKeyPem = args.publicKeyPem || options.publicKeyPem;
95
+
96
+ const live = readLiveStateSnapshot(sessionId, { cwd, ...(homeDir ? { homeDir } : {}) });
97
+ const summary = getSavedQuotaReceiptSummary({ cwd, ...(homeDir ? { homeDir } : {}) });
98
+ const entitlement = getProEntitlementStatus({
99
+ ...(homeDir ? { homeDir } : {}),
100
+ ...(licensePath ? { licensePath } : {}),
101
+ ...(publicKeyPem ? { publicKeyPem } : {})
102
+ });
103
+
104
+ return {
105
+ ok: true,
106
+ cwd,
107
+ sessionId,
108
+ entitlement: {
109
+ entitled: Boolean(entitlement.entitled),
110
+ tier: entitlement.tier || 'free',
111
+ source: entitlement.source || 'free'
112
+ },
113
+ savedQuota: summary,
114
+ liveState: live || null
115
+ };
116
+ }
117
+
118
+ function executeCacheGravityCheckTool(args = {}) {
119
+ const scorer = new CacheGravityScorer();
120
+ const cachedTokens = Number(args.cachedTokens || 0);
121
+ const ttlRemainingSeconds = Number(args.ttlRemainingSeconds ?? 240);
122
+ const expectedOutputTokens = Number(args.expectedOutputTokens ?? 1500);
123
+ const remainingExpectedTurns = Math.max(1, Number(args.remainingExpectedTurns || 1));
124
+
125
+ const verdict = scorer.computeBreakEven({
126
+ currentModel: args.currentModel || 'claude-opus-5-5',
127
+ targetModel: args.targetModel || 'claude-sonnet-5-5',
128
+ targetEffort: args.targetEffort || 'low',
129
+ cachedTokens,
130
+ ttlRemainingSeconds,
131
+ expectedOutputTokens
132
+ });
133
+
134
+ return {
135
+ ok: true,
136
+ remainingExpectedTurns,
137
+ ...verdict
138
+ };
139
+ }
140
+
141
+ function executeScopeLockClaimTool(args = {}, options = {}) {
142
+ const workspaceDir = args.workspaceDir || args.cwd || options.cwd || process.cwd();
143
+ const sessionId = args.sessionId || args.trajectoryId || options.sessionId || 'mcp-session';
144
+ const toolName = args.agentId || args.tool || 'mcp';
145
+ const paths = Array.isArray(args.paths) ? args.paths.filter(Boolean) : [];
146
+
147
+ if (paths.length === 0) {
148
+ const reg = loadRegistry(workspaceDir);
149
+ return {
150
+ ok: true,
151
+ mode: 'inspect',
152
+ workspaceDir,
153
+ activeLeases: reg.leases,
154
+ leaseCount: reg.leases.length
155
+ };
156
+ }
157
+
158
+ const registry = new ScopeLockRegistry({ workspaceDir, tool: toolName });
159
+ const res = registry.acquireOrRenewLease({
160
+ trajectoryId: sessionId,
161
+ claimedPaths: paths,
162
+ ttlSeconds: Number(args.ttlSeconds || 900)
163
+ });
164
+
165
+ return {
166
+ mode: 'claim',
167
+ workspaceDir,
168
+ ...res
169
+ };
170
+ }
171
+
172
+ function executeExportReceiptPdfTool(args = {}, options = {}) {
173
+ const cwd = args.cwd || options.cwd || process.cwd();
174
+ const homeDir = args.homeDir || options.homeDir;
175
+ const licensePath = args.licensePath || options.licensePath;
176
+ const publicKeyPem = args.publicKeyPem || options.publicKeyPem;
177
+
178
+ const entitlement = getProEntitlementStatus({
179
+ ...(homeDir ? { homeDir } : {}),
180
+ ...(licensePath ? { licensePath } : {}),
181
+ ...(publicKeyPem ? { publicKeyPem } : {})
182
+ });
183
+ const entitled = Boolean(entitlement.entitled);
184
+ const previewOnly = !entitled;
185
+
186
+ const summary = getSavedQuotaReceiptSummary({ cwd, ...(homeDir ? { homeDir } : {}) });
187
+ const receipt = generateCorporateExpenseReceipt(summary, {
188
+ email: args.email || entitlement.payload?.email || 'developer@workspace.local',
189
+ tierLabel: 'Highbeam Pro ($15.00/mo)',
190
+ subscriptionCostUSD: 15.0
191
+ });
192
+
193
+ let writtenPath = null;
194
+ if (args.outPath && (entitled || Boolean(args.allowPreview))) {
195
+ const resolvedOut = path.resolve(cwd, String(args.outPath));
196
+ fs.mkdirSync(path.dirname(resolvedOut), { recursive: true });
197
+ fs.writeFileSync(resolvedOut, Buffer.from(receipt.pdfBytes));
198
+ writtenPath = resolvedOut;
199
+ }
200
+
201
+ return {
202
+ ok: true,
203
+ entitled,
204
+ tier: entitlement.tier || 'free',
205
+ previewOnly,
206
+ receiptId: receipt.receiptId,
207
+ sha256: receipt.sha256,
208
+ pdfByteLength: receipt.pdfBytes.length,
209
+ writtenPath,
210
+ summary
211
+ };
212
+ }
213
+
214
+ export async function handleMcpToolCall(name, args = {}, options = {}) {
215
+ switch (String(name || '')) {
216
+ case 'horizon_status':
217
+ return executeHorizonStatusTool(args, options);
218
+ case 'cache_gravity_check':
219
+ return executeCacheGravityCheckTool(args);
220
+ case 'scope_lock_claim':
221
+ return executeScopeLockClaimTool(args, options);
222
+ case 'export_receipt_pdf':
223
+ return executeExportReceiptPdfTool(args, options);
224
+ default: {
225
+ const err = new Error(`Unknown MCP tool: ${name}`);
226
+ err.code = -32601;
227
+ throw err;
228
+ }
229
+ }
230
+ }
231
+
232
+ export async function handleMcpJsonRpcRequest(request, options = {}) {
233
+ if (!request || typeof request !== 'object') {
234
+ return {
235
+ jsonrpc: '2.0',
236
+ id: null,
237
+ error: { code: -32600, message: 'Invalid Request' }
238
+ };
239
+ }
240
+
241
+ const id = request.id ?? null;
242
+ const method = String(request.method || '');
243
+ const params = request.params || {};
244
+
245
+ if (method === 'notifications/initialized' || id === null && method.startsWith('notifications/')) {
246
+ return null;
247
+ }
248
+
249
+ try {
250
+ if (method === 'initialize') {
251
+ return {
252
+ jsonrpc: '2.0',
253
+ id,
254
+ result: {
255
+ protocolVersion: params.protocolVersion || MCP_SERVER_INFO.protocolVersion,
256
+ capabilities: { tools: {} },
257
+ serverInfo: {
258
+ name: MCP_SERVER_INFO.name,
259
+ version: MCP_SERVER_INFO.version
260
+ }
261
+ }
262
+ };
263
+ }
264
+
265
+ if (method === 'ping') {
266
+ return { jsonrpc: '2.0', id, result: {} };
267
+ }
268
+
269
+ if (method === 'tools/list') {
270
+ return {
271
+ jsonrpc: '2.0',
272
+ id,
273
+ result: { tools: MCP_TOOLS }
274
+ };
275
+ }
276
+
277
+ if (method === 'tools/call') {
278
+ const toolName = String(params.name || '');
279
+ try {
280
+ const result = await handleMcpToolCall(toolName, params.arguments || {}, options);
281
+ return {
282
+ jsonrpc: '2.0',
283
+ id,
284
+ result: {
285
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
286
+ structuredContent: result,
287
+ isError: false
288
+ }
289
+ };
290
+ } catch (toolErr) {
291
+ if (toolErr.code === -32601) {
292
+ return {
293
+ jsonrpc: '2.0',
294
+ id,
295
+ error: { code: -32601, message: toolErr.message }
296
+ };
297
+ }
298
+ return {
299
+ jsonrpc: '2.0',
300
+ id,
301
+ result: {
302
+ content: [{ type: 'text', text: JSON.stringify({ ok: false, error: toolErr.message }) }],
303
+ isError: true
304
+ }
305
+ };
306
+ }
307
+ }
308
+
309
+ return {
310
+ jsonrpc: '2.0',
311
+ id,
312
+ error: { code: -32601, message: `Method not found: ${method}` }
313
+ };
314
+ } catch (err) {
315
+ return {
316
+ jsonrpc: '2.0',
317
+ id,
318
+ error: { code: -32603, message: err?.message || 'Internal error' }
319
+ };
320
+ }
321
+ }
322
+
323
+ function writeMcpMessage(stream, payload, useContentLength = false) {
324
+ const json = JSON.stringify(payload);
325
+ if (useContentLength) {
326
+ const byteLen = Buffer.byteLength(json, 'utf8');
327
+ stream.write(`Content-Length: ${byteLen}\r\n\r\n${json}`);
328
+ } else {
329
+ stream.write(`${json}\n`);
330
+ }
331
+ }
332
+
333
+ export function startMcpStdioServer(options = {}) {
334
+ const input = options.stdin || process.stdin;
335
+ const output = options.stdout || process.stdout;
336
+ let buffer = Buffer.alloc(0);
337
+
338
+ const processPayloadText = async (text, useContentLength) => {
339
+ const trimmed = String(text || '').trim();
340
+ if (!trimmed) return;
341
+ try {
342
+ const req = JSON.parse(trimmed);
343
+ const res = await handleMcpJsonRpcRequest(req, options);
344
+ if (res !== null && req.id !== undefined) {
345
+ writeMcpMessage(output, res, useContentLength);
346
+ }
347
+ } catch (err) {
348
+ writeMcpMessage(
349
+ output,
350
+ { jsonrpc: '2.0', id: null, error: { code: -32700, message: `Parse error: ${err.message}` } },
351
+ useContentLength
352
+ );
353
+ }
354
+ };
355
+
356
+ input.on('data', async (chunk) => {
357
+ buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf8')]);
358
+ while (buffer.length > 0) {
359
+ const asStr = buffer.toString('utf8');
360
+ if (/^Content-Length:\s*\d+/i.test(asStr)) {
361
+ const sepIdx = buffer.indexOf('\r\n\r\n');
362
+ const lfSepIdx = sepIdx === -1 ? buffer.indexOf('\n\n') : sepIdx;
363
+ const sepLen = sepIdx !== -1 ? 4 : 2;
364
+ if (lfSepIdx === -1) break;
365
+ const header = buffer.slice(0, lfSepIdx).toString('utf8');
366
+ const match = header.match(/Content-Length:\s*(\d+)/i);
367
+ const contentLength = match ? Number(match[1]) : 0;
368
+ const totalNeed = lfSepIdx + sepLen + contentLength;
369
+ if (buffer.length < totalNeed) break;
370
+ const body = buffer.slice(lfSepIdx + sepLen, totalNeed).toString('utf8');
371
+ buffer = buffer.slice(totalNeed);
372
+ await processPayloadText(body, true);
373
+ } else {
374
+ const nlIdx = buffer.indexOf('\n');
375
+ if (nlIdx === -1) break;
376
+ const line = buffer.slice(0, nlIdx).toString('utf8');
377
+ buffer = buffer.slice(nlIdx + 1);
378
+ await processPayloadText(line, false);
379
+ }
380
+ }
381
+ });
382
+ }
383
+
384
+ function isMainEntry(argv1 = process.argv[1], metaUrl = import.meta.url) {
385
+ if (!argv1) return false;
386
+ try {
387
+ return fs.realpathSync(argv1) === fs.realpathSync(fileURLToPath(metaUrl));
388
+ } catch (err) {
389
+ void err;
390
+ return path.resolve(argv1) === path.resolve(fileURLToPath(metaUrl));
391
+ }
392
+ }
393
+
394
+ if (isMainEntry()) {
395
+ startMcpStdioServer();
396
+ }
@@ -0,0 +1,19 @@
1
+ # Highbeam Pro (`@ctxtop/pro`) — Commercial Source-Available License
2
+
3
+ Copyright (c) 2026 Gizzant (Highbeam). All rights reserved.
4
+
5
+ ## 1. Scope of This License
6
+ This Commercial Source-Available License governs all files inside `packages/pro/**`, `src/core/pro_license.mjs`, and the commercial features unlocked by an Highbeam Pro (`CTXP1`) cryptographic license key (`AUTO_PILOT` active cache/model-switch locks, cross-harness `DET-20` lease enforcement, signed Corporate PDF 1.4 Expense Receipts, and the Team FinOps OTel/Grafana Pack).
7
+
8
+ All other components of this repository (`@ctxtop/core`, `@ctxtop/antigravity`, `@ctxtop/claude-code`, the 40-cell HUD, 5-minute TTL clock, `--roast`, and advisory `COACH` mode) remain licensed under the root **MIT License**.
9
+
10
+ ## 2. Permitted Source Inspection & Local Trial
11
+ You are permitted to view, inspect, and audit the source code in `packages/pro/**` to verify security, privacy, and zero-network compliance, and to evaluate Pro features during a 14-day local trial (`npx ctxtop license trial`).
12
+
13
+ ## 3. Commercial Restrictions
14
+ Without a valid, unexpired Highbeam Pro (`$15/mo`, `$149/yr`, or `$199` Lifetime) or Team (`$39/seat/mo` or `$299/yr` 5-seat starter) `CTXP1` Ed25519 license key issued to you or your organization, you may **NOT**:
15
+ 1. Remove, patch, stub, or bypass `verifyProLicenseKey()`, `getProEntitlementStatus()`, or `requireProFeature()` checks in production builds or forks.
16
+ 2. Redistribute, publish, or host modified packages that unlock `@ctxtop/pro` commercial features without a valid `CTXP1` cryptographic key.
17
+ 3. Generate or share forged `CTXP1` license keys for third parties.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
@@ -0,0 +1,30 @@
1
+ # `@ctxtop/pro` Production Ed25519 Key Rotation & Polar.sh Signing Runbook
2
+
3
+ ## 1. Zero-Network Offline Architecture
4
+ `@ctxtop/pro` licenses use offline `CTXP1.<payloadB64Url>.<sigB64Url>` Ed25519 tokens verified locally via Node's built-in `node:crypto` module (`verifyProLicenseKey()` in `src/core/pro_license.mjs`). The client IDE/CLI makes **zero** outbound network calls.
5
+
6
+ ## 2. Generate Production Keypair
7
+ Run an offline one-liner using `generateProKeyPair()` on a secure local workstation:
8
+ ```bash
9
+ node -e "import('./src/core/pro_license.mjs').then(m => { const kp = m.generateProKeyPair(); console.log(kp.publicKeyPem); console.log(kp.privateKeyPem); })"
10
+ ```
11
+
12
+ ## 3. Bind Cloudflare Worker Secrets (Polar.sh Webhook)
13
+ Store the PKCS#8 private key and Polar.sh webhook HMAC secret in Cloudflare Worker encrypted secrets:
14
+ ```bash
15
+ wrangler secret put CTXTOP_ED25519_PRIVATE_KEY_PEM
16
+ wrangler secret put CTXTOP_POLAR_WEBHOOK_SECRET
17
+ ```
18
+ Never commit `CTXTOP_ED25519_PRIVATE_KEY_PEM` to Git or npm tarballs.
19
+
20
+ ## 4. Embed or Override the SPKI Public Key
21
+ 1. Update `DEFAULT_PRO_PUBLIC_KEY_PEM` in `src/core/pro_license.mjs` with the corresponding SPKI PEM public key before tagging a release.
22
+ 2. Enterprise deployments or staged key-rotation tests can override the embedded public key via environment variable without modifying code:
23
+ ```bash
24
+ export CTXTOP_ED25519_PUBLIC_KEY_PEM="$(cat prod-ed25519-pub.pem)"
25
+ ```
26
+
27
+ ## 5. Key Rotation Checklist
28
+ 1. Generate a new keypair and deploy `CTXTOP_ED25519_PRIVATE_KEY_PEM` to the signing worker only after shipping the matching `DEFAULT_PRO_PUBLIC_KEY_PEM` in `ctxtop`.
29
+ 2. Verify signature round-trip locally using `signProLicensePayload()` -> `verifyProLicenseKey()`.
30
+ 3. Confirm tampered and expired payloads return `INVALID_SIGNATURE` and `LICENSE_EXPIRED`.
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@ctxtop/pro",
3
+ "version": "4.1.0",
4
+ "description": "Highbeam Pro — Offline Ed25519 License Verifier, Team FinOps Pack & Commercial Entitlements (Polar.sh)",
5
+ "license": "SEE LICENSE IN LICENSE-COMMERCIAL.md",
6
+ "type": "module",
7
+ "main": "./src/index.mjs",
8
+ "exports": {
9
+ ".": "./src/index.mjs",
10
+ "./worker": "./workers/polar_webhook_worker.mjs",
11
+ "./team-finops": "./src/team_finops_pack.mjs"
12
+ },
13
+ "engines": {
14
+ "node": ">=20.0.0"
15
+ }
16
+ }
@@ -0,0 +1,3 @@
1
+ export * from '../../../src/core/pro_license.mjs';
2
+ export * from './team_finops_pack.mjs';
3
+ export * from '../workers/polar_webhook_worker.mjs';