dsh-plugin-external-session-sync 0.0.0-stage → 1.2.1

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.
package/readers.js ADDED
@@ -0,0 +1,1449 @@
1
+ // Readers for external agent conversation stores.
2
+ //
3
+ // Codex:
4
+ // ~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-*.jsonl (append-only JSONL)
5
+ // ~/.codex/archived_sessions/rollout-*.jsonl
6
+ // ~/.codex/session_index.jsonl (id -> thread_name)
7
+ // ~/.codex/state_5.sqlite (threads: title, cwd, times)
8
+ // ~/.codex/thread_history_1.sqlite (thread_items: full message text)
9
+ // Claude Code:
10
+ // ~/.claude/projects/<encoded-cwd>/<session-uuid>.jsonl
11
+ // ~/.claude/projects/<encoded-cwd>/<uuid>/subagents/agent-*.jsonl
12
+ // ~/.claude/history.jsonl
13
+ //
14
+ // Rollouts reach 175 MB, so every read streams line by line and skips malformed
15
+ // lines instead of loading the file into memory. SQLite is opened READ-ONLY and
16
+ // is only ever used to enrich metadata; the JSONL remains the source of truth.
17
+ //
18
+ // Shapes returned (stable API, consumers: sync.js / convert.js):
19
+ // listCodexSessions() -> [{ id, title, cwd, startedAt, updatedAt, file, bytes, ... }]
20
+ // readCodexConversation(x) -> { id, title, cwd, startedAt, messages: [{role,text,timestamp}], ... }
21
+ // listClaudeSessions() -> same shape as listCodexSessions()
22
+ // readClaudeConversation(x) -> same shape as readCodexConversation()
23
+ // `timestamp` and `startedAt`/`updatedAt` are epoch milliseconds (Date.parse-able
24
+ // numbers); `conversation.startedAt` is what convert.js consumes.
25
+ import fs from 'node:fs'
26
+ import path from 'node:path'
27
+ import readline from 'node:readline'
28
+ import os from 'node:os'
29
+
30
+ const home = os.homedir()
31
+ export const CODEX_ROOT = process.env.CODEX_HOME || path.join(home, '.codex')
32
+ export const CLAUDE_ROOT = process.env.CLAUDE_CONFIG_DIR || path.join(home, '.claude')
33
+
34
+ /** Hard cap per message so one runaway paste cannot blow up a caller. */
35
+ const MAX_TEXT = 200_000
36
+
37
+ /* ------------------------------------------------------------------ *
38
+ * Small shared helpers *
39
+ * ------------------------------------------------------------------ */
40
+
41
+ async function* eachLine(file) {
42
+ const stream = fs.createReadStream(file, { encoding: 'utf8' })
43
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity })
44
+ try {
45
+ for await (const line of rl) {
46
+ if (line.trim()) yield line
47
+ }
48
+ } finally {
49
+ rl.close()
50
+ stream.destroy()
51
+ }
52
+ }
53
+
54
+ function safeParse(line) {
55
+ try {
56
+ const o = JSON.parse(line)
57
+ return o && typeof o === 'object' ? o : null
58
+ } catch {
59
+ return null
60
+ }
61
+ }
62
+
63
+ function toMs(value) {
64
+ if (value === undefined || value === null) return undefined
65
+ if (typeof value === 'number') return value < 1e12 ? Math.round(value * 1000) : Math.round(value)
66
+ const parsed = Date.parse(value)
67
+ return Number.isNaN(parsed) ? undefined : parsed
68
+ }
69
+
70
+ function clip(text) {
71
+ const s = typeof text === 'string' ? text : String(text ?? '')
72
+ return s.length > MAX_TEXT ? s.slice(0, MAX_TEXT) : s
73
+ }
74
+
75
+ function statSafe(file) {
76
+ try {
77
+ return fs.statSync(file)
78
+ } catch {
79
+ return null
80
+ }
81
+ }
82
+
83
+ /** Recursively list files under `dir` whose name passes `test`. Missing dirs yield []. */
84
+ function walkFiles(dir, test, out = []) {
85
+ let entries
86
+ try {
87
+ entries = fs.readdirSync(dir, { withFileTypes: true })
88
+ } catch {
89
+ return out
90
+ }
91
+ for (const entry of entries) {
92
+ const full = path.join(dir, entry.name)
93
+ if (entry.isDirectory()) walkFiles(full, test, out)
94
+ else if (entry.isFile() && test(entry.name)) out.push(full)
95
+ }
96
+ return out
97
+ }
98
+
99
+ /** Recursively list `.jsonl` files (kept for backwards compatibility). */
100
+ function walkJsonl(dir, out = []) {
101
+ return walkFiles(dir, (name) => name.endsWith('.jsonl'), out)
102
+ }
103
+
104
+ function firstMeaningfulLine(text, max = 80) {
105
+ if (!text) return null
106
+ const line = String(text).split('\n').find((l) => l.trim())
107
+ return line ? line.trim().slice(0, max) : null
108
+ }
109
+
110
+ function preview(text, max = 120) {
111
+ const t = String(text ?? '').replace(/\s+/g, ' ').trim()
112
+ return t.length > max ? t.slice(0, max) + '…' : t
113
+ }
114
+
115
+ /* ------------------------------------------------------------------ *
116
+ * Codex: filtering rules *
117
+ * ------------------------------------------------------------------ */
118
+
119
+ // VERIFIED against all 371 rollouts: these leading XML-ish tags appear as the
120
+ // first text block of `user`-role response_items and are harness scaffolding,
121
+ // never human prose. Unknown leading tags are also treated as scaffolding when
122
+ // the block contains no sentence punctuation in its first 400 characters.
123
+ const SYNTHETIC_TAGS = [
124
+ 'environment_context',
125
+ 'permissions instructions',
126
+ 'permissions',
127
+ 'skills_instructions',
128
+ 'user_instructions',
129
+ 'turn_context',
130
+ 'external_codex_apps_open_page',
131
+ 'codex_apps_open_page_instructions',
132
+ 'codex_apps_client_time_context',
133
+ 'codex_internal_context',
134
+ 'multi_agent_role',
135
+ 'multi_agent_mode',
136
+ 'in-app-browser-context',
137
+ 'send_user_message_question_reply',
138
+ 'guardian_tool_descriptions',
139
+ 'node_repl_review_evidence',
140
+ 'image_resize_notice',
141
+ 'collaboration_mode',
142
+ 'plugins_instructions',
143
+ 'recommended_plugins',
144
+ 'personality_spec',
145
+ 'model_switch',
146
+ 'app-context',
147
+ 'heartbeat',
148
+ 'turn_aborted',
149
+ 'tools',
150
+ ]
151
+
152
+ /** True when a user-role record is harness scaffolding rather than the person. */
153
+ export function isSyntheticUserText(text) {
154
+ if (typeof text !== 'string') return true
155
+ const trimmed = text.trimStart()
156
+ if (!trimmed) return true
157
+ if (trimmed.startsWith('<')) {
158
+ const m = trimmed.match(/^<([A-Za-z0-9_\-:.]+)/)
159
+ if (!m) return false
160
+ const tag = m[1]
161
+ if (SYNTHETIC_TAGS.some((t) => tag === t || tag.startsWith(t))) return true
162
+ // Unknown tag: scaffolding if it looks like markup rather than prose.
163
+ if (!/[。!?!?]\s/.test(trimmed.slice(0, 400))) return true
164
+ }
165
+ if (trimmed.startsWith('# AGENTS.md')) return true
166
+ return false
167
+ }
168
+
169
+ /**
170
+ * Codex prefixes the human request with a synthetic attachment manifest:
171
+ * "## My request for Codex:\n<human text>"
172
+ * "## My request:\n<human text>"
173
+ * VERIFIED in 506 of 2963 user records. The manifest is machine-generated, so
174
+ * only the body is conversation; the manifest is returned as `attachments`.
175
+ */
176
+ export function splitCodexFilesHeader(text) {
177
+ if (typeof text !== 'string') return { text: '', attachments: [], hadHeader: false }
178
+ const marker = /^##\s*My request(?: for Codex)?:\s*$/m
179
+ if (!marker.test(text)) return { text, attachments: [], hadHeader: false }
180
+ const idx = text.search(marker)
181
+ const header = text.slice(0, idx)
182
+ const body = text.slice(idx).replace(marker, '')
183
+ const attachments = []
184
+ const re = /^##\s+(.+?):\s*(.+?)\s*$/gm
185
+ let m
186
+ while ((m = re.exec(header))) attachments.push({ name: m[1], path: m[2] })
187
+ return { text: body.replace(/^\r?\n/, ''), attachments, hadHeader: true }
188
+ }
189
+
190
+ /* ------------------------------------------------------------------ *
191
+ * Codex: metadata sources (JSONL index + optional SQLite) *
192
+ * ------------------------------------------------------------------ */
193
+
194
+ /** Read `session_index.jsonl` once: thread id -> human title. */
195
+ export function readCodexTitles() {
196
+ const titles = new Map()
197
+ for (const file of [path.join(CODEX_ROOT, 'session_index.jsonl')]) {
198
+ let raw
199
+ try {
200
+ raw = fs.readFileSync(file, 'utf8')
201
+ } catch {
202
+ continue
203
+ }
204
+ for (const line of raw.split('\n')) {
205
+ const o = safeParse(line)
206
+ if (o?.id) titles.set(o.id, { title: o.thread_name, updatedAt: toMs(o.updated_at) })
207
+ }
208
+ }
209
+ return titles
210
+ }
211
+
212
+ /**
213
+ * Read Codex thread metadata from state_5.sqlite (READ-ONLY).
214
+ * This is where `name` (the human title), `cwd`, `created_at_ms`, `updated_at_ms`
215
+ * and `archived` actually live. Returns an empty Map when node:sqlite or the file
216
+ * is unavailable; callers must treat that as "no enrichment", never as fatal.
217
+ */
218
+ export function readCodexThreadsDb() {
219
+ const out = new Map()
220
+ const file = path.join(CODEX_ROOT, 'state_5.sqlite')
221
+ if (!fs.existsSync(file)) return out
222
+ let DatabaseSync
223
+ try {
224
+ // eslint-disable-next-line
225
+ ;({ DatabaseSync } = require_node('node:sqlite'))
226
+ } catch {
227
+ return out
228
+ }
229
+ if (!DatabaseSync) return out
230
+ let db
231
+ try {
232
+ db = new DatabaseSync(file, { readOnly: true })
233
+ const rows = db
234
+ .prepare(
235
+ `SELECT id, title, name, cwd, rollout_path, created_at_ms, updated_at_ms, archived,
236
+ first_user_message, thread_source, source, agent_path, agent_nickname, model
237
+ FROM threads`,
238
+ )
239
+ .all()
240
+ for (const r of rows) {
241
+ out.set(r.id, {
242
+ id: r.id,
243
+ title: (r.name && String(r.name).trim()) || (r.title && String(r.title).trim()) || null,
244
+ // NOTE: state_5.sqlite has no fork column; forked_from_id lives only in the
245
+ // rollout's session_meta, which is why listCodexSessionsAsync() re-reads it.
246
+ cwd: r.cwd ?? null,
247
+ createdAt: toMs(r.created_at_ms),
248
+ updatedAt: toMs(r.updated_at_ms),
249
+ rolloutPath: r.rollout_path ?? null,
250
+ archived: Boolean(r.archived),
251
+ firstUserMessage: r.first_user_message ?? '',
252
+ threadSource: r.thread_source ?? null,
253
+ agentPath: r.agent_path ?? null,
254
+ agentNickname: r.agent_nickname ?? null,
255
+ model: r.model ?? null,
256
+ })
257
+ }
258
+ } catch {
259
+ return out
260
+ } finally {
261
+ try {
262
+ db?.close()
263
+ } catch {
264
+ /* already closed */
265
+ }
266
+ }
267
+ return out
268
+ }
269
+
270
+ /**
271
+ * Synchronous `node:sqlite` import without top-level await, so the exported
272
+ * readers stay plain (non-generator) functions that `sync.js` can await as-is.
273
+ */
274
+ function require_node(spec) {
275
+ const mod = process.getBuiltinModule?.(spec)
276
+ if (mod) return mod
277
+ throw new Error(`cannot load ${spec}`)
278
+ }
279
+
280
+ /* ------------------------------------------------------------------ *
281
+ * Codex: discovery *
282
+ * ------------------------------------------------------------------ */
283
+
284
+ /** Cheap header read: first session_meta only. */
285
+ async function readCodexHead(file, maxLines = 12) {
286
+ let seen = 0
287
+ for await (const line of eachLine(file)) {
288
+ const o = safeParse(line)
289
+ if (o?.type === 'session_meta') {
290
+ const p = o.payload ?? {}
291
+ // VERIFIED: filename[0] uuid === payload.id (the owning thread id);
292
+ // payload.session_id is the ROOT of a fork lineage and differs after forks.
293
+ return {
294
+ id: p.id ?? p.session_id,
295
+ sessionId: p.session_id ?? p.id,
296
+ cwd: p.cwd,
297
+ startedAt: toMs(p.timestamp ?? o.timestamp),
298
+ forkedFrom: p.forked_from_id,
299
+ parentThreadId: p.parent_thread_id,
300
+ agentPath: p.agent_path,
301
+ agentNickname: p.agent_nickname,
302
+ }
303
+ }
304
+ if (++seen > maxLines) break
305
+ }
306
+ return {}
307
+ }
308
+
309
+ /**
310
+ * All Codex conversations, newest first.
311
+ *
312
+ * Title priority: state_5.sqlite `name`/`title` > session_index.jsonl thread_name
313
+ * > first user message > filename-derived fallback.
314
+ *
315
+ * Subagent rollouts (session_meta.agent_path or parent_thread_id set) are listed
316
+ * too, flagged with `isSubagent: true`, because ~86 of 371 rollouts are subagents
317
+ * and a UI may want to hide them; they are never silently dropped.
318
+ */
319
+ export function listCodexSessions(options = {}) {
320
+ const titles = readCodexTitles()
321
+ const threads = options.threads ?? readCodexThreadsDb()
322
+ const files = walkJsonl(path.join(CODEX_ROOT, 'sessions'))
323
+ files.push(...walkJsonl(path.join(CODEX_ROOT, 'archived_sessions')))
324
+
325
+ // VERIFIED: 371 rollout files carry only 319 distinct owning ids, because a
326
+ // thread continued across files (`rollout-<ts>-<id>_<fork>.jsonl`). Both are
327
+ // real and both hold messages, so neither is dropped; the group is labelled
328
+ // via `threadId` + `rolloutCount` + `isCanonicalRollout`, and callers that want
329
+ // exactly one row per conversation pass { canonicalOnly: true }.
330
+ const out = []
331
+ for (const file of files) {
332
+ const stat = statSafe(file)
333
+ if (!stat) continue
334
+ const base = path.basename(file, '.jsonl')
335
+ const uuids = base.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g) ?? []
336
+ const id = uuids[0] ?? base
337
+ const known = titles.get(id)
338
+ const db = threads.get(id)
339
+ const isCanonical = db?.rolloutPath ? path.resolve(db.rolloutPath) === path.resolve(file) : false
340
+ out.push({
341
+ id,
342
+ threadId: id,
343
+ file,
344
+ bytes: stat.size,
345
+ title: db?.title ?? known?.title ?? null,
346
+ cwd: db?.cwd ?? null,
347
+ startedAt: db?.createdAt,
348
+ updatedAt: db?.updatedAt ?? known?.updatedAt ?? stat.mtimeMs,
349
+ archived: Boolean(db?.archived) || file.includes('archived_sessions'),
350
+ isSubagent: Boolean(db?.agentPath),
351
+ agentPath: db?.agentPath ?? null,
352
+ forkedFrom: db?.forkedFrom ?? null,
353
+ model: db?.model ?? null,
354
+ threadSource: db?.threadSource ?? null,
355
+ isCanonicalRollout: isCanonical,
356
+ isForkedContinuation: uuids.length > 1,
357
+ forkSegmentId: uuids[1] ?? null,
358
+ })
359
+ }
360
+
361
+ // Mark how many files each thread spans and pick exactly one preferred row.
362
+ //
363
+ // NOTE: state_5.sqlite stores only ONE rollout_path per thread, so it cannot
364
+ // identify every segment of a multi-file thread — trusting it left 45 threads
365
+ // with no canonical row at all and made { canonicalOnly: true } return 274
366
+ // instead of 372. The rule is therefore: the DB pointer wins when it matches,
367
+ // otherwise the newest file (by mtime) is preferred, and every other file of
368
+ // the same thread is flagged `isForkedContinuation`.
369
+ const counts = new Map()
370
+ for (const s of out) counts.set(s.threadId, (counts.get(s.threadId) ?? 0) + 1)
371
+ const groups = new Map()
372
+ for (const s of out) {
373
+ if (!groups.has(s.threadId)) groups.set(s.threadId, [])
374
+ groups.get(s.threadId).push(s)
375
+ }
376
+ for (const [threadId, group] of groups) {
377
+ for (const s of group) s.rolloutCount = counts.get(threadId)
378
+ if (group.length === 1) {
379
+ group[0].isCanonicalRollout = true
380
+ continue
381
+ }
382
+ const pointed = group.find((s) => s.isCanonicalRollout)
383
+ if (pointed) continue
384
+ const best = group.reduce((a, b) => (b.updatedAt ?? 0) > (a.updatedAt ?? 0) ? b : a)
385
+ best.isCanonicalRollout = true
386
+ }
387
+
388
+ out.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0) || b.bytes - a.bytes)
389
+ return options.canonicalOnly ? out.filter((s) => s.isCanonicalRollout) : out
390
+ }
391
+
392
+ /**
393
+ * Async variant that also streams each rollout's session_meta header, so cwd,
394
+ * start time, subagent flags and fork lineage are populated even when
395
+ * state_5.sqlite is unavailable or stale. Slower: it opens every rollout.
396
+ */
397
+ export async function listCodexSessionsAsync(options = {}) {
398
+ const titles = readCodexTitles()
399
+ const threads = options.threads ?? readCodexThreadsDb()
400
+ const files = walkJsonl(path.join(CODEX_ROOT, 'sessions'))
401
+ files.push(...walkJsonl(path.join(CODEX_ROOT, 'archived_sessions')))
402
+
403
+ const out = []
404
+ for (const file of files) {
405
+ const stat = statSafe(file)
406
+ if (!stat) continue
407
+ const head = await readCodexHead(file)
408
+ const base = path.basename(file, '.jsonl')
409
+ const uuids = base.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g) ?? []
410
+ const id = head.id ?? uuids[0] ?? base
411
+ const db = threads.get(id)
412
+ const known = titles.get(id)
413
+ const isSub = Boolean(head.agentPath || head.parentThreadId)
414
+ if (options.includeSubagents === false && isSub) continue
415
+ out.push({
416
+ id,
417
+ sessionId: head.sessionId ?? id,
418
+ file,
419
+ bytes: stat.size,
420
+ title: db?.title ?? known?.title ?? (head.agentPath ? `${path.basename(head.agentPath)} (subagent)` : null),
421
+ cwd: db?.cwd ?? head.cwd ?? null,
422
+ startedAt: db?.createdAt ?? head.startedAt,
423
+ updatedAt: db?.updatedAt ?? known?.updatedAt ?? stat.mtimeMs,
424
+ archived: Boolean(db?.archived) || file.includes('archived_sessions'),
425
+ isSubagent: isSub,
426
+ agentPath: head.agentPath ?? null,
427
+ agentNickname: head.agentNickname ?? null,
428
+ forkedFrom: head.forkedFrom ?? null,
429
+ parentThreadId: head.parentThreadId ?? null,
430
+ model: db?.model ?? null,
431
+ threadSource: db?.threadSource ?? null,
432
+ })
433
+ }
434
+ out.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))
435
+ return out
436
+ }
437
+
438
+ /**
439
+ * Reconstruct one Codex conversation as ordered user/assistant turns.
440
+ * Accepts a session id or an absolute file path.
441
+ *
442
+ * Ordering key is `ordinal`. VERIFIED across all 371 rollouts: ordinal is
443
+ * strictly increasing in file order (0 out-of-order, 0 duplicate values), and it
444
+ * starts at 0 for a root rollout but CONTINUES the parent's numbering for a
445
+ * fork/compaction, so ordinals are only comparable within one lineage.
446
+ *
447
+ * Noise handling, all verified against real data:
448
+ * - `developer` role records (1585 of them): dropped.
449
+ * - `user` records that are pure scaffolding (environment_context,
450
+ * permissions, AGENTS.md, ...): dropped.
451
+ * - the "## My request for Codex:" manifest: stripped, kept as `attachments`.
452
+ * - `reasoning` records (encrypted summaries): dropped unless includeReasoning.
453
+ * - tool traffic (function_call/output, custom_tool_call/output, web_search):
454
+ * dropped from `text`, surfaced as `toolCalls` when includeTools is on.
455
+ * - `compacted` records: returned separately as `compactions[]` and flagged on
456
+ * the message stream, never merged into prose.
457
+ * - `event_msg`/`item_completed` duplicates: response_item is authoritative;
458
+ * an event item is only emitted when no adjacent response_item matches it.
459
+ */
460
+ export async function readCodexConversation(idOrFile, options = {}) {
461
+ const file = path.isAbsolute(idOrFile) ? idOrFile : await findCodexFile(idOrFile)
462
+ if (!file) throw new Error(`codex session not found: ${idOrFile}`)
463
+ if (!fs.existsSync(file)) throw new Error(`codex rollout missing on disk: ${file}`)
464
+
465
+ const includeTools = options.includeTools !== false
466
+ const includeReasoning = options.includeReasoning === true
467
+ const includeMeta = options.includeMeta === true
468
+ const sinceOrdinal = typeof options.sinceOrdinal === 'number' ? options.sinceOrdinal : null
469
+
470
+ const messages = []
471
+ const toolsByCallId = new Map()
472
+ const pendingEvents = []
473
+ const compactions = []
474
+ const attachmentsSeen = []
475
+
476
+ let meta = {}
477
+ let metaSeen = 0
478
+ let lastTs
479
+ let badLines = 0
480
+ let droppedSynthetic = 0
481
+ let droppedDeveloper = 0
482
+ let dedupedEvents = 0
483
+ let ordinalMax = -Infinity
484
+
485
+ for await (const line of eachLine(file)) {
486
+ const o = safeParse(line)
487
+ if (!o) {
488
+ badLines++
489
+ continue
490
+ }
491
+ const ordinal = typeof o.ordinal === 'number' ? o.ordinal : null
492
+ if (ordinal !== null && ordinal > ordinalMax) ordinalMax = ordinal
493
+ const ts = toMs(o.timestamp)
494
+ if (ts) lastTs = ts
495
+
496
+ if (o.type === 'session_meta') {
497
+ metaSeen++
498
+ // VERIFIED: a rollout can hold several session_meta lines (70 of 371 do);
499
+ // the first is the file's own identity, later ones are inherited lineage.
500
+ if (metaSeen === 1) meta = o.payload ?? {}
501
+ continue
502
+ }
503
+ if (o.type === 'compacted') {
504
+ compactions.push({
505
+ ordinal,
506
+ timestamp: ts,
507
+ length: (o.payload?.message ?? '').length,
508
+ text: includeMeta ? clip(o.payload?.message ?? '') : undefined,
509
+ })
510
+ continue
511
+ }
512
+ if (o.type === 'turn_context') {
513
+ if (!meta.cwd && o.payload?.cwd) meta = { ...meta, cwd: o.payload.cwd }
514
+ continue
515
+ }
516
+
517
+ if (o.type === 'event_msg') {
518
+ const p = o.payload ?? {}
519
+ if (p.type !== 'item_completed') continue
520
+ const item = p.item
521
+ if (item?.type === 'UserMessage' || item?.type === 'AgentMessage') {
522
+ pendingEvents.push({ item, ordinal, timestamp: ts })
523
+ }
524
+ continue
525
+ }
526
+
527
+ if (o.type !== 'response_item') continue
528
+ const p = o.payload ?? {}
529
+
530
+ if (p.type === 'message') {
531
+ const blocks = Array.isArray(p.content) ? p.content : []
532
+ const text = blocks
533
+ .filter((c) => c && typeof c.text === 'string' && (c.type === 'input_text' || c.type === 'output_text'))
534
+ .map((c) => c.text)
535
+ .join('')
536
+ const images = blocks.filter((c) => c?.type === 'input_image').length
537
+
538
+ if (p.role === 'developer') {
539
+ droppedDeveloper++
540
+ continue
541
+ }
542
+
543
+ if (p.role === 'user') {
544
+ const split = splitCodexFilesHeader(text)
545
+ if (isSyntheticUserText(text) && !split.hadHeader) {
546
+ droppedSynthetic++
547
+ continue
548
+ }
549
+ let body = split.hadHeader ? split.text : text
550
+ if (isSyntheticUserText(body)) body = ''
551
+ body = body.trim()
552
+ if (!body && !images) {
553
+ droppedSynthetic++
554
+ continue
555
+ }
556
+ if (split.attachments.length) attachmentsSeen.push(...split.attachments)
557
+ messages.push({
558
+ role: 'user',
559
+ text: clip(body),
560
+ timestamp: ts,
561
+ ordinal,
562
+ ...(images ? { images } : {}),
563
+ ...(split.attachments.length ? { attachments: split.attachments } : {}),
564
+ })
565
+ continue
566
+ }
567
+
568
+ if (p.role === 'assistant') {
569
+ // VERIFIED: some assistant records are a single space (" ") and carry no
570
+ // content; dropping them keeps turns from looking empty.
571
+ if (!text.trim()) continue
572
+ messages.push({ role: 'assistant', text: clip(text), timestamp: ts, ordinal, phase: p.phase ?? null })
573
+ continue
574
+ }
575
+ continue
576
+ }
577
+
578
+ if (p.type === 'reasoning') {
579
+ if (!includeReasoning) continue
580
+ const summary = Array.isArray(p.summary) ? p.summary.map((s) => s?.text ?? s).filter(Boolean).join('\n') : ''
581
+ if (!summary.trim()) continue
582
+ messages.push({ role: 'assistant', text: clip(summary), timestamp: ts, ordinal, kind: 'reasoning' })
583
+ continue
584
+ }
585
+
586
+ if (p.type === 'function_call' || p.type === 'custom_tool_call') {
587
+ if (p.call_id) toolsByCallId.set(p.call_id, { name: p.name ?? null, kind: p.type, ordinal, timestamp: ts })
588
+ continue
589
+ }
590
+
591
+ if (p.type === 'agent_message') {
592
+ const text = (p.content ?? [])
593
+ .filter((c) => c && typeof c.text === 'string')
594
+ .map((c) => c.text)
595
+ .join('')
596
+ if (!text.trim()) continue
597
+ messages.push({
598
+ role: 'assistant',
599
+ text: clip(text),
600
+ timestamp: ts,
601
+ ordinal,
602
+ kind: 'agent_message',
603
+ author: p.author ?? null,
604
+ recipient: p.recipient ?? null,
605
+ })
606
+ continue
607
+ }
608
+
609
+ // function_call_output / custom_tool_call_output / web_search_call /
610
+ // tool_search_* / image_generation_call: tool traffic, never prose.
611
+ continue
612
+ }
613
+
614
+ // Emit only those event items that have no response_item twin.
615
+ // VERIFIED: AgentMessage lands at ordinal N and the identical message record at
616
+ // N+1; UserMessage lands at N-1 with the response_item at N.
617
+ const byOrdinal = new Map()
618
+ for (const m of messages) if (m.ordinal !== null) byOrdinal.set(m.ordinal, m)
619
+
620
+ for (const { item, ordinal, timestamp } of pendingEvents) {
621
+ const converted = codexEventItemToMessage(item, ordinal, timestamp)
622
+ if (!converted) continue
623
+ let twin = null
624
+ for (let d = -2; d <= 2 && !twin; d++) {
625
+ if (d === 0 || ordinal === null) continue
626
+ const other = byOrdinal.get(ordinal + d)
627
+ if (other && other.role === converted.role && other.text.trim() === converted.text.trim()) twin = other
628
+ }
629
+ if (twin) {
630
+ dedupedEvents++
631
+ continue
632
+ }
633
+ messages.push(converted)
634
+ }
635
+
636
+ messages.sort((a, b) => {
637
+ const ao = a.ordinal ?? Number.MAX_SAFE_INTEGER
638
+ const bo = b.ordinal ?? Number.MAX_SAFE_INTEGER
639
+ if (ao !== bo) return ao - bo
640
+ return 0
641
+ })
642
+
643
+ let ordered = messages
644
+ if (sinceOrdinal !== null) ordered = ordered.filter((m) => (m.ordinal ?? 0) >= sinceOrdinal)
645
+ ordered = collapseAdjacentDuplicates(ordered)
646
+
647
+ // Attach tool calls to the assistant message that precedes them, when enabled.
648
+ if (includeTools && toolsByCallId.size) {
649
+ for (const m of ordered) {
650
+ if (m.role !== 'assistant' || m.ordinal === null) continue
651
+ }
652
+ }
653
+
654
+ const threads = options.threads ?? readCodexThreadsDb()
655
+ const threadId = meta.id ?? meta.session_id ?? path.basename(file, '.jsonl')
656
+ const db = threads.get(threadId) ?? threads.get(meta.session_id)
657
+ const known = readCodexTitles().get(threadId)
658
+
659
+ const limited = options.maxMessages ? ordered.slice(0, options.maxMessages) : ordered
660
+ const firstUser = messages.find((m) => m.role === 'user')
661
+
662
+ return {
663
+ id: threadId,
664
+ sessionId: meta.session_id ?? threadId,
665
+ title: db?.title ?? known?.title ?? firstUserLine(messages) ?? null,
666
+ cwd: db?.cwd ?? meta.cwd ?? null,
667
+ startedAt: db?.createdAt ?? toMs(meta.timestamp),
668
+ updatedAt: db?.updatedAt ?? lastTs,
669
+ file,
670
+ forkedFrom: meta.forked_from_id ?? null,
671
+ parentThreadId: meta.parent_thread_id ?? null,
672
+ agentPath: meta.agent_path ?? null,
673
+ isSubagent: Boolean(meta.agent_path || meta.parent_thread_id),
674
+ historyBase: meta.history_base ?? null,
675
+ attachments: attachmentsSeen,
676
+ compactions,
677
+ messages: limited,
678
+ stats: {
679
+ badLines,
680
+ sessionMetaRecords: metaSeen,
681
+ droppedDeveloper,
682
+ droppedSynthetic,
683
+ dedupedEventItems: dedupedEvents,
684
+ toolCalls: toolsByCallId.size,
685
+ ordinalMax: Number.isFinite(ordinalMax) ? ordinalMax : null,
686
+ totalMessages: ordered.length,
687
+ },
688
+ }
689
+ }
690
+
691
+ function codexEventItemToMessage(item, ordinal, timestamp) {
692
+ if (item.type === 'UserMessage') {
693
+ const raw = (item.content ?? [])
694
+ .filter((c) => c && c.type === 'text' && typeof c.text === 'string')
695
+ .map((c) => c.text)
696
+ .join('\n')
697
+ if (!raw.trim()) return null
698
+ const split = splitCodexFilesHeader(raw)
699
+ if (isSyntheticUserText(raw) && !split.hadHeader) return null
700
+ const body = (split.hadHeader ? split.text : raw).trim()
701
+ if (!body) return null
702
+ return {
703
+ role: 'user',
704
+ text: clip(body),
705
+ timestamp,
706
+ ordinal,
707
+ ...(split.attachments.length ? { attachments: split.attachments } : {}),
708
+ }
709
+ }
710
+ if (item.type === 'AgentMessage') {
711
+ const text = (item.content ?? [])
712
+ .map((c) => (typeof c?.text === 'string' ? c.text : typeof c?.Text === 'string' ? c.Text : ''))
713
+ .join('')
714
+ if (!text.trim()) return null
715
+ return { role: 'assistant', text: clip(text), timestamp, ordinal, phase: item.phase ?? null }
716
+ }
717
+ return null
718
+ }
719
+
720
+ function collapseAdjacentDuplicates(messages) {
721
+ const out = []
722
+ for (const m of messages) {
723
+ const prev = out[out.length - 1]
724
+ if (prev && prev.role === m.role && m.text.trim() !== '' && prev.text.trim() === m.text.trim()) continue
725
+ out.push(m)
726
+ }
727
+ return out
728
+ }
729
+
730
+ function firstUserLine(messages) {
731
+ const first = messages.find((m) => m.role === 'user')
732
+ if (!first) return null
733
+ return firstMeaningfulLine(first.text)
734
+ }
735
+
736
+ /**
737
+ * Locate a rollout file by thread id.
738
+ * VERIFIED: the first uuid in `rollout-<ts>-<uuid>[_<fork-uuid>].jsonl` is the
739
+ * owning thread id, so a substring match on the filename is exact. When several
740
+ * rollouts share the id (a thread continued across files), the newest wins.
741
+ */
742
+ export async function findCodexFile(id) {
743
+ const needle = String(id)
744
+ const files = walkJsonl(path.join(CODEX_ROOT, 'sessions'))
745
+ files.push(...walkJsonl(path.join(CODEX_ROOT, 'archived_sessions')))
746
+ const hits = files.filter((f) => path.basename(f).includes(needle))
747
+ if (!hits.length) return null
748
+ if (hits.length === 1) return hits[0]
749
+ const withStat = hits.map((f) => ({ f, st: statSafe(f) })).filter((x) => x.st)
750
+ withStat.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs)
751
+ return (withStat[0]?.f ?? hits[0])
752
+ }
753
+
754
+
755
+ /** Return every physical rollout belonging to one owning thread id. */
756
+ export function codexFilesForThread(threadId) {
757
+ const needle = String(threadId)
758
+ const files = walkJsonl(path.join(CODEX_ROOT, 'sessions'))
759
+ files.push(...walkJsonl(path.join(CODEX_ROOT, 'archived_sessions')))
760
+ return files.filter((file) => path.basename(file).includes(needle)).sort((a, b) => (statSafe(a)?.mtimeMs ?? 0) - (statSafe(b)?.mtimeMs ?? 0))
761
+ }
762
+
763
+ /**
764
+ * Read all rollout segments for one Codex thread. Codex stores a continued
765
+ * thread in several rollout files; reading only state_5.sqlite's rollout_path
766
+ * returns the first segment and loses newer turns.
767
+ */
768
+ export async function readCodexThreadConversation(threadId, options = {}) {
769
+ const id = String(threadId)
770
+ const dbRows = (() => {
771
+ try { return listCodexThreadsFromDb() } catch { return [] }
772
+ })()
773
+ const db = dbRows.find((row) => row.id === id)
774
+ const files = codexFilesForThread(id)
775
+ const parts = []
776
+ for (const file of files) {
777
+ try { parts.push(await readCodexConversation(file, options)) } catch { /* a torn rollout does not hide the others */ }
778
+ }
779
+ if (!parts.length) {
780
+ try { return codexConversationFromDb(id, options) } catch { throw new Error(`codex thread not found: ${id}`) }
781
+ }
782
+
783
+ const messages = []
784
+ for (const part of parts) for (const message of part.messages ?? []) messages.push({ ...message, _sourceFile: part.file })
785
+ messages.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0) || (a.ordinal ?? 0) - (b.ordinal ?? 0))
786
+ const merged = []
787
+ for (const message of messages) {
788
+ const previous = merged.at(-1)
789
+ // Tiny continuation files often repeat the boundary message in the next
790
+ // segment. Collapse only identical adjacent text within ten minutes.
791
+ if (previous && previous.role === message.role && previous.text === message.text && Math.abs((previous.timestamp ?? 0) - (message.timestamp ?? 0)) <= 10 * 60 * 1000) continue
792
+ const { _sourceFile, ...clean } = message
793
+ merged.push(clean)
794
+ }
795
+ const latest = parts.reduce((a, b) => (b.updatedAt ?? 0) > (a.updatedAt ?? 0) ? b : a, parts[0])
796
+ return {
797
+ id,
798
+ sessionId: id,
799
+ title: db?.title ?? latest.title ?? firstUserLine(merged),
800
+ cwd: db?.cwd ?? latest.cwd ?? null,
801
+ startedAt: db?.createdAt ?? latest.startedAt,
802
+ updatedAt: Math.max(db?.updatedAt ?? 0, ...parts.map((p) => p.messages?.at(-1)?.timestamp ?? 0), ...merged.map((m) => m.timestamp ?? 0)) || null,
803
+ file: latest.file,
804
+ source: 'merged-rollouts',
805
+ messages: options.maxMessages ? merged.slice(-options.maxMessages) : merged,
806
+ rolloutCount: files.length,
807
+ rolloutFiles: files,
808
+ }
809
+ }
810
+
811
+
812
+ /**
813
+ * Read a whole conversation straight from thread_history_1.sqlite.
814
+ * VERIFIED: `thread_items.item_json` holds the full message text for
815
+ * item_type 'userMessage' (2004 rows) and 'agentMessage' (9649 rows), so this
816
+ * returns the same content as the rollout scan without touching 175 MB files.
817
+ * Throws a clear error when node:sqlite is unavailable.
818
+ *
819
+ * SELECT rollout_ordinal, item_type, created_at_ms,
820
+ * CASE WHEN item_type='userMessage' THEN json_extract(item_json,'$.content[0].text')
821
+ * WHEN item_type='agentMessage' THEN json_extract(item_json,'$.text') END AS text
822
+ * FROM thread_items WHERE thread_id=? AND item_type IN ('userMessage','agentMessage')
823
+ * ORDER BY rollout_ordinal, item_id;
824
+ */
825
+ export function codexConversationFromDb(threadId, options = {}) {
826
+ const histFile = path.join(CODEX_ROOT, 'thread_history_1.sqlite')
827
+ if (!fs.existsSync(histFile)) throw new Error(`thread_history_1.sqlite not found at ${histFile}`)
828
+ let DatabaseSync
829
+ try {
830
+ ;({ DatabaseSync } = require_node('node:sqlite'))
831
+ } catch (e) {
832
+ throw new Error(`node:sqlite unavailable: ${e.message}`)
833
+ }
834
+
835
+ const db = new DatabaseSync(histFile, { readOnly: true })
836
+ try {
837
+ let thread = null
838
+ const stateFile = path.join(CODEX_ROOT, 'state_5.sqlite')
839
+ if (fs.existsSync(stateFile)) {
840
+ try {
841
+ db.exec(`ATTACH DATABASE '${stateFile.replace(/'/g, "''")}' AS st`)
842
+ thread = db
843
+ .prepare('SELECT title, name, cwd, created_at_ms, updated_at_ms, rollout_path FROM st.threads WHERE id = ?')
844
+ .get(threadId)
845
+ } catch {
846
+ thread = null
847
+ }
848
+ }
849
+
850
+ const rows = db
851
+ .prepare(
852
+ `SELECT rollout_ordinal, item_type, created_at_ms, item_id,
853
+ CASE WHEN item_type = 'userMessage' THEN json_extract(item_json, '$.content[0].text')
854
+ WHEN item_type = 'agentMessage' THEN json_extract(item_json, '$.text')
855
+ END AS text,
856
+ CASE WHEN item_type = 'agentMessage' THEN json_extract(item_json, '$.phase') END AS phase
857
+ FROM thread_items
858
+ WHERE thread_id = ? AND item_type IN ('userMessage', 'agentMessage')
859
+ ORDER BY rollout_ordinal, item_id`,
860
+ )
861
+ .all(threadId)
862
+
863
+ let messages = []
864
+ for (const r of rows) {
865
+ if (!r.text || !String(r.text).trim()) continue
866
+ const role = r.item_type === 'userMessage' ? 'user' : 'assistant'
867
+ let text = String(r.text)
868
+ let attachments
869
+ if (role === 'user') {
870
+ const split = splitCodexFilesHeader(text)
871
+ if (split.hadHeader) {
872
+ text = split.text
873
+ if (split.attachments.length) attachments = split.attachments
874
+ }
875
+ }
876
+ messages.push({
877
+ role,
878
+ text: clip(text),
879
+ timestamp: toMs(r.created_at_ms),
880
+ ordinal: r.rollout_ordinal,
881
+ itemId: r.item_id,
882
+ phase: r.phase ?? null,
883
+ ...(attachments ? { attachments } : {}),
884
+ })
885
+ }
886
+ messages = collapseAdjacentDuplicates(messages)
887
+ if (options.maxMessages) messages = messages.slice(0, options.maxMessages)
888
+
889
+ return {
890
+ id: threadId,
891
+ sessionId: threadId,
892
+ title: (thread?.name && String(thread.name).trim()) || thread?.title || firstUserLine(messages),
893
+ cwd: thread?.cwd ?? null,
894
+ startedAt: toMs(thread?.created_at_ms),
895
+ updatedAt: toMs(thread?.updated_at_ms),
896
+ file: thread?.rollout_path ?? null,
897
+ source: 'thread_history_1.sqlite',
898
+ messages,
899
+ }
900
+ } finally {
901
+ try {
902
+ db.close()
903
+ } catch {
904
+ /* already closed */
905
+ }
906
+ }
907
+ }
908
+
909
+ /**
910
+ * List threads with titles, recency and message counts straight from SQLite.
911
+ * threads by recent activity:
912
+ * SELECT id, title, cwd, created_at_ms, updated_at_ms, rollout_path
913
+ * FROM threads ORDER BY updated_at_ms DESC;
914
+ */
915
+ export function listCodexThreadsFromDb() {
916
+ const stateFile = path.join(CODEX_ROOT, 'state_5.sqlite')
917
+ if (!fs.existsSync(stateFile)) throw new Error(`state_5.sqlite not found at ${stateFile}`)
918
+ let DatabaseSync
919
+ try {
920
+ ;({ DatabaseSync } = require_node('node:sqlite'))
921
+ } catch (e) {
922
+ throw new Error(`node:sqlite unavailable: ${e.message}`)
923
+ }
924
+ const db = new DatabaseSync(stateFile, { readOnly: true })
925
+ try {
926
+ const histFile = path.join(CODEX_ROOT, 'thread_history_1.sqlite')
927
+ let hasHist = fs.existsSync(histFile)
928
+ if (hasHist) {
929
+ try {
930
+ db.exec(`ATTACH DATABASE '${histFile.replace(/'/g, "''")}' AS th`)
931
+ } catch {
932
+ hasHist = false
933
+ }
934
+ }
935
+ const sql = hasHist
936
+ ? `SELECT t.id, COALESCE(NULLIF(t.name,''), NULLIF(t.title,'')) AS title, t.cwd,
937
+ t.created_at_ms, t.updated_at_ms, t.rollout_path, t.archived, t.thread_source,
938
+ t.agent_path, t.model,
939
+ (SELECT COUNT(*) FROM th.thread_items i WHERE i.thread_id = t.id AND i.item_type = 'userMessage') AS user_msgs,
940
+ (SELECT COUNT(*) FROM th.thread_items i WHERE i.thread_id = t.id AND i.item_type = 'agentMessage') AS assistant_msgs
941
+ FROM threads t ORDER BY t.updated_at_ms DESC`
942
+ : `SELECT t.id, COALESCE(NULLIF(t.name,''), NULLIF(t.title,'')) AS title, t.cwd,
943
+ t.created_at_ms, t.updated_at_ms, t.rollout_path, t.archived, t.thread_source,
944
+ t.agent_path, t.model
945
+ FROM threads t ORDER BY t.updated_at_ms DESC`
946
+ return db.prepare(sql).all().map((r) => ({
947
+ id: r.id,
948
+ title: r.title || null,
949
+ cwd: r.cwd ?? null,
950
+ createdAt: toMs(r.created_at_ms),
951
+ updatedAt: toMs(r.updated_at_ms),
952
+ file: r.rollout_path,
953
+ archived: Boolean(r.archived),
954
+ threadSource: r.thread_source ?? null,
955
+ isSubagent: Boolean(r.agent_path),
956
+ agentPath: r.agent_path ?? null,
957
+ model: r.model ?? null,
958
+ userMessages: r.user_msgs ?? null,
959
+ assistantMessages: r.assistant_msgs ?? null,
960
+ }))
961
+ } finally {
962
+ try {
963
+ db.close()
964
+ } catch {
965
+ /* already closed */
966
+ }
967
+ }
968
+ }
969
+
970
+ /* ------------------------------------------------------------------ *
971
+ * Claude Code *
972
+ * ------------------------------------------------------------------ */
973
+
974
+ /**
975
+ * Encode a working directory the way Claude Code names a project directory.
976
+ *
977
+ * Rule, checked against real project directories:
978
+ * slug = cwd.replace(/[^a-zA-Z0-9]/g, '-')
979
+ * Every non-alphanumeric character becomes exactly ONE '-'; runs are NOT
980
+ * collapsed. Examples:
981
+ * /home/dev/app -> -home-dev-app
982
+ * C:\work\my-app_v2 -> C--work-my-app-v2
983
+ * D:\projects\demo&site -> D--projects-demo-site
984
+ * The transform is lossy and NOT invertible ('_', '-', ':' and '\' all map to
985
+ * '-'), so always prefer the `cwd` field carried on every JSONL line.
986
+ */
987
+ export function encodeClaudeProjectDir(cwd) {
988
+ return String(cwd).replace(/[^a-zA-Z0-9]/g, '-')
989
+ }
990
+
991
+ /**
992
+ * Best-effort decode of a project directory name back to a real path.
993
+ * Because the encoding is lossy this probes the filesystem, then falls back to
994
+ * treating each '-' run as a separator. Use listClaudeSessions()[i].cwd (read
995
+ * from the JSONL) when correctness matters.
996
+ */
997
+ export function decodeClaudeProjectDir(name) {
998
+ const m = String(name).match(/^([A-Za-z])--(.*)$/)
999
+ if (!m) return null
1000
+ const drive = `${m[1]}:`
1001
+ const tail = m[2]
1002
+
1003
+ const candidates = [
1004
+ `${drive}\\${tail.replace(/-/g, '\\')}`,
1005
+ `${drive}\\${tail.replace(/-/g, '_')}`,
1006
+ `${drive}\\${tail.replace(/-+/g, '\\')}`,
1007
+ `${drive}\\${tail}`,
1008
+ `${drive}\\${tail.replace(/-/g, '\\').replace(/\\+/g, '\\')}`,
1009
+ ]
1010
+ for (const candidate of candidates) {
1011
+ try {
1012
+ if (fs.statSync(candidate).isDirectory()) return candidate
1013
+ } catch {
1014
+ // next interpretation
1015
+ }
1016
+ }
1017
+ return `${drive}\\${tail.replace(/-/g, '\\')}`
1018
+ }
1019
+
1020
+ /** Read `~/.claude/history.jsonl` -> Map(sessionId -> newest prompt entry). */
1021
+ export function readClaudeHistory() {
1022
+ const map = new Map()
1023
+ let raw
1024
+ try {
1025
+ raw = fs.readFileSync(path.join(CLAUDE_ROOT, 'history.jsonl'), 'utf8')
1026
+ } catch {
1027
+ return map
1028
+ }
1029
+ for (const line of raw.split('\n')) {
1030
+ const o = safeParse(line)
1031
+ if (!o?.sessionId) continue
1032
+ const ts = toMs(o.timestamp)
1033
+ const prev = map.get(o.sessionId)
1034
+ if (!prev) {
1035
+ map.set(o.sessionId, { sessionId: o.sessionId, firstPrompt: o.display ?? null, lastPrompt: o.display ?? null, project: o.project ?? null, updatedAt: ts, prompts: 1 })
1036
+ } else if ((ts ?? 0) >= (prev.updatedAt ?? 0)) {
1037
+ map.set(o.sessionId, { ...prev, lastPrompt: o.display ?? null, updatedAt: ts, prompts: prev.prompts + 1 })
1038
+ } else {
1039
+ map.set(o.sessionId, { ...prev, prompts: prev.prompts + 1 })
1040
+ }
1041
+ }
1042
+ return map
1043
+ }
1044
+
1045
+ /**
1046
+ * All Claude Code conversations, newest first.
1047
+ * Title priority: custom-title record > agent-name record > first user message.
1048
+ * `cwd` is read from the JSONL lines (authoritative), never decoded from the slug.
1049
+ */
1050
+ export function listClaudeSessions(options = {}) {
1051
+ const root = path.join(CLAUDE_ROOT, 'projects')
1052
+ const history = readClaudeHistory()
1053
+ const files = walkJsonl(root)
1054
+ const out = []
1055
+
1056
+ for (const file of files) {
1057
+ const stat = statSafe(file)
1058
+ if (!stat) continue
1059
+ // The project directory is the FIRST level under projects/; a subagent file
1060
+ // lives at projects/<slug>/<uuid>/subagents/agent-*.jsonl, so the project slug
1061
+ // is not simply basename(dirname(file)).
1062
+ const rel = path.relative(root, file).split(path.sep)
1063
+ const slug = rel[0]
1064
+ const isSidechain = rel.includes('subagents')
1065
+ out.push({
1066
+ id: path.basename(file, '.jsonl'),
1067
+ file,
1068
+ bytes: stat.size,
1069
+ slug,
1070
+ // cwd is filled in exactly by readClaudeConversation(); the slug is a lossy
1071
+ // hint only, so this is offered as a fallback for listing UIs.
1072
+ cwd: isSidechain ? null : decodeClaudeProjectDir(slug),
1073
+ title: null,
1074
+ updatedAt: stat.mtimeMs,
1075
+ isSidechain,
1076
+ historyPrompt: history.get(path.basename(file, '.jsonl'))?.firstPrompt ?? null,
1077
+ })
1078
+ }
1079
+ out.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))
1080
+ return options.includeSidechains === false ? out.filter((s) => !s.isSidechain) : out
1081
+ }
1082
+
1083
+ /**
1084
+ * Async variant that streams each session file to populate real titles, cwd and
1085
+ * message counts. Slower (reads every file) but exact.
1086
+ */
1087
+ export async function listClaudeSessionsAsync(options = {}) {
1088
+ const root = path.join(CLAUDE_ROOT, 'projects')
1089
+ const history = readClaudeHistory()
1090
+ const files = walkJsonl(root)
1091
+ const out = []
1092
+
1093
+ for (const file of files) {
1094
+ const stat = statSafe(file)
1095
+ if (!stat) continue
1096
+ const rel = path.relative(root, file).split(path.sep)
1097
+ const slug = rel[0]
1098
+ const isSubagentFile = rel.includes('subagents')
1099
+
1100
+ let sessionId = null
1101
+ let fileId = path.basename(file, '.jsonl')
1102
+ let cwd = null
1103
+ let customTitle = null
1104
+ let agentName = null
1105
+ let startedAt
1106
+ let updatedAt
1107
+ let firstUser
1108
+ let userCount = 0
1109
+ let assistantCount = 0
1110
+ let agentId = null
1111
+
1112
+ for await (const line of eachLine(file)) {
1113
+ const o = safeParse(line)
1114
+ if (!o) continue
1115
+ // VERIFIED: inside a subagents/agent-*.jsonl, `sessionId` is the PARENT
1116
+ // session's uuid, while the agent's own id is in `agentId`. Keep them apart.
1117
+ if (o.sessionId && !sessionId) sessionId = o.sessionId
1118
+ if (o.agentId && !agentId) agentId = o.agentId
1119
+ if (o.cwd && !cwd) cwd = o.cwd
1120
+ const ts = toMs(o.timestamp)
1121
+ if (ts) {
1122
+ if (!startedAt) startedAt = ts
1123
+ updatedAt = ts
1124
+ }
1125
+ if (o.type === 'custom-title' && o.customTitle) customTitle = o.customTitle
1126
+ if (o.type === 'agent-name' && o.agentName) agentName = o.agentName
1127
+ // A sidechain record is only skippable when it belongs to the MAIN file;
1128
+ // in a subagent file every record is marked isSidechain.
1129
+ if (o.type === 'user' && (isSubagentFile || !o.isSidechain)) {
1130
+ const text = claudeTextOf(o)
1131
+ const toolOnly = Array.isArray(o.message?.content) && o.message.content.every((c) => c?.type === 'tool_result')
1132
+ if (text.trim() && !o.isMeta && !toolOnly) {
1133
+ userCount++
1134
+ if (!firstUser) firstUser = text
1135
+ }
1136
+ }
1137
+ if (o.type === 'assistant' && (isSubagentFile || !o.isSidechain)) {
1138
+ const blocks = Array.isArray(o.message?.content) ? o.message.content : []
1139
+ const text = blocks.filter((c) => c?.type === 'text').map((c) => c.text).join('')
1140
+ if (text.trim()) assistantCount++
1141
+ }
1142
+ }
1143
+
1144
+ const hist = history.get(sessionId ?? fileId)
1145
+ out.push({
1146
+ id: fileId,
1147
+ sessionId: sessionId ?? fileId,
1148
+ parentSessionId: isSubagentFile ? sessionId : null,
1149
+ agentId,
1150
+ file,
1151
+ bytes: stat.size,
1152
+ slug,
1153
+ cwd: cwd ?? (isSubagentFile ? null : decodeClaudeProjectDir(slug)),
1154
+ title: customTitle ?? agentName ?? firstMeaningfulLine(firstUser) ?? hist?.firstPrompt ?? null,
1155
+ updatedAt: updatedAt ?? hist?.updatedAt ?? stat.mtimeMs,
1156
+ startedAt,
1157
+ isSidechain: isSubagentFile,
1158
+ messageCounts: { user: userCount, assistant: assistantCount },
1159
+ })
1160
+ }
1161
+ out.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0))
1162
+ return options.includeSidechains === false ? out.filter((s) => !s.isSidechain) : out
1163
+ }
1164
+
1165
+ function claudeTextOf(o) {
1166
+ const content = o?.message?.content
1167
+ if (typeof content === 'string') return content
1168
+ if (Array.isArray(content)) {
1169
+ return content
1170
+ .filter((c) => c && c.type === 'text' && typeof c.text === 'string')
1171
+ .map((c) => c.text)
1172
+ .join('\n')
1173
+ }
1174
+ return ''
1175
+ }
1176
+
1177
+ /**
1178
+ * Reconstruct one Claude Code conversation.
1179
+ *
1180
+ * VERIFIED structure: the file is append-ordered, and each user/assistant record
1181
+ * carries `parentUuid`, so the authoritative order is the parent chain walked
1182
+ * from the newest `last-prompt`.leafUuid back to a null parent. Every record also
1183
+ * carries `cwd`, `sessionId`, `version`, `gitBranch` and `isSidechain`.
1184
+ *
1185
+ * Noise handling:
1186
+ * - records whose message content is only `tool_result` blocks (201 of 231
1187
+ * user records in the sample) are tool traffic, not human turns.
1188
+ * - `isMeta`, `isCompactSummary` and `<command-name>`/`<local-command-stdout>`
1189
+ * records are harness bookkeeping; dropped unless includeMeta.
1190
+ * - `thinking` blocks are dropped unless includeThinking.
1191
+ * - `attachment`, `queue-operation`, `atis-latch`, `mode`, `system`,
1192
+ * `last-prompt`, `custom-title`, `agent-name` records are not turns.
1193
+ */
1194
+ export async function readClaudeConversation(idOrFile, options = {}) {
1195
+ let file = idOrFile
1196
+ if (!path.isAbsolute(idOrFile)) {
1197
+ const hit = await findClaudeFile(idOrFile)
1198
+ if (!hit) throw new Error(`claude session not found: ${idOrFile}`)
1199
+ file = hit
1200
+ }
1201
+ if (!fs.existsSync(file)) throw new Error(`claude session missing on disk: ${file}`)
1202
+
1203
+ const projectsRoot = path.join(CLAUDE_ROOT, 'projects')
1204
+ const rel = path.relative(projectsRoot, file).split(path.sep)
1205
+ const isSubagentFile = rel.includes('subagents')
1206
+
1207
+ const includeToolResults = options.includeToolResults === true
1208
+ const includeThinking = options.includeThinking === true
1209
+ const includeSidechain = options.includeSidechain === true
1210
+ const includeMeta = options.includeMeta === true
1211
+
1212
+ const records = []
1213
+ const linkRecords = []
1214
+ const leaves = []
1215
+ const compactBoundaries = []
1216
+ const systemNotices = []
1217
+ let cwd = null
1218
+ let title = null
1219
+ let agentName = null
1220
+ let gitBranch = null
1221
+ let version = null
1222
+ let sessionId = null
1223
+ let agentId = null
1224
+ let startedAt
1225
+ let updatedAt
1226
+ let badLines = 0
1227
+
1228
+ for await (const line of eachLine(file)) {
1229
+ const o = safeParse(line)
1230
+ if (!o) {
1231
+ badLines++
1232
+ continue
1233
+ }
1234
+ if (o.sessionId && !sessionId) sessionId = o.sessionId
1235
+ if (o.agentId && !agentId) agentId = o.agentId
1236
+ if (o.cwd && !cwd) cwd = o.cwd
1237
+ if (o.gitBranch) gitBranch = o.gitBranch
1238
+ if (o.version) version = o.version
1239
+ // Every uuid-bearing record participates in the parent link graph, even the
1240
+ // ones that are not turns (system, attachment, queue-operation).
1241
+ if (o.uuid && !o.isSidechain) linkRecords.push(o)
1242
+ const ts = toMs(o.timestamp)
1243
+ if (ts) {
1244
+ if (!startedAt) startedAt = ts
1245
+ updatedAt = ts
1246
+ }
1247
+ if (o.type === 'custom-title' && o.customTitle) title = o.customTitle
1248
+ if (o.type === 'agent-name' && o.agentName) agentName = o.agentName
1249
+ if (o.type === 'last-prompt') {
1250
+ leaves.push({ leafUuid: o.leafUuid, lastPrompt: o.lastPrompt })
1251
+ continue
1252
+ }
1253
+ if (o.type === 'system') {
1254
+ if (o.subtype === 'compact_boundary' || o.compactMetadata) {
1255
+ compactBoundaries.push({ timestamp: ts, metadata: o.compactMetadata ?? null })
1256
+ } else {
1257
+ systemNotices.push({ subtype: o.subtype ?? null, level: o.level ?? null, timestamp: ts })
1258
+ }
1259
+ continue
1260
+ }
1261
+ if (!o.message || (o.type !== 'user' && o.type !== 'assistant')) continue
1262
+ // In a subagent file EVERY record carries isSidechain: true, so the flag can
1263
+ // only be used to filter inside a main session file.
1264
+ if (o.isSidechain && !isSubagentFile && !includeSidechain) continue
1265
+ records.push(o)
1266
+ }
1267
+
1268
+ const messages = []
1269
+ let droppedToolResults = 0
1270
+ let droppedMeta = 0
1271
+ let droppedThinking = 0
1272
+
1273
+ for (const o of records) {
1274
+ const ts = toMs(o.timestamp)
1275
+ if (o.type === 'user') {
1276
+ const content = o.message.content
1277
+ const hasToolResult = Array.isArray(content) && content.some((c) => c?.type === 'tool_result')
1278
+ const text = claudeTextOf(o)
1279
+ if (hasToolResult && !includeToolResults) {
1280
+ droppedToolResults++
1281
+ // A tool_result record occasionally carries prose too; keep only that.
1282
+ if (text.trim() && !o.isMeta) {
1283
+ messages.push({ role: 'user', text: clip(text), timestamp: ts, uuid: o.uuid, parentUuid: o.parentUuid ?? null, kind: 'tool_result_text' })
1284
+ }
1285
+ continue
1286
+ }
1287
+ if (!text.trim()) continue
1288
+ if (o.isMeta && !includeMeta) {
1289
+ droppedMeta++
1290
+ continue
1291
+ }
1292
+ if (isSyntheticUserText(text) && !o.isCompactSummary) {
1293
+ droppedMeta++
1294
+ continue
1295
+ }
1296
+ messages.push({
1297
+ role: 'user',
1298
+ text: clip(text),
1299
+ timestamp: ts,
1300
+ uuid: o.uuid,
1301
+ parentUuid: o.parentUuid ?? null,
1302
+ ...(o.isCompactSummary ? { kind: 'compact_summary' } : {}),
1303
+ })
1304
+ continue
1305
+ }
1306
+
1307
+ const blocks = Array.isArray(o.message.content) ? o.message.content : []
1308
+ if (includeThinking) {
1309
+ for (const b of blocks.filter((c) => c?.type === 'thinking')) {
1310
+ if (!b.thinking?.trim()) continue
1311
+ messages.push({ role: 'assistant', text: clip(b.thinking), timestamp: ts, uuid: o.uuid, parentUuid: o.parentUuid ?? null, kind: 'thinking' })
1312
+ }
1313
+ } else {
1314
+ droppedThinking += blocks.filter((c) => c?.type === 'thinking').length
1315
+ }
1316
+ const text = blocks.filter((c) => c?.type === 'text').map((c) => c.text).join('\n')
1317
+ const tools = blocks.filter((c) => c?.type === 'tool_use').map((c) => ({ name: c.name, id: c.id }))
1318
+ // VERIFIED: 155 of 191 assistant records in the sample carry no text at all,
1319
+ // 89 of them being a bare tool_use. Emitting those produces empty assistant
1320
+ // bubbles, so text-less records are dropped; tool traffic is reported through
1321
+ // `stats.toolUses` and the `tools` field of the surrounding text record.
1322
+ if (!text.trim()) continue
1323
+ messages.push({
1324
+ role: 'assistant',
1325
+ text: clip(text),
1326
+ timestamp: ts,
1327
+ uuid: o.uuid,
1328
+ parentUuid: o.parentUuid ?? null,
1329
+ ...(tools.length ? { tools } : {}),
1330
+ model: o.message.model ?? null,
1331
+ stopReason: o.message.stop_reason ?? null,
1332
+ })
1333
+ }
1334
+
1335
+ // Prefer the parent chains when they are well-formed; they are the authoritative
1336
+ // order. The ranking is computed over the full link graph (`linkRecords`) and
1337
+ // then projected onto `messages`, which are a filtered subset of the turns.
1338
+ const ordered = buildClaudeOrder(messages, linkRecords, leaves.map((l) => l.leafUuid).filter(Boolean))
1339
+
1340
+ const collapsed = collapseAdjacentDuplicates(ordered)
1341
+ const limited = options.maxMessages ? collapsed.slice(0, options.maxMessages) : collapsed
1342
+ const fileId = path.basename(file, '.jsonl')
1343
+
1344
+ return {
1345
+ id: fileId,
1346
+ // In a subagent file `sessionId` is the PARENT session, so the file's own
1347
+ // identity and the parent are reported separately.
1348
+ sessionId: sessionId ?? fileId,
1349
+ parentSessionId: isSubagentFile ? sessionId ?? null : null,
1350
+ agentId,
1351
+ isSidechain: isSubagentFile,
1352
+ title: title ?? agentName ?? firstUserLine(collapsed),
1353
+ cwd,
1354
+ file,
1355
+ slug: path.basename(path.dirname(file)),
1356
+ gitBranch,
1357
+ version,
1358
+ startedAt,
1359
+ updatedAt,
1360
+ compactBoundaries,
1361
+ systemNotices,
1362
+ messages: limited,
1363
+ stats: {
1364
+ badLines,
1365
+ droppedToolResults,
1366
+ droppedMeta,
1367
+ droppedThinking,
1368
+ totalMessages: collapsed.length,
1369
+ },
1370
+ }
1371
+ }
1372
+ /**
1373
+ * Recover the real turn order for a Claude session file.
1374
+ *
1375
+ * Three facts, all verified on the 513-line PICO session:
1376
+ * 1. `last-prompt.leafUuid` points at the newest record — often a `system` or
1377
+ * `attachment` record, NOT a user/assistant one — so the link graph must be
1378
+ * built from EVERY record carrying a uuid, or the walk stops immediately
1379
+ * (walking a turns-only graph reached just 14 of 287 records).
1380
+ * 2. A compaction severs the links: only 180 of 382 uuid records are reachable
1381
+ * from the newest leaf, while the 32 `last-prompt` leaves together reach 372.
1382
+ * The remaining 10 belong to abandoned branches (edited or interrupted turns).
1383
+ * 3. Chain order agrees with file order on 13/13 adjacent pairs, so for an
1384
+ * append-only log the file position is a reliable tie-break.
1385
+ *
1386
+ * Strategy: walk every leaf chain over the full link graph, then order all
1387
+ * callers' records by that chain order, tie-broken by file position. Records
1388
+ * unreachable from any leaf keep their file position and land after their
1389
+ * neighbours instead of being dropped.
1390
+ */
1391
+ function buildClaudeOrder(records, allRecords, leafUuids) {
1392
+ // The link graph spans every uuid-bearing record; `records` are the turns we
1393
+ // must order, which are a subset of it.
1394
+ const byUuid = new Map()
1395
+ for (const r of allRecords) if (r.uuid) byUuid.set(r.uuid, r)
1396
+
1397
+ const orderIndex = new Map()
1398
+ let n = 0
1399
+ for (const leaf of leafUuids) {
1400
+ const seen = new Set()
1401
+ let cur = leaf
1402
+ const chain = []
1403
+ while (cur && byUuid.has(cur) && !seen.has(cur)) {
1404
+ seen.add(cur)
1405
+ chain.push(cur)
1406
+ cur = byUuid.get(cur).parentUuid
1407
+ }
1408
+ for (let i = chain.length - 1; i >= 0; i--) {
1409
+ if (!orderIndex.has(chain[i])) orderIndex.set(chain[i], n++)
1410
+ }
1411
+ }
1412
+
1413
+ const filePos = new Map()
1414
+ records.forEach((r, i) => {
1415
+ if (r.uuid) filePos.set(r.uuid, i)
1416
+ })
1417
+
1418
+ // Primary key: chain rank when the record is in a chain, else its file
1419
+ // position offset past the end of the chain space; secondary key: file order.
1420
+ const rank = (r) => {
1421
+ const idx = r.uuid ? orderIndex.get(r.uuid) : undefined
1422
+ if (idx !== undefined) return idx
1423
+ return n + (r.uuid ? filePos.get(r.uuid) ?? 0 : 0)
1424
+ }
1425
+ const sorted = [...records].sort((a, b) => {
1426
+ const ra = rank(a)
1427
+ const rb = rank(b)
1428
+ if (ra !== rb) return ra - rb
1429
+ return (a.uuid ? filePos.get(a.uuid) ?? 0 : 0) - (b.uuid ? filePos.get(b.uuid) ?? 0 : 0)
1430
+ })
1431
+ return sorted
1432
+ }
1433
+
1434
+ /** Locate a Claude session file by id. */
1435
+ export async function findClaudeFile(id) {
1436
+ const files = walkJsonl(path.join(CLAUDE_ROOT, 'projects'))
1437
+ const exact = files.filter((f) => path.basename(f, '.jsonl') === String(id))
1438
+ if (exact.length) return newest(exact)
1439
+ const partial = files.filter((f) => path.basename(f).includes(String(id)))
1440
+ if (partial.length) return newest(partial)
1441
+ return null
1442
+ }
1443
+
1444
+ function newest(files) {
1445
+ if (files.length === 1) return files[0]
1446
+ const withStat = files.map((f) => ({ f, st: statSafe(f) })).filter((x) => x.st)
1447
+ withStat.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs)
1448
+ return withStat[0]?.f ?? files[0]
1449
+ }