ctxtop 0.0.0-stage → 4.0.0

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