@cyfsh/discovery 0.1.0 → 0.2.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.
@@ -3,7 +3,7 @@ import * as fsp from "node:fs/promises";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import { DatabaseSync } from "node:sqlite";
6
- import { asNonEmptyString, finalizeDiscoveredSession, isDirectory, isJsonRecord, isRegularFile, parseTimestampToIso, safeStatDates, summarizeThinking, summarizeToolCall, walkFiles, } from "./common.js";
6
+ import { asNonEmptyString, deriveSessionTitle, extractWorkspaceName, finalizeDiscoveredSession, finalizeSessionSummary, isDirectory, isJsonRecord, isRegularFile, parseTimestampToIso, runWithConcurrency, safeStatDates, summarizeThinking, summarizeToolCall, walkFiles, } from "./common.js";
7
7
  export function resolveOpenCodePaths(customRoot) {
8
8
  if (customRoot && customRoot.trim().length > 0) {
9
9
  const resolved = path.resolve(customRoot);
@@ -67,18 +67,34 @@ function parseJsonColumn(val) {
67
67
  return undefined;
68
68
  }
69
69
  }
70
- export async function withReadOnlySqlite(dbPath, reader) {
70
+ export async function computeSqliteSignature(dbPath) {
71
71
  try {
72
- const db = new DatabaseSync(dbPath, { readOnly: true, timeout: 1500 });
72
+ const mainStat = await fsp.stat(dbPath);
73
+ let walPart = "0:0";
73
74
  try {
74
- return reader(db);
75
+ const walStat = await fsp.stat(`${dbPath}-wal`);
76
+ walPart = `${walStat.mtimeMs}:${walStat.size}`;
75
77
  }
76
- finally {
77
- db.close();
78
+ catch {
79
+ // No WAL sidecar present
78
80
  }
81
+ return `${mainStat.mtimeMs}:${mainStat.size}:${walPart}`;
79
82
  }
80
83
  catch {
81
- // Fallback: copy read-only snapshot to os.tmpdir() if WAL/file lock is held by active daemon
84
+ return "";
85
+ }
86
+ }
87
+ export async function withReadOnlySqlite(dbPath, reader) {
88
+ let db;
89
+ try {
90
+ db = new DatabaseSync(dbPath, { readOnly: true, timeout: 2000 });
91
+ }
92
+ catch (openErr) {
93
+ const stat = await fsp.stat(dbPath).catch(() => null);
94
+ // Never copy multi-hundred-MB databases into tmpdir
95
+ if (!stat || stat.size > 128 * 1024 * 1024) {
96
+ throw openErr;
97
+ }
82
98
  const snapDir = path.join(os.tmpdir(), `cyf-sqlite-snap-${crypto.randomUUID()}`);
83
99
  await fsp.mkdir(snapDir, { recursive: true });
84
100
  const snapDbPath = path.join(snapDir, path.basename(dbPath));
@@ -90,7 +106,7 @@ export async function withReadOnlySqlite(dbPath, reader) {
90
106
  await fsp.copyFile(sidecar, `${snapDbPath}${suffix}`);
91
107
  }
92
108
  }
93
- const snapDb = new DatabaseSync(snapDbPath, { readOnly: true, timeout: 1500 });
109
+ const snapDb = new DatabaseSync(snapDbPath, { readOnly: true, timeout: 2000 });
94
110
  try {
95
111
  return reader(snapDb);
96
112
  }
@@ -102,24 +118,68 @@ export async function withReadOnlySqlite(dbPath, reader) {
102
118
  await fsp.rm(snapDir, { recursive: true, force: true }).catch(() => undefined);
103
119
  }
104
120
  }
121
+ try {
122
+ return reader(db);
123
+ }
124
+ finally {
125
+ db.close();
126
+ }
105
127
  }
106
- function queryTableRows(db, tableName) {
128
+ function getTableColumns(db, tableName) {
107
129
  const tableCheck = db
108
130
  .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
109
131
  .get(tableName);
110
132
  if (!tableCheck) {
111
- return [];
133
+ return new Set();
112
134
  }
113
- return db.prepare(`SELECT * FROM "${tableName}"`).all();
135
+ const cols = db.prepare(`PRAGMA table_info("${tableName}")`).all();
136
+ return new Set(cols
137
+ .map((c) => sqlValToString(c.name))
138
+ .filter((n) => Boolean(n)));
114
139
  }
115
- function extractSessionsFromOpenCodeDb(db, dbPath, fallbackIso) {
116
- const projectRows = queryTableRows(db, "project");
117
- const sessionRows = queryTableRows(db, "session");
118
- const messageRows = queryTableRows(db, "message");
119
- const partRows = queryTableRows(db, "part");
120
- if (sessionRows.length === 0) {
140
+ function selectProjectedColumns(db, tableName, desiredColumns, whereClause = "", params = []) {
141
+ const existing = getTableColumns(db, tableName);
142
+ if (existing.size === 0) {
143
+ return [];
144
+ }
145
+ const selected = desiredColumns.filter((c) => existing.has(c));
146
+ if (selected.length === 0) {
121
147
  return [];
122
148
  }
149
+ const colExpr = selected.map((c) => `"${c}"`).join(", ");
150
+ const sql = `SELECT ${colExpr} FROM "${tableName}"${whereClause ? ` ${whereClause}` : ""}`;
151
+ return db.prepare(sql).all(...params);
152
+ }
153
+ const LIGHTWEIGHT_PROJECT_COLS = [
154
+ "id",
155
+ "worktree",
156
+ "directory",
157
+ "cwd",
158
+ "path",
159
+ "git_branch",
160
+ "branch",
161
+ "data",
162
+ ];
163
+ // Explicitly excludes megabyte-sized `summary_diffs` & `revert` columns!
164
+ const LIGHTWEIGHT_SESSION_COLS = [
165
+ "id",
166
+ "project_id",
167
+ "projectID",
168
+ "directory",
169
+ "cwd",
170
+ "workspace_path",
171
+ "title",
172
+ "git_branch",
173
+ "branch",
174
+ "model",
175
+ "time_created",
176
+ "created_at",
177
+ "time_updated",
178
+ "updated_at",
179
+ "data",
180
+ ];
181
+ function parseProjectsMap(db) {
182
+ const projectRows = selectProjectedColumns(db, "project", LIGHTWEIGHT_PROJECT_COLS);
123
183
  const projectsById = new Map();
124
184
  for (const pRow of projectRows) {
125
185
  const pId = sqlValToString(pRow.id);
@@ -142,369 +202,622 @@ function extractSessionsFromOpenCodeDb(db, dbPath, fallbackIso) {
142
202
  ...(gitBranch ? { gitBranch } : {}),
143
203
  });
144
204
  }
145
- // Group parts by message_id
146
- const partsByMessageId = new Map();
147
- for (const partRow of partRows) {
148
- const pData = parseJsonColumn(partRow.data);
149
- const msgId = sqlValToString(partRow.message_id) ??
150
- sqlValToString(partRow.messageID) ??
151
- asNonEmptyString(pData?.messageID) ??
152
- asNonEmptyString(pData?.message_id);
153
- if (!msgId) {
154
- continue;
155
- }
156
- const bucket = partsByMessageId.get(msgId);
157
- if (bucket) {
158
- bucket.push(partRow);
159
- }
160
- else {
161
- partsByMessageId.set(msgId, [partRow]);
162
- }
205
+ return projectsById;
206
+ }
207
+ /**
208
+ * Fast summary query over `opencode.db` (~5-15ms even on 2.3GB databases).
209
+ * Projects only lightweight columns (skipping `summary_diffs` and avoiding full `part` table scans).
210
+ */
211
+ function extractSessionSummariesFromOpenCodeDb(db, dbPath, fallbackIso) {
212
+ const sessionRows = selectProjectedColumns(db, "session", LIGHTWEIGHT_SESSION_COLS);
213
+ if (sessionRows.length === 0) {
214
+ return [];
163
215
  }
164
- // Group messages by session_id
165
- const messagesBySessionId = new Map();
166
- for (const msgRow of messageRows) {
167
- const mData = parseJsonColumn(msgRow.data);
168
- const sId = sqlValToString(msgRow.session_id) ??
169
- sqlValToString(msgRow.sessionID) ??
170
- asNonEmptyString(mData?.sessionID) ??
171
- asNonEmptyString(mData?.session_id);
172
- if (!sId) {
173
- continue;
216
+ const projectsById = parseProjectsMap(db);
217
+ const msgCols = getTableColumns(db, "message");
218
+ const partCols = getTableColumns(db, "part");
219
+ // Fast SQL message count per session without reading `part` blobs
220
+ const msgCounts = new Map();
221
+ if (msgCols.has("session_id")) {
222
+ const countRows = db
223
+ .prepare('SELECT "session_id" AS sid, COUNT(*) AS cnt FROM "message" GROUP BY "session_id"')
224
+ .all();
225
+ for (const r of countRows) {
226
+ const sid = sqlValToString(r.sid);
227
+ const cnt = Number(r.cnt ?? 0);
228
+ if (sid && cnt > 0) {
229
+ msgCounts.set(sid, cnt);
230
+ }
174
231
  }
175
- const bucket = messagesBySessionId.get(sId);
176
- if (bucket) {
177
- bucket.push(msgRow);
232
+ }
233
+ else if (msgCols.has("sessionID")) {
234
+ const countRows = db
235
+ .prepare('SELECT "sessionID" AS sid, COUNT(*) AS cnt FROM "message" GROUP BY "sessionID"')
236
+ .all();
237
+ for (const r of countRows) {
238
+ const sid = sqlValToString(r.sid);
239
+ const cnt = Number(r.cnt ?? 0);
240
+ if (sid && cnt > 0) {
241
+ msgCounts.set(sid, cnt);
242
+ }
178
243
  }
179
- else {
180
- messagesBySessionId.set(sId, [msgRow]);
244
+ }
245
+ else if (msgCols.has("data")) {
246
+ const allMsgs = db.prepare('SELECT "data" FROM "message"').all();
247
+ for (const m of allMsgs) {
248
+ const d = parseJsonColumn(m.data);
249
+ const sid = asNonEmptyString(d?.sessionID) ?? asNonEmptyString(d?.session_id);
250
+ if (sid) {
251
+ msgCounts.set(sid, (msgCounts.get(sid) ?? 0) + 1);
252
+ }
181
253
  }
182
254
  }
183
- const results = [];
255
+ const summaries = [];
184
256
  for (const sRow of sessionRows) {
185
257
  const rawSessionId = sqlValToString(sRow.id);
186
258
  if (!rawSessionId) {
187
259
  continue;
188
260
  }
261
+ const msgCount = msgCounts.get(rawSessionId) ?? 0;
262
+ if (msgCount === 0) {
263
+ continue;
264
+ }
189
265
  const sData = parseJsonColumn(sRow.data);
190
266
  const projectId = sqlValToString(sRow.project_id) ??
191
267
  sqlValToString(sRow.projectID) ??
192
268
  asNonEmptyString(sData?.projectID) ??
193
269
  asNonEmptyString(sData?.project_id);
194
270
  const projectInfo = projectId ? projectsById.get(projectId) : undefined;
195
- const workspacePath = sqlValToString(sRow.directory) ??
271
+ const rawWorkspace = sqlValToString(sRow.directory) ??
196
272
  sqlValToString(sRow.cwd) ??
197
273
  sqlValToString(sRow.workspace_path) ??
198
274
  asNonEmptyString(sData?.directory) ??
199
275
  asNonEmptyString(sData?.cwd) ??
200
276
  projectInfo?.worktree ??
201
277
  "/unknown-workspace";
202
- const explicitTitle = sqlValToString(sRow.title) ?? asNonEmptyString(sData?.title);
278
+ const workspacePath = rawWorkspace.trim() || "/unknown-workspace";
279
+ const workspaceName = extractWorkspaceName(workspacePath);
280
+ let explicitTitle = sqlValToString(sRow.title) ?? asNonEmptyString(sData?.title);
281
+ // Only touch `part` with LIMIT 3 if this specific session has no explicit title
282
+ if (!explicitTitle && partCols.has("session_id") && partCols.has("data")) {
283
+ const sampleParts = db
284
+ .prepare('SELECT "data" FROM "part" WHERE "session_id" = ? LIMIT 4')
285
+ .all(rawSessionId);
286
+ for (const sp of sampleParts) {
287
+ const pd = parseJsonColumn(sp.data);
288
+ if ((pd?.type === "text" || !pd?.type) && typeof pd?.text === "string" && pd.text.trim()) {
289
+ explicitTitle = pd.text.trim();
290
+ break;
291
+ }
292
+ }
293
+ }
203
294
  const gitBranch = sqlValToString(sRow.git_branch) ??
204
295
  sqlValToString(sRow.branch) ??
205
296
  asNonEmptyString(sData?.gitBranch) ??
206
297
  projectInfo?.gitBranch;
207
- let sessionModel = sqlValToString(sRow.model) ?? asNonEmptyString(sData?.modelID);
298
+ const model = sqlValToString(sRow.model) ?? asNonEmptyString(sData?.modelID);
208
299
  const sTimeObj = isJsonRecord(sData?.time) ? sData.time : undefined;
209
- const sessionCreatedIso = parseTimestampToIso(sRow.time_created ?? sRow.created_at ?? sTimeObj?.created, fallbackIso);
210
- const sessionUpdatedIso = parseTimestampToIso(sRow.time_updated ?? sRow.updated_at ?? sTimeObj?.updated, sessionCreatedIso);
211
- const sMsgRows = messagesBySessionId.get(rawSessionId) ?? [];
212
- sMsgRows.sort((a, b) => {
213
- const aTime = Number(a.time_created ?? a.created_at ?? 0);
214
- const bTime = Number(b.time_created ?? b.created_at ?? 0);
300
+ const createdAt = parseTimestampToIso(sRow.time_created ?? sRow.created_at ?? sTimeObj?.created, fallbackIso);
301
+ const updatedAt = parseTimestampToIso(sRow.time_updated ?? sRow.updated_at ?? sTimeObj?.updated, createdAt);
302
+ const title = deriveSessionTitle(explicitTitle, [], workspaceName, rawSessionId);
303
+ summaries.push({
304
+ id: `opencode:${rawSessionId}`,
305
+ rawSessionId,
306
+ engine: "opencode",
307
+ title,
308
+ workspacePath,
309
+ workspaceName,
310
+ sourcePath: dbPath,
311
+ messageCount: msgCount,
312
+ createdAt,
313
+ updatedAt,
314
+ ...(gitBranch ? { gitBranch } : {}),
315
+ ...(model ? { model } : {}),
316
+ });
317
+ }
318
+ return summaries;
319
+ }
320
+ function parseSingleSessionFromOpenCodeDb(db, dbPath, targetRawSessionId, fallbackIso) {
321
+ const sRows = selectProjectedColumns(db, "session", LIGHTWEIGHT_SESSION_COLS, 'WHERE "id" = ?', [targetRawSessionId]);
322
+ const sRow = sRows[0];
323
+ if (!sRow) {
324
+ return null;
325
+ }
326
+ const sData = parseJsonColumn(sRow.data);
327
+ const projectId = sqlValToString(sRow.project_id) ??
328
+ sqlValToString(sRow.projectID) ??
329
+ asNonEmptyString(sData?.projectID) ??
330
+ asNonEmptyString(sData?.project_id);
331
+ let projectInfo;
332
+ if (projectId) {
333
+ const pRows = selectProjectedColumns(db, "project", LIGHTWEIGHT_PROJECT_COLS, 'WHERE "id" = ?', [projectId]);
334
+ const pRow = pRows[0];
335
+ if (pRow) {
336
+ const pData = parseJsonColumn(pRow.data);
337
+ const worktree = sqlValToString(pRow.worktree) ??
338
+ sqlValToString(pRow.directory) ??
339
+ sqlValToString(pRow.cwd) ??
340
+ sqlValToString(pRow.path) ??
341
+ asNonEmptyString(pData?.worktree) ??
342
+ asNonEmptyString(pData?.directory) ??
343
+ "";
344
+ const gitBranch = sqlValToString(pRow.git_branch) ??
345
+ sqlValToString(pRow.branch) ??
346
+ asNonEmptyString(pData?.branch);
347
+ projectInfo = { worktree, ...(gitBranch ? { gitBranch } : {}) };
348
+ }
349
+ }
350
+ const workspacePath = sqlValToString(sRow.directory) ??
351
+ sqlValToString(sRow.cwd) ??
352
+ sqlValToString(sRow.workspace_path) ??
353
+ asNonEmptyString(sData?.directory) ??
354
+ asNonEmptyString(sData?.cwd) ??
355
+ projectInfo?.worktree ??
356
+ "/unknown-workspace";
357
+ const explicitTitle = sqlValToString(sRow.title) ?? asNonEmptyString(sData?.title);
358
+ const gitBranch = sqlValToString(sRow.git_branch) ??
359
+ sqlValToString(sRow.branch) ??
360
+ asNonEmptyString(sData?.gitBranch) ??
361
+ projectInfo?.gitBranch;
362
+ let sessionModel = sqlValToString(sRow.model) ?? asNonEmptyString(sData?.modelID);
363
+ const sTimeObj = isJsonRecord(sData?.time) ? sData.time : undefined;
364
+ const sessionCreatedIso = parseTimestampToIso(sRow.time_created ?? sRow.created_at ?? sTimeObj?.created, fallbackIso);
365
+ const sessionUpdatedIso = parseTimestampToIso(sRow.time_updated ?? sRow.updated_at ?? sTimeObj?.updated, sessionCreatedIso);
366
+ const msgCols = getTableColumns(db, "message");
367
+ let sMsgRows = [];
368
+ if (msgCols.has("session_id")) {
369
+ sMsgRows = db
370
+ .prepare('SELECT * FROM "message" WHERE "session_id" = ?')
371
+ .all(targetRawSessionId);
372
+ }
373
+ else if (msgCols.has("sessionID")) {
374
+ sMsgRows = db
375
+ .prepare('SELECT * FROM "message" WHERE "sessionID" = ?')
376
+ .all(targetRawSessionId);
377
+ }
378
+ else if (msgCols.size > 0) {
379
+ const allMsgs = db.prepare('SELECT * FROM "message"').all();
380
+ sMsgRows = allMsgs.filter((m) => {
381
+ const md = parseJsonColumn(m.data);
382
+ return (asNonEmptyString(md?.sessionID) ?? asNonEmptyString(md?.session_id)) === targetRawSessionId;
383
+ });
384
+ }
385
+ sMsgRows.sort((a, b) => {
386
+ const aTime = Number(a.time_created ?? a.created_at ?? 0);
387
+ const bTime = Number(b.time_created ?? b.created_at ?? 0);
388
+ if (Number.isFinite(aTime) && Number.isFinite(bTime) && aTime !== bTime) {
389
+ return aTime - bTime;
390
+ }
391
+ return 0;
392
+ });
393
+ const partCols = getTableColumns(db, "part");
394
+ let partRows = [];
395
+ if (partCols.has("session_id")) {
396
+ partRows = db
397
+ .prepare('SELECT * FROM "part" WHERE "session_id" = ?')
398
+ .all(targetRawSessionId);
399
+ }
400
+ else if (partCols.has("message_id") && sMsgRows.length > 0) {
401
+ const msgIds = sMsgRows
402
+ .map((m) => sqlValToString(m.id))
403
+ .filter((id) => Boolean(id));
404
+ if (msgIds.length > 0) {
405
+ const placeholders = msgIds.map(() => "?").join(", ");
406
+ partRows = db
407
+ .prepare(`SELECT * FROM "part" WHERE "message_id" IN (${placeholders})`)
408
+ .all(...msgIds);
409
+ }
410
+ }
411
+ const partsByMessageId = new Map();
412
+ for (const partRow of partRows) {
413
+ const pData = parseJsonColumn(partRow.data);
414
+ const msgId = sqlValToString(partRow.message_id) ??
415
+ sqlValToString(partRow.messageID) ??
416
+ asNonEmptyString(pData?.messageID) ??
417
+ asNonEmptyString(pData?.message_id);
418
+ if (!msgId) {
419
+ continue;
420
+ }
421
+ const bucket = partsByMessageId.get(msgId);
422
+ if (bucket) {
423
+ bucket.push(partRow);
424
+ }
425
+ else {
426
+ partsByMessageId.set(msgId, [partRow]);
427
+ }
428
+ }
429
+ const parsedMessages = [];
430
+ for (let mIdx = 0; mIdx < sMsgRows.length; mIdx += 1) {
431
+ const mRow = sMsgRows[mIdx];
432
+ if (!mRow) {
433
+ continue;
434
+ }
435
+ const msgId = sqlValToString(mRow.id) ?? `${targetRawSessionId}-msg-${mIdx + 1}`;
436
+ const mData = parseJsonColumn(mRow.data);
437
+ const roleStr = sqlValToString(mRow.role) ?? asNonEmptyString(mData?.role);
438
+ if (roleStr !== "user" && roleStr !== "assistant" && roleStr !== "system") {
439
+ continue;
440
+ }
441
+ const rowModel = sqlValToString(mRow.model) ??
442
+ asNonEmptyString(mData?.modelID) ??
443
+ (isJsonRecord(mData?.model)
444
+ ? asNonEmptyString(mData.model.modelID)
445
+ : undefined);
446
+ if (rowModel) {
447
+ sessionModel = rowModel;
448
+ }
449
+ const mTimeObj = isJsonRecord(mData?.time) ? mData.time : undefined;
450
+ const msgTimestamp = parseTimestampToIso(mRow.time_created ?? mRow.created_at ?? mTimeObj?.created, sessionUpdatedIso);
451
+ const textChunks = [];
452
+ const thinkingChunks = [];
453
+ const toolCalls = [];
454
+ const directMsgContent = sqlValToString(mRow.content) ?? asNonEmptyString(mData?.content);
455
+ if (directMsgContent) {
456
+ textChunks.push(directMsgContent);
457
+ }
458
+ const directThinking = sqlValToString(mRow.thinking) ?? asNonEmptyString(mData?.thinking);
459
+ if (directThinking) {
460
+ thinkingChunks.push(directThinking);
461
+ }
462
+ const msgParts = partsByMessageId.get(msgId) ?? [];
463
+ msgParts.sort((a, b) => {
464
+ const aTime = Number(a.time_created ?? a.created_at ?? a.sort_order ?? 0);
465
+ const bTime = Number(b.time_created ?? b.created_at ?? b.sort_order ?? 0);
215
466
  if (Number.isFinite(aTime) && Number.isFinite(bTime) && aTime !== bTime) {
216
467
  return aTime - bTime;
217
468
  }
218
469
  return 0;
219
470
  });
220
- const parsedMessages = [];
221
- for (let mIdx = 0; mIdx < sMsgRows.length; mIdx += 1) {
222
- const mRow = sMsgRows[mIdx];
223
- if (!mRow) {
224
- continue;
225
- }
226
- const msgId = sqlValToString(mRow.id) ?? `${rawSessionId}-msg-${mIdx + 1}`;
227
- const mData = parseJsonColumn(mRow.data);
228
- const roleStr = sqlValToString(mRow.role) ?? asNonEmptyString(mData?.role);
229
- if (roleStr !== "user" && roleStr !== "assistant" && roleStr !== "system") {
230
- continue;
231
- }
232
- const rowModel = sqlValToString(mRow.model) ??
233
- asNonEmptyString(mData?.modelID) ??
234
- (isJsonRecord(mData?.model)
235
- ? asNonEmptyString(mData.model.modelID)
236
- : undefined);
237
- if (rowModel) {
238
- sessionModel = rowModel;
239
- }
240
- const mTimeObj = isJsonRecord(mData?.time) ? mData.time : undefined;
241
- const msgTimestamp = parseTimestampToIso(mRow.time_created ?? mRow.created_at ?? mTimeObj?.created, sessionUpdatedIso);
242
- const textChunks = [];
243
- const thinkingChunks = [];
244
- const toolCalls = [];
245
- const directMsgContent = sqlValToString(mRow.content) ?? asNonEmptyString(mData?.content);
246
- if (directMsgContent) {
247
- textChunks.push(directMsgContent);
248
- }
249
- const directThinking = sqlValToString(mRow.thinking) ?? asNonEmptyString(mData?.thinking);
250
- if (directThinking) {
251
- thinkingChunks.push(directThinking);
252
- }
253
- const msgParts = partsByMessageId.get(msgId) ?? [];
254
- msgParts.sort((a, b) => {
255
- const aTime = Number(a.time_created ?? a.created_at ?? a.sort_order ?? 0);
256
- const bTime = Number(b.time_created ?? b.created_at ?? b.sort_order ?? 0);
257
- if (Number.isFinite(aTime) && Number.isFinite(bTime) && aTime !== bTime) {
258
- return aTime - bTime;
259
- }
260
- return 0;
261
- });
262
- for (const partRow of msgParts) {
263
- const pData = parseJsonColumn(partRow.data);
264
- const partType = sqlValToString(partRow.type) ?? asNonEmptyString(pData?.type) ?? "text";
265
- if (partType === "text") {
266
- const txt = sqlValToString(partRow.text) ??
267
- sqlValToString(partRow.content) ??
268
- asNonEmptyString(pData?.text) ??
269
- asNonEmptyString(pData?.content);
270
- if (txt && !textChunks.includes(txt)) {
271
- textChunks.push(txt);
272
- }
273
- }
274
- else if (partType === "reasoning" || partType === "thinking") {
275
- const thought = sqlValToString(partRow.text) ??
276
- sqlValToString(partRow.content) ??
277
- asNonEmptyString(pData?.text) ??
278
- asNonEmptyString(pData?.thinking);
279
- if (thought) {
280
- thinkingChunks.push(thought);
281
- }
282
- }
283
- else if (partType === "tool" ||
284
- partType === "tool_use" ||
285
- partType === "tool-invocation" ||
286
- partType === "tool_call") {
287
- const toolName = sqlValToString(partRow.tool_name) ??
288
- sqlValToString(partRow.name) ??
289
- asNonEmptyString(pData?.tool) ??
290
- asNonEmptyString(pData?.name) ??
291
- "tool";
292
- const stateRec = isJsonRecord(pData?.state) ? pData.state : undefined;
293
- const toolInput = partRow.tool_input ??
294
- partRow.input ??
295
- stateRec?.input ??
296
- pData?.input ??
297
- pData?.args;
298
- toolCalls.push(summarizeToolCall(toolName, toolInput));
471
+ for (const partRow of msgParts) {
472
+ const pData = parseJsonColumn(partRow.data);
473
+ const partType = sqlValToString(partRow.type) ?? asNonEmptyString(pData?.type) ?? "text";
474
+ if (partType === "text") {
475
+ const txt = sqlValToString(partRow.text) ??
476
+ sqlValToString(partRow.content) ??
477
+ asNonEmptyString(pData?.text) ??
478
+ asNonEmptyString(pData?.content);
479
+ if (txt && !textChunks.includes(txt)) {
480
+ textChunks.push(txt);
299
481
  }
300
482
  }
301
- let finalContent = textChunks.join("\n").trim();
302
- if (!finalContent && toolCalls.length > 0 && roleStr === "assistant") {
303
- finalContent = `[调用工具: ${toolCalls.map((t) => t.name).join(", ")}]`;
483
+ else if (partType === "reasoning" || partType === "thinking") {
484
+ const thought = sqlValToString(partRow.text) ??
485
+ sqlValToString(partRow.content) ??
486
+ asNonEmptyString(pData?.text) ??
487
+ asNonEmptyString(pData?.thinking);
488
+ if (thought) {
489
+ thinkingChunks.push(thought);
490
+ }
304
491
  }
305
- if (!finalContent) {
306
- continue;
492
+ else if (partType === "tool" ||
493
+ partType === "tool_use" ||
494
+ partType === "tool-invocation" ||
495
+ partType === "tool_call") {
496
+ const toolName = sqlValToString(partRow.tool_name) ??
497
+ sqlValToString(partRow.name) ??
498
+ asNonEmptyString(pData?.tool) ??
499
+ asNonEmptyString(pData?.name) ??
500
+ "tool";
501
+ const stateRec = isJsonRecord(pData?.state) ? pData.state : undefined;
502
+ const toolInput = partRow.tool_input ??
503
+ partRow.input ??
504
+ stateRec?.input ??
505
+ pData?.input ??
506
+ pData?.args;
507
+ toolCalls.push(summarizeToolCall(toolName, toolInput));
307
508
  }
308
- const thinkingSummary = summarizeThinking(thinkingChunks.join("\n"));
309
- parsedMessages.push({
310
- id: msgId,
311
- role: roleStr,
312
- content: finalContent,
313
- timestamp: msgTimestamp,
314
- ...(thinkingSummary ? { thinkingSummary } : {}),
315
- ...(toolCalls.length > 0 ? { toolCalls } : {}),
316
- });
317
509
  }
318
- const finalized = finalizeDiscoveredSession({
319
- engine: "opencode",
320
- rawSessionId,
321
- explicitTitle,
322
- workspacePath,
323
- sourcePath: dbPath,
324
- messages: parsedMessages,
325
- fallbackCreatedAt: sessionCreatedIso,
326
- fallbackUpdatedAt: sessionUpdatedIso,
327
- gitBranch,
328
- model: sessionModel,
329
- });
330
- if (finalized) {
331
- results.push(finalized);
510
+ let finalContent = textChunks.join("\n").trim();
511
+ if (!finalContent && toolCalls.length > 0 && roleStr === "assistant") {
512
+ finalContent = `[调用工具: ${toolCalls.map((t) => t.name).join(", ")}]`;
513
+ }
514
+ if (!finalContent) {
515
+ continue;
332
516
  }
517
+ const thinkingSummary = summarizeThinking(thinkingChunks.join("\n"));
518
+ parsedMessages.push({
519
+ id: msgId,
520
+ role: roleStr,
521
+ content: finalContent,
522
+ timestamp: msgTimestamp,
523
+ ...(thinkingSummary ? { thinkingSummary } : {}),
524
+ ...(toolCalls.length > 0 ? { toolCalls } : {}),
525
+ });
333
526
  }
334
- return results;
527
+ return finalizeDiscoveredSession({
528
+ engine: "opencode",
529
+ rawSessionId: targetRawSessionId,
530
+ explicitTitle,
531
+ workspacePath,
532
+ sourcePath: dbPath,
533
+ messages: parsedMessages,
534
+ fallbackCreatedAt: sessionCreatedIso,
535
+ fallbackUpdatedAt: sessionUpdatedIso,
536
+ gitBranch,
537
+ model: sessionModel,
538
+ });
335
539
  }
336
- async function scanLegacyOpenCodeJsonDir(sessionDir) {
540
+ async function parseLegacyOpenCodeJsonFile(sFile, sessionDir, includeDetails) {
337
541
  const storageRoot = path.dirname(sessionDir);
338
542
  const messageRoot = path.join(storageRoot, "message");
339
543
  const partRoot = path.join(storageRoot, "part");
340
- const sessionFiles = await walkFiles(sessionDir, (_full, name) => name.endsWith(".json"), 4);
341
- const discovered = [];
342
- for (const sFile of sessionFiles) {
343
- try {
344
- const raw = await fsp.readFile(sFile, "utf8");
345
- const parsed = JSON.parse(raw);
346
- if (!isJsonRecord(parsed)) {
544
+ const raw = await fsp.readFile(sFile, "utf8");
545
+ const parsed = JSON.parse(raw);
546
+ if (!isJsonRecord(parsed)) {
547
+ return { summary: null, detail: null };
548
+ }
549
+ const rawSessionId = asNonEmptyString(parsed.id) ?? path.basename(sFile, ".json");
550
+ const workspacePath = asNonEmptyString(parsed.directory) ??
551
+ asNonEmptyString(parsed.cwd) ??
552
+ asNonEmptyString(parsed.worktree) ??
553
+ "/unknown-workspace";
554
+ const explicitTitle = asNonEmptyString(parsed.title);
555
+ const gitBranch = asNonEmptyString(parsed.gitBranch) ?? asNonEmptyString(parsed.branch);
556
+ let model = asNonEmptyString(parsed.model) ?? asNonEmptyString(parsed.modelID);
557
+ const { createdAt, updatedAt } = await safeStatDates(sFile);
558
+ const messages = [];
559
+ if (Array.isArray(parsed.messages)) {
560
+ for (let idx = 0; idx < parsed.messages.length; idx += 1) {
561
+ const item = parsed.messages[idx];
562
+ if (!isJsonRecord(item)) {
347
563
  continue;
348
564
  }
349
- const rawSessionId = asNonEmptyString(parsed.id) ?? path.basename(sFile, ".json");
350
- const workspacePath = asNonEmptyString(parsed.directory) ??
351
- asNonEmptyString(parsed.cwd) ??
352
- asNonEmptyString(parsed.worktree) ??
353
- "/unknown-workspace";
354
- const explicitTitle = asNonEmptyString(parsed.title);
355
- const gitBranch = asNonEmptyString(parsed.gitBranch) ?? asNonEmptyString(parsed.branch);
356
- let model = asNonEmptyString(parsed.model) ?? asNonEmptyString(parsed.modelID);
357
- const { createdAt, updatedAt } = await safeStatDates(sFile);
358
- const messages = [];
359
- // Case 1: Inline messages array in session JSON
360
- if (Array.isArray(parsed.messages)) {
361
- for (let idx = 0; idx < parsed.messages.length; idx += 1) {
362
- const item = parsed.messages[idx];
363
- if (!isJsonRecord(item)) {
364
- continue;
365
- }
366
- const role = asNonEmptyString(item.role);
367
- const content = asNonEmptyString(item.content) ?? asNonEmptyString(item.text);
368
- if ((role === "user" || role === "assistant") && content) {
369
- const ts = parseTimestampToIso(item.timestamp ?? item.createdAt, updatedAt);
370
- const thinkingSummary = summarizeThinking(asNonEmptyString(item.thinking) ?? "");
371
- messages.push({
372
- id: asNonEmptyString(item.id) ?? `${rawSessionId}-legacy-${idx + 1}`,
373
- role,
374
- content,
375
- timestamp: ts,
376
- ...(thinkingSummary ? { thinkingSummary } : {}),
377
- });
378
- }
379
- }
380
- }
381
- // Case 2: Split storage/message/<sessionId>/*.json + storage/part/<messageId>/*.json
382
- const perSessionMsgDir = path.join(messageRoot, rawSessionId);
383
- if (messages.length === 0 && (await isDirectory(perSessionMsgDir))) {
384
- const msgFiles = await walkFiles(perSessionMsgDir, (_f, name) => name.endsWith(".json"), 2);
385
- msgFiles.sort();
386
- for (let idx = 0; idx < msgFiles.length; idx += 1) {
387
- const mf = msgFiles[idx];
388
- if (!mf) {
389
- continue;
390
- }
391
- const mRaw = await fsp.readFile(mf, "utf8");
392
- const mObj = JSON.parse(mRaw);
393
- if (!isJsonRecord(mObj)) {
394
- continue;
395
- }
396
- const msgId = asNonEmptyString(mObj.id) ?? path.basename(mf, ".json");
397
- const role = asNonEmptyString(mObj.role);
398
- if (role !== "user" && role !== "assistant") {
399
- continue;
400
- }
401
- const mModel = asNonEmptyString(mObj.modelID) ?? asNonEmptyString(mObj.model);
402
- if (mModel) {
403
- model = mModel;
404
- }
405
- const timeObj = isJsonRecord(mObj.time) ? mObj.time : undefined;
406
- const ts = parseTimestampToIso(timeObj?.created ?? mObj.createdAt, updatedAt);
407
- const textChunks = [];
408
- const directContent = asNonEmptyString(mObj.content);
409
- if (directContent) {
410
- textChunks.push(directContent);
411
- }
412
- const perMsgPartDir = path.join(partRoot, msgId);
413
- if (await isDirectory(perMsgPartDir)) {
414
- const partFiles = await walkFiles(perMsgPartDir, (_f, name) => name.endsWith(".json"), 2);
415
- partFiles.sort();
416
- for (const pf of partFiles) {
417
- const pRaw = await fsp.readFile(pf, "utf8");
418
- const pObj = JSON.parse(pRaw);
419
- if (isJsonRecord(pObj)) {
420
- const txt = asNonEmptyString(pObj.text) ?? asNonEmptyString(pObj.content);
421
- if (txt) {
422
- textChunks.push(txt);
423
- }
424
- }
425
- }
426
- }
427
- const joined = textChunks.join("\n").trim();
428
- if (joined) {
429
- messages.push({
430
- id: msgId,
431
- role,
432
- content: joined,
433
- timestamp: ts,
434
- });
435
- }
436
- }
565
+ const role = asNonEmptyString(item.role);
566
+ const content = asNonEmptyString(item.content) ?? asNonEmptyString(item.text);
567
+ if ((role === "user" || role === "assistant") && content) {
568
+ const ts = parseTimestampToIso(item.timestamp ?? item.createdAt, updatedAt);
569
+ const thinkingSummary = includeDetails
570
+ ? summarizeThinking(asNonEmptyString(item.thinking) ?? "")
571
+ : undefined;
572
+ messages.push({
573
+ id: asNonEmptyString(item.id) ?? `${rawSessionId}-legacy-${idx + 1}`,
574
+ role,
575
+ content,
576
+ timestamp: ts,
577
+ ...(thinkingSummary ? { thinkingSummary } : {}),
578
+ });
437
579
  }
438
- const finalized = finalizeDiscoveredSession({
580
+ }
581
+ }
582
+ const perSessionMsgDir = path.join(messageRoot, rawSessionId);
583
+ if (messages.length === 0 && (await isDirectory(perSessionMsgDir))) {
584
+ const msgFiles = await walkFiles(perSessionMsgDir, (_f, name) => name.endsWith(".json"), 2);
585
+ if (!includeDetails && explicitTitle && msgFiles.length > 0) {
586
+ const summary = finalizeSessionSummary({
439
587
  engine: "opencode",
440
588
  rawSessionId,
441
589
  explicitTitle,
442
590
  workspacePath,
443
591
  sourcePath: sFile,
444
- messages,
592
+ messages: [],
593
+ estimatedMessageCount: msgFiles.length,
445
594
  fallbackCreatedAt: createdAt,
446
595
  fallbackUpdatedAt: updatedAt,
447
596
  gitBranch,
448
597
  model,
449
598
  });
450
- if (finalized) {
451
- discovered.push(finalized);
599
+ return { summary, detail: null };
600
+ }
601
+ msgFiles.sort();
602
+ for (let idx = 0; idx < msgFiles.length; idx += 1) {
603
+ const mf = msgFiles[idx];
604
+ if (!mf) {
605
+ continue;
606
+ }
607
+ const mRaw = await fsp.readFile(mf, "utf8");
608
+ const mObj = JSON.parse(mRaw);
609
+ if (!isJsonRecord(mObj)) {
610
+ continue;
611
+ }
612
+ const msgId = asNonEmptyString(mObj.id) ?? path.basename(mf, ".json");
613
+ const role = asNonEmptyString(mObj.role);
614
+ if (role !== "user" && role !== "assistant") {
615
+ continue;
616
+ }
617
+ const mModel = asNonEmptyString(mObj.modelID) ?? asNonEmptyString(mObj.model);
618
+ if (mModel) {
619
+ model = mModel;
620
+ }
621
+ const timeObj = isJsonRecord(mObj.time) ? mObj.time : undefined;
622
+ const ts = parseTimestampToIso(timeObj?.created ?? mObj.createdAt, updatedAt);
623
+ const textChunks = [];
624
+ const directContent = asNonEmptyString(mObj.content);
625
+ if (directContent) {
626
+ textChunks.push(directContent);
627
+ }
628
+ const perMsgPartDir = path.join(partRoot, msgId);
629
+ if (await isDirectory(perMsgPartDir)) {
630
+ const partFiles = await walkFiles(perMsgPartDir, (_f, name) => name.endsWith(".json"), 2);
631
+ partFiles.sort();
632
+ for (const pf of partFiles) {
633
+ const pRaw = await fsp.readFile(pf, "utf8");
634
+ const pObj = JSON.parse(pRaw);
635
+ if (isJsonRecord(pObj)) {
636
+ const txt = asNonEmptyString(pObj.text) ?? asNonEmptyString(pObj.content);
637
+ if (txt) {
638
+ textChunks.push(txt);
639
+ }
640
+ }
641
+ }
642
+ }
643
+ const joined = textChunks.join("\n").trim();
644
+ if (joined) {
645
+ messages.push({
646
+ id: msgId,
647
+ role,
648
+ content: joined,
649
+ timestamp: ts,
650
+ });
452
651
  }
453
652
  }
454
- catch {
455
- // Skip malformed legacy JSON files
653
+ }
654
+ const baseParams = {
655
+ engine: "opencode",
656
+ rawSessionId,
657
+ explicitTitle,
658
+ workspacePath,
659
+ sourcePath: sFile,
660
+ messages,
661
+ fallbackCreatedAt: createdAt,
662
+ fallbackUpdatedAt: updatedAt,
663
+ gitBranch,
664
+ model,
665
+ };
666
+ if (includeDetails) {
667
+ const detail = finalizeDiscoveredSession(baseParams);
668
+ return { summary: detail, detail };
669
+ }
670
+ return { summary: finalizeSessionSummary(baseParams), detail: null };
671
+ }
672
+ export async function readOpenCodeSessionDetail(sourcePath, rawSessionId) {
673
+ if (sourcePath.endsWith(".json")) {
674
+ let sessionDir = path.dirname(sourcePath);
675
+ if (path.basename(path.dirname(sessionDir)) === "session") {
676
+ sessionDir = path.dirname(sessionDir);
456
677
  }
678
+ const { detail } = await parseLegacyOpenCodeJsonFile(sourcePath, sessionDir, true).catch(() => ({ detail: null }));
679
+ return detail;
457
680
  }
458
- return discovered;
681
+ if (!(await isRegularFile(sourcePath))) {
682
+ return null;
683
+ }
684
+ const { updatedAt } = await safeStatDates(sourcePath);
685
+ return withReadOnlySqlite(sourcePath, (db) => parseSingleSessionFromOpenCodeDb(db, sourcePath, rawSessionId, updatedAt)).catch(() => null);
459
686
  }
460
- export async function scanOpenCodeSessions(customRoot) {
687
+ export async function prepareOpenCodeScan(customRoot, fileCache, sqliteCache) {
461
688
  const { primaryRoot, dbCandidates, legacySessionDirs } = resolveOpenCodePaths(customRoot);
689
+ const activeDbs = [];
462
690
  let detectedRoot = primaryRoot;
463
691
  let storageDetected = false;
464
- const sessionMap = new Map();
465
692
  for (const candidateDb of dbCandidates) {
466
693
  if (await isRegularFile(candidateDb)) {
467
694
  if (!storageDetected) {
468
695
  detectedRoot = candidateDb;
469
696
  storageDetected = true;
470
697
  }
471
- try {
472
- const { updatedAt } = await safeStatDates(candidateDb);
473
- const dbSessions = await withReadOnlySqlite(candidateDb, (db) => extractSessionsFromOpenCodeDb(db, candidateDb, updatedAt));
474
- for (const s of dbSessions) {
475
- if (!sessionMap.has(s.rawSessionId)) {
476
- sessionMap.set(s.rawSessionId, s);
477
- }
478
- }
479
- }
480
- catch {
481
- // Ignore corrupted or unreadable SQLite file
482
- }
698
+ activeDbs.push(candidateDb);
483
699
  if (!customRoot) {
484
- // Stop probing lower-priority default OS locations once primary active DB is found
485
700
  break;
486
701
  }
487
702
  }
488
703
  }
704
+ const legacyTasks = [];
489
705
  for (const legacyDir of legacySessionDirs) {
490
706
  if (await isDirectory(legacyDir)) {
491
707
  if (!storageDetected) {
492
708
  detectedRoot = legacyDir;
493
709
  storageDetected = true;
494
710
  }
495
- const legacySessions = await scanLegacyOpenCodeJsonDir(legacyDir);
496
- for (const s of legacySessions) {
497
- if (!sessionMap.has(s.rawSessionId)) {
498
- sessionMap.set(s.rawSessionId, s);
499
- }
711
+ const files = await walkFiles(legacyDir, (_full, name) => name.endsWith(".json"), 4);
712
+ for (const fp of files) {
713
+ legacyTasks.push({ sessionDir: legacyDir, filePath: fp });
500
714
  }
501
715
  }
502
716
  }
717
+ const totalItems = activeDbs.length + legacyTasks.length;
718
+ if (!storageDetected) {
719
+ return {
720
+ engine: "opencode",
721
+ storageRoot: detectedRoot,
722
+ storageDetected: false,
723
+ totalItems: 0,
724
+ runScan: async () => ({ summaries: [], cacheHits: 0 }),
725
+ };
726
+ }
503
727
  return {
504
728
  engine: "opencode",
505
729
  storageRoot: detectedRoot,
506
- storageDetected,
507
- sessions: Array.from(sessionMap.values()),
730
+ storageDetected: true,
731
+ totalItems,
732
+ runScan: async (onItemDone) => {
733
+ const sessionMap = new Map();
734
+ let cacheHits = 0;
735
+ for (const dbPath of activeDbs) {
736
+ try {
737
+ const sig = await computeSqliteSignature(dbPath);
738
+ const cached = sig ? sqliteCache.get(dbPath) : undefined;
739
+ let dbSummaries;
740
+ if (cached && cached.signature === sig) {
741
+ dbSummaries = cached.summaries;
742
+ cacheHits += 1;
743
+ }
744
+ else {
745
+ const { updatedAt } = await safeStatDates(dbPath);
746
+ dbSummaries = await withReadOnlySqlite(dbPath, (db) => extractSessionSummariesFromOpenCodeDb(db, dbPath, updatedAt));
747
+ if (sig) {
748
+ sqliteCache.set(dbPath, { signature: sig, summaries: dbSummaries });
749
+ }
750
+ }
751
+ let newlyAdded = 0;
752
+ for (const s of dbSummaries) {
753
+ if (!sessionMap.has(s.rawSessionId)) {
754
+ sessionMap.set(s.rawSessionId, s);
755
+ newlyAdded += 1;
756
+ }
757
+ }
758
+ onItemDone(newlyAdded);
759
+ }
760
+ catch {
761
+ onItemDone(0);
762
+ }
763
+ }
764
+ await runWithConcurrency(legacyTasks, 16, async ({ sessionDir, filePath }) => {
765
+ try {
766
+ const stat = await fsp.stat(filePath);
767
+ const cached = fileCache.get(filePath);
768
+ let summary;
769
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
770
+ summary = cached.summary;
771
+ cacheHits += 1;
772
+ }
773
+ else {
774
+ const res = await parseLegacyOpenCodeJsonFile(filePath, sessionDir, false);
775
+ summary = res.summary;
776
+ fileCache.set(filePath, {
777
+ mtimeMs: stat.mtimeMs,
778
+ size: stat.size,
779
+ summary,
780
+ });
781
+ }
782
+ if (summary && !sessionMap.has(summary.rawSessionId)) {
783
+ sessionMap.set(summary.rawSessionId, summary);
784
+ onItemDone(1);
785
+ }
786
+ else {
787
+ onItemDone(0);
788
+ }
789
+ }
790
+ catch {
791
+ onItemDone(0);
792
+ }
793
+ });
794
+ return { summaries: Array.from(sessionMap.values()), cacheHits };
795
+ },
796
+ };
797
+ }
798
+ export async function scanOpenCodeSessions(customRoot) {
799
+ const prepared = await prepareOpenCodeScan(customRoot, new Map(), new Map());
800
+ if (!prepared.storageDetected) {
801
+ return {
802
+ engine: "opencode",
803
+ storageRoot: prepared.storageRoot,
804
+ storageDetected: false,
805
+ sessions: [],
806
+ };
807
+ }
808
+ const { summaries } = await prepared.runScan(() => undefined);
809
+ const details = [];
810
+ for (const s of summaries) {
811
+ const detail = await readOpenCodeSessionDetail(s.sourcePath, s.rawSessionId);
812
+ if (detail) {
813
+ details.push(detail);
814
+ }
815
+ }
816
+ return {
817
+ engine: "opencode",
818
+ storageRoot: prepared.storageRoot,
819
+ storageDetected: true,
820
+ sessions: details,
508
821
  };
509
822
  }
510
823
  //# sourceMappingURL=opencode.js.map