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,645 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ const SQLITE_OPEN_READONLY_OPTIONS = Object.freeze({ readOnly: true });
5
+ import { canonicalizePath } from './paths.mjs';
6
+ import { getDatabaseSyncClass } from '../engine-node/db/probe.mjs';
7
+
8
+ /**
9
+ * Cross-Harness SQLite & Protobuf Trajectory Stitcher.
10
+ *
11
+ * 1. Antigravity CLI/IDE: Zero-dependency protobuf wire-walker for `conversations/<uuid>.db`
12
+ * (`steps` table: `idx`, `step_type`, `metadata`, `step_payload`) to extract authoritative
13
+ * `file:///` workspace URIs or shell `cwd` and stitch with `transcript_full.jsonl` & `annotations/<uuid>.pbtxt`.
14
+ * 2. Cursor: Correlates `composerData:<id>`, `bubbleId:<id>:<bubble>`, `messageRequestContext:<id>:<id>`,
15
+ * and `agentKv:blob:*` (`providerOptions.cursor.requestId` / `ai_code_hashes.requestId`) with `store.db`
16
+ * and timestamp-less `agent-transcripts/*.jsonl`.
17
+ * 3. Claude Code: Reconstructs the full `uuid -> parentUuid` DAG up to the active `leafUuid`,
18
+ * identifying `/rewind` forks, `file-history-snapshot` restore points, and inferred system prompt tokens.
19
+ */
20
+
21
+ const FILE_URI_RE = /file:\/\/\/[^\s"'\x00-\x1f<>]+/gi;
22
+ const CWD_PATH_RE = /(?:[A-Za-z]:[\\/](?:[^\s"'\x00-\x1f<>\\/:*?|]+[\\/])*[^\s"'\x00-\x1f<>\\/:*?|]+|\/(?:Users|home|workspaces|projects|var|opt|tmp)\/[^\s"'\x00-\x1f<>:]+)/g;
23
+
24
+ function readVarint(buf, offset) {
25
+ let result = 0n;
26
+ let shift = 0n;
27
+ let pos = offset;
28
+ while (pos < buf.length) {
29
+ const byte = buf[pos++];
30
+ result |= BigInt(byte & 0x7f) << shift;
31
+ if ((byte & 0x80) === 0) {
32
+ return { value: result <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(result) : result, nextOffset: pos };
33
+ }
34
+ shift += 7n;
35
+ if (shift > 63n) return null;
36
+ }
37
+ return null;
38
+ }
39
+
40
+ function isLikelyPrintableUtf8(sub) {
41
+ if (!sub || sub.length === 0) return false;
42
+ const str = sub.toString('utf8');
43
+ if (str.includes('\uFFFD')) return false;
44
+ let printable = 0;
45
+ for (let i = 0; i < str.length; i++) {
46
+ const code = str.charCodeAt(i);
47
+ if (code === 9 || code === 10 || code === 13 || (code >= 32 && code < 0xfffd)) {
48
+ printable++;
49
+ }
50
+ }
51
+ return (printable / str.length) >= 0.85;
52
+ }
53
+
54
+ /**
55
+ * Zero-dependency Protobuf wire-format decoder.
56
+ * Walks binary `step_payload` and `metadata` blobs without requiring `.proto` schemas.
57
+ */
58
+ export function decodeProtobufWire(buffer, depth = 0) {
59
+ const fields = [];
60
+ const strings = [];
61
+ const fileUris = new Set();
62
+ const cwdCandidates = new Set();
63
+
64
+ if (!buffer) {
65
+ return { fields, strings, fileUris: [], cwdCandidates: [] };
66
+ }
67
+ const buf = Buffer.isBuffer(buffer)
68
+ ? buffer
69
+ : (buffer instanceof Uint8Array ? Buffer.from(buffer) : Buffer.from(String(buffer), 'utf8'));
70
+
71
+ const extractStringSignals = (str) => {
72
+ const trimmed = str.trim();
73
+ if (!trimmed) return;
74
+ strings.push(trimmed);
75
+ const uris = trimmed.match(FILE_URI_RE) || [];
76
+ for (const u of uris) fileUris.add(u);
77
+ const paths = trimmed.match(CWD_PATH_RE) || [];
78
+ for (const p of paths) {
79
+ if (!/^https?:\/\//i.test(p)) cwdCandidates.add(p);
80
+ }
81
+ };
82
+
83
+ let offset = 0;
84
+ while (offset < buf.length) {
85
+ const tagVarint = readVarint(buf, offset);
86
+ if (!tagVarint || typeof tagVarint.value !== 'number' || tagVarint.value <= 0) break;
87
+ offset = tagVarint.nextOffset;
88
+
89
+ const wireType = tagVarint.value & 0x07;
90
+ const fieldNumber = tagVarint.value >>> 3;
91
+ if (fieldNumber <= 0 || fieldNumber > 536870911) break;
92
+
93
+ if (wireType === 0) {
94
+ const val = readVarint(buf, offset);
95
+ if (!val) break;
96
+ offset = val.nextOffset;
97
+ fields.push({ fieldNumber, wireType, value: val.value });
98
+ } else if (wireType === 1) {
99
+ if (offset + 8 > buf.length) break;
100
+ const slice = buf.subarray(offset, offset + 8);
101
+ offset += 8;
102
+ fields.push({ fieldNumber, wireType, value: slice });
103
+ } else if (wireType === 2) {
104
+ const lenVarint = readVarint(buf, offset);
105
+ if (!lenVarint || typeof lenVarint.value !== 'number' || lenVarint.value < 0) break;
106
+ offset = lenVarint.nextOffset;
107
+ const len = lenVarint.value;
108
+ if (offset + len > buf.length) break;
109
+ const sub = buf.subarray(offset, offset + len);
110
+ offset += len;
111
+
112
+ if (isLikelyPrintableUtf8(sub)) {
113
+ const text = sub.toString('utf8');
114
+ extractStringSignals(text);
115
+ fields.push({ fieldNumber, wireType, value: text });
116
+ } else if (depth < 4 && sub.length >= 2) {
117
+ const nested = decodeProtobufWire(sub, depth + 1);
118
+ for (const s of nested.strings) extractStringSignals(s);
119
+ for (const u of nested.fileUris) fileUris.add(u);
120
+ for (const c of nested.cwdCandidates) cwdCandidates.add(c);
121
+ fields.push({ fieldNumber, wireType, value: nested.fields.length > 0 ? nested.fields : sub });
122
+ } else {
123
+ fields.push({ fieldNumber, wireType, value: sub });
124
+ }
125
+ } else if (wireType === 5) {
126
+ if (offset + 4 > buf.length) break;
127
+ const slice = buf.subarray(offset, offset + 4);
128
+ offset += 4;
129
+ fields.push({ fieldNumber, wireType, value: slice });
130
+ } else {
131
+ break;
132
+ }
133
+ }
134
+
135
+ // Fallback raw scan if the buffer contains embedded plaintext or JSON
136
+ if (fileUris.size === 0 && cwdCandidates.size === 0 && buf.length > 0) {
137
+ const rawStr = buf.toString('utf8');
138
+ extractStringSignals(rawStr);
139
+ }
140
+
141
+ return {
142
+ fields,
143
+ strings,
144
+ fileUris: Array.from(fileUris),
145
+ cwdCandidates: Array.from(cwdCandidates)
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Parses `annotations/<uuid>.pbtxt` for session title and workspace metadata.
151
+ */
152
+ export function parsePbtxtAnnotations(pbtxtContent = '') {
153
+ const text = String(pbtxtContent || '');
154
+ const titleMatch = text.match(/\btitle\s*:\s*"([^"]+)"/i) || text.match(/\bsummary\s*:\s*"([^"]+)"/i);
155
+ const uriMatch = text.match(/file:\/\/\/[^\s"']+/i);
156
+ return {
157
+ title: titleMatch ? titleMatch[1].trim() : '',
158
+ workspaceUri: uriMatch ? uriMatch[0].trim() : null
159
+ };
160
+ }
161
+
162
+ /**
163
+ * Stitches Antigravity CLI SQLite `conversations/<uuid>.db` (`steps` table protobuf blobs)
164
+ * with `transcript_full.jsonl` and `annotations/<uuid>.pbtxt`.
165
+ */
166
+ export async function stitchAntigravityCliTrajectory(dbPath, options = {}) {
167
+ const sessionId = options.sessionId || (dbPath ? path.basename(dbPath, '.db') : 'unknown');
168
+ let title = '';
169
+ let workspaceUri = null;
170
+ const cwdFound = [];
171
+ const dbSteps = [];
172
+
173
+ if (options.pbtxtPath && fs.existsSync(options.pbtxtPath)) {
174
+ try {
175
+ const parsedPbtxt = parsePbtxtAnnotations(fs.readFileSync(options.pbtxtPath, 'utf8'));
176
+ if (parsedPbtxt.title) title = parsedPbtxt.title;
177
+ if (parsedPbtxt.workspaceUri) workspaceUri = parsedPbtxt.workspaceUri;
178
+ } catch {}
179
+ } else if (options.pbtxtContent) {
180
+ const parsedPbtxt = parsePbtxtAnnotations(options.pbtxtContent);
181
+ if (parsedPbtxt.title) title = parsedPbtxt.title;
182
+ if (parsedPbtxt.workspaceUri) workspaceUri = parsedPbtxt.workspaceUri;
183
+ }
184
+
185
+ let dbRows = Array.isArray(options.stepRows) ? options.stepRows : null;
186
+ if (!dbRows && dbPath && fs.existsSync(dbPath)) {
187
+ let db = null;
188
+ try {
189
+ const DbCtor = options.DatabaseSync || getDatabaseSyncClass();
190
+ if (!DbCtor) throw new Error('node:sqlite unavailable');
191
+ db = new DbCtor(dbPath, SQLITE_OPEN_READONLY_OPTIONS);
192
+ dbRows = db.prepare(
193
+ 'SELECT idx, step_type, status, has_subtrajectory, metadata, error_details, permissions, task_details, render_info, step_payload, step_format FROM steps ORDER BY idx ASC'
194
+ ).all();
195
+ } catch {
196
+ dbRows = [];
197
+ } finally {
198
+ try { if (db && typeof db.close === 'function') db.close(); } catch {}
199
+ }
200
+ }
201
+
202
+ for (const row of (dbRows || [])) {
203
+ const blobs = [row.step_payload, row.metadata, row.task_details, row.render_info, row.error_details].filter(Boolean);
204
+ const stepStrings = [];
205
+ let hasSubtrajectory = Boolean(row.has_subtrajectory);
206
+
207
+ for (const blob of blobs) {
208
+ const decoded = decodeProtobufWire(blob);
209
+ for (const u of decoded.fileUris) {
210
+ if (!workspaceUri) workspaceUri = u;
211
+ }
212
+ for (const c of decoded.cwdCandidates) {
213
+ cwdFound.push(c);
214
+ }
215
+ stepStrings.push(...decoded.strings);
216
+ }
217
+
218
+ dbSteps.push({
219
+ stepIndex: Number(row.idx ?? dbSteps.length),
220
+ stepType: row.step_type ?? 'STEP',
221
+ status: row.status ?? 'DONE',
222
+ hasSubtrajectory,
223
+ extractedText: stepStrings.join('\n').slice(0, 4000)
224
+ });
225
+ }
226
+
227
+ let jsonlSteps = Array.isArray(options.jsonlSteps) ? options.jsonlSteps : [];
228
+ if (jsonlSteps.length === 0 && options.transcriptPath && fs.existsSync(options.transcriptPath)) {
229
+ try {
230
+ const lines = fs.readFileSync(options.transcriptPath, 'utf8').split(/\r?\n/).filter(Boolean);
231
+ jsonlSteps = lines.map((l, idx) => {
232
+ try { return JSON.parse(l); } catch { return { step_index: idx, content: l }; }
233
+ });
234
+ } catch {}
235
+ }
236
+
237
+ const dbByIndex = new Map(dbSteps.map(s => [s.stepIndex, s]));
238
+ const mergedSteps = [];
239
+ const seenIndices = new Set();
240
+
241
+ for (const jStep of jsonlSteps) {
242
+ const idx = Number(jStep.step_index ?? jStep.stepIndex ?? mergedSteps.length);
243
+ seenIndices.add(idx);
244
+ const dbMatch = dbByIndex.get(idx);
245
+ mergedSteps.push({
246
+ ...jStep,
247
+ stepIndex: idx,
248
+ type: jStep.type || dbMatch?.stepType || 'STEP',
249
+ hasSubtrajectory: Boolean(jStep.hasSubtrajectory || dbMatch?.hasSubtrajectory),
250
+ content: jStep.content || dbMatch?.extractedText || '',
251
+ workspaceUri: workspaceUri || null
252
+ });
253
+ }
254
+
255
+ // Inject filtered PLANNER_RESPONSE or SQLite-only steps omitted from CLI JSONL
256
+ for (const dStep of dbSteps) {
257
+ if (!seenIndices.has(dStep.stepIndex)) {
258
+ mergedSteps.push({
259
+ stepIndex: dStep.stepIndex,
260
+ type: String(dStep.stepType || 'PLANNER_RESPONSE'),
261
+ status: dStep.status,
262
+ hasSubtrajectory: dStep.hasSubtrajectory,
263
+ content: dStep.extractedText,
264
+ stitchedFromSqlite: true,
265
+ workspaceUri: workspaceUri || null
266
+ });
267
+ }
268
+ }
269
+
270
+ mergedSteps.sort((a, b) => a.stepIndex - b.stepIndex);
271
+
272
+ const rawWorkspace = workspaceUri || cwdFound[0] || '';
273
+ const canonicalWorkspace = rawWorkspace ? canonicalizePath(rawWorkspace) : '';
274
+
275
+ return {
276
+ sessionId,
277
+ title: title || sessionId.slice(0, 8),
278
+ workspaceUri: workspaceUri || (cwdFound[0] ? `file:///${cwdFound[0].replace(/\\/g, '/')}` : null),
279
+ canonicalWorkspace,
280
+ steps: mergedSteps,
281
+ stitchedCount: dbSteps.length,
282
+ stitchedStepCount: dbSteps.length
283
+ };
284
+ }
285
+
286
+ /**
287
+ * Correlates Cursor `state.vscdb` (`cursorDiskKV`), `store.db` (`blobs`, `meta`),
288
+ * and timestamp-less `agent-transcripts/*.jsonl` via `requestId` and content digests.
289
+ */
290
+ export async function stitchCursorTrajectory(sources = {}) {
291
+ let composerId = sources.composerId || sources.sessionId || null;
292
+ let agentId = null;
293
+ let latestRootBlobId = null;
294
+ const correlatedRequestIds = new Set();
295
+ const bubbles = [];
296
+ const contexts = new Map();
297
+
298
+ let kvRows = Array.isArray(sources.diskKvRows) ? sources.diskKvRows : null;
299
+ if (!kvRows && sources.stateVscdbPath && fs.existsSync(sources.stateVscdbPath)) {
300
+ let db = null;
301
+ try {
302
+ const DbCtor = sources.DatabaseSync || getDatabaseSyncClass();
303
+ if (!DbCtor) throw new Error('node:sqlite unavailable');
304
+ db = new DbCtor(sources.stateVscdbPath, SQLITE_OPEN_READONLY_OPTIONS);
305
+ kvRows = db.prepare('SELECT key, value FROM cursorDiskKV').all();
306
+ } catch {
307
+ kvRows = [];
308
+ } finally {
309
+ try { if (db && typeof db.close === 'function') db.close(); } catch {}
310
+ }
311
+ }
312
+
313
+ for (const row of (kvRows || [])) {
314
+ const key = String(row.key || '');
315
+ let val = row.value;
316
+ if (typeof val === 'string') {
317
+ try { val = JSON.parse(val); } catch {}
318
+ } else if (Buffer.isBuffer(val)) {
319
+ try { val = JSON.parse(val.toString('utf8')); } catch {}
320
+ }
321
+
322
+ if (key.startsWith('composerData:')) {
323
+ const cid = key.slice('composerData:'.length);
324
+ if (!composerId) composerId = cid;
325
+ } else if (key.startsWith('bubbleId:')) {
326
+ const parts = key.split(':');
327
+ const cid = parts[1] || '';
328
+ if (!composerId || cid === composerId) {
329
+ const reqId = val?.requestId || val?.providerOptions?.cursor?.requestId || val?.ai_code_hashes?.requestId || null;
330
+ if (reqId) correlatedRequestIds.add(reqId);
331
+ bubbles.push({
332
+ composerId: cid,
333
+ bubbleId: parts[2] || '',
334
+ type: val?.type === 1 ? 'USER_INPUT' : 'PLANNER_RESPONSE',
335
+ content: String(val?.text || val?.rawText || val?.content || ''),
336
+ toolFormerData: val?.toolFormerData || null,
337
+ requestId: reqId,
338
+ createdAt: val?.createdAt || val?.timingInfo?.clientStartTime || null
339
+ });
340
+ }
341
+ } else if (key.startsWith('messageRequestContext:')) {
342
+ const parts = key.split(':');
343
+ contexts.set(`${parts[1]}:${parts[2]}`, val);
344
+ } else if (key.startsWith('agentKv:blob:')) {
345
+ const reqId = val?.providerOptions?.cursor?.requestId || val?.ai_code_hashes?.requestId || val?.requestId || null;
346
+ if (reqId) correlatedRequestIds.add(reqId);
347
+ }
348
+ }
349
+
350
+ // Inspect Cursor CLI `store.db` (`meta` hex-encoded & `blobs`)
351
+ let metaRows = Array.isArray(sources.storeMetaRows) ? sources.storeMetaRows : null;
352
+ if (!metaRows && sources.storeDbPath && fs.existsSync(sources.storeDbPath)) {
353
+ let db = null;
354
+ try {
355
+ const DbCtor = sources.DatabaseSync || getDatabaseSyncClass();
356
+ if (!DbCtor) throw new Error('node:sqlite unavailable');
357
+ db = new DbCtor(sources.storeDbPath, SQLITE_OPEN_READONLY_OPTIONS);
358
+ metaRows = db.prepare('SELECT key, value FROM meta').all();
359
+ } catch {
360
+ metaRows = [];
361
+ } finally {
362
+ try { if (db && typeof db.close === 'function') db.close(); } catch {}
363
+ }
364
+ }
365
+
366
+ for (const m of (metaRows || [])) {
367
+ let rawVal = String(m.value || '');
368
+ if (/^[0-9a-fA-F]+$/.test(rawVal) && rawVal.length % 2 === 0) {
369
+ try { rawVal = Buffer.from(rawVal, 'hex').toString('utf8'); } catch {}
370
+ }
371
+ try {
372
+ const parsed = JSON.parse(rawVal);
373
+ if (parsed.agentId) agentId = parsed.agentId;
374
+ if (parsed.latestRootBlobId) latestRootBlobId = parsed.latestRootBlobId;
375
+ } catch {
376
+ if (m.key === 'agentId') agentId = rawVal;
377
+ if (m.key === 'latestRootBlobId') latestRootBlobId = rawVal;
378
+ }
379
+ }
380
+
381
+ // Correlate timestamp-less `agent-transcripts/*.jsonl` lines by content hash
382
+ let transcriptLines = Array.isArray(sources.transcriptLines) ? sources.transcriptLines : [];
383
+ if (transcriptLines.length === 0 && sources.transcriptJsonlPath && fs.existsSync(sources.transcriptJsonlPath)) {
384
+ try {
385
+ transcriptLines = fs.readFileSync(sources.transcriptJsonlPath, 'utf8')
386
+ .split(/\r?\n/)
387
+ .filter(Boolean)
388
+ .map(l => { try { return JSON.parse(l); } catch { return { content: l }; } });
389
+ } catch {}
390
+ }
391
+
392
+ const bubbleByDigest = new Map();
393
+ for (const b of bubbles) {
394
+ const digest = crypto.createHash('sha1').update(String(b.content || '').trim().slice(0, 200)).digest('hex');
395
+ bubbleByDigest.set(digest, b);
396
+ }
397
+
398
+ const steps = bubbles.map((b, idx) => ({
399
+ stepIndex: idx,
400
+ type: b.type,
401
+ content: b.content,
402
+ toolFormerData: b.toolFormerData,
403
+ requestId: b.requestId,
404
+ createdAt: b.createdAt,
405
+ messageRequestContext: contexts.get(`${b.composerId}:${b.bubbleId}`) || null
406
+ }));
407
+
408
+ for (const tLine of transcriptLines) {
409
+ const text = String(tLine.content || tLine.text || '');
410
+ const digest = crypto.createHash('sha1').update(text.trim().slice(0, 200)).digest('hex');
411
+ if (!bubbleByDigest.has(digest)) {
412
+ steps.push({
413
+ stepIndex: steps.length,
414
+ type: tLine.role === 'user' ? 'USER_INPUT' : 'PLANNER_RESPONSE',
415
+ content: text,
416
+ stitchedFromTranscript: true
417
+ });
418
+ }
419
+ }
420
+
421
+ return {
422
+ sessionId: composerId || agentId || 'cursor-session',
423
+ composerId,
424
+ agentId,
425
+ storeAgentId: agentId,
426
+ latestRootBlobId,
427
+ correlatedRequestIds: Array.from(correlatedRequestIds),
428
+ steps
429
+ };
430
+ }
431
+
432
+ /**
433
+ * Reconstructs the Claude Code `uuid -> parentUuid` DAG up to the active `leafUuid`,
434
+ * identifying `/rewind` branches, `file-history-snapshot` restore points, and turn-1 inferred system prompt tokens.
435
+ */
436
+ export function stitchClaudeCodeDag(jsonlLinesOrContent = []) {
437
+ const rawArr = typeof jsonlLinesOrContent === 'string'
438
+ ? jsonlLinesOrContent.split(/\r?\n/).filter(Boolean)
439
+ : (Array.isArray(jsonlLinesOrContent) ? jsonlLinesOrContent : []);
440
+ const entries = rawArr.map(item => {
441
+ if (typeof item === 'string') {
442
+ try { return JSON.parse(item); } catch { return null; }
443
+ }
444
+ return item;
445
+ }).filter(Boolean);
446
+
447
+ const nodeMap = new Map();
448
+ const childrenMap = new Map();
449
+ const restorePoints = [];
450
+ let explicitLeafUuid = null;
451
+ let lastEntryUuid = null;
452
+ let inferredSystemPromptTokens = 0;
453
+
454
+ for (let i = 0; i < entries.length; i++) {
455
+ const e = entries[i];
456
+ if (!e || typeof e !== 'object') continue;
457
+
458
+ if (e.leafUuid) explicitLeafUuid = e.leafUuid;
459
+ if (e.type === 'file-history-snapshot' || e.snapshot) {
460
+ restorePoints.push({
461
+ uuid: e.uuid || `restore-${i}`,
462
+ stepIndex: i,
463
+ timestamp: e.timestamp || e.createdAt || null,
464
+ files: Object.keys(e.snapshot?.trackedFileBackups || e.files || {})
465
+ });
466
+ }
467
+
468
+ const nestedCreate = e.message?.usage?.cache_creation || e.usage?.cache_creation || e.cache_creation || null;
469
+ const nestedEphemeralCreate = nestedCreate && typeof nestedCreate === 'object'
470
+ ? (Number(nestedCreate.ephemeral_5m_input_tokens || 0) + Number(nestedCreate.ephemeral_1h_input_tokens || 0))
471
+ : 0;
472
+ const cacheCreate = Number(
473
+ e.cache_creation_input_tokens ??
474
+ e.message?.usage?.cache_creation_input_tokens ??
475
+ e.usage?.cache_creation_input_tokens ??
476
+ 0
477
+ ) || nestedEphemeralCreate;
478
+ if (inferredSystemPromptTokens === 0 && cacheCreate > 0) {
479
+ inferredSystemPromptTokens = cacheCreate;
480
+ }
481
+
482
+ const uuid = e.uuid || e.id || `step-${i}`;
483
+ const parentUuid = e.parentUuid !== undefined ? e.parentUuid : (lastEntryUuid || null);
484
+ lastEntryUuid = uuid;
485
+
486
+ nodeMap.set(uuid, { ...e, uuid, parentUuid, rawIndex: i });
487
+ const pKey = parentUuid || '__ROOT__';
488
+ if (!childrenMap.has(pKey)) childrenMap.set(pKey, []);
489
+ childrenMap.get(pKey).push(uuid);
490
+ }
491
+
492
+ const activeTipUuid = (explicitLeafUuid && nodeMap.has(explicitLeafUuid)) ? explicitLeafUuid : lastEntryUuid;
493
+ const activeUuidSet = new Set();
494
+ const activeChain = [];
495
+
496
+ let curr = activeTipUuid;
497
+ const visited = new Set();
498
+ while (curr && nodeMap.has(curr) && !visited.has(curr)) {
499
+ visited.add(curr);
500
+ activeUuidSet.add(curr);
501
+ activeChain.push(nodeMap.get(curr));
502
+ curr = nodeMap.get(curr).parentUuid;
503
+ }
504
+ activeChain.reverse();
505
+
506
+ // Identify /rewind branches: children of active nodes that are not in activeUuidSet
507
+ const rewindBranches = [];
508
+ const countSubtree = (startUuid) => {
509
+ let count = 0;
510
+ let tokens = 0;
511
+ let tip = startUuid;
512
+ const stack = [startUuid];
513
+ while (stack.length > 0) {
514
+ const u = stack.pop();
515
+ const n = nodeMap.get(u);
516
+ if (!n) continue;
517
+ count++;
518
+ tip = u;
519
+ tokens += Number(n.output_tokens ?? n.message?.usage?.output_tokens ?? Math.ceil(String(n.content || '').length / 4));
520
+ for (const ch of (childrenMap.get(u) || [])) {
521
+ stack.push(ch);
522
+ }
523
+ }
524
+ return { count, tokens, tip };
525
+ };
526
+
527
+ for (const activeNode of activeChain) {
528
+ const siblings = childrenMap.get(activeNode.uuid) || [];
529
+ for (const childUuid of siblings) {
530
+ if (!activeUuidSet.has(childUuid)) {
531
+ const sub = countSubtree(childUuid);
532
+ rewindBranches.push({
533
+ forkParentUuid: activeNode.uuid,
534
+ forkUuid: activeNode.uuid,
535
+ abandonedTipUuid: sub.tip,
536
+ droppedStepCount: sub.count,
537
+ abandonedStepCount: sub.count,
538
+ droppedTokens: sub.tokens,
539
+ abandonedTokens: sub.tokens
540
+ });
541
+ }
542
+ }
543
+ }
544
+
545
+ // Deduplicate/consolidate streaming assistant JSONL chunks sharing the same message.id
546
+ // so content blocks merge cleanly while ONLY the final chunk's usage snapshot is retained.
547
+ const consolidatedActiveChain = [];
548
+ const msgIdIndexMap = new Map();
549
+
550
+ const mergeMessageContentBlocks = (prevContent, nextContent) => {
551
+ if (nextContent === undefined || nextContent === null) return prevContent;
552
+ if (prevContent === undefined || prevContent === null) return nextContent;
553
+ if (typeof prevContent === 'string' && typeof nextContent === 'string') {
554
+ if (nextContent.startsWith(prevContent)) return nextContent;
555
+ if (prevContent === nextContent) return nextContent;
556
+ return `${prevContent}\n${nextContent}`;
557
+ }
558
+ const toBlocks = (val) => (Array.isArray(val) ? val : [{ type: 'text', text: String(val) }]);
559
+ const merged = [...toBlocks(prevContent)];
560
+ for (const blk of toBlocks(nextContent)) {
561
+ if (!blk || typeof blk !== 'object') continue;
562
+ if (blk.id) {
563
+ const existingIdx = merged.findIndex((b) => b && b.id === blk.id);
564
+ if (existingIdx >= 0) {
565
+ merged[existingIdx] = blk;
566
+ continue;
567
+ }
568
+ }
569
+ if (blk.type === 'text' && typeof blk.text === 'string') {
570
+ const prevTextIdx = merged.findIndex(
571
+ (b) => b && b.type === 'text' && typeof b.text === 'string' &&
572
+ (b.text === blk.text || blk.text.startsWith(b.text))
573
+ );
574
+ if (prevTextIdx >= 0) {
575
+ merged[prevTextIdx] = blk;
576
+ continue;
577
+ }
578
+ }
579
+ if (blk.type === 'thinking' && typeof blk.thinking === 'string') {
580
+ const prevThinkIdx = merged.findIndex(
581
+ (b) => b && b.type === 'thinking' && typeof b.thinking === 'string' &&
582
+ (b.thinking === blk.thinking || blk.thinking.startsWith(b.thinking))
583
+ );
584
+ if (prevThinkIdx >= 0) {
585
+ merged[prevThinkIdx] = blk;
586
+ continue;
587
+ }
588
+ }
589
+ merged.push(blk);
590
+ }
591
+ return merged;
592
+ };
593
+
594
+ for (const node of activeChain) {
595
+ const msg = node?.message && typeof node.message === 'object' ? node.message : null;
596
+ const role = String(msg?.role || node?.role || node?.type || '').toLowerCase();
597
+ const msgId = (role === 'assistant' || node?.type === 'assistant')
598
+ ? String(msg?.id || node?.message_id || node?.messageId || '').trim()
599
+ : '';
600
+
601
+ if (msgId && msgIdIndexMap.has(msgId)) {
602
+ const idx = msgIdIndexMap.get(msgId);
603
+ const prev = consolidatedActiveChain[idx];
604
+ const prevMsg = prev?.message && typeof prev.message === 'object' ? prev.message : {};
605
+ const nextMsg = msg || {};
606
+ const mergedContent = mergeMessageContentBlocks(
607
+ prevMsg.content ?? prev.content,
608
+ nextMsg.content ?? node.content
609
+ );
610
+ consolidatedActiveChain[idx] = {
611
+ ...prev,
612
+ ...node,
613
+ uuid: node.uuid || prev.uuid,
614
+ parentUuid: prev.parentUuid,
615
+ content: msg ? prev.content : mergedContent,
616
+ tool_calls: [
617
+ ...(Array.isArray(prev.tool_calls) ? prev.tool_calls : []),
618
+ ...(Array.isArray(node.tool_calls) ? node.tool_calls : [])
619
+ ],
620
+ message: msg || prev.message
621
+ ? {
622
+ ...prevMsg,
623
+ ...nextMsg,
624
+ content: mergedContent,
625
+ usage: nextMsg.usage || prevMsg.usage
626
+ }
627
+ : undefined,
628
+ usage: node.usage || nextMsg.usage || prev.usage
629
+ };
630
+ } else {
631
+ if (msgId) {
632
+ msgIdIndexMap.set(msgId, consolidatedActiveChain.length);
633
+ }
634
+ consolidatedActiveChain.push(node);
635
+ }
636
+ }
637
+
638
+ return {
639
+ leafUuid: activeTipUuid || null,
640
+ activeBranchSteps: consolidatedActiveChain.map((n, idx) => ({ ...n, stepIndex: idx })),
641
+ rewindBranches,
642
+ restorePoints,
643
+ inferredSystemPromptTokens
644
+ };
645
+ }