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,73 @@
1
+ import path from 'node:path';
2
+ import { suppressSqliteExperimentalWarning } from './paths.mjs';
3
+
4
+ suppressSqliteExperimentalWarning();
5
+
6
+ /**
7
+ * Normalizes file paths across Windows 11, POSIX, and URI schemes.
8
+ * Ensures consistent canonical string comparisons across Antigravity tools and sidecars.
9
+ *
10
+ * @param {string} rawPath
11
+ * @returns {string} Canonicalized path
12
+ */
13
+ export function canonicalizePath(rawPath) {
14
+ if (!rawPath || typeof rawPath !== 'string') {
15
+ return '';
16
+ }
17
+
18
+ let cleaned = rawPath.trim();
19
+ if (!cleaned) return '';
20
+
21
+ // Handle file URI schemes (file:/// or file://)
22
+ if (cleaned.startsWith('file://')) {
23
+ cleaned = cleaned.replace(/^file:\/\/\/?/i, '');
24
+ try {
25
+ cleaned = decodeURIComponent(cleaned);
26
+ } catch {
27
+ // Keep cleaned as is if decodeURIComponent fails
28
+ }
29
+ }
30
+
31
+ // Normalize Windows backslashes to forward slashes
32
+ cleaned = cleaned.replace(/\\/g, '/');
33
+
34
+ // Collapse multiple consecutive slashes except if leading double slash (UNC)
35
+ cleaned = cleaned.replace(/\/+/g, '/');
36
+
37
+ // Normalize dot and double-dot segments using posix normalize
38
+ cleaned = path.posix.normalize(cleaned);
39
+
40
+ // Strip trailing slashes unless it is root '/' or Windows drive root 'c:/'
41
+ if (cleaned.length > 1 && cleaned.endsWith('/')) {
42
+ const isWindowsDriveRoot = /^[a-zA-Z]:\/$/.test(cleaned);
43
+ if (!isWindowsDriveRoot) {
44
+ cleaned = cleaned.slice(0, -1);
45
+ }
46
+ }
47
+
48
+ // Windows case-insensitivity: lowercase drive letter and path
49
+ const isWindows = process.platform === 'win32' || /^[a-zA-Z]:\//.test(cleaned);
50
+ if (isWindows) {
51
+ cleaned = cleaned.toLowerCase();
52
+ }
53
+
54
+ return cleaned;
55
+ }
56
+
57
+ /**
58
+ * Checks whether childPath is the same as or a sub-path of parentPath.
59
+ *
60
+ * @param {string} parentPath
61
+ * @param {string} childPath
62
+ * @returns {boolean}
63
+ */
64
+ export function isSameOrSubPath(parentPath, childPath) {
65
+ const normParent = canonicalizePath(parentPath);
66
+ const normChild = canonicalizePath(childPath);
67
+
68
+ if (!normParent || !normChild) return false;
69
+ if (normParent === normChild) return true;
70
+
71
+ const prefix = normParent.endsWith('/') ? normParent : `${normParent}/`;
72
+ return normChild.startsWith(prefix);
73
+ }
@@ -0,0 +1,311 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+
4
+ /**
5
+ * Suppresses Node.js `ExperimentalWarning: SQLite is an experimental feature` on CLI and daemon entrypoints.
6
+ */
7
+ export function suppressSqliteExperimentalWarning() {
8
+ if (typeof process === 'undefined' || process.__ctxtopSqliteWarningSuppressed) return;
9
+ process.__ctxtopSqliteWarningSuppressed = true;
10
+ if (typeof process.emitWarning === 'function') {
11
+ const origEmitWarning = process.emitWarning.bind(process);
12
+ process.emitWarning = function (warning, ...args) {
13
+ const msg = typeof warning === 'string' ? warning : (warning && warning.message) || '';
14
+ const type = typeof args[0] === 'string' ? args[0] : (args[0] && args[0].type) || (warning && warning.name) || '';
15
+ if ((type === 'ExperimentalWarning' && /SQLite/i.test(msg)) || /SQLite is an experimental feature/i.test(msg)) {
16
+ return;
17
+ }
18
+ return origEmitWarning(warning, ...args);
19
+ };
20
+ }
21
+ }
22
+
23
+ suppressSqliteExperimentalWarning();
24
+
25
+ export function parseNodeVersion(versionStr = (typeof process !== 'undefined' && process.versions?.node) || '0.0.0') {
26
+ const parts = String(versionStr || '0.0.0').replace(/^v/i, '').split('.').map(n => parseInt(n, 10) || 0);
27
+ return { major: parts[0] || 0, minor: parts[1] || 0, patch: parts[2] || 0 };
28
+ }
29
+
30
+ export function isSupportedNodeVersion(versionStr = (typeof process !== 'undefined' && process.versions?.node) || '0.0.0') {
31
+ const { major } = parseNodeVersion(versionStr);
32
+ return major >= 20;
33
+ }
34
+
35
+ export function hasNativeNodeSqlite(versionStr = (typeof process !== 'undefined' && process.versions?.node) || '0.0.0') {
36
+ if (typeof process !== 'undefined' && process.env?.CTXTOP_FORCE_NO_SQLITE === '1') {
37
+ return false;
38
+ }
39
+ const { major, minor } = parseNodeVersion(versionStr);
40
+ return major > 22 || (major === 22 && minor >= 5);
41
+ }
42
+
43
+ export function formatNodeUpgradeHint(versionStr = (typeof process !== 'undefined' && process.versions?.node) || '0.0.0') {
44
+ const cleanVer = String(versionStr || '0.0.0').replace(/^v/i, '');
45
+ return [
46
+ `\x1b[33m▲ ctxtop requires Node.js >= 20.0.0 LTS (Node.js >= 22.5.0 for built-in zero-dependency SQLite; detected v${cleanVer}).\x1b[0m`,
47
+ ` Upgrade in 10s: \x1b[36mnvm install 22 && nvm use 22\x1b[0m (or download from https://nodejs.org)`
48
+ ].join('\n');
49
+ }
50
+
51
+ export function ensureSupportedNodeVersion({ exitOnUnsupported = true, stream = process.stderr, versionStr = process.versions?.node } = {}) {
52
+ if (isSupportedNodeVersion(versionStr)) return { supported: true, message: '' };
53
+ const message = formatNodeUpgradeHint(versionStr);
54
+ if (stream && typeof stream.write === 'function') {
55
+ stream.write(message + '\n');
56
+ }
57
+ if (exitOnUnsupported && typeof process !== 'undefined' && typeof process.exit === 'function') {
58
+ process.exit(1);
59
+ }
60
+ return { supported: false, message };
61
+ }
62
+
63
+ /**
64
+ * Normalizes Windows & POSIX paths and file:// URIs into a canonical lowercase forward-slash path.
65
+ * Handles file:///c%3A/..., file:///C:/..., C:\..., c:/...
66
+ */
67
+ export function canonicalizePath(input) {
68
+ if (!input || typeof input !== 'string') return '';
69
+ let str = input.trim();
70
+ try {
71
+ str = decodeURIComponent(str);
72
+ } catch {
73
+ // keep as-is if decoding fails
74
+ }
75
+
76
+ // Strip file:// prefix
77
+ str = str.replace(/^file:\/\/\/?/i, '');
78
+
79
+ // Normalize all backslashes to forward slashes
80
+ str = str.replace(/\\+/g, '/');
81
+
82
+ // Strip leading slash before Windows drive letters (e.g. /c:/ -> c:/)
83
+ if (/^\/[a-zA-Z]:/.test(str)) {
84
+ str = str.slice(1);
85
+ }
86
+
87
+ // Remove trailing slashes (except root "c:/" or "/")
88
+ if (str.length > 3 && str.endsWith('/')) {
89
+ str = str.replace(/\/+$/, '');
90
+ }
91
+
92
+ // Lowercase on Windows or Windows drive formats for deterministic case-insensitive matching
93
+ if (process.platform === 'win32' || /^[a-zA-Z]:\//.test(str)) {
94
+ str = str.toLowerCase();
95
+ }
96
+
97
+ return str;
98
+ }
99
+
100
+ /**
101
+ * Returns user home directory across platforms
102
+ */
103
+ export function getHomeDir() {
104
+ return process.env.USERPROFILE || process.env.HOME || path.resolve('/');
105
+ }
106
+
107
+ /**
108
+ * Returns true only for lockfiles, logs, build artifacts, or scratch files.
109
+ * Rule: Active source code files must NEVER be recommended for .antigravityignore.
110
+ */
111
+ export function isIgnorablePath(p) {
112
+ if (!p) return false;
113
+ const raw = String(p).replace(/\\/g, '/');
114
+ const s = raw
115
+ .replace(/^[a-z]:\/users\/[^/]+\/appdata\/local\/temp\/[^/]+\//i, '')
116
+ .replace(/^\/(?:private\/)?var\/folders\/[^/]+\/[^/]+\/[^/]+\/[^/]+\//i, '')
117
+ .replace(/^\/(?:private\/)?tmp\/(?:[^/]+\/)?/i, '');
118
+ if (/(?:^|\/)(?:src|lib|packages|app|bin|test|tests|scripts)\/.*\.(?:[mc]?[jt]sx?|py|rs|go|java|c|cpp|h|hpp|rb|php|swift|kt|vue|svelte|html|css)$/i.test(s)) {
119
+ return false;
120
+ }
121
+ if (/(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Cargo\.lock|Gemfile\.lock|composer\.lock|\.lock)$/i.test(s)) return true;
122
+ if (/\.log$/i.test(s) || /(^|\/)logs?(\/|$)/i.test(s) || /\.jsonl$/i.test(s)) return true;
123
+ if (/(^|\/)(dist|build|out|target|\.next|\.nuxt|coverage|node_modules)(\/|$)/i.test(s)) return true;
124
+ if (/\.(min\.js|min\.css|map|pyc)$/i.test(s)) return true;
125
+ if (/(^|\/)(scratch|\.scratch|tmp|temp)(\/|$)/i.test(s)) return true;
126
+ return false;
127
+ }
128
+
129
+ /**
130
+ * Returns all three local Antigravity surface store descriptors:
131
+ * - Desktop 2.0 / Unified Daemon: ~/.gemini/antigravity ([App])
132
+ * - Standalone IDE Fork: ~/.gemini/antigravity-ide ([IDE])
133
+ * - CLI: ~/.gemini/antigravity-cli ([CLI])
134
+ */
135
+ export function getAntigravitySurfaces(homeDir = getHomeDir(), { includeMissing = false } = {}) {
136
+ const surfaces = [
137
+ {
138
+ name: 'antigravity',
139
+ surfaceTag: '[App]',
140
+ rootDir: path.join(homeDir, '.gemini', 'antigravity'),
141
+ path: path.join(homeDir, '.gemini', 'antigravity', 'brain'),
142
+ brainDir: path.join(homeDir, '.gemini', 'antigravity', 'brain'),
143
+ conversationsDir: path.join(homeDir, '.gemini', 'antigravity', 'conversations'),
144
+ summariesDbPath: path.join(homeDir, '.gemini', 'antigravity', 'conversation_summaries.db')
145
+ },
146
+ {
147
+ name: 'antigravity-ide',
148
+ surfaceTag: '[IDE]',
149
+ rootDir: path.join(homeDir, '.gemini', 'antigravity-ide'),
150
+ path: path.join(homeDir, '.gemini', 'antigravity-ide', 'brain'),
151
+ brainDir: path.join(homeDir, '.gemini', 'antigravity-ide', 'brain'),
152
+ conversationsDir: path.join(homeDir, '.gemini', 'antigravity-ide', 'conversations'),
153
+ summariesDbPath: path.join(homeDir, '.gemini', 'antigravity-ide', 'conversation_summaries.db')
154
+ },
155
+ {
156
+ name: 'antigravity-cli',
157
+ surfaceTag: '[CLI]',
158
+ rootDir: path.join(homeDir, '.gemini', 'antigravity-cli'),
159
+ path: path.join(homeDir, '.gemini', 'antigravity-cli', 'brain'),
160
+ brainDir: path.join(homeDir, '.gemini', 'antigravity-cli', 'brain'),
161
+ conversationsDir: path.join(homeDir, '.gemini', 'antigravity-cli', 'conversations'),
162
+ summariesDbPath: path.join(homeDir, '.gemini', 'antigravity-cli', 'conversation_summaries.db')
163
+ }
164
+ ];
165
+ if (includeMissing) return surfaces;
166
+ return surfaces.filter(s =>
167
+ fs.existsSync(s.brainDir) ||
168
+ fs.existsSync(s.conversationsDir) ||
169
+ fs.existsSync(s.summariesDbPath)
170
+ );
171
+ }
172
+
173
+ /**
174
+ * Discovers potential Antigravity brain directories across all three surfaces
175
+ */
176
+ export function getBrainStores(homeDir = getHomeDir()) {
177
+ return getAntigravitySurfaces(homeDir, { includeMissing: true })
178
+ .filter(s => fs.existsSync(s.path));
179
+ }
180
+
181
+ /**
182
+ * Returns canonical `~/.ctxtop/daemon.port` path used by CLI, healthchecks, and UI.
183
+ */
184
+ export function getDaemonPortFile(homeDir = getHomeDir()) {
185
+ return path.join(homeDir, '.ctxtop', 'daemon.port');
186
+ }
187
+
188
+ /**
189
+ * Reads the active daemon port from `~/.ctxtop/daemon.port` (or `~/.gemini/runtime/horizon-latest.json` fallback).
190
+ */
191
+ export function readDaemonPort(homeDir = getHomeDir(), fallbackPort = 62935) {
192
+ const portFile = getDaemonPortFile(homeDir);
193
+ if (fs.existsSync(portFile)) {
194
+ try {
195
+ const p = parseInt(fs.readFileSync(portFile, 'utf8').trim(), 10);
196
+ if (p > 0 && p <= 65535) return p;
197
+ } catch {}
198
+ }
199
+ const latestJson = path.join(homeDir, '.gemini', 'runtime', 'horizon-latest.json');
200
+ if (fs.existsSync(latestJson)) {
201
+ try {
202
+ const parsed = JSON.parse(fs.readFileSync(latestJson, 'utf8'));
203
+ const p = parseInt(String(parsed?.port || '0'), 10);
204
+ if (p > 0 && p <= 65535) return p;
205
+ } catch {}
206
+ }
207
+ return fallbackPort;
208
+ }
209
+
210
+ /**
211
+ * Parses an explicit `--harness=<name>` or `--harness <name>` CLI flag.
212
+ * Returns normalized harness string ('antigravity' | 'claude' | 'cursor' | 'all') or null when absent.
213
+ */
214
+ export function parseCliHarnessArg(argv = []) {
215
+ if (!Array.isArray(argv)) return null;
216
+ for (let i = 0; i < argv.length; i++) {
217
+ const token = String(argv[i] || '');
218
+ if (token.startsWith('--harness=')) {
219
+ return token.slice('--harness='.length).trim().toLowerCase() || null;
220
+ }
221
+ if (token === '--harness' && i + 1 < argv.length) {
222
+ return String(argv[i + 1] || '').trim().toLowerCase() || null;
223
+ }
224
+ }
225
+ return null;
226
+ }
227
+
228
+ /**
229
+ * Returns true ONLY when cross-host session discovery (`claude` or `cursor`) is explicitly enabled
230
+ * via `{ harness: 'claude' | 'cursor' | 'all' }` or `{ includeCrossHost: true }`.
231
+ */
232
+ export function isCrossHostHarnessEnabled(targetHarness, options = {}) {
233
+ if (!options || typeof options !== 'object') return false;
234
+ if (options.includeCrossHost === true) return true;
235
+ const h = String(options.harness || '').trim().toLowerCase();
236
+ if (!h) return false;
237
+ if (h === 'all' || h === 'cross-host') return true;
238
+ if (targetHarness === 'claude') return h === 'claude' || h === 'claude-code';
239
+ if (targetHarness === 'cursor') return h === 'cursor';
240
+ if (targetHarness === 'codex') return h === 'codex' || h === 'codex-cli';
241
+ if (targetHarness === 'gemini-cli') return h === 'gemini-cli';
242
+ return false;
243
+ }
244
+
245
+ /**
246
+ * Returns OpenAI Codex CLI `~/.codex/sessions` directory ONLY when explicitly gated
247
+ * via `--harness=codex` or `--harness=all`. Strictly scopes to session rollout transcripts.
248
+ */
249
+ export function getCodexSessionsDir(homeDir = getHomeDir(), options = {}) {
250
+ if (!isCrossHostHarnessEnabled('codex', options)) {
251
+ return '';
252
+ }
253
+ return path.join(homeDir, '.codex', 'sessions');
254
+ }
255
+
256
+ /**
257
+ * Returns Google Gemini CLI `~/.gemini/tmp/<hash>/chats` directories ONLY when explicitly gated
258
+ * via `--harness=gemini-cli` or `--harness=all`. Strictly scopes to `chats` subdirectories
259
+ * (never touches root credential files).
260
+ */
261
+ export function getGeminiCliChatsDirs(homeDir = getHomeDir(), options = {}) {
262
+ if (!isCrossHostHarnessEnabled('gemini-cli', options)) {
263
+ return [];
264
+ }
265
+ const tmpRoot = path.join(homeDir, '.gemini', 'tmp');
266
+ if (!fs.existsSync(tmpRoot)) return [];
267
+ const chatDirs = [];
268
+ try {
269
+ for (const entry of fs.readdirSync(tmpRoot, { withFileTypes: true })) {
270
+ if (!entry.isDirectory()) continue;
271
+ const chatsSubdir = path.join(tmpRoot, entry.name, 'chats');
272
+ if (fs.existsSync(chatsSubdir)) {
273
+ chatDirs.push(chatsSubdir);
274
+ }
275
+ }
276
+ } catch {}
277
+ return chatDirs;
278
+ }
279
+
280
+ /**
281
+ * Returns Claude Code `~/.claude/projects` directory when explicitly gated via `--harness=claude`
282
+ * (`options.harness === 'claude'` or `options.includeCrossHost === true`), or empty string by default.
283
+ */
284
+ export function getClaudeCodeProjectsDir(homeDir = getHomeDir(), options = {}) {
285
+ if (!isCrossHostHarnessEnabled('claude', options)) {
286
+ return '';
287
+ }
288
+ return path.join(homeDir, '.claude', 'projects');
289
+ }
290
+
291
+ /**
292
+ * Returns candidate Cursor `workspaceStorage` directories ONLY when explicitly gated via `--harness=cursor`
293
+ * (`options.harness === 'cursor'` or `options.includeCrossHost === true`).
294
+ */
295
+ export function getCursorWorkspaceStorageDirs(homeDir = getHomeDir(), options = {}) {
296
+ if (!isCrossHostHarnessEnabled('cursor', options)) {
297
+ return [];
298
+ }
299
+ const candidates = [
300
+ path.join(homeDir, 'AppData', 'Roaming', 'Cursor', 'User', 'workspaceStorage'),
301
+ path.join(homeDir, 'Library', 'Application Support', 'Cursor', 'User', 'workspaceStorage'),
302
+ path.join(homeDir, '.config', 'Cursor', 'User', 'workspaceStorage'),
303
+ path.join(homeDir, '.cursor', 'workspaceStorage'),
304
+ path.join(homeDir, 'workspaceStorage')
305
+ ];
306
+ if (process.env.APPDATA && canonicalizePath(process.env.APPDATA).startsWith(canonicalizePath(homeDir))) {
307
+ const appDataPath = path.join(process.env.APPDATA, 'Cursor', 'User', 'workspaceStorage');
308
+ if (!candidates.includes(appDataPath)) candidates.unshift(appDataPath);
309
+ }
310
+ return candidates.filter(p => fs.existsSync(p));
311
+ }