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,1997 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { createRequire } from 'node:module';
5
+ import {
6
+ canonicalizePath,
7
+ getHomeDir,
8
+ getBrainStores,
9
+ getAntigravitySurfaces,
10
+ getClaudeCodeProjectsDir,
11
+ getCursorWorkspaceStorageDirs,
12
+ getCodexSessionsDir,
13
+ getGeminiCliChatsDirs,
14
+ isCrossHostHarnessEnabled
15
+ } from './paths.mjs';
16
+ import { EFFORT_PROFILES, resolveEffortProfile, resolveSurfaceTag, normalizeModelId } from './constants.mjs';
17
+ import { stitchAntigravityCliTrajectory, stitchClaudeCodeDag } from './trajectory_stitcher.mjs';
18
+ import { atomicWriteFileSync } from './atomic_io.mjs';
19
+ import { getDatabaseSyncClass } from '../engine-node/db/probe.mjs';
20
+
21
+ function getSqliteDatabaseSync() {
22
+ return getDatabaseSyncClass();
23
+ }
24
+
25
+ /**
26
+ * Zero-Trust Read-Only Filesystem Lock Configuration (SQLITE_OPEN_READONLY).
27
+ * Never acquires write locks on active Antigravity session databases (conversations/*.db,
28
+ * conversation_summaries.db) or JSONL transcript files (transcript_full.jsonl).
29
+ */
30
+ export const SQLITE_OPEN_READONLY_OPTIONS = Object.freeze({ readOnly: true });
31
+ export const ZERO_TRUST_SECURITY_MANIFEST = Object.freeze({
32
+ networkProfile: 'ZERO_OUTBOUND_CONNECTIONS',
33
+ telemetryParsing: '100%_LOCAL_IN_MEMORY',
34
+ sqliteOpenFlag: 'SQLITE_OPEN_READONLY',
35
+ sqliteOptions: SQLITE_OPEN_READONLY_OPTIONS,
36
+ jsonlOpenMode: 'r',
37
+ requiresExternalApiKeys: false
38
+ });
39
+
40
+ /**
41
+ * Matches the host's settings-change sentence, e.g.
42
+ * "The user changed setting `Model Selection` from Claude Sonnet 5.5 (Medium) to Claude Opus 5.5 (Medium). No need ..."
43
+ * Values may contain dots ("5.5"), so the terminator is ". No need" (or a sentence end at block end).
44
+ */
45
+ const SETTINGS_CHANGE_RE = /changed setting\s+`(Model Selection|Reasoning Effort|Effort)`\s+from\s+(.+?)\s+to\s+(.+?)\.\s+No need/i;
46
+ const SETTINGS_CHANGE_FALLBACK_RE = /changed setting\s+`?(Model Selection|Reasoning Effort|Effort)`?\s+from\s+(.+?)\s+to\s+(.+?)\.?\s*(?:<|$)/i;
47
+
48
+ /**
49
+ * Only genuine user turns carry authoritative settings-change blocks. Tool output, code views
50
+ * and planner text that merely quote the tag are ignored.
51
+ */
52
+ function isUserInputEntry(entry) {
53
+ const t = String(entry?.type || '').toUpperCase();
54
+ if (t) return t === 'USER_INPUT';
55
+ return /^USER/i.test(String(entry?.source || ''));
56
+ }
57
+
58
+ /**
59
+ * Parses all <USER_SETTINGS_CHANGE> blocks in a user turn.
60
+ * Returns [{ setting, from, to }] in order of appearance.
61
+ */
62
+ export function parseSettingsChanges(rawContent = '') {
63
+ const out = [];
64
+ const text = String(rawContent || '');
65
+ if (!text.includes('<USER_SETTINGS_CHANGE>')) return out;
66
+ const blocks = text.match(/<USER_SETTINGS_CHANGE>[\s\S]*?<\/USER_SETTINGS_CHANGE>/gi) || [];
67
+ for (const block of blocks) {
68
+ const inner = block.replace(/<\/?USER_SETTINGS_CHANGE>/gi, '').replace(/\r?\n/g, ' ').trim();
69
+ const m = inner.match(SETTINGS_CHANGE_RE) || inner.match(SETTINGS_CHANGE_FALLBACK_RE);
70
+ if (m) {
71
+ out.push({ setting: m[1], from: m[2].trim(), to: m[3].trim() });
72
+ }
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /**
78
+ * Returns the most recent `Model Selection` target from USER_INPUT settings-change blocks,
79
+ * or null when the transcript never records a model switch.
80
+ */
81
+ export function resolveModelFromTranscript(steps = []) {
82
+ for (let i = (steps?.length || 0) - 1; i >= 0; i--) {
83
+ const st = steps[i];
84
+ if (!st || !isUserInputEntry(st)) continue;
85
+ const content = String(st.content || '');
86
+ if (!content.includes('<USER_SETTINGS_CHANGE>')) continue;
87
+ const changes = parseSettingsChanges(content).filter(c => /model selection/i.test(c.setting));
88
+ if (changes.length > 0) {
89
+ const raw = changes[changes.length - 1].to;
90
+ if (raw && !/^none$/i.test(raw)) return { raw, id: normalizeModelId(raw) };
91
+ }
92
+ }
93
+ return null;
94
+ }
95
+
96
+ /**
97
+ * Model precedence: stdin (host) > gen_metadata.model > last USER_INPUT Model Selection > fallback.
98
+ * Returns { id, raw, source: 'stdin' | 'gen_metadata' | 'transcript' | 'fallback' }.
99
+ */
100
+ export function resolveSessionModel({ stdinData = null, genMetadata = null, steps = [], fallback = 'gemini-3.8-flash' } = {}) {
101
+ const stdinModel = stdinData?.model?.id || (typeof stdinData?.model === 'string' ? stdinData.model : null) || stdinData?.modelName || null;
102
+ if (stdinModel) return { id: stdinModel, raw: stdinModel, source: 'stdin' };
103
+ if (genMetadata?.model) return { id: normalizeModelId(genMetadata.model), raw: genMetadata.model, source: 'gen_metadata' };
104
+ const fromTranscript = resolveModelFromTranscript(steps);
105
+ if (fromTranscript) return { id: fromTranscript.id, raw: fromTranscript.raw, source: 'transcript' };
106
+ return { id: fallback, raw: fallback, source: 'fallback' };
107
+ }
108
+
109
+ /**
110
+ * Extracts model/effort metadata from a raw JSONL transcript entry if present.
111
+ */
112
+ export function extractTurnEffortMetadata(entry) {
113
+ if (!entry || typeof entry !== 'object') return null;
114
+
115
+ const rawContent = String(entry.content || '');
116
+ let fromSpec = null;
117
+ let toSpec = null;
118
+ let setting = null;
119
+ let modelFromSpec = null;
120
+ let modelToSpec = null;
121
+
122
+ if (isUserInputEntry(entry) && rawContent.includes('<USER_SETTINGS_CHANGE>')) {
123
+ for (const change of parseSettingsChanges(rawContent)) {
124
+ if (fromSpec === null) fromSpec = change.from;
125
+ toSpec = change.to;
126
+ setting = change.setting;
127
+ if (/model selection/i.test(change.setting)) {
128
+ if (modelFromSpec === null) modelFromSpec = change.from;
129
+ modelToSpec = change.to;
130
+ }
131
+ }
132
+ }
133
+
134
+ const rawExplicit = entry.turnMetadata || entry.turn_metadata;
135
+ const explicitMeta = rawExplicit && typeof rawExplicit === 'object' ? rawExplicit : null;
136
+ const effort = explicitMeta?.effort || explicitMeta?.reasoningEffort || explicitMeta?.reasoning_effort ||
137
+ entry.effort || entry.reasoning_effort || entry.reasoningEffort || null;
138
+ const tier = explicitMeta?.tier || explicitMeta?.effortTier || entry.effortTier || entry.tier || null;
139
+ const model = explicitMeta?.model || explicitMeta?.modelId ||
140
+ (typeof entry.model === 'string' ? entry.model : (entry.model?.id || entry.modelId || entry.model_id || null));
141
+
142
+ if (!toSpec && !effort && !tier && !model && !explicitMeta) {
143
+ return null;
144
+ }
145
+
146
+ return {
147
+ fromSpec: explicitMeta?.fromSpec ?? fromSpec,
148
+ toSpec: explicitMeta?.toSpec ?? toSpec,
149
+ setting: setting || null,
150
+ effort: effort || toSpec || null,
151
+ tier: tier || null,
152
+ model: model || modelToSpec || null,
153
+ modelId: modelToSpec ? normalizeModelId(modelToSpec) : null,
154
+ modelFromSpec,
155
+ modelToSpec,
156
+ rawLabel: toSpec || effort || tier || model || ''
157
+ };
158
+ }
159
+
160
+ /**
161
+ * Evaluates step-by-step effort profile resolution and mid-session transitions.
162
+ */
163
+ export function extractEffortTimeline(steps = [], options = {}) {
164
+ let currentProfile = { ...EFFORT_PROFILES.STANDARD };
165
+ let hasEstablishedTier = false;
166
+ let cumTokens = 0;
167
+ const effortHistory = [];
168
+ const maxTokens = Number(options?.maxTokens) > 0 ? Number(options.maxTokens) : 256000;
169
+ const tokensPerCell = Math.max(1, Math.round(maxTokens / 40));
170
+
171
+ for (let idx = 0; idx < steps.length; idx++) {
172
+ const step = steps[idx] || {};
173
+ const stepTok = step.inputTokens > 0 && step.outputTokens > 0
174
+ ? Math.max(step.outputTokens, Math.round((step.untruncatedLength || 0) / 4))
175
+ : (step.outputTokens || Math.round((step.untruncatedLength || 0) / 4) || 1000);
176
+ const estBlock = Math.min(39, Math.max(0, Math.floor(cumTokens / tokensPerCell)));
177
+ cumTokens += stepTok;
178
+
179
+ const meta = step.turnMetadata || extractTurnEffortMetadata(step);
180
+ if (!meta) continue;
181
+
182
+ const hasExplicitFrom = meta.fromSpec && !/^none$/i.test(String(meta.fromSpec).trim());
183
+ if (hasExplicitFrom) {
184
+ const fromProf = resolveEffortProfile(meta.fromSpec);
185
+ const toProf = resolveEffortProfile(meta);
186
+ const effectiveFrom = hasEstablishedTier ? currentProfile : fromProf;
187
+ if (toProf.tier !== effectiveFrom.tier) {
188
+ effortHistory.push({
189
+ turnIndex: idx,
190
+ stepNumber: step.stepIndex ?? idx,
191
+ blockIndex: estBlock,
192
+ fromTier: effectiveFrom.tier,
193
+ toTier: toProf.tier,
194
+ fromLabel: effectiveFrom.shortLabel || effectiveFrom.label,
195
+ toLabel: toProf.shortLabel || toProf.label,
196
+ timestamp: step.createdAt || step.timestamp || null
197
+ });
198
+ }
199
+ currentProfile = toProf;
200
+ hasEstablishedTier = true;
201
+ continue;
202
+ }
203
+
204
+ if (idx === 0 && !hasEstablishedTier) {
205
+ currentProfile = resolveEffortProfile(meta);
206
+ hasEstablishedTier = true;
207
+ continue;
208
+ }
209
+
210
+ const nextProfile = resolveEffortProfile(meta);
211
+ if (nextProfile.tier !== currentProfile.tier) {
212
+ effortHistory.push({
213
+ turnIndex: idx,
214
+ stepNumber: step.stepIndex ?? idx,
215
+ blockIndex: estBlock,
216
+ fromTier: currentProfile.tier,
217
+ toTier: nextProfile.tier,
218
+ fromLabel: currentProfile.shortLabel || currentProfile.label,
219
+ toLabel: nextProfile.shortLabel || nextProfile.label,
220
+ timestamp: step.createdAt || step.timestamp || null
221
+ });
222
+ currentProfile = nextProfile;
223
+ }
224
+ hasEstablishedTier = true;
225
+ }
226
+
227
+ return {
228
+ activeEffortProfile: currentProfile,
229
+ effortHistory
230
+ };
231
+ }
232
+
233
+ /**
234
+ * 4-Tier Untruncated Log Resolver
235
+ * Tier 1: transcript_full.jsonl
236
+ * Tier 2: chunks/transcript_full/*.jsonl
237
+ * Tier 3: transcript.jsonl + steps/<idx>/output.txt hydration
238
+ * Tier 4: chunks/transcript/*.jsonl
239
+ */
240
+ export function resolveSessionLogs(sessionDir) {
241
+ if (!sessionDir || typeof sessionDir !== 'string') return null;
242
+
243
+ // Support direct file paths for Claude Code (.jsonl) and Cursor (state.vscdb)
244
+ try {
245
+ if (fs.existsSync(sessionDir) && fs.statSync(sessionDir).isFile()) {
246
+ if (sessionDir.toLowerCase().endsWith('.vscdb')) {
247
+ return { tier: 1, type: 'cursor-vscdb', path: sessionDir };
248
+ }
249
+ if (sessionDir.toLowerCase().endsWith('.jsonl')) {
250
+ return { tier: 1, type: 'claude-jsonl', path: sessionDir };
251
+ }
252
+ }
253
+ } catch {}
254
+
255
+ const vscdbCandidate = path.join(sessionDir, 'state.vscdb');
256
+ if (fs.existsSync(vscdbCandidate)) {
257
+ return { tier: 1, type: 'cursor-vscdb', path: vscdbCandidate };
258
+ }
259
+
260
+ const logsDir = path.join(sessionDir, '.system_generated', 'logs');
261
+ const stepsDir = path.join(sessionDir, '.system_generated', 'steps');
262
+
263
+ // Tier 1
264
+ const t1 = path.join(logsDir, 'transcript_full.jsonl');
265
+ if (fs.existsSync(t1) && fs.statSync(t1).size > 0) {
266
+ return { tier: 1, type: 'single', path: t1 };
267
+ }
268
+
269
+ // Tier 2
270
+ const t2Dir = path.join(logsDir, 'chunks', 'transcript_full');
271
+ if (fs.existsSync(t2Dir)) {
272
+ const chunkFiles = fs.readdirSync(t2Dir)
273
+ .filter(f => f.endsWith('.jsonl'))
274
+ .sort((a, b) => {
275
+ const numA = parseInt(a.replace(/\D/g, '') || '0', 10);
276
+ const numB = parseInt(b.replace(/\D/g, '') || '0', 10);
277
+ return numA - numB;
278
+ })
279
+ .map(f => path.join(t2Dir, f));
280
+ if (chunkFiles.length > 0) {
281
+ return { tier: 2, type: 'chunks', paths: chunkFiles };
282
+ }
283
+ }
284
+
285
+ // Tier 3
286
+ const t3 = path.join(logsDir, 'transcript.jsonl');
287
+ if (fs.existsSync(t3) && fs.statSync(t3).size > 0) {
288
+ return { tier: 3, type: 'hydrated', path: t3, stepsDir };
289
+ }
290
+
291
+ // Tier 4
292
+ const t4Dir = path.join(logsDir, 'chunks', 'transcript');
293
+ if (fs.existsSync(t4Dir)) {
294
+ const chunkFiles = fs.readdirSync(t4Dir)
295
+ .filter(f => f.endsWith('.jsonl'))
296
+ .sort((a, b) => {
297
+ const numA = parseInt(a.replace(/\D/g, '') || '0', 10);
298
+ const numB = parseInt(b.replace(/\D/g, '') || '0', 10);
299
+ return numA - numB;
300
+ })
301
+ .map(f => path.join(t4Dir, f));
302
+ if (chunkFiles.length > 0) {
303
+ return { tier: 4, type: 'chunks', paths: chunkFiles };
304
+ }
305
+ }
306
+
307
+ return null;
308
+ }
309
+
310
+ /**
311
+ * Parses raw JSONL lines into structured step records.
312
+ * Hydrates steps/<idx>/output.txt when tier is 3 and truncated_fields is present.
313
+ */
314
+ export function parseRawJsonl(content, { tier = 1, stepsDir = null, withHealth = false } = {}) {
315
+ const lines = content.split(/\r?\n/).filter(line => line.trim().length > 0);
316
+ const steps = [];
317
+ let malformedLines = 0;
318
+ let unknownShapeLines = 0;
319
+
320
+ for (const line of lines) {
321
+ let entry;
322
+ try {
323
+ entry = JSON.parse(line);
324
+ } catch {
325
+ malformedLines++;
326
+ continue;
327
+ }
328
+
329
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
330
+ malformedLines++;
331
+ continue;
332
+ }
333
+
334
+ // Check recognizable Antigravity/Agent log shape
335
+ const hasIdx = entry.step_index !== undefined || entry.stepIndex !== undefined;
336
+ const hasType = typeof entry.type === 'string' || entry.step_type !== undefined || entry.stepType !== undefined;
337
+ const hasContent = entry.content !== undefined;
338
+ const hasRole = typeof entry.role === 'string';
339
+ const hasCalls = Array.isArray(entry.tool_calls) || Array.isArray(entry.toolCalls);
340
+ if (!hasIdx && !hasType && !hasContent && !hasRole && !hasCalls) {
341
+ unknownShapeLines++;
342
+ continue;
343
+ }
344
+
345
+ try {
346
+ const stepIdx = entry.step_index ?? entry.stepIndex ?? steps.length;
347
+ let rawContent = entry.content || '';
348
+ let isTruncated = Array.isArray(entry.truncated_fields) && entry.truncated_fields.length > 0;
349
+
350
+ // Tier 3 Hydration check
351
+ if (isTruncated && stepsDir) {
352
+ const outputTxtPath = path.join(stepsDir, String(stepIdx), 'output.txt');
353
+ if (fs.existsSync(outputTxtPath)) {
354
+ try {
355
+ rawContent = fs.readFileSync(outputTxtPath, 'utf8');
356
+ isTruncated = false;
357
+ } catch {
358
+ // retain rawContent
359
+ }
360
+ }
361
+ }
362
+
363
+ const turnMetadata = extractTurnEffortMetadata({ ...entry, content: rawContent });
364
+ const usage = entry.usage || entry.token_usage || {};
365
+ const cacheReadTokens = Number(
366
+ entry.cache_read_input_tokens ??
367
+ entry.cacheReadInputTokens ??
368
+ usage.cache_read_input_tokens ??
369
+ usage.cached_content_token_count ??
370
+ 0
371
+ );
372
+ const cacheCreationTokens = Number(
373
+ entry.cache_creation_input_tokens ??
374
+ entry.cacheCreationInputTokens ??
375
+ usage.cache_creation_input_tokens ??
376
+ 0
377
+ );
378
+ const thinkingTokens = Number(
379
+ entry.thinking_tokens ??
380
+ entry.thinkingTokens ??
381
+ usage.thinking_tokens ??
382
+ usage.thoughts_token_count ??
383
+ (entry.thinking ? Math.ceil(String(entry.thinking).length / 4) : 0)
384
+ );
385
+ const rawSubagentId = entry.subagent_id || entry.subagentId || entry.agent_id || entry.agentId || null;
386
+ const agentId = rawSubagentId && rawSubagentId !== 'parent' && rawSubagentId !== 'main'
387
+ ? (String(rawSubagentId).startsWith('child:') ? String(rawSubagentId) : `child:${rawSubagentId}`)
388
+ : 'parent';
389
+
390
+ const rawStepType = entry.step_type ?? entry.stepType ?? null;
391
+ const isCortexCheckpoint =
392
+ Number(rawStepType) === 23 ||
393
+ rawStepType === 'CORTEX_STEP_TYPE_CHECKPOINT' ||
394
+ entry.type === 'CORTEX_STEP_TYPE_CHECKPOINT' ||
395
+ entry.type === 'CHECKPOINT';
396
+
397
+ steps.push({
398
+ stepIndex: stepIdx,
399
+ agentId,
400
+ source: entry.source || 'MODEL',
401
+ type: isCortexCheckpoint ? 'CHECKPOINT' : (entry.type || 'PLANNER_RESPONSE'),
402
+ ...(rawStepType !== null ? { stepType: rawStepType, step_type: rawStepType } : (isCortexCheckpoint ? { stepType: 23, step_type: 23 } : {})),
403
+ status: entry.status || 'DONE',
404
+ createdAt: entry.created_at || entry.createdAt || entry.timestamp || null,
405
+ toolCalls: entry.tool_calls || entry.toolCalls || [],
406
+ content: rawContent,
407
+ inputTokens: entry.input_tokens || entry.inputTokens || usage.input_tokens || 0,
408
+ outputTokens: entry.output_tokens || entry.outputTokens || usage.output_tokens || 0,
409
+ cacheReadTokens,
410
+ cacheCreationTokens,
411
+ thinkingTokens,
412
+ untruncatedLength: rawContent.length,
413
+ isTruncated,
414
+ ...(turnMetadata ? { turnMetadata } : {})
415
+ });
416
+ } catch {
417
+ malformedLines++;
418
+ }
419
+ }
420
+
421
+ const totalLines = lines.length;
422
+ const parsedLines = steps.length;
423
+ let confidence = 'HIGH';
424
+ if (totalLines > 0) {
425
+ const badFraction = (malformedLines + unknownShapeLines) / totalLines;
426
+ if (parsedLines === 0 || badFraction > 0.15) {
427
+ confidence = 'LOW';
428
+ } else if (badFraction > 0.02) {
429
+ confidence = 'DEGRADED';
430
+ }
431
+ }
432
+
433
+ const health = {
434
+ totalLines,
435
+ parsedLines,
436
+ malformedLines,
437
+ unknownShapeLines,
438
+ confidence
439
+ };
440
+
441
+ Object.defineProperty(steps, 'health', {
442
+ value: health,
443
+ enumerable: false,
444
+ writable: true,
445
+ configurable: true
446
+ });
447
+
448
+ if (withHealth) {
449
+ return { steps, health };
450
+ }
451
+
452
+ return steps;
453
+ }
454
+
455
+ /**
456
+ * Helper to get the real last-activity timestamp of a session folder on Windows
457
+ * (checks transcript logs inside .system_generated/logs rather than just folder mtime)
458
+ */
459
+ function getRealSessionMtimeMs(sessionDir) {
460
+ let maxMtime = 0;
461
+ try {
462
+ maxMtime = fs.statSync(sessionDir).mtimeMs;
463
+ } catch {
464
+ return 0;
465
+ }
466
+ const candidates = [
467
+ path.join(sessionDir, '.system_generated', 'logs', 'transcript_full.jsonl'),
468
+ path.join(sessionDir, '.system_generated', 'logs', 'transcript.jsonl')
469
+ ];
470
+ for (const c of candidates) {
471
+ try {
472
+ if (fs.existsSync(c)) {
473
+ const m = fs.statSync(c).mtimeMs;
474
+ if (m > maxMtime) maxMtime = m;
475
+ }
476
+ } catch {}
477
+ }
478
+ return maxMtime;
479
+ }
480
+
481
+ /**
482
+ * Discovers Claude Code sessions under ~/.claude/projects/<project>/<sid>.jsonl
483
+ * Direct calls work as an explicit adapter; automatic discovery callers pass options.
484
+ */
485
+ export function discoverClaudeCodeSessions(homeDir = getHomeDir(), options = { includeCrossHost: true }) {
486
+ const projectsDir = getClaudeCodeProjectsDir(homeDir, options);
487
+ if (!projectsDir || !fs.existsSync(projectsDir)) return [];
488
+ const sessions = [];
489
+ const inspectJsonlFile = (fullPath, projectSlug = '') => {
490
+ try {
491
+ const stat = fs.statSync(fullPath);
492
+ if (!stat.isFile() || stat.size === 0) return;
493
+ const base = path.basename(fullPath);
494
+ if (!base.endsWith('.jsonl') || base.startsWith('.')) return;
495
+ const sessionId = base.replace(/\.jsonl$/i, '');
496
+ sessions.push({
497
+ storeName: 'claude-code',
498
+ surface: 'claude-code',
499
+ surfaceTag: '[Claude]',
500
+ sessionDir: fullPath,
501
+ filePath: fullPath,
502
+ sessionId,
503
+ projectSlug,
504
+ mtimeMs: stat.mtimeMs
505
+ });
506
+ } catch {}
507
+ };
508
+
509
+ try {
510
+ const entries = fs.readdirSync(projectsDir, { withFileTypes: true });
511
+ for (const entry of entries) {
512
+ const full = path.join(projectsDir, entry.name);
513
+ if (entry.isFile() && entry.name.endsWith('.jsonl')) {
514
+ inspectJsonlFile(full, '');
515
+ } else if (entry.isDirectory()) {
516
+ try {
517
+ const children = fs.readdirSync(full);
518
+ for (const child of children) {
519
+ if (child.endsWith('.jsonl')) {
520
+ inspectJsonlFile(path.join(full, child), entry.name);
521
+ }
522
+ }
523
+ } catch {}
524
+ }
525
+ }
526
+ } catch {}
527
+
528
+ return sessions.sort((a, b) => b.mtimeMs - a.mtimeMs);
529
+ }
530
+
531
+ /**
532
+ * Discovers Cursor IDE sessions under workspaceStorage/<hash>/state.vscdb in strict read-only mode.
533
+ * Direct calls work as an explicit adapter; automatic discovery callers pass options.
534
+ */
535
+ export function discoverCursorSessions(homeDir = getHomeDir(), DatabaseSyncClass = null, options = { includeCrossHost: true }) {
536
+ const storageDirs = getCursorWorkspaceStorageDirs(homeDir, options);
537
+ if (storageDirs.length === 0) return [];
538
+ const DbCtor = DatabaseSyncClass || getSqliteDatabaseSync();
539
+ const sessions = [];
540
+
541
+ for (const storageRoot of storageDirs) {
542
+ let entries = [];
543
+ try {
544
+ entries = fs.readdirSync(storageRoot, { withFileTypes: true });
545
+ } catch {
546
+ continue;
547
+ }
548
+ for (const entry of entries) {
549
+ if (!entry.isDirectory()) continue;
550
+ const wsDir = path.join(storageRoot, entry.name);
551
+ const vscdbPath = path.join(wsDir, 'state.vscdb');
552
+ if (!fs.existsSync(vscdbPath)) continue;
553
+ try {
554
+ const stat = fs.statSync(vscdbPath);
555
+ if (!stat.isFile() || stat.size === 0) continue;
556
+ let composerId = null;
557
+ let title = '';
558
+ let bubbleCount = 0;
559
+ let workspaceUri = '';
560
+
561
+ const wsJsonPath = path.join(wsDir, 'workspace.json');
562
+ if (fs.existsSync(wsJsonPath)) {
563
+ try {
564
+ const wsJson = JSON.parse(fs.readFileSync(wsJsonPath, 'utf8'));
565
+ workspaceUri = wsJson.folder || wsJson.workspace || '';
566
+ } catch {}
567
+ }
568
+
569
+ if (DbCtor) {
570
+ let db = null;
571
+ try {
572
+ db = new DbCtor(vscdbPath, SQLITE_OPEN_READONLY_OPTIONS);
573
+ const hasTable = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='cursorDiskKV'").get();
574
+ if (hasTable) {
575
+ const compRow = db.prepare("SELECT key, value FROM cursorDiskKV WHERE key LIKE 'composerData:%' LIMIT 1").get();
576
+ if (compRow && compRow.key) {
577
+ composerId = String(compRow.key).slice('composerData:'.length);
578
+ try {
579
+ const val = typeof compRow.value === 'string' ? JSON.parse(compRow.value) : JSON.parse(Buffer.from(compRow.value).toString('utf8'));
580
+ title = val?.name || val?.title || '';
581
+ } catch {}
582
+ }
583
+ const cntRow = db.prepare("SELECT COUNT(*) AS cnt FROM cursorDiskKV WHERE key LIKE 'bubbleId:%'").get();
584
+ bubbleCount = Number(cntRow?.cnt || 0);
585
+ }
586
+ } catch {} finally {
587
+ try { if (db && typeof db.close === 'function') db.close(); } catch {}
588
+ }
589
+ }
590
+
591
+ if (composerId || bubbleCount > 0) {
592
+ const sid = composerId || `cursor-${entry.name}`;
593
+ sessions.push({
594
+ storeName: 'cursor',
595
+ surface: 'cursor',
596
+ surfaceTag: '[Cursor]',
597
+ sessionDir: vscdbPath,
598
+ filePath: vscdbPath,
599
+ sessionId: sid,
600
+ title: title || sid.slice(0, 8),
601
+ stepCount: bubbleCount,
602
+ workspaceUri,
603
+ mtimeMs: stat.mtimeMs
604
+ });
605
+ }
606
+ } catch {}
607
+ }
608
+ }
609
+
610
+ return sessions.sort((a, b) => b.mtimeMs - a.mtimeMs);
611
+ }
612
+
613
+ /**
614
+ * Finds the active session directory across Antigravity ([App], [IDE], [CLI]) by default.
615
+ * Cross-host Claude Code ([Claude]) and Cursor ([Cursor]) discovery is strictly gated behind
616
+ * `options.harness === 'claude' | 'cursor' | 'all'` or `options.includeCrossHost === true`.
617
+ */
618
+ export function findSessionDirectory(sessionId, homeDir = getHomeDir(), options = {}) {
619
+ const opts = options && typeof options === 'object' ? options : {};
620
+ const includeClaude = isCrossHostHarnessEnabled('claude', opts);
621
+ const includeCursor = isCrossHostHarnessEnabled('cursor', opts);
622
+ const normalizedHarness = String(opts.harness || '').trim().toLowerCase();
623
+ const includeAntigravity =
624
+ !normalizedHarness ||
625
+ normalizedHarness === 'antigravity' ||
626
+ normalizedHarness === 'all' ||
627
+ normalizedHarness === 'cross-host' ||
628
+ opts.includeCrossHost === true;
629
+
630
+ const stores = includeAntigravity ? getBrainStores(homeDir) : [];
631
+ if (sessionId) {
632
+ if (fs.existsSync(sessionId)) {
633
+ const isVscdb = sessionId.toLowerCase().endsWith('.vscdb') || fs.existsSync(path.join(sessionId, 'state.vscdb'));
634
+ const isJsonl = sessionId.toLowerCase().endsWith('.jsonl');
635
+ const storeName = isVscdb ? 'cursor' : (isJsonl ? 'claude-code' : 'antigravity');
636
+ return {
637
+ storeName,
638
+ surfaceTag: resolveSurfaceTag(storeName),
639
+ sessionDir: sessionId,
640
+ sessionId: path.basename(sessionId).replace(/\.(jsonl|vscdb)$/i, '')
641
+ };
642
+ }
643
+ for (const store of stores) {
644
+ const target = path.join(store.path, sessionId);
645
+ if (fs.existsSync(target)) {
646
+ return {
647
+ storeName: store.name,
648
+ surfaceTag: store.surfaceTag || resolveSurfaceTag(store.name),
649
+ sessionDir: target,
650
+ sessionId
651
+ };
652
+ }
653
+ }
654
+ if (includeAntigravity) {
655
+ // Check if a conversations/<sessionId>.db exists in any surface even if brain/<sessionId> is not yet created
656
+ const surfaces = getAntigravitySurfaces(homeDir, { includeMissing: true });
657
+ for (const surface of surfaces) {
658
+ const dbFile = path.join(surface.conversationsDir, `${sessionId}.db`);
659
+ if (fs.existsSync(dbFile)) {
660
+ return {
661
+ storeName: surface.name,
662
+ surfaceTag: surface.surfaceTag || resolveSurfaceTag(surface.name),
663
+ sessionDir: path.join(surface.brainDir, sessionId),
664
+ dbPath: dbFile,
665
+ sessionId
666
+ };
667
+ }
668
+ }
669
+ }
670
+ if (includeClaude) {
671
+ const claudeMatch = discoverClaudeCodeSessions(homeDir, opts).find(s => s.sessionId === sessionId);
672
+ if (claudeMatch) return claudeMatch;
673
+ }
674
+ if (includeCursor) {
675
+ const cursorMatch = discoverCursorSessions(homeDir, null, opts).find(s => s.sessionId === sessionId);
676
+ if (cursorMatch) return cursorMatch;
677
+ }
678
+ }
679
+
680
+ // Fallback to most recently active session based on real transcript log mtime across enabled harnesses
681
+ let latest = null;
682
+ for (const store of stores) {
683
+ try {
684
+ const entries = fs.readdirSync(store.path);
685
+ for (const name of entries) {
686
+ const full = path.join(store.path, name);
687
+ try {
688
+ const stat = fs.statSync(full);
689
+ if (stat.isDirectory()) {
690
+ const realMtime = getRealSessionMtimeMs(full);
691
+ if (!latest || realMtime > latest.mtimeMs) {
692
+ latest = {
693
+ storeName: store.name,
694
+ surfaceTag: store.surfaceTag || resolveSurfaceTag(store.name),
695
+ sessionDir: full,
696
+ sessionId: name,
697
+ mtimeMs: realMtime
698
+ };
699
+ }
700
+ }
701
+ } catch {}
702
+ }
703
+ } catch {}
704
+ }
705
+
706
+ if (includeClaude) {
707
+ for (const claudeSess of discoverClaudeCodeSessions(homeDir, opts)) {
708
+ if (!latest || claudeSess.mtimeMs > latest.mtimeMs) {
709
+ latest = claudeSess;
710
+ }
711
+ }
712
+ }
713
+
714
+ if (includeCursor) {
715
+ for (const cursorSess of discoverCursorSessions(homeDir, null, opts)) {
716
+ if (!latest || cursorSess.mtimeMs > latest.mtimeMs) {
717
+ latest = cursorSess;
718
+ }
719
+ }
720
+ }
721
+
722
+ return latest;
723
+ }
724
+
725
+ const genMetaMemo = new Map();
726
+
727
+ /**
728
+ * Reads exact token telemetry (input_tokens + cache_read_tokens) and mid-run Prefix Bust
729
+ * events from a session's conversations/<uuid>.db SQLite store (gen_metadata table) in strict read-only mode.
730
+ */
731
+ export function readSessionGenMetadataSync(dbPath, DatabaseSyncClass = null) {
732
+ if (!dbPath || !fs.existsSync(dbPath) || !DatabaseSyncClass) return null;
733
+ let sig = '';
734
+ try {
735
+ const st = fs.statSync(dbPath);
736
+ sig = `${dbPath}|${st.mtimeMs}|${st.size}`;
737
+ if (genMetaMemo.has(sig)) return genMetaMemo.get(sig);
738
+ } catch {
739
+ return null;
740
+ }
741
+ let db = null;
742
+ try {
743
+ db = new DatabaseSyncClass(dbPath, SQLITE_OPEN_READONLY_OPTIONS);
744
+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='gen_metadata'").all();
745
+ if (!tables || tables.length === 0) return null;
746
+
747
+ const rows = db.prepare(
748
+ 'SELECT input_tokens, cache_read_tokens, output_tokens, model, created_at FROM gen_metadata ORDER BY rowid DESC LIMIT 10'
749
+ ).all();
750
+ if (!rows || rows.length === 0) return null;
751
+
752
+ let turnCount = rows.length;
753
+ try {
754
+ const countRow = db.prepare('SELECT COUNT(*) AS cnt FROM gen_metadata').get();
755
+ if (countRow && Number(countRow.cnt) > 0) turnCount = Number(countRow.cnt);
756
+ } catch {}
757
+
758
+ const row = rows[0];
759
+ const prevRow = rows[1] || null;
760
+ const inputTokens = Number(row.input_tokens || 0);
761
+ const cacheReadTokens = Number(row.cache_read_tokens || 0);
762
+ const outputTokens = Number(row.output_tokens || 0);
763
+
764
+ let prefixBustDetected = false;
765
+ let prefixBustDeltaSec = null;
766
+ const prevCacheRead = Number(prevRow?.cache_read_tokens || 0);
767
+ const modelChanged = Boolean(prevRow?.model && row?.model && prevRow.model !== row.model);
768
+ if (prevRow && cacheReadTokens === 0 && inputTokens > 0 && prevCacheRead > 0) {
769
+ const currMs = row.created_at ? Date.parse(row.created_at) : NaN;
770
+ const prevMs = prevRow.created_at ? Date.parse(prevRow.created_at) : NaN;
771
+ if (Number.isFinite(currMs) && Number.isFinite(prevMs) && currMs >= prevMs) {
772
+ const deltaSec = (currMs - prevMs) / 1000;
773
+ if (deltaSec < 300) {
774
+ prefixBustDetected = true;
775
+ prefixBustDeltaSec = Math.round(deltaSec);
776
+ }
777
+ }
778
+ }
779
+
780
+ const recentTurns = rows.slice().reverse().map((r, idx) => ({
781
+ stepIndex: idx,
782
+ inputTokens: Number(r.input_tokens || 0),
783
+ cacheReadTokens: Number(r.cache_read_tokens || 0),
784
+ outputTokens: Number(r.output_tokens || 0),
785
+ model: r.model || null,
786
+ createdAt: r.created_at || null
787
+ }));
788
+
789
+ const result = {
790
+ inputTokens,
791
+ cacheReadTokens,
792
+ outputTokens,
793
+ totalContextTokens: inputTokens + cacheReadTokens,
794
+ turnCount,
795
+ model: row.model || null,
796
+ createdAt: row.created_at || null,
797
+ prefixBustDetected,
798
+ prefixBustDeltaSec,
799
+ recentTurns,
800
+ // Attribute a bust to a model switch when gen_metadata shows one.
801
+ prefixBustCause: (prefixBustDetected && modelChanged)
802
+ ? { cause: 'model_switch', from: prevRow.model, to: row.model }
803
+ : null
804
+ };
805
+ if (sig) {
806
+ if (genMetaMemo.size > 64) genMetaMemo.clear();
807
+ genMetaMemo.set(sig, result);
808
+ }
809
+ return result;
810
+ } catch {
811
+ return null;
812
+ } finally {
813
+ try { if (db && typeof db.close === 'function') db.close(); } catch {}
814
+ }
815
+ }
816
+
817
+ const incrementalMemCache = new Map();
818
+
819
+ /**
820
+ * Parses a Claude Code JSONL transcript using stitchClaudeCodeDag() to reconstruct
821
+ * active branch steps, /rewind branches, and exact prompt-cache usage telemetry.
822
+ */
823
+ export function parseClaudeCodeJsonl(rawContent = '') {
824
+ const dag = stitchClaudeCodeDag(rawContent);
825
+ const steps = [];
826
+ const usageTurns = [];
827
+ let sessionTitle = '';
828
+ let workspacePath = '';
829
+ let latestModel = null;
830
+
831
+ for (let i = 0; i < dag.activeBranchSteps.length; i++) {
832
+ const node = dag.activeBranchSteps[i];
833
+ if (!node || typeof node !== 'object') continue;
834
+ if (node.type === 'file-history-snapshot' && !node.message && !node.content) {
835
+ continue;
836
+ }
837
+ if (node.cwd && !workspacePath) {
838
+ workspacePath = String(node.cwd);
839
+ }
840
+
841
+ const msg = node.message && typeof node.message === 'object' ? node.message : null;
842
+ const role = String(msg?.role || node.role || node.type || '').toLowerCase();
843
+ const isUser = role === 'user' || node.type === 'USER_INPUT' || node.source === 'USER_EXPLICIT';
844
+ const isSummary = role === 'summary' || node.type === 'summary' || node.type === 'CHECKPOINT';
845
+
846
+ const toolCalls = Array.isArray(node.tool_calls)
847
+ ? [...node.tool_calls]
848
+ : (Array.isArray(node.toolCalls) ? [...node.toolCalls] : []);
849
+ const textParts = [];
850
+ let thinkingText = String(node.thinking || '');
851
+
852
+ const rawMsgContent = msg?.content ?? node.content;
853
+ if (typeof rawMsgContent === 'string') {
854
+ textParts.push(rawMsgContent);
855
+ } else if (Array.isArray(rawMsgContent)) {
856
+ for (const block of rawMsgContent) {
857
+ if (!block || typeof block !== 'object') continue;
858
+ if (block.type === 'text' && block.text) {
859
+ textParts.push(String(block.text));
860
+ } else if (block.type === 'thinking' && block.thinking) {
861
+ thinkingText += (thinkingText ? '\n' : '') + String(block.thinking);
862
+ } else if (block.type === 'tool_use') {
863
+ toolCalls.push({
864
+ name: block.name || 'tool_use',
865
+ args: block.input || block.args || {}
866
+ });
867
+ } else if (block.type === 'tool_result') {
868
+ const resContent = typeof block.content === 'string'
869
+ ? block.content
870
+ : (Array.isArray(block.content)
871
+ ? block.content.map(c => c?.text || '').join('\n')
872
+ : JSON.stringify(block.content || ''));
873
+ if (resContent) textParts.push(resContent);
874
+ }
875
+ }
876
+ }
877
+
878
+ const content = textParts.join('\n').trim();
879
+ if (isUser && content && !sessionTitle) {
880
+ sessionTitle = content.split(/\r?\n/)[0].slice(0, 64);
881
+ }
882
+
883
+ const usage = msg?.usage || node.usage || node.token_usage || {};
884
+ const nestedCacheCreation = (usage.cache_creation && typeof usage.cache_creation === 'object')
885
+ ? usage.cache_creation
886
+ : ((node.cache_creation && typeof node.cache_creation === 'object') ? node.cache_creation : null);
887
+ const cacheCreationEphemeral5mInputTokens = Math.max(0, Number(
888
+ node.cache_creation_ephemeral_5m_input_tokens ??
889
+ node.cacheCreationEphemeral5mInputTokens ??
890
+ usage.cache_creation_ephemeral_5m_input_tokens ??
891
+ nestedCacheCreation?.ephemeral_5m_input_tokens ??
892
+ 0
893
+ ) || 0);
894
+ const cacheCreationEphemeral1hInputTokens = Math.max(0, Number(
895
+ node.cache_creation_ephemeral_1h_input_tokens ??
896
+ node.cacheCreationEphemeral1hInputTokens ??
897
+ usage.cache_creation_ephemeral_1h_input_tokens ??
898
+ nestedCacheCreation?.ephemeral_1h_input_tokens ??
899
+ 0
900
+ ) || 0);
901
+
902
+ const inputTokens = Math.max(0, Number(
903
+ node.input_tokens ??
904
+ node.inputTokens ??
905
+ usage.input_tokens ??
906
+ 0
907
+ ) || 0);
908
+ const outputTokens = Math.max(0, Number(
909
+ node.output_tokens ??
910
+ node.outputTokens ??
911
+ usage.output_tokens ??
912
+ 0
913
+ ) || 0);
914
+ const cacheReadTokens = Math.max(0, Number(
915
+ node.cache_read_input_tokens ??
916
+ node.cacheReadInputTokens ??
917
+ usage.cache_read_input_tokens ??
918
+ usage.cached_content_token_count ??
919
+ 0
920
+ ) || 0);
921
+ const flatCacheCreationTokens = Math.max(0, Number(
922
+ node.cache_creation_input_tokens ??
923
+ node.cacheCreationInputTokens ??
924
+ usage.cache_creation_input_tokens ??
925
+ 0
926
+ ) || 0);
927
+ const cacheCreationTokens = flatCacheCreationTokens > 0
928
+ ? flatCacheCreationTokens
929
+ : (cacheCreationEphemeral5mInputTokens + cacheCreationEphemeral1hInputTokens);
930
+ const totalPromptTokens = inputTokens + cacheReadTokens + cacheCreationTokens;
931
+ const thinkingTokens = Math.max(0, Number(
932
+ node.thinking_tokens ??
933
+ node.thinkingTokens ??
934
+ usage.thinking_tokens ??
935
+ (thinkingText ? Math.ceil(thinkingText.length / 4) : 0)
936
+ ) || 0);
937
+ const model = msg?.model || node.model || null;
938
+ if (model) latestModel = model;
939
+ const createdAt = node.timestamp || node.created_at || node.createdAt || null;
940
+
941
+ if (inputTokens > 0 || cacheReadTokens > 0 || cacheCreationTokens > 0 || outputTokens > 0) {
942
+ usageTurns.push({
943
+ stepIndex: steps.length,
944
+ freshInputTokens: inputTokens,
945
+ inputTokens: inputTokens + cacheCreationTokens,
946
+ cacheReadTokens,
947
+ cacheCreationTokens,
948
+ cacheCreationEphemeral5mInputTokens,
949
+ cacheCreationEphemeral1hInputTokens,
950
+ totalPromptTokens,
951
+ outputTokens,
952
+ model: model || latestModel,
953
+ createdAt
954
+ });
955
+ }
956
+
957
+ const turnMetadata = extractTurnEffortMetadata({ ...node, model: model || undefined, content });
958
+ steps.push({
959
+ stepIndex: steps.length,
960
+ agentId: 'parent',
961
+ messageId: msg?.id || node.message_id || node.messageId || null,
962
+ source: isUser ? 'USER_EXPLICIT' : (isSummary ? 'SYSTEM' : 'MODEL'),
963
+ type: isSummary ? 'CHECKPOINT' : (isUser ? 'USER_INPUT' : 'PLANNER_RESPONSE'),
964
+ ...(isSummary ? { stepType: 23, step_type: 23 } : {}),
965
+ status: 'DONE',
966
+ createdAt,
967
+ toolCalls,
968
+ content,
969
+ freshInputTokens: inputTokens,
970
+ inputTokens,
971
+ outputTokens,
972
+ cacheReadTokens,
973
+ cacheCreationTokens,
974
+ cacheCreationEphemeral5mInputTokens,
975
+ cacheCreationEphemeral1hInputTokens,
976
+ totalPromptTokens,
977
+ totalPromptEnvelopeTokens: totalPromptTokens,
978
+ thinkingTokens,
979
+ untruncatedLength: content.length,
980
+ isTruncated: false,
981
+ ...(turnMetadata ? { turnMetadata } : {})
982
+ });
983
+ }
984
+
985
+ // Never add inferredSystemPromptTokens into steps[0].inputTokens when any step already carries
986
+ // explicit cacheCreationTokens (avoiding 2x Turn-1 cache_creation_input_tokens billing).
987
+ const hasExplicitCacheCreation = steps.some((st) => Number(st.cacheCreationTokens || 0) > 0);
988
+ if (
989
+ steps.length > 0 &&
990
+ !hasExplicitCacheCreation &&
991
+ dag.inferredSystemPromptTokens > 0 &&
992
+ steps[0].inputTokens < dag.inferredSystemPromptTokens
993
+ ) {
994
+ steps[0].inputTokens += dag.inferredSystemPromptTokens;
995
+ steps[0].totalPromptTokens = steps[0].inputTokens + steps[0].cacheReadTokens + steps[0].cacheCreationTokens;
996
+ steps[0].totalPromptEnvelopeTokens = steps[0].totalPromptTokens;
997
+ }
998
+
999
+ let genMetadata = null;
1000
+ if (usageTurns.length > 0) {
1001
+ const last = usageTurns[usageTurns.length - 1];
1002
+ const prev = usageTurns.length > 1 ? usageTurns[usageTurns.length - 2] : null;
1003
+ let prefixBustDetected = false;
1004
+ let prefixBustDeltaSec = null;
1005
+ if (prev && last.cacheReadTokens === 0 && last.inputTokens > 0 && prev.cacheReadTokens > 0) {
1006
+ const currMs = last.createdAt ? Date.parse(last.createdAt) : NaN;
1007
+ const prevMs = prev.createdAt ? Date.parse(prev.createdAt) : NaN;
1008
+ if (Number.isFinite(currMs) && Number.isFinite(prevMs) && currMs >= prevMs) {
1009
+ const deltaSec = (currMs - prevMs) / 1000;
1010
+ if (deltaSec < 300) {
1011
+ prefixBustDetected = true;
1012
+ prefixBustDeltaSec = Math.round(deltaSec);
1013
+ }
1014
+ }
1015
+ }
1016
+ const userTurnCount = steps.filter(s => s.type === 'USER_INPUT').length || usageTurns.length;
1017
+ genMetadata = {
1018
+ inputTokens: last.inputTokens,
1019
+ cacheReadTokens: last.cacheReadTokens,
1020
+ outputTokens: last.outputTokens,
1021
+ totalContextTokens: last.inputTokens + last.cacheReadTokens,
1022
+ turnCount: userTurnCount,
1023
+ model: last.model || latestModel || 'claude-sonnet-4-5',
1024
+ createdAt: last.createdAt || new Date().toISOString(),
1025
+ prefixBustDetected,
1026
+ prefixBustDeltaSec,
1027
+ recentTurns: usageTurns.slice(-10),
1028
+ prefixBustCause: null
1029
+ };
1030
+ }
1031
+
1032
+ return {
1033
+ steps,
1034
+ claudeDag: dag,
1035
+ rewindDetected: dag.rewindBranches.length > 0,
1036
+ genMetadata,
1037
+ sessionTitle,
1038
+ workspacePath
1039
+ };
1040
+ }
1041
+
1042
+ /**
1043
+ * Parses a Cursor state.vscdb SQLite file in strict read-only mode (SQLITE_OPEN_READONLY_OPTIONS).
1044
+ */
1045
+ export function parseCursorVscdbSync(vscdbPath, DatabaseSyncClass = null) {
1046
+ const DbCtor = DatabaseSyncClass || getSqliteDatabaseSync();
1047
+ if (!DbCtor || !vscdbPath || !fs.existsSync(vscdbPath)) {
1048
+ return { steps: [], genMetadata: null, sessionTitle: '', workspacePath: '' };
1049
+ }
1050
+ let db = null;
1051
+ const steps = [];
1052
+ let sessionTitle = '';
1053
+ let workspacePath = '';
1054
+ let composerId = null;
1055
+ let modelName = 'claude-sonnet-4-5';
1056
+
1057
+ try {
1058
+ const wsJsonPath = path.join(path.dirname(vscdbPath), 'workspace.json');
1059
+ if (fs.existsSync(wsJsonPath)) {
1060
+ const wsJson = JSON.parse(fs.readFileSync(wsJsonPath, 'utf8'));
1061
+ workspacePath = wsJson.folder || wsJson.workspace || '';
1062
+ }
1063
+ } catch {}
1064
+
1065
+ try {
1066
+ db = new DbCtor(vscdbPath, SQLITE_OPEN_READONLY_OPTIONS);
1067
+ const kvRows = db.prepare('SELECT key, value FROM cursorDiskKV').all();
1068
+ const bubbles = [];
1069
+ for (const row of (kvRows || [])) {
1070
+ const key = String(row.key || '');
1071
+ let val = row.value;
1072
+ if (typeof val === 'string') {
1073
+ try { val = JSON.parse(val); } catch {}
1074
+ } else if (Buffer.isBuffer(val)) {
1075
+ try { val = JSON.parse(val.toString('utf8')); } catch {}
1076
+ }
1077
+ if (key.startsWith('composerData:')) {
1078
+ const cid = key.slice('composerData:'.length);
1079
+ if (!composerId) composerId = cid;
1080
+ if (val?.name || val?.title) sessionTitle = String(val.name || val.title);
1081
+ if (val?.model || val?.modelName) modelName = String(val.model || val.modelName);
1082
+ } else if (key.startsWith('bubbleId:')) {
1083
+ const parts = key.split(':');
1084
+ const cid = parts[1] || '';
1085
+ if (!composerId || cid === composerId) {
1086
+ bubbles.push({
1087
+ composerId: cid,
1088
+ bubbleId: parts[2] || '',
1089
+ val: val || {}
1090
+ });
1091
+ }
1092
+ }
1093
+ }
1094
+
1095
+ let totalInputTok = 0;
1096
+ let totalCacheReadTok = 0;
1097
+ const recentTurns = [];
1098
+
1099
+ for (let idx = 0; idx < bubbles.length; idx++) {
1100
+ const b = bubbles[idx].val;
1101
+ const isUser = b.type === 1 || b.role === 'user';
1102
+ const content = String(b.text || b.rawText || b.content || '');
1103
+ if (isUser && content && !sessionTitle) {
1104
+ sessionTitle = content.split(/\r?\n/)[0].slice(0, 64);
1105
+ }
1106
+ if (b.model || b.modelName) modelName = String(b.model || b.modelName);
1107
+
1108
+ const toolCalls = [];
1109
+ const tfList = Array.isArray(b.toolFormerData)
1110
+ ? b.toolFormerData
1111
+ : (b.toolFormerData && typeof b.toolFormerData === 'object' ? [b.toolFormerData] : []);
1112
+ for (const tf of tfList) {
1113
+ let args = tf.params || tf.args || tf.input || {};
1114
+ if (typeof tf.rawArgs === 'string') {
1115
+ try { args = JSON.parse(tf.rawArgs); } catch {}
1116
+ }
1117
+ toolCalls.push({
1118
+ name: tf.name || tf.toolName || 'read_file',
1119
+ args: typeof args === 'object' && args ? args : {}
1120
+ });
1121
+ }
1122
+
1123
+ const inputTokens = Math.max(0, Number(b.inputTokens ?? b.tokenCount?.inputTokens ?? 0) || 0);
1124
+ const outputTokens = Math.max(0, Number(b.outputTokens ?? b.tokenCount?.outputTokens ?? 0) || 0);
1125
+ const cacheReadTokens = Math.max(0, Number(b.cacheReadTokens ?? b.tokenCount?.cacheReadTokens ?? 0) || 0);
1126
+ const createdAt = b.createdAt || b.timingInfo?.clientStartTime || null;
1127
+
1128
+ if (inputTokens > 0) totalInputTok = inputTokens;
1129
+ if (cacheReadTokens > 0) totalCacheReadTok = cacheReadTokens;
1130
+
1131
+ recentTurns.push({
1132
+ stepIndex: idx,
1133
+ inputTokens: totalInputTok,
1134
+ cacheReadTokens: totalCacheReadTok,
1135
+ outputTokens,
1136
+ model: modelName,
1137
+ createdAt
1138
+ });
1139
+
1140
+ steps.push({
1141
+ stepIndex: idx,
1142
+ agentId: 'parent',
1143
+ source: isUser ? 'USER_EXPLICIT' : 'MODEL',
1144
+ type: isUser ? 'USER_INPUT' : 'PLANNER_RESPONSE',
1145
+ status: 'DONE',
1146
+ createdAt,
1147
+ toolCalls,
1148
+ content,
1149
+ inputTokens,
1150
+ outputTokens,
1151
+ cacheReadTokens,
1152
+ cacheCreationTokens: 0,
1153
+ thinkingTokens: 0,
1154
+ untruncatedLength: content.length,
1155
+ isTruncated: false
1156
+ });
1157
+ }
1158
+
1159
+ const userTurns = steps.filter(s => s.type === 'USER_INPUT').length || steps.length;
1160
+ const genMetadata = steps.length > 0 ? {
1161
+ inputTokens: totalInputTok,
1162
+ cacheReadTokens: totalCacheReadTok,
1163
+ outputTokens: steps[steps.length - 1].outputTokens || 0,
1164
+ totalContextTokens: totalInputTok + totalCacheReadTok,
1165
+ turnCount: userTurns,
1166
+ model: modelName,
1167
+ createdAt: steps[steps.length - 1].createdAt || null,
1168
+ prefixBustDetected: false,
1169
+ prefixBustDeltaSec: null,
1170
+ recentTurns: recentTurns.slice(-10),
1171
+ prefixBustCause: null
1172
+ } : null;
1173
+
1174
+ return {
1175
+ steps,
1176
+ genMetadata,
1177
+ sessionTitle,
1178
+ workspacePath
1179
+ };
1180
+ } catch {
1181
+ return { steps: [], genMetadata: null, sessionTitle: '', workspacePath: '' };
1182
+ } finally {
1183
+ try { if (db && typeof db.close === 'function') db.close(); } catch {}
1184
+ }
1185
+ }
1186
+
1187
+ /**
1188
+ * Reads transcript incrementally using byte offsets and inode cache
1189
+ */
1190
+ export function parseTranscriptIncremental(sessionDir, cacheDir = null) {
1191
+ const resolved = resolveSessionLogs(sessionDir);
1192
+ if (!resolved) {
1193
+ return {
1194
+ tier: 0,
1195
+ steps: [],
1196
+ lastByteOffset: 0,
1197
+ activeEffortProfile: { ...EFFORT_PROFILES.STANDARD },
1198
+ effortHistory: [],
1199
+ effortTransitions: []
1200
+ };
1201
+ }
1202
+
1203
+ // Claude Code JSONL (DAG with parentUuid, /rewind, and cache_read_input_tokens)
1204
+ if (resolved.type === 'claude-jsonl') {
1205
+ const rawContent = fs.readFileSync(resolved.path, 'utf8');
1206
+ // Detect whether this JSONL is Claude Code format (has parentUuid, message.usage, or type user/assistant) vs Antigravity raw JSONL
1207
+ const isClaudeFormat = /"parentUuid"|"cache_read_input_tokens"|"cache_creation_input_tokens"|"leafUuid"|"role"\s*:\s*"(?:user|assistant)"/.test(rawContent);
1208
+ if (isClaudeFormat) {
1209
+ const parsedClaude = parseClaudeCodeJsonl(rawContent);
1210
+ const effortInfo = extractEffortTimeline(parsedClaude.steps);
1211
+ return {
1212
+ tier: resolved.tier,
1213
+ steps: parsedClaude.steps,
1214
+ filePath: resolved.path,
1215
+ rewindDetected: parsedClaude.rewindDetected,
1216
+ claudeDag: parsedClaude.claudeDag,
1217
+ genMetadata: parsedClaude.genMetadata,
1218
+ sessionTitle: parsedClaude.sessionTitle,
1219
+ workspacePath: parsedClaude.workspacePath,
1220
+ activeEffortProfile: effortInfo.activeEffortProfile,
1221
+ effortHistory: effortInfo.effortHistory,
1222
+ effortTransitions: effortInfo.effortHistory
1223
+ };
1224
+ }
1225
+ const steps = parseRawJsonl(rawContent, { tier: resolved.tier });
1226
+ const effortInfo = extractEffortTimeline(steps);
1227
+ return {
1228
+ tier: resolved.tier,
1229
+ steps,
1230
+ filePath: resolved.path,
1231
+ rewindDetected: false,
1232
+ activeEffortProfile: effortInfo.activeEffortProfile,
1233
+ effortHistory: effortInfo.effortHistory,
1234
+ effortTransitions: effortInfo.effortHistory
1235
+ };
1236
+ }
1237
+
1238
+ // Cursor state.vscdb (SQLite cursorDiskKV)
1239
+ if (resolved.type === 'cursor-vscdb') {
1240
+ const parsedCursor = parseCursorVscdbSync(resolved.path);
1241
+ const effortInfo = extractEffortTimeline(parsedCursor.steps);
1242
+ return {
1243
+ tier: resolved.tier,
1244
+ steps: parsedCursor.steps,
1245
+ filePath: resolved.path,
1246
+ rewindDetected: false,
1247
+ genMetadata: parsedCursor.genMetadata,
1248
+ sessionTitle: parsedCursor.sessionTitle,
1249
+ workspacePath: parsedCursor.workspacePath,
1250
+ activeEffortProfile: effortInfo.activeEffortProfile,
1251
+ effortHistory: effortInfo.effortHistory,
1252
+ effortTransitions: effortInfo.effortHistory
1253
+ };
1254
+ }
1255
+
1256
+ // If chunks or multiple files, do a full read of chunks
1257
+ if (resolved.type === 'chunks') {
1258
+ let allContent = '';
1259
+ for (const p of resolved.paths) {
1260
+ allContent += fs.readFileSync(p, 'utf8') + '\n';
1261
+ }
1262
+ const steps = parseRawJsonl(allContent, { tier: resolved.tier });
1263
+ const effortInfo = extractEffortTimeline(steps);
1264
+ return {
1265
+ tier: resolved.tier,
1266
+ steps,
1267
+ filePath: resolved.paths[resolved.paths.length - 1],
1268
+ activeEffortProfile: effortInfo.activeEffortProfile,
1269
+ effortHistory: effortInfo.effortHistory,
1270
+ effortTransitions: effortInfo.effortHistory
1271
+ };
1272
+ }
1273
+
1274
+ const filePath = resolved.path;
1275
+ const stat = fs.statSync(filePath);
1276
+ const sessionId = path.basename(sessionDir);
1277
+
1278
+ const defaultCacheDir = path.join(getHomeDir(), '.gemini', 'antigravity', 'cache', 'agy-horizon');
1279
+ const actualCacheDir = cacheDir || defaultCacheDir;
1280
+ const cacheFile = path.join(actualCacheDir, `${sessionId}.idx.json`);
1281
+
1282
+ let cached = { lastByteOffset: 0, steps: [], mtimeMs: 0, schemaRev: 0 };
1283
+ let rewindDetected = false;
1284
+ const memCached = incrementalMemCache.get(cacheFile);
1285
+ if (memCached && memCached.filePath === filePath && fs.existsSync(cacheFile)) {
1286
+ if (memCached.lastByteOffset <= stat.size) {
1287
+ cached = memCached;
1288
+ } else {
1289
+ rewindDetected = true;
1290
+ }
1291
+ } else if (fs.existsSync(cacheFile)) {
1292
+ try {
1293
+ const cachedData = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
1294
+ if (cachedData.schemaRev === 2 && cachedData.filePath === filePath) {
1295
+ if (cachedData.lastByteOffset <= stat.size) {
1296
+ cached = cachedData;
1297
+ incrementalMemCache.set(cacheFile, cachedData);
1298
+ } else {
1299
+ // File shrank due to IDE Undo/Rewind or surgical prune
1300
+ rewindDetected = true;
1301
+ }
1302
+ }
1303
+ } catch {}
1304
+ }
1305
+
1306
+ if (cached.lastByteOffset === stat.size && cached.schemaRev === 2) {
1307
+ const effortInfo = cached.effortInfo || extractEffortTimeline(cached.steps);
1308
+ return {
1309
+ tier: resolved.tier,
1310
+ steps: cached.steps,
1311
+ filePath,
1312
+ rewindDetected: false,
1313
+ activeEffortProfile: effortInfo.activeEffortProfile,
1314
+ effortHistory: effortInfo.effortHistory,
1315
+ effortTransitions: effortInfo.effortHistory
1316
+ };
1317
+ }
1318
+
1319
+ // Read newly appended slice in 64KB chunks via StringDecoder so multi-byte UTF-8 characters
1320
+ // split across chunk boundaries never corrupt into U+FFFD replacement characters.
1321
+ const CHUNK_BYTES = 64 * 1024;
1322
+ const fd = fs.openSync(filePath, 'r');
1323
+ let newContent = '';
1324
+ try {
1325
+ const bytesToRead = stat.size - cached.lastByteOffset;
1326
+ const chunkBuf = Buffer.alloc(Math.min(CHUNK_BYTES, Math.max(1, bytesToRead)));
1327
+ const decoder = new StringDecoder('utf8');
1328
+ let readPos = cached.lastByteOffset;
1329
+ let remaining = bytesToRead;
1330
+ while (remaining > 0) {
1331
+ const toRead = Math.min(chunkBuf.length, remaining);
1332
+ const bytesRead = fs.readSync(fd, chunkBuf, 0, toRead, readPos);
1333
+ if (bytesRead <= 0) break;
1334
+ newContent += decoder.write(chunkBuf.subarray(0, bytesRead));
1335
+ readPos += bytesRead;
1336
+ remaining -= bytesRead;
1337
+ }
1338
+ newContent += decoder.end();
1339
+ } finally {
1340
+ fs.closeSync(fd);
1341
+ }
1342
+
1343
+ const newSteps = parseRawJsonl(newContent, { tier: resolved.tier, stepsDir: resolved.stepsDir });
1344
+
1345
+ // Detect non-monotonic stepIndex regression on parent stream (Undo/Rewind)
1346
+ const prevParentSteps = (cached.steps || []).filter(s => !s?.agentId || s.agentId === 'parent');
1347
+ const newParentSteps = newSteps.filter(s => !s?.agentId || s.agentId === 'parent');
1348
+ let allSteps = [...(cached.steps || []), ...newSteps];
1349
+
1350
+ if (
1351
+ prevParentSteps.length > 0 &&
1352
+ newParentSteps.length > 0 &&
1353
+ newParentSteps[0].stepIndex <= prevParentSteps[prevParentSteps.length - 1].stepIndex
1354
+ ) {
1355
+ rewindDetected = true;
1356
+ const rollbackIdx = newParentSteps[0].stepIndex;
1357
+ const retained = (cached.steps || []).filter(s => (s.agentId && s.agentId !== 'parent') || s.stepIndex < rollbackIdx);
1358
+ allSteps = [...retained, ...newSteps];
1359
+ }
1360
+ const effortInfo = extractEffortTimeline(allSteps);
1361
+
1362
+ const updatedCachePayload = {
1363
+ schemaRev: 2,
1364
+ filePath,
1365
+ sessionId,
1366
+ lastByteOffset: stat.size,
1367
+ mtimeMs: stat.mtimeMs,
1368
+ steps: allSteps
1369
+ };
1370
+ if (incrementalMemCache.size > 24) incrementalMemCache.clear();
1371
+ incrementalMemCache.set(cacheFile, { ...updatedCachePayload, effortInfo });
1372
+
1373
+ // Save updated cache atomically
1374
+ try {
1375
+ atomicWriteFileSync(cacheFile, JSON.stringify(updatedCachePayload), { encoding: 'utf8' });
1376
+ } catch {}
1377
+
1378
+ return {
1379
+ tier: resolved.tier,
1380
+ steps: allSteps,
1381
+ filePath,
1382
+ rewindDetected,
1383
+ activeEffortProfile: effortInfo.activeEffortProfile,
1384
+ effortHistory: effortInfo.effortHistory,
1385
+ effortTransitions: effortInfo.effortHistory
1386
+ };
1387
+ }
1388
+
1389
+ /**
1390
+ * Reconciles session with conversation_summaries.db, multi-store conversations/*.db,
1391
+ * and Knowledge Items for foreign bleed detection across [App], [IDE], and [CLI].
1392
+ */
1393
+ export async function reconcileWorkspaceAndKIs(sessionId, homeDir = getHomeDir(), dbOverride = null, options = {}) {
1394
+ let workspaceUris = [];
1395
+ let projectId = '';
1396
+ let sessionTitle = '';
1397
+ let sessionSurface = 'antigravity';
1398
+ let sessionSurfaceTag = '[App]';
1399
+ let recentSessions = [];
1400
+ let sessionGenMetadata = null;
1401
+ const canonicalWorkspaceSet = new Set();
1402
+ const hasDbOverride = Boolean(dbOverride && typeof dbOverride.prepare === 'function');
1403
+ const opts = (!hasDbOverride && dbOverride && typeof dbOverride === 'object')
1404
+ ? dbOverride
1405
+ : (options && typeof options === 'object' ? options : {});
1406
+ const includeClaude = isCrossHostHarnessEnabled('claude', opts);
1407
+ const includeCursor = isCrossHostHarnessEnabled('cursor', opts);
1408
+
1409
+ try {
1410
+ const DatabaseSync = getDatabaseSyncClass();
1411
+ const surfaces = getAntigravitySurfaces(homeDir, { includeMissing: true });
1412
+ const discoveredMap = new Map();
1413
+
1414
+ const upsertDiscoveredSession = (sid, candidate) => {
1415
+ if (!sid || !candidate) return;
1416
+ if (!discoveredMap.has(sid)) {
1417
+ discoveredMap.set(sid, candidate);
1418
+ return;
1419
+ }
1420
+ const existing = discoveredMap.get(sid);
1421
+ const existingMod = String(existing.lastModified || '');
1422
+ const candidateMod = String(candidate.lastModified || '');
1423
+ const preferCandidate = candidateMod.localeCompare(existingMod) > 0;
1424
+ const primary = preferCandidate ? candidate : existing;
1425
+ const secondary = preferCandidate ? existing : candidate;
1426
+ const defaultPrefix = sid.slice(0, 8);
1427
+ const bestTitle = (primary.title && primary.title !== defaultPrefix)
1428
+ ? primary.title
1429
+ : (secondary.title || primary.title || defaultPrefix);
1430
+
1431
+ discoveredMap.set(sid, {
1432
+ ...secondary,
1433
+ ...primary,
1434
+ title: bestTitle,
1435
+ stepCount: Math.max(Number(existing.stepCount || 0), Number(candidate.stepCount || 0)),
1436
+ workspace: primary.workspace || secondary.workspace || '',
1437
+ liveTokens: primary.liveTokens || secondary.liveTokens,
1438
+ cacheReadTokens: primary.cacheReadTokens ?? secondary.cacheReadTokens
1439
+ });
1440
+ };
1441
+
1442
+ const processSummaryDb = (dbInstance, surfaceDesc) => {
1443
+ if (!dbInstance) return;
1444
+ if (sessionId) {
1445
+ try {
1446
+ const row = dbInstance.prepare('SELECT title, workspace_uris, project_id FROM conversation_summaries WHERE conversation_id = ?').get(sessionId);
1447
+ if (row && !sessionTitle) {
1448
+ sessionTitle = row.title || '';
1449
+ projectId = row.project_id || '';
1450
+ sessionSurface = surfaceDesc.name;
1451
+ sessionSurfaceTag = surfaceDesc.surfaceTag;
1452
+ try {
1453
+ workspaceUris = JSON.parse(row.workspace_uris || '[]');
1454
+ } catch {
1455
+ workspaceUris = row.workspace_uris ? [row.workspace_uris] : [];
1456
+ }
1457
+ }
1458
+ } catch {}
1459
+ }
1460
+ try {
1461
+ const recentRows = dbInstance.prepare('SELECT conversation_id, title, step_count, workspace_uris, last_modified_time FROM conversation_summaries WHERE parent_conversation_id = \'\' ORDER BY last_modified_time DESC LIMIT 12').all();
1462
+ for (const r of recentRows) {
1463
+ let ws = '';
1464
+ try {
1465
+ const parsed = JSON.parse(r.workspace_uris || '[]');
1466
+ ws = canonicalizePath(parsed[0] || '');
1467
+ } catch {}
1468
+ const sid = r.conversation_id;
1469
+ const convDbPath = path.join(surfaceDesc.conversationsDir, `${sid}.db`);
1470
+ const genMeta = readSessionGenMetadataSync(convDbPath, DatabaseSync);
1471
+ if (sessionId && sid === sessionId && genMeta && !sessionGenMetadata) {
1472
+ sessionGenMetadata = genMeta;
1473
+ }
1474
+ upsertDiscoveredSession(sid, {
1475
+ sessionId: sid,
1476
+ title: r.title || sid.slice(0, 8),
1477
+ stepCount: Math.max(Number(r.step_count || 0), Number(genMeta?.turnCount || 0)),
1478
+ workspace: ws ? path.basename(ws) : '',
1479
+ lastModified: r.last_modified_time,
1480
+ surface: surfaceDesc.name,
1481
+ surfaceTag: surfaceDesc.surfaceTag,
1482
+ brainDir: path.join(surfaceDesc.brainDir, sid),
1483
+ ...(genMeta && genMeta.totalContextTokens > 0 ? {
1484
+ liveTokens: genMeta.totalContextTokens,
1485
+ cacheReadTokens: genMeta.cacheReadTokens
1486
+ } : {})
1487
+ });
1488
+ }
1489
+ } catch {}
1490
+ };
1491
+
1492
+ if (hasDbOverride) {
1493
+ processSummaryDb(dbOverride, surfaces[0]);
1494
+ } else {
1495
+ for (const surface of surfaces) {
1496
+ if (DatabaseSync && fs.existsSync(surface.summariesDbPath)) {
1497
+ let db = null;
1498
+ try {
1499
+ db = new DatabaseSync(surface.summariesDbPath, SQLITE_OPEN_READONLY_OPTIONS);
1500
+ processSummaryDb(db, surface);
1501
+ } catch {} finally {
1502
+ try { if (db && typeof db.close === 'function') db.close(); } catch {}
1503
+ }
1504
+ }
1505
+
1506
+ // Also inspect per-conversation SQLite stores: ~/.gemini/<surface>/conversations/*.db
1507
+ if (DatabaseSync && fs.existsSync(surface.conversationsDir)) {
1508
+ try {
1509
+ const dbCandidates = fs.readdirSync(surface.conversationsDir)
1510
+ .filter(f => f.endsWith('.db'))
1511
+ .map(file => {
1512
+ const sid = file.replace(/\.db$/i, '');
1513
+ const fullDbPath = path.join(surface.conversationsDir, file);
1514
+ let mtimeMs = 0;
1515
+ try { mtimeMs = fs.statSync(fullDbPath).mtimeMs; } catch {}
1516
+ return { file, sid, fullDbPath, mtimeMs };
1517
+ })
1518
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
1519
+ const topDbCandidates = dbCandidates.slice(0, 12);
1520
+ if (sessionId && !topDbCandidates.some(c => c.sid === sessionId)) {
1521
+ const targetEntry = dbCandidates.find(c => c.sid === sessionId);
1522
+ if (targetEntry) topDbCandidates.push(targetEntry);
1523
+ }
1524
+ for (const { sid, fullDbPath, mtimeMs } of topDbCandidates) {
1525
+ const genMeta = readSessionGenMetadataSync(fullDbPath, DatabaseSync);
1526
+ if (sessionId && sid === sessionId && genMeta && !sessionGenMetadata) {
1527
+ sessionGenMetadata = genMeta;
1528
+ }
1529
+ if (sessionId && sid === sessionId && workspaceUris.length === 0) {
1530
+ try {
1531
+ const pbtxtPath = path.join(path.dirname(surface.conversationsDir), 'annotations', `${sid}.pbtxt`);
1532
+ const stitched = await stitchAntigravityCliTrajectory(fullDbPath, {
1533
+ sessionId: sid,
1534
+ pbtxtPath,
1535
+ DatabaseSync
1536
+ });
1537
+ if (stitched.workspaceUri) workspaceUris.push(stitched.workspaceUri);
1538
+ if (stitched.title && !sessionTitle) sessionTitle = stitched.title;
1539
+ } catch {}
1540
+ }
1541
+ const mtimeIso = mtimeMs > 0 ? new Date(mtimeMs).toISOString() : '';
1542
+ upsertDiscoveredSession(sid, {
1543
+ sessionId: sid,
1544
+ title: sid.slice(0, 8),
1545
+ stepCount: Number(genMeta?.turnCount || 0),
1546
+ workspace: '',
1547
+ lastModified: mtimeIso,
1548
+ surface: surface.name,
1549
+ surfaceTag: surface.surfaceTag,
1550
+ brainDir: path.join(surface.brainDir, sid),
1551
+ ...(genMeta && genMeta.totalContextTokens > 0 ? {
1552
+ liveTokens: genMeta.totalContextTokens,
1553
+ cacheReadTokens: genMeta.cacheReadTokens
1554
+ } : {})
1555
+ });
1556
+ }
1557
+ } catch {}
1558
+ }
1559
+
1560
+ // Node 20 LTS / JSONL fallback: scan brain/<sid>/.system_generated/logs/transcript*.jsonl when SQLite is absent or brainDirs exist
1561
+ if (fs.existsSync(surface.brainDir)) {
1562
+ try {
1563
+ const brainEntries = fs.readdirSync(surface.brainDir, { withFileTypes: true })
1564
+ .filter(d => d.isDirectory());
1565
+ for (const dirent of brainEntries.slice(0, 20)) {
1566
+ const sid = dirent.name;
1567
+ const sessBrainDir = path.join(surface.brainDir, sid);
1568
+ const logsDir = path.join(sessBrainDir, '.system_generated', 'logs');
1569
+ const fullJsonl = path.join(logsDir, 'transcript_full.jsonl');
1570
+ const compactJsonl = path.join(logsDir, 'transcript.jsonl');
1571
+ const targetJsonl = fs.existsSync(fullJsonl)
1572
+ ? fullJsonl
1573
+ : (fs.existsSync(compactJsonl) ? compactJsonl : null);
1574
+ if (!targetJsonl) continue;
1575
+ let stat = null;
1576
+ let stepCount = 0;
1577
+ try {
1578
+ stat = fs.statSync(targetJsonl);
1579
+ const rawLines = fs.readFileSync(targetJsonl, 'utf8').split(/\r?\n/).filter(Boolean);
1580
+ stepCount = rawLines.length;
1581
+ } catch {}
1582
+ if (stepCount > 0) {
1583
+ const mtimeIso = stat && stat.mtimeMs > 0 ? new Date(stat.mtimeMs).toISOString() : '';
1584
+ upsertDiscoveredSession(sid, {
1585
+ sessionId: sid,
1586
+ title: sid.slice(0, 8),
1587
+ stepCount,
1588
+ workspace: '',
1589
+ lastModified: mtimeIso,
1590
+ surface: surface.name,
1591
+ surfaceTag: surface.surfaceTag,
1592
+ brainDir: sessBrainDir
1593
+ });
1594
+ }
1595
+ }
1596
+ } catch {}
1597
+ }
1598
+ }
1599
+
1600
+ // Include cross-host Claude Code and Cursor sessions ONLY when explicitly requested via options
1601
+ if (includeClaude) {
1602
+ for (const claudeSess of discoverClaudeCodeSessions(homeDir, opts).slice(0, 8)) {
1603
+ try {
1604
+ const parsedClaude = parseClaudeCodeJsonl(fs.readFileSync(claudeSess.filePath, 'utf8'));
1605
+ if (sessionId && claudeSess.sessionId === sessionId) {
1606
+ if (!sessionTitle && parsedClaude.sessionTitle) sessionTitle = parsedClaude.sessionTitle;
1607
+ if (!sessionGenMetadata && parsedClaude.genMetadata) sessionGenMetadata = parsedClaude.genMetadata;
1608
+ if (parsedClaude.workspacePath && workspaceUris.length === 0) workspaceUris.push(parsedClaude.workspacePath);
1609
+ sessionSurface = 'claude-code';
1610
+ sessionSurfaceTag = '[Claude]';
1611
+ }
1612
+ const mtimeIso = claudeSess.mtimeMs > 0 ? new Date(claudeSess.mtimeMs).toISOString() : '';
1613
+ upsertDiscoveredSession(claudeSess.sessionId, {
1614
+ sessionId: claudeSess.sessionId,
1615
+ title: parsedClaude.sessionTitle || claudeSess.sessionId.slice(0, 8),
1616
+ stepCount: parsedClaude.steps.length,
1617
+ workspace: parsedClaude.workspacePath ? path.basename(parsedClaude.workspacePath) : claudeSess.projectSlug,
1618
+ lastModified: mtimeIso,
1619
+ surface: 'claude-code',
1620
+ surfaceTag: '[Claude]',
1621
+ brainDir: claudeSess.filePath,
1622
+ ...(parsedClaude.genMetadata && parsedClaude.genMetadata.totalContextTokens > 0 ? {
1623
+ liveTokens: parsedClaude.genMetadata.totalContextTokens,
1624
+ cacheReadTokens: parsedClaude.genMetadata.cacheReadTokens
1625
+ } : {})
1626
+ });
1627
+ } catch {}
1628
+ }
1629
+ }
1630
+
1631
+ if (includeCursor) {
1632
+ for (const cursorSess of discoverCursorSessions(homeDir, DatabaseSync, opts).slice(0, 8)) {
1633
+ try {
1634
+ const parsedCursor = parseCursorVscdbSync(cursorSess.filePath, DatabaseSync);
1635
+ if (sessionId && cursorSess.sessionId === sessionId) {
1636
+ if (!sessionTitle && (parsedCursor.sessionTitle || cursorSess.title)) sessionTitle = parsedCursor.sessionTitle || cursorSess.title;
1637
+ if (!sessionGenMetadata && parsedCursor.genMetadata) sessionGenMetadata = parsedCursor.genMetadata;
1638
+ if ((parsedCursor.workspacePath || cursorSess.workspaceUri) && workspaceUris.length === 0) {
1639
+ workspaceUris.push(parsedCursor.workspacePath || cursorSess.workspaceUri);
1640
+ }
1641
+ sessionSurface = 'cursor';
1642
+ sessionSurfaceTag = '[Cursor]';
1643
+ }
1644
+ const mtimeIso = cursorSess.mtimeMs > 0 ? new Date(cursorSess.mtimeMs).toISOString() : '';
1645
+ upsertDiscoveredSession(cursorSess.sessionId, {
1646
+ sessionId: cursorSess.sessionId,
1647
+ title: parsedCursor.sessionTitle || cursorSess.title || cursorSess.sessionId.slice(0, 8),
1648
+ stepCount: parsedCursor.steps.length || cursorSess.stepCount || 0,
1649
+ workspace: parsedCursor.workspacePath ? path.basename(parsedCursor.workspacePath) : '',
1650
+ lastModified: mtimeIso,
1651
+ surface: 'cursor',
1652
+ surfaceTag: '[Cursor]',
1653
+ brainDir: cursorSess.filePath,
1654
+ ...(parsedCursor.genMetadata && parsedCursor.genMetadata.totalContextTokens > 0 ? {
1655
+ liveTokens: parsedCursor.genMetadata.totalContextTokens,
1656
+ cacheReadTokens: parsedCursor.genMetadata.cacheReadTokens
1657
+ } : {})
1658
+ });
1659
+ } catch {}
1660
+ }
1661
+ }
1662
+
1663
+ if (isCrossHostHarnessEnabled('codex', opts)) {
1664
+ for (const codexSess of discoverCodexSessions(homeDir, opts).slice(0, 8)) {
1665
+ try {
1666
+ const parsedCodex = parseCodexRolloutJsonl(codexSess.filePath);
1667
+ if (sessionId && parsedCodex.sessionId === sessionId) {
1668
+ if (!sessionTitle && parsedCodex.sessionTitle) sessionTitle = parsedCodex.sessionTitle;
1669
+ if (!sessionGenMetadata && parsedCodex.genMetadata) sessionGenMetadata = parsedCodex.genMetadata;
1670
+ if (parsedCodex.workspacePath && workspaceUris.length === 0) {
1671
+ workspaceUris.push(parsedCodex.workspacePath);
1672
+ }
1673
+ sessionSurface = 'codex';
1674
+ sessionSurfaceTag = '[Codex]';
1675
+ }
1676
+ const mtimeIso = codexSess.mtimeMs > 0 ? new Date(codexSess.mtimeMs).toISOString() : '';
1677
+ upsertDiscoveredSession(parsedCodex.sessionId, {
1678
+ sessionId: parsedCodex.sessionId,
1679
+ title: parsedCodex.sessionTitle || parsedCodex.sessionId.slice(0, 8),
1680
+ stepCount: parsedCodex.steps.length,
1681
+ workspace: parsedCodex.workspacePath ? path.basename(parsedCodex.workspacePath) : '',
1682
+ lastModified: mtimeIso,
1683
+ surface: 'codex',
1684
+ surfaceTag: '[Codex]',
1685
+ brainDir: codexSess.filePath,
1686
+ ...(parsedCodex.genMetadata?.totalContextTokens > 0 ? {
1687
+ liveTokens: parsedCodex.genMetadata.totalContextTokens,
1688
+ cacheReadTokens: parsedCodex.genMetadata.cacheReadTokens
1689
+ } : {})
1690
+ });
1691
+ } catch {}
1692
+ }
1693
+ }
1694
+
1695
+ if (isCrossHostHarnessEnabled('gemini-cli', opts)) {
1696
+ for (const gemSess of discoverGeminiCliSessions(homeDir, opts).slice(0, 8)) {
1697
+ try {
1698
+ const parsedGem = parseGeminiCliChatJson(gemSess.filePath);
1699
+ if (sessionId && parsedGem.sessionId === sessionId) {
1700
+ if (!sessionTitle && parsedGem.sessionTitle) sessionTitle = parsedGem.sessionTitle;
1701
+ if (!sessionGenMetadata && parsedGem.genMetadata) sessionGenMetadata = parsedGem.genMetadata;
1702
+ sessionSurface = 'gemini-cli';
1703
+ sessionSurfaceTag = '[Gemini CLI]';
1704
+ }
1705
+ const mtimeIso = gemSess.mtimeMs > 0 ? new Date(gemSess.mtimeMs).toISOString() : '';
1706
+ upsertDiscoveredSession(parsedGem.sessionId, {
1707
+ sessionId: parsedGem.sessionId,
1708
+ title: parsedGem.sessionTitle || parsedGem.sessionId.slice(0, 8),
1709
+ stepCount: parsedGem.steps.length,
1710
+ workspace: '',
1711
+ lastModified: mtimeIso,
1712
+ surface: 'gemini-cli',
1713
+ surfaceTag: '[Gemini CLI]',
1714
+ brainDir: gemSess.filePath,
1715
+ ...(parsedGem.genMetadata?.totalContextTokens > 0 ? {
1716
+ liveTokens: parsedGem.genMetadata.totalContextTokens,
1717
+ cacheReadTokens: parsedGem.genMetadata.cacheReadTokens
1718
+ } : {})
1719
+ });
1720
+ } catch {}
1721
+ }
1722
+ }
1723
+ }
1724
+
1725
+ recentSessions = Array.from(discoveredMap.values())
1726
+ .filter(s => s.sessionId === sessionId || Number(s.stepCount || 0) > 0)
1727
+ .sort((a, b) => String(b.lastModified || '').localeCompare(String(a.lastModified || '')))
1728
+ .slice(0, 12);
1729
+ } catch {
1730
+ // SQLite lookup failure is non-fatal
1731
+ }
1732
+
1733
+ for (const uri of workspaceUris) {
1734
+ const canon = canonicalizePath(uri);
1735
+ if (canon) canonicalWorkspaceSet.add(canon);
1736
+ }
1737
+
1738
+ // Also check project json if projectId is present
1739
+ if (projectId && projectId !== 'outside-of-project') {
1740
+ const projFile = path.join(homeDir, '.gemini', 'config', 'projects', `${projectId}.json`);
1741
+ if (fs.existsSync(projFile)) {
1742
+ try {
1743
+ const projData = JSON.parse(fs.readFileSync(projFile, 'utf8'));
1744
+ const resources = projData.projectResources?.resources || [];
1745
+ for (const res of resources) {
1746
+ if (res.folderUri) {
1747
+ const canon = canonicalizePath(res.folderUri);
1748
+ if (canon) canonicalWorkspaceSet.add(canon);
1749
+ }
1750
+ }
1751
+ } catch {}
1752
+ }
1753
+ }
1754
+
1755
+ // Reconcile KIs
1756
+ const kiBleedMap = new Map();
1757
+ const knowledgeDir = path.join(homeDir, '.gemini', 'antigravity', 'knowledge');
1758
+ if (fs.existsSync(knowledgeDir)) {
1759
+ try {
1760
+ const items = fs.readdirSync(knowledgeDir);
1761
+ for (const item of items) {
1762
+ const itemDir = path.join(knowledgeDir, item);
1763
+ const metaPath = path.join(itemDir, 'metadata.json');
1764
+ if (fs.existsSync(metaPath)) {
1765
+ try {
1766
+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
1767
+ const refs = meta.references || [];
1768
+ let isBleed = false;
1769
+ let foreignSources = [];
1770
+
1771
+ for (const ref of refs) {
1772
+ if (ref.type === 'file') {
1773
+ const canon = canonicalizePath(ref.value);
1774
+ // Check if reference belongs to any canonical workspace
1775
+ const matches = Array.from(canonicalWorkspaceSet).some(w => canon.startsWith(w));
1776
+ if (!matches && canonicalWorkspaceSet.size > 0) {
1777
+ isBleed = true;
1778
+ foreignSources.push(ref.value);
1779
+ }
1780
+ }
1781
+ }
1782
+
1783
+ kiBleedMap.set(item, {
1784
+ title: meta.title || item,
1785
+ isBleed,
1786
+ foreignSources
1787
+ });
1788
+ } catch {}
1789
+ }
1790
+ }
1791
+ } catch {}
1792
+ }
1793
+
1794
+ return {
1795
+ sessionTitle,
1796
+ sessionSurface,
1797
+ sessionSurfaceTag,
1798
+ recentSessions,
1799
+ workspaceUris,
1800
+ projectId,
1801
+ canonicalWorkspaceSet,
1802
+ primaryWorkspace: Array.from(canonicalWorkspaceSet)[0] || '',
1803
+ kiBleedMap,
1804
+ // Read-only gen_metadata for the requested session (model, last-turn cache counters, bust cause).
1805
+ sessionGenMetadata
1806
+ };
1807
+ }
1808
+
1809
+
1810
+ /**
1811
+ * Recursively discovers OpenAI Codex CLI rollout `.jsonl` files under `~/.codex/sessions`
1812
+ * ONLY when explicitly enabled via `--harness=codex` or `--harness=all`.
1813
+ */
1814
+ export function discoverCodexSessions(homeDir = getHomeDir(), options = {}) {
1815
+ const sessionsRoot = getCodexSessionsDir(homeDir, options);
1816
+ if (!sessionsRoot || !fs.existsSync(sessionsRoot)) return [];
1817
+ const found = [];
1818
+ const walk = (dir, depth = 0) => {
1819
+ if (depth > 4) return;
1820
+ let entries = [];
1821
+ try {
1822
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1823
+ } catch {
1824
+ return;
1825
+ }
1826
+ for (const ent of entries) {
1827
+ const fullPath = path.join(dir, ent.name);
1828
+ if (ent.isDirectory()) {
1829
+ walk(fullPath, depth + 1);
1830
+ } else if (ent.isFile() && ent.name.endsWith('.jsonl')) {
1831
+ try {
1832
+ const st = fs.statSync(fullPath);
1833
+ found.push({ filePath: fullPath, mtimeMs: st.mtimeMs });
1834
+ } catch {}
1835
+ }
1836
+ }
1837
+ };
1838
+ walk(sessionsRoot, 0);
1839
+ return found.sort((a, b) => b.mtimeMs - a.mtimeMs);
1840
+ }
1841
+
1842
+ /**
1843
+ * Read-only parser for OpenAI Codex CLI session rollout `.jsonl` transcripts (`flag: 'r'`).
1844
+ */
1845
+ export function parseCodexRolloutJsonl(filePath) {
1846
+ const fd = fs.openSync(filePath, 'r');
1847
+ let raw = '';
1848
+ try {
1849
+ raw = fs.readFileSync(fd, 'utf8');
1850
+ } finally {
1851
+ fs.closeSync(fd);
1852
+ }
1853
+ const lines = raw.split(/\r?\n/).filter(Boolean);
1854
+ let sessionId = path.basename(filePath, '.jsonl');
1855
+ let sessionTitle = '';
1856
+ let workspacePath = '';
1857
+ let modelId = 'gpt-5-codex';
1858
+ let totalContextTokens = 0;
1859
+ let cacheReadTokens = 0;
1860
+ const steps = [];
1861
+
1862
+ for (let i = 0; i < lines.length; i++) {
1863
+ let entry;
1864
+ try {
1865
+ entry = JSON.parse(lines[i]);
1866
+ } catch {
1867
+ continue;
1868
+ }
1869
+ const payload = entry.payload || entry;
1870
+ if (entry.type === 'session_meta' || payload?.id) {
1871
+ if (payload.id) sessionId = String(payload.id);
1872
+ if (payload.cwd) workspacePath = String(payload.cwd);
1873
+ if (payload.model) modelId = String(payload.model);
1874
+ }
1875
+ if (entry.type === 'event_msg' && payload?.type === 'token_count') {
1876
+ const usage = payload.info?.last_token_usage || payload.info?.total_token_usage || {};
1877
+ const inputTok = Number(usage.input_tokens || 0);
1878
+ const cachedTok = Number(usage.cached_input_tokens || 0);
1879
+ if (inputTok > 0) totalContextTokens = inputTok;
1880
+ if (cachedTok >= 0) cacheReadTokens = cachedTok;
1881
+ }
1882
+ const role = String(payload?.role || entry.role || '').toLowerCase();
1883
+ if (role === 'user' || role === 'assistant') {
1884
+ const contentArr = Array.isArray(payload?.content) ? payload.content : [];
1885
+ const text = typeof payload?.content === 'string'
1886
+ ? payload.content
1887
+ : contentArr.map(c => c?.text || c?.input_text || c?.output_text || '').filter(Boolean).join('\n');
1888
+ if (role === 'user' && !sessionTitle && text) {
1889
+ sessionTitle = text.trim().slice(0, 80);
1890
+ }
1891
+ steps.push({
1892
+ stepIndex: steps.length,
1893
+ type: role === 'user' ? 'USER_INPUT' : 'PLANNER_RESPONSE',
1894
+ source: role === 'user' ? 'USER_EXPLICIT' : 'MODEL',
1895
+ content: text
1896
+ });
1897
+ }
1898
+ }
1899
+
1900
+ return {
1901
+ sessionId,
1902
+ sessionTitle: sessionTitle || `Codex Session (${sessionId.slice(0, 8)})`,
1903
+ workspacePath,
1904
+ surface: 'codex',
1905
+ surfaceTag: '[Codex]',
1906
+ steps,
1907
+ genMetadata: {
1908
+ model: modelId,
1909
+ totalContextTokens,
1910
+ cacheReadTokens
1911
+ }
1912
+ };
1913
+ }
1914
+
1915
+ /**
1916
+ * Discovers Google Gemini CLI chat session `.json` files under `~/.gemini/tmp/<hash>/chats`
1917
+ * ONLY when explicitly enabled via `--harness=gemini-cli` or `--harness=all`.
1918
+ */
1919
+ export function discoverGeminiCliSessions(homeDir = getHomeDir(), options = {}) {
1920
+ const chatDirs = getGeminiCliChatsDirs(homeDir, options);
1921
+ const found = [];
1922
+ for (const dir of chatDirs) {
1923
+ let entries = [];
1924
+ try {
1925
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1926
+ } catch {
1927
+ continue;
1928
+ }
1929
+ for (const ent of entries) {
1930
+ if (ent.isFile() && ent.name.endsWith('.json')) {
1931
+ const fullPath = path.join(dir, ent.name);
1932
+ try {
1933
+ const st = fs.statSync(fullPath);
1934
+ found.push({ filePath: fullPath, mtimeMs: st.mtimeMs });
1935
+ } catch {}
1936
+ }
1937
+ }
1938
+ }
1939
+ return found.sort((a, b) => b.mtimeMs - a.mtimeMs);
1940
+ }
1941
+
1942
+ /**
1943
+ * Read-only parser for Google Gemini CLI chat transcript `.json` files (`flag: 'r'`).
1944
+ */
1945
+ export function parseGeminiCliChatJson(filePath) {
1946
+ const fd = fs.openSync(filePath, 'r');
1947
+ let raw = '';
1948
+ try {
1949
+ raw = fs.readFileSync(fd, 'utf8');
1950
+ } finally {
1951
+ fs.closeSync(fd);
1952
+ }
1953
+ const parsed = JSON.parse(raw);
1954
+ const sessionId = String(parsed.sessionId || path.basename(filePath, '.json'));
1955
+ const messages = Array.isArray(parsed.messages) ? parsed.messages : [];
1956
+ let sessionTitle = '';
1957
+ let modelId = 'gemini-2.5-pro';
1958
+ let totalContextTokens = 0;
1959
+ let cacheReadTokens = 0;
1960
+ const steps = [];
1961
+
1962
+ for (const msg of messages) {
1963
+ const type = String(msg?.type || msg?.role || '').toLowerCase();
1964
+ const content = typeof msg?.content === 'string'
1965
+ ? msg.content
1966
+ : (Array.isArray(msg?.content) ? msg.content.map(p => p?.text || '').join('\n') : '');
1967
+ if (msg?.model) modelId = String(msg.model);
1968
+ if (msg?.tokens && typeof msg.tokens === 'object') {
1969
+ const inTok = Number(msg.tokens.input || msg.tokens.total || 0);
1970
+ const cachedTok = Number(msg.tokens.cached || 0);
1971
+ if (inTok > 0) totalContextTokens = inTok;
1972
+ if (cachedTok >= 0) cacheReadTokens = cachedTok;
1973
+ }
1974
+ if (type === 'user' && !sessionTitle && content) {
1975
+ sessionTitle = content.trim().slice(0, 80);
1976
+ }
1977
+ steps.push({
1978
+ stepIndex: steps.length,
1979
+ type: type === 'user' ? 'USER_INPUT' : 'PLANNER_RESPONSE',
1980
+ source: type === 'user' ? 'USER_EXPLICIT' : 'MODEL',
1981
+ content
1982
+ });
1983
+ }
1984
+
1985
+ return {
1986
+ sessionId,
1987
+ sessionTitle: sessionTitle || `Gemini CLI Session (${sessionId.slice(0, 8)})`,
1988
+ surface: 'gemini-cli',
1989
+ surfaceTag: '[Gemini CLI]',
1990
+ steps,
1991
+ genMetadata: {
1992
+ model: modelId,
1993
+ totalContextTokens,
1994
+ cacheReadTokens
1995
+ }
1996
+ };
1997
+ }